@1agh/maude 1.8.1 → 1.9.0

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 (73) hide show
  1. package/apps/studio/acp/bridge.ts +14 -2
  2. package/apps/studio/acp/probe.ts +51 -1
  3. package/apps/studio/api.ts +19 -4
  4. package/apps/studio/bin/_curl-local.mjs +7 -0
  5. package/apps/studio/bin/annotate.mjs +16 -7
  6. package/apps/studio/bin/read-annotations.mjs +62 -4
  7. package/apps/studio/client/app.jsx +428 -15977
  8. package/apps/studio/client/dialogs/asset-picker.jsx +331 -0
  9. package/apps/studio/client/dialogs/command-palette.jsx +112 -0
  10. package/apps/studio/client/dialogs/export-dialog.jsx +782 -0
  11. package/apps/studio/client/dialogs/help-modal.jsx +324 -0
  12. package/apps/studio/client/dialogs/shortcuts-overlay.jsx +144 -0
  13. package/apps/studio/client/hooks/use-canvas-bridge.jsx +2150 -0
  14. package/apps/studio/client/hooks/use-git-actions.jsx +236 -0
  15. package/apps/studio/client/hooks/use-keyboard-shortcuts.jsx +297 -0
  16. package/apps/studio/client/hooks/use-palette-and-panels.jsx +474 -0
  17. package/apps/studio/client/hooks/use-photo-and-timeline.jsx +901 -0
  18. package/apps/studio/client/hooks/use-project-data.jsx +90 -0
  19. package/apps/studio/client/hooks/use-shell-core.jsx +1212 -0
  20. package/apps/studio/client/hooks/use-tabs.jsx +723 -0
  21. package/apps/studio/client/hooks/use-web-socket.jsx +13 -0
  22. package/apps/studio/client/inspector/artboard-knobs.jsx +456 -0
  23. package/apps/studio/client/inspector/color-picker.jsx +196 -0
  24. package/apps/studio/client/inspector/color.js +92 -0
  25. package/apps/studio/client/inspector/css-knobs.jsx +1720 -0
  26. package/apps/studio/client/inspector/css-vocab.jsx +131 -0
  27. package/apps/studio/client/inspector/ds-tokens.js +90 -0
  28. package/apps/studio/client/inspector/grid-tracks-editor.jsx +97 -0
  29. package/apps/studio/client/inspector/inspect-computed.jsx +68 -0
  30. package/apps/studio/client/inspector/inspector-panel.jsx +769 -0
  31. package/apps/studio/client/inspector/layers.jsx +322 -0
  32. package/apps/studio/client/inspector/selection.js +65 -0
  33. package/apps/studio/client/inspector/token-popover.jsx +301 -0
  34. package/apps/studio/client/menus/menubar.jsx +856 -0
  35. package/apps/studio/client/selection-scope.js +40 -0
  36. package/apps/studio/client/shell/banners.jsx +272 -0
  37. package/apps/studio/client/shell/collapsed-rail.jsx +23 -0
  38. package/apps/studio/client/shell/comments-panel.jsx +177 -0
  39. package/apps/studio/client/shell/constants.js +60 -0
  40. package/apps/studio/client/shell/dock.jsx +131 -0
  41. package/apps/studio/client/shell/icons.jsx +370 -0
  42. package/apps/studio/client/shell/status-bar.jsx +215 -0
  43. package/apps/studio/client/shell/util.js +332 -0
  44. package/apps/studio/client/shell/viewport.jsx +254 -0
  45. package/apps/studio/client/system/system-view.jsx +255 -0
  46. package/apps/studio/client/tree/tree.jsx +1243 -0
  47. package/apps/studio/comments-overlay.tsx +6 -4
  48. package/apps/studio/config.schema.json +5 -0
  49. package/apps/studio/context.ts +13 -0
  50. package/apps/studio/dist/client.bundle.js +1337 -1337
  51. package/apps/studio/dist/comment-mount.js +2 -2
  52. package/apps/studio/exporters/_browser-bundles.ts +21 -2
  53. package/apps/studio/exporters/jobs.ts +75 -15
  54. package/apps/studio/exporters/scope.ts +15 -12
  55. package/apps/studio/format.ts +296 -0
  56. package/apps/studio/http.ts +213 -23
  57. package/apps/studio/server.ts +118 -29
  58. package/apps/studio/sync/accepted-link.ts +6 -0
  59. package/apps/studio/sync/agent.ts +9 -1
  60. package/apps/studio/sync/cold-start-apply.ts +29 -4
  61. package/apps/studio/sync/cold-start.ts +78 -0
  62. package/apps/studio/sync/file-plane.ts +61 -1
  63. package/apps/studio/sync/format-sync.ts +160 -0
  64. package/apps/studio/sync/index.ts +134 -10
  65. package/apps/studio/sync/journal-client.ts +25 -5
  66. package/apps/studio/sync/migrate-seed.ts +8 -1
  67. package/apps/studio/sync/status.ts +2 -0
  68. package/apps/studio/sync/transaction-client.ts +130 -13
  69. package/apps/studio/ui-prefs.ts +95 -10
  70. package/apps/studio/whats-new.json +9 -0
  71. package/apps/studio/ws.ts +19 -4
  72. package/cli/bin/claude-design-server.mjs +0 -0
  73. package/package.json +10 -8
@@ -0,0 +1,2150 @@
1
+ // hooks/use-canvas-bridge.jsx — moved verbatim out of client/app.jsx (Maude v2 plan V2-0.2, move-only split).
2
+
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
+ import { SYSTEM_TAB, isModuleCanvasPath } from '../shell/constants.js';
5
+ import { acceptCanvasNotice } from '../../canvas-notice-message.ts';
6
+ import { notifyCanvasText } from '../../notifications.tsx';
7
+ import { browseFirstRunHint, layersTreeSig } from '../shell/util.js';
8
+ import { resolveToolCursor } from '../../canvas-cursors.ts';
9
+ import { afterRecordableWrites } from '../inspector/css-knobs.jsx';
10
+ import { applyEditRequest } from '../apply-edit-request.ts';
11
+ import { localSelectRecord } from '../selection-scope.js';
12
+ import { PHOTO_ASSET_RE } from '../inspector/inspector-panel.jsx';
13
+ import { sanitizeArtboardText } from '../panels/timeline-comp-target.js';
14
+ import { isNativeApp } from '../github.js';
15
+ import { browserCaptureEligible, captureDeckViaBrowser, captureScale, sanitizeCapturedItems } from '../export-lane.js';
16
+ import { downloadCapturedBlob } from '../dialogs/export-dialog.jsx';
17
+ import { moveLayerNode } from '../inspector/layers.jsx';
18
+ import { SCREEN_PRESETS, replacedValue } from '../inspector/css-vocab.jsx';
19
+ import { PAPER_PRESETS, resolvePrintArtboard } from '../../print/units.ts';
20
+
21
+ export function useCanvasBridge({
22
+ activePath, selected, setSelected, selectedRef, lastLocalSelectRef, scheduleHaloRestore,
23
+ scheduleArtboardResync, pendingReorderRef, lastLayersTreeRef, settlePendingSelectionRef,
24
+ reorderLayerRef, repositionElementRef, resizeElementRef, layersBusyRef, layersBusyTimerRef,
25
+ layersTree, setLayersTree, setLoadingPath, setCanvasError, setLoadedPath, cfg, viewerMode,
26
+ commentsByFile, focusedCommentId, setFocusedCommentId, theme, setPaletteOpen, setExportDialog,
27
+ setTimelineOpen, setActiveComps, setTimelineFrame, setTimelinePlaying, canvasActiveArtboard,
28
+ setCanvasActiveArtboard, timelineFrameRef, timelineCompIdRef, setInspectorTab, setPhotoSel,
29
+ openRightPanel, toggleRightPanel, maybeAutoOpenInspectorOnSelect, toggleTimeline, minimapVisible,
30
+ zoomCtlVisible, presentMode, setPresentMode, setActiveArtboards, iframesRef, postToActiveCanvas,
31
+ captureFromCanvas, broadcastChrome, wsSend, reloadActive
32
+ }) {
33
+ // ----- Inbound messages from iframes -----
34
+ useEffect(() => {
35
+ // Does this comment id belong to the canvas the user is actually looking
36
+ // at? Scopes the patch/delete relays below — see the SECURITY note there.
37
+ //
38
+ // The leading `!!activePath` is load-bearing, not defensive noise: with no
39
+ // active canvas the branches' `activeWin` is `null`, and `e.source` is also
40
+ // `null` for a message whose source context was discarded before dispatch —
41
+ // so `e.source === activeWin` can pass as `null === null`. This is the
42
+ // second conjunct that closes that path. Don't "simplify" it away.
43
+ const ownsActiveComment = (id) =>
44
+ !!activePath && (commentsByFile[activePath] || []).some((c) => c && c.id === id);
45
+ function onMessage(e) {
46
+ // Cross-origin hardening (DDR-054): only accept dgn control messages from
47
+ // the canvas-content origin — the split origin when on, else our own origin
48
+ // for the same-origin iframe. Drops spoofed messages from any other window.
49
+ // Every canvas iframe shares that origin, so the check below proves only
50
+ // "a canvas said this", NOT "the canvas the user is looking at said it" —
51
+ // each mutating branch additionally gates on `e.source === activeWin`.
52
+ const expectedOrigin = cfg?.canvasOrigin || window.location.origin;
53
+ if (e.origin !== expectedOrigin) return;
54
+ const m = e.data;
55
+ if (!m || typeof m !== 'object' || !m.dgn) return;
56
+ if (m.dgn === 'canvas-notice') {
57
+ const activeWin = activePath && activePath !== SYSTEM_TAB
58
+ ? iframesRef.current.get(activePath)?.contentWindow : null;
59
+ const notice = acceptCanvasNotice(e, expectedOrigin, activeWin);
60
+ if (notice) notifyCanvasText(notice.title, notice.kind);
61
+ return;
62
+ }
63
+ if (m.dgn === 'tool-cursor') {
64
+ // Phase 24 — show the active canvas tool's cursor across the WHOLE app
65
+ // shell (sidebar, top bar, everything) so the custom cursor is visible
66
+ // everywhere in maude, not just inside the canvas iframe. The canvas
67
+ // sends only a tool TOKEN; we resolve it to a cursor string from our own
68
+ // trusted map (resolveToolCursor) and apply THAT — never a raw
69
+ // canvas-supplied value. A malicious synced canvas (DDR-054) can thus
70
+ // only pick a known, always-visible glyph; it cannot inject an
71
+ // invisible/displaced SVG cursor as a clickjacking aid over the un-CSP'd
72
+ // shell (phase-24 ethical-hacker Finding 2; DDR-067).
73
+ // feature-4 — the browse tool is a pure pass-through: don't force a
74
+ // global shell cursor, so the shell chrome keeps its own affordance
75
+ // cursors (pointer over buttons). Also fire the one-time "press V" hint
76
+ // — a live canvas booting in browse is exactly when it's teachable.
77
+ if (m.tool === 'browse') {
78
+ document.body.style.cursor = '';
79
+ const el = document.getElementById('dc-app-cursor');
80
+ if (el) el.textContent = '';
81
+ browseFirstRunHint(viewerMode);
82
+ return;
83
+ }
84
+ const cursor = resolveToolCursor(m.tool);
85
+ if (cursor) {
86
+ document.body.style.cursor = cursor;
87
+ let el = document.getElementById('dc-app-cursor');
88
+ if (!el) {
89
+ el = document.createElement('style');
90
+ el.id = 'dc-app-cursor';
91
+ document.head.appendChild(el);
92
+ }
93
+ el.textContent = `* { cursor: ${cursor} !important; }`;
94
+ }
95
+ return;
96
+ }
97
+ // SECURITY (attacker Finding 2, mirrors the phase-28 F-2 reorder/present
98
+ // gate at the handlers below): selection posts are honored ONLY from the
99
+ // ACTIVE canvas's window. Every open canvas iframe shares one
100
+ // `canvasOrigin`, so the origin check above can't tell the foreground
101
+ // canvas from a background/synced one — and a selection carries an
102
+ // attacker-chosen `file` that the server trusts verbatim and write-throughs
103
+ // into the persistent per-canvas `selections` map, then rides into the
104
+ // auto-approving ACP agent's frozen context. A background (untrusted, DDR-054)
105
+ // canvas must not be able to plant a selection with no user gesture. The
106
+ // user can only click the visible active canvas, so a non-active source is
107
+ // never a legitimate selection.
108
+ //
109
+ // The SAME gate now covers the privileged SOURCE-WRITE relays — `edit-text`
110
+ // (inline text commit) and `apply-edit` (undo/redo re-application). Both
111
+ // ride into a main-origin `.tsx` rewrite; a write path is strictly more
112
+ // dangerous than a selection, yet was previously ungated (ethical-hacker
113
+ // F-B, DDR-160 follow-up). A background/synced untrusted canvas (DDR-054)
114
+ // must not drive a gestureless write into another canvas — and inline edits
115
+ // + Cmd+Z always originate in the ACTIVE canvas the user is looking at, so
116
+ // a non-active source is never legitimate here either.
117
+ if (
118
+ m.dgn === 'select' ||
119
+ m.dgn === 'select-set' ||
120
+ m.dgn === 'clear-select' ||
121
+ m.dgn === 'edit-text' ||
122
+ m.dgn === 'apply-edit' ||
123
+ m.dgn === 'undo-barrier'
124
+ ) {
125
+ const activeWin =
126
+ activePath && activePath !== SYSTEM_TAB
127
+ ? iframesRef.current.get(activePath)?.contentWindow
128
+ : null;
129
+ if (e.source !== activeWin) return;
130
+ }
131
+ if (m.dgn === 'select' && m.selection) {
132
+ setPhotoSel(null); // a DOM selection supersedes an annotation-image Photo target
133
+ lastLocalSelectRef.current = localSelectRecord(m.selection, activePath);
134
+ wsSend({ type: 'select', selection: m.selection });
135
+ setSelected(m.selection);
136
+ maybeAutoOpenInspectorOnSelect(m.selection); // Stage C
137
+ } else if (m.dgn === 'select-set') {
138
+ setPhotoSel(null);
139
+ lastLocalSelectRef.current = localSelectRecord(m.selection, activePath);
140
+ // Canvas multi-select. Payload shape:
141
+ // null → empty selection
142
+ // Selection → length-1 (back-compat with legacy single-element shape)
143
+ // Selection[] → N > 1
144
+ // For shell purposes we track the focused entry (head of array, or
145
+ // the bare object) — comments + halo only act on one element at a
146
+ // time today. Multi-target editing is an explicit Phase-4.1 non-goal.
147
+ const payload = m.selection;
148
+ if (payload == null) {
149
+ wsSend({ type: 'clear-select' });
150
+ setSelected(null);
151
+ } else if (Array.isArray(payload)) {
152
+ const head = payload[0] ?? null;
153
+ if (head) wsSend({ type: 'select', selection: head });
154
+ setSelected(head);
155
+ // Stage C — auto-open only for a genuine SINGLE selection, never multi.
156
+ if (payload.length === 1) maybeAutoOpenInspectorOnSelect(head);
157
+ } else {
158
+ wsSend({ type: 'select', selection: payload });
159
+ setSelected(payload);
160
+ maybeAutoOpenInspectorOnSelect(payload); // Stage C
161
+ }
162
+ } else if (m.dgn === 'clear-select') {
163
+ setPhotoSel(null);
164
+ lastLocalSelectRef.current = localSelectRecord(null, activePath);
165
+ wsSend({ type: 'clear-select' });
166
+ setSelected(null);
167
+ } else if (m.dgn === 'edit-text' && m.id) {
168
+ // Phase 12 (DDR-103) — inline text edit committed in the canvas. POST to
169
+ // the main-origin-only /_api/edit-text → editText writes the escaped
170
+ // JSXText to source; the file-watcher HMR reload then shows the new text.
171
+ // DDR-150 P1: a refusal is NO LONGER silent — post `edit-reverted` back
172
+ // to the canvas, which reverts the optimistic contenteditable text AND
173
+ // toasts the reason, so a failed edit can't silently vanish on the next
174
+ // reload ("my text edit didn't stick"). The user-facing toast lives
175
+ // canvas-side (showCanvasToast) because App has no in-scope status
176
+ // surface — `setStatus` belongs to ExportDialog, not App.
177
+ const editSource = e.source;
178
+ const revert = (reason) => {
179
+ try {
180
+ editSource?.postMessage({ dgn: 'edit-reverted', op: 'text', id: m.id, reason }, '*');
181
+ } catch {}
182
+ };
183
+ fetch('/_api/edit-text', {
184
+ method: 'POST',
185
+ headers: { 'content-type': 'application/json' },
186
+ body: JSON.stringify({
187
+ canvas: m.file,
188
+ id: m.id,
189
+ text: m.text ?? '',
190
+ // Context for editing `{variable}` text — which rendered instance +
191
+ // its pre-edit text, so the engine targets the right source string.
192
+ ...(typeof m.occurrence === 'number' ? { occurrence: m.occurrence } : {}),
193
+ ...(typeof m.before === 'string' ? { before: m.before } : {}),
194
+ }),
195
+ })
196
+ .then((r) => r.json().catch(() => ({})))
197
+ .then((j) => {
198
+ if (!j.ok) revert(j.error || "this element can't be edited inline");
199
+ })
200
+ .catch(() => revert('network error'));
201
+ } else if (m.dgn === 'undo-barrier' && typeof m.requestId === 'string') {
202
+ // Answer once every write that will post a `record-edit` has settled
203
+ // (and so posted it — window messages arrive in order), so the canvas's
204
+ // Cmd+Z sees the edit that is on screen. Read-only; nothing is written.
205
+ const source = e.source;
206
+ Promise.all([editApplyChainRef.current.catch(() => {}), afterRecordableWrites()]).then(() => {
207
+ try {
208
+ source?.postMessage({ dgn: 'undo-barrier-ok', requestId: m.requestId }, '*');
209
+ } catch {}
210
+ });
211
+ } else if (m.dgn === 'apply-edit' && m.id && (m.op === 'css' || m.op === 'text' || m.op === 'attr')) {
212
+ // Inline-edit undo/redo (DDR-103/104 follow-up). The canvas iframe's
213
+ // `edit-source` command can't call the main-origin-only `/_api/edit-*`
214
+ // routes (DDR-054), so it asks us to re-apply the before/after value.
215
+ // `value` null = reset (remove the inline prop / attr). The css/attr
216
+ // request carries the command's expected current value, so an undo can
217
+ // never overwrite a teammate's newer value (audit 2026-09-13 P1 #5);
218
+ // the outcome goes back to the canvas so a refused undo/redo does not
219
+ // advance its stack.
220
+ const req = applyEditRequest(m);
221
+ if (!req) return;
222
+ const replyTo = e.source;
223
+ const reply = (result) => {
224
+ if (typeof m.requestId !== 'string') return;
225
+ try {
226
+ replyTo?.postMessage({ dgn: 'apply-edit-result', requestId: m.requestId, ...result }, '*');
227
+ } catch {}
228
+ };
229
+ const value = typeof m.value === 'string' ? m.value : null;
230
+ editApplyChainRef.current = editApplyChainRef.current
231
+ .catch(() => {})
232
+ .then(() =>
233
+ fetch(req.url, {
234
+ method: 'POST',
235
+ headers: { 'content-type': 'application/json' },
236
+ body: JSON.stringify(req.body),
237
+ })
238
+ .then((r) => r.json().catch(() => ({})))
239
+ .then((j) => {
240
+ if (j.ok) {
241
+ // Repaint only once the source accepted it: a refused undo
242
+ // must not show a value the file does not hold.
243
+ if (req.op === 'css') applyOptimisticStyle({ id: m.id, prop: m.key, value });
244
+ reply({ ok: true });
245
+ return;
246
+ }
247
+ console.warn('[apply-edit]', req.op, j.error || 'failed');
248
+ reply({ ok: false, error: j.error || 'failed', conflict: j.conflict === true });
249
+ })
250
+ .catch(() => reply({ ok: false, error: 'network error' }))
251
+ );
252
+ } else if (m.dgn === 'layers-tree') {
253
+ // Phase 12 Task 4 — browsable layers tree for the active artboard.
254
+ setLayersTree({ artboardId: m.artboardId, nodes: Array.isArray(m.tree) ? m.tree : [] });
255
+ const sig = layersTreeSig(m.tree);
256
+ lastLayersTreeRef.current = { tree: m.tree, sig, artboardId: m.artboardId ?? null };
257
+ // fresh tree (correct ids) landed — drags OK again
258
+ layersBusyRef.current = false;
259
+ if (layersBusyTimerRef.current) {
260
+ clearTimeout(layersBusyTimerRef.current);
261
+ layersBusyTimerRef.current = null;
262
+ }
263
+ // Phase 12.1 — a reorder writes source → SOFT HMR (no dgn:'loaded' fires,
264
+ // so the loaded-handler re-select never runs). The live observer's fresh
265
+ // tree is our signal instead: re-select the moved element by its NEW
266
+ // positional id (movedId) so the selection halo + the keyboard cursor
267
+ // follow it. Without this the next Alt+arrow acts on the STALE id, which
268
+ // positionally now points at a different element. Only act once the tree
269
+ // actually CONTAINS movedId — an in-canvas drag posts a PREVIEW tree
270
+ // first (old ids, pre-write); consuming then would re-select nothing and
271
+ // burn the pending ref before the real post-HMR tree lands.
272
+ settlePendingSelectionRef.current?.(m.tree, sig, m.artboardId ?? null);
273
+ } else if (m.dgn === 'reorder-revert') {
274
+ // Phase 12.1 follow-up — Cmd+Z/Cmd+Shift+Z on a reorder. The canvas undo
275
+ // stack (untrusted iframe) can't reach the main-origin-only
276
+ // /_api/reorder-revert, so it REQUESTS; the shell writes. Active canvas
277
+ // only. SECURITY (adversarial F4): pin the target to `activePath` — do NOT
278
+ // forward m.canvas (an untrusted iframe could name a different canvas); the
279
+ // undo stack is per active canvas anyway, and the server's seq→entry.abs +
280
+ // 409 content-match are the backstop.
281
+ const rvWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
282
+ const rvShape = typeof m.seq === 'number' && (m.dir === 'undo' || m.dir === 'redo');
283
+ if (e.source === rvWin && rvShape && activePath) {
284
+ layersBusyRef.current = true;
285
+ if (layersBusyTimerRef.current) clearTimeout(layersBusyTimerRef.current);
286
+ layersBusyTimerRef.current = setTimeout(() => {
287
+ layersBusyRef.current = false;
288
+ layersBusyTimerRef.current = null;
289
+ }, 700);
290
+ fetch('/_api/reorder-revert', {
291
+ method: 'POST',
292
+ headers: { 'content-type': 'application/json' },
293
+ body: JSON.stringify({ canvas: activePath, seq: m.seq, dir: m.dir }),
294
+ })
295
+ .then((r) => r.json().catch(() => ({})))
296
+ .then((j) => {
297
+ if (!j.ok) console.warn('[reorder-revert]', j.error || 'failed');
298
+ })
299
+ .catch(() => {});
300
+ }
301
+ } else if (m.dgn === 'reorder-request') {
302
+ // Phase 12.1 (DDR-138) — the in-canvas ReorderGrip (untrusted canvas
303
+ // iframe) can't reach the main-origin-only /_api/reorder (DDR-054), so it
304
+ // REQUESTS a move; the shell performs the privileged write via reorderLayer
305
+ // (same lane as edit-text → /_api/edit-text). Honor it ONLY from the ACTIVE
306
+ // canvas (a background tab's untrusted canvas must not mutate source), and
307
+ // only for well-formed ids/position (reorderLayer + the server re-validate).
308
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
309
+ const okShape =
310
+ typeof m.id === 'string' &&
311
+ typeof m.refId === 'string' &&
312
+ (m.position === 'before' ||
313
+ m.position === 'after' ||
314
+ m.position === 'inside-start' ||
315
+ m.position === 'inside-end');
316
+ if (e.source === activeWin && okShape) {
317
+ reorderLayerRef.current?.(m.id, m.refId, m.position, {
318
+ idIndex: Number.isInteger(m.idIndex) ? m.idIndex : undefined,
319
+ refIndex: Number.isInteger(m.refIndex) ? m.refIndex : undefined,
320
+ });
321
+ }
322
+ } else if (m.dgn === 'reposition-request') {
323
+ // Free-XY reposition for out-of-flow elements (position:absolute/
324
+ // fixed) — the in-canvas drag switches from reorder-mode to
325
+ // coordinate-mode when the dragged element is out of flow, because
326
+ // reordering an absolute/fixed element's JSX siblings never changes
327
+ // where it paints (the "moves then snaps back" RCA). Same trust
328
+ // model + confused-deputy guard as reorder-request: untrusted canvas
329
+ // REQUESTS, shell WRITES, pinned to the ACTIVE canvas (never
330
+ // `m.canvas`, which an untrusted iframe could spoof).
331
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
332
+ const okShape =
333
+ typeof m.id === 'string' &&
334
+ Number.isFinite(m.left) &&
335
+ Number.isFinite(m.top) &&
336
+ Number.isFinite(m.beforeLeft) &&
337
+ Number.isFinite(m.beforeTop);
338
+ if (e.source === activeWin && okShape) {
339
+ repositionElementRef.current?.(
340
+ m.id,
341
+ m.left,
342
+ m.top,
343
+ m.beforeLeft,
344
+ m.beforeTop,
345
+ Number.isInteger(m.idIndex) ? m.idIndex : undefined
346
+ );
347
+ }
348
+ } else if (m.dgn === 'resize-request') {
349
+ // feature-element-editing-robustness Stage D — in-canvas drag-resize
350
+ // commit. Same trust model + confused-deputy guard as reposition-request:
351
+ // untrusted canvas REQUESTS, shell WRITES, pinned to the ACTIVE canvas
352
+ // (never `m.canvas`). Payload: { id, patch:{width,height,left?,top?},
353
+ // before:{width,height,left,top} } — px strings, before values null when
354
+ // the prop was unset (reset on undo).
355
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
356
+ const okShape =
357
+ typeof m.id === 'string' && m.patch && typeof m.patch === 'object';
358
+ if (e.source === activeWin && okShape) {
359
+ resizeElementRef.current?.(
360
+ m.id,
361
+ m.patch,
362
+ m.before,
363
+ Number.isInteger(m.idIndex) ? m.idIndex : undefined
364
+ );
365
+ }
366
+ } else if (m.dgn === 'delete-request') {
367
+ // feature-element-editing-robustness Stage I — delete an element (Del key
368
+ // / context menu / toolbar in the canvas). Same confused-deputy guard as
369
+ // reorder/reposition/resize: untrusted canvas REQUESTS, shell WRITES,
370
+ // pinned to the ACTIVE canvas (never `m.canvas`).
371
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
372
+ if (e.source === activeWin && typeof m.id === 'string') {
373
+ deleteElementShellRef.current?.(m.id, Number.isInteger(m.idIndex) ? m.idIndex : undefined);
374
+ }
375
+ } else if (m.dgn === 'duplicate-request') {
376
+ // Cmd+D (Task L3) — duplicate the selected element. Confused-deputy gated
377
+ // + pinned to the active canvas, like the other structural verbs.
378
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
379
+ if (e.source === activeWin && typeof m.id === 'string') {
380
+ duplicateElementShellRef.current?.(
381
+ m.id,
382
+ Number.isInteger(m.idIndex) ? m.idIndex : undefined
383
+ );
384
+ }
385
+ } else if (m.dgn === 'copy-style') {
386
+ // Task L4 — capture the current selection's authored style (shell-side).
387
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
388
+ if (e.source === activeWin) copyStyleRef.current?.();
389
+ } else if (m.dgn === 'paste-style') {
390
+ // Task L4 — apply the copied style to the target element.
391
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
392
+ if (e.source === activeWin && typeof m.id === 'string') pasteStyleRef.current?.(m.id);
393
+ } else if (m.dgn === 'insert-request') {
394
+ // Stage I3 — insert a synthesized div/text/image relative to `refId`,
395
+ // OR — empty-artboard fallback (tool-palette "+ Element" on a fresh
396
+ // artboard with no elements yet) — as a child of `artboardId`. Exactly
397
+ // one of the two must be present; the artboardId variant only makes
398
+ // sense inside-start/inside-end (no sibling to be before/after).
399
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
400
+ const hasRefId = typeof m.refId === 'string';
401
+ const hasArtboardId = typeof m.artboardId === 'string';
402
+ const okPosition =
403
+ m.position === 'before' ||
404
+ m.position === 'after' ||
405
+ m.position === 'inside-start' ||
406
+ m.position === 'inside-end';
407
+ const okShape =
408
+ hasRefId !== hasArtboardId &&
409
+ (m.kind === 'div' || m.kind === 'text' || m.kind === 'image') &&
410
+ okPosition &&
411
+ (!hasArtboardId || m.position === 'inside-start' || m.position === 'inside-end');
412
+ if (e.source === activeWin && okShape) {
413
+ insertElementShellRef.current?.(m.refId, m.position, m.kind, {
414
+ artboardId: hasArtboardId ? m.artboardId : undefined,
415
+ src: typeof m.src === 'string' ? m.src : undefined,
416
+ refIndex: Number.isInteger(m.refIndex) ? m.refIndex : undefined,
417
+ });
418
+ }
419
+ } else if (m.dgn === 'insert-image-request') {
420
+ // Stage F/I3 — "Insert ▸ Image" from the canvas context menu, or the
421
+ // tool-palette's Image tool (`artboardId` in place of `refId` for its
422
+ // empty-artboard fallback, or NEITHER when the canvas has no artboard
423
+ // at all — feature-bulk-media-insert). An image needs a contained
424
+ // asset src, so the shell opens the AssetPicker in bulk mode; the
425
+ // confirm then drives insertElementShell(kind:'image') per path (Task
426
+ // 10) or a single batched annotation insert. Confused-deputy gated +
427
+ // pinned to the active canvas like the other request verbs.
428
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
429
+ const hasRefId = typeof m.refId === 'string';
430
+ const hasArtboardId = typeof m.artboardId === 'string';
431
+ const noAnchor = !hasRefId && !hasArtboardId;
432
+ const okShape =
433
+ (hasRefId !== hasArtboardId || noAnchor) &&
434
+ (noAnchor ||
435
+ m.position === 'before' ||
436
+ m.position === 'after' ||
437
+ m.position === 'inside-start' ||
438
+ m.position === 'inside-end') &&
439
+ (!hasArtboardId || m.position === 'inside-start' || m.position === 'inside-end');
440
+ if (e.source === activeWin && okShape) {
441
+ openAssetPickerRef.current?.({
442
+ purpose: 'insert-image',
443
+ canvas: activePath,
444
+ refId: m.refId,
445
+ artboardId: hasArtboardId ? m.artboardId : undefined,
446
+ position: noAnchor ? undefined : m.position,
447
+ refIndex: Number.isInteger(m.refIndex) ? m.refIndex : undefined,
448
+ multiple: true,
449
+ // Artboard destination is possible whenever there's ANY resolvable
450
+ // anchor — a refId (context-menu, or the tool-palette's normal
451
+ // last-element case) inserts inside the SAME artboard that
452
+ // element already lives in, not just the artboardId fallback.
453
+ hasArtboardAnchor: !noAnchor,
454
+ });
455
+ }
456
+ } else if (m.dgn === 'replace-media-request') {
457
+ // Stage F2 — "Replace image…" from the canvas context menu. Opens the
458
+ // AssetPicker in replace mode; the pick re-points src via edit-attr. The
459
+ // context menu supplies the current src as the undo before-value.
460
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
461
+ if (e.source === activeWin && typeof m.id === 'string') {
462
+ openAssetPickerRef.current?.({
463
+ purpose: 'replace-src',
464
+ canvas: activePath,
465
+ id: m.id,
466
+ before: typeof m.before === 'string' ? m.before : null,
467
+ });
468
+ }
469
+ } else if (m.dgn === 'convert-to-absolute-request') {
470
+ // feature-4 T8 (convert-to-absolute, DDR-188) — the canvas measured the
471
+ // frozen child boxes; perform the main-origin batch write (ONE undo
472
+ // seq via structuralWrite). The server re-validates every field; here we
473
+ // just confused-deputy-guard the source (DDR-054) + a light shape check.
474
+ // Two shapes: single-container (element context menu) or `containers`
475
+ // batch (the artboard-level "Convert layout to absolute").
476
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
477
+ const isBatch = Array.isArray(m.containers) && m.containers.length > 0;
478
+ const isSingle =
479
+ typeof m.containerId === 'string' && Array.isArray(m.children) && m.children.length > 0;
480
+ if (e.source === activeWin && (isBatch || isSingle)) {
481
+ const count = isBatch
482
+ ? m.containers.reduce(
483
+ (n, c) => n + (Array.isArray(c?.children) ? c.children.length : 0),
484
+ 0
485
+ )
486
+ : m.children.length;
487
+ structuralWriteRef.current?.(
488
+ '/_api/convert-to-absolute',
489
+ isBatch
490
+ ? {
491
+ allowShared: m.allowShared === true,
492
+ containers: m.containers,
493
+ // feature-4 TRUE FLATTEN — unstyled layout wrappers to remove.
494
+ ...(Array.isArray(m.dissolve) && m.dissolve.length > 0
495
+ ? { dissolve: m.dissolve }
496
+ : {}),
497
+ }
498
+ : {
499
+ containerId: m.containerId,
500
+ containerSetRelative: m.containerSetRelative === true,
501
+ // feature-4 T8b — the canvas asked the user's confirm already;
502
+ // the server still refuses `.map` children regardless.
503
+ allowShared: m.allowShared === true,
504
+ children: m.children,
505
+ },
506
+ {
507
+ label: 'convert to absolute',
508
+ // Dogfood 2026-07-19 — the conversion is zero-visual-delta by
509
+ // design, which LOOKED like "nic nedělá". Say what happened, and
510
+ // surface server refusals (.map children etc.) as a toast
511
+ // instead of a console.warn nobody sees.
512
+ onOk: () => {
513
+ postToActiveCanvas({ dgn: 'selection-clear' });
514
+ postToActiveCanvas({
515
+ dgn: 'op-toast',
516
+ message: `Converted ${count} element${count === 1 ? '' : 's'} to absolute — press V and drag them freely (⌘Z to undo).`,
517
+ });
518
+ },
519
+ onFail: (j) =>
520
+ postToActiveCanvas({
521
+ dgn: 'op-toast',
522
+ message: `Convert failed: ${j?.error || 'unknown error'}`,
523
+ }),
524
+ }
525
+ );
526
+ }
527
+ } else if (m.dgn === 'replace-annotation-media-request') {
528
+ // Stage F3 — "Replace…" on an annotation ImageStroke/MediaRefStroke.
529
+ // Opens the SAME AssetPicker; unlike F2 the pick is posted BACK DOWN to
530
+ // the canvas (no data-cd-id to ride edit-attr — the annotation model owns
531
+ // its own strokes, so the canvas iframe performs the write itself).
532
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
533
+ if (e.source === activeWin && typeof m.id === 'string') {
534
+ openAssetPickerRef.current?.({
535
+ purpose: 'replace-annotation-media',
536
+ canvas: activePath,
537
+ id: m.id,
538
+ before: typeof m.before === 'string' ? m.before : null,
539
+ });
540
+ }
541
+ } else if (m.dgn === 'edit-annotation-photo-request') {
542
+ // feature-photo-editor (Task 17) — "Edit Photo…" on an annotation
543
+ // ImageStroke. The annotation model has no data-cd-id / DOM selection, so
544
+ // it can't ride the normal select path; instead the canvas posts its
545
+ // `assets/<sha8>.<ext>` href up and the shell opens the Photo-only tab on
546
+ // it. Same confused-deputy gate (DDR-054) + active-canvas pin as F3.
547
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
548
+ const asset = PHOTO_ASSET_RE.exec(typeof m.asset === 'string' ? m.asset : '')?.[0] || null;
549
+ if (e.source === activeWin && typeof m.id === 'string' && asset) {
550
+ setPhotoSel({ asset, strokeId: m.id });
551
+ openRightPanel('inspector');
552
+ setInspectorTab('photo');
553
+ }
554
+ } else if (m.dgn === 'open-sticker-picker') {
555
+ // Phase 4 (whiteboard-improvements) — the toolbar's Stickers button.
556
+ // Confused-deputy gated + pinned to the active canvas like the other
557
+ // request verbs above.
558
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
559
+ if (e.source === activeWin) {
560
+ openStickerPickerRef.current?.({ canvas: activePath });
561
+ }
562
+ } else if (m.dgn === 'insert-artboard-request') {
563
+ // Stage I4 — insert a new empty artboard from a screen-size preset.
564
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
565
+ const okShape =
566
+ typeof m.id === 'string' &&
567
+ Number.isFinite(m.width) &&
568
+ Number.isFinite(m.height);
569
+ if (e.source === activeWin && okShape) {
570
+ insertArtboardShellRef.current?.({
571
+ id: m.id,
572
+ label: typeof m.label === 'string' ? m.label : m.id,
573
+ width: m.width,
574
+ height: m.height,
575
+ });
576
+ }
577
+ } else if (m.dgn === 'resize-artboard-request') {
578
+ // Stage D4 — free-hand artboard resize (numeric width/height props).
579
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
580
+ const okShape =
581
+ typeof m.artboardId === 'string' &&
582
+ (Number.isFinite(m.width) || Number.isFinite(m.height));
583
+ if (e.source === activeWin && okShape) {
584
+ resizeArtboardShellRef.current?.(
585
+ m.artboardId,
586
+ Number.isFinite(m.width) ? m.width : undefined,
587
+ Number.isFinite(m.height) ? m.height : undefined
588
+ );
589
+ }
590
+ } else if (m.dgn === 'delete-artboard-request') {
591
+ // Backspace / context-menu delete of a whole artboard (by its id prop).
592
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
593
+ if (e.source === activeWin && typeof m.artboardId === 'string') {
594
+ deleteArtboardShellRef.current?.(m.artboardId);
595
+ }
596
+ } else if (m.dgn === 'rename-artboard-request') {
597
+ // Plan T25/L08 — double-click an artboard's name to rename it. Same
598
+ // confused-deputy guard: the canvas asks, the shell writes the active
599
+ // canvas only.
600
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
601
+ if (
602
+ e.source === activeWin &&
603
+ typeof m.artboardId === 'string' &&
604
+ typeof m.label === 'string' &&
605
+ m.label.trim()
606
+ ) {
607
+ structuralWriteRef.current?.(
608
+ '/_api/set-artboard-label',
609
+ { artboardId: m.artboardId, label: m.label.slice(0, 80) },
610
+ { label: 'rename artboard' }
611
+ );
612
+ }
613
+ } else if (m.dgn === 'set-artboard-kind-request') {
614
+ // feature-1-artboard-kinds-foundation, T8 — context-menu "Artboard
615
+ // kind" submenu (inside the untrusted iframe). `kind: null` clears
616
+ // back to the implicit default.
617
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
618
+ const okKind = m.kind === null || typeof m.kind === 'string';
619
+ if (e.source === activeWin && typeof m.artboardId === 'string' && okKind) {
620
+ // Dogfood round 6 — DIRECT write, never back into the ask flow (the
621
+ // ask lives shell-side in setArtboardKindShell; re-entering it from
622
+ // this canvas round-trip looped the confirm dialog forever).
623
+ directArtboardKindWriteRef.current?.(m.artboardId, m.kind);
624
+ }
625
+ } else if (m.dgn === 'duplicate-artboard-request') {
626
+ // feature-3-web-artboards T3 — context-menu "Duplicate at width…"
627
+ // submenu (inside the untrusted iframe).
628
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
629
+ if (e.source === activeWin && typeof m.artboardId === 'string' && Number.isFinite(m.width)) {
630
+ duplicateArtboardShellRef.current?.(m.artboardId, m.width);
631
+ }
632
+ } else if (m.dgn === 'open-inspector') {
633
+ // Phase 12 — context-menu "Inspect" / tool-palette Inspect opens the right panel.
634
+ // feature-photo-editor (Task 16) — an optional `tab` lands the panel on a
635
+ // specific tab (the element "Edit Photo…" entry passes `tab: 'photo'`; the
636
+ // img is already selected via select-set, so the Photo tab derives its
637
+ // target from that selection's `photoAsset`).
638
+ openRightPanel('inspector');
639
+ if (typeof m.tab === 'string') setInspectorTab(m.tab);
640
+ } else if (m.dgn === 'present-enter') {
641
+ // Canvas tool-palette "Presentation mode" button — Present Mode is a
642
+ // shell-level state (hides the menubar / sidebar / panels), so the
643
+ // canvas requests it here and the shell flips it on + broadcasts
644
+ // dgn:'view-chrome' back to every iframe. Enter-only (the palette is
645
+ // hidden while presenting); exit is Esc or the floating pill. The
646
+ // inbound origin gate above (DDR-054) already authenticates the canvas.
647
+ // Hardening (phase-28 audit F-2): honor it ONLY from the ACTIVE canvas
648
+ // (a background tab's untrusted canvas must not flip the foreground),
649
+ // and NEVER while a modal dialog is open — present mode hides Sidebar-
650
+ // descendant modals (OAuth device-code / Share-invite), so an untrusted
651
+ // canvas could otherwise blank an in-flight confirmation.
652
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
653
+ const modalOpen = !!document.querySelector('[role="dialog"][aria-modal="true"]');
654
+ if (e.source === activeWin && !modalOpen && !presentMode) {
655
+ setPresentMode(true);
656
+ broadcastChrome({ present: true });
657
+ }
658
+ } else if (m.dgn === 'comment-compose' && m.selection) {
659
+ // Phase 6 — the iframe overlay owns the composer surface now. The
660
+ // shell just mirrors `selected` so the StatusBar / sidebar still
661
+ // reflect the target, and skips the legacy `startDraftFor` path that
662
+ // opened the shell-side composer. Legacy `.html` mocks (no
663
+ // canvas-shell mount) fall through to the same path; they lose the
664
+ // shell composer in this phase. Acceptable per Phase 6 scope.
665
+ setSelected(m.selection);
666
+ } else if (m.dgn === 'comment-submit' && m.payload && typeof m.payload.text === 'string') {
667
+ // Phase 6 — iframe overlay finished composing. Relay through the
668
+ // existing WS `comments-add` channel; server-side persistence +
669
+ // broadcast back are identical to the legacy shell-composer flow.
670
+ //
671
+ // SECURITY — gated on `activeWin` and PINNED to `activePath`, the same
672
+ // shape as every other mutating branch in this handler. The origin
673
+ // check at the top passes for EVERY canvas iframe (they all share
674
+ // `canvasOrigin`), so without this a canvas sitting in a BACKGROUND
675
+ // tab could post comments onto any file it cared to name, with no user
676
+ // gesture. This handler's preamble waived that on the grounds that
677
+ // comments are an "inert store" — the ACP panel's one-click
678
+ // "Implement N comments" action retires that premise, because open
679
+ // comments are now a feed the agent acts on. `p.file` is ignored
680
+ // rather than validated: the active canvas is the only file the user
681
+ // can actually see themselves commenting on.
682
+ const p = m.payload;
683
+ const txt = String(p.text).trim();
684
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
685
+ if (e.source === activeWin && txt && activePath && activePath !== SYSTEM_TAB) {
686
+ wsSend({
687
+ type: 'comments-add',
688
+ payload: {
689
+ file: activePath,
690
+ selector: p.selector,
691
+ index: p.index,
692
+ dom_path: p.dom_path,
693
+ tag: p.tag,
694
+ classes: p.classes,
695
+ bounds: p.bounds,
696
+ html_excerpt: p.html_excerpt,
697
+ // #134/#136 anchors — shape-checked server-side (api.ts commentsAdd).
698
+ annotationId: p.annotationId,
699
+ world: p.world,
700
+ text: txt,
701
+ },
702
+ });
703
+ }
704
+ } else if (m.dgn === 'comment-patch' && m.id && m.patch && typeof m.patch === 'object') {
705
+ // Phase 6 — thread popover routes resolve / reopen through here.
706
+ // SECURITY — same gate as comment-submit, plus an ownership check: a
707
+ // bare id would otherwise reach ANY comment in the project. Patch and
708
+ // delete change or remove somebody else's note, which is exactly why
709
+ // ws.ts refuses both for a viewer session; the iframe lane needs the
710
+ // matching restriction.
711
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
712
+ if (e.source === activeWin && ownsActiveComment(m.id)) {
713
+ wsSend({ type: 'comments-patch', id: m.id, patch: m.patch });
714
+ }
715
+ } else if (m.dgn === 'comment-delete' && m.id) {
716
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
717
+ if (e.source === activeWin && ownsActiveComment(m.id)) {
718
+ wsSend({ type: 'comments-delete', id: m.id });
719
+ setFocusedCommentId((prev) => (prev === m.id ? null : prev));
720
+ }
721
+ } else if (m.dgn === 'comment-click' && m.id) {
722
+ setFocusedCommentId(m.id);
723
+ } else if (m.dgn === 'artboards' && typeof m.count === 'number') {
724
+ // P2 (Plan C) — optional iframe-reported artboard count; overrides the
725
+ // meta.json-derived seed when the canvas knows better. Clamp.
726
+ const n = Math.round(m.count);
727
+ if (Number.isFinite(n) && n >= 0 && n <= 999) setActiveArtboards(n);
728
+ } else if (m.dgn === 'active-artboard') {
729
+ // DDR-148 — canvas-lib reports the viewport-active artboard on pan. Gate
730
+ // to the ACTIVE canvas window (a background canvas must not hijack the
731
+ // Timeline's target). The Timeline re-parses to this artboard's comp.
732
+ const activeWin =
733
+ activePath && activePath !== SYSTEM_TAB
734
+ ? iframesRef.current.get(activePath)?.contentWindow
735
+ : null;
736
+ if (e.source !== activeWin) return;
737
+ // Neutralize + cap exactly like the sibling timeline-comps handler —
738
+ // this id is matched AGAINST that one, so both sides must go through
739
+ // the same normalization or an odd-but-legal id would never match.
740
+ setCanvasActiveArtboard(sanitizeArtboardText(m.id));
741
+ } else if (m.dgn === 'timeline-comps' && Array.isArray(m.comps)) {
742
+ // DDR-148 — a video-comp announces its comp meta (from video-comp.tsx).
743
+ // Gate to the ACTIVE canvas window (phase-28 F-2 pattern): a background
744
+ // canvas must not plant comps into the Timeline panel, which shows the
745
+ // active canvas's comps. Inert display, but keep the seam closed.
746
+ const activeWin =
747
+ activePath && activePath !== SYSTEM_TAB
748
+ ? iframesRef.current.get(activePath)?.contentWindow
749
+ : null;
750
+ if (e.source !== activeWin) return;
751
+ const safe = m.comps
752
+ .filter((c) => c && typeof c.id === 'string')
753
+ .slice(0, 32)
754
+ .map((c) => ({
755
+ id: String(c.id).slice(0, 120),
756
+ fps: Math.max(1, Math.min(120, Math.round(Number(c.fps) || 30))),
757
+ durationInFrames: Math.max(1, Math.min(1_000_000, Math.round(Number(c.durationInFrames) || 1))),
758
+ width: Math.max(1, Math.round(Number(c.width) || 0)),
759
+ height: Math.max(1, Math.round(Number(c.height) || 0)),
760
+ // The enclosing artboard (issue #75) — the key the transport target
761
+ // is resolved on, and (the label) shell chrome the user reads. This
762
+ // is untrusted canvas-origin text, so neutralize the bidi/zero-width
763
+ // class HERE, at the boundary, and every downstream consumer
764
+ // inherits a clean value (security-review 2026-08-12).
765
+ artboardId: sanitizeArtboardText(c.artboardId),
766
+ artboardLabel: sanitizeArtboardText(c.artboardLabel),
767
+ }));
768
+ setActiveComps(safe);
769
+ // rca/issue-video-artboard-frame-reset-on-edit — the SAME comp
770
+ // re-announcing means its Player just remounted (an edit-triggered
771
+ // HMR remount, or a ⌘R hard iframe reload that wiped video-comp.tsx's
772
+ // own module-scope frame mirror too). The shell's `timelineFrame`
773
+ // survives either way (this component doesn't remount) — push it back
774
+ // down so the fresh Player opens where the Timeline left off, instead
775
+ // of the poster-frame default. Skip on a genuinely new comp/canvas
776
+ // (no prior id, or frame still at its post-switch 0).
777
+ const prevCompId = timelineCompIdRef.current;
778
+ const stillPresent = prevCompId && safe.some((c) => c.id === prevCompId);
779
+ if (stillPresent && timelineFrameRef.current > 0) {
780
+ postToActiveCanvas({
781
+ dgn: 'timeline-seek',
782
+ frame: timelineFrameRef.current,
783
+ id: prevCompId,
784
+ });
785
+ }
786
+ } else if (m.dgn === 'timeline-frame' && typeof m.frame === 'number') {
787
+ // Live playhead mirror from the Player (preview scrub/playback).
788
+ const activeWin =
789
+ activePath && activePath !== SYSTEM_TAB
790
+ ? iframesRef.current.get(activePath)?.contentWindow
791
+ : null;
792
+ if (e.source !== activeWin) return;
793
+ // Only the Timeline's target comp drives the playhead — a sibling
794
+ // artboard's Player must not fight it for the readout (multi-comp canvas).
795
+ if (m.id && timelineCompIdRef.current && m.id !== timelineCompIdRef.current) return;
796
+ if (Number.isFinite(m.frame)) setTimelineFrame(Math.max(0, Math.round(m.frame)));
797
+ } else if (m.dgn === 'timeline-ended') {
798
+ // The Player stopped itself at the last frame (loop off) — resync the
799
+ // shell's Play/Pause button, which otherwise has no way to learn
800
+ // playback ended on its own (rca/issue-video-artboard-loop-defaults-on).
801
+ const activeWin =
802
+ activePath && activePath !== SYSTEM_TAB
803
+ ? iframesRef.current.get(activePath)?.contentWindow
804
+ : null;
805
+ if (e.source !== activeWin) return;
806
+ if (m.id && timelineCompIdRef.current && m.id !== timelineCompIdRef.current) return;
807
+ setTimelinePlaying(false);
808
+ } else if (m.dgn === 'toggle-palette') {
809
+ // ⌘K pressed while focus was inside the canvas iframe — the injected
810
+ // inspector forwards the chord here since the iframe's keydown never
811
+ // reaches the shell's window listener. Mirror that handler's toggle.
812
+ //
813
+ // SECURITY (V2-2.8 S3) — the same `activeWin` gate as `shell-shortcut`
814
+ // below: the chord is pressed inside the canvas in view, so a
815
+ // background/synced canvas (DDR-054) must not pop the palette on demand.
816
+ // `activeWin &&` closes the `null === null` path (no active canvas + a
817
+ // discarded source) the comment relays above document.
818
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
819
+ if (activeWin && e.source === activeWin) setPaletteOpen((v) => !v);
820
+ } else if (m.dgn === 'shell-shortcut') {
821
+ // Same forwarding lane for the other shell chords (inspect.ts) — so
822
+ // ⌘R / ⌘⇧I / ⌘⇧M / ⌘⇧E / ⌘⇧H behave identically wherever focus is.
823
+ //
824
+ // SECURITY — every one of these is a chord the user pressed INSIDE the
825
+ // canvas they are looking at, so it gets the same `activeWin` gate as
826
+ // its siblings. Ungated, a background canvas could reload the active
827
+ // file out from under an edit or pop the Export/Handoff dialog on
828
+ // demand — a modal-timing primitive, and the mirror image of the
829
+ // present-enter branch that was already hardened against modal HIDING.
830
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
831
+ if (e.source === activeWin) {
832
+ if (m.id === 'reload') reloadActive();
833
+ else if (m.id === 'inspector') toggleRightPanel('inspector');
834
+ else if (m.id === 'assistant' && isNativeApp()) toggleRightPanel('assistant');
835
+ else if (m.id === 'comments') toggleRightPanel('comments');
836
+ else if (m.id === 'changes') toggleRightPanel('changes');
837
+ else if (m.id === 'timeline') toggleTimeline();
838
+ else if (m.id === 'export') setExportDialog({ mode: 'export' });
839
+ else if (m.id === 'handoff') setExportDialog({ mode: 'handoff' });
840
+ }
841
+ } else if (m.dgn === 'open-export') {
842
+ // Plan C — the in-canvas toolbar / context menu route here so they open
843
+ // the SAME shell Export dialog as the menubar (one look, all settings).
844
+ // Carry the context-menu's scope hint (e.g. "Export selection").
845
+ //
846
+ // SECURITY — gated with `shell-shortcut` above rather than separately:
847
+ // both reach the same `setExportDialog`, so leaving this one open would
848
+ // hand back the capability the other now refuses.
849
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
850
+ if (e.source === activeWin) {
851
+ setExportDialog({
852
+ mode: 'export',
853
+ scope: m.detail && typeof m.detail.scope === 'string' ? m.detail.scope : undefined,
854
+ });
855
+ }
856
+ } else if (m.dgn === 'open-timeline-request') {
857
+ // Artboard-chrome context menu's "Open Timeline" (video-comp artboards
858
+ // only). Scope the Timeline to the right-clicked artboard, then open it.
859
+ // SECURITY — same class: a context-menu action from the canvas in view.
860
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
861
+ if (e.source === activeWin) {
862
+ if (typeof m.artboardId === 'string') setCanvasActiveArtboard(m.artboardId.slice(0, 120));
863
+ setTimelineOpen(true);
864
+ }
865
+ } else if ((m.dgn === 'canvas-rendered' || m.dgn === 'canvas-failed') && m.file) {
866
+ // The canvas drew (or its shell is now showing its own build error) —
867
+ // only now drop the loading screen. See `loaded` below for why that
868
+ // one is not enough. Only from the frame IN VIEW, like every branch
869
+ // that changes what the user sees (review F5).
870
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
871
+ if (e.source === activeWin) setLoadingPath((p) => (p === m.file ? null : p));
872
+ } else if (m.dgn === 'loaded' && m.file) {
873
+ // The shell document ran — push current comments + carry over the
874
+ // focused pin. For a TSX/JSX canvas this is NOT "drawn": the module
875
+ // still has to build and render, which on a cold cloud canvas takes
876
+ // seconds, and dropping the loading screen here showed a white pane
877
+ // with bare comment pins. Those canvases clear it on `canvas-rendered`
878
+ // / `canvas-failed`; a legacy .html canvas has nothing to wait for.
879
+ if (!isModuleCanvasPath(m.file)) setLoadingPath((p) => (p === m.file ? null : p));
880
+ setLoadedPath(m.file);
881
+ // …and retire any #115 error panel for this canvas: it just proved it
882
+ // can load (a late load, or a successful Retry).
883
+ setCanvasError((e) => (e && e.path === m.file ? null : e));
884
+ // Presentation Mode suppresses comment pins (same gate as the push
885
+ // effect above), so a canvas opened while presenting starts pin-free.
886
+ const list = presentMode ? [] : commentsByFile[m.file] || [];
887
+ const el = [...iframesRef.current.entries()].find(([k]) => k === m.file)?.[1];
888
+ if (el && el.contentWindow) {
889
+ try {
890
+ el.contentWindow.postMessage({ dgn: 'comments-set', comments: list }, '*');
891
+ } catch {}
892
+ // System-review D9 — seed the just-loaded canvas with the current
893
+ // chrome theme so a canvas opened AFTER a theme toggle starts
894
+ // correct (no flash from the dark default).
895
+ try {
896
+ el.contentWindow.postMessage({ dgn: 'theme', theme }, '*');
897
+ } catch {}
898
+ // Seed the just-loaded canvas with the current chrome-visibility
899
+ // state (minimap / zoom-controls toggles + Presentation Mode) so a
900
+ // canvas opened after a toggle starts in the right state.
901
+ try {
902
+ el.contentWindow.postMessage(
903
+ { dgn: 'view-chrome', minimap: minimapVisible, zoom: zoomCtlVisible, present: presentMode },
904
+ '*'
905
+ );
906
+ } catch {}
907
+ if (focusedCommentId && list.some((c) => c.id === focusedCommentId)) {
908
+ try {
909
+ el.contentWindow.postMessage({ dgn: 'comment-focus', id: focusedCommentId }, '*');
910
+ } catch {}
911
+ }
912
+ // Phase 12.1 (DDR-138) — a reorder just wrote source: the moved
913
+ // element's positional data-cd-id renumbered, so re-selecting by the
914
+ // PRE-move id would land on the wrong node. Re-select by the recomputed
915
+ // movedId instead (null ⇒ leave selection to the user, never guess), and
916
+ // rebuild the layers tree so the panel reflects the new order.
917
+ const pend = pendingReorderRef.current;
918
+ if (pend && pend.file === m.file) {
919
+ pendingReorderRef.current = null;
920
+ try {
921
+ el.contentWindow.postMessage(
922
+ { dgn: 'request-layers', artboardId: pend.artboardId ?? null },
923
+ '*'
924
+ );
925
+ } catch {}
926
+ if (pend.movedId) {
927
+ try {
928
+ el.contentWindow.postMessage(
929
+ {
930
+ dgn: 'select-by-id',
931
+ id: pend.movedId,
932
+ artboardId: pend.artboardId ?? null,
933
+ index: 0,
934
+ },
935
+ '*'
936
+ );
937
+ } catch {}
938
+ }
939
+ } else {
940
+ // Phase 12.3 (W1.1) — an edit-css/edit-attr commit triggers the file
941
+ // watcher's HMR reload, which remounts the canvas and drops the
942
+ // in-canvas selection halo. Re-select the same element by its stable
943
+ // data-cd-id so the user keeps focus on what they're editing. The
944
+ // canvas-shell `select-by-id` handler re-emits select-set, which keeps
945
+ // the Inspector panel + halo in sync. Guarded to the active file.
946
+ // Retry-laddered: dgn:'loaded' fires from the inline inspector script
947
+ // BEFORE the React canvas-shell mounts its listener, so a one-shot
948
+ // post is lost on fresh iframes (canvas-switch restore case).
949
+ const sel0 = selectedRef.current;
950
+ const sel = Array.isArray(sel0) ? sel0[0] : sel0;
951
+ if (sel && sel.id && sel.file === m.file) {
952
+ scheduleHaloRestore(sel);
953
+ }
954
+ }
955
+ }
956
+ } else if (m.dgn === 'export-request' && m.id && m.payload) {
957
+ // The export dialog renders inside the canvas iframe (canvas origin),
958
+ // but /_api/export is a privileged MAIN-origin endpoint deliberately
959
+ // kept off the canvas allowlist (DDR-060). A direct in-iframe fetch
960
+ // therefore 403s ("Forbidden (canvas origin)"). Bridge it: run the
961
+ // export here on the trusted main origin, stream the download, and
962
+ // report status back to the iframe. Origin is already validated
963
+ // (e.origin === expectedOrigin) above, so only the real canvas iframe
964
+ // can ask — this is NOT a generic fetch proxy.
965
+ //
966
+ // DDR-231 security (M1): additionally require the request come from the
967
+ // ACTIVE canvas — captureFromCanvas + the browser-lane branch capture
968
+ // and auto-download `activePath`'s pixels regardless of who asked, so
969
+ // WITHOUT this gate a background (untrusted, DDR-054) same-origin canvas
970
+ // could `postMessage({dgn:'export-request'})` with no user gesture and
971
+ // force a silent download of whatever the user is currently looking at.
972
+ // Same one-liner every sibling mutating branch already uses.
973
+ const activeWin = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
974
+ if (e.source !== activeWin) return;
975
+ void runBridgedExport(e.source, m.id, m.payload);
976
+ } else if (m.dgn === 'export-history-request' && m.id) {
977
+ // Same bridge for the dialog's Recent tab (/_api/export-history is
978
+ // also main-origin-only).
979
+ void runBridgedHistory(e.source, m.id);
980
+ }
981
+ }
982
+ // Reply target for the export bridge: the canvas iframe's own origin.
983
+ const replyOrigin = cfg?.canvasOrigin || window.location.origin;
984
+ async function runBridgedExport(source, id, payload) {
985
+ // The in-canvas dialog exports the canvas it LIVES IN — which the M1
986
+ // gate above just proved is `activePath`. Stamp it so scope resolution
987
+ // never falls back to the server's (asynchronously written, possibly
988
+ // stale) `_active.json` — same rule as the shell dialog's canvasFile.
989
+ // OVERWRITE, not fill-if-absent: the M1 gate above proved the sender IS
990
+ // the active canvas iframe (untrusted, DDR-054), so a canvasFile IT
991
+ // supplied must not survive — the bridged export renders the canvas it
992
+ // lives in, full stop (security review W2).
993
+ if (payload?.options && activePath && activePath !== SYSTEM_TAB) {
994
+ payload.options.canvasFile = activePath;
995
+ }
996
+ const reply = (msg) => {
997
+ try {
998
+ if (source) source.postMessage({ dgn: 'export-result', id, ...msg }, replyOrigin);
999
+ } catch {}
1000
+ };
1001
+ // DDR-231 — the browser lane, mirrored for the IN-CANVAS dialog: png/svg
1002
+ // of a known artboard is captured by the asking canvas itself (the shell
1003
+ // relays the request back over the export-capture bridge and downloads
1004
+ // the blobs — the sandboxed iframe can't download, the shell can).
1005
+ const opts = payload?.options || {};
1006
+ const bridgedBrowserEligible = browserCaptureEligible({
1007
+ exportLane: cfg.exportLane || 'local',
1008
+ format: payload?.format,
1009
+ scope: payload?.scope,
1010
+ artboardId: opts.artboardId,
1011
+ });
1012
+ if (bridgedBrowserEligible) {
1013
+ try {
1014
+ if (payload.format === 'pptx') {
1015
+ const { filename, blob } = await captureDeckViaBrowser({
1016
+ capture: captureFromCanvas,
1017
+ name: activePath ? activePath.replace(/^.*\//, '').replace(/\.[^.]+$/, '') : 'export',
1018
+ });
1019
+ downloadCapturedBlob(filename, blob);
1020
+ } else {
1021
+ const capScale = captureScale(opts);
1022
+ const items = await captureFromCanvas({
1023
+ format: payload.format,
1024
+ artboardIds: [opts.artboardId],
1025
+ scale: capScale,
1026
+ });
1027
+ const safeItems = await sanitizeCapturedItems(items, payload.format);
1028
+ for (const it of safeItems) downloadCapturedBlob(it.name, it.blob);
1029
+ }
1030
+ reply({ ok: true, browser: true });
1031
+ return;
1032
+ } catch {
1033
+ if (cfg.exportLane !== 'remote') {
1034
+ reply({
1035
+ ok: false,
1036
+ error:
1037
+ 'Capturing in the browser failed and this workspace has no render service to fall back to — try again, or ask your admin to add maude-render.',
1038
+ });
1039
+ return;
1040
+ }
1041
+ // Render service available — degrade to the jobs lane below.
1042
+ }
1043
+ }
1044
+ // feature-cloud-export-render-workers — a workspace with no render
1045
+ // service can't produce browser-rendered formats; answer the in-canvas
1046
+ // dialog with the reason instead of relaying a request the proxy 404s.
1047
+ // ZIP (and any browser-free format) still goes through.
1048
+ if (cfg.exportLane === 'none' && payload?.format !== 'zip') {
1049
+ reply({
1050
+ ok: false,
1051
+ error:
1052
+ 'This format needs the render service, which this workspace doesn’t have configured. PNG/SVG of the active artboard and the PPTX deck export straight from the browser; ZIP works too. For the rest use the desktop app or ask your admin to add maude-render.',
1053
+ });
1054
+ return;
1055
+ }
1056
+ try {
1057
+ // feature-background-export-notification-center — enqueue and reply
1058
+ // with the job id immediately; the notification center (which
1059
+ // already owns the WS connection) is the single place status/
1060
+ // progress/completion live from here, regardless of which dialog
1061
+ // created the job.
1062
+ const r = await fetch('/_api/export-jobs', {
1063
+ method: 'POST',
1064
+ headers: { 'content-type': 'application/json' },
1065
+ body: JSON.stringify(payload),
1066
+ });
1067
+ if (!r.ok) {
1068
+ reply({ ok: false, error: (await r.text()) || String(r.status) });
1069
+ return;
1070
+ }
1071
+ const { jobId } = await r.json();
1072
+ reply({ ok: true, jobId });
1073
+ } catch (err) {
1074
+ reply({ ok: false, error: err && err.message ? err.message : String(err) });
1075
+ }
1076
+ }
1077
+ async function runBridgedHistory(source, id) {
1078
+ let history = [];
1079
+ try {
1080
+ const r = await fetch('/_api/export-history');
1081
+ if (r.ok) {
1082
+ const data = await r.json();
1083
+ if (Array.isArray(data.history)) history = data.history;
1084
+ }
1085
+ } catch {
1086
+ /* best-effort — empty list */
1087
+ }
1088
+ try {
1089
+ if (source) source.postMessage({ dgn: 'export-history-result', id, history }, replyOrigin);
1090
+ } catch {}
1091
+ }
1092
+ window.addEventListener('message', onMessage);
1093
+ return () => window.removeEventListener('message', onMessage);
1094
+ }, [
1095
+ commentsByFile,
1096
+ focusedCommentId,
1097
+ cfg,
1098
+ theme,
1099
+ reloadActive,
1100
+ presentMode,
1101
+ minimapVisible,
1102
+ zoomCtlVisible,
1103
+ broadcastChrome,
1104
+ activePath,
1105
+ postToActiveCanvas,
1106
+ captureFromCanvas,
1107
+ ]);
1108
+
1109
+ // Tell the active canvas iframe to drop any persistent selection (canvas
1110
+ // SelectionSet) — used when the comment composer closes via submit /
1111
+ // cancel / Esc. canvas-shell listens for `force-clear` on the window
1112
+ // message channel and calls selSet.clear().
1113
+ const clearActiveCanvasSelection = useCallback(() => {
1114
+ if (!activePath || activePath === SYSTEM_TAB) return;
1115
+ const el = iframesRef.current.get(activePath);
1116
+ if (el && el.contentWindow) {
1117
+ try {
1118
+ el.contentWindow.postMessage({ dgn: 'force-clear' }, '*');
1119
+ } catch {}
1120
+ }
1121
+ }, [activePath]);
1122
+
1123
+ // Phase 12.3 (W1.1) — optimistic inline-style preview. The CSS panel calls this
1124
+ // on commit so the selected element updates instantly in the canvas before the
1125
+ // edit-css → HMR reload lands. `value` null = the reset path (remove the prop).
1126
+ const applyOptimisticStyle = useCallback(
1127
+ (payload) => {
1128
+ if (!activePath || activePath === SYSTEM_TAB) return;
1129
+ const el = iframesRef.current.get(activePath);
1130
+ if (el && el.contentWindow) {
1131
+ try {
1132
+ el.contentWindow.postMessage({ dgn: 'apply-style', ...payload }, '*');
1133
+ } catch {}
1134
+ }
1135
+ },
1136
+ [activePath]
1137
+ );
1138
+
1139
+ // Inline-edit undo (DDR-103/104 follow-up). The inspector calls this after it
1140
+ // POSTs `/_api/edit-css` / `/_api/edit-attr`, so the canvas iframe records the
1141
+ // edit on its undo stack and Cmd+Z can invert it. The iframe gates this to
1142
+ // parent-origin posts (DDR-054). See `commands/edit-source-command.ts`.
1143
+ const recordSourceEdit = useCallback(
1144
+ (payload) => {
1145
+ if (!activePath || activePath === SYSTEM_TAB || !payload) return;
1146
+ const el = iframesRef.current.get(activePath);
1147
+ if (el && el.contentWindow) {
1148
+ try {
1149
+ el.contentWindow.postMessage({ dgn: 'record-edit', payload }, '*');
1150
+ } catch {}
1151
+ }
1152
+ },
1153
+ [activePath]
1154
+ );
1155
+
1156
+ // Serializes `apply-edit` source writes from canvas undo/redo so a rapid
1157
+ // multi-Cmd+Z on the same property lands on disk in dispatch order (the
1158
+ // iframe sink is fire-and-forget, so without this the POSTs could race).
1159
+ const editApplyChainRef = useRef(Promise.resolve());
1160
+
1161
+ // Phase 12.1 (DDR-138) — commit a Layers-panel drag/keyboard reorder. The shell
1162
+ // is main-origin, so it calls the privileged /_api/reorder directly (the CSS/
1163
+ // text edits go the other way — canvas requests, shell writes; here the gesture
1164
+ // originates in the shell). Serialized on the same chain as apply-edit so a
1165
+ // reorder can't race an in-flight edit write to the same file.
1166
+ const reorderLayer = useCallback(
1167
+ (draggedId, refId, position, occ) => {
1168
+ const idIndex = Number.isInteger(occ?.idIndex) ? occ.idIndex : undefined;
1169
+ const refIndex = Number.isInteger(occ?.refIndex) ? occ.refIndex : undefined;
1170
+ // A same-id move is valid for two INSTANCES of a reused component (distinct
1171
+ // occurrence indices → distinct usages); only a true self-move is a no-op.
1172
+ if (!draggedId || !refId) return;
1173
+ if (draggedId === refId && (idIndex ?? 0) === (refIndex ?? 0)) return;
1174
+ const sel = selectedRef.current;
1175
+ const one = Array.isArray(sel) ? sel[0] : sel;
1176
+ // SECURITY (DDR-139 / adversarial F1): a reorder ALWAYS applies to the
1177
+ // ACTIVE canvas — both the in-canvas drag and the Layers panel operate on
1178
+ // what the user is viewing. Pin the target to `activePath`; never derive it
1179
+ // from `selection.canvas`, which an untrusted iframe can spoof (an ungated
1180
+ // dgn:'select' followed by dgn:'reorder-request') to retarget the write to
1181
+ // a DIFFERENT canvas (confused deputy, breaks DDR-054/DDR-138 containment).
1182
+ const canvas = activePath;
1183
+ if (!canvas) return;
1184
+ const file = activePath;
1185
+ const artboardId = layersTree?.artboardId ?? one?.artboardId ?? null;
1186
+ // Optimistically reorder the layers tree so the panel reflects the move
1187
+ // instantly; the HMR rebuild (request-layers, dgn:'loaded') confirms it a
1188
+ // beat later. Ids here are distinct (repeated/list nodes are non-draggable).
1189
+ setLayersTree((prev) =>
1190
+ prev ? { ...prev, nodes: moveLayerNode(prev.nodes, draggedId, refId, position) } : prev
1191
+ );
1192
+ // Gate the next layers-panel drag until the rebuilt tree lands — the write
1193
+ // churns positional ids, so a rapid 2nd drag on the optimistic tree would
1194
+ // carry stale ids. Cleared by the incoming layers-tree message, with a
1195
+ // hard timeout fallback so the list can NEVER stay frozen if that message
1196
+ // doesn't arrive (a no-op reorder, no HMR, etc.).
1197
+ layersBusyRef.current = true;
1198
+ if (layersBusyTimerRef.current) clearTimeout(layersBusyTimerRef.current);
1199
+ layersBusyTimerRef.current = setTimeout(() => {
1200
+ layersBusyRef.current = false;
1201
+ layersBusyTimerRef.current = null;
1202
+ }, 700);
1203
+ editApplyChainRef.current = editApplyChainRef.current
1204
+ .catch(() => {})
1205
+ .then(() =>
1206
+ fetch('/_api/reorder', {
1207
+ method: 'POST',
1208
+ headers: { 'content-type': 'application/json' },
1209
+ body: JSON.stringify({ canvas, id: draggedId, refId, position, idIndex, refIndex }),
1210
+ })
1211
+ .then((r) => r.json().catch(() => ({})))
1212
+ .then((j) => {
1213
+ if (!j.ok) {
1214
+ console.warn('[reorder]', j.error || 'failed');
1215
+ // The move was REJECTED (e.g. a .map()ed/looped element, or a
1216
+ // reparent that would break the JSX) — but the canvas already
1217
+ // applied it optimistically (applyDrop) and the layers panel via
1218
+ // moveLayerNode. Nothing was written, so without a revert the user
1219
+ // sees a phantom change that vanishes on the next canvas switch
1220
+ // ("it didn't save") and Cmd+Z has no entry to undo. Tell the
1221
+ // canvas to put the node back; its observer re-posts the tree, so
1222
+ // the panel reverts too. For a LAYERS-panel reorder (no canvas DOM
1223
+ // move to observe) also re-request the tree to drop the optimistic
1224
+ // moveLayerNode.
1225
+ postToActiveCanvas({ dgn: 'reorder-failed' });
1226
+ postToActiveCanvas({ dgn: 'request-layers', artboardId });
1227
+ layersBusyRef.current = false;
1228
+ if (layersBusyTimerRef.current) {
1229
+ clearTimeout(layersBusyTimerRef.current);
1230
+ layersBusyTimerRef.current = null;
1231
+ }
1232
+ return;
1233
+ }
1234
+ // The write triggers an HMR reload; the dgn:'loaded' handler
1235
+ // re-selects the moved element by its recomputed id + rebuilds the
1236
+ // tree. movedId is best-effort — null means "leave selection to the
1237
+ // user" (never re-select by the stale pre-move id).
1238
+ pendingReorderRef.current = { file, movedId: j.movedId || null, artboardId };
1239
+ // Record onto the canvas undo stack so Cmd+Z reverts the move via
1240
+ // the server's reorder log (id-churn-proof whole-file swap).
1241
+ if (typeof j.seq === 'number') {
1242
+ postToActiveCanvas({
1243
+ dgn: 'record-edit',
1244
+ payload: { op: 'reorder', canvas, seq: j.seq, label: 'move element' },
1245
+ });
1246
+ }
1247
+ })
1248
+ .catch(() => {})
1249
+ );
1250
+ },
1251
+ [activePath, layersTree, postToActiveCanvas]
1252
+ );
1253
+ // Keep the ref the (stale-closure) onMessage reorder-request handler reads
1254
+ // pointed at the latest reorderLayer.
1255
+ useEffect(() => {
1256
+ reorderLayerRef.current = reorderLayer;
1257
+ }, [reorderLayer]);
1258
+
1259
+ // Commit an in-canvas coordinate-mode drag (out-of-flow element: absolute/
1260
+ // fixed) as two sequential single-property writes through the SAME
1261
+ // main-origin endpoint the CSS panel already uses (`/_api/edit-css`, Phase
1262
+ // 12 / DDR-103) — no new write surface. `editStyleProp` upserts into the
1263
+ // existing `style={{}}` object, so the second call (top) lands next to the
1264
+ // first (left) rather than clobbering it. Serialized on the shared
1265
+ // apply-edit chain so it can't race an in-flight write to the same file.
1266
+ const repositionElement = useCallback(
1267
+ (id, left, top, beforeLeft, beforeTop, idIndex) => {
1268
+ if (!id || !activePath) return;
1269
+ const canvas = activePath;
1270
+ // Stage H3 — when the dragged target is a whole component INSTANCE the canvas
1271
+ // passes its DOM-occurrence index; the server routes the left/top write to
1272
+ // that instance's own `<Component/>` usage so moving one instance stays local.
1273
+ const occ = Number.isInteger(idIndex) ? idIndex : undefined;
1274
+ // INV-2 (DDR-105) — arm the reload-suppression window BEFORE the edit-css
1275
+ // writes so the HMR reload is skipped and the canvas doesn't remount + drop
1276
+ // the selection (dogfood: "když pohnu elementem myší, ztratím focus"). Same
1277
+ // fix as resizeElement; also covers the keyboard nudge (L1) which reuses this.
1278
+ applyOptimisticStyle({ id, prop: 'left', value: `${left}px` });
1279
+ applyOptimisticStyle({ id, prop: 'top', value: `${top}px` });
1280
+ let j1ref = null;
1281
+ const writeProp = (property, value) =>
1282
+ fetch('/_api/edit-css', {
1283
+ method: 'POST',
1284
+ headers: { 'content-type': 'application/json' },
1285
+ body: JSON.stringify({ canvas, id, property, value: `${value}px`, idIndex: occ }),
1286
+ }).then((r) => r.json().catch(() => ({})));
1287
+ editApplyChainRef.current = editApplyChainRef.current
1288
+ .catch(() => {})
1289
+ .then(() => writeProp('left', left))
1290
+ .then((j1) => {
1291
+ if (!j1.ok) throw new Error(j1.error || 'left write failed');
1292
+ j1ref = j1;
1293
+ return writeProp('top', top);
1294
+ })
1295
+ .then((j2) => {
1296
+ if (!j2.ok) throw new Error(j2.error || 'top write failed');
1297
+ // Record BOTH properties onto the canvas undo stack — two Cmd+Z
1298
+ // steps (top, then left), same as committing two CSS knobs by hand.
1299
+ recordSourceEdit({
1300
+ op: 'css',
1301
+ canvas,
1302
+ id,
1303
+ key: 'left',
1304
+ before: replacedValue(j1ref, `${beforeLeft}px`),
1305
+ after: `${left}px`,
1306
+ });
1307
+ recordSourceEdit({
1308
+ op: 'css',
1309
+ canvas,
1310
+ id,
1311
+ key: 'top',
1312
+ before: replacedValue(j2, `${beforeTop}px`),
1313
+ after: `${top}px`,
1314
+ });
1315
+ })
1316
+ .catch((err) => {
1317
+ console.warn('[reposition]', err?.message || err);
1318
+ // Nothing (or only `left`) persisted — tell the canvas to restore
1319
+ // the pre-drag inline style so a phantom move doesn't linger.
1320
+ postToActiveCanvas({ dgn: 'reposition-failed' });
1321
+ });
1322
+ },
1323
+ [activePath, postToActiveCanvas, recordSourceEdit, applyOptimisticStyle]
1324
+ );
1325
+ useEffect(() => {
1326
+ repositionElementRef.current = repositionElement;
1327
+ }, [repositionElement]);
1328
+
1329
+ // feature-element-editing-robustness Stage D (Task D3) — commit an in-canvas
1330
+ // drag-resize. `patch` = { width, height, left?, top? } (px strings); left/top
1331
+ // are present only for a top/left-edge drag on an out-of-flow element. Writes
1332
+ // each present property through the SAME main-origin `/_api/edit-css` endpoint
1333
+ // the CSS panel + reposition use (no new write surface), serialized on the
1334
+ // shared apply-edit chain, and records one undo entry per property (as
1335
+ // reposition records left+top). Pinned to `activePath` (never `m.canvas`) —
1336
+ // the confused-deputy guard DDR-138/DDR-054 established for reorder/reposition.
1337
+ const resizeElement = useCallback(
1338
+ (id, patch, before, idIndex) => {
1339
+ if (!id || !activePath || !patch || typeof patch !== 'object') return;
1340
+ const canvas = activePath;
1341
+ const b = before && typeof before === 'object' ? before : {};
1342
+ // Stage H3 — a whole-instance resize carries its DOM-occurrence index so the
1343
+ // width/height/left/top write lands on that instance's own `<Component/>`
1344
+ // usage (local), not the shared inner definition. undefined for a plain element.
1345
+ const occ = Number.isInteger(idIndex) ? idIndex : undefined;
1346
+ // `transform` rides the same lane for the rotate handle (Task L8);
1347
+ // `padding-*`/`gap` ride it for the on-canvas spacing drag (Stage J);
1348
+ // `grid-template-columns`/`grid-template-rows` ride it for the on-canvas
1349
+ // grid gutter drag (feature-3-web-artboards T5) — same single-prop
1350
+ // /_api/edit-css write + per-prop undo record, no new lane.
1351
+ const props = [
1352
+ 'width',
1353
+ 'height',
1354
+ 'left',
1355
+ 'top',
1356
+ 'transform',
1357
+ 'padding-top',
1358
+ 'padding-right',
1359
+ 'padding-bottom',
1360
+ 'padding-left',
1361
+ 'gap',
1362
+ 'grid-template-columns',
1363
+ 'grid-template-rows',
1364
+ ].filter((p) => typeof patch[p] === 'string' && patch[p]);
1365
+ if (!props.length) return;
1366
+ // Dogfood 2026-07-07 — "resize paddingu nebo gap" was still deselecting on
1367
+ // completion. `applyOptimisticStyle` was posting {id, prop, value} only —
1368
+ // missing artboardId/index — so the canvas-side `apply-style` handler
1369
+ // resolved the UNSCOPED `[data-cd-id]` selector (dom-selection.ts
1370
+ // `resolveSelectionEl`/`scopedCdSelector`), which is a latent multi-
1371
+ // artboard/reused-component miss. Pull the current selection's own
1372
+ // artboardId/index (when it matches `id`) so every optimistic apply +
1373
+ // the belt-and-suspenders reselect below target the SAME instance.
1374
+ const curSel = selectedRef.current;
1375
+ const curOne = Array.isArray(curSel)
1376
+ ? curSel.length === 1
1377
+ ? curSel[0]
1378
+ : null
1379
+ : curSel;
1380
+ const selArtboardId = curOne && curOne.id === id ? (curOne.artboardId ?? null) : null;
1381
+ const selIndex = curOne && curOne.id === id ? (curOne.index ?? 0) : 0;
1382
+ // INV-2 (DDR-105) — arm the reload-suppression window BEFORE the edit-css
1383
+ // writes so the follow-up HMR is skipped. Without this the canvas remounts
1384
+ // and drops the selection (the "resize deselects the element" dogfood bug).
1385
+ for (const p of props) {
1386
+ applyOptimisticStyle({
1387
+ id,
1388
+ artboardId: selArtboardId,
1389
+ index: selIndex,
1390
+ prop: p,
1391
+ value: patch[p],
1392
+ });
1393
+ }
1394
+ const writeProp = (property, value) =>
1395
+ fetch('/_api/edit-css', {
1396
+ method: 'POST',
1397
+ headers: { 'content-type': 'application/json' },
1398
+ body: JSON.stringify({ canvas, id, property, value, idIndex: occ }),
1399
+ }).then((r) => r.json().catch(() => ({})));
1400
+ const replies = {};
1401
+ let chain = editApplyChainRef.current.catch(() => {});
1402
+ for (const p of props) {
1403
+ chain = chain.then((prev) => {
1404
+ if (prev && prev.ok === false) throw new Error(prev.error || `${p} write failed`);
1405
+ return writeProp(p, patch[p]).then((j) => {
1406
+ replies[p] = j;
1407
+ return j;
1408
+ });
1409
+ });
1410
+ }
1411
+ editApplyChainRef.current = chain
1412
+ .then((last) => {
1413
+ if (last && last.ok === false) throw new Error(last.error || 'resize write failed');
1414
+ // Record one undo entry per written property (each Cmd+Z reverts one).
1415
+ for (const p of props) {
1416
+ recordSourceEdit({
1417
+ op: 'css',
1418
+ canvas,
1419
+ id,
1420
+ key: p,
1421
+ before: replacedValue(replies[p], b[p] ?? null),
1422
+ after: patch[p],
1423
+ });
1424
+ }
1425
+ // Dogfood 2026-07-07 — belt-and-suspenders reselect, mirroring the
1426
+ // structural ops' `pendingReorderRef` re-settle. The DDR-105 suppression
1427
+ // window should make this a no-op (no reload → the selection was never
1428
+ // lost) — idempotent per `scheduleHaloRestore`'s own doc comment, so it's
1429
+ // safe to always fire, and it's the backstop if suppression ever misses
1430
+ // (a slow FS-watcher round trip past the 1.5s window, for example).
1431
+ scheduleHaloRestore({ id, file: canvas, artboardId: selArtboardId, index: selIndex });
1432
+ })
1433
+ .catch((err) => {
1434
+ console.warn('[resize]', err?.message || err);
1435
+ // Nothing (or only a prefix) persisted — tell the canvas to restore the
1436
+ // pre-drag inline style so a phantom resize doesn't linger.
1437
+ postToActiveCanvas({ dgn: 'resize-failed' });
1438
+ });
1439
+ },
1440
+ [activePath, postToActiveCanvas, recordSourceEdit, applyOptimisticStyle, scheduleHaloRestore]
1441
+ );
1442
+ useEffect(() => {
1443
+ resizeElementRef.current = resizeElement;
1444
+ }, [resizeElement]);
1445
+
1446
+ // feature-element-editing-robustness Stage I — general element structural edits
1447
+ // (delete / insert element / insert artboard) + Stage D4 (artboard resize).
1448
+ // Each is a main-origin-only write the untrusted canvas can only REQUEST over
1449
+ // the dgn:* bus; the shell performs it, pinned to `activePath` (confused-deputy
1450
+ // guard, DDR-054/138). Undo reuses the reorder command's whole-file seq revert
1451
+ // (record-edit op:'reorder') — a structural edit renumbers positional ids, so an
1452
+ // inverse descriptor goes stale (same reason reorder uses the server seq log).
1453
+ const structuralWriteRef = useRef(null);
1454
+ const structuralWrite = useCallback(
1455
+ (route, body, { label, onOk, onFail: failed } = {}) => {
1456
+ if (!activePath) return;
1457
+ const canvas = activePath;
1458
+ // A refused structural edit used to vanish into the console: the
1459
+ // designer pressed Delete and nothing happened. Say so in the canvas.
1460
+ const onFail =
1461
+ failed ??
1462
+ ((j) =>
1463
+ postToActiveCanvas({
1464
+ dgn: 'op-toast',
1465
+ message: `Couldn't ${label || 'apply the edit'}${j?.error ? ` — ${j.error}` : ''}.`,
1466
+ }));
1467
+ editApplyChainRef.current = editApplyChainRef.current
1468
+ .catch(() => {})
1469
+ .then(() =>
1470
+ fetch(route, {
1471
+ method: 'POST',
1472
+ headers: { 'content-type': 'application/json' },
1473
+ body: JSON.stringify({ ...body, canvas }),
1474
+ })
1475
+ .then((r) => r.json().catch(() => ({})))
1476
+ .then((j) => {
1477
+ if (!j.ok) {
1478
+ console.warn(`[${route}]`, j.error || 'failed');
1479
+ onFail?.(j);
1480
+ return;
1481
+ }
1482
+ if (typeof j.seq === 'number') {
1483
+ postToActiveCanvas({
1484
+ dgn: 'record-edit',
1485
+ payload: { op: 'reorder', canvas, seq: j.seq, label: label || 'edit' },
1486
+ });
1487
+ }
1488
+ onOk?.(j, canvas);
1489
+ })
1490
+ .catch((err) => onFail?.({ error: err?.message }))
1491
+ );
1492
+ },
1493
+ [activePath, postToActiveCanvas]
1494
+ );
1495
+ useEffect(() => {
1496
+ structuralWriteRef.current = structuralWrite;
1497
+ }, [structuralWrite]);
1498
+
1499
+ const deleteElementShell = useCallback(
1500
+ (id, idIndex) => {
1501
+ // After the delete lands + HMR reloads, clear the (now-gone) selection.
1502
+ structuralWrite(
1503
+ '/_api/delete-element',
1504
+ { id, idIndex: Number.isInteger(idIndex) ? idIndex : undefined },
1505
+ { label: 'delete element', onOk: () => postToActiveCanvas({ dgn: 'selection-clear' }) }
1506
+ );
1507
+ },
1508
+ [structuralWrite, postToActiveCanvas]
1509
+ );
1510
+
1511
+ const insertElementShell = useCallback(
1512
+ (refId, position, kind, opts = {}) => {
1513
+ const staleSig = lastLayersTreeRef.current?.sig ?? null;
1514
+ structuralWrite(
1515
+ '/_api/insert-element',
1516
+ {
1517
+ refId,
1518
+ artboardId: typeof opts.artboardId === 'string' ? opts.artboardId : undefined,
1519
+ position,
1520
+ kind,
1521
+ src: typeof opts.src === 'string' ? opts.src : undefined,
1522
+ refIndex: Number.isInteger(opts.refIndex) ? opts.refIndex : undefined,
1523
+ },
1524
+ {
1525
+ label: `insert ${kind}`,
1526
+ // Select the new element once the HMR reload lands (its id is stamped
1527
+ // on transpile — best-effort, like reorder's pendingReorderRef).
1528
+ onOk: (j, canvas) => {
1529
+ if (!j.newId) return;
1530
+ pendingReorderRef.current = { file: canvas, movedId: j.newId, artboardId: null, staleSig };
1531
+ const last = lastLayersTreeRef.current;
1532
+ if (last) settlePendingSelectionRef.current?.(last.tree, last.sig, last.artboardId);
1533
+ },
1534
+ }
1535
+ );
1536
+ },
1537
+ [structuralWrite]
1538
+ );
1539
+
1540
+ // feature-ai-media-generation Phase 1 (Task 1.1) — auto-insert a generated
1541
+ // image onto the canvas where the user is looking, so generation is never a
1542
+ // dead-end modal. The image landed in the content-addressed asset store
1543
+ // (assets/<sha8>.png) via the privileged /_api/generate-jobs route; splice it
1544
+ // into the active artboard through the SAME main-origin source-write lane the
1545
+ // AssetPicker uses (insertElementShell → /_api/insert-element). Returns true
1546
+ // when it placed the image, false when there's no target artboard (no canvas
1547
+ // open / no active artboard) so the caller can fall back to a manual affordance.
1548
+ const insertGeneratedImage = useCallback(
1549
+ (assetPath) => {
1550
+ if (typeof assetPath !== 'string' || !assetPath) return false;
1551
+ if (!activePath) return false;
1552
+ // Respect the active-canvas + selected-artboard signals (_active.json): an
1553
+ // explicit selection wins, else the viewport-active artboard canvas-lib
1554
+ // reports on pan. Without a target artboard we can't source-write.
1555
+ const artboardId = selectedRef.current?.artboardId ?? canvasActiveArtboard ?? null;
1556
+ if (!artboardId) return false;
1557
+ // Insert as the last child of the artboard (empty or not — the engine's
1558
+ // insertElementIntoArtboard handles both). Content-addressed src only; the
1559
+ // route contains an `image` src to assets/ (no remote hotlink / scheme).
1560
+ insertElementShell(undefined, 'inside-end', 'image', { artboardId, src: assetPath });
1561
+ return true;
1562
+ },
1563
+ [activePath, canvasActiveArtboard, insertElementShell]
1564
+ );
1565
+
1566
+ // feature-4 detach-component (2026-07-19) — clone the definition + repoint
1567
+ // this usage so edits stay local to this instance. Rides structuralWrite
1568
+ // (one undo seq); the id churn after HMR invalidates the selection → clear.
1569
+ const detachInstanceShell = useCallback(
1570
+ (id, idIndex) => {
1571
+ structuralWrite(
1572
+ '/_api/detach-component',
1573
+ { id, idIndex: Number.isInteger(idIndex) ? idIndex : undefined },
1574
+ {
1575
+ label: 'detach instance',
1576
+ onOk: (j) => {
1577
+ postToActiveCanvas({ dgn: 'selection-clear' });
1578
+ postToActiveCanvas({
1579
+ dgn: 'op-toast',
1580
+ message: `Detached — this instance is now ${j.detachedName || 'its own component'}; edits stay local (⌘Z to undo).`,
1581
+ });
1582
+ },
1583
+ onFail: (j) =>
1584
+ postToActiveCanvas({
1585
+ dgn: 'op-toast',
1586
+ message: `Detach failed: ${j?.error || 'unknown error'}`,
1587
+ }),
1588
+ }
1589
+ );
1590
+ },
1591
+ [structuralWrite, postToActiveCanvas]
1592
+ );
1593
+
1594
+ const duplicateElementShell = useCallback(
1595
+ (id, idIndex) => {
1596
+ const staleSig = lastLayersTreeRef.current?.sig ?? null;
1597
+ structuralWrite(
1598
+ '/_api/duplicate-element',
1599
+ { id, idIndex: Number.isInteger(idIndex) ? idIndex : undefined },
1600
+ {
1601
+ label: 'duplicate element',
1602
+ // Select the copy once the post-write tree lands — not the pre-write
1603
+ // one, where the copy's id still names the next sibling.
1604
+ onOk: (j, canvas) => {
1605
+ if (!j.newId) return;
1606
+ pendingReorderRef.current = { file: canvas, movedId: j.newId, artboardId: null, staleSig };
1607
+ const last = lastLayersTreeRef.current;
1608
+ if (last) settlePendingSelectionRef.current?.(last.tree, last.sig, last.artboardId);
1609
+ },
1610
+ }
1611
+ );
1612
+ },
1613
+ [structuralWrite]
1614
+ );
1615
+
1616
+ // Task L4 — copy-style / paste-style. Captures a selection's AUTHORED inline
1617
+ // styles (not resolved/computed, so DS-token + inherited values aren't baked in)
1618
+ // minus layout/geometry props, then applies them to another element via chained
1619
+ // edit-css writes (one per prop, like resize — N-step undo). Clipboard lives in
1620
+ // the shell so it survives selection + canvas changes.
1621
+ const copiedStyleRef = useRef(null);
1622
+ // Appearance-only: exclude position/size/margin so paste-style copies the LOOK,
1623
+ // not the layout (Figma parity — padding/color/border/shadow/font/… carry over).
1624
+ const PASTE_STYLE_EXCLUDE = useMemo(
1625
+ () =>
1626
+ new Set([
1627
+ 'position',
1628
+ 'top',
1629
+ 'right',
1630
+ 'bottom',
1631
+ 'left',
1632
+ 'inset',
1633
+ 'width',
1634
+ 'height',
1635
+ 'min-width',
1636
+ 'max-width',
1637
+ 'min-height',
1638
+ 'max-height',
1639
+ 'margin',
1640
+ 'margin-top',
1641
+ 'margin-right',
1642
+ 'margin-bottom',
1643
+ 'margin-left',
1644
+ ]),
1645
+ []
1646
+ );
1647
+ const copyStyle = useCallback(() => {
1648
+ const sel = selectedRef.current;
1649
+ const one = Array.isArray(sel) ? (sel.length === 1 ? sel[0] : null) : sel;
1650
+ if (!one) return;
1651
+ const map = {};
1652
+ for (const [k, v] of Object.entries(one.authored || {})) {
1653
+ if (!PASTE_STYLE_EXCLUDE.has(k)) map[k] = v;
1654
+ }
1655
+ for (const [k, v] of Object.entries(one.customStyles || {})) {
1656
+ if (!PASTE_STYLE_EXCLUDE.has(k)) map[k] = v;
1657
+ }
1658
+ copiedStyleRef.current = Object.keys(map).length ? map : null;
1659
+ }, [PASTE_STYLE_EXCLUDE]);
1660
+ const pasteStyle = useCallback(
1661
+ (id) => {
1662
+ const canvas = activePath;
1663
+ const map = copiedStyleRef.current;
1664
+ if (!canvas || !id || !map) return;
1665
+ const entries = Object.entries(map);
1666
+ let chain = editApplyChainRef.current.catch(() => {});
1667
+ for (const [property, value] of entries) {
1668
+ applyOptimisticStyle({ id, prop: property, value }); // preview + arm no-flicker
1669
+ chain = chain.then(() =>
1670
+ fetch('/_api/edit-css', {
1671
+ method: 'POST',
1672
+ headers: { 'content-type': 'application/json' },
1673
+ body: JSON.stringify({ canvas, id, property, value }),
1674
+ })
1675
+ .then((r) => r.json().catch(() => ({})))
1676
+ .then((j) => {
1677
+ if (j.ok)
1678
+ recordSourceEdit({
1679
+ op: 'css',
1680
+ canvas,
1681
+ id,
1682
+ key: property,
1683
+ before: replacedValue(j, null),
1684
+ after: value,
1685
+ });
1686
+ })
1687
+ .catch(() => {})
1688
+ );
1689
+ }
1690
+ editApplyChainRef.current = chain;
1691
+ },
1692
+ [activePath, applyOptimisticStyle, recordSourceEdit]
1693
+ );
1694
+
1695
+ const insertArtboardShell = useCallback(
1696
+ ({ id, label, width, height }) => {
1697
+ structuralWrite(
1698
+ '/_api/insert-artboard',
1699
+ { id, label, width, height },
1700
+ { label: 'insert artboard' }
1701
+ );
1702
+ },
1703
+ [structuralWrite]
1704
+ );
1705
+
1706
+ const resizeArtboardShell = useCallback(
1707
+ (artboardId, width, height) => {
1708
+ structuralWrite(
1709
+ '/_api/resize-artboard',
1710
+ { artboardId, width, height },
1711
+ {
1712
+ label: 'resize artboard',
1713
+ // Stage D4 — the resize overlay applies a live inline-style preview
1714
+ // during the drag (no HMR yet); on a rejected/failed write, tell it to
1715
+ // restore the pre-drag box so a phantom resize doesn't linger.
1716
+ onFail: () => postToActiveCanvas({ dgn: 'resize-artboard-failed' }),
1717
+ // Dogfood follow-up — resync the Inspector's own W/H (and any other
1718
+ // attrs) once the HMR reload lands, so a paper-preset pick doesn't
1719
+ // leave the fields showing the pre-resize size.
1720
+ onOk: () => scheduleArtboardResync(artboardId, activePath),
1721
+ }
1722
+ );
1723
+ },
1724
+ [structuralWrite, postToActiveCanvas, scheduleArtboardResync, activePath]
1725
+ );
1726
+
1727
+ const deleteArtboardShell = useCallback(
1728
+ (artboardId) => {
1729
+ structuralWrite('/_api/delete-artboard', { artboardId }, { label: 'delete artboard' });
1730
+ },
1731
+ [structuralWrite]
1732
+ );
1733
+
1734
+ // feature-3-web-artboards T3 — "Duplicate at width…". No onOk auto-select
1735
+ // (matches insertArtboardShell's own precedent above — the new frame lands
1736
+ // selectable, not auto-selected).
1737
+ const duplicateArtboardShell = useCallback(
1738
+ (artboardId, width) => {
1739
+ structuralWrite(
1740
+ '/_api/duplicate-artboard',
1741
+ { artboardId, width },
1742
+ { label: 'duplicate artboard at width' }
1743
+ );
1744
+ },
1745
+ [structuralWrite]
1746
+ );
1747
+
1748
+ // Artboard "hug height" default — Hug ⇄ Fixed toggle from ArtboardKnobs
1749
+ // (CSS panel). Direct shell-side action (no canvas postMessage round trip,
1750
+ // unlike resizeArtboardShell's drag-overlay caller), so no *ShellRef needed.
1751
+ const setArtboardHugShell = useCallback(
1752
+ (artboardId, fixed, freezeHeight) => {
1753
+ structuralWrite(
1754
+ '/_api/set-artboard-hug',
1755
+ { artboardId, fixed, freezeHeight },
1756
+ {
1757
+ label: fixed ? 'pin artboard height' : 'hug artboard height',
1758
+ onOk: () => scheduleArtboardResync(artboardId, activePath),
1759
+ }
1760
+ );
1761
+ },
1762
+ [structuralWrite, scheduleArtboardResync, activePath]
1763
+ );
1764
+
1765
+ // Artboard "more settings" (background/padding/layout/gap) from ArtboardKnobs.
1766
+ const setArtboardStyleShell = useCallback(
1767
+ (artboardId, patch) => {
1768
+ structuralWrite('/_api/set-artboard-style', { artboardId, ...patch }, {
1769
+ label: 'artboard style',
1770
+ onOk: () => scheduleArtboardResync(artboardId, activePath),
1771
+ });
1772
+ },
1773
+ [structuralWrite, scheduleArtboardResync, activePath]
1774
+ );
1775
+ // feature-1-artboard-kinds-foundation, T8 — kind-switch surfaces. Direct
1776
+ // callable from ArtboardKnobs (Inspector); the context-menu submenu (inside
1777
+ // the iframe) reaches the SAME endpoint via the postMessage ref below.
1778
+ //
1779
+ // Dogfood follow-up — every one of these ArtboardKnobs writers now resyncs
1780
+ // the Inspector's OWN selection snapshot once the HMR reload lands
1781
+ // (scheduleArtboardResync's retry ladder). Before this fix the ARTBOARD
1782
+ // re-rendered correctly (new kind, new paper size) but the Inspector kept
1783
+ // showing PRE-edit attrs (e.g. "Digital" right after picking "Print",
1784
+ // "Preset size…" still listing screen presets) until the user manually
1785
+ // re-clicked the artboard — structuralWrite's onOk never refreshed
1786
+ // `selected`, only recorded undo history.
1787
+ // feature-4 dogfood round 6 — the DIRECT kind write (+ the Inspector's
1788
+ // print-seed, sequenced AFTER it on the same structuralWrite chain, so a
1789
+ // freeze-convert enqueued just before lands FIRST and the A4 resize can't
1790
+ // move anything pre-freeze). This is what the canvas's
1791
+ // `set-artboard-kind-request` calls — it must NEVER re-enter the ask flow
1792
+ // below (that round-trip was an infinite confirm loop: every "Switch +
1793
+ // freeze" click spawned the next dialog).
1794
+ const pendingPrintSeedRef = useRef(null);
1795
+ const directArtboardKindWrite = useCallback(
1796
+ (artboardId, kind) => {
1797
+ structuralWrite('/_api/set-artboard-kind', { artboardId, kind }, {
1798
+ label: 'artboard kind',
1799
+ onOk: () => scheduleArtboardResync(artboardId, activePath),
1800
+ });
1801
+ const seed = pendingPrintSeedRef.current;
1802
+ if (kind === 'print' && seed && seed.artboardId === artboardId) {
1803
+ pendingPrintSeedRef.current = null;
1804
+ // Same chain → serialized after the kind write (and after any freeze
1805
+ // convert the canvas enqueued before it).
1806
+ structuralWrite(
1807
+ '/_api/resize-artboard',
1808
+ { artboardId, width: seed.widthPx, height: seed.heightPx },
1809
+ { label: 'artboard size' }
1810
+ );
1811
+ structuralWrite(
1812
+ '/_api/set-artboard-print',
1813
+ { artboardId, print: seed.defaults },
1814
+ { label: 'artboard print' }
1815
+ );
1816
+ }
1817
+ },
1818
+ [structuralWrite, scheduleArtboardResync, activePath]
1819
+ );
1820
+ const directArtboardKindWriteRef = useRef(null);
1821
+ useEffect(() => {
1822
+ directArtboardKindWriteRef.current = directArtboardKindWrite;
1823
+ }, [directArtboardKindWrite]);
1824
+
1825
+ const setArtboardKindShell = useCallback(
1826
+ (artboardId, kind, seedPrint) => {
1827
+ // feature-4 (user steer 2026-07-20) — Digital & Print are the freely-
1828
+ // composed marketing kinds: switching TO them from the Inspector offers
1829
+ // the freeze-and-flatten convert first. The confirm runs IN THE CANVAS
1830
+ // (canvasConfirm — the shell's window.confirm is a silent no-op in the
1831
+ // Tauri WKWebView); the canvas then re-posts `set-artboard-kind-request`,
1832
+ // which lands on the DIRECT writer above (no re-entry → no dialog loop).
1833
+ if (kind === 'print' || kind == null || kind === 'digital') {
1834
+ if (seedPrint) pendingPrintSeedRef.current = { artboardId, ...seedPrint };
1835
+ postToActiveCanvas({
1836
+ dgn: 'freeze-and-set-kind',
1837
+ artboardId,
1838
+ kind: kind === 'digital' ? null : kind,
1839
+ ask: true,
1840
+ });
1841
+ return;
1842
+ }
1843
+ directArtboardKindWrite(artboardId, kind);
1844
+ },
1845
+ [directArtboardKindWrite, postToActiveCanvas]
1846
+ );
1847
+ // feature-2-print-artboards T2 — paper/orientation/bleed/margins. Direct
1848
+ // Inspector-only callable (no canvas-origin postMessage path — same shape
1849
+ // as setArtboardStyleShell, unlike setArtboardKindShell which also has a
1850
+ // context-menu caller inside the iframe).
1851
+ const setArtboardPrintShell = useCallback(
1852
+ (artboardId, print) => {
1853
+ structuralWrite('/_api/set-artboard-print', { artboardId, print }, {
1854
+ label: 'artboard print',
1855
+ onOk: () => scheduleArtboardResync(artboardId, activePath),
1856
+ });
1857
+ },
1858
+ [structuralWrite, scheduleArtboardResync, activePath]
1859
+ );
1860
+
1861
+ // Stage I4 — "New artboard: <preset>" from the Edit menu. Generates a unique
1862
+ // id (server 422s a dup, negligible with a random suffix) + a preset label/dims
1863
+ // and inserts an empty <DCArtboard> after the last one (runtime default-grid
1864
+ // places it; DDR-027). The new frame is then selectable + resizable.
1865
+ const onInsertArtboard = useCallback(
1866
+ (presetKey) => {
1867
+ const id = `s${Math.random().toString(36).slice(2, 8)}`;
1868
+ // feature-2-print-artboards T2 — kind="print" + the print prop must
1869
+ // land together, so the created artboard is never a plain digital
1870
+ // board sized to paper by coincidence. structuralWrite serializes
1871
+ // calls in submission order (editApplyChainRef), so these three
1872
+ // sequential POSTs land as insert → kind → print, in order.
1873
+ if (presetKey.startsWith('print-')) {
1874
+ const paper = presetKey.slice('print-'.length);
1875
+ let resolved;
1876
+ try {
1877
+ resolved = resolvePrintArtboard({ paper });
1878
+ } catch {
1879
+ return;
1880
+ }
1881
+ const preset = PAPER_PRESETS.find((p) => p.id === paper);
1882
+ insertArtboardShell({
1883
+ id,
1884
+ label: preset ? preset.label : paper.toUpperCase(),
1885
+ width: resolved.widthPx,
1886
+ height: resolved.heightPx,
1887
+ });
1888
+ setArtboardKindShell(id, 'print');
1889
+ setArtboardPrintShell(id, { paper });
1890
+ return;
1891
+ }
1892
+ const p = SCREEN_PRESETS[presetKey];
1893
+ if (!p) return;
1894
+ insertArtboardShell({ id, label: p.label, width: p.width, height: p.height });
1895
+ },
1896
+ [insertArtboardShell, setArtboardKindShell, setArtboardPrintShell]
1897
+ );
1898
+ // Refs the (stale-closure) onMessage handlers below read.
1899
+ const deleteElementShellRef = useRef(null);
1900
+ const insertElementShellRef = useRef(null);
1901
+ const insertArtboardShellRef = useRef(null);
1902
+ const resizeArtboardShellRef = useRef(null);
1903
+ const deleteArtboardShellRef = useRef(null);
1904
+ const setArtboardKindShellRef = useRef(null);
1905
+ const duplicateElementShellRef = useRef(null);
1906
+ const duplicateArtboardShellRef = useRef(null);
1907
+ const copyStyleRef = useRef(null);
1908
+ const pasteStyleRef = useRef(null);
1909
+ useEffect(() => {
1910
+ deleteElementShellRef.current = deleteElementShell;
1911
+ insertElementShellRef.current = insertElementShell;
1912
+ insertArtboardShellRef.current = insertArtboardShell;
1913
+ resizeArtboardShellRef.current = resizeArtboardShell;
1914
+ deleteArtboardShellRef.current = deleteArtboardShell;
1915
+ setArtboardKindShellRef.current = setArtboardKindShell;
1916
+ duplicateElementShellRef.current = duplicateElementShell;
1917
+ duplicateArtboardShellRef.current = duplicateArtboardShell;
1918
+ copyStyleRef.current = copyStyle;
1919
+ pasteStyleRef.current = pasteStyle;
1920
+ }, [
1921
+ deleteElementShell,
1922
+ insertElementShell,
1923
+ insertArtboardShell,
1924
+ resizeArtboardShell,
1925
+ deleteArtboardShell,
1926
+ setArtboardKindShell,
1927
+ duplicateElementShell,
1928
+ duplicateArtboardShell,
1929
+ copyStyle,
1930
+ pasteStyle,
1931
+ ]);
1932
+
1933
+ // Shell-level Backspace/Delete guard. CRITICAL: in the Tauri desktop app, an
1934
+ // unhandled Backspace triggers WKWebView back-navigation, which reloads the
1935
+ // WHOLE app to "Starting…" (dogfood crash). When an artboard is selected, focus
1936
+ // sits on the shell (not the canvas iframe), so the in-canvas key handler never
1937
+ // sees the keydown — the shell must catch it. Preventing the default here stops
1938
+ // the back-nav universally; if a single artboard is the selection, also delete
1939
+ // it (Backspace parity with the context menu). Element delete stays in the
1940
+ // canvas iframe (which has focus when an element is selected; its keydown never
1941
+ // reaches this window, so there's no double-handling).
1942
+ useEffect(() => {
1943
+ const onKey = (e) => {
1944
+ if (e.key !== 'Backspace' && e.key !== 'Delete') return;
1945
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
1946
+ const t = e.target;
1947
+ const editable =
1948
+ t &&
1949
+ (t.tagName === 'INPUT' ||
1950
+ t.tagName === 'TEXTAREA' ||
1951
+ t.tagName === 'SELECT' ||
1952
+ t.isContentEditable);
1953
+ if (editable) return;
1954
+ // Suppress the WKWebView back-nav unconditionally once focus isn't editable —
1955
+ // the activePath/SYSTEM_TAB check below is app logic, not default-action gating,
1956
+ // so it must not gate preventDefault (that gap caused the desktop "Starting…" hang).
1957
+ e.preventDefault();
1958
+ if (!activePath || activePath === SYSTEM_TAB) return;
1959
+ const one = Array.isArray(selected) ? (selected.length === 1 ? selected[0] : null) : selected;
1960
+ if (one?.artboardId && !one.id) deleteArtboardShell(one.artboardId);
1961
+ };
1962
+ window.addEventListener('keydown', onKey);
1963
+ return () => window.removeEventListener('keydown', onKey);
1964
+ }, [activePath, selected, deleteArtboardShell]);
1965
+
1966
+ // feature-element-editing-robustness Stage F — AssetPicker request. `req` is
1967
+ // { purpose:'insert-image', refId, position, refIndex } (Insert ▸ Image) or
1968
+ // { purpose:'replace-src', id, before } (Media-section "Replace…"). null = closed.
1969
+ const [assetPickerReq, setAssetPickerReq] = useState(null);
1970
+ const openAssetPickerRef = useRef(null);
1971
+ useEffect(() => {
1972
+ openAssetPickerRef.current = (req) => setAssetPickerReq(req);
1973
+ }, []);
1974
+
1975
+ // Phase 4 (whiteboard-improvements) — { canvas: activePath } when open, null
1976
+ // when closed. Mirrors assetPickerReq's ref-indirection (the message
1977
+ // listener below is set up with a minimal dep array, so it reaches a FRESH
1978
+ // opener via a ref rather than needing setStickerPickerReq in its own deps).
1979
+ const [stickerPickerReq, setStickerPickerReq] = useState(null);
1980
+ const openStickerPickerRef = useRef(null);
1981
+ useEffect(() => {
1982
+ openStickerPickerRef.current = (req) => setStickerPickerReq(req);
1983
+ }, []);
1984
+ const onAssetPicked = useCallback(
1985
+ (pickedPath) => {
1986
+ const req = assetPickerReq;
1987
+ setAssetPickerReq(null);
1988
+ if (!req || !pickedPath) return;
1989
+ // G3 security (DDR-152) — the request captured refId/id against the canvas
1990
+ // that was active when the picker opened; if the user switched canvases
1991
+ // while the modal was up, those ids are meaningless (or worse, collide) on
1992
+ // the now-active canvas. Abort rather than write to the wrong file.
1993
+ if (req.canvas && req.canvas !== activePath) {
1994
+ console.warn('[asset-picker] active canvas changed since request — aborting');
1995
+ return;
1996
+ }
1997
+ if (req.purpose === 'insert-image') {
1998
+ insertElementShell(req.refId, req.position || 'after', 'image', {
1999
+ artboardId: req.artboardId,
2000
+ src: pickedPath,
2001
+ refIndex: req.refIndex,
2002
+ });
2003
+ return;
2004
+ }
2005
+ if (req.purpose === 'replace-src') {
2006
+ // Re-point an authored <img>/<video> src via /_api/edit-attr (+ undo).
2007
+ const canvas = activePath;
2008
+ if (!canvas || !req.id) return;
2009
+ editApplyChainRef.current = editApplyChainRef.current
2010
+ .catch(() => {})
2011
+ .then(() =>
2012
+ fetch('/_api/edit-attr', {
2013
+ method: 'POST',
2014
+ headers: { 'content-type': 'application/json' },
2015
+ body: JSON.stringify({ canvas, id: req.id, attr: 'src', value: pickedPath }),
2016
+ })
2017
+ .then((r) => r.json().catch(() => ({})))
2018
+ .then((j) => {
2019
+ if (j.ok) {
2020
+ recordSourceEdit({
2021
+ op: 'attr',
2022
+ canvas,
2023
+ id: req.id,
2024
+ key: 'src',
2025
+ before: replacedValue(j, req.before ?? null),
2026
+ after: pickedPath,
2027
+ });
2028
+ } else {
2029
+ console.warn('[replace-src]', j.error || 'failed');
2030
+ }
2031
+ })
2032
+ .catch(() => {})
2033
+ );
2034
+ return;
2035
+ }
2036
+ if (req.purpose === 'replace-annotation-media') {
2037
+ // Stage F3 — relay the picked path DOWN to the canvas; the annotation
2038
+ // model owns its own strokes + persistence + undo (`commitStrokes`), so
2039
+ // unlike `replace-src` the shell performs no write of its own here.
2040
+ postToActiveCanvas({ dgn: 'replace-annotation-media', id: req.id, path: pickedPath });
2041
+ }
2042
+ },
2043
+ [assetPickerReq, insertElementShell, activePath, recordSourceEdit, postToActiveCanvas]
2044
+ );
2045
+
2046
+ // feature-bulk-media-insert Task 10 — the picker's multi-select confirm.
2047
+ // `destination === 'artboard'`: loop insertElementShell once per path
2048
+ // (already race-safe via editApplyChainRef, no new serialization needed);
2049
+ // always appended `inside-end` of whichever artboard is currently active —
2050
+ // NOT the single-pick request's own refId/position, which only made sense
2051
+ // for inserting exactly one image relative to one anchor. `destination ===
2052
+ // 'annotation'`: one batched message so the canvas-side handler (Task 11)
2053
+ // performs a single atomic commit instead of N racing ones.
2054
+ const onPickMany = useCallback(
2055
+ (paths, destination) => {
2056
+ const req = assetPickerReq;
2057
+ setAssetPickerReq(null);
2058
+ if (!req || !Array.isArray(paths) || !paths.length) return;
2059
+ if (req.canvas && req.canvas !== activePath) {
2060
+ console.warn('[asset-picker] active canvas changed since request — aborting');
2061
+ return;
2062
+ }
2063
+ if (destination === 'artboard') {
2064
+ const artboardId = selectedRef.current?.artboardId ?? canvasActiveArtboard ?? null;
2065
+ if (!artboardId) return;
2066
+ for (const src of paths) {
2067
+ insertElementShell(undefined, 'inside-end', 'image', { artboardId, src });
2068
+ }
2069
+ return;
2070
+ }
2071
+ postToActiveCanvas({ dgn: 'insert-annotation-media', paths });
2072
+ },
2073
+ [assetPickerReq, activePath, insertElementShell, canvasActiveArtboard, postToActiveCanvas]
2074
+ );
2075
+
2076
+ // Phase 4 (whiteboard-improvements) — a bundled sticker has no project asset
2077
+ // path yet (it lives in MAUDE's own STICKERS_DIR, main-origin-only per
2078
+ // DDR-054), so re-upload its bytes through the SAME /_api/asset lane every
2079
+ // other image source uses (content-addressed, canvas-origin-allowlisted) —
2080
+ // then relay the resulting project-relative path down to the canvas exactly
2081
+ // like replace-annotation-media above (the annotation model owns its own
2082
+ // strokes; the shell performs no stroke write of its own).
2083
+ const onStickerPicked = useCallback(
2084
+ async (sticker) => {
2085
+ const req = stickerPickerReq;
2086
+ setStickerPickerReq(null);
2087
+ if (!req || !sticker?.url) return;
2088
+ // G3 security (DDR-152) — same re-check as onAssetPicked: the request
2089
+ // captured the active canvas when the picker opened; abort rather than
2090
+ // insert into whatever canvas happens to be active now.
2091
+ if (req.canvas && req.canvas !== activePath) {
2092
+ console.warn('[sticker-picker] active canvas changed since request — aborting');
2093
+ return;
2094
+ }
2095
+ try {
2096
+ const blob = await fetch(sticker.url).then((r) =>
2097
+ r.ok ? r.blob() : Promise.reject(new Error(`HTTP ${r.status}`))
2098
+ );
2099
+ const res = await fetch('/_api/asset', {
2100
+ method: 'POST',
2101
+ headers: { 'content-type': blob.type || 'image/png' },
2102
+ body: blob,
2103
+ });
2104
+ const j = await res.json().catch(() => ({}));
2105
+ if (!res.ok || !j.path) {
2106
+ console.warn('[sticker-picker]', j.error || `upload failed (HTTP ${res.status})`);
2107
+ return;
2108
+ }
2109
+ postToActiveCanvas({ dgn: 'insert-sticker', path: j.path });
2110
+ } catch {
2111
+ console.warn('[sticker-picker] could not load or upload that sticker');
2112
+ }
2113
+ },
2114
+ [stickerPickerReq, activePath, postToActiveCanvas]
2115
+ );
2116
+ // Media-section "Replace…" (CssKnobs) → open the picker in replace mode with
2117
+ // the element's current src as the undo before-value (captured from the
2118
+ // Selection's `attrs.src`, not the resolved URL).
2119
+ const onReplaceMedia = useCallback(
2120
+ (elSel) => {
2121
+ if (!elSel?.id) return;
2122
+ setAssetPickerReq({
2123
+ purpose: 'replace-src',
2124
+ canvas: activePath,
2125
+ id: elSel.id,
2126
+ before: elSel.attrs?.src ?? null,
2127
+ });
2128
+ },
2129
+ [activePath]
2130
+ );
2131
+
2132
+ const resolveComment = useCallback((id) => {
2133
+ wsSend({ type: 'comments-patch', id, patch: { status: 'resolved' } });
2134
+ }, []);
2135
+ const reopenComment = useCallback((id) => {
2136
+ wsSend({ type: 'comments-patch', id, patch: { status: 'open' } });
2137
+ }, []);
2138
+ const deleteComment = useCallback((id) => {
2139
+ wsSend({ type: 'comments-delete', id });
2140
+ setFocusedCommentId((prev) => (prev === id ? null : prev));
2141
+ }, []);
2142
+ return {
2143
+ applyOptimisticStyle, assetPickerReq, clearActiveCanvasSelection, deleteComment,
2144
+ detachInstanceShell, duplicateArtboardShell, insertGeneratedImage, onAssetPicked,
2145
+ onInsertArtboard, onPickMany, onReplaceMedia, onStickerPicked, recordSourceEdit, reopenComment,
2146
+ reorderLayer, resizeArtboardShell, resolveComment, setArtboardHugShell, setArtboardKindShell,
2147
+ setArtboardPrintShell, setArtboardStyleShell, setAssetPickerReq, setStickerPickerReq,
2148
+ stickerPickerReq
2149
+ };
2150
+ }