@1agh/maude 1.7.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 (108) hide show
  1. package/apps/studio/acp/bridge.ts +15 -2
  2. package/apps/studio/acp/login-state.ts +1 -0
  3. package/apps/studio/acp/probe.ts +52 -1
  4. package/apps/studio/api.ts +431 -39
  5. package/apps/studio/asset-upload.ts +174 -0
  6. package/apps/studio/assets-s3.ts +37 -2
  7. package/apps/studio/bin/_curl-local.mjs +7 -0
  8. package/apps/studio/bin/_pdf-playwright.mjs +22 -1
  9. package/apps/studio/bin/_png-playwright.mjs +20 -1
  10. package/apps/studio/bin/_region.mjs +92 -0
  11. package/apps/studio/bin/annotate.mjs +16 -7
  12. package/apps/studio/bin/read-annotations.mjs +62 -4
  13. package/apps/studio/canvas-build.ts +59 -4
  14. package/apps/studio/canvas-lib.tsx +48 -1
  15. package/apps/studio/canvas-shell.tsx +28 -4
  16. package/apps/studio/client/app.jsx +441 -15903
  17. package/apps/studio/client/canvas-url.js +9 -0
  18. package/apps/studio/client/dialogs/asset-picker.jsx +331 -0
  19. package/apps/studio/client/dialogs/command-palette.jsx +112 -0
  20. package/apps/studio/client/dialogs/export-dialog.jsx +782 -0
  21. package/apps/studio/client/dialogs/help-modal.jsx +324 -0
  22. package/apps/studio/client/dialogs/shortcuts-overlay.jsx +144 -0
  23. package/apps/studio/client/embed-view.jsx +284 -0
  24. package/apps/studio/client/embed.js +101 -0
  25. package/apps/studio/client/export-center.jsx +2 -0
  26. package/apps/studio/client/github.js +36 -3
  27. package/apps/studio/client/hooks/use-canvas-bridge.jsx +2150 -0
  28. package/apps/studio/client/hooks/use-git-actions.jsx +236 -0
  29. package/apps/studio/client/hooks/use-keyboard-shortcuts.jsx +297 -0
  30. package/apps/studio/client/hooks/use-palette-and-panels.jsx +474 -0
  31. package/apps/studio/client/hooks/use-photo-and-timeline.jsx +901 -0
  32. package/apps/studio/client/hooks/use-project-data.jsx +90 -0
  33. package/apps/studio/client/hooks/use-shell-core.jsx +1212 -0
  34. package/apps/studio/client/hooks/use-tabs.jsx +723 -0
  35. package/apps/studio/client/hooks/use-web-socket.jsx +13 -0
  36. package/apps/studio/client/inspector/artboard-knobs.jsx +456 -0
  37. package/apps/studio/client/inspector/color-picker.jsx +196 -0
  38. package/apps/studio/client/inspector/color.js +92 -0
  39. package/apps/studio/client/inspector/css-knobs.jsx +1720 -0
  40. package/apps/studio/client/inspector/css-vocab.jsx +131 -0
  41. package/apps/studio/client/inspector/ds-tokens.js +90 -0
  42. package/apps/studio/client/inspector/grid-tracks-editor.jsx +97 -0
  43. package/apps/studio/client/inspector/inspect-computed.jsx +68 -0
  44. package/apps/studio/client/inspector/inspector-panel.jsx +769 -0
  45. package/apps/studio/client/inspector/layers.jsx +322 -0
  46. package/apps/studio/client/inspector/selection.js +65 -0
  47. package/apps/studio/client/inspector/token-popover.jsx +301 -0
  48. package/apps/studio/client/menus/menubar.jsx +856 -0
  49. package/apps/studio/client/report-bug.jsx +8 -2
  50. package/apps/studio/client/selection-scope.js +40 -0
  51. package/apps/studio/client/shell/banners.jsx +272 -0
  52. package/apps/studio/client/shell/collapsed-rail.jsx +23 -0
  53. package/apps/studio/client/shell/comments-panel.jsx +177 -0
  54. package/apps/studio/client/shell/constants.js +60 -0
  55. package/apps/studio/client/shell/dock.jsx +131 -0
  56. package/apps/studio/client/shell/icons.jsx +370 -0
  57. package/apps/studio/client/shell/status-bar.jsx +215 -0
  58. package/apps/studio/client/shell/util.js +332 -0
  59. package/apps/studio/client/shell/viewport.jsx +254 -0
  60. package/apps/studio/client/system/system-view.jsx +255 -0
  61. package/apps/studio/client/tree/tree.jsx +1243 -0
  62. package/apps/studio/comments-overlay.tsx +6 -4
  63. package/apps/studio/config.schema.json +5 -0
  64. package/apps/studio/context.ts +20 -0
  65. package/apps/studio/dist/client.bundle.js +2728 -2728
  66. package/apps/studio/dist/comment-mount.js +2 -2
  67. package/apps/studio/embed-origins.ts +52 -0
  68. package/apps/studio/export-dialog.tsx +55 -3
  69. package/apps/studio/exporters/_browser-bundles.ts +21 -2
  70. package/apps/studio/exporters/format-scopes.ts +11 -3
  71. package/apps/studio/exporters/index.ts +17 -2
  72. package/apps/studio/exporters/jobs.ts +91 -23
  73. package/apps/studio/exporters/pdf.ts +10 -2
  74. package/apps/studio/exporters/png.ts +10 -2
  75. package/apps/studio/exporters/scope.ts +89 -15
  76. package/apps/studio/format.ts +296 -0
  77. package/apps/studio/generation/runtime-probe.ts +1 -1
  78. package/apps/studio/git/service.ts +1 -0
  79. package/apps/studio/http.ts +399 -36
  80. package/apps/studio/input-router.tsx +7 -1
  81. package/apps/studio/path-containment.ts +72 -0
  82. package/apps/studio/paths.ts +14 -1
  83. package/apps/studio/read-only-mode.ts +53 -0
  84. package/apps/studio/server.ts +123 -25
  85. package/apps/studio/sync/accepted-link.ts +6 -0
  86. package/apps/studio/sync/agent.ts +9 -1
  87. package/apps/studio/sync/cold-start-apply.ts +29 -4
  88. package/apps/studio/sync/cold-start.ts +78 -0
  89. package/apps/studio/sync/file-plane.ts +61 -1
  90. package/apps/studio/sync/format-sync.ts +160 -0
  91. package/apps/studio/sync/index.ts +208 -23
  92. package/apps/studio/sync/journal-client.ts +25 -5
  93. package/apps/studio/sync/migrate-seed.ts +8 -1
  94. package/apps/studio/sync/park.ts +39 -0
  95. package/apps/studio/sync/presentation.ts +9 -3
  96. package/apps/studio/sync/status.ts +2 -0
  97. package/apps/studio/sync/transaction-client.ts +130 -13
  98. package/apps/studio/sync/writer-registry.ts +5 -0
  99. package/apps/studio/ui-prefs.ts +95 -10
  100. package/apps/studio/use-canvas-media-drop.tsx +8 -28
  101. package/apps/studio/whats-new.json +36 -0
  102. package/apps/studio/ws.ts +19 -4
  103. package/cli/bin/claude-design-server.mjs +0 -0
  104. package/cli/commands/design.mjs +9 -2
  105. package/cli/commands/hub-workspace.mjs +25 -0
  106. package/cli/lib/workspace-plan.mjs +51 -0
  107. package/package.json +11 -9
  108. package/plugins/design/templates/_shell.html +58 -0
@@ -0,0 +1,1212 @@
1
+ // hooks/use-shell-core.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 { notifyDesktop, readBoolStore, readInitialTheme, readJsonStore, shellToast } from '../shell/util.js';
5
+ import { DOCK_PANELS, PANEL_SIDES_DEFAULTS, usePanelSize } from '../shell/dock.jsx';
6
+ import { ANNOT_STORE, ATTENTION_NOTIFY_COOLDOWN_MS, COLLAB_TOUR_STORE, CP_MODE_STORE, LAYERS_MODE_STORE, MDCC_VERSION, MINIMAP_STORE, PANEL_SIDES_STORE, SHOW_HIDDEN_STORE, SIDEBAR_STORE, USAGE_TOUR_STORE, ZOOMCTL_STORE, isModuleCanvasPath } from '../shell/constants.js';
7
+ import { useTreeExpansion } from '../tree-expansion.js';
8
+ import { appIsFirstRun, isNativeApp, onMenuReportBug, onUpdateReady } from '../github.js';
9
+ import { useSetupReadiness } from '../panels/SetupChecklist.jsx';
10
+ import { activeComp, resolveCompTarget } from '../panels/timeline-comp-target.js';
11
+ import { useWhatsNew } from '../whats-new.jsx';
12
+ import { useExportCenter } from '../export-center.jsx';
13
+ import { canvasTokenRefreshDelay, setLiveCanvasToken, withCanvasToken } from '../canvas-url.js';
14
+
15
+ export function useShellCore({}) {
16
+ const [groups, setGroups] = useState([]);
17
+ const [treeLoaded, setTreeLoaded] = useState(false);
18
+ // Failed /_index-data attempts since the last success — the tree's loading
19
+ // state says "still trying" instead of sitting blank (the loader retries).
20
+ const [treeLoadFailures, setTreeLoadFailures] = useState(0);
21
+ const addressMode = useRef('push');
22
+ const previousAddressPath = useRef(null);
23
+ const [project, setProject] = useState('Design');
24
+ const [tabs, setTabs] = useState([]);
25
+ const [activePath, setActivePath] = useState(null);
26
+ // feature-studio-file-preview — deliberately separate from `tabs`/
27
+ // `activePath`: a previewed file was never a canvas, so it must never
28
+ // trigger the WS `active`/`tabs` broadcasts, the compile-skeleton loading
29
+ // state, or iframe registration that openTab()/openSystem() drive.
30
+ const [previewPath, setPreviewPath] = useState(null);
31
+ const onPreview = useCallback((path) => {
32
+ addressMode.current = 'push';
33
+ setPreviewPath(path);
34
+ }, []);
35
+ const [selected, setSelected] = useState(null);
36
+ // Phase 12.3 — latest selection, readable from the (stale-closure) onMessage
37
+ // handler so an HMR reload (triggered by a CSS/attr edit) can re-select the
38
+ // same element and restore the in-canvas halo the remount dropped.
39
+ const selectedRef = useRef(null);
40
+ useEffect(() => {
41
+ selectedRef.current = selected;
42
+ }, [selected]);
43
+
44
+ // Stage H (INV-3) — resolve the edit-scope (local vs shared component instance)
45
+ // for the current single selection so the Inspector can show whether an edit
46
+ // stays here or changes N places. Read-only GET, debounced by the selection id;
47
+ // aborts a stale in-flight fetch when the selection changes. Fetched with
48
+ // rendered=1 (source-usage-driven; the .map() refinement is a follow-up).
49
+ const [editScope, setEditScope] = useState(null);
50
+ useEffect(() => {
51
+ const one = Array.isArray(selected) ? (selected.length === 1 ? selected[0] : null) : selected;
52
+ const id = one && typeof one.id === 'string' ? one.id : null;
53
+ if (!id || !activePath) {
54
+ setEditScope(null);
55
+ return;
56
+ }
57
+ const ac = new AbortController();
58
+ const q = new URLSearchParams({ canvas: activePath, id });
59
+ fetch(`/_api/edit-scope?${q}`, { signal: ac.signal })
60
+ .then((r) => (r.ok ? r.json() : null))
61
+ .then((j) => {
62
+ if (j?.ok) setEditScope(j);
63
+ })
64
+ .catch(() => {
65
+ /* aborted / offline — leave the last verdict, the badge just won't show */
66
+ });
67
+ return () => ac.abort();
68
+ }, [selected, activePath]);
69
+ // feature-acp-context-hardening — halo re-apply retry ladder. A single
70
+ // select-by-id post races the fresh iframe: dgn:'loaded' fires from the
71
+ // inline inspector script at HTML-parse time, BEFORE the React canvas-shell
72
+ // mounts its message listener (module fetch + mount takes 100ms–seconds), so
73
+ // a one-shot post silently evaporates and the restored selection never gets
74
+ // its halo back. Re-post on a fixed ladder; each attempt aborts when the
75
+ // user meanwhile selected something else. select-by-id is idempotent
76
+ // (replace-same → select-set echo → ws guard sees same id → no re-schedule),
77
+ // so the ladder can't loop.
78
+ // feature-4 dogfood fix — timestamp of the last LOCAL selection change sent
79
+ // over WS. The ws 'selected' broadcast is both (a) our own echo and (b) a
80
+ // genuine cross-canvas restore; within this window it's always (a) and must
81
+ // not overwrite fresher local state (multi-select / drill races).
82
+ // What THIS shell last selected locally, and when — set synchronously at the select, so the
83
+ // server's echo is recognised even before `selectedRef` (an effect) catches up (V2-2.8 P2).
84
+ const lastLocalSelectRef = useRef({ at: 0, sel: null, file: null });
85
+ const haloRestoreTimersRef = useRef([]);
86
+ const scheduleHaloRestore = useCallback((one) => {
87
+ if (!one?.id || !one.file) return;
88
+ for (const t of haloRestoreTimersRef.current) clearTimeout(t);
89
+ haloRestoreTimersRef.current = [50, 450, 1200, 2500, 5000].map((delay) =>
90
+ setTimeout(() => {
91
+ const cur = selectedRef.current;
92
+ const c1 = Array.isArray(cur) ? cur[0] : cur;
93
+ if (!c1 || c1.id !== one.id || c1.file !== one.file) return; // superseded
94
+ const frame = iframesRef.current.get(one.file);
95
+ if (!frame?.contentWindow) return;
96
+ try {
97
+ frame.contentWindow.postMessage(
98
+ {
99
+ dgn: 'select-by-id',
100
+ id: one.id,
101
+ artboardId: one.artboardId ?? null,
102
+ index: one.index ?? 0,
103
+ },
104
+ '*'
105
+ );
106
+ } catch {}
107
+ }, delay)
108
+ );
109
+ }, []);
110
+ // Dogfood follow-up — the ArtboardKnobs panel (Kind/Print/Style/Hug/W-H)
111
+ // writes via structuralWrite, which never refreshed the Inspector's OWN
112
+ // `attrs` snapshot afterward: the artboard itself re-rendered correctly
113
+ // (new kind, new size) but the Inspector kept showing the PRE-edit values
114
+ // (e.g. "Digital" right after picking "Print") until the user manually
115
+ // re-clicked the artboard. Mirrors scheduleHaloRestore's retry ladder
116
+ // (the HMR reload lands async, so a single immediate post races it) but
117
+ // for a bare ARTBOARD selection (no data-cd-id to key off of — compares
118
+ // by artboardId instead of id).
119
+ const artboardResyncTimersRef = useRef([]);
120
+ const scheduleArtboardResync = useCallback((artboardId, file) => {
121
+ if (!artboardId || !file) return;
122
+ for (const t of artboardResyncTimersRef.current) clearTimeout(t);
123
+ artboardResyncTimersRef.current = [50, 450, 1200, 2500, 5000].map((delay) =>
124
+ setTimeout(() => {
125
+ const cur = selectedRef.current;
126
+ const c1 = Array.isArray(cur) ? cur[0] : cur;
127
+ if (!c1 || c1.artboardId !== artboardId || c1.file !== file) return; // superseded
128
+ const frame = iframesRef.current.get(file);
129
+ if (!frame?.contentWindow) return;
130
+ try {
131
+ frame.contentWindow.postMessage({ dgn: 'select-by-id', artboardId }, '*');
132
+ } catch {}
133
+ }, delay)
134
+ );
135
+ }, []);
136
+ // Phase 12.1 (DDR-138) — after a reorder writes source, the HMR reload remounts
137
+ // the canvas and the positional data-cd-id of the moved element (and everything
138
+ // after it) renumbers. Stash the re-settle target { file, movedId, artboardId }
139
+ // so the dgn:'loaded' handler re-selects the moved element by its NEW id.
140
+ const pendingReorderRef = useRef(null);
141
+ // The last layers tree the canvas posted, and its id signature. A duplicate
142
+ // or insert renumbers every later positional id, so the copy's NEW id already
143
+ // names another element (the next sibling) in the pre-write tree: settling
144
+ // on the first tree that merely contains it selected the wrong node. The
145
+ // pending entry records the signature at request time and waits for a tree
146
+ // that differs from it.
147
+ const lastLayersTreeRef = useRef(null);
148
+ const settlePendingSelectionRef = useRef(null);
149
+ settlePendingSelectionRef.current = (tree, sig, artboardId) => {
150
+ const pend = pendingReorderRef.current;
151
+ if (!pend || !pend.movedId) return;
152
+ if (pend.staleSig != null && sig === pend.staleSig) return; // still the pre-write DOM
153
+ const has = (function find(nodes) {
154
+ return (nodes || []).some((n) => n.id === pend.movedId || find(n.children));
155
+ })(tree);
156
+ if (!has) return;
157
+ pendingReorderRef.current = null;
158
+ const win = activePath ? iframesRef.current.get(activePath)?.contentWindow : null;
159
+ if (win) {
160
+ try {
161
+ win.postMessage({ dgn: 'select-by-id', id: pend.movedId, artboardId, index: 0 }, '*');
162
+ } catch {}
163
+ }
164
+ };
165
+ // Latest `reorderLayer` (defined far below), read from the stale-closure
166
+ // onMessage handler when the in-canvas grip posts dgn:'reorder-request'
167
+ // (same freshness idiom as selectedRef; avoids a render-time TDZ on the
168
+ // later useCallback).
169
+ const reorderLayerRef = useRef(null);
170
+ // Same freshness idiom for `repositionElement` (defined far below), read
171
+ // when the in-canvas drag posts dgn:'reposition-request' — the coordinate-
172
+ // mode commit for out-of-flow (position:absolute/fixed) elements.
173
+ const repositionElementRef = useRef(null);
174
+ // feature-element-editing-robustness Stage D — sibling ref for `resizeElement`
175
+ // (defined far below), read when the in-canvas resize overlay posts
176
+ // dgn:'resize-request' on pointer-up. Same origin-split as reposition.
177
+ const resizeElementRef = useRef(null);
178
+ // Phase 12.1 — true between a layers-panel reorder and the fresh layers-tree
179
+ // landing. A reorder churns positional data-cd-ids, so a rapid 2nd drag would
180
+ // target stale ids; the Layers tree gates new drags on this until the rebuilt
181
+ // tree (with correct ids) arrives. Cleared by the layers-tree message.
182
+ const layersBusyRef = useRef(false);
183
+ const layersBusyTimerRef = useRef(null);
184
+ // Phase 12 Task 4 — Layers tree for the active artboard (posted by canvas-shell).
185
+ const [layersTree, setLayersTree] = useState(null);
186
+ // feature-4 T7a — Layers-panel component map ({ [cdId]: { component, root,
187
+ // usages } }) for purple instance rows. Fetched from the read-only main-origin
188
+ // /_api/component-map on canvas/tree changes, throttled: the map only changes
189
+ // when SOURCE changes, but the tree re-posts on any DOM churn (drag reflows) —
190
+ // don't re-parse the canvas for those.
191
+ const [componentMap, setComponentMap] = useState(null);
192
+ const componentMapAtRef = useRef({ canvas: null, at: 0 });
193
+ useEffect(() => {
194
+ if (!activePath || !layersTree) return;
195
+ const now = Date.now();
196
+ const last = componentMapAtRef.current;
197
+ if (last.canvas === activePath && now - last.at < 1500) return;
198
+ componentMapAtRef.current = { canvas: activePath, at: now };
199
+ fetch(`/_api/component-map?canvas=${encodeURIComponent(activePath)}`)
200
+ .then((r) => r.json())
201
+ .then((j) => {
202
+ if (j?.ok && j.map && typeof j.map === 'object') setComponentMap(j.map);
203
+ else setComponentMap(null);
204
+ })
205
+ .catch(() => setComponentMap(null));
206
+ }, [activePath, layersTree]);
207
+ const [wsConnected, setWsConnected] = useState(false);
208
+ // Phase 8 Task 7 — git lifecycle reload prompt. Server has already flushed
209
+ // every dirty Y.Doc to disk by the time this state populates, so accepting
210
+ // the reload is data-loss-safe (DDR-051 §3).
211
+ const [gitLifecycle, setGitLifecycle] = useState(null);
212
+ // Phase 9 Task 8 — hub-down offline mode banner. Driven by the 'sync:status'
213
+ // WS message the linked-mode sync runtime emits. null in solo mode.
214
+ const [syncStatus, setSyncStatus] = useState(null);
215
+ // feature-large-project-seed — the NATIVE half of seed progress.
216
+ //
217
+ // A seed against a large project is minutes to hours of work, and the target
218
+ // user (DDR-177) never opens a terminal. The Sync panel is the detail view;
219
+ // this is what reaches them when the panel is not on screen: the window
220
+ // title while it runs, and ONE notification per phase transition.
221
+ //
222
+ // Per TRANSITION, never per file. A 2 961-file seed must produce two
223
+ // notifications, not 2 961 — `send_notification` throttles on the Rust side
224
+ // too, but a client that leans on that is a client that would spam a plain
225
+ // browser tab through the Web fallback.
226
+ const seedPhaseRef = useRef(null);
227
+ useEffect(() => {
228
+ const p = syncStatus?.files?.progress;
229
+ if (!p) return;
230
+ const prev = seedPhaseRef.current;
231
+ seedPhaseRef.current = p.phase;
232
+ if (prev === null || prev === p.phase) return;
233
+ if (p.phase === 'converged' && (prev === 'seeding' || prev === 'paused')) {
234
+ notifyDesktop('Project synced', `${p.delivered} files are up to date.`);
235
+ } else if (p.phase === 'blocked') {
236
+ const total = (p.blocked ?? []).reduce((n, b) => n + b.count, 0);
237
+ notifyDesktop(
238
+ 'Sync needs a decision',
239
+ `${total} file${total === 1 ? '' : 's'} could not be sent. Open the Sync panel for the reason.`
240
+ );
241
+ }
242
+ }, [syncStatus?.files?.progress]);
243
+ // The title carries the count while a seed runs, and is restored afterwards —
244
+ // it is the one surface visible without opening anything.
245
+ useEffect(() => {
246
+ if (typeof document === 'undefined') return undefined;
247
+ const p = syncStatus?.files?.progress;
248
+ const base = document.title.replace(/\s+—\s+syncing\s+\d+\/\d+$/, '');
249
+ if (p && (p.phase === 'seeding' || p.phase === 'paused') && p.tracked > 0) {
250
+ document.title = `${base} — syncing ${p.delivered}/${p.tracked}`;
251
+ } else {
252
+ document.title = base;
253
+ }
254
+ return undefined;
255
+ }, [syncStatus?.files?.progress]);
256
+ // DDR-218 — the folder's cloud link ({url, credentialed} | null), lifted from
257
+ // CloudBar (status resolve / attach / detach). Gates the GitPanel's
258
+ // cloud-managed posture; linked-but-uncredentialed keeps the full panel.
259
+ const [cloudLinkedHub, setCloudLinkedHub] = useState(null);
260
+ const [localProjectName, setLocalProjectName] = useState(null);
261
+ // Phase 27 (E2) — in-UI git layer. `gitStatus` is the live dirty-state the
262
+ // server broadcasts on `git-status`; `changesOpen` toggles the Changes panel;
263
+ // `diffTarget` opens the before/after DiffView ({ file, conflict }).
264
+ const [gitStatus, setGitStatus] = useState(null);
265
+ // Phase 28 (E3) — remote ahead/behind ("Get latest" nudge). Kept in its OWN
266
+ // slice, NOT folded into `gitStatus`, because the `git-status` WS broadcast
267
+ // (line ~5791) replaces `gitStatus` on every dirty-state change and carries
268
+ // only LOCAL status — merging remote-ahead into it would be clobbered on the
269
+ // next keystroke. The probe is a real network `git fetch` (server-side, token
270
+ // from the keychain bridge), so it runs on a slow cadence — mount, a periodic
271
+ // tick, and after each git action — never on the per-edit WS path.
272
+ const [remoteSync, setRemoteSync] = useState(null); // { remoteAhead, behind } | null
273
+ const [changesOpen, setChangesOpen] = useState(false);
274
+ // feature-sync-progress-modal — the per-file Sync panel; toggled from the
275
+ // status-bar HUB SYNC chip. Only available while `syncStatus` is non-null
276
+ // (a linked project), mirroring how `changes` gates on `gitStatus.repo`.
277
+ const [syncPanelOpen, setSyncPanelOpen] = useState(false);
278
+ const [diffTarget, setDiffTarget] = useState(null);
279
+ const [search, setSearch] = useState('');
280
+ const [systemData, setSystemData] = useState(null);
281
+ // Canvas-compile skeleton (single-canvas model → one path at a time).
282
+ const [loadingPath, setLoadingPath] = useState(null);
283
+ const loadFallbackTimer = useRef(null);
284
+ // issue #115 — a canvas that never reported `loaded`. `{ path, kind }`, where
285
+ // kind is 'server' (the canvas origin did not answer /_health — a dead or
286
+ // respawned sidecar) or 'compile' (the origin is up, the canvas itself never
287
+ // mounted). Rendered instead of the blank pane the cap used to leave behind.
288
+ const [canvasError, setCanvasError] = useState(null);
289
+ // Bumped by the error panel's Retry. Folded into the iframe `key` so a retry
290
+ // REMOUNTS the frame — re-setting `src` to the identical URL would not
291
+ // re-navigate, and after a respawn the URL is identical in every case except
292
+ // the port that `loadServerConfig()` is about to correct.
293
+ const [canvasReloadNonce, setCanvasReloadNonce] = useState(0);
294
+ // The canvas whose SHELL DOCUMENT has actually loaded, per its `dgn:'loaded'`
295
+ // post. Distinct from `!loadingPath`, which the 2.5 s onLoad fallback and the
296
+ // 15 s cap also clear — this one only ever means "the shell ran". That makes
297
+ // it the honest signal for `data-canvas-state` below, and the one the #115 E2E
298
+ // scenario asserts: the shell's inline script posts it whether or not the
299
+ // canvas TSX went on to build, so it isolates "the origin was reachable" from
300
+ // "the canvas compiled" — exactly the axis #115 is about.
301
+ const [loadedPath, setLoadedPath] = useState(null);
302
+ // Resizable side panels (DS components-resize-panels) + the active drag side.
303
+ const sbSize = usePanelSize('maude-sb-w', { min: 200, max: 420, def: 252 });
304
+ const rpSize = usePanelSize('maude-rp-w', { min: 260, max: 480, def: 304 });
305
+ const [dragSide, setDragSide] = useState(null); // 'sb' | 'rp' | null
306
+ const bodyRef = useRef(null);
307
+
308
+ // Pointer drag for the panel grips — window listeners while dragging (the
309
+ // grip also pointer-captures, and `.st-body.is-resizing iframe` drops pointer
310
+ // events so the canvas iframe can't swallow the move stream mid-drag).
311
+ useEffect(() => {
312
+ if (!dragSide) return;
313
+ const onMove = (e) => {
314
+ const rect = bodyRef.current?.getBoundingClientRect();
315
+ if (!rect) return;
316
+ if (dragSide === 'sb') sbSize.setW(e.clientX - rect.left);
317
+ else rpSize.setW(rect.right - e.clientX);
318
+ };
319
+ const onUp = () => setDragSide(null);
320
+ window.addEventListener('pointermove', onMove);
321
+ window.addEventListener('pointerup', onUp);
322
+ return () => {
323
+ window.removeEventListener('pointermove', onMove);
324
+ window.removeEventListener('pointerup', onUp);
325
+ };
326
+ }, [dragSide, sbSize.setW, rpSize.setW]);
327
+
328
+ // Loading-skeleton lifecycle: dgn:'loaded' clears it instantly (TSX canvases);
329
+ // the iframe load event arms a short fallback for legacy .html canvases that
330
+ // never post it; a hard cap guards against a canvas that dies mid-compile.
331
+ const onIframeLoad = useCallback((path) => {
332
+ // A module canvas reports its own render; the iframe `load` event fires
333
+ // long before it has drawn anything, so a timer here would only bring
334
+ // back the white pane.
335
+ if (isModuleCanvasPath(path)) return;
336
+ clearTimeout(loadFallbackTimer.current);
337
+ loadFallbackTimer.current = setTimeout(() => {
338
+ setLoadingPath((p) => (p === path ? null : p));
339
+ }, 2500);
340
+ }, []);
341
+ // Loaded at boot from /_config and re-fetched on the server's
342
+ // `config-updated` push (config.json hot-reload — /design:setup-ds rewrites
343
+ // it mid-session) — informs canvasUrl() so TSX iframes can pass the right
344
+ // ?designRel + ?tokens query to the canvas mount shell.
345
+ // `cloud` is deliberately TRI-STATE, and the third state is the useful one:
346
+ // undefined — `/_config` has not answered yet; which shell this is is
347
+ // UNKNOWN, and anything that would behave differently in the
348
+ // two shells must wait rather than assume the desktop.
349
+ // null — desktop or plain local browser.
350
+ // object — a cloud tab (`{ dashboardUrl?, projectName, user, role }`).
351
+ //
352
+ // Collapsing unknown into "not cloud" is what made the cloud studio open with
353
+ // two console 404s every time: the sign-in bar and the export centre mounted
354
+ // for one frame, each fired the request its shell exists to refuse, and then
355
+ // unmounted. Nothing was broken and everything looked broken.
356
+ const [cfg, setCfg] = useState({ designRel: '.design', cloud: undefined });
357
+ // THE CAP MUST NOT CLEAR TO WHITE — issue #115. This used to be a bare
358
+ // `setLoadingPath(null)`, which is the most useless thing it could do: when
359
+ // the canvas origin is unreachable the shell HTML never loads, so the shell's
360
+ // own `#canvas-mount-error` surface (templates/_shell.html) does not exist to
361
+ // report anything, and dropping the skeleton left a blank pane with no error,
362
+ // no reason and no way back inside the app. Probe the canvas origin to tell
363
+ // the two failures apart — a dead server (the #115 stale-origin case, and any
364
+ // sidecar crash) versus a canvas that genuinely never finished compiling —
365
+ // and hand the user the recovery in both cases.
366
+ //
367
+ // DECLARED AFTER `cfg`, ON PURPOSE — the same rule the block below states for
368
+ // the git flags, and this effect is what taught us it is not decorative. Its
369
+ // dependency array reads `cfg?.canvasOrigin`, and A DEPENDENCY ARRAY IS
370
+ // EVALUATED DURING RENDER: sitting above the `useState` above, it hit `cfg` in
371
+ // its temporal dead zone, so `App` threw `Cannot access 'cfg' before
372
+ // initialization` on its very first render and the WHOLE STUDIO mounted
373
+ // nothing — a white page for every user, not only the desktop shell the fix
374
+ // was written for. It reached the branch because the PR carried a merge
375
+ // conflict, which stops GitHub from building a merge ref, which means the
376
+ // client-boot gate never ran on it (issue #112 close-out).
377
+ // Once the shell has said `loaded` the origin is demonstrably up and the
378
+ // wait is the canvas building — on a cold cloud canvas that can outlast 15 s
379
+ // without anything being wrong, so the cap stretches instead of calling it a
380
+ // failure. The shell reports a real build error itself (`canvas-failed`).
381
+ const shellAlive = !!loadingPath && loadedPath === loadingPath;
382
+ useEffect(() => {
383
+ if (!loadingPath) return;
384
+ const path = loadingPath;
385
+ const cap = setTimeout(async () => {
386
+ let kind = 'compile';
387
+ try {
388
+ const r = await fetch(`${cfg?.canvasOrigin || ''}/_health`, {
389
+ cache: 'no-store',
390
+ });
391
+ if (!r.ok) kind = 'server';
392
+ } catch {
393
+ kind = 'server';
394
+ }
395
+ setCanvasError({ path, kind });
396
+ setLoadingPath((p) => (p === path ? null : p));
397
+ }, shellAlive ? 60000 : 15000);
398
+ return () => clearTimeout(cap);
399
+ }, [loadingPath, shellAlive, cfg?.canvasOrigin]);
400
+ // WHO IS SAVING THIS PROJECT — one expression, read by every surface that
401
+ // would otherwise offer to save it, poll for it, or badge it (DDR-218, widened
402
+ // by feature-cloud-managed-git-posture).
403
+ //
404
+ // These two flags were previously derived at the GitPanel call site alone, so
405
+ // the panel withdrew correctly while the toolbar menu and the status-bar chip
406
+ // kept rendering a raw dirty count from `gitStatus.files.length` — the very
407
+ // "lie about work that is already saved" the withdrawal exists to delete. The
408
+ // count is the claim, wherever it is drawn; hoisting the rule here is what
409
+ // keeps a third surface from re-introducing it.
410
+ //
411
+ // DECLARED HERE, AT THE TOP, ON PURPOSE. Every local-git POLL below is gated
412
+ // on it, and a dependency array evaluates during render — a `const` further
413
+ // down would be in its temporal dead zone at the first `useEffect` that names
414
+ // it. The same hazard the remote-sync effect's own comment records.
415
+ //
416
+ // PRESENTATION, NOT A CONTROL — unchanged from DDR-218. `.git` is untouched:
417
+ // no hook is installed, no config is written, a terminal `git status` /
418
+ // `git commit` behaves exactly as before, the local `/_api/git/*` routes keep
419
+ // exactly their old gates, and `git/watch.ts` still flushes a terminal
420
+ // `git checkout` into Yjs (DDR-051). What stops is MAUDE's own local git
421
+ // activity — the polls and the surfaces that describe a repo nobody is
422
+ // editing through. Disconnect restores every one of them live.
423
+ const cellManaged = !!cfg.cloud;
424
+ const cloudManaged = !cfg.cloud && !!cloudLinkedHub?.credentialed;
425
+ const savingIsManaged = cellManaged || cloudManaged;
426
+ // The raw truth stays available for surfaces that legitimately need it (the
427
+ // panel's own file list); only the COUNT — the thing that reads as a to-do —
428
+ // is withheld when this project's saving is somebody else's job.
429
+ const unsavedCount = savingIsManaged ? 0 : gitStatus?.files?.length || 0;
430
+ // The posture, readable from callbacks that must NOT re-subscribe when it
431
+ // flips: the WS handler is installed once for the socket's lifetime, and the
432
+ // two git-status refreshers are `useCallback([])`s a dozen call sites depend
433
+ // on being stable. A ref is how they read a live value without becoming a
434
+ // reason to tear the socket down.
435
+ const savingIsManagedRef = useRef(savingIsManaged);
436
+ savingIsManagedRef.current = savingIsManaged;
437
+ // Cloud Phase 25 C2 — viewer role, known at boot from /_config. Every
438
+ // editing affordance in the shell gates on this (absent, not hidden).
439
+ const viewerMode = !!cfg.readOnly;
440
+ const loadServerConfig = useCallback(() => {
441
+ fetch('/_config')
442
+ .then((r) => r.json())
443
+ .then((data) => {
444
+ const designRel = (data.designRoot || '.design').replace(/^\/+|\/+$/g, '');
445
+ // Functional merge — the `/_config` and `/_index-data` fetches race, and
446
+ // the latter contributes `canvasDesignSystems` (DDR-093). A full-replace
447
+ // here would clobber that map if it resolved second.
448
+ setCfg((prev) => ({
449
+ ...prev,
450
+ designRel,
451
+ tokensCssRel: data.tokensCssRel,
452
+ // Pass through designSystems so canvasUrl can resolve the right
453
+ // tokens/components paths per-DS. Top-level tokensCssRel is the
454
+ // legacy default; designSystems[0].tokensCssRel is the project's
455
+ // authoritative value (post DS-bootstrap).
456
+ designSystems: data.designSystems,
457
+ // T2 (9.1-A) — segregated canvas-content origin. canvasUrl() prepends
458
+ // it so iframes load cross-origin (hub-pushed JSX is then walled off
459
+ // from the main origin's /_api). Absent on older servers → relative
460
+ // URL fallback keeps same-origin behavior.
461
+ canvasOrigin: data.canvasOrigin,
462
+ // Cloud Phase 25 C2 — the linked hub vouched a `viewer` role at
463
+ // sign-in. Known at BOOT (before anything draws), so editing
464
+ // affordances are ABSENT rather than shown-then-refused. This flag
465
+ // decides what the UI offers; the cell (C1) and the dev-server's
466
+ // read-only gate (http.ts) are what actually stop a write.
467
+ readOnly: !!data.readOnly,
468
+ // V2-1.12 §5.6 — the project's file format, the gate when this build
469
+ // does not edit it ({ projectFormat, supported, source } | null), and
470
+ // why `readOnly` holds: 'role' | 'format' | null. FormatGateBanner
471
+ // (V2-2.18 P1) and the v2 "Update project" dialog read these.
472
+ formatVersion: data.formatVersion ?? 1,
473
+ formatGate: data.formatGate ?? null,
474
+ readOnlyReason: data.readOnlyReason ?? null,
475
+ // Cloud Phase 27 (DDR-209) — the capability that opens the cookieless
476
+ // canvas origin. `canvasUrl()` appends it to every iframe URL. Absent
477
+ // on a desktop, where the canvas origin is loopback and needs none.
478
+ //
479
+ // NOTE FOR WHOEVER ADDS THE NEXT FIELD: this is an explicit
480
+ // projection, not a spread of `data`. A field the server starts
481
+ // returning does NOT arrive here until it is named — which is how
482
+ // both of these went missing and the cloud studio rendered without
483
+ // its chrome and with every canvas iframe unauthenticated.
484
+ canvasToken: data.canvasToken,
485
+ // Which release this server is — rendered as the status-bar chip.
486
+ // Undefined on a server too old to report it, which is why the chip
487
+ // renders conditionally rather than printing `vundefined`.
488
+ version: data.version,
489
+ // C2/C4 — `{ dashboardUrl?, projectName, user, role }` when this is a
490
+ // cloud tab. Its presence is what tells the shared client it is in a
491
+ // browser tab on somebody else's machine; `user`/`role` are what let
492
+ // it say WHICH account that tab is, and offer the way out.
493
+ cloud: data.cloud ?? null,
494
+ // feature-cloud-export-render-workers — `local` | `remote` | `none`.
495
+ // Which export formats this server can actually produce; the export
496
+ // dialogs gate on it. Absent on older servers → undefined, treated
497
+ // as `local` (the pre-lane behavior) everywhere it is read.
498
+ exportLane: data.exportLane,
499
+ // DDR-247 — the apps allowed to frame this studio. Read by the
500
+ // `?embed=1` root (embed-view.jsx), which never mounts <App>; named
501
+ // here so the projection stays total (config-projection.test.ts).
502
+ embedOrigins: data.embedOrigins,
503
+ }));
504
+ })
505
+ .catch(() => {});
506
+ }, []);
507
+ useEffect(() => {
508
+ loadServerConfig();
509
+ }, [loadServerConfig]);
510
+ // Backfill the sync banner on mount from /_sync-status. The 'sync:status' WS
511
+ // broadcast is one-shot for the zero-syncable case (DDR-060 / 9.1-D), so a
512
+ // tab that connects after boot would otherwise miss it. {linked:false} (solo)
513
+ // leaves the banner null.
514
+ useEffect(() => {
515
+ let cancelled = false;
516
+ fetch('/_sync-status')
517
+ .then((r) => r.json())
518
+ .then((data) => {
519
+ if (cancelled || !data || data.linked === false) return;
520
+ setSyncStatus(data);
521
+ })
522
+ .catch(() => {});
523
+ return () => {
524
+ cancelled = true;
525
+ };
526
+ }, []);
527
+ // Phase 27 (E2) — seed the git dirty-state on mount; live updates arrive over
528
+ // the `git-status` WS broadcast (Task 5). Solo/non-git projects → repo:false.
529
+ //
530
+ // NOT WHILE SOMEBODY ELSE IS COMMITTING. In cloud-managed posture this asks
531
+ // about a repo the user is not editing through, and every answer it brings
532
+ // back is drawn somewhere as a claim about their work. Reactive on
533
+ // `savingIsManaged`, not mount-only, so Disconnect resumes it live and
534
+ // Connect stops it live — the requirement `git-cloud-posture.test.ts`
535
+ // already pins for the panel.
536
+ useEffect(() => {
537
+ if (savingIsManaged) {
538
+ // Drop what the local repo last said, too. A stale `gitStatus` left
539
+ // standing keeps the tree's M/A/D badges lit after the posture changed.
540
+ setGitStatus(null);
541
+ return undefined;
542
+ }
543
+ let cancelled = false;
544
+ fetch('/_api/git/status')
545
+ .then((r) => r.json())
546
+ .then((data) => {
547
+ if (!cancelled && data) setGitStatus(data);
548
+ })
549
+ .catch(() => {});
550
+ return () => {
551
+ cancelled = true;
552
+ };
553
+ }, [savingIsManaged]);
554
+ const [commentsByFile, setCommentsByFile] = useState({}); // { file: [Comment] }
555
+ // Phase 6 — the in-iframe composer owns drafting; the shell no longer holds
556
+ // a `draft` state. Mutations route through postMessage → WS instead.
557
+ const [focusedCommentId, setFocusedCommentId] = useState(null);
558
+ const [commentsPanelOpen, setCommentsPanelOpen] = useState(false);
559
+ const [commentsFilter, setCommentsFilter] = useState('open'); // 'all' | 'open' | 'resolved'
560
+ const [theme, setTheme] = useState(readInitialTheme);
561
+ // DDR-171 — CSS-panel vocabulary mode ('advanced' | 'designer'), App-owned so
562
+ // the in-panel corner toggle (CssKnobs) and Settings → Appearance share one
563
+ // source of truth; persisted to `maude-cp-mode` (same pattern as `theme`).
564
+ const [cpMode, setCpMode] = useState(() => {
565
+ const m = readJsonStore(CP_MODE_STORE, 'advanced');
566
+ return m === 'designer' ? 'designer' : 'advanced';
567
+ });
568
+ useEffect(() => {
569
+ try {
570
+ localStorage.setItem(CP_MODE_STORE, JSON.stringify(cpMode));
571
+ } catch {}
572
+ }, [cpMode]);
573
+ const [openMenu, setOpenMenu] = useState(null);
574
+ const [sidebarOpen, setSidebarOpen] = useState(() => readBoolStore(SIDEBAR_STORE, true));
575
+ const [showHidden, setShowHidden] = useState(() => readBoolStore(SHOW_HIDDEN_STORE, false));
576
+ // Issue #124 — folder + section disclosure of the Files panel, remembered
577
+ // per project on disk (tree-expansion.js). Absent ⇒ closed.
578
+ const treeExp = useTreeExpansion();
579
+ const updateTreeExp = treeExp.update;
580
+ const sectionsExpanded = treeExp.state.sections;
581
+ const [helpOpen, setHelpOpen] = useState(false);
582
+ const [reportBugOpen, setReportBugOpen] = useState(false);
583
+
584
+ // Native Help ▸ Report a Bug… (menu.rs emits `menu://report-bug`) — same
585
+ // lane as IdentityBar's File ▸ New Project… subscription.
586
+ useEffect(() => {
587
+ if (!isNativeApp()) return;
588
+ const p = onMenuReportBug(() => setReportBugOpen(true));
589
+ return () => {
590
+ p.then((un) => un()).catch(() => {});
591
+ };
592
+ }, []);
593
+ const [readinessOpen, setReadinessOpen] = useState(false);
594
+ const [introOpen, setIntroOpen] = useState(false);
595
+ const [quickSetupOpen, setQuickSetupOpen] = useState(false);
596
+ const [brandUploadOpen, setBrandUploadOpen] = useState(false);
597
+ const [figmaImportOpen, setFigmaImportOpen] = useState(false);
598
+ // DDR-166 plan, Phase 2 (T7) — the persistent "Setup" affordance in the empty
599
+ // canvas state (below) only renders while the project's own setup (design
600
+ // system / first canvas / brand assets) is incomplete; native-only concern.
601
+ const { report: setupReadiness } = useSetupReadiness(isNativeApp());
602
+ // ? cheat-sheet (DS components-shortcuts-overlay) — separate from the deep
603
+ // Help modal (F1), which keeps commands & flows.
604
+ const [shortcutsOpen, setShortcutsOpen] = useState(false);
605
+ const [paletteOpen, setPaletteOpen] = useState(false);
606
+ // T5/T6 (Plan C) — shell-level export/handoff dialog + inspector panel state.
607
+ // The palette (T4) drives them; the dialog (T5) + panel (T6) consume them.
608
+ const [shareDialog, setShareDialog] = useState(null);
609
+ const [exportDialog, setExportDialog] = useState(null); // null | { mode: 'export'|'handoff', scope? }
610
+ // feature-ai-media-generation (DDR-16x) — BYOK provider-key Settings modal +
611
+ // the AI generate action.
612
+ const [settingsOpen, setSettingsOpen] = useState(false);
613
+ const [generateOpen, setGenerateOpen] = useState(false);
614
+ const [inspectorOpen, setInspectorOpen] = useState(false);
615
+ // feature-configurable-panel-docking — Layers as its own openable panel (when
616
+ // layersMode==='separate'), plus the per-panel side map + layers mode. All
617
+ // three hydrate from disk (/_api/ui-prefs) on mount and persist on change,
618
+ // mirroring the view-pref pattern.
619
+ const [layersOpen, setLayersOpen] = useState(false);
620
+ const [panelSide, setPanelSide] = useState(() =>
621
+ readJsonStore(PANEL_SIDES_STORE, PANEL_SIDES_DEFAULTS)
622
+ );
623
+ const [layersMode, setLayersMode] = useState(() => {
624
+ try {
625
+ const v = localStorage.getItem(LAYERS_MODE_STORE);
626
+ if (v === 'separate' || v === 'in-inspector') return v;
627
+ } catch {}
628
+ return 'separate';
629
+ });
630
+ // DDR-148 — Timeline panel (right dock) for scrubbing a video-comp. `activeComps`
631
+ // is populated from the iframe's `timeline-comps` announce; `timelineFrame` from
632
+ // its live `timeline-frame`. Empty comps ⇒ the panel shows its empty state.
633
+ const [timelineOpen, setTimelineOpen] = useState(false);
634
+ const [activeComps, setActiveComps] = useState([]);
635
+ const [timelineFrame, setTimelineFrame] = useState(0);
636
+ const [timelinePlaying, setTimelinePlaying] = useState(false);
637
+ // Default off — looping is an explicit opt-in per session, not a surprise
638
+ // once the user presses Play (rca/issue-video-artboard-loop-defaults-on).
639
+ const [timelineLoop, setTimelineLoop] = useState(false);
640
+ const [timelineMuted, setTimelineMuted] = useState(false);
641
+ const [timelineVolume, setTimelineVolume] = useState(1);
642
+ const [timelineHeight, setTimelineHeight] = useState(216);
643
+ // The artboard nearest the viewport centre (reported by canvas-lib on pan) —
644
+ // the Timeline follows THIS, so it redraws as you move across the canvas.
645
+ const [canvasActiveArtboard, setCanvasActiveArtboard] = useState(null);
646
+ // DDR-148 — parsed sequence/keyframe rows for the Timeline (from raw .tsx).
647
+ const [timelineSequences, setTimelineSequences] = useState([]);
648
+ const [timelineAudio, setTimelineAudio] = useState([]);
649
+ // Task 5 — seam transitions between series beats ({ afterIndex, dur }).
650
+ const [timelineTransitions, setTimelineTransitions] = useState([]);
651
+ const [timelineTotal, setTimelineTotal] = useState(0);
652
+ // rca/issue-video-artboard-frame-reset-on-edit — last known playhead, read
653
+ // from the `timeline-comps` handler below (which fires on every comp
654
+ // (re)mount, incl. a ⌘R hard iframe reload) to re-seed the fresh Player
655
+ // instance. A ref, not state, so the handler always sees the latest value
656
+ // without pulling `timelineFrame` into that big message-listener's deps.
657
+ const timelineFrameRef = useRef(0);
658
+ useEffect(() => {
659
+ timelineFrameRef.current = timelineFrame;
660
+ }, [timelineFrame]);
661
+ // The DCArtboard id the timeline scoped to (from parseCompTimeline). Used for
662
+ // /_api/comp-clips + every clip op so the enumerator targets the SAME comp the
663
+ // rows came from — `timelineCompId` is the Player's `videocomp-N` id, which
664
+ // never matches a DCArtboard id and made the enumerator fall back to the wrong
665
+ // comp on a multi-comp canvas (the showreel badge/replace/op mis-scope).
666
+ const [timelineArtboardId, setTimelineArtboardId] = useState(null);
667
+ const timelineArtboardIdRef = useRef(null);
668
+ useEffect(() => {
669
+ timelineArtboardIdRef.current = timelineArtboardId;
670
+ }, [timelineArtboardId]);
671
+ // On a multi-comp canvas the Timeline drives ONE comp: the one mounted in the
672
+ // artboard whose rows the panel is drawing. Resolved by artboard identity
673
+ // (announced by video-comp.tsx), NOT by duration — two comps of equal length
674
+ // made the old duration match return the first artboard's Player, so scrub +
675
+ // playback moved a comp the user wasn't even looking at (issue #75).
676
+ const timelineCompId = useMemo(
677
+ () =>
678
+ resolveCompTarget(activeComps, {
679
+ // Both signals, in confidence order: the artboard the ROW PARSER scoped
680
+ // to (lexical, from the .tsx) then the viewport-active one canvas-lib
681
+ // reports on pan (structural). See resolveCompTarget — when the two
682
+ // disagree, the one that names a comp actually mounted there wins.
683
+ artboardId: [timelineArtboardId, canvasActiveArtboard],
684
+ total: timelineTotal,
685
+ }),
686
+ [activeComps, timelineArtboardId, canvasActiveArtboard, timelineTotal]
687
+ );
688
+ const timelineCompIdRef = useRef(null);
689
+ useEffect(() => {
690
+ timelineCompIdRef.current = timelineCompId;
691
+ }, [timelineCompId]);
692
+ // Frame math (drop position, split, overlay insert) must use the timebase of
693
+ // the comp the Timeline is actually on — `activeComps[0].fps` silently used
694
+ // the first artboard's (issue #75).
695
+ const timelineFps = useMemo(
696
+ () => activeComp(activeComps, timelineCompId)?.fps || 30,
697
+ [activeComps, timelineCompId]
698
+ );
699
+ // feature-enhanced-video-editing (Task 3) — the timeline's single-select model.
700
+ // Holds the selected clip's stableId (NOT a row index — DDR-150), so the
701
+ // selection survives comp-clips refetches, reorders, and external file edits.
702
+ const [timelineSelectedClip, setTimelineSelectedClip] = useState(null);
703
+ // Task 8 — bumped after a concurrent-edit refusal so the source + comp-clips
704
+ // effects refetch ("Timeline changed — reloaded, try again").
705
+ const [timelineRefresh, setTimelineRefresh] = useState(0);
706
+ const timelineOpFailed = useCallback((prefix, msg) => {
707
+ if (/concurrent edit|changed since it was read/i.test(msg || '')) {
708
+ shellToast('Timeline changed — reloaded, try again.');
709
+ setTimelineRefresh((n) => n + 1);
710
+ } else {
711
+ shellToast(`${prefix}: ${msg || 'failed'}`);
712
+ }
713
+ }, []);
714
+ // Phase 31 (DDR-123) — the native ACP chat sidepanel (right dock, native-only).
715
+ const [assistantOpen, setAssistantOpen] = useState(false);
716
+ const [assistantBusy, setAssistantBusy] = useState(false);
717
+ const [assistantUnseen, setAssistantUnseen] = useState(false);
718
+ const assistantOpenRef = useRef(assistantOpen);
719
+ useEffect(() => {
720
+ assistantOpenRef.current = assistantOpen;
721
+ if (assistantOpen) {
722
+ setAssistantUnseen(false); // opening clears the unseen badge
723
+ // Ask for notification permission on a real user gesture (panel open).
724
+ try {
725
+ if (typeof Notification !== 'undefined' && Notification.permission === 'default') {
726
+ Notification.requestPermission();
727
+ }
728
+ } catch {
729
+ /* notifications unavailable */
730
+ }
731
+ }
732
+ }, [assistantOpen]);
733
+ // ChatPanel owns one connection PER CHAT (so chats run in parallel in the
734
+ // background) and reports up here: `onBusyChange` for the menubar pulse, and
735
+ // `onFinished` when any chat's turn ends — badge + notify if you weren't looking.
736
+ const handleAssistantFinished = useCallback(() => {
737
+ if (!assistantOpenRef.current || document.hidden) {
738
+ setAssistantUnseen(true);
739
+ notifyDesktop('Claude finished', 'Your assistant turn is ready in Maude.');
740
+ }
741
+ }, []);
742
+ // DDR-185 — same "you weren't looking" gate as handleAssistantFinished
743
+ // above, fired instead when a chat is PAUSED waiting on the user (a
744
+ // permission prompt or an AskUserQuestion/elicitation form), not just when
745
+ // a turn completes. A stalled turn otherwise gives no signal at all if the
746
+ // window isn't focused. Distinct copy so it doesn't read as "done".
747
+ //
748
+ // Security-review addendum (Finding G): DDR-179/180 already cap concurrent
749
+ // pending requests at 10 permissions + 5 elicitations, so a single
750
+ // adversarial turn can legitimately queue up to 15 DISTINCT approval
751
+ // decisions — each one now fires a real OS Notification, which is exactly
752
+ // the burst that manufactures the "rapid Enter-mashing" precondition
753
+ // DDR-179's own addendum already treats as a security-relevant habituation
754
+ // risk. The in-app badge (setAssistantUnseen) still reflects EVERY new
755
+ // request instantly — only the OS notification itself is rate-limited, so
756
+ // a burst reads as one attention-getting ping, not fifteen.
757
+ const lastAttentionNotifyRef = useRef(0);
758
+ const handleAssistantAttention = useCallback(() => {
759
+ if (!assistantOpenRef.current || document.hidden) {
760
+ setAssistantUnseen(true);
761
+ const now = Date.now();
762
+ if (now - lastAttentionNotifyRef.current < ATTENTION_NOTIFY_COOLDOWN_MS) return;
763
+ lastAttentionNotifyRef.current = now;
764
+ notifyDesktop('Maude needs your input', 'Claude is waiting on an approval or a question in Maude.');
765
+ }
766
+ }, []);
767
+ // Inspector tab is lifted so View ▸ Layers can open the panel ON the Layers
768
+ // tab (the menu item sat disabled as "Phase 12" long after the tab shipped).
769
+ const [inspectorTab, setInspectorTab] = useState('inspect');
770
+ // feature-photo-editor (Task 13) — the annotation-image Photo-tab target,
771
+ // threaded up from the annotation layer's "Edit Photo…" (the annotation model
772
+ // has no DOM selection to ride, unlike an artboard `<img>`). `{ asset, strokeId }`
773
+ // or null. Cleared whenever a normal DOM selection arrives so the two never
774
+ // fight over the panel. The shell-side photo undo stack lives alongside it.
775
+ const [photoSel, setPhotoSel] = useState(null);
776
+ const photoUndoRef = useRef({ undo: [], redo: [] });
777
+ // Bumped by the Cmd+Z/Cmd+Shift+Z photo-undo handler below so the mounted
778
+ // PhotoKnobs (keyed on `asset:photoRev`) remounts and re-fetches the sidecar
779
+ // it just PUT, instead of drifting from its own stale local `edit` state.
780
+ const [photoRev, setPhotoRev] = useState(0);
781
+ // feature-element-editing-robustness Stage C — auto-open the Inspector on the
782
+ // CSS tab when a fresh single selection arrives AND no right panel is already
783
+ // open. Preference-backed (default ON); disable it in the View menu. Refs keep
784
+ // the postMessage selection listener stale-closure-safe.
785
+ const [autoOpenInspector, setAutoOpenInspector] = useState(() => {
786
+ try {
787
+ return localStorage.getItem('maude-auto-open-inspector') !== '0';
788
+ } catch {
789
+ return true;
790
+ }
791
+ });
792
+ const autoOpenInspectorRef = useRef(autoOpenInspector);
793
+ useEffect(() => {
794
+ autoOpenInspectorRef.current = autoOpenInspector;
795
+ try {
796
+ localStorage.setItem('maude-auto-open-inspector', autoOpenInspector ? '1' : '0');
797
+ } catch {
798
+ /* private mode / storage disabled */
799
+ }
800
+ }, [autoOpenInspector]);
801
+ // Whether ANY right-dock panel is open — the auto-open guard reads this ref so
802
+ // it never steals focus from an already-open panel (the user's explicit rule).
803
+ const anyRightPanelOpenRef = useRef(false);
804
+ useEffect(() => {
805
+ anyRightPanelOpenRef.current =
806
+ inspectorOpen || commentsPanelOpen || changesOpen || syncPanelOpen || assistantOpen;
807
+ }, [inspectorOpen, commentsPanelOpen, changesOpen, syncPanelOpen, assistantOpen]);
808
+ // The right dock holds exactly ONE panel (Changes / Inspector / Comments) at
809
+ // a time — opening any panel REPLACES whatever was there. These two helpers
810
+ // are the single source of that invariant; every open/toggle path routes
811
+ // through them. (Before, the three booleans were flipped independently across
812
+ // ~13 call sites and only some closed their siblings, so a panel opened via a
813
+ // path that left a sibling `true` rendered *behind* it under the fixed
814
+ // precedence — looking like the new panel "overlapped" the old one.)
815
+ // feature-configurable-panel-docking — generic, SIDE-AWARE panel management.
816
+ // A slot (left/right) shows one panel at a time, so opening a panel closes any
817
+ // OTHER open panel ON THE SAME SIDE (panels on the other side are independent).
818
+ // A live ref carries the current open + side maps so the callbacks stay stable
819
+ // yet never act on stale state. (The Timeline is a BOTTOM dock, DDR-148, and is
820
+ // NOT part of either slot's mutual-exclusion.)
821
+ const panelStateRef = useRef({ open: {}, side: PANEL_SIDES_DEFAULTS });
822
+ panelStateRef.current = {
823
+ open: {
824
+ tree: sidebarOpen,
825
+ layers: layersOpen,
826
+ inspector: inspectorOpen,
827
+ comments: commentsPanelOpen,
828
+ changes: changesOpen,
829
+ sync: syncPanelOpen,
830
+ assistant: assistantOpen,
831
+ },
832
+ side: panelSide,
833
+ };
834
+ const setPanelOpen = useCallback((id, val) => {
835
+ if (id === 'tree') setSidebarOpen(val);
836
+ else if (id === 'layers') setLayersOpen(val);
837
+ else if (id === 'inspector') setInspectorOpen(val);
838
+ else if (id === 'comments') setCommentsPanelOpen(val);
839
+ else if (id === 'changes') setChangesOpen(val);
840
+ else if (id === 'sync') setSyncPanelOpen(val);
841
+ else if (id === 'assistant') setAssistantOpen(val);
842
+ }, []);
843
+ const sideOf = useCallback(
844
+ (id) => panelStateRef.current.side?.[id] || PANEL_SIDES_DEFAULTS[id],
845
+ []
846
+ );
847
+ const openPanelExclusive = useCallback(
848
+ (id) => {
849
+ const side = sideOf(id);
850
+ setPanelOpen(id, true);
851
+ for (const p of DOCK_PANELS) {
852
+ if (p.id !== id && sideOf(p.id) === side) setPanelOpen(p.id, false);
853
+ }
854
+ },
855
+ [setPanelOpen, sideOf]
856
+ );
857
+ const togglePanel = useCallback(
858
+ (id) => {
859
+ if (panelStateRef.current.open?.[id]) setPanelOpen(id, false);
860
+ else openPanelExclusive(id);
861
+ },
862
+ [openPanelExclusive, setPanelOpen]
863
+ );
864
+ // Legacy name kept for the many call sites; now side-aware (opens `which` and
865
+ // closes only same-side siblings, so a panel moved to the left is unaffected).
866
+ const openRightPanel = openPanelExclusive;
867
+ const toggleRightPanel = togglePanel;
868
+ // feature-element-editing-robustness Stage C (Task C1) — open the Inspector on
869
+ // the CSS tab for a fresh SINGLE selection, but only when nothing is already
870
+ // docked on the right (never override an open Layers/Inspect/Comments panel)
871
+ // and only when the preference is on. Idempotent: once the inspector is open,
872
+ // the `anyRightPanelOpen` guard stops it re-firing on the next selection.
873
+ const maybeAutoOpenInspectorOnSelect = useCallback(
874
+ (sel) => {
875
+ if (!autoOpenInspectorRef.current) return;
876
+ if (viewerMode) return; // Cloud Phase 25 C2 — inspector is edit chrome
877
+ if (!sel || !sel.id) return; // need a stable element id to inspect
878
+ if (anyRightPanelOpenRef.current) return; // don't steal from an open panel
879
+ openRightPanel('inspector');
880
+ setInspectorTab('css');
881
+ },
882
+ [openRightPanel, viewerMode]
883
+ );
884
+ // DDR-148 — the Timeline is a BOTTOM dock, independent of the right rail: it
885
+ // toggles on its own and coexists with Inspector/Changes/Comments/Chat.
886
+ const toggleTimeline = useCallback(() => setTimelineOpen((v) => !v), []);
887
+ const whatsNew = useWhatsNew(MDCC_VERSION);
888
+ // Same tri-state rule as the sign-in bar: hydrating before the shell is
889
+ // known 404s every boot. On desktop (`cloud === null`) the export queue is
890
+ // the LOCAL job runner, always on. In a cloud tab it hydrates only when the
891
+ // cell actually holds a jobs lane (`exportLane === 'remote'`) — a cell
892
+ // without a render service still refuses `/_api/export-jobs` outright
893
+ // (DDR-209 D1 posture, now lane-scoped by feature-cloud-export-render-workers).
894
+ const exportCenter = useExportCenter({
895
+ enabled: cfg.cloud === null || cfg.exportLane === 'remote',
896
+ });
897
+ // Phase 29 (E4) — first-run onboarding wizard. The native shell boots a minimal
898
+ // "welcome" project on first launch; we ask it whether this is a first run and, if
899
+ // so, show the wizard OVER the (empty) canvas browser. Completing any door switches
900
+ // the sidecar to a real project (the webview reloads → first-run is then false).
901
+ const [firstRun, setFirstRun] = useState(false);
902
+ // Offer the collab "rychlý kurz" once, AFTER onboarding (native app, not first run,
903
+ // not yet seen). A returning user who already took it isn't re-nudged.
904
+ const [collabNudge, setCollabNudge] = useState(false);
905
+ useEffect(() => {
906
+ if (!isNativeApp()) return undefined;
907
+ let alive = true;
908
+ appIsFirstRun()
909
+ .then((v) => {
910
+ if (!alive) return;
911
+ setFirstRun(!!v);
912
+ if (!v && !readBoolStore(COLLAB_TOUR_STORE, false)) setCollabNudge(true);
913
+ })
914
+ .catch(() => {});
915
+ return () => {
916
+ alive = false;
917
+ };
918
+ }, []);
919
+ const markCollabSeen = useCallback(() => {
920
+ setCollabNudge(false);
921
+ try {
922
+ localStorage.setItem(COLLAB_TOUR_STORE, '1');
923
+ } catch {}
924
+ }, []);
925
+ // Phase 32 (Task 1) — auto-update. The native shell downloads + stages a newer
926
+ // build in the background and emits `update-ready`; we surface a non-blocking
927
+ // banner. Native-only (the web studio is updated by its own deploy).
928
+ const [updateReady, setUpdateReady] = useState(null);
929
+ useEffect(() => {
930
+ if (!isNativeApp()) return undefined;
931
+ let un;
932
+ onUpdateReady((p) => setUpdateReady(p && typeof p === 'object' ? p : {}))
933
+ .then((fn) => {
934
+ un = fn;
935
+ })
936
+ .catch(() => {});
937
+ return () => {
938
+ try {
939
+ un?.();
940
+ } catch {}
941
+ };
942
+ }, []);
943
+ const [tourSteps, setTourSteps] = useState(null);
944
+ const [usageNudge, setUsageNudge] = useState(() => !readBoolStore(USAGE_TOUR_STORE, false));
945
+ const startTour = useCallback((steps) => {
946
+ setTourSteps(Array.isArray(steps) && steps.length ? steps : null);
947
+ }, []);
948
+ // Guided-tour bus — the overlay calls setup() before each step to put the shell
949
+ // into the state the step spotlights: open a canvas, open the Inspector, switch
950
+ // its tab. The canvas iframe is cross-origin (DDR-054) so the tour can't select
951
+ // an element for the user; requireSelection steps instead wait for a real
952
+ // ⌘-click. Plain object (the overlay refs it), so per-render churn is harmless.
953
+ const tourBus = {
954
+ setup: (step) => {
955
+ if (!step) return;
956
+ if ((step.canvas || step.requireSelection) && tabs.length === 0) {
957
+ openPanelExclusive('tree');
958
+ setTimeout(() => {
959
+ try {
960
+ document.querySelector('.st-sidebar [data-testid^="canvas-row-"]')?.click();
961
+ } catch {}
962
+ }, 80);
963
+ }
964
+ if (step.inspector || step.tab || step.requireSelection) openRightPanel('inspector');
965
+ if (step.tab) setInspectorTab(step.tab);
966
+ // Phase 29 (E4) collab tour — open the Changes panel so the Save / Publish /
967
+ // Get-latest controls the action steps spotlight actually exist to anchor on.
968
+ if (step.changes) openRightPanel('changes');
969
+ },
970
+ };
971
+ const markUsageSeen = useCallback(() => {
972
+ setUsageNudge(false);
973
+ try {
974
+ localStorage.setItem(USAGE_TOUR_STORE, '1');
975
+ } catch {}
976
+ }, []);
977
+ const [annotationsVisible, setAnnotationsVisible] = useState(() =>
978
+ readBoolStore(ANNOT_STORE, true)
979
+ );
980
+ // feature-unified-settings-modal — gate the disk-write effect until the boot
981
+ // GET /_api/ui-prefs has reconciled (disk-wins), so we never clobber a stored
982
+ // pref with the localStorage/default value on the first render.
983
+ const [uiPrefsHydrated, setUiPrefsHydrated] = useState(false);
984
+ // Canvas-chrome visibility (View menu). minimap + zoom-controls are
985
+ // persistent prefs broadcast to every open canvas iframe; presentMode is a
986
+ // non-destructive "hide ALL chrome + shell, artboards only" overlay with an
987
+ // Esc / floating-pill escape hatch back to the chrome.
988
+ const [minimapVisible, setMinimapVisible] = useState(() => readBoolStore(MINIMAP_STORE, false));
989
+ const [zoomCtlVisible, setZoomCtlVisible] = useState(() => readBoolStore(ZOOMCTL_STORE, false));
990
+ const [presentMode, setPresentMode] = useState(false);
991
+ // feature-2-print-artboards T3 — "Show print guides". Per-CANVAS persisted
992
+ // (view.json `overlays.print`, via /_api/canvas-meta), not a global
993
+ // localStorage pref like minimap/zoomctl — mirrors the foundation's
994
+ // `overlays.guides` lane. Re-read whenever the active canvas changes (see
995
+ // the activeArtboards effect below); sent only to the active iframe.
996
+ const [printGuidesVisible, setPrintGuidesVisible] = useState(false);
997
+ // P2/P3 (Plan C) — top-bar live state. (Zoom lives in the canvas toolbar pill,
998
+ // so the top bar no longer mirrors it.)
999
+ // activeArtboards — real artboard count of the open canvas, read from its
1000
+ // `<canvas>.meta.json` sidecar (shell-side, no iframe dep).
1001
+ // gitUser — local user (name/initials) for the menubar presence avatar.
1002
+ // agentActive — transient flag set on `ai-activity`, cleared after idle, so
1003
+ // the menubar shows a live agent avatar while Claude edits.
1004
+ const [activeArtboards, setActiveArtboards] = useState(0);
1005
+ const [gitUser, setGitUser] = useState(null);
1006
+ const [agentActive, setAgentActive] = useState(false);
1007
+ const agentIdleRef = useRef(null);
1008
+ const wsRef = useRef(null);
1009
+ const iframesRef = useRef(new Map());
1010
+
1011
+ // THE CANVAS CAPABILITY OUTLIVES NO TAB (cloud only). It expires 15 minutes
1012
+ // after the proxy minted it (render-token.mjs) and cannot be revoked, so it
1013
+ // stays short — which left every cloud tab open longer than that with
1014
+ // canvases that stopped updating: a teammate's edit re-imports the canvas
1015
+ // module, and the canvas origin answered 401. Re-mint it well inside the
1016
+ // lifetime (every `/_config` answer carries a fresh one), hand it to each
1017
+ // open canvas, and let new frames be built with it. On waking a tab that
1018
+ // slept past the cadence, do it at once. Desktops have no capability and
1019
+ // never start the timer.
1020
+ useEffect(() => {
1021
+ if (!cfg?.canvasToken) return undefined;
1022
+ let stopped = false;
1023
+ let timer = null;
1024
+ let dueAt = 0;
1025
+ const schedule = (token) => {
1026
+ clearTimeout(timer);
1027
+ const delay = canvasTokenRefreshDelay(token);
1028
+ dueAt = Date.now() + delay;
1029
+ timer = setTimeout(refresh, delay);
1030
+ };
1031
+ async function refresh() {
1032
+ let token = null;
1033
+ try {
1034
+ const res = await fetch('/_config', { cache: 'no-store', credentials: 'same-origin' });
1035
+ if (res.ok) token = (await res.json())?.canvasToken;
1036
+ } catch {
1037
+ /* retried below; the current capability may still be valid */
1038
+ }
1039
+ if (stopped) return;
1040
+ if (typeof token !== 'string' || !token) {
1041
+ clearTimeout(timer);
1042
+ dueAt = Date.now() + 30_000;
1043
+ timer = setTimeout(refresh, 30_000);
1044
+ return;
1045
+ }
1046
+ setLiveCanvasToken(token);
1047
+ // To the canvas origin only, never '*': a frame the canvas content
1048
+ // navigated elsewhere must not be handed the capability.
1049
+ const target = canvasTarget();
1050
+ if (target) {
1051
+ for (const el of iframesRef.current.values()) {
1052
+ try {
1053
+ el.contentWindow?.postMessage({ dgn: 'canvas-cap', t: token }, target);
1054
+ } catch {}
1055
+ }
1056
+ }
1057
+ schedule(token);
1058
+ return token;
1059
+ }
1060
+ function canvasTarget() {
1061
+ try {
1062
+ return new URL(cfg.canvasOrigin, location.href).origin;
1063
+ } catch {
1064
+ return null;
1065
+ }
1066
+ }
1067
+ // A FRAME WHOSE OWN DOCUMENT WAS REFUSED AS EXPIRED. The re-mint above
1068
+ // reaches a running canvas's fetches, but not a frame that re-navigates
1069
+ // itself (a hard reload, a laptop that slept past the cadence): that load
1070
+ // carries the URL it was built with, and the canvas origin answers with a
1071
+ // small page that asks us for a fresh capability (hub studio-proxy). Mint
1072
+ // one and point just that frame at it — no "reload the project".
1073
+ let reviving = false;
1074
+ async function onExpired(e) {
1075
+ if (e.data?.dgn !== 'canvas-expired' || e.origin !== canvasTarget() || reviving) return;
1076
+ reviving = true;
1077
+ try {
1078
+ const token = await refresh();
1079
+ if (!token) return;
1080
+ for (const el of iframesRef.current.values()) {
1081
+ if (el.contentWindow === e.source) el.src = withCanvasToken(el.src, token);
1082
+ }
1083
+ } finally {
1084
+ reviving = false;
1085
+ }
1086
+ }
1087
+ window.addEventListener('message', onExpired);
1088
+ schedule(cfg.canvasToken);
1089
+ // A background tab's timers are throttled; one woken past its due time
1090
+ // re-mints at once rather than on the throttled tick.
1091
+ const onVisible = () => {
1092
+ if (document.visibilityState === 'visible' && Date.now() >= dueAt) refresh();
1093
+ };
1094
+ document.addEventListener('visibilitychange', onVisible);
1095
+ return () => {
1096
+ stopped = true;
1097
+ clearTimeout(timer);
1098
+ document.removeEventListener('visibilitychange', onVisible);
1099
+ window.removeEventListener('message', onExpired);
1100
+ };
1101
+ }, [cfg?.canvasToken, cfg?.canvasOrigin]);
1102
+
1103
+ // Phase 5.1 — postMessage bridge from menubar dropdowns to the canvas iframe.
1104
+ // The canvas-shell listens for these `dgn:*` messages and dispatches into the
1105
+ // matching local provider (annotations visibility / both selection stores /
1106
+ // tool mode). Mirrors the existing `force-clear` / `select-clear` channel.
1107
+ const postToActiveCanvas = useCallback(
1108
+ (payload) => {
1109
+ const el = activePath ? iframesRef.current.get(activePath) : null;
1110
+ if (!el || !el.contentWindow) return;
1111
+ try {
1112
+ el.contentWindow.postMessage(payload, '*');
1113
+ } catch {}
1114
+ },
1115
+ [activePath]
1116
+ );
1117
+
1118
+ // DDR-231 (hybrid export lanes) — ask the active canvas iframe to capture
1119
+ // its own artboards (canvas-lib's useExportCaptureBridge) and hand back the
1120
+ // blobs. The shell can't reach the cross-origin canvas DOM, and the sandbox
1121
+ // omits allow-downloads, so this is the division of labour: the CANVAS
1122
+ // captures (it renders the pixels), the SHELL downloads. Resolves with
1123
+ // [{ name, type, blob }]; rejects on canvas error or timeout.
1124
+ const browserCaptureSeq = useRef(0);
1125
+ const captureFromCanvas = useCallback(
1126
+ ({ format, artboardIds = null, scale = 1, onProgress, timeoutMs = 120_000 }) =>
1127
+ new Promise((resolve, reject) => {
1128
+ const el = activePath ? iframesRef.current.get(activePath) : null;
1129
+ if (!el || !el.contentWindow) {
1130
+ reject(new Error('no active canvas to capture'));
1131
+ return;
1132
+ }
1133
+ const cw = el.contentWindow;
1134
+ browserCaptureSeq.current += 1;
1135
+ const id = `cap-${Date.now().toString(36)}-${browserCaptureSeq.current}`;
1136
+ let settled = false;
1137
+ const finish = (fn, arg) => {
1138
+ if (settled) return;
1139
+ settled = true;
1140
+ window.removeEventListener('message', onMsg);
1141
+ clearTimeout(timer);
1142
+ fn(arg);
1143
+ };
1144
+ const onMsg = (e) => {
1145
+ // Only answers from the iframe we asked — a message with a matching
1146
+ // id from any other window is ignored.
1147
+ if (e.source !== cw) return;
1148
+ const m = e.data;
1149
+ if (!m || m.id !== id) return;
1150
+ if (m.dgn === 'export-capture-progress') onProgress?.(m.current, m.total);
1151
+ else if (m.dgn === 'export-capture-done')
1152
+ finish(resolve, Array.isArray(m.items) ? m.items : []);
1153
+ else if (m.dgn === 'export-capture-error')
1154
+ finish(reject, new Error(m.message || 'capture failed'));
1155
+ };
1156
+ const timer = setTimeout(
1157
+ () => finish(reject, new Error('capture timed out — the canvas did not answer')),
1158
+ timeoutMs
1159
+ );
1160
+ window.addEventListener('message', onMsg);
1161
+ try {
1162
+ cw.postMessage({ dgn: 'export-capture', id, format, artboardIds, scale }, '*');
1163
+ } catch (err) {
1164
+ finish(reject, err);
1165
+ }
1166
+ }),
1167
+ [activePath]
1168
+ );
1169
+ return {
1170
+ activeArtboards, activeComps, activePath, addressMode, agentActive, agentIdleRef,
1171
+ annotationsVisible, assistantBusy, assistantOpen, assistantUnseen, autoOpenInspector, bodyRef,
1172
+ brandUploadOpen, canvasActiveArtboard, canvasError, canvasReloadNonce, captureFromCanvas,
1173
+ cellManaged, cfg, changesOpen, cloudLinkedHub, cloudManaged, collabNudge, commentsByFile,
1174
+ commentsFilter, commentsPanelOpen, componentMap, cpMode, diffTarget, dragSide, editScope,
1175
+ exportCenter, exportDialog, figmaImportOpen, firstRun, focusedCommentId, generateOpen,
1176
+ gitLifecycle, gitStatus, gitUser, groups, handleAssistantAttention, handleAssistantFinished,
1177
+ helpOpen, iframesRef, inspectorOpen, inspectorTab, introOpen, lastLayersTreeRef,
1178
+ lastLocalSelectRef, layersBusyRef, layersBusyTimerRef, layersMode, layersOpen, layersTree,
1179
+ loadServerConfig, loadedPath, loadingPath, localProjectName, markCollabSeen, markUsageSeen,
1180
+ maybeAutoOpenInspectorOnSelect, minimapVisible, onIframeLoad, onPreview, openMenu,
1181
+ openPanelExclusive, openRightPanel, paletteOpen, panelSide, pendingReorderRef, photoRev,
1182
+ photoSel, photoUndoRef, postToActiveCanvas, presentMode, previewPath, previousAddressPath,
1183
+ printGuidesVisible, project, quickSetupOpen, readinessOpen, remoteSync, reorderLayerRef,
1184
+ reportBugOpen, repositionElementRef, resizeElementRef, rpSize, savingIsManaged,
1185
+ savingIsManagedRef, sbSize, scheduleArtboardResync, scheduleHaloRestore, search,
1186
+ sectionsExpanded, selected, selectedRef, setActiveArtboards, setActiveComps, setActivePath,
1187
+ setAgentActive, setAnnotationsVisible, setAssistantBusy, setAssistantOpen, setAutoOpenInspector,
1188
+ setBrandUploadOpen, setCanvasActiveArtboard, setCanvasError, setCanvasReloadNonce, setCfg,
1189
+ setChangesOpen, setCloudLinkedHub, setCommentsByFile, setCommentsFilter, setCpMode,
1190
+ setDiffTarget, setDragSide, setExportDialog, setFigmaImportOpen, setFocusedCommentId,
1191
+ setGenerateOpen, setGitLifecycle, setGitStatus, setGitUser, setGroups, setHelpOpen,
1192
+ setInspectorOpen, setInspectorTab, setIntroOpen, setLayersMode, setLayersOpen, setLayersTree,
1193
+ setLoadedPath, setLoadingPath, setLocalProjectName, setMinimapVisible, setOpenMenu,
1194
+ setPaletteOpen, setPanelSide, setPhotoRev, setPhotoSel, setPresentMode, setPreviewPath,
1195
+ setPrintGuidesVisible, setProject, setQuickSetupOpen, setReadinessOpen, setRemoteSync,
1196
+ setReportBugOpen, setSearch, setSelected, setSettingsOpen, setShareDialog, setShortcutsOpen,
1197
+ setShowHidden, setSyncPanelOpen, setSyncStatus, setSystemData, setTabs, setTheme,
1198
+ setTimelineArtboardId, setTimelineAudio, setTimelineFrame, setTimelineHeight, setTimelineLoop,
1199
+ setTimelineMuted, setTimelineOpen, setTimelinePlaying, setTimelineSelectedClip,
1200
+ setTimelineSequences, setTimelineTotal, setTimelineTransitions, setTimelineVolume, setTourSteps,
1201
+ setTreeLoadFailures, setTreeLoaded, setUiPrefsHydrated, setUpdateReady, setWsConnected,
1202
+ setZoomCtlVisible, settingsOpen, settlePendingSelectionRef, setupReadiness, shareDialog,
1203
+ shortcutsOpen, showHidden, sidebarOpen, startTour, syncPanelOpen, syncStatus, systemData, tabs,
1204
+ theme, timelineArtboardId, timelineArtboardIdRef, timelineAudio, timelineCompId,
1205
+ timelineCompIdRef, timelineFps, timelineFrame, timelineFrameRef, timelineHeight, timelineLoop,
1206
+ timelineMuted, timelineOpFailed, timelineOpen, timelinePlaying, timelineRefresh,
1207
+ timelineSelectedClip, timelineSequences, timelineTotal, timelineTransitions, timelineVolume,
1208
+ togglePanel, toggleRightPanel, toggleTimeline, tourBus, tourSteps, treeExp, treeLoadFailures,
1209
+ treeLoaded, uiPrefsHydrated, unsavedCount, updateReady, updateTreeExp, usageNudge, viewerMode,
1210
+ whatsNew, wsConnected, wsRef, zoomCtlVisible
1211
+ };
1212
+ }