@agent-native/core 0.84.1 → 0.84.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/core/CHANGELOG.md +15 -0
  3. package/corpus/core/docs/design/durable-agent-runs.md +34 -35
  4. package/corpus/core/package.json +1 -1
  5. package/corpus/core/src/agent/engine/builder-engine.ts +81 -9
  6. package/corpus/core/src/agent/production-agent.ts +9 -2
  7. package/corpus/core/src/agent/run-loop-with-resume.ts +38 -8
  8. package/corpus/core/src/agent/run-manager.ts +8 -7
  9. package/corpus/core/src/agent/thread-data-builder.ts +6 -0
  10. package/corpus/core/src/cli/design-connect.ts +175 -0
  11. package/corpus/core/src/cli/skills.ts +5 -7
  12. package/corpus/core/src/client/AgentPanel.tsx +8 -0
  13. package/corpus/core/src/client/MultiTabAssistantChat.tsx +4 -1
  14. package/corpus/core/src/client/agent-chat-adapter.ts +253 -24
  15. package/corpus/core/src/client/sharing/ShareButton.tsx +70 -21
  16. package/corpus/core/src/client/sse-event-processor.ts +46 -4
  17. package/corpus/core/src/templates/workspace-core/.agents/skills/reliable-mutations/SKILL.md +15 -17
  18. package/corpus/templates/analytics/AGENTS.md +1 -1
  19. package/corpus/templates/design/actions/apply-motion-edit.ts +50 -18
  20. package/corpus/templates/design/actions/get-motion-timeline.ts +4 -14
  21. package/corpus/templates/design/app/components/design/DesignCanvas.tsx +156 -12
  22. package/corpus/templates/design/app/components/design/MotionDock.tsx +2 -3
  23. package/corpus/templates/design/app/components/design/MultiScreenCanvas.tsx +217 -75
  24. package/corpus/templates/design/app/components/design/QuestionFlow.tsx +39 -39
  25. package/corpus/templates/design/app/components/design/bridge/editor-chrome.bridge.ts +558 -37
  26. package/corpus/templates/design/app/components/design/bridge/hit-test.bridge.ts +75 -3
  27. package/corpus/templates/design/app/components/design/types.ts +13 -0
  28. package/corpus/templates/design/app/components/layout/Layout.tsx +1 -0
  29. package/corpus/templates/design/app/i18n/zh-TW.ts +17 -0
  30. package/corpus/templates/design/app/i18n-data.ts +245 -0
  31. package/corpus/templates/design/app/pages/DesignEditor.tsx +890 -252
  32. package/corpus/templates/design/changelog/2026-06-30-agent-chat-now-reports-saved-design-generations-clearly-when.md +6 -0
  33. package/corpus/templates/design/changelog/2026-06-30-apply-styles-now-appears-only-for-localhost-visual-edit-scre.md +6 -0
  34. package/corpus/templates/design/changelog/2026-06-30-copying-or-dragging-screen-elements-onto-the-infinite-canvas.md +6 -0
  35. package/corpus/templates/design/changelog/2026-06-30-design-questions-now-use-tighter-editor-typography-and-contr.md +6 -0
  36. package/corpus/templates/design/changelog/2026-06-30-element-drags-can-be-cancelled-with-escape-before-they-commi.md +6 -0
  37. package/corpus/templates/design/changelog/2026-06-30-pending-visual-style-edits-now-warn-before-you-leave-the-edi.md +6 -0
  38. package/corpus/templates/design/changelog/2026-06-30-share-options-now-make-export-and-agent-handoff-easier-to-no.md +6 -0
  39. package/corpus/templates/design/changelog/2026-06-30-visual-style-drags-stay-live-while-pending-edits-can-be-appl.md +6 -0
  40. package/corpus/templates/design/changelog/2026-07-01-design-chat-no-longer-shows-a-redundant-context-tab-above-the-composer.md +6 -0
  41. package/corpus/templates/design/changelog/2026-07-01-motion-track-creation-no-longer-fails-in-local-editors.md +6 -0
  42. package/corpus/templates/design/changelog/2026-07-01-share-general-access-menu-stays-open-when-choosing-organization.md +6 -0
  43. package/corpus/templates/design/server/plugins/db.ts +10 -0
  44. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  45. package/dist/agent/engine/builder-engine.js +61 -10
  46. package/dist/agent/engine/builder-engine.js.map +1 -1
  47. package/dist/agent/production-agent.d.ts.map +1 -1
  48. package/dist/agent/production-agent.js +9 -2
  49. package/dist/agent/production-agent.js.map +1 -1
  50. package/dist/agent/run-loop-with-resume.d.ts +2 -2
  51. package/dist/agent/run-loop-with-resume.d.ts.map +1 -1
  52. package/dist/agent/run-loop-with-resume.js +31 -8
  53. package/dist/agent/run-loop-with-resume.js.map +1 -1
  54. package/dist/agent/run-manager.d.ts +8 -7
  55. package/dist/agent/run-manager.d.ts.map +1 -1
  56. package/dist/agent/run-manager.js +8 -7
  57. package/dist/agent/run-manager.js.map +1 -1
  58. package/dist/agent/thread-data-builder.d.ts +2 -0
  59. package/dist/agent/thread-data-builder.d.ts.map +1 -1
  60. package/dist/agent/thread-data-builder.js +5 -0
  61. package/dist/agent/thread-data-builder.js.map +1 -1
  62. package/dist/cli/design-connect.d.ts +2 -0
  63. package/dist/cli/design-connect.d.ts.map +1 -1
  64. package/dist/cli/design-connect.js +140 -0
  65. package/dist/cli/design-connect.js.map +1 -1
  66. package/dist/cli/skills.d.ts.map +1 -1
  67. package/dist/cli/skills.js +5 -7
  68. package/dist/cli/skills.js.map +1 -1
  69. package/dist/client/AgentPanel.d.ts +5 -1
  70. package/dist/client/AgentPanel.d.ts.map +1 -1
  71. package/dist/client/AgentPanel.js +4 -4
  72. package/dist/client/AgentPanel.js.map +1 -1
  73. package/dist/client/MultiTabAssistantChat.d.ts +3 -1
  74. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  75. package/dist/client/MultiTabAssistantChat.js +2 -2
  76. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  77. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  78. package/dist/client/agent-chat-adapter.js +216 -22
  79. package/dist/client/agent-chat-adapter.js.map +1 -1
  80. package/dist/client/sharing/ShareButton.d.ts +6 -0
  81. package/dist/client/sharing/ShareButton.d.ts.map +1 -1
  82. package/dist/client/sharing/ShareButton.js +25 -11
  83. package/dist/client/sharing/ShareButton.js.map +1 -1
  84. package/dist/client/sse-event-processor.d.ts +18 -1
  85. package/dist/client/sse-event-processor.d.ts.map +1 -1
  86. package/dist/client/sse-event-processor.js +34 -5
  87. package/dist/client/sse-event-processor.js.map +1 -1
  88. package/dist/collab/awareness.d.ts +2 -2
  89. package/dist/collab/awareness.d.ts.map +1 -1
  90. package/dist/collab/routes.d.ts +2 -2
  91. package/dist/file-upload/actions/upload-image.d.ts +2 -2
  92. package/dist/notifications/routes.d.ts +3 -3
  93. package/dist/observability/routes.d.ts +7 -7
  94. package/dist/resources/handlers.d.ts +2 -2
  95. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  96. package/dist/server/transcribe-voice.d.ts +1 -1
  97. package/dist/templates/workspace-core/.agents/skills/reliable-mutations/SKILL.md +15 -17
  98. package/docs/design/durable-agent-runs.md +34 -35
  99. package/package.json +1 -1
  100. package/src/templates/workspace-core/.agents/skills/reliable-mutations/SKILL.md +15 -17
@@ -18,6 +18,8 @@ export type ContentPart =
18
18
  argsText: string;
19
19
  args: Record<string, string>;
20
20
  result?: string;
21
+ isError?: boolean;
22
+ completedSideEffect?: boolean;
21
23
  mcpApp?: AgentMcpAppPayload;
22
24
  chatUI?: ActionChatUIConfig;
23
25
  activity?: boolean;
@@ -45,6 +47,8 @@ export interface SSEEvent {
45
47
  label?: string;
46
48
  input?: Record<string, string>;
47
49
  result?: string;
50
+ isError?: boolean;
51
+ completedSideEffect?: boolean;
48
52
  mcpApp?: AgentMcpAppPayload;
49
53
  chatUI?: ActionChatUIConfig;
50
54
  /** Stable key the client echoes back in `approvedToolCalls` to approve a
@@ -80,21 +84,34 @@ export type AgentAutoContinueReason =
80
84
 
81
85
  export type AgentActivityTrailEntry = { label: string; tool?: string };
82
86
 
87
+ export interface AgentAutoContinueErrorInfo {
88
+ message: string;
89
+ details?: string;
90
+ errorCode?: string;
91
+ recoverable?: boolean;
92
+ upgradeUrl?: string;
93
+ }
94
+
83
95
  const INTERRUPTED_TOOL_RESULT =
84
96
  "Interrupted before this tool returned a result.";
97
+ const INTERRUPTED_ACTIVITY_RESULT = "Stopped before this action started.";
85
98
 
86
99
  export function settleInterruptedToolCalls(
87
100
  content: ContentPart[],
88
101
  result = INTERRUPTED_TOOL_RESULT,
102
+ options?: { includeActivity?: boolean; activityResult?: string },
89
103
  ): boolean {
90
104
  let changed = false;
91
105
  for (const part of content) {
92
106
  if (
93
107
  part.type === "tool-call" &&
94
108
  part.result === undefined &&
95
- part.activity !== true
109
+ (part.activity !== true || options?.includeActivity === true)
96
110
  ) {
97
- part.result = result;
111
+ part.result =
112
+ part.activity === true
113
+ ? (options?.activityResult ?? INTERRUPTED_ACTIVITY_RESULT)
114
+ : result;
98
115
  changed = true;
99
116
  }
100
117
  }
@@ -105,17 +122,20 @@ export class AgentAutoContinueSignal extends Error {
105
122
  readonly reason: AgentAutoContinueReason;
106
123
  readonly maxIterations?: number;
107
124
  readonly activityTrail: AgentActivityTrailEntry[];
125
+ readonly errorInfo?: AgentAutoContinueErrorInfo;
108
126
 
109
127
  constructor(options: {
110
128
  reason: AgentAutoContinueReason;
111
129
  maxIterations?: number;
112
130
  activityTrail?: AgentActivityTrailEntry[];
131
+ errorInfo?: AgentAutoContinueErrorInfo;
113
132
  }) {
114
133
  super(`Agent run needs automatic continuation: ${options.reason}`);
115
134
  this.name = "AgentAutoContinueSignal";
116
135
  this.reason = options.reason;
117
136
  this.maxIterations = options.maxIterations;
118
137
  this.activityTrail = options.activityTrail ?? [];
138
+ this.errorInfo = options.errorInfo;
119
139
  }
120
140
  }
121
141
 
@@ -342,6 +362,7 @@ export function processEvent(
342
362
  autoContinue?: {
343
363
  reason: AgentAutoContinueReason;
344
364
  maxIterations?: number;
365
+ errorInfo?: AgentAutoContinueErrorInfo;
345
366
  };
346
367
  } {
347
368
  if (ev.type === "clear") {
@@ -508,6 +529,10 @@ export function processEvent(
508
529
  const part = content[doneIdx];
509
530
  if (part.type === "tool-call") {
510
531
  part.result = ev.result ?? "";
532
+ if (ev.isError !== undefined) part.isError = ev.isError;
533
+ if (ev.completedSideEffect !== undefined) {
534
+ part.completedSideEffect = ev.completedSideEffect;
535
+ }
511
536
  if (ev.mcpApp) part.mcpApp = ev.mcpApp;
512
537
  if (ev.chatUI) part.chatUI = ev.chatUI;
513
538
  }
@@ -598,7 +623,7 @@ export function processEvent(
598
623
  }),
599
624
  );
600
625
  }
601
- settleInterruptedToolCalls(content);
626
+ settleInterruptedToolCalls(content, undefined, { includeActivity: true });
602
627
  content.push({
603
628
  type: "text",
604
629
  text: formatChatErrorText(errMsg, undefined, errorCode),
@@ -665,6 +690,7 @@ export function processEvent(
665
690
  (ev.errorCode === "run_timeout" && ev.recoverable) ||
666
691
  isAutoRecoverableError(ev, errMsg)
667
692
  ) {
693
+ const normalized = normalizeChatError(errMsg, ev.errorCode);
668
694
  return {
669
695
  action: "auto_continue",
670
696
  autoContinue: {
@@ -676,6 +702,15 @@ export function processEvent(
676
702
  errMsg.toLowerCase().includes("timeout")
677
703
  ? "run_timeout"
678
704
  : "stream_ended",
705
+ errorInfo: {
706
+ message: normalized.message,
707
+ ...(ev.details || normalized.details
708
+ ? { details: ev.details ?? normalized.details }
709
+ : {}),
710
+ ...(ev.errorCode ? { errorCode: ev.errorCode } : {}),
711
+ recoverable: ev.recoverable ?? true,
712
+ ...(ev.upgradeUrl ? { upgradeUrl: ev.upgradeUrl } : {}),
713
+ },
679
714
  },
680
715
  };
681
716
  }
@@ -700,7 +735,7 @@ export function processEvent(
700
735
  }),
701
736
  );
702
737
  }
703
- settleInterruptedToolCalls(content);
738
+ settleInterruptedToolCalls(content, undefined, { includeActivity: true });
704
739
  content.push({
705
740
  type: "text",
706
741
  text: formatChatErrorText(errMsg, ev.upgradeUrl, ev.errorCode),
@@ -824,6 +859,13 @@ export async function* readSSEStream(
824
859
  label: runningToolLabel(tool),
825
860
  tool,
826
861
  });
862
+ } else if (ev.type === "tool_done") {
863
+ const tool = ev.tool ?? "unknown";
864
+ for (let i = activityTrail.length - 1; i >= 0; i--) {
865
+ if (activityTrail[i]?.tool === tool) {
866
+ activityTrail.splice(i, 1);
867
+ }
868
+ }
827
869
  }
828
870
 
829
871
  const { action, result, autoContinue } = processEvent(
@@ -2,9 +2,9 @@
2
2
  name: reliable-mutations
3
3
  description: >-
4
4
  How the agent must perform writes so they actually persist under the hosted
5
- ~40s run budget. Use whenever you create, update, delete, or batch-write app
6
- data — especially "do this for many items" loops, or any task where the user
7
- expects N things to end up saved.
5
+ foreground run budget and long-running background handoffs. Use whenever you
6
+ create, update, delete, or batch-write app data — especially "do this for many
7
+ items" loops, or any task where the user expects N things to end up saved.
8
8
  ---
9
9
 
10
10
  # Reliable Mutations
@@ -18,15 +18,12 @@ tool ✓ alone.
18
18
 
19
19
  ## Why
20
20
 
21
- Hosted agent runs have a ~40s soft budget (it exists to hand off cleanly under
22
- the upstream gateway/function walls it is correct and is not raisable; see the
23
- durable-agent-runs design doc). When you loop many sequential writes inside one
24
- turn, the budget can cut you off mid-loop. The run resumes in a new chunk, but
25
- the resume often re-does earlier steps instead of advancing, so the loop churns
26
- and the *saved* result ends up partial — or empty — even though each individual
27
- tool call appeared to succeed. The user gets told "done" while the data says
28
- otherwise. One atomic call commits or fails as a unit; verification turns a
29
- hopeful ✓ into a fact.
21
+ Hosted foreground agent runs have a short soft budget so they can hand off
22
+ cleanly under synchronous serverless walls. Durable background runs get a much
23
+ longer budget, but they still should not rely on loops of many small writes:
24
+ continuations can retry the same intent and leave partial state if each item is
25
+ committed separately. One atomic call commits or fails as a unit; verification
26
+ turns a hopeful into a fact.
30
27
 
31
28
  ## How
32
29
 
@@ -34,11 +31,12 @@ hopeful ✓ into a fact.
34
31
  many, set all, bulk update), pass the full batch in one call so it commits
35
32
  atomically. Check the action surface for a batch/plural form before reaching
36
33
  for a loop.
37
- 2. **Do not loop many small writes under the run budget.** A sequence of N
38
- per-item writes in one turn will race the ~40s cutoff and can leave partial
39
- or no state. If no batch action exists, that is a gap in the action layer —
40
- add or extend an action that accepts the batch (see the `actions` skill)
41
- rather than papering over it with a loop.
34
+ 2. **Do not loop many small writes under any run budget.** A sequence of N
35
+ per-item writes can still leave partial or no state when a foreground run
36
+ hands off, a background run continues, or an upstream provider fails. If no
37
+ batch action exists, that is a gap in the action layer add or extend an
38
+ action that accepts the batch (see the `actions` skill) rather than papering
39
+ over it with a loop.
42
40
  3. **Verify the end state after writing.** Re-read the data (a list/read action,
43
41
  a count query) and confirm the result matches intent — the right number of
44
42
  rows, the expected ids/fields. Do this before you tell the user it worked.
@@ -137,7 +137,7 @@ details live in `.agents/skills/`.
137
137
  name the metrics and the server generates the validated SQL/config for every
138
138
  panel in ONE fast call. Do NOT hand-author big `update-dashboard` configs
139
139
  panel-by-panel or loop `update-dashboard` — streaming a giant multi-panel
140
- argument inside the ~40s budget fails and thrashes. Unknown metric keys are
140
+ argument across timeout boundaries fails and thrashes. Unknown metric keys are
141
141
  skipped and reported; per-panel SQL validates independently; existing
142
142
  dashboards append by default (`overwrite: true` replaces). Report the returned
143
143
  `panelCount` as proof-of-done.
@@ -20,7 +20,7 @@ import {
20
20
  getRequestOrgId,
21
21
  getRequestUserEmail,
22
22
  } from "@agent-native/core/server/request-context";
23
- import { accessFilter, assertAccess } from "@agent-native/core/sharing";
23
+ import { assertAccess } from "@agent-native/core/sharing";
24
24
  import { and, desc, eq } from "drizzle-orm";
25
25
  import { nanoid } from "nanoid";
26
26
  import { z } from "zod";
@@ -70,6 +70,33 @@ const trackSchema = z.object({
70
70
 
71
71
  // ─── Helpers ──────────────────────────────────────────────────────────────────
72
72
 
73
+ function nonEmptyString(value: unknown): string | null {
74
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
75
+ }
76
+
77
+ export function resolveMotionTimelineInsertOwnership(args: {
78
+ requestUserEmail?: string | null;
79
+ requestOrgId?: string | null;
80
+ designOwnerEmail?: unknown;
81
+ designOrgId?: unknown;
82
+ }): { ownerEmail: string; orgId: string | null } {
83
+ const ownerEmail =
84
+ nonEmptyString(args.requestUserEmail) ??
85
+ nonEmptyString(args.designOwnerEmail);
86
+
87
+ if (!ownerEmail) throw new Error("no authenticated user");
88
+
89
+ return {
90
+ ownerEmail,
91
+ orgId:
92
+ nonEmptyString(args.requestOrgId) ?? nonEmptyString(args.designOrgId),
93
+ };
94
+ }
95
+
96
+ export function canPatchManagedMotionCss(content: string): boolean {
97
+ return /<\s*(?:!doctype|[a-z][a-z0-9:-]*(?:\s|>|\/>))/i.test(content);
98
+ }
99
+
73
100
  async function persistFileContent(
74
101
  fileId: string,
75
102
  designId: string,
@@ -179,16 +206,13 @@ export default defineAction({
179
206
  includeContent,
180
207
  currentContent: currentContentInput,
181
208
  }) => {
182
- await assertAccess("design", designId, "editor");
209
+ const access = await assertAccess("design", designId, "editor");
183
210
 
184
211
  const db = getDb();
185
212
  const now = new Date().toISOString();
186
213
 
187
214
  // ── 1. Resolve the target design file ──────────────────────────────────
188
- const conditions = [
189
- accessFilter(schema.designs, schema.designShares),
190
- eq(schema.designFiles.designId, designId),
191
- ];
215
+ const conditions = [eq(schema.designFiles.designId, designId)];
192
216
  if (fileIdInput) {
193
217
  conditions.push(eq(schema.designFiles.id, fileIdInput));
194
218
  } else {
@@ -256,7 +280,10 @@ export default defineAction({
256
280
  });
257
281
 
258
282
  // ── 3. Inject the managed CSS block into the HTML ───────────────────────
259
- const patchedContent = injectManagedMotionCss(currentContent, css);
283
+ const contentPatched = canPatchManagedMotionCss(currentContent);
284
+ const patchedContent = contentPatched
285
+ ? injectManagedMotionCss(currentContent, css)
286
+ : currentContent;
260
287
  const bytesBefore = currentContent.length;
261
288
  const bytesAfter = patchedContent.length;
262
289
 
@@ -303,11 +330,18 @@ export default defineAction({
303
330
  if (existingForSource) {
304
331
  existingTimelineId = existingForSource.id;
305
332
  } else {
306
- // Insert new row — derive ownership from the request context (same
307
- // pattern as create-design-state and other create actions).
308
- insertOwnerEmail = getRequestUserEmail() ?? null;
309
- if (!insertOwnerEmail) throw new Error("no authenticated user");
310
- insertOrgId = getRequestOrgId() ?? null;
333
+ // Insert new row — derive ownership from the request context, falling
334
+ // back to the already-authorized design owner for local/public editor
335
+ // sessions that do not carry an authenticated request user.
336
+ const insertOwnership = resolveMotionTimelineInsertOwnership({
337
+ requestUserEmail: getRequestUserEmail(),
338
+ requestOrgId: getRequestOrgId(),
339
+ designOwnerEmail: (access.resource as { ownerEmail?: unknown })
340
+ .ownerEmail,
341
+ designOrgId: (access.resource as { orgId?: unknown }).orgId,
342
+ });
343
+ insertOwnerEmail = insertOwnership.ownerEmail;
344
+ insertOrgId = insertOwnership.orgId;
311
345
  }
312
346
  }
313
347
 
@@ -352,12 +386,9 @@ export default defineAction({
352
386
  // Written after the row so a SQL failure here leaves the timeline row
353
387
  // accurate (correct tracks + hash) and the stale HTML can be recompiled on
354
388
  // the next apply-motion-edit call via compiledHash drift detection.
355
- const updatedAt = await persistFileContent(
356
- fileId,
357
- designId,
358
- patchedContent,
359
- now,
360
- );
389
+ const updatedAt = contentPatched
390
+ ? await persistFileContent(fileId, designId, patchedContent, now)
391
+ : now;
361
392
 
362
393
  return {
363
394
  timelineId: resolvedTimelineId,
@@ -371,6 +402,7 @@ export default defineAction({
371
402
  bytesAfter,
372
403
  bytesDelta: bytesAfter - bytesBefore,
373
404
  persisted: true,
405
+ contentPatched,
374
406
  patchedContent: includeContent ? patchedContent : undefined,
375
407
  };
376
408
  },
@@ -1,6 +1,6 @@
1
1
  import { defineAction } from "@agent-native/core";
2
2
  import { getText, hasCollabState } from "@agent-native/core/collab";
3
- import { accessFilter } from "@agent-native/core/sharing";
3
+ import { assertAccess } from "@agent-native/core/sharing";
4
4
  import { and, desc, eq } from "drizzle-orm";
5
5
  import { z } from "zod";
6
6
 
@@ -67,13 +67,8 @@ async function readManagedCssForSource(args: {
67
67
  content: schema.designFiles.content,
68
68
  })
69
69
  .from(schema.designFiles)
70
- .innerJoin(
71
- schema.designs,
72
- eq(schema.designFiles.designId, schema.designs.id),
73
- )
74
70
  .where(
75
71
  and(
76
- accessFilter(schema.designs, schema.designShares),
77
72
  eq(schema.designFiles.designId, args.designId),
78
73
  eq(schema.designFiles.id, args.sourceRef),
79
74
  ),
@@ -124,12 +119,11 @@ export default defineAction({
124
119
  ),
125
120
  }),
126
121
  run: async ({ designId, timelineId, sourceRef }) => {
122
+ await assertAccess("design", designId, "viewer");
123
+
127
124
  const db = getDb();
128
125
 
129
- const conditions = [
130
- accessFilter(schema.designs, schema.designShares),
131
- eq(schema.motionTimeline.designId, designId),
132
- ];
126
+ const conditions = [eq(schema.motionTimeline.designId, designId)];
133
127
 
134
128
  if (timelineId) {
135
129
  conditions.push(eq(schema.motionTimeline.id, timelineId));
@@ -151,10 +145,6 @@ export default defineAction({
151
145
  updatedAt: schema.motionTimeline.updatedAt,
152
146
  })
153
147
  .from(schema.motionTimeline)
154
- .innerJoin(
155
- schema.designs,
156
- eq(schema.motionTimeline.designId, schema.designs.id),
157
- )
158
148
  .where(and(...conditions))
159
149
  .orderBy(desc(schema.motionTimeline.updatedAt))
160
150
  .limit(timelineId ? 1 : 100);
@@ -333,6 +333,13 @@ interface DesignCanvasProps {
333
333
  contentOffsetY?: number;
334
334
  };
335
335
  boardSurface?: boolean;
336
+ /**
337
+ * Optional live document replacement channel. When paired with
338
+ * `runtimeReplacementKey`, this lets callers update iframe DOM through the
339
+ * editor bridge without changing `srcDoc` and reloading the iframe.
340
+ */
341
+ runtimeReplacementContent?: string;
342
+ runtimeReplacementKey?: string;
336
343
  embeddedFrameBackground?: string;
337
344
  transparentBackground?: boolean;
338
345
  editorChromeScaleX?: number;
@@ -367,6 +374,7 @@ interface DesignCanvasProps {
367
374
  onElementDblClickText?: (info: ElementInfo) => void;
368
375
  onIframeHotkey?: (event: IframeHotkeyPayload) => void;
369
376
  onIframeContextMenu?: (event: IframeContextMenuPayload) => void;
377
+ onEditorDragStateChange?: (active: boolean) => void;
370
378
  onVisualStructureChange?: (
371
379
  selector: string,
372
380
  anchorSelector: string,
@@ -376,6 +384,9 @@ interface DesignCanvasProps {
376
384
  sourceId?: string;
377
385
  anchorSourceId?: string;
378
386
  requestId?: string;
387
+ dropMode?: "flow-insert" | "absolute-container";
388
+ sourceRect?: { x: number; y: number; width: number; height: number };
389
+ anchorRect?: { x: number; y: number; width: number; height: number };
379
390
  },
380
391
  ) => boolean | void;
381
392
  onVisualDuplicateChange?: (
@@ -571,6 +582,26 @@ function injectEmbeddedFrameStyle(content: string, style: string): string {
571
582
  return `${style}${content}`;
572
583
  }
573
584
 
585
+ export function getEmbeddedFrameDocumentContent(args: {
586
+ content: string;
587
+ embeddedFrameBackground?: string;
588
+ transparentBackground?: boolean;
589
+ contentOffsetX?: number;
590
+ contentOffsetY?: number;
591
+ }): string {
592
+ const frameStyle = [
593
+ getEmbeddedFrameBackgroundStyle({
594
+ embeddedFrameBackground: args.embeddedFrameBackground,
595
+ transparentBackground: args.transparentBackground,
596
+ }),
597
+ embeddedContentOffsetStyle(
598
+ args.contentOffsetX ?? 0,
599
+ args.contentOffsetY ?? 0,
600
+ ),
601
+ ].join("");
602
+ return injectEmbeddedFrameStyle(args.content, frameStyle);
603
+ }
604
+
574
605
  export interface IframeHotkeyPayload {
575
606
  key: string;
576
607
  code: string;
@@ -602,6 +633,8 @@ export function DesignCanvas({
602
633
  deviceFrame,
603
634
  embeddedFrame,
604
635
  boardSurface = false,
636
+ runtimeReplacementContent,
637
+ runtimeReplacementKey,
605
638
  embeddedFrameBackground,
606
639
  transparentBackground = false,
607
640
  editorChromeScaleX = 1,
@@ -621,6 +654,7 @@ export function DesignCanvas({
621
654
  onElementDblClickText,
622
655
  onIframeHotkey,
623
656
  onIframeContextMenu,
657
+ onEditorDragStateChange,
624
658
  onVisualStructureChange,
625
659
  onVisualDuplicateChange,
626
660
  tweakValues,
@@ -652,6 +686,9 @@ export function DesignCanvas({
652
686
  const scrollContainerRef = useRef<HTMLDivElement>(null);
653
687
  const zoomRef = useRef(zoom);
654
688
  const previousContentKeyRef = useRef(contentKey);
689
+ const runtimeReplacementContentRef = useRef(runtimeReplacementContent);
690
+ const runtimeReplacementKeyRef = useRef(runtimeReplacementKey);
691
+ const lastRuntimeReplacementKeyRef = useRef(runtimeReplacementKey);
655
692
  const [renderedContent, setRenderedContent] = useState(content);
656
693
  const [annotationPins, setAnnotationPins] = useState<CanvasPin[]>([]);
657
694
  const [pinSubmitSignal, setPinSubmitSignal] = useState(0);
@@ -707,6 +744,8 @@ export function DesignCanvas({
707
744
  const waitingForEditableExternalSnapshot =
708
745
  requiresEditableExternalSnapshot && !activeExternalSnapshotHtml;
709
746
  zoomRef.current = zoom;
747
+ runtimeReplacementContentRef.current = runtimeReplacementContent;
748
+ runtimeReplacementKeyRef.current = runtimeReplacementKey;
710
749
 
711
750
  useEffect(() => {
712
751
  onExternalContentSnapshotRef.current = onExternalContentSnapshot;
@@ -819,6 +858,7 @@ export function DesignCanvas({
819
858
  useEffect(() => {
820
859
  if (previousContentKeyRef.current !== contentKey) {
821
860
  previousContentKeyRef.current = contentKey;
861
+ lastRuntimeReplacementKeyRef.current = runtimeReplacementKey;
822
862
  setRenderedContent(content);
823
863
  }
824
864
  // Same-screen visual edits are already applied optimistically inside the
@@ -826,7 +866,7 @@ export function DesignCanvas({
826
866
  // reloads the iframe, flashes unstyled content, and drops selection. Only a
827
867
  // content-key change (screen switch / explicit remount) should replace the
828
868
  // iframe document here; the bridge replays inspector state after that load.
829
- }, [content, contentKey]);
869
+ }, [content, contentKey, runtimeReplacementKey]);
830
870
 
831
871
  usePinchZoom({
832
872
  containerRef: scrollContainerRef,
@@ -879,6 +919,20 @@ export function DesignCanvas({
879
919
  NAV_BRIDGE_SCRIPT +
880
920
  embeddedWheelBridge +
881
921
  editorChromeBridge;
922
+ const frameContent = getEmbeddedFrameDocumentContent({
923
+ content: iframeRenderContent,
924
+ embeddedFrameBackground,
925
+ transparentBackground,
926
+ contentOffsetX: embeddedFrame?.contentOffsetX ?? 0,
927
+ contentOffsetY: embeddedFrame?.contentOffsetY ?? 0,
928
+ });
929
+ if (frameContent.includes("</body>")) {
930
+ return frameContent.replace("</body>", bridgeToInject + "</body>"); // i18n-ignore generated iframe HTML injection
931
+ }
932
+ if (frameContent.includes("</html>")) {
933
+ return frameContent.replace("</html>", bridgeToInject + "</html>"); // i18n-ignore generated iframe HTML injection
934
+ }
935
+ // No body/html tags — wrap it
882
936
  const frameStyle = [
883
937
  getEmbeddedFrameBackgroundStyle({
884
938
  embeddedFrameBackground,
@@ -889,17 +943,6 @@ export function DesignCanvas({
889
943
  embeddedFrame?.contentOffsetY ?? 0,
890
944
  ),
891
945
  ].join("");
892
- const frameContent = injectEmbeddedFrameStyle(
893
- iframeRenderContent,
894
- frameStyle,
895
- );
896
- if (frameContent.includes("</body>")) {
897
- return frameContent.replace("</body>", bridgeToInject + "</body>"); // i18n-ignore generated iframe HTML injection
898
- }
899
- if (frameContent.includes("</html>")) {
900
- return frameContent.replace("</html>", bridgeToInject + "</html>"); // i18n-ignore generated iframe HTML injection
901
- }
902
- // No body/html tags — wrap it
903
946
  return `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${frameStyle}</head><body>${iframeRenderContent}${bridgeToInject}</body></html>`;
904
947
  // editorChromeScaleX/Y are intentionally NOT deps: they only seed the initial
905
948
  // baked chrome scale. Live zoom updates flow through the set-editor-chrome-scale
@@ -968,6 +1011,10 @@ export function DesignCanvas({
968
1011
  if (e.data.type === "element-hover") {
969
1012
  onElementHover(e.data.payload);
970
1013
  }
1014
+ if (e.data.type === "agent-native:editor-drag-state") {
1015
+ onEditorDragStateChange?.(Boolean(e.data.active));
1016
+ return;
1017
+ }
971
1018
  if (e.data.type === "visual-style-change") {
972
1019
  const selector = String(e.data.selector || "");
973
1020
  const styles =
@@ -1001,6 +1048,39 @@ export function DesignCanvas({
1001
1048
  typeof e.data.anchorSourceId === "string"
1002
1049
  ? e.data.anchorSourceId
1003
1050
  : undefined;
1051
+ const dropMode =
1052
+ e.data.dropMode === "flow-insert" ||
1053
+ e.data.dropMode === "absolute-container"
1054
+ ? e.data.dropMode
1055
+ : undefined;
1056
+ const sourceRect =
1057
+ e.data.sourceRect &&
1058
+ typeof e.data.sourceRect === "object" &&
1059
+ Number.isFinite(e.data.sourceRect.x) &&
1060
+ Number.isFinite(e.data.sourceRect.y) &&
1061
+ Number.isFinite(e.data.sourceRect.width) &&
1062
+ Number.isFinite(e.data.sourceRect.height)
1063
+ ? {
1064
+ x: Number(e.data.sourceRect.x),
1065
+ y: Number(e.data.sourceRect.y),
1066
+ width: Number(e.data.sourceRect.width),
1067
+ height: Number(e.data.sourceRect.height),
1068
+ }
1069
+ : undefined;
1070
+ const anchorRect =
1071
+ e.data.anchorRect &&
1072
+ typeof e.data.anchorRect === "object" &&
1073
+ Number.isFinite(e.data.anchorRect.x) &&
1074
+ Number.isFinite(e.data.anchorRect.y) &&
1075
+ Number.isFinite(e.data.anchorRect.width) &&
1076
+ Number.isFinite(e.data.anchorRect.height)
1077
+ ? {
1078
+ x: Number(e.data.anchorRect.x),
1079
+ y: Number(e.data.anchorRect.y),
1080
+ width: Number(e.data.anchorRect.width),
1081
+ height: Number(e.data.anchorRect.height),
1082
+ }
1083
+ : undefined;
1004
1084
  if (
1005
1085
  (selector || sourceId) &&
1006
1086
  (anchorSelector || anchorSourceId) &&
@@ -1017,6 +1097,9 @@ export function DesignCanvas({
1017
1097
  requestId,
1018
1098
  sourceId,
1019
1099
  anchorSourceId,
1100
+ dropMode,
1101
+ sourceRect,
1102
+ anchorRect,
1020
1103
  },
1021
1104
  );
1022
1105
  if (requestId) {
@@ -1209,6 +1292,7 @@ export function DesignCanvas({
1209
1292
  onElementDblClickText,
1210
1293
  onIframeHotkey,
1211
1294
  onIframeContextMenu,
1295
+ onEditorDragStateChange,
1212
1296
  onVisualStructureChange,
1213
1297
  onVisualDuplicateChange,
1214
1298
  onZoomChange,
@@ -1519,6 +1603,66 @@ export function DesignCanvas({
1519
1603
  [],
1520
1604
  );
1521
1605
 
1606
+ const replaceRuntimeContentInPlace = useCallback(
1607
+ (nextContent: string) => {
1608
+ if (externalPreviewUrl) return false;
1609
+ return replacePreviewContent(
1610
+ getEmbeddedFrameDocumentContent({
1611
+ content: nextContent,
1612
+ embeddedFrameBackground,
1613
+ transparentBackground,
1614
+ contentOffsetX: embeddedFrame?.contentOffsetX ?? 0,
1615
+ contentOffsetY: embeddedFrame?.contentOffsetY ?? 0,
1616
+ }),
1617
+ null,
1618
+ [],
1619
+ { forceFullDocument: true },
1620
+ );
1621
+ },
1622
+ [
1623
+ embeddedFrame?.contentOffsetX,
1624
+ embeddedFrame?.contentOffsetY,
1625
+ embeddedFrameBackground,
1626
+ externalPreviewUrl,
1627
+ replacePreviewContent,
1628
+ transparentBackground,
1629
+ ],
1630
+ );
1631
+
1632
+ useEffect(() => {
1633
+ if (
1634
+ runtimeReplacementKey === undefined ||
1635
+ runtimeReplacementContent === undefined ||
1636
+ lastRuntimeReplacementKeyRef.current === runtimeReplacementKey
1637
+ ) {
1638
+ return;
1639
+ }
1640
+ if (replaceRuntimeContentInPlace(runtimeReplacementContent)) {
1641
+ lastRuntimeReplacementKeyRef.current = runtimeReplacementKey;
1642
+ }
1643
+ }, [
1644
+ replaceRuntimeContentInPlace,
1645
+ runtimeReplacementContent,
1646
+ runtimeReplacementKey,
1647
+ ]);
1648
+
1649
+ const runtimeReplacementEnabled = runtimeReplacementKey !== undefined;
1650
+ useEffect(() => {
1651
+ if (!runtimeReplacementEnabled) return;
1652
+ const iframe = iframeRef.current;
1653
+ if (!iframe) return;
1654
+ const replaceLatestRuntimeContent = () => {
1655
+ const nextContent = runtimeReplacementContentRef.current;
1656
+ if (nextContent === undefined) return;
1657
+ if (replaceRuntimeContentInPlace(nextContent)) {
1658
+ lastRuntimeReplacementKeyRef.current = runtimeReplacementKeyRef.current;
1659
+ }
1660
+ };
1661
+ iframe.addEventListener("load", replaceLatestRuntimeContent);
1662
+ return () =>
1663
+ iframe.removeEventListener("load", replaceLatestRuntimeContent);
1664
+ }, [replaceRuntimeContentInPlace, runtimeReplacementEnabled]);
1665
+
1522
1666
  const deleteRuntimeElement = useCallback(
1523
1667
  (selector?: string | null, candidates?: string[]) => {
1524
1668
  const iframe = iframeRef.current;
@@ -449,15 +449,14 @@ export function MotionDock({
449
449
 
450
450
  {/* Dock toolbar */}
451
451
  <div className="flex h-8 shrink-0 items-center gap-1 border-b border-border px-2">
452
- {/* Collapse toggle. The label and nearby space are part of the target. */}
452
+ {/* Collapse toggle. The rail owns the visible Motion label. */}
453
453
  <button
454
454
  type="button"
455
- className="-ml-1 flex h-7 shrink-0 cursor-pointer items-center gap-1.5 rounded-md px-1.5 !text-[11px] font-medium uppercase tracking-wide text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-1 focus-visible:ring-[var(--design-editor-accent-color)]"
455
+ className="-ml-1 flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-1 focus-visible:ring-[var(--design-editor-accent-color)]"
456
456
  onClick={() => setOpen(false)}
457
457
  aria-label="Collapse motion dock"
458
458
  >
459
459
  <IconChevronDown className="size-3.5" />
460
- <span>Motion</span>
461
460
  </button>
462
461
 
463
462
  <>