dsh-workflow-canvas 1.6.0 → 1.6.1

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.
package/client.js CHANGED
@@ -8,8 +8,51 @@ window.__ModuleLoader__.load({
8
8
  const useState = React.useState;
9
9
  const useRef = React.useRef;
10
10
  const useEffect = React.useEffect;
11
+ const useMemo = React.useMemo || ((fn) => fn());
11
12
  const Component = React.Component;
12
13
 
14
+ /** Isolated 1s elapsed timer so live ticks never re-render the full canvas tree. */
15
+ function LiveElapsedText({ active, startedAt, endedAt, style }) {
16
+ const [now, setNow] = useState(() => Date.now());
17
+ useEffect(() => {
18
+ if (!active) return undefined;
19
+ setNow(Date.now());
20
+ const id = setInterval(() => {
21
+ if (typeof document === 'undefined' || document.visibilityState !== 'hidden') {
22
+ setNow(Date.now());
23
+ }
24
+ }, 1000);
25
+ return () => clearInterval(id);
26
+ }, [active, startedAt]);
27
+ if (typeof startedAt !== 'number') return null;
28
+ const ms = Math.max(0, (typeof endedAt === 'number' ? endedAt : now) - startedAt);
29
+ return h('span', { style }, ' · ' + formatDurationMs(ms));
30
+ }
31
+
32
+ /**
33
+ * Source-verified DSH 0.2.2-rc.5 panel visibility check:
34
+ * - Tab/session switches set `hidden` (`display: none` -> `offsetParent === null`),
35
+ * - Collapsing the right sidebar uses `transform + visibility: hidden` (`offsetParent !== null`),
36
+ * while `[data-dockkit-content]` sets `aria-hidden="true"` and `inert = true` across ALL 3 hidden states.
37
+ */
38
+ function isDockElementHidden(el) {
39
+ if (!el) return false;
40
+ if (el.offsetParent === null) return true;
41
+ if (typeof el.closest === 'function') {
42
+ const dockHost = el.closest('[data-dockkit-content]');
43
+ if (dockHost) {
44
+ if (typeof dockHost.getAttribute === 'function' && dockHost.getAttribute('aria-hidden') === 'true') return true;
45
+ if (dockHost.inert === true) return true;
46
+ }
47
+ }
48
+ if (typeof el.checkVisibility === 'function') {
49
+ try {
50
+ if (!el.checkVisibility({ visibilityProperty: true, contentVisibilityAuto: true })) return true;
51
+ } catch (_e) { /* ignore older engines */ }
52
+ }
53
+ return false;
54
+ }
55
+
13
56
  /** Resolved lazily so a missing namespace can never fail plugin load. */
14
57
  let workspaceFilesService = null;
15
58
  function resolveWorkspaceFiles(ctx) {
@@ -1456,6 +1499,8 @@ window.__ModuleLoader__.load({
1456
1499
  waitingLead,
1457
1500
  haltedReason: (sum && sum.haltedReason) || '',
1458
1501
  maxParallel: (sum && typeof sum.maxParallel === 'number') ? sum.maxParallel : null,
1502
+ startedAt,
1503
+ endedAt,
1459
1504
  elapsedMs,
1460
1505
  totalCount: rows.length,
1461
1506
  doneCount,
@@ -2834,7 +2879,8 @@ window.__ModuleLoader__.load({
2834
2879
  }
2835
2880
  }
2836
2881
 
2837
- function storageKey(sessionId) { return STORAGE_PREFIX + (sessionId || '__global__');
2882
+ function storageKey(sessionId) {
2883
+ return STORAGE_PREFIX + (sessionId || '__global__');
2838
2884
  }
2839
2885
 
2840
2886
  function loadDoc(sessionId) {
@@ -2849,13 +2895,60 @@ window.__ModuleLoader__.load({
2849
2895
  }
2850
2896
  }
2851
2897
 
2898
+ const MAX_STORED_CANVAS_SESSIONS = 80;
2899
+ const RESERVED_STORAGE_SUFFIXES = new Set(['presets', 'direction', 'shortcuts', 'lang', 'cut', 'fx', 'maxParallel']);
2900
+ let storagePrunedOnce = false;
2901
+
2902
+ /** Evict oldest session canvas entries from localStorage so months of chats never fill quota. */
2903
+ function pruneSessionStorage(keepKey, maxSessions = MAX_STORED_CANVAS_SESSIONS) {
2904
+ try {
2905
+ const ls = window.localStorage;
2906
+ if (!ls || typeof ls.length !== 'number' || typeof ls.key !== 'function' || typeof ls.removeItem !== 'function') return 0;
2907
+ const entries = [];
2908
+ for (let i = 0; i < ls.length; i += 1) {
2909
+ const k = ls.key(i);
2910
+ if (!k || !k.startsWith(STORAGE_PREFIX)) continue;
2911
+ const suffix = k.slice(STORAGE_PREFIX.length);
2912
+ if (RESERVED_STORAGE_SUFFIXES.has(suffix)) continue;
2913
+ if (k === keepKey) continue;
2914
+ let at = 0;
2915
+ try {
2916
+ const parsed = JSON.parse(ls.getItem(k) || 'null');
2917
+ if (parsed && typeof parsed.at === 'number') at = parsed.at;
2918
+ } catch (_e) { /* treat corrupt entry as oldest */ }
2919
+ entries.push({ key: k, at });
2920
+ }
2921
+ const limit = Math.max(1, maxSessions - (keepKey ? 1 : 0));
2922
+ if (entries.length <= limit) return 0;
2923
+ entries.sort((a, b) => a.at - b.at);
2924
+ const dropCount = entries.length - limit;
2925
+ for (let i = 0; i < dropCount; i += 1) {
2926
+ try { ls.removeItem(entries[i].key); } catch (_e) { /* ignore */ }
2927
+ }
2928
+ return dropCount;
2929
+ } catch (_e) {
2930
+ return 0;
2931
+ }
2932
+ }
2933
+
2852
2934
  function saveDoc(sessionId, doc, stamp) {
2935
+ const key = storageKey(sessionId);
2936
+ const serialized = JSON.stringify({ ...doc, at: typeof stamp === 'number' ? stamp : Date.now() });
2853
2937
  try {
2854
- /** Stamp every local edit so a stale generated canvas cannot overwrite it. */
2855
- const stamped = { ...doc, at: typeof stamp === 'number' ? stamp : Date.now() };
2856
- window.localStorage.setItem(storageKey(sessionId), JSON.stringify(stamped));
2938
+ const ls = window.localStorage;
2939
+ if (!storagePrunedOnce || (ls && typeof ls.length === 'number' && ls.length > MAX_STORED_CANVAS_SESSIONS + 16)) {
2940
+ storagePrunedOnce = true;
2941
+ pruneSessionStorage(key);
2942
+ }
2943
+ ls.setItem(key, serialized);
2857
2944
  } catch (_e) {
2858
- /* storage unavailable */
2945
+ // Retry once after evicting older sessions in case QuotaExceededError triggered.
2946
+ try {
2947
+ pruneSessionStorage(key, 30);
2948
+ window.localStorage.setItem(key, serialized);
2949
+ } catch (_retryErr) {
2950
+ /* storage unavailable */
2951
+ }
2859
2952
  }
2860
2953
  }
2861
2954
 
@@ -3051,12 +3144,64 @@ window.__ModuleLoader__.load({
3051
3144
  const skipDirtyOnce = useRef(false);
3052
3145
  const staleChildIds = useRef(new Set());
3053
3146
 
3147
+ // Debounce localStorage persistence so high-frequency node drags & typing do not
3148
+ // synchronously serialize JSON on every pointer pixel; skip initial mount write
3149
+ // (preventing untouched tabs from polluting localStorage or stamping over pending
3150
+ // Host-generated canvases) and track `lastLocalEditAtRef` immediately so a remote
3151
+ // poll during the 250ms window can never clobber an unflushed local edit.
3152
+ const pendingSaveRef = useRef(null);
3153
+ const didInitSaveRef = useRef(false);
3154
+ const lastLocalEditAtRef = useRef(initial && typeof initial.at === 'number' ? initial.at : 0);
3054
3155
  useEffect(() => {
3156
+ if (!didInitSaveRef.current) {
3157
+ didInitSaveRef.current = true;
3158
+ return undefined;
3159
+ }
3055
3160
  const stamp = applyStamp.current;
3056
3161
  applyStamp.current = null;
3057
- saveDoc(sessionId, { nodes, edges, enabled, direction }, stamp === null ? undefined : stamp);
3162
+ const payload = { nodes, edges, enabled, direction };
3163
+ if (pendingSaveRef.current && pendingSaveRef.current.timer) {
3164
+ clearTimeout(pendingSaveRef.current.timer);
3165
+ }
3166
+ const flush = () => {
3167
+ const rec = pendingSaveRef.current;
3168
+ if (!rec) return;
3169
+ if (rec.timer) clearTimeout(rec.timer);
3170
+ pendingSaveRef.current = null;
3171
+ saveDoc(rec.sessionId, rec.payload, rec.stamp);
3172
+ };
3173
+ if (stamp !== null) {
3174
+ lastLocalEditAtRef.current = Math.max(lastLocalEditAtRef.current, stamp);
3175
+ pendingSaveRef.current = null;
3176
+ saveDoc(sessionId, payload, stamp);
3177
+ return undefined;
3178
+ }
3179
+ const editAt = Date.now();
3180
+ lastLocalEditAtRef.current = editAt;
3181
+ const timer = setTimeout(flush, 250);
3182
+ pendingSaveRef.current = { sessionId, payload, stamp: editAt, timer };
3183
+ return undefined;
3058
3184
  }, [sessionId, nodes, edges, enabled, direction]);
3059
3185
 
3186
+ useEffect(() => {
3187
+ const flushNow = () => {
3188
+ const rec = pendingSaveRef.current;
3189
+ if (!rec) return;
3190
+ if (rec.timer) clearTimeout(rec.timer);
3191
+ pendingSaveRef.current = null;
3192
+ saveDoc(rec.sessionId, rec.payload, rec.stamp);
3193
+ };
3194
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
3195
+ window.addEventListener('beforeunload', flushNow);
3196
+ }
3197
+ return () => {
3198
+ if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
3199
+ window.removeEventListener('beforeunload', flushNow);
3200
+ }
3201
+ flushNow();
3202
+ };
3203
+ }, [sessionId]);
3204
+
3060
3205
  // Plan signature excludes visual (x, y) coordinates so dragging nodes does
3061
3206
  // not trigger false "unsaved changes" warnings; `skipDirtyOnce` suppresses
3062
3207
  // the dirty flag when applying a canvas written by the Host itself.
@@ -3076,7 +3221,7 @@ window.__ModuleLoader__.load({
3076
3221
  skipDirtyOnce.current = false;
3077
3222
  return;
3078
3223
  }
3079
- if (!enabled) return;
3224
+ if (!enabled || nodeDrag.current) return;
3080
3225
  const sig = planSig(true, nodes, edges);
3081
3226
  if (lastSync.current && sig === lastSync.current) {
3082
3227
  setDirty(false);
@@ -3331,8 +3476,12 @@ window.__ModuleLoader__.load({
3331
3476
  // Sync the moment a user message starts a turn, so this turn's tool call
3332
3477
  // already sees the latest canvas. Falls back to the turn end if the start
3333
3478
  // edge was missed; `dirty` clears on success so only one fires.
3334
- const liveRef = useRef({ enabled, dirty, pushPlan });
3335
- liveRef.current = { enabled, dirty, pushPlan };
3479
+ // Never auto-sync while a workflow is running or paused at Lead (`need-lead`),
3480
+ // otherwise replying to approve a Lead step after a minor canvas tweak would
3481
+ // trigger `/canvas-sync` and wipe the paused run progress.
3482
+ const runStatusForSync = runState && typeof runState.status === 'string' ? runState.status : '';
3483
+ const liveRef = useRef({ enabled, dirty, pushPlan, runStatus: runStatusForSync });
3484
+ liveRef.current = { enabled, dirty, pushPlan, runStatus: runStatusForSync };
3336
3485
 
3337
3486
  useEffect(() => {
3338
3487
  const face = sessionFace(sessionId);
@@ -3344,7 +3493,8 @@ window.__ModuleLoader__.load({
3344
3493
  try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
3345
3494
  if (running !== wasRunning) {
3346
3495
  const live = liveRef.current;
3347
- if (live.enabled && live.dirty) live.pushPlan(true);
3496
+ const runBusyOrPaused = live.runStatus === 'running' || live.runStatus === 'need-lead';
3497
+ if (live.enabled && live.dirty && !runBusyOrPaused) live.pushPlan(true);
3348
3498
  }
3349
3499
  wasRunning = running;
3350
3500
  };
@@ -3449,16 +3599,20 @@ window.__ModuleLoader__.load({
3449
3599
  const stop = () => { if (timer) { clearInterval(timer); timer = null; } };
3450
3600
  let wasRunning = false;
3451
3601
  try { wasRunning = Boolean(face.getSnapshot().running); } catch (_e) { wasRunning = false; }
3602
+ const readIfVisible = () => {
3603
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
3604
+ read();
3605
+ };
3452
3606
  setSessionRunning(wasRunning);
3453
3607
  read();
3454
- if (wasRunning) timer = setInterval(read, 700);
3608
+ if (wasRunning) timer = setInterval(readIfVisible, 700);
3455
3609
  const onSnapshot = () => {
3456
3610
  let running = false;
3457
3611
  try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
3458
3612
  const finished = !running && wasRunning;
3459
3613
  wasRunning = running;
3460
3614
  setSessionRunning(running);
3461
- if (running && !timer) { read(); timer = setInterval(read, 700); }
3615
+ if (running && !timer) { read(); timer = setInterval(readIfVisible, 700); }
3462
3616
  if (!running && timer) { stop(); read(); }
3463
3617
  if (finished && typeof sessions.refreshProjections === 'function') {
3464
3618
  Promise.resolve(sessions.refreshProjections(sessionId)).then(read, () => {});
@@ -4457,8 +4611,10 @@ window.__ModuleLoader__.load({
4457
4611
  setAddMenu, setCtxMenu, setLoopEditEdgeId, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setSummaryOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
4458
4612
  };
4459
4613
  const summaryIsLive = Boolean(runState && (runState.status === 'running' || runState.status === 'need-lead'));
4614
+ // Only tick root `summaryNow` while the Run Summary modal is actually open;
4615
+ // the bottom-left pill uses its own isolated `LiveElapsedText` timer so the canvas stays idle.
4460
4616
  useEffect(() => {
4461
- if (!summaryIsLive) return undefined;
4617
+ if (!summaryIsLive || !summaryOpen) return undefined;
4462
4618
  setSummaryNow(Date.now());
4463
4619
  const timer = setInterval(() => setSummaryNow(Date.now()), 1000);
4464
4620
  return () => clearInterval(timer);
@@ -4470,6 +4626,8 @@ window.__ModuleLoader__.load({
4470
4626
  return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
4471
4627
  };
4472
4628
  const onKey = (ev) => {
4629
+ // Ignore IME composition events (e.g. pressing Escape/Enter while selecting Chinese candidates).
4630
+ if (ev.isComposing || ev.keyCode === 229) return;
4473
4631
  const act = keyActionsRef.current;
4474
4632
  if (!act) return;
4475
4633
  if (act.recordingAction) {
@@ -4582,11 +4740,43 @@ window.__ModuleLoader__.load({
4582
4740
  return () => window.removeEventListener('keydown', onKey);
4583
4741
  }, []);
4584
4742
 
4743
+ // Attach drag listeners once per drag gesture (never churn on marquee/pending pixels)
4744
+ // and coalesce pointer moves to one animation frame for 120Hz+/high-DPI mice.
4745
+ const dragHandlersRef = useRef({ move: null, up: null });
4585
4746
  useEffect(() => {
4586
4747
  if (!dragging) return undefined;
4587
- const move = (ev) => onCanvasMove(ev);
4588
- const up = (ev) => onCanvasUp(ev);
4748
+ let rafId = 0;
4749
+ let queuedEv = null;
4750
+ const cancelRaf = () => {
4751
+ if (rafId && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(rafId);
4752
+ rafId = 0;
4753
+ queuedEv = null;
4754
+ };
4755
+ const move = (ev) => {
4756
+ queuedEv = ev;
4757
+ if (typeof requestAnimationFrame !== 'function') {
4758
+ const hdl = dragHandlersRef.current.move;
4759
+ if (hdl) hdl(ev);
4760
+ return;
4761
+ }
4762
+ if (rafId) return;
4763
+ rafId = requestAnimationFrame(() => {
4764
+ rafId = 0;
4765
+ const latest = queuedEv;
4766
+ queuedEv = null;
4767
+ const hdl = dragHandlersRef.current.move;
4768
+ if (latest && hdl) hdl(latest);
4769
+ });
4770
+ };
4771
+ const up = (ev) => {
4772
+ const latest = queuedEv;
4773
+ cancelRaf();
4774
+ if (latest && dragHandlersRef.current.move) dragHandlersRef.current.move(latest);
4775
+ const hdl = dragHandlersRef.current.up;
4776
+ if (hdl) hdl(ev);
4777
+ };
4589
4778
  const cancelDrag = () => {
4779
+ cancelRaf();
4590
4780
  panDrag.current = null;
4591
4781
  nodeDrag.current = null;
4592
4782
  rightClickRef.current = null;
@@ -4604,11 +4794,12 @@ window.__ModuleLoader__.load({
4604
4794
  window.addEventListener('mouseup', up);
4605
4795
  window.addEventListener('blur', cancelDrag);
4606
4796
  return () => {
4797
+ cancelRaf();
4607
4798
  window.removeEventListener('mousemove', move);
4608
4799
  window.removeEventListener('mouseup', up);
4609
4800
  window.removeEventListener('blur', cancelDrag);
4610
4801
  };
4611
- }, [dragging, marquee, pending]);
4802
+ }, [dragging]);
4612
4803
 
4613
4804
  const onCanvasDown = (e) => {
4614
4805
  if (e.button === 2) {
@@ -4767,8 +4958,14 @@ window.__ModuleLoader__.load({
4767
4958
  }
4768
4959
  }
4769
4960
  if (cutPath.length) { setCutPath([]); setCutVictims([]); }
4961
+ // Recompute drop coordinates directly from the mouseup event so a fast <16ms flick
4962
+ // whose final mousemove was just flushed synchronously never reads stale React state.
4963
+ const endPt = (ev && typeof ev.clientX === 'number' && (marquee || pending)) ? pointTo(ev) : null;
4770
4964
  if (marquee) {
4771
- setSelectedIds(hitTest(marquee));
4965
+ const finalRect = endPt
4966
+ ? { x1: marquee.x1, y1: marquee.y1, x2: endPt.x, y2: endPt.y }
4967
+ : marquee;
4968
+ setSelectedIds(hitTest(finalRect));
4772
4969
  setMarquee(null);
4773
4970
  }
4774
4971
  if (panDrag.current) {
@@ -4779,7 +4976,9 @@ window.__ModuleLoader__.load({
4779
4976
  const handled = pendingHandledRef.current;
4780
4977
  pendingHandledRef.current = false;
4781
4978
  if (!handled && pending && pending.dir === 'out') {
4782
- const dist = Math.hypot(pending.x - pending.sx, pending.y - pending.sy);
4979
+ const px = endPt ? endPt.x : pending.x;
4980
+ const py = endPt ? endPt.y : pending.y;
4981
+ const dist = Math.hypot(px - pending.sx, py - pending.sy);
4783
4982
  const wrap = canvasWrapRef.current;
4784
4983
  if (dist >= 16 && wrap) {
4785
4984
  const wrapRect = wrap.getBoundingClientRect();
@@ -4790,8 +4989,8 @@ window.__ModuleLoader__.load({
4790
4989
  setAddMenu({
4791
4990
  sx,
4792
4991
  sy,
4793
- wx: pending.x,
4794
- wy: pending.y,
4992
+ wx: px,
4993
+ wy: py,
4795
4994
  linkFrom: {
4796
4995
  fromId: pending.fromId,
4797
4996
  type: pending.type || 'prompt',
@@ -4799,8 +4998,8 @@ window.__ModuleLoader__.load({
4799
4998
  color: pending.color || '#8a8f98',
4800
4999
  sx: pending.sx,
4801
5000
  sy: pending.sy,
4802
- x: pending.x,
4803
- y: pending.y,
5001
+ x: px,
5002
+ y: py,
4804
5003
  },
4805
5004
  });
4806
5005
  setMenuOpen(false);
@@ -4812,6 +5011,7 @@ window.__ModuleLoader__.load({
4812
5011
  setPending(null);
4813
5012
  setDragging(false);
4814
5013
  };
5014
+ dragHandlersRef.current = { move: onCanvasMove, up: onCanvasUp };
4815
5015
 
4816
5016
  const savePresetNow = () => {
4817
5017
  const name = presetName.trim();
@@ -4844,7 +5044,9 @@ window.__ModuleLoader__.load({
4844
5044
  const merge = doc.mode === 'merge';
4845
5045
  if (!merge && !doc.nodes.length) return false;
4846
5046
  pushSnapshot();
4847
- const stamp = typeof remoteAt === 'number' ? remoteAt : (typeof doc.at === 'number' ? doc.at : null);
5047
+ // Only preserve remote timestamp when applying a Host bridge file; local JSON
5048
+ // imports/presets must stamp Date.now() so an older workspace file never clobbers them.
5049
+ const stamp = fromRemote && typeof remoteAt === 'number' ? remoteAt : null;
4848
5050
  applyStamp.current = stamp;
4849
5051
  if (fromRemote) {
4850
5052
  skipDirtyOnce.current = true;
@@ -4978,7 +5180,17 @@ window.__ModuleLoader__.load({
4978
5180
 
4979
5181
  // The Host writes generated canvases where the workspace Remote can read
4980
5182
  // them; polling that file is the only Host -> canvas channel available.
5183
+ // Pause polling while the window or keepMounted tab is hidden, cache matched
5184
+ // path prefixes (6 IPC reads -> 2), and back off while disabled & idle.
4981
5185
  const AUTO_CANVAS = true;
5186
+ const pollActiveRef = useRef(false);
5187
+ pollActiveRef.current = Boolean(enabled || sessionRunning);
5188
+ const pollWakeRef = useRef(null);
5189
+ useEffect(() => {
5190
+ if ((enabled || sessionRunning) && pollWakeRef.current) {
5191
+ pollWakeRef.current();
5192
+ }
5193
+ }, [enabled, sessionRunning]);
4982
5194
  useEffect(() => {
4983
5195
  if (!AUTO_CANVAS) return undefined;
4984
5196
  let remote;
@@ -4989,101 +5201,251 @@ window.__ModuleLoader__.load({
4989
5201
  }
4990
5202
  if (!wf || typeof wf.read !== 'function') { setSyncNote(t('syncOff')); return undefined; }
4991
5203
  if (!sessionId) { setSyncNote(t('syncNoSession')); return undefined; }
4992
- // The Host names the file after the agent id (session-<uuid>); the
4993
- // pane prop may carry either form, so try both.
5204
+ // The Host names the file after the sanitized agent id (session-<uuid>); the
5205
+ // pane prop may carry either form, so try them until one hits, then cache it.
5206
+ const sanitizeId = (s) => String(s || '').trim().replace(/[^A-Za-z0-9._-]/g, '_').replace(/\.\.+/g, '_').replace(/^\.+/, '_').slice(0, 180);
5207
+ const safeSid = sanitizeId(sessionId);
4994
5208
  const bare = String(sessionId).replace(/^session-/, '');
5209
+ const safeBare = sanitizeId(bare);
4995
5210
  const paths = [
4996
- '.dsh/canvas/' + String(sessionId) + '.json',
4997
- '.dsh/canvas/session-' + bare + '.json',
4998
- '.dsh/canvas/' + bare + '.json',
4999
- ].filter((v, i, all) => all.indexOf(v) === i);
5211
+ '.dsh/canvas/' + safeSid + '.json',
5212
+ '.dsh/canvas/session-' + safeBare + '.json',
5213
+ '.dsh/canvas/' + safeBare + '.json',
5214
+ ].filter((v, i, all) => v && all.indexOf(v) === i);
5000
5215
  const runPaths = [
5001
- '.dsh/canvas/' + String(sessionId) + '.run.json',
5002
- '.dsh/canvas/session-' + bare + '.run.json',
5003
- '.dsh/canvas/' + bare + '.run.json',
5004
- ].filter((v, i, all) => all.indexOf(v) === i);
5216
+ '.dsh/canvas/' + safeSid + '.run.json',
5217
+ '.dsh/canvas/session-' + safeBare + '.run.json',
5218
+ '.dsh/canvas/' + safeBare + '.run.json',
5219
+ ].filter((v, i, all) => v && all.indexOf(v) === i);
5005
5220
  setRunState(null);
5006
5221
  setDecisionViewFor(null);
5007
5222
  let alive = true;
5223
+ let busy = false;
5224
+ let timer = null;
5008
5225
  let lastText = '';
5009
5226
  let lastRunText = '';
5227
+ let lastCanvasStatSig = '';
5228
+ let lastRunStatSig = '';
5229
+ let cachedCanvasPath = '';
5230
+ let cachedRunPath = '';
5231
+
5232
+ const isPaneVisible = () => {
5233
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return false;
5234
+ if (isDockElementHidden(canvasWrapRef.current)) return false;
5235
+ return true;
5236
+ };
5237
+
5238
+ const statFingerprint = (val) => {
5239
+ if (!val || typeof val !== 'object') return '';
5240
+ const hasMeta = val.mtimeMs !== undefined || val.mtime !== undefined
5241
+ || val.modifiedAt !== undefined || val.size !== undefined || val.etag !== undefined;
5242
+ if (!hasMeta) return '';
5243
+ try { return JSON.stringify(val); } catch (_e) { return ''; }
5244
+ };
5245
+
5246
+ const readFirstMatch = async (candidates, cached, prevStatSig, onErr) => {
5247
+ const order = cached ? [cached, ...candidates.filter((p) => p !== cached)] : candidates;
5248
+ const canStat = typeof wf.stat === 'function';
5249
+ let lastErr = null;
5250
+ for (const p of order) {
5251
+ let nextStatSig = '';
5252
+ if (canStat) {
5253
+ try {
5254
+ const stRes = await wf.stat(sessionId, p, new AbortController().signal);
5255
+ if (!alive) return { text: '', hit: cached, statSig: prevStatSig, unchanged: false };
5256
+ if (stRes && stRes.ok === false) {
5257
+ const code = stRes.error && stRes.error.code;
5258
+ if (code !== 'workspace-file/not-found' && stRes.error) lastErr = stRes.error;
5259
+ continue;
5260
+ }
5261
+ const stVal = stRes && stRes.value !== undefined ? stRes.value : stRes;
5262
+ nextStatSig = statFingerprint(stVal);
5263
+ if (nextStatSig && p === cached && nextStatSig === prevStatSig) {
5264
+ return { text: '', hit: p, statSig: nextStatSig, unchanged: true };
5265
+ }
5266
+ } catch (statErr) {
5267
+ lastErr = statErr;
5268
+ continue;
5269
+ }
5270
+ }
5271
+ try {
5272
+ const res = await wf.read(sessionId, p, {}, new AbortController().signal);
5273
+ if (!alive) return { text: '', hit: cached, statSig: prevStatSig, unchanged: false };
5274
+ if (res && res.ok === false) {
5275
+ const code = res.error && res.error.code;
5276
+ if (code !== 'workspace-file/not-found' && res.error) lastErr = res.error;
5277
+ continue;
5278
+ }
5279
+ const payload = res && res.value !== undefined ? res.value : res;
5280
+ const read = payload && (typeof payload.text === 'string' ? payload.text : '');
5281
+ if (read) return { text: read, hit: p, statSig: nextStatSig, unchanged: false };
5282
+ } catch (err) {
5283
+ lastErr = err;
5284
+ }
5285
+ }
5286
+ if (lastErr && onErr) onErr(lastErr);
5287
+ return { text: '', hit: cached, statSig: prevStatSig, unchanged: false };
5288
+ };
5289
+
5290
+ const schedule = (visibleHint) => {
5291
+ if (!alive) return;
5292
+ if (timer) clearTimeout(timer);
5293
+ const visible = visibleHint !== undefined ? visibleHint : isPaneVisible();
5294
+ const delay = (visible && pollActiveRef.current) ? 1500 : 4000;
5295
+ timer = setTimeout(tick, delay);
5296
+ };
5297
+
5010
5298
  const tick = async () => {
5299
+ if (!alive) return;
5300
+ if (!isPaneVisible()) {
5301
+ schedule(false);
5302
+ return;
5303
+ }
5304
+ if (busy) {
5305
+ schedule(true);
5306
+ return;
5307
+ }
5308
+ busy = true;
5011
5309
  try {
5012
- let text = '';
5013
- for (const path of paths) {
5014
- try {
5015
- const res = await wf.read(sessionId, path, {}, new AbortController().signal);
5016
- if (!alive) return;
5017
- const payload = res && res.ok === false ? null : (res && res.value !== undefined ? res.value : res);
5018
- const read = payload && (typeof payload.text === 'string' ? payload.text : '');
5019
- if (read) { text = read; break; }
5020
- } catch (err) {
5310
+ try {
5311
+ const { text, hit, statSig, unchanged } = await readFirstMatch(paths, cachedCanvasPath, lastCanvasStatSig, (err) => {
5021
5312
  setSyncNote(t('syncReadFail') + String((err && err.message) || err).slice(0, 80));
5313
+ });
5314
+ if (!alive) return;
5315
+ if (hit) {
5316
+ cachedCanvasPath = hit;
5317
+ if (!cachedRunPath) {
5318
+ const pairedRun = hit.replace(/\.json$/, '.run.json');
5319
+ if (runPaths.includes(pairedRun)) cachedRunPath = pairedRun;
5320
+ }
5022
5321
  }
5023
- }
5024
- if (text && text !== lastText) {
5025
- lastText = text;
5026
- const doc = JSON.parse(text);
5027
- const canvas = doc && doc.canvas;
5028
- // A canvas the user has edited more recently wins over an old file.
5029
- let staleLocal = false;
5030
- try {
5031
- const raw = window.localStorage.getItem(storageKey(sessionId));
5032
- const local = raw ? JSON.parse(raw) : null;
5033
- if (local && typeof local.at === 'number' && typeof doc.at === 'number' && local.at > doc.at) {
5034
- staleLocal = true;
5322
+ if (!unchanged && text && text !== lastText) {
5323
+ const doc = JSON.parse(text);
5324
+ lastText = text;
5325
+ if (statSig) lastCanvasStatSig = statSig;
5326
+ const canvas = doc && doc.canvas;
5327
+ // A canvas the user has edited more recently wins over an old file;
5328
+ // also check `lastLocalEditAtRef` so unflushed debounced edits are never clobbered.
5329
+ let staleLocal = false;
5330
+ try {
5331
+ const raw = window.localStorage.getItem(storageKey(sessionId));
5332
+ const local = raw ? JSON.parse(raw) : null;
5333
+ const effectiveLocalAt = Math.max(
5334
+ (local && typeof local.at === 'number') ? local.at : 0,
5335
+ lastLocalEditAtRef.current || 0,
5336
+ );
5337
+ if (effectiveLocalAt > 0 && typeof doc.at === 'number' && effectiveLocalAt > doc.at) {
5338
+ staleLocal = true;
5339
+ }
5340
+ } catch (_e) { /* ignore */ }
5341
+ if (!staleLocal) {
5342
+ const valid = canvas && Array.isArray(canvas.nodes)
5343
+ && (canvas.mode === 'merge' || canvas.nodes.length > 0)
5344
+ && canvas.nodes.every((n) => n && typeof n.id === 'string');
5345
+ if (valid && applyCanvasDoc(canvas, doc.at, true)) {
5346
+ flash(t('generated'));
5347
+ setSyncNote(t('syncApplied'));
5348
+ setTimeout(() => setSyncNote(''), 4000);
5349
+ }
5350
+ else setSyncNote(t('syncBadFile'));
5035
5351
  }
5036
- } catch (_e) { /* ignore */ }
5037
- if (!staleLocal) {
5038
- const valid = canvas && Array.isArray(canvas.nodes)
5039
- && (canvas.mode === 'merge' || canvas.nodes.length > 0)
5040
- && canvas.nodes.every((n) => n && typeof n.id === 'string');
5041
- if (valid && applyCanvasDoc(canvas, doc.at, true)) {
5042
- flash(t('generated'));
5043
- setSyncNote(t('syncApplied'));
5044
- setTimeout(() => setSyncNote(''), 4000);
5352
+ } else if (!unchanged && text && text === lastText && statSig) {
5353
+ lastCanvasStatSig = statSig;
5354
+ }
5355
+ } catch (_e) { /* file absent or not readable yet */ }
5356
+ try {
5357
+ const { text: runText, hit: runHit, statSig: runStatSig, unchanged: runUnchanged } = await readFirstMatch(runPaths, cachedRunPath, lastRunStatSig);
5358
+ if (!alive) return;
5359
+ if (runHit) {
5360
+ cachedRunPath = runHit;
5361
+ if (!cachedCanvasPath) {
5362
+ const pairedCanvas = runHit.replace(/\.run\.json$/, '.json');
5363
+ if (paths.includes(pairedCanvas)) cachedCanvasPath = pairedCanvas;
5045
5364
  }
5046
- else setSyncNote(t('syncBadFile'));
5047
5365
  }
5048
- }
5049
- } catch (_e) { /* file absent or not readable yet */ }
5050
- try {
5051
- let runText = '';
5052
- for (const rp of runPaths) {
5053
- try {
5054
- const res = await wf.read(sessionId, rp, {}, new AbortController().signal);
5055
- if (!alive) return;
5056
- const payload = res && res.ok === false ? null : (res && res.value !== undefined ? res.value : res);
5057
- const read = payload && (typeof payload.text === 'string' ? payload.text : '');
5058
- if (read) { runText = read; break; }
5059
- } catch (_e) { /* ignore */ }
5060
- }
5061
- if (runText && runText !== lastRunText) {
5062
- lastRunText = runText;
5063
- const parsed = JSON.parse(runText);
5064
- if (parsed && typeof parsed === 'object') {
5065
- setRunState(parsed.status === 'idle' ? null : parsed);
5366
+ if (!runUnchanged && runText && runText !== lastRunText) {
5367
+ const parsed = JSON.parse(runText);
5368
+ lastRunText = runText;
5369
+ if (runStatSig) lastRunStatSig = runStatSig;
5370
+ if (parsed && typeof parsed === 'object') {
5371
+ setRunState(parsed.status === 'idle' ? null : parsed);
5372
+ }
5373
+ } else if (!runUnchanged && runText && runText === lastRunText && runStatSig) {
5374
+ lastRunStatSig = runStatSig;
5066
5375
  }
5067
- }
5068
- } catch (_e) { /* run state file absent or not readable yet */ }
5376
+ } catch (_e) { /* run state file absent or not readable yet */ }
5377
+ } finally {
5378
+ busy = false;
5379
+ schedule();
5380
+ }
5381
+ };
5382
+
5383
+ const wake = () => {
5384
+ if (!alive || !isPaneVisible()) return;
5385
+ if (timer) { clearTimeout(timer); timer = null; }
5386
+ tick();
5069
5387
  };
5070
- const timer = setInterval(tick, 1500);
5388
+ pollWakeRef.current = wake;
5389
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
5390
+ document.addEventListener('visibilitychange', wake);
5391
+ }
5392
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
5393
+ window.addEventListener('focus', wake);
5394
+ }
5395
+ let io = null;
5396
+ if (typeof IntersectionObserver === 'function' && canvasWrapRef.current) {
5397
+ try {
5398
+ io = new IntersectionObserver((entries) => {
5399
+ if (entries && entries.some((e) => e.isIntersecting)) wake();
5400
+ });
5401
+ io.observe(canvasWrapRef.current);
5402
+ } catch (_e) { io = null; }
5403
+ }
5404
+ // Watch `[data-dockkit-content]` aria-hidden/inert so expanding a collapsed right
5405
+ // sidebar wakes polling on frame 0 instead of waiting for CSS slide transition.
5406
+ let mo = null;
5407
+ if (typeof MutationObserver === 'function' && canvasWrapRef.current && typeof canvasWrapRef.current.closest === 'function') {
5408
+ try {
5409
+ const dockHost = canvasWrapRef.current.closest('[data-dockkit-content]');
5410
+ if (dockHost) {
5411
+ mo = new MutationObserver(() => {
5412
+ if (isPaneVisible()) wake();
5413
+ });
5414
+ mo.observe(dockHost, { attributes: true, attributeFilter: ['aria-hidden', 'inert'] });
5415
+ }
5416
+ } catch (_e) { mo = null; }
5417
+ }
5071
5418
  tick();
5072
- return () => { alive = false; clearInterval(timer); };
5419
+ return () => {
5420
+ alive = false;
5421
+ if (pollWakeRef.current === wake) pollWakeRef.current = null;
5422
+ if (timer) clearTimeout(timer);
5423
+ if (io) try { io.disconnect(); } catch (_e) { /* ignore */ }
5424
+ if (mo) try { mo.disconnect(); } catch (_e) { /* ignore */ }
5425
+ if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
5426
+ document.removeEventListener('visibilitychange', wake);
5427
+ }
5428
+ if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
5429
+ window.removeEventListener('focus', wake);
5430
+ }
5431
+ };
5073
5432
  }, [sessionId]);
5074
5433
 
5075
5434
  const importFromClipboard = () => {
5076
5435
  const finish = (text) => {
5077
- if (!text) { flash(t('importNone')); return; }
5436
+ if (!text || typeof text !== 'string') { flash(t('importNone')); return; }
5437
+ if (text.length > 2 * 1024 * 1024) { flash(t('importBad')); return; }
5078
5438
  let doc;
5079
5439
  try {
5080
5440
  const start = text.indexOf('{');
5081
5441
  const end = text.lastIndexOf('}');
5442
+ if (start === -1 || end <= start) { flash(t('importBad')); return; }
5082
5443
  doc = JSON.parse(text.slice(start, end + 1));
5083
5444
  } catch (_e) { flash(t('importBad')); return; }
5084
- if (!applyCanvasDoc(doc.canvas || doc)) { flash(t('importBad')); return; }
5445
+ const payload = doc && (doc.canvas || doc);
5446
+ if (!payload || !applyCanvasDoc(payload)) { flash(t('importBad')); return; }
5085
5447
  if (enabled) setTimeout(() => pushPlan(true), 0);
5086
- flash(t('importOk') + (doc.canvas || doc).nodes.length);
5448
+ flash(t('importOk') + payload.nodes.length);
5087
5449
  };
5088
5450
  try {
5089
5451
  if (navigator.clipboard && navigator.clipboard.readText) {
@@ -5392,27 +5754,39 @@ window.__ModuleLoader__.load({
5392
5754
  };
5393
5755
 
5394
5756
  const fxName = (level) => (level === 'minimal' ? t('fxMinimal') : (level === 'vivid' ? t('fxVivid') : t('fxStandard')));
5395
- const selectedSet = new Set(selectedIds);
5396
- const nodeById = new Map(nodes.map((n) => [n.id, n]));
5397
- const inColorByNode = new Map();
5398
- const inCountByNode = new Map();
5399
- const inPriority = (e) => (e.loop ? 0.5 : (e.type === 'session-ref' ? 3 : (e.type === 'structured' ? 2 : (e.branch ? 1.5 : 1))));
5400
- const inPrioByNode = new Map();
5401
- const connectedOut = new Set();
5402
- for (const e of edges) {
5403
- const type = e.type || 'prompt';
5404
- const b = typeof e.branch === 'string' ? e.branch.trim() : '';
5405
- connectedOut.add(e.from + '|' + (b ? 'branch:' + b : type));
5406
- inCountByNode.set(e.to, (inCountByNode.get(e.to) || 0) + 1);
5407
- const prio = inPriority(e);
5408
- if (!inPrioByNode.has(e.to) || prio >= inPrioByNode.get(e.to)) {
5409
- inPrioByNode.set(e.to, prio);
5410
- inColorByNode.set(e.to, edgeColorFor(nodeById.get(e.from), e));
5757
+ const selectedSet = useMemo(() => new Set(selectedIds), [selectedIds]);
5758
+ // Memoize O(V+E) graph topology & loop analyses so viewport pan/zoom, status polls,
5759
+ // and popover toggles never re-run BFS or loop-body intersections.
5760
+ const graphMeta = useMemo(() => {
5761
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
5762
+ const inColorByNode = new Map();
5763
+ const inCountByNode = new Map();
5764
+ const inPriority = (e) => (e.loop ? 0.5 : (e.type === 'session-ref' ? 3 : (e.type === 'structured' ? 2 : (e.branch ? 1.5 : 1))));
5765
+ const inPrioByNode = new Map();
5766
+ const connectedOut = new Set();
5767
+ for (const e of edges) {
5768
+ const type = e.type || 'prompt';
5769
+ const b = typeof e.branch === 'string' ? e.branch.trim() : '';
5770
+ connectedOut.add(e.from + '|' + (b ? 'branch:' + b : type));
5771
+ inCountByNode.set(e.to, (inCountByNode.get(e.to) || 0) + 1);
5772
+ const prio = inPriority(e);
5773
+ if (!inPrioByNode.has(e.to) || prio >= inPrioByNode.get(e.to)) {
5774
+ inPrioByNode.set(e.to, prio);
5775
+ inColorByNode.set(e.to, edgeColorFor(nodeById.get(e.from), e));
5776
+ }
5411
5777
  }
5412
- }
5413
- const reachableIds = reachableFrom(nodes, edges);
5414
- const soloLeadIds = soloLeadNodeIds(nodes, edges);
5415
- const deadEndIds = deadEndNodeIds(nodes, edges);
5778
+ return {
5779
+ nodeById,
5780
+ inColorByNode,
5781
+ inCountByNode,
5782
+ connectedOut,
5783
+ reachableIds: reachableFrom(nodes, edges),
5784
+ soloLeadIds: soloLeadNodeIds(nodes, edges),
5785
+ deadEndIds: deadEndNodeIds(nodes, edges),
5786
+ loopGroups: loopGroupsForUI(nodes, edges),
5787
+ };
5788
+ }, [nodes, edges]);
5789
+ const { nodeById, inColorByNode, inCountByNode, connectedOut, reachableIds, soloLeadIds, deadEndIds, loopGroups } = graphMeta;
5416
5790
 
5417
5791
  // Lead nodes are never spawned, so their status is derived via `deriveLeadStatuses`,
5418
5792
  // honoring authoritative backend `runState.status` (`halted` / `done` / `need-lead`).
@@ -5496,7 +5870,6 @@ window.__ModuleLoader__.load({
5496
5870
  now: summaryNow,
5497
5871
  fallbackTiming: clientRunTimingRef.current,
5498
5872
  });
5499
- const loopGroups = loopGroupsForUI(nodes, edges);
5500
5873
  const edgeKeyForState = (e) => String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
5501
5874
  const loopPillItems = [];
5502
5875
 
@@ -6669,6 +7042,7 @@ window.__ModuleLoader__.load({
6669
7042
  : runSummary.status === 'running' || runSummary.status === 'need-lead'
6670
7043
  ? '#2f81f7'
6671
7044
  : '#e5534b';
7045
+ const elapsedStyle = { flex: '0 0 auto', color: C.dim, fontVariantNumeric: 'tabular-nums' };
6672
7046
  const elapsedText = runSummary.elapsedMs !== null ? ' · ' + formatDurationMs(runSummary.elapsedMs) : '';
6673
7047
  const loopText = runSummary.totalLoops > 0 ? ' · ↺' + runSummary.totalLoops : '';
6674
7048
  return h('button', {
@@ -6692,7 +7066,9 @@ window.__ModuleLoader__.load({
6692
7066
  h('span', { style: { color: pillColor, flex: '0 0 auto' } }, pillIcon),
6693
7067
  h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 } },
6694
7068
  t('runSummaryBtn') + ' · ' + runSummary.doneCount + '/' + runSummary.totalCount + loopText),
6695
- elapsedText && h('span', { style: { flex: '0 0 auto', color: C.dim, fontVariantNumeric: 'tabular-nums' } }, elapsedText),
7069
+ runSummary.isLive && typeof runSummary.startedAt === 'number'
7070
+ ? h(LiveElapsedText, { active: true, startedAt: runSummary.startedAt, endedAt: runSummary.endedAt, style: elapsedStyle })
7071
+ : (elapsedText && h('span', { style: elapsedStyle }, elapsedText)),
6696
7072
  );
6697
7073
  })(),
6698
7074
  h('div', {
@@ -6731,6 +7107,7 @@ window.__ModuleLoader__.load({
6731
7107
  style: {
6732
7108
  ...S.content, width: contentW, height: contentH, overflow: 'visible',
6733
7109
  transform: 'translate(' + view.x + 'px,' + view.y + 'px) scale(' + view.k + ')',
7110
+ willChange: panning ? 'transform' : undefined,
6734
7111
  transformOrigin: '0 0',
6735
7112
  },
6736
7113
  },
@@ -7375,7 +7752,7 @@ window.__ModuleLoader__.load({
7375
7752
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
7376
7753
  }
7377
7754
  },
7378
- __test: { I18N, S, topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, applyPanStep, normalizeDirection, loadDefaultDirection, saveDefaultDirection, loadPresets, savePresets, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, distanceToEdge, edgeCurve, compatibleTargetsForWire, conditionVerdictSummary, entryRunButtonState, stopButtonState, deriveLeadStatuses, formatDurationMs, buildRunSummaryView, formatRunSummaryMarkdown, outputSocketX, inputSocketPos, outputSocketPos, normalizeRefsUI, clampMenuPos, cloneSelection, nextSelectionOnNodeClick, DEFAULT_SHORTCUTS, normalizeShortcut, formatShortcutFromEvent, matchesShortcut, applyShortcutBinding, normalizeMaxIterationsUI, loopMemberIdsUI, loopGroupsForUI, pruneInvalidLoopEdges, canLinkAsLoop, analyzeLoopSelection, loopEdgeArc },
7755
+ __test: { I18N, S, isDockElementHidden, topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, applyPanStep, normalizeDirection, loadDefaultDirection, saveDefaultDirection, loadPresets, savePresets, buildPlan, loadDoc, saveDoc, pruneSessionStorage, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, distanceToEdge, edgeCurve, compatibleTargetsForWire, conditionVerdictSummary, entryRunButtonState, stopButtonState, deriveLeadStatuses, formatDurationMs, buildRunSummaryView, formatRunSummaryMarkdown, outputSocketX, inputSocketPos, outputSocketPos, normalizeRefsUI, clampMenuPos, cloneSelection, nextSelectionOnNodeClick, DEFAULT_SHORTCUTS, normalizeShortcut, formatShortcutFromEvent, matchesShortcut, applyShortcutBinding, normalizeMaxIterationsUI, loopMemberIdsUI, loopGroupsForUI, pruneInvalidLoopEdges, canLinkAsLoop, analyzeLoopSelection, loopEdgeArc },
7379
7756
  };
7380
7757
  },
7381
7758
  });