dsh-workflow-canvas 1.5.5 → 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) {
@@ -197,7 +240,7 @@ window.__ModuleLoader__.load({
197
240
  '10. 点右上角「☰ 预设」可保存当前画布(连同横/竖排方向),多会话实时同步并支持点 ↻ 刷新;切换横/竖排会自动记住默认偏好供新会话沿用。',
198
241
  '11. 你可以直接让我改画布:说「把那三个节点的分工改成…」,我会就地修改,不动你摆的位置。',
199
242
  '12. session 线连到 Lead 时,我会在暂停那步拿到那个子代理的会话,可以继续追问它。',
200
- '13. 按住鼠标中键(或空格 + 左键)拖动画布平移;点击子代理节点左下角状态可直达它的对话记录。',
243
+ '13. 按住鼠标中键(或空格 + 左键)拖动画布平移;点击子代理节点左下角状态可直达它的对话记录;运行后左下角「复盘」胶囊(或「⋯ → 📊 执行复盘」)可查看耗时、分支与回环记录并复制 Markdown(零额外 Token)。',
201
244
  '14. 快捷键与历史:顶栏提供 ↶ 撤销 / ↷ 重做按钮(支持撤销节点移动与横竖排切换);默认 Shift+A 新建,Shift+D 复制,Delete 删除,Ctrl+Z / Ctrl+Shift+Z(Ctrl+Y)撤销重做,Esc 关闭弹窗(可在「⋯ → 快捷键设置」自定义)。',
202
245
  ].join('\n'),
203
246
  openChat: '会话',
@@ -314,6 +357,34 @@ window.__ModuleLoader__.load({
314
357
  tipMemoryPick: '选择要续接的历史子会话(默认自动沿用最新记忆)',
315
358
  tipPreset: '能力范围(点一下切换,受主对话权限上限约束):standard = 全部工具(读写文件、跑命令、子代理、工作流、网页、办公);minimal = 只读思考(文件读写关闭,没有子代理/工作流/网页)',
316
359
  tipFallback: '失败重试:该节点出错时自动换一个模型再跑一次',
360
+ runSummaryBtn: '复盘',
361
+ runSummaryMenu: '📊 执行复盘',
362
+ runSummaryTitle: '执行复盘摘要',
363
+ runSummaryEmpty: '当前会话还没有运行记录',
364
+ runSummaryCopy: '⧉ 复制 MD',
365
+ runSummaryCopied: '已复制 Markdown 复盘报告',
366
+ runSummaryElapsed: '总耗时',
367
+ runSummaryDone: '已完成',
368
+ runSummaryLoops: '回环重试',
369
+ runSummaryParallel: '并发上限',
370
+ runSummaryNodesHead: '节点耗时与状态',
371
+ runSummaryLoopsHead: '回环记录',
372
+ runSummaryFallback: '备用回退',
373
+ runSummaryContinued: '续接会话',
374
+ runSummaryReused: '缓存复用',
375
+ runSummaryRuns: '{n} 轮',
376
+ runSummaryExhausted: '已达上限',
377
+ runSummaryFocusTip: '点击居中定位到该节点',
378
+ runSummaryOpenChatTip: '打开该子代理会话',
379
+ runSummaryTip: '查看本次工作流耗时、节点状态、条件分支与回环复盘(零额外 Token)',
380
+ runStRunning: '运行中',
381
+ runStDone: '已完成',
382
+ runStWaiting: '待拍板',
383
+ runStHalted: '已终止',
384
+ runStFailed: '失败',
385
+ runStEmpty: '空输出',
386
+ runStPruned: '跳过',
387
+ runStPending: '未启动',
317
388
  },
318
389
  en: {
319
390
  addAgent: '+ Subagent', addLead: '+ Lead', addCond: '+ Condition', undo: '↶ Undo', redo: '↷ Redo', sync: '↥ Sync',
@@ -393,7 +464,7 @@ window.__ModuleLoader__.load({
393
464
  '10. Open ☰ Presets to save the current canvas (including horizontal/vertical direction) — presets sync live across open chats with a manual ↻ refresh button; toggling layout direction is remembered for new sessions.',
394
465
  '11. You can ask me to edit the canvas; I patch it in place and keep your layout.',
395
466
  '12. A session link into a Lead step hands me that child agent, so I can follow up with it.',
396
- '13. Hold the middle mouse button (or Space + drag) to pan; click a subagent status badge at the bottom-left to open its chat.',
467
+ '13. Hold the middle mouse button (or Space + drag) to pan; click a subagent status badge at the bottom-left to open its chat; click the bottom-left Summary pill (or ⋯ → 📊 Run summary) for live timing, branch & retry breakdown and Markdown export (zero extra tokens).',
397
468
  '14. History & shortcuts: toolbar ↶ Undo / ↷ Redo buttons undo structural edits, node drags, and layout flips; Shift+A adds at cursor, Shift+D duplicates, Delete removes, Ctrl+Z / Ctrl+Shift+Z (Ctrl+Y) undo/redo, Esc closes popups (customizable under ⋯ → Shortcuts).',
398
469
  ].join('\n'),
399
470
  openChat: 'Chat',
@@ -510,6 +581,34 @@ window.__ModuleLoader__.load({
510
581
  tipMemoryPick: 'Pick which past child session to resume (defaults to latest)',
511
582
  tipPreset: 'Capability (click to toggle; bounded by the main chat permission mode): standard = all tools (files, shells, subagents, workflow, web, office); minimal = read-only thinking (no file writes, no subagents/workflow/web)',
512
583
  tipFallback: 'Retry: when this node fails, rerun it once on another model',
584
+ runSummaryBtn: 'Summary',
585
+ runSummaryMenu: '📊 Run summary',
586
+ runSummaryTitle: 'Run Summary',
587
+ runSummaryEmpty: 'No workflow run recorded in this session yet',
588
+ runSummaryCopy: '⧉ Copy MD',
589
+ runSummaryCopied: 'Copied Markdown run summary',
590
+ runSummaryElapsed: 'Elapsed',
591
+ runSummaryDone: 'Completed',
592
+ runSummaryLoops: 'Loop retries',
593
+ runSummaryParallel: 'Max parallel',
594
+ runSummaryNodesHead: 'Node timeline',
595
+ runSummaryLoopsHead: 'Loop history',
596
+ runSummaryFallback: 'Fallback',
597
+ runSummaryContinued: 'Continued',
598
+ runSummaryReused: 'Cached',
599
+ runSummaryRuns: '{n} runs',
600
+ runSummaryExhausted: 'Exhausted',
601
+ runSummaryFocusTip: 'Click to focus this node on canvas',
602
+ runSummaryOpenChatTip: 'Open child session',
603
+ runSummaryTip: 'Inspect run timing, node status, branch verdicts & retry history (zero extra tokens)',
604
+ runStRunning: 'Running',
605
+ runStDone: 'Completed',
606
+ runStWaiting: 'Awaiting Lead',
607
+ runStHalted: 'Halted',
608
+ runStFailed: 'Failed',
609
+ runStEmpty: 'Empty',
610
+ runStPruned: 'Skipped',
611
+ runStPending: 'Pending',
513
612
  },
514
613
  };
515
614
 
@@ -600,6 +699,45 @@ window.__ModuleLoader__.load({
600
699
  background: 'transparent', color: C.text, fontSize: '11px',
601
700
  cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '16px',
602
701
  },
702
+ floatSummaryBtn: {
703
+ position: 'absolute', left: '10px', bottom: '10px', zIndex: 30,
704
+ display: 'inline-flex', alignItems: 'center', gap: '5px',
705
+ padding: '4px 10px', borderRadius: '999px',
706
+ background: C.elevated, color: C.text, border: '1px solid ' + C.border,
707
+ fontSize: '11px', fontWeight: 600, lineHeight: '16px',
708
+ cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.28)',
709
+ maxWidth: 'calc(100% - 118px)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
710
+ fontVariantNumeric: 'tabular-nums',
711
+ },
712
+ summaryKpiRow: {
713
+ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(84px, 1fr))', gap: '6px',
714
+ marginBottom: '10px', flex: '0 0 auto',
715
+ },
716
+ summaryKpi: {
717
+ padding: '6px 8px', borderRadius: '6px',
718
+ background: C.raised, border: '1px solid ' + C.border,
719
+ display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0,
720
+ },
721
+ summaryRow: {
722
+ padding: '7px 8px', borderRadius: '6px', flex: '0 0 auto',
723
+ background: C.raised, border: '1px solid ' + C.border,
724
+ display: 'flex', flexDirection: 'column', gap: '4px',
725
+ },
726
+ summaryBarTrack: {
727
+ width: '100%', height: '3px', borderRadius: '2px',
728
+ background: C.border, overflow: 'hidden', opacity: 0.75,
729
+ },
730
+ summaryBarFill: {
731
+ height: '100%', borderRadius: '2px',
732
+ transition: 'width 180ms ease',
733
+ },
734
+ summaryChip: {
735
+ display: 'inline-flex', alignItems: 'center', gap: '3px',
736
+ padding: '1px 5px', borderRadius: '4px',
737
+ border: '1px solid ' + C.border, background: C.base,
738
+ color: C.dim, fontSize: '10px', lineHeight: '13px',
739
+ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
740
+ },
603
741
  ctxDivider: {
604
742
  height: '1px', background: C.border, opacity: 0.65, margin: '3px 4px',
605
743
  },
@@ -1126,17 +1264,25 @@ window.__ModuleLoader__.load({
1126
1264
  };
1127
1265
  }
1128
1266
 
1129
- /** Compute unified Stop button visibility, label and tooltip across running & waitingLead states. */
1267
+ /** Compute unified Stop button state across idle, running & waitingLead modes. */
1130
1268
  function stopButtonState({ sessionRunning, runningNodesCount, waitingLead, triggering, stopping, lang }) {
1131
1269
  const en = lang === 'en';
1132
1270
  const hasRunning = Boolean(sessionRunning || triggering || Number(runningNodesCount) > 0);
1133
1271
  const hasWaiting = Boolean(waitingLead);
1134
1272
  if (!hasRunning && !hasWaiting) {
1135
- return { visible: false, disabled: true, mode: 'idle', label: '', title: '' };
1273
+ return {
1274
+ visible: true,
1275
+ active: false,
1276
+ disabled: true,
1277
+ mode: 'idle',
1278
+ label: en ? '⏹ Stop' : '⏹ 终止',
1279
+ title: en ? 'No running or paused workflow to stop' : '当前没有运行中或等待拍板的任务',
1280
+ };
1136
1281
  }
1137
1282
  const mode = hasRunning ? 'running' : 'waiting';
1138
1283
  return {
1139
1284
  visible: true,
1285
+ active: true,
1140
1286
  disabled: Boolean(stopping),
1141
1287
  mode,
1142
1288
  label: stopping
@@ -1211,6 +1357,230 @@ window.__ModuleLoader__.load({
1211
1357
  return { leadReadyIds, leadDoneIds };
1212
1358
  }
1213
1359
 
1360
+ /** Format millisecond durations cleanly for badges, KPI cards and Markdown tables. */
1361
+ function formatDurationMs(ms) {
1362
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return '—';
1363
+ if (ms < 1000) return Math.round(ms) + 'ms';
1364
+ if (ms < 60000) return (ms / 1000).toFixed(1) + 's';
1365
+ const totalSec = Math.round(ms / 1000);
1366
+ const min = Math.floor(totalSec / 60);
1367
+ const sec = totalSec % 60;
1368
+ if (min < 60) return min + 'm ' + sec + 's';
1369
+ const hr = Math.floor(min / 60);
1370
+ const remMin = min % 60;
1371
+ return hr + 'h ' + remMin + 'm';
1372
+ }
1373
+
1374
+ /**
1375
+ * Normalize `.run.json` telemetry into a UI/Markdown view model.
1376
+ * Supports both v1.6 `runState.summary` and older `.run.json` files without `summary`.
1377
+ */
1378
+ function buildRunSummaryView({ runState, nodes, runsById, now, fallbackTiming }) {
1379
+ if (!runState || typeof runState !== 'object' || runState.status === 'idle') {
1380
+ return { hasData: false };
1381
+ }
1382
+ const clock = typeof now === 'number' ? now : Date.now();
1383
+ const canvasNodes = Array.isArray(nodes) ? nodes : [];
1384
+ const byCanvasId = new Map(canvasNodes.map((n) => [n.id, n]));
1385
+ const runMap = runsById && typeof runsById === 'object' ? runsById : {};
1386
+ const sum = runState.summary && typeof runState.summary === 'object' ? runState.summary : null;
1387
+ const status = runState.status || (sum && sum.status) || 'running';
1388
+ const waitingLead = runState.waitingLead || null;
1389
+ const isLive = status === 'running' || status === 'need-lead';
1390
+
1391
+ let rows = [];
1392
+ let minNodeStart = null;
1393
+ let maxNodeEnd = null;
1394
+ if (sum && Array.isArray(sum.nodes) && sum.nodes.length > 0) {
1395
+ rows = sum.nodes.map((entry) => {
1396
+ if (typeof entry.startedAt === 'number' && (minNodeStart === null || entry.startedAt < minNodeStart)) {
1397
+ minNodeStart = entry.startedAt;
1398
+ }
1399
+ if (typeof entry.endedAt === 'number' && (maxNodeEnd === null || entry.endedAt > maxNodeEnd)) {
1400
+ maxNodeEnd = entry.endedAt;
1401
+ }
1402
+ const baseMs = typeof entry.durationMs === 'number' ? entry.durationMs : 0;
1403
+ const liveExtra = (entry.status === 'running' || entry.status === 'waiting')
1404
+ && typeof entry.startedAt === 'number' && !entry.endedAt
1405
+ ? Math.max(0, clock - entry.startedAt)
1406
+ : 0;
1407
+ const totalMs = baseMs + liveExtra;
1408
+ const canvasNode = byCanvasId.get(entry.id);
1409
+ const childRun = runMap[entry.id] || null;
1410
+ const entryStatus = entry.status || 'pending';
1411
+ const isUnrun = entryStatus === 'pruned' || (entryStatus === 'pending' && totalMs === 0);
1412
+ const isZeroLead = (entry.kind || (canvasNode && canvasNode.kind)) === 'lead' && totalMs === 0 && entryStatus !== 'running' && entryStatus !== 'waiting';
1413
+ return {
1414
+ id: entry.id,
1415
+ label: entry.label || (canvasNode && canvasNode.label) || entry.id,
1416
+ kind: entry.kind || (canvasNode && canvasNode.kind) || 'agent',
1417
+ status: entryStatus,
1418
+ durationMs: (isUnrun || isZeroLead) ? null : totalMs,
1419
+ runs: typeof entry.runs === 'number' ? entry.runs : 0,
1420
+ model: entry.model || '',
1421
+ fallbackUsed: Boolean(entry.fallbackUsed),
1422
+ sessionContinued: Boolean(entry.sessionContinued),
1423
+ childId: isUnrun ? '' : (entry.childId || (childRun && childRun.childId) || ''),
1424
+ reason: entry.reason || '',
1425
+ onCanvas: Boolean(canvasNode),
1426
+ };
1427
+ });
1428
+ } else {
1429
+ // Graceful fallback for older `.run.json` payloads written before `summary` existed.
1430
+ const doneSet = new Set(Array.isArray(runState.done) ? runState.done : []);
1431
+ const prunedSet = new Set(Array.isArray(runState.pruned) ? runState.pruned : []);
1432
+ const decisions = runState.decisions && typeof runState.decisions === 'object' ? runState.decisions : {};
1433
+ rows = canvasNodes.filter((n) => n && n.id !== 'lead').map((n) => {
1434
+ const dec = decisions[n.id] || null;
1435
+ const childRun = runMap[n.id] || null;
1436
+ let st = 'pending';
1437
+ if (prunedSet.has(n.id)) st = 'pruned';
1438
+ else if (status === 'need-lead' && waitingLead && waitingLead.id === n.id) st = 'waiting';
1439
+ else if (dec && dec.failed) st = 'failed';
1440
+ else if (doneSet.has(n.id)) st = 'done';
1441
+ const reason = dec
1442
+ ? ((Array.isArray(dec.branchLabels) && dec.branchLabels.length ? dec.branchLabels.join(', ') : (dec.branchLabel || ''))
1443
+ + (dec.reason ? ' — ' + dec.reason : ''))
1444
+ : '';
1445
+ return {
1446
+ id: n.id,
1447
+ label: n.label || n.id,
1448
+ kind: n.kind || 'agent',
1449
+ status: st,
1450
+ durationMs: null,
1451
+ runs: doneSet.has(n.id) ? 1 : 0,
1452
+ model: n.model || '',
1453
+ fallbackUsed: false,
1454
+ sessionContinued: false,
1455
+ childId: (st === 'pruned' || st === 'pending') ? '' : ((childRun && childRun.childId) || ''),
1456
+ reason,
1457
+ onCanvas: true,
1458
+ };
1459
+ });
1460
+ }
1461
+
1462
+ if (!rows.length) return { hasData: false };
1463
+
1464
+ let doneCount = 0;
1465
+ let failedCount = 0;
1466
+ let prunedCount = 0;
1467
+ let runningCount = 0;
1468
+ let maxNodeMs = 0;
1469
+ for (const r of rows) {
1470
+ if (r.status === 'done' || r.status === 'reused') doneCount += 1;
1471
+ else if (r.status === 'failed' || r.status === 'empty') failedCount += 1;
1472
+ else if (r.status === 'pruned') prunedCount += 1;
1473
+ else if (r.status === 'running' || r.status === 'waiting') runningCount += 1;
1474
+ if (typeof r.durationMs === 'number' && r.durationMs > maxNodeMs) maxNodeMs = r.durationMs;
1475
+ }
1476
+
1477
+ const fb = fallbackTiming && typeof fallbackTiming === 'object' ? fallbackTiming : null;
1478
+ const startedAt = (sum && typeof sum.startedAt === 'number')
1479
+ ? sum.startedAt
1480
+ : (minNodeStart !== null ? minNodeStart : (fb && typeof fb.startedAt === 'number' ? fb.startedAt : null));
1481
+ const endedAt = (sum && typeof sum.endedAt === 'number')
1482
+ ? sum.endedAt
1483
+ : (!isLive && maxNodeEnd !== null
1484
+ ? maxNodeEnd
1485
+ : (!isLive && fb && typeof fb.endedAt === 'number' ? fb.endedAt : null));
1486
+ const elapsedMs = startedAt !== null
1487
+ ? Math.max(0, (endedAt !== null ? endedAt : (isLive ? clock : (runState.at || clock))) - startedAt)
1488
+ : (maxNodeMs > 0 ? maxNodeMs : null);
1489
+
1490
+ const loops = sum && Array.isArray(sum.loops) ? sum.loops : [];
1491
+ const totalLoops = sum && typeof sum.totalLoops === 'number'
1492
+ ? sum.totalLoops
1493
+ : loops.reduce((acc, l) => acc + (Number(l && l.used) || 0), 0);
1494
+
1495
+ return {
1496
+ hasData: true,
1497
+ status,
1498
+ isLive,
1499
+ waitingLead,
1500
+ haltedReason: (sum && sum.haltedReason) || '',
1501
+ maxParallel: (sum && typeof sum.maxParallel === 'number') ? sum.maxParallel : null,
1502
+ startedAt,
1503
+ endedAt,
1504
+ elapsedMs,
1505
+ totalCount: rows.length,
1506
+ doneCount,
1507
+ failedCount,
1508
+ prunedCount,
1509
+ runningCount,
1510
+ maxNodeMs,
1511
+ totalLoops,
1512
+ loops,
1513
+ nodes: rows,
1514
+ };
1515
+ }
1516
+
1517
+ /** Render a deterministic GitHub-Flavored Markdown report from a run summary view. */
1518
+ function formatRunSummaryMarkdown(view, lang) {
1519
+ if (!view || !view.hasData) return '';
1520
+ const en = lang === 'en';
1521
+ const dict = I18N[en ? 'en' : 'zh'];
1522
+ const statusLabel = (st) => {
1523
+ if (st === 'done') return dict.runStDone;
1524
+ if (st === 'reused') return dict.runSummaryReused;
1525
+ if (st === 'running') return dict.runStRunning;
1526
+ if (st === 'waiting' || st === 'need-lead') return dict.runStWaiting;
1527
+ if (st === 'halted') return dict.runStHalted;
1528
+ if (st === 'failed') return dict.runStFailed;
1529
+ if (st === 'empty') return dict.runStEmpty;
1530
+ if (st === 'pruned') return dict.runStPruned;
1531
+ return dict.runStPending;
1532
+ };
1533
+ const kindLabel = (k) => (k === 'condition' ? (en ? 'Condition' : '条件') : (k === 'lead' ? 'Lead' : (en ? 'Subagent' : '子代理')));
1534
+ const esc = (s) => String(s || '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
1535
+ const lines = [
1536
+ '### ' + dict.runSummaryTitle,
1537
+ '',
1538
+ '- **' + (en ? 'Status' : '状态') + '**: ' + statusLabel(view.status)
1539
+ + (view.waitingLead && view.waitingLead.label ? ' (' + view.waitingLead.label + ')' : ''),
1540
+ '- **' + dict.runSummaryElapsed + '**: ' + formatDurationMs(view.elapsedMs),
1541
+ '- **' + (en ? 'Nodes' : '节点') + '**: ' + view.doneCount + '/' + view.totalCount
1542
+ + (view.failedCount ? ' · ' + view.failedCount + ' ' + dict.runStFailed : '')
1543
+ + (view.prunedCount ? ' · ' + view.prunedCount + ' ' + dict.runStPruned : ''),
1544
+ '- **' + dict.runSummaryLoops + '**: ' + view.totalLoops
1545
+ + (view.maxParallel ? ' · **' + dict.runSummaryParallel + '**: ×' + view.maxParallel : ''),
1546
+ ];
1547
+ if (view.haltedReason) {
1548
+ lines.push('- **' + (en ? 'Halt reason' : '终止原因') + '**: ' + esc(view.haltedReason));
1549
+ }
1550
+ lines.push('');
1551
+ lines.push(en
1552
+ ? '| Node | Type | Status | Duration | Runs | Notes |'
1553
+ : '| 节点 | 类型 | 状态 | 耗时 | 轮次 | 备注 |');
1554
+ lines.push('| :--- | :--- | :--- | ---: | ---: | :--- |');
1555
+ for (const n of view.nodes) {
1556
+ const notes = [];
1557
+ if (n.model) notes.push(n.model);
1558
+ if (n.fallbackUsed) notes.push(dict.runSummaryFallback);
1559
+ if (n.sessionContinued) notes.push(dict.runSummaryContinued);
1560
+ if (n.reason) notes.push(n.reason);
1561
+ lines.push(
1562
+ '| ' + esc(n.label)
1563
+ + ' | ' + kindLabel(n.kind)
1564
+ + ' | ' + statusLabel(n.status)
1565
+ + ' | ' + formatDurationMs(n.durationMs)
1566
+ + ' | ' + (n.runs > 0 ? String(n.runs) : '—')
1567
+ + ' | ' + esc(notes.join(' · '))
1568
+ + ' |',
1569
+ );
1570
+ }
1571
+ if (view.loops && view.loops.length) {
1572
+ lines.push('');
1573
+ lines.push('#### ' + dict.runSummaryLoopsHead);
1574
+ for (const lp of view.loops) {
1575
+ lines.push('- **' + esc(lp.fromLabel) + ' ↺ ' + esc(lp.toLabel) + '** (' + lp.used + '/' + lp.max + (lp.exhausted ? ' · ' + dict.runSummaryExhausted : '') + ')');
1576
+ for (const r of (lp.rounds || [])) {
1577
+ lines.push(' - R' + r.round + ': ' + esc(r.reason));
1578
+ }
1579
+ }
1580
+ }
1581
+ return lines.join('\n');
1582
+ }
1583
+
1214
1584
  function isCustomBranches(node) {
1215
1585
  return Boolean(node && node.kind === 'condition' && Array.isArray(node.branches) && node.branches.length >= 2);
1216
1586
  }
@@ -2057,50 +2427,100 @@ window.__ModuleLoader__.load({
2057
2427
  {
2058
2428
  id: 'lead', kind: 'lead', label: 'Lead', y: 0,
2059
2429
  task: en
2060
- ? 'Implement the requested change and verify with tests: if checks fail, automatically loop back with feedback to fix (up to 3 retries), then hand off to me for final review.'
2061
- : '实现目标功能并跑测试验证:若测试或检查不通过,自动带着失败原因回环修改(最多 3 次),全部通过后交我终审交付。',
2430
+ ? 'Ship OAuth login end-to-end: scan codebase and security constraints in parallel, pause for my sign-off, build core code and tests/docs concurrently with an automated retry loop if checks fail, then deliver to final review.'
2431
+ : '端到端交付 OAuth 登录模块:先并行摸底代码库与安全约束,我拍板后并行开发实现与文档用例;质量门禁未通过则带反馈自动回环修复(最多 3 轮),通过后直达终审交付。',
2432
+ refs: ['AGENTS.md', 'docs/auth-spec.md'],
2062
2433
  provider: '', model: '', role: '',
2063
2434
  },
2435
+ {
2436
+ id: 'lp_scan', kind: 'agent', y: 0,
2437
+ label: en ? 'Codebase Scan' : '代码库摸底',
2438
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: true,
2439
+ role: en
2440
+ ? 'Locate auth routes, session middleware and conventions; keep warm session for Core Implement.'
2441
+ : '定位鉴权路由、会话中间件与工程约定,保留热会话供核心实现无缝续接。',
2442
+ },
2443
+ {
2444
+ id: 'lp_risk', kind: 'agent', y: 100,
2445
+ label: en ? 'Security Spec' : '安全与约束',
2446
+ provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false,
2447
+ refs: ['docs/security.md'],
2448
+ role: en
2449
+ ? 'Read-only threat check (CSRF, PKCE, token rotation); output structured JSON spec.'
2450
+ : '只读梳理 CSRF、PKCE 与令牌轮换约束,输出结构化 JSON 方案。',
2451
+ },
2452
+ {
2453
+ id: 'lp_signoff', kind: 'lead', y: 0,
2454
+ label: en ? 'Lead Sign-Off' : 'Lead 拍板',
2455
+ provider: '', model: '',
2456
+ role: en
2457
+ ? 'Review structured spec, confirm scope and non-goals, then release parallel delivery.'
2458
+ : '评审结构化安全方案,锁定改动边界与不做的事,放行并行实现。',
2459
+ },
2064
2460
  {
2065
2461
  id: 'lp_impl', kind: 'agent', y: 0,
2066
- label: en ? 'Implement' : '编写实现',
2067
- provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
2462
+ label: en ? 'Core Implement' : '核心实现与自测',
2463
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: true,
2068
2464
  role: en
2069
- ? 'Implement the requested change cleanly. When invoked on a retry round, focus directly on fixing the reported issues and list modified files.'
2070
- : '按需求完成代码或文档实现;若处于回环修正轮次,针对打回理由直接定点修复并列出改动清单。',
2465
+ ? 'Continue inside scan session to implement OAuth flow and run tests; on retry rounds fix reported defects directly.'
2466
+ : '沿用摸底热会话实现 OAuth 流程并跑测试;若被打回则按反馈定点修复。',
2071
2467
  },
2072
2468
  {
2073
- id: 'lp_test', kind: 'agent', y: 0,
2074
- label: en ? 'Test & Verify' : '测试与检查',
2469
+ id: 'lp_docs', kind: 'agent', y: 100,
2470
+ label: en ? 'Docs & Checklist' : '文档与验收清单',
2075
2471
  provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
2076
2472
  role: en
2077
- ? 'Run tests/lint/checks against the implementation and report exact pass/fail status, error logs, and remaining defects.'
2078
- : '对实现结果运行单测、构建或逐项核验,如实汇报通过情况、具体报错日志与遗留缺陷。',
2473
+ ? 'Update config docs and acceptance checklist in parallel (never touch source files).'
2474
+ : '并行补齐配置文档与验收清单(不改业务源码,与回环实现互不干扰)。',
2079
2475
  },
2080
2476
  {
2081
2477
  id: 'lp_gate', kind: 'condition', y: 0,
2082
- label: en ? 'Checks Passed?' : '是否通过?',
2478
+ label: en ? 'Quality Gate' : '质量门禁',
2083
2479
  provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false,
2480
+ branches: [
2481
+ { id: 'true', label: en ? 'Pass' : '通过', when: en ? 'All tests and security checks passed' : '单测与安全核验全部通过' },
2482
+ { id: 'false', label: en ? 'Fix Loop' : '打回修复', when: en ? 'Any test failed or defect remains' : '存在测试失败或未解决缺陷' },
2483
+ ],
2084
2484
  role: en
2085
- ? 'Return pass=true only if all tests/checks passed with no unresolved defects; otherwise return pass=false with a concise, actionable fix reason.'
2086
- : '仅当测试与检查全部通过且无未解决缺陷时返回 true;否则返回 false,并在理由里写清下一轮需修复的具体问题。',
2485
+ ? 'Verify test results and security checklist; route to Pass only when clean, otherwise return actionable fix feedback.'
2486
+ : '核验测试结果与安全清单;全部通过走「通过」,否则走「打回修复」并附具体修复理由。',
2087
2487
  },
2088
2488
  {
2089
2489
  id: 'lp_final', kind: 'lead', y: 0,
2090
- label: en ? 'Lead Final Review' : 'Lead 终审',
2490
+ label: en ? 'Lead Ship Gate' : 'Lead 终审交付',
2091
2491
  provider: '', model: '',
2092
2492
  role: en
2093
- ? 'Review the verified result (or the round-by-round summary if retries exhausted) and decide whether to ship or intervene.'
2094
- : '审阅最终通过的改动摘要(或回环达上限后的历次失败记录),确认交付或拍板下一步处理。',
2493
+ ? 'Combine verified implementation and docs into final release summary.'
2494
+ : '汇聚通过门禁的实现与文档,给出最终交付结论。',
2095
2495
  },
2096
2496
  ];
2097
2497
  const loopEdges = [
2098
- { id: 'lp1', from: 'lead', to: 'lp_impl', type: 'prompt' },
2099
- { id: 'lp2', from: 'lp_impl', to: 'lp_test', type: 'prompt' },
2100
- { id: 'lp3', from: 'lp_test', to: 'lp_gate', type: 'prompt' },
2101
- { id: 'lp4', from: 'lp_gate', to: 'lp_final', type: 'prompt', branch: 'true' },
2102
- { id: 'lp5', from: 'lp_gate', to: 'lp_impl', type: 'prompt', branch: 'false', loop: true, maxIterations: 3 },
2498
+ { id: 'lp1', from: 'lead', to: 'lp_scan', type: 'prompt' },
2499
+ { id: 'lp2', from: 'lead', to: 'lp_risk', type: 'prompt' },
2500
+ { id: 'lp3', from: 'lp_scan', to: 'lp_signoff', type: 'prompt' },
2501
+ { id: 'lp4', from: 'lp_risk', to: 'lp_signoff', type: 'structured' },
2502
+ { id: 'lp5', from: 'lp_signoff', to: 'lp_impl', type: 'prompt' },
2503
+ { id: 'lp6', from: 'lp_scan', to: 'lp_impl', type: 'session-ref' },
2504
+ { id: 'lp7', from: 'lp_signoff', to: 'lp_docs', type: 'prompt' },
2505
+ { id: 'lp8', from: 'lp_impl', to: 'lp_gate', type: 'prompt' },
2506
+ { id: 'lp9', from: 'lp_gate', to: 'lp_final', type: 'prompt', branch: 'true' },
2507
+ { id: 'lp10', from: 'lp_gate', to: 'lp_impl', type: 'prompt', branch: 'false', loop: true, maxIterations: 3 },
2508
+ { id: 'lp11', from: 'lp_docs', to: 'lp_final', type: 'prompt' },
2103
2509
  ];
2510
+ // Align the loop pair (lp_impl -> lp_gate) on the outer rail side (top in lr, right in tb)
2511
+ // so the dashed loop frame and outer bypass arc never overlap the parallel bypass node lp_docs.
2512
+ const loopLaid = layoutGraph(loopNodes, loopEdges, direction).map((n) => ({ ...n }));
2513
+ const lpById = new Map(loopLaid.map((n) => [n.id, n]));
2514
+ if (direction === 'tb') {
2515
+ const leftX = Math.min(lpById.get('lp_impl').x, lpById.get('lp_docs').x);
2516
+ const rightX = Math.max(lpById.get('lp_impl').x, lpById.get('lp_docs').x);
2517
+ lpById.get('lp_docs').x = leftX;
2518
+ lpById.get('lp_impl').x = rightX;
2519
+ lpById.get('lp_gate').x = rightX;
2520
+ } else {
2521
+ lpById.get('lp_gate').y = lpById.get('lp_impl').y - 8;
2522
+ lpById.get('lp_docs').y = Math.max(lpById.get('lp_docs').y, lpById.get('lp_gate').y + nodeHeight(lpById.get('lp_gate')) + 64);
2523
+ }
2104
2524
  return [
2105
2525
  {
2106
2526
  id: 'tpl-swe',
@@ -2128,8 +2548,8 @@ window.__ModuleLoader__.load({
2128
2548
  },
2129
2549
  {
2130
2550
  id: 'tpl-loop',
2131
- name: en ? 'Retry Loop: Implement → Test ↺ Fix → Review' : '循环重试:实现 → 测试验收 ↺ 自动修复 → 终审',
2132
- nodes: layoutGraph(loopNodes, loopEdges, direction),
2551
+ name: en ? 'Full Showcase: Parallel → Gate → Loop ↺ Fix → Ship' : '全功能回环:并行摸底 → 拍板 → 实现 ↺ 门禁 → 终审',
2552
+ nodes: loopLaid,
2133
2553
  edges: loopEdges,
2134
2554
  },
2135
2555
  ];
@@ -2459,7 +2879,8 @@ window.__ModuleLoader__.load({
2459
2879
  }
2460
2880
  }
2461
2881
 
2462
- function storageKey(sessionId) { return STORAGE_PREFIX + (sessionId || '__global__');
2882
+ function storageKey(sessionId) {
2883
+ return STORAGE_PREFIX + (sessionId || '__global__');
2463
2884
  }
2464
2885
 
2465
2886
  function loadDoc(sessionId) {
@@ -2474,13 +2895,60 @@ window.__ModuleLoader__.load({
2474
2895
  }
2475
2896
  }
2476
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
+
2477
2934
  function saveDoc(sessionId, doc, stamp) {
2935
+ const key = storageKey(sessionId);
2936
+ const serialized = JSON.stringify({ ...doc, at: typeof stamp === 'number' ? stamp : Date.now() });
2478
2937
  try {
2479
- /** Stamp every local edit so a stale generated canvas cannot overwrite it. */
2480
- const stamped = { ...doc, at: typeof stamp === 'number' ? stamp : Date.now() };
2481
- 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);
2482
2944
  } catch (_e) {
2483
- /* 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
+ }
2484
2952
  }
2485
2953
  }
2486
2954
 
@@ -2552,6 +3020,9 @@ window.__ModuleLoader__.load({
2552
3020
  const [menuAlign, setMenuAlign] = useState('right');
2553
3021
  const [presetAlign, setPresetAlign] = useState('right');
2554
3022
  const [helpOpen, setHelpOpen] = useState(false);
3023
+ const [summaryOpen, setSummaryOpen] = useState(false);
3024
+ const [summaryNow, setSummaryNow] = useState(() => Date.now());
3025
+ const clientRunTimingRef = useRef({ startedAt: null, endedAt: null, prevStatus: '', runAt: null });
2555
3026
  const [shortcuts, setShortcuts] = useState(loadShortcuts);
2556
3027
  const shortcutsRef = useRef(shortcuts);
2557
3028
  shortcutsRef.current = shortcuts;
@@ -2673,12 +3144,64 @@ window.__ModuleLoader__.load({
2673
3144
  const skipDirtyOnce = useRef(false);
2674
3145
  const staleChildIds = useRef(new Set());
2675
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);
2676
3155
  useEffect(() => {
3156
+ if (!didInitSaveRef.current) {
3157
+ didInitSaveRef.current = true;
3158
+ return undefined;
3159
+ }
2677
3160
  const stamp = applyStamp.current;
2678
3161
  applyStamp.current = null;
2679
- 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;
2680
3184
  }, [sessionId, nodes, edges, enabled, direction]);
2681
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
+
2682
3205
  // Plan signature excludes visual (x, y) coordinates so dragging nodes does
2683
3206
  // not trigger false "unsaved changes" warnings; `skipDirtyOnce` suppresses
2684
3207
  // the dirty flag when applying a canvas written by the Host itself.
@@ -2698,7 +3221,7 @@ window.__ModuleLoader__.load({
2698
3221
  skipDirtyOnce.current = false;
2699
3222
  return;
2700
3223
  }
2701
- if (!enabled) return;
3224
+ if (!enabled || nodeDrag.current) return;
2702
3225
  const sig = planSig(true, nodes, edges);
2703
3226
  if (lastSync.current && sig === lastSync.current) {
2704
3227
  setDirty(false);
@@ -2925,10 +3448,14 @@ window.__ModuleLoader__.load({
2925
3448
  await Promise.all(tasks);
2926
3449
  runTriggeringRef.current = false;
2927
3450
  setRunTriggering(false);
3451
+ const stopNow = Date.now();
2928
3452
  setRunState((prev) => ({
2929
3453
  ...(prev || {}),
2930
3454
  status: 'halted',
2931
3455
  waitingLead: null,
3456
+ ...(prev && prev.summary
3457
+ ? { summary: { ...prev.summary, status: 'halted', endedAt: prev.summary.endedAt || stopNow } }
3458
+ : {}),
2932
3459
  }));
2933
3460
  setStatusById((prev) => {
2934
3461
  const next = {};
@@ -2949,8 +3476,12 @@ window.__ModuleLoader__.load({
2949
3476
  // Sync the moment a user message starts a turn, so this turn's tool call
2950
3477
  // already sees the latest canvas. Falls back to the turn end if the start
2951
3478
  // edge was missed; `dirty` clears on success so only one fires.
2952
- const liveRef = useRef({ enabled, dirty, pushPlan });
2953
- 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 };
2954
3485
 
2955
3486
  useEffect(() => {
2956
3487
  const face = sessionFace(sessionId);
@@ -2962,7 +3493,8 @@ window.__ModuleLoader__.load({
2962
3493
  try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
2963
3494
  if (running !== wasRunning) {
2964
3495
  const live = liveRef.current;
2965
- 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);
2966
3498
  }
2967
3499
  wasRunning = running;
2968
3500
  };
@@ -3067,16 +3599,20 @@ window.__ModuleLoader__.load({
3067
3599
  const stop = () => { if (timer) { clearInterval(timer); timer = null; } };
3068
3600
  let wasRunning = false;
3069
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
+ };
3070
3606
  setSessionRunning(wasRunning);
3071
3607
  read();
3072
- if (wasRunning) timer = setInterval(read, 700);
3608
+ if (wasRunning) timer = setInterval(readIfVisible, 700);
3073
3609
  const onSnapshot = () => {
3074
3610
  let running = false;
3075
3611
  try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
3076
3612
  const finished = !running && wasRunning;
3077
3613
  wasRunning = running;
3078
3614
  setSessionRunning(running);
3079
- if (running && !timer) { read(); timer = setInterval(read, 700); }
3615
+ if (running && !timer) { read(); timer = setInterval(readIfVisible, 700); }
3080
3616
  if (!running && timer) { stop(); read(); }
3081
3617
  if (finished && typeof sessions.refreshProjections === 'function') {
3082
3618
  Promise.resolve(sessions.refreshProjections(sessionId)).then(read, () => {});
@@ -3191,6 +3727,13 @@ window.__ModuleLoader__.load({
3191
3727
  centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2, nextK);
3192
3728
  };
3193
3729
 
3730
+ const focusNode = (nodeId) => {
3731
+ const target = nodesRef.current.find((n) => n.id === nodeId);
3732
+ if (!target) return;
3733
+ setSelectedIds([target.id]);
3734
+ centerOn(target.x + NODE_W / 2, target.y + nodeHeight(target) / 2);
3735
+ };
3736
+
3194
3737
  /** Horizontal drag scrubber on the percentage pill; pure click resets to 100% on Lead. */
3195
3738
  const onZoomPillDown = (e) => {
3196
3739
  if (e.button !== 0) return;
@@ -3350,7 +3893,7 @@ window.__ModuleLoader__.load({
3350
3893
  }
3351
3894
  };
3352
3895
 
3353
- const openNodeSession = async (node) => {
3896
+ const openNodeSession = async (node, fallbackChildId) => {
3354
3897
  let run = runsById[node.id];
3355
3898
  if (!run) {
3356
3899
  const sessions = hostCtx && hostCtx.sessions;
@@ -3364,6 +3907,9 @@ window.__ModuleLoader__.load({
3364
3907
  run = nextRuns[node.id];
3365
3908
  }
3366
3909
  }
3910
+ if (!run && fallbackChildId) {
3911
+ run = { childId: fallbackChildId, mode: 'local', label: node.label || node.id };
3912
+ }
3367
3913
  if (!run) { flash(t('cannotOpen')); return; }
3368
3914
  openRun(node, run);
3369
3915
  };
@@ -3705,12 +4251,7 @@ window.__ModuleLoader__.load({
3705
4251
  flash(t('clearedCanvas'));
3706
4252
  };
3707
4253
 
3708
- const exportToClipboard = () => {
3709
- const cleanNodes = nodesRef.current.map((n) => {
3710
- const { runs: _runs, ...rest } = n;
3711
- return rest;
3712
- });
3713
- const text = JSON.stringify({ nodes: cleanNodes, edges: edgesRef.current, direction: directionRef.current }, null, 2);
4254
+ const copyTextToClipboard = (text, okMsg) => {
3714
4255
  const fallbackCopy = () => {
3715
4256
  try {
3716
4257
  const ta = document.createElement('textarea');
@@ -3721,20 +4262,35 @@ window.__ModuleLoader__.load({
3721
4262
  ta.select();
3722
4263
  const ok = document.execCommand && document.execCommand('copy');
3723
4264
  document.body.removeChild(ta);
3724
- flash(ok ? t('exportOk') : t('exportFail'));
4265
+ flash(ok ? okMsg : t('exportFail'));
3725
4266
  } catch (_e) {
3726
4267
  flash(t('exportFail'));
3727
4268
  }
3728
4269
  };
3729
4270
  try {
3730
4271
  if (navigator.clipboard && navigator.clipboard.writeText) {
3731
- navigator.clipboard.writeText(text).then(() => flash(t('exportOk')), fallbackCopy);
4272
+ navigator.clipboard.writeText(text).then(() => flash(okMsg), fallbackCopy);
3732
4273
  return;
3733
4274
  }
3734
4275
  } catch (_e) { /* fall through */ }
3735
4276
  fallbackCopy();
3736
4277
  };
3737
4278
 
4279
+ const exportToClipboard = () => {
4280
+ const cleanNodes = nodesRef.current.map((n) => {
4281
+ const { runs: _runs, ...rest } = n;
4282
+ return rest;
4283
+ });
4284
+ const text = JSON.stringify({ nodes: cleanNodes, edges: edgesRef.current, direction: directionRef.current }, null, 2);
4285
+ copyTextToClipboard(text, t('exportOk'));
4286
+ };
4287
+
4288
+ const copyRunSummary = (view) => {
4289
+ const md = formatRunSummaryMarkdown(view, lang);
4290
+ if (!md) { flash(t('runSummaryEmpty')); return; }
4291
+ copyTextToClipboard(md, t('runSummaryCopied'));
4292
+ };
4293
+
3738
4294
  const openAddMenuAtCursor = () => {
3739
4295
  const wrap = canvasWrapRef.current;
3740
4296
  const content = contentRef.current;
@@ -4051,9 +4607,18 @@ window.__ModuleLoader__.load({
4051
4607
  const keyActionsRef = useRef(null);
4052
4608
  keyActionsRef.current = {
4053
4609
  undo, redo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode, fitView, autoLayout, toggleDirection, flash, t,
4054
- addMenu, ctxMenu, loopEditEdgeId, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, shortcutsOpen, recordingAction, decisionViewFor, refsEditFor,
4055
- setAddMenu, setCtxMenu, setLoopEditEdgeId, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
4610
+ addMenu, ctxMenu, loopEditEdgeId, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, summaryOpen, shortcutsOpen, recordingAction, decisionViewFor, refsEditFor,
4611
+ setAddMenu, setCtxMenu, setLoopEditEdgeId, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setSummaryOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
4056
4612
  };
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.
4616
+ useEffect(() => {
4617
+ if (!summaryIsLive || !summaryOpen) return undefined;
4618
+ setSummaryNow(Date.now());
4619
+ const timer = setInterval(() => setSummaryNow(Date.now()), 1000);
4620
+ return () => clearInterval(timer);
4621
+ }, [summaryIsLive, summaryOpen]);
4057
4622
  useEffect(() => {
4058
4623
  const isEditable = (target) => {
4059
4624
  if (!target || !(target instanceof HTMLElement)) return false;
@@ -4061,6 +4626,8 @@ window.__ModuleLoader__.load({
4061
4626
  return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
4062
4627
  };
4063
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;
4064
4631
  const act = keyActionsRef.current;
4065
4632
  if (!act) return;
4066
4633
  if (act.recordingAction) {
@@ -4081,7 +4648,7 @@ window.__ModuleLoader__.load({
4081
4648
  return;
4082
4649
  }
4083
4650
  if (ev.key === 'Escape') {
4084
- if (act.addMenu || act.ctxMenu || act.loopEditEdgeId || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen || act.shortcutsOpen || act.decisionViewFor || act.refsEditFor) {
4651
+ if (act.addMenu || act.ctxMenu || act.loopEditEdgeId || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen || act.summaryOpen || act.shortcutsOpen || act.decisionViewFor || act.refsEditFor) {
4085
4652
  ev.preventDefault();
4086
4653
  act.setAddMenu(null);
4087
4654
  act.setCtxMenu(null);
@@ -4091,6 +4658,7 @@ window.__ModuleLoader__.load({
4091
4658
  act.setMenuOpen(false);
4092
4659
  act.setPresetOpen(null);
4093
4660
  act.setHelpOpen(false);
4661
+ act.setSummaryOpen(false);
4094
4662
  act.setShortcutsOpen(false);
4095
4663
  act.setRecordingAction(null);
4096
4664
  act.setDecisionViewFor(null);
@@ -4098,7 +4666,7 @@ window.__ModuleLoader__.load({
4098
4666
  }
4099
4667
  return;
4100
4668
  }
4101
- if (act.shortcutsOpen) return;
4669
+ if (act.shortcutsOpen || act.summaryOpen || act.helpOpen) return;
4102
4670
  if (isEditable(ev.target)) return;
4103
4671
  if (act.addMenu) {
4104
4672
  const lf = act.addMenu.linkFrom || null;
@@ -4172,11 +4740,43 @@ window.__ModuleLoader__.load({
4172
4740
  return () => window.removeEventListener('keydown', onKey);
4173
4741
  }, []);
4174
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 });
4175
4746
  useEffect(() => {
4176
4747
  if (!dragging) return undefined;
4177
- const move = (ev) => onCanvasMove(ev);
4178
- 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
+ };
4179
4778
  const cancelDrag = () => {
4779
+ cancelRaf();
4180
4780
  panDrag.current = null;
4181
4781
  nodeDrag.current = null;
4182
4782
  rightClickRef.current = null;
@@ -4194,11 +4794,12 @@ window.__ModuleLoader__.load({
4194
4794
  window.addEventListener('mouseup', up);
4195
4795
  window.addEventListener('blur', cancelDrag);
4196
4796
  return () => {
4797
+ cancelRaf();
4197
4798
  window.removeEventListener('mousemove', move);
4198
4799
  window.removeEventListener('mouseup', up);
4199
4800
  window.removeEventListener('blur', cancelDrag);
4200
4801
  };
4201
- }, [dragging, marquee, pending]);
4802
+ }, [dragging]);
4202
4803
 
4203
4804
  const onCanvasDown = (e) => {
4204
4805
  if (e.button === 2) {
@@ -4357,8 +4958,14 @@ window.__ModuleLoader__.load({
4357
4958
  }
4358
4959
  }
4359
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;
4360
4964
  if (marquee) {
4361
- 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));
4362
4969
  setMarquee(null);
4363
4970
  }
4364
4971
  if (panDrag.current) {
@@ -4369,7 +4976,9 @@ window.__ModuleLoader__.load({
4369
4976
  const handled = pendingHandledRef.current;
4370
4977
  pendingHandledRef.current = false;
4371
4978
  if (!handled && pending && pending.dir === 'out') {
4372
- 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);
4373
4982
  const wrap = canvasWrapRef.current;
4374
4983
  if (dist >= 16 && wrap) {
4375
4984
  const wrapRect = wrap.getBoundingClientRect();
@@ -4380,8 +4989,8 @@ window.__ModuleLoader__.load({
4380
4989
  setAddMenu({
4381
4990
  sx,
4382
4991
  sy,
4383
- wx: pending.x,
4384
- wy: pending.y,
4992
+ wx: px,
4993
+ wy: py,
4385
4994
  linkFrom: {
4386
4995
  fromId: pending.fromId,
4387
4996
  type: pending.type || 'prompt',
@@ -4389,8 +4998,8 @@ window.__ModuleLoader__.load({
4389
4998
  color: pending.color || '#8a8f98',
4390
4999
  sx: pending.sx,
4391
5000
  sy: pending.sy,
4392
- x: pending.x,
4393
- y: pending.y,
5001
+ x: px,
5002
+ y: py,
4394
5003
  },
4395
5004
  });
4396
5005
  setMenuOpen(false);
@@ -4402,6 +5011,7 @@ window.__ModuleLoader__.load({
4402
5011
  setPending(null);
4403
5012
  setDragging(false);
4404
5013
  };
5014
+ dragHandlersRef.current = { move: onCanvasMove, up: onCanvasUp };
4405
5015
 
4406
5016
  const savePresetNow = () => {
4407
5017
  const name = presetName.trim();
@@ -4434,7 +5044,9 @@ window.__ModuleLoader__.load({
4434
5044
  const merge = doc.mode === 'merge';
4435
5045
  if (!merge && !doc.nodes.length) return false;
4436
5046
  pushSnapshot();
4437
- 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;
4438
5050
  applyStamp.current = stamp;
4439
5051
  if (fromRemote) {
4440
5052
  skipDirtyOnce.current = true;
@@ -4568,7 +5180,17 @@ window.__ModuleLoader__.load({
4568
5180
 
4569
5181
  // The Host writes generated canvases where the workspace Remote can read
4570
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.
4571
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]);
4572
5194
  useEffect(() => {
4573
5195
  if (!AUTO_CANVAS) return undefined;
4574
5196
  let remote;
@@ -4579,101 +5201,251 @@ window.__ModuleLoader__.load({
4579
5201
  }
4580
5202
  if (!wf || typeof wf.read !== 'function') { setSyncNote(t('syncOff')); return undefined; }
4581
5203
  if (!sessionId) { setSyncNote(t('syncNoSession')); return undefined; }
4582
- // The Host names the file after the agent id (session-<uuid>); the
4583
- // 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);
4584
5208
  const bare = String(sessionId).replace(/^session-/, '');
5209
+ const safeBare = sanitizeId(bare);
4585
5210
  const paths = [
4586
- '.dsh/canvas/' + String(sessionId) + '.json',
4587
- '.dsh/canvas/session-' + bare + '.json',
4588
- '.dsh/canvas/' + bare + '.json',
4589
- ].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);
4590
5215
  const runPaths = [
4591
- '.dsh/canvas/' + String(sessionId) + '.run.json',
4592
- '.dsh/canvas/session-' + bare + '.run.json',
4593
- '.dsh/canvas/' + bare + '.run.json',
4594
- ].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);
4595
5220
  setRunState(null);
4596
5221
  setDecisionViewFor(null);
4597
5222
  let alive = true;
5223
+ let busy = false;
5224
+ let timer = null;
4598
5225
  let lastText = '';
4599
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
+
4600
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;
4601
5309
  try {
4602
- let text = '';
4603
- for (const path of paths) {
4604
- try {
4605
- const res = await wf.read(sessionId, path, {}, new AbortController().signal);
4606
- if (!alive) return;
4607
- const payload = res && res.ok === false ? null : (res && res.value !== undefined ? res.value : res);
4608
- const read = payload && (typeof payload.text === 'string' ? payload.text : '');
4609
- if (read) { text = read; break; }
4610
- } catch (err) {
5310
+ try {
5311
+ const { text, hit, statSig, unchanged } = await readFirstMatch(paths, cachedCanvasPath, lastCanvasStatSig, (err) => {
4611
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
+ }
4612
5321
  }
4613
- }
4614
- if (text && text !== lastText) {
4615
- lastText = text;
4616
- const doc = JSON.parse(text);
4617
- const canvas = doc && doc.canvas;
4618
- // A canvas the user has edited more recently wins over an old file.
4619
- let staleLocal = false;
4620
- try {
4621
- const raw = window.localStorage.getItem(storageKey(sessionId));
4622
- const local = raw ? JSON.parse(raw) : null;
4623
- if (local && typeof local.at === 'number' && typeof doc.at === 'number' && local.at > doc.at) {
4624
- 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'));
4625
5351
  }
4626
- } catch (_e) { /* ignore */ }
4627
- if (!staleLocal) {
4628
- const valid = canvas && Array.isArray(canvas.nodes)
4629
- && (canvas.mode === 'merge' || canvas.nodes.length > 0)
4630
- && canvas.nodes.every((n) => n && typeof n.id === 'string');
4631
- if (valid && applyCanvasDoc(canvas, doc.at, true)) {
4632
- flash(t('generated'));
4633
- setSyncNote(t('syncApplied'));
4634
- 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;
4635
5364
  }
4636
- else setSyncNote(t('syncBadFile'));
4637
5365
  }
4638
- }
4639
- } catch (_e) { /* file absent or not readable yet */ }
4640
- try {
4641
- let runText = '';
4642
- for (const rp of runPaths) {
4643
- try {
4644
- const res = await wf.read(sessionId, rp, {}, new AbortController().signal);
4645
- if (!alive) return;
4646
- const payload = res && res.ok === false ? null : (res && res.value !== undefined ? res.value : res);
4647
- const read = payload && (typeof payload.text === 'string' ? payload.text : '');
4648
- if (read) { runText = read; break; }
4649
- } catch (_e) { /* ignore */ }
4650
- }
4651
- if (runText && runText !== lastRunText) {
4652
- lastRunText = runText;
4653
- const parsed = JSON.parse(runText);
4654
- if (parsed && typeof parsed === 'object') {
4655
- 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;
4656
5375
  }
4657
- }
4658
- } 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();
4659
5387
  };
4660
- 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
+ }
4661
5418
  tick();
4662
- 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
+ };
4663
5432
  }, [sessionId]);
4664
5433
 
4665
5434
  const importFromClipboard = () => {
4666
5435
  const finish = (text) => {
4667
- 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; }
4668
5438
  let doc;
4669
5439
  try {
4670
5440
  const start = text.indexOf('{');
4671
5441
  const end = text.lastIndexOf('}');
5442
+ if (start === -1 || end <= start) { flash(t('importBad')); return; }
4672
5443
  doc = JSON.parse(text.slice(start, end + 1));
4673
5444
  } catch (_e) { flash(t('importBad')); return; }
4674
- 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; }
4675
5447
  if (enabled) setTimeout(() => pushPlan(true), 0);
4676
- flash(t('importOk') + (doc.canvas || doc).nodes.length);
5448
+ flash(t('importOk') + payload.nodes.length);
4677
5449
  };
4678
5450
  try {
4679
5451
  if (navigator.clipboard && navigator.clipboard.readText) {
@@ -4982,27 +5754,39 @@ window.__ModuleLoader__.load({
4982
5754
  };
4983
5755
 
4984
5756
  const fxName = (level) => (level === 'minimal' ? t('fxMinimal') : (level === 'vivid' ? t('fxVivid') : t('fxStandard')));
4985
- const selectedSet = new Set(selectedIds);
4986
- const nodeById = new Map(nodes.map((n) => [n.id, n]));
4987
- const inColorByNode = new Map();
4988
- const inCountByNode = new Map();
4989
- const inPriority = (e) => (e.loop ? 0.5 : (e.type === 'session-ref' ? 3 : (e.type === 'structured' ? 2 : (e.branch ? 1.5 : 1))));
4990
- const inPrioByNode = new Map();
4991
- const connectedOut = new Set();
4992
- for (const e of edges) {
4993
- const type = e.type || 'prompt';
4994
- const b = typeof e.branch === 'string' ? e.branch.trim() : '';
4995
- connectedOut.add(e.from + '|' + (b ? 'branch:' + b : type));
4996
- inCountByNode.set(e.to, (inCountByNode.get(e.to) || 0) + 1);
4997
- const prio = inPriority(e);
4998
- if (!inPrioByNode.has(e.to) || prio >= inPrioByNode.get(e.to)) {
4999
- inPrioByNode.set(e.to, prio);
5000
- 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
+ }
5001
5777
  }
5002
- }
5003
- const reachableIds = reachableFrom(nodes, edges);
5004
- const soloLeadIds = soloLeadNodeIds(nodes, edges);
5005
- 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;
5006
5790
 
5007
5791
  // Lead nodes are never spawned, so their status is derived via `deriveLeadStatuses`,
5008
5792
  // honoring authoritative backend `runState.status` (`halted` / `done` / `need-lead`).
@@ -5041,7 +5825,51 @@ window.__ModuleLoader__.load({
5041
5825
  const nodeAttemptsMap = (enabled && runState && runState.nodeAttempts && typeof runState.nodeAttempts === 'object')
5042
5826
  ? runState.nodeAttempts
5043
5827
  : {};
5044
- const loopGroups = loopGroupsForUI(nodes, edges);
5828
+ // Client-side fallback wall-clock tracking in case an older backend `.run.json` omits `summary.startedAt`.
5829
+ // Never synthesize startedAt from `runState.at` (which is the write/finish timestamp of `.run.json`).
5830
+ (() => {
5831
+ const curSt = runState && typeof runState.status === 'string' ? runState.status : '';
5832
+ const curAt = runState && typeof runState.at === 'number' ? runState.at : null;
5833
+ const tr = clientRunTimingRef.current;
5834
+ if (!curSt || curSt === 'idle') {
5835
+ tr.startedAt = null;
5836
+ tr.endedAt = null;
5837
+ tr.runAt = null;
5838
+ tr.prevStatus = curSt;
5839
+ } else if (curSt === 'running' && tr.prevStatus !== 'running' && tr.prevStatus !== 'need-lead') {
5840
+ tr.startedAt = (runState && runState.summary && typeof runState.summary.startedAt === 'number')
5841
+ ? runState.summary.startedAt
5842
+ : Date.now();
5843
+ tr.endedAt = null;
5844
+ tr.runAt = curAt;
5845
+ tr.prevStatus = curSt;
5846
+ } else if (curSt === 'done' || curSt === 'halted') {
5847
+ if (tr.prevStatus === 'running' || tr.prevStatus === 'need-lead') {
5848
+ if (tr.startedAt !== null) {
5849
+ tr.endedAt = (runState && runState.summary && typeof runState.summary.endedAt === 'number')
5850
+ ? runState.summary.endedAt
5851
+ : Date.now();
5852
+ tr.runAt = curAt;
5853
+ }
5854
+ } else if (curAt !== null && tr.runAt !== null && curAt !== tr.runAt) {
5855
+ // A fresh terminal `.run.json` arrived without observing a `running` poll in between:
5856
+ // drop any prior run's client clock rather than mixing two different runs.
5857
+ tr.startedAt = null;
5858
+ tr.endedAt = null;
5859
+ tr.runAt = curAt;
5860
+ }
5861
+ tr.prevStatus = curSt;
5862
+ } else {
5863
+ tr.prevStatus = curSt;
5864
+ }
5865
+ })();
5866
+ const runSummary = buildRunSummaryView({
5867
+ runState,
5868
+ nodes,
5869
+ runsById,
5870
+ now: summaryNow,
5871
+ fallbackTiming: clientRunTimingRef.current,
5872
+ });
5045
5873
  const edgeKeyForState = (e) => String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
5046
5874
  const loopPillItems = [];
5047
5875
 
@@ -5747,6 +6575,12 @@ window.__ModuleLoader__.load({
5747
6575
  onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
5748
6576
  onClick: () => { toggleLang(); },
5749
6577
  }, t('ctxLangToggle') + t('sep') + (lang === 'zh' ? '中文' : 'EN')),
6578
+ h('div', {
6579
+ style: S.moreRow,
6580
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
6581
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
6582
+ onClick: () => { setMenuOpen(false); setSummaryNow(Date.now()); setSummaryOpen(true); },
6583
+ }, t('runSummaryMenu')),
5750
6584
  h('div', {
5751
6585
  style: S.moreRow,
5752
6586
  onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
@@ -5775,6 +6609,165 @@ window.__ModuleLoader__.load({
5775
6609
  h('div', { style: S.helpBody }, t('helpBody').split('\n').map((line, i) => h('div', { key: i, style: S.helpLine }, line))),
5776
6610
  ),
5777
6611
  ),
6612
+ summaryOpen && (() => {
6613
+ const stVisual = (st) => {
6614
+ if (st === 'done') return { icon: '✓', color: '#3fb950', label: t('runStDone') };
6615
+ if (st === 'reused') return { icon: '⚡', color: '#3fb950', label: t('runSummaryReused') };
6616
+ if (st === 'running') return { icon: '●', color: '#2f81f7', label: t('runStRunning') };
6617
+ if (st === 'waiting' || st === 'need-lead') return { icon: '⏸', color: '#2f81f7', label: t('runStWaiting') };
6618
+ if (st === 'halted') return { icon: '⏹', color: '#e5534b', label: t('runStHalted') };
6619
+ if (st === 'failed') return { icon: '✕', color: '#e5534b', label: t('runStFailed') };
6620
+ if (st === 'empty') return { icon: '⚠', color: '#d29922', label: t('runStEmpty') };
6621
+ if (st === 'pruned') return { icon: '↷', color: C.dim, label: t('runStPruned') };
6622
+ return { icon: '○', color: C.dim, label: t('runStPending') };
6623
+ };
6624
+ const topSt = runSummary.hasData ? stVisual(runSummary.status) : null;
6625
+ return h('div', {
6626
+ style: S.helpOverlay,
6627
+ onMouseDown: (e) => { e.stopPropagation(); if (e.target === e.currentTarget) setSummaryOpen(false); },
6628
+ },
6629
+ h('div', { style: { ...S.helpCard, maxWidth: '460px', display: 'flex', flexDirection: 'column', maxHeight: '82%', overflow: 'hidden' } },
6630
+ h('div', { style: { ...S.helpHead, flex: '0 0 auto' } },
6631
+ h('span', { style: { ...S.helpTitle, display: 'inline-flex', alignItems: 'center', gap: '6px', minWidth: 0 } },
6632
+ h('span', null, t('runSummaryTitle')),
6633
+ topSt && h('span', {
6634
+ style: {
6635
+ fontSize: '10px', fontWeight: 600, padding: '1px 6px', borderRadius: '999px',
6636
+ color: topSt.color, border: '1px solid ' + topSt.color,
6637
+ whiteSpace: 'nowrap',
6638
+ },
6639
+ }, topSt.icon + ' ' + topSt.label),
6640
+ ),
6641
+ runSummary.hasData && h('button', {
6642
+ style: S.btn,
6643
+ type: 'button',
6644
+ onClick: () => copyRunSummary(runSummary),
6645
+ }, t('runSummaryCopy')),
6646
+ h('button', {
6647
+ style: S.btn,
6648
+ type: 'button',
6649
+ onClick: () => setSummaryOpen(false),
6650
+ }, t('close')),
6651
+ ),
6652
+ !runSummary.hasData
6653
+ ? h('div', { style: { padding: '18px 8px', textAlign: 'center', color: C.dim, fontSize: '12px' } }, t('runSummaryEmpty'))
6654
+ : h(React.Fragment, null,
6655
+ h('div', { style: S.summaryKpiRow },
6656
+ h('div', { style: S.summaryKpi },
6657
+ h('span', { style: { fontSize: '10px', color: C.dim } }, t('runSummaryElapsed')),
6658
+ h('span', { style: { fontSize: '13px', fontWeight: 600, color: C.text, fontVariantNumeric: 'tabular-nums' } }, formatDurationMs(runSummary.elapsedMs)),
6659
+ ),
6660
+ h('div', { style: S.summaryKpi },
6661
+ h('span', { style: { fontSize: '10px', color: C.dim } }, t('runSummaryDone')),
6662
+ h('span', { style: { fontSize: '13px', fontWeight: 600, color: runSummary.failedCount ? '#e5534b' : '#3fb950', fontVariantNumeric: 'tabular-nums' } },
6663
+ runSummary.doneCount + '/' + runSummary.totalCount),
6664
+ ),
6665
+ h('div', { style: S.summaryKpi },
6666
+ h('span', { style: { fontSize: '10px', color: C.dim } }, t('runSummaryLoops')),
6667
+ h('span', { style: { fontSize: '13px', fontWeight: 600, color: runSummary.totalLoops ? '#d29922' : C.text, fontVariantNumeric: 'tabular-nums' } }, String(runSummary.totalLoops)),
6668
+ ),
6669
+ h('div', { style: S.summaryKpi },
6670
+ h('span', { style: { fontSize: '10px', color: C.dim } }, t('runSummaryParallel')),
6671
+ h('span', { style: { fontSize: '13px', fontWeight: 600, color: C.text, fontVariantNumeric: 'tabular-nums' } }, '×' + (runSummary.maxParallel || maxParallel)),
6672
+ ),
6673
+ ),
6674
+ h('div', { style: { flex: '1 1 auto', minHeight: 0, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '8px', paddingRight: '2px' } },
6675
+ runSummary.haltedReason && h('div', {
6676
+ style: {
6677
+ flex: '0 0 auto', padding: '6px 8px', borderRadius: '6px', fontSize: '11px', lineHeight: '1.45',
6678
+ color: '#e5534b', background: 'rgba(229,83,75,0.12)', border: '1px solid rgba(229,83,75,0.4)',
6679
+ },
6680
+ }, '⏹ ' + runSummary.haltedReason),
6681
+ runSummary.status === 'need-lead' && runSummary.waitingLead && h('div', {
6682
+ style: {
6683
+ flex: '0 0 auto', padding: '6px 8px', borderRadius: '6px', fontSize: '11px', lineHeight: '1.45',
6684
+ color: '#2f81f7', background: 'rgba(47,129,247,0.12)', border: '1px solid rgba(47,129,247,0.4)',
6685
+ },
6686
+ }, '⏸ ' + t('runStWaiting') + ': ' + (runSummary.waitingLead.label || runSummary.waitingLead.id)),
6687
+ h('div', { style: { flex: '0 0 auto', fontSize: '11px', fontWeight: 600, color: C.dim } }, t('runSummaryNodesHead')),
6688
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: '5px' } },
6689
+ runSummary.nodes.map((n) => {
6690
+ const sv = stVisual(n.status);
6691
+ const barPct = (typeof n.durationMs === 'number' && n.durationMs > 0 && runSummary.maxNodeMs > 0)
6692
+ ? Math.max(4, Math.min(100, Math.round((n.durationMs / runSummary.maxNodeMs) * 100)))
6693
+ : 0;
6694
+ const kindMeta = n.kind === 'condition'
6695
+ ? { label: lang === 'en' ? 'Cond' : '条件', color: '#d29922', border: 'rgba(210,153,34,0.45)' }
6696
+ : n.kind === 'lead'
6697
+ ? { label: 'Lead', color: '#2f81f7', border: 'rgba(47,129,247,0.45)' }
6698
+ : { label: lang === 'en' ? 'Agent' : '子代理', color: '#3fb950', border: 'rgba(63,185,80,0.45)' };
6699
+ return h('div', { key: n.id, style: S.summaryRow },
6700
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0 } },
6701
+ h('span', { style: { color: sv.color, fontSize: '11px', fontWeight: 700, flex: '0 0 auto' }, title: sv.label }, sv.icon),
6702
+ h('button', {
6703
+ type: 'button',
6704
+ disabled: !n.onCanvas,
6705
+ title: n.onCanvas ? t('runSummaryFocusTip') : undefined,
6706
+ style: {
6707
+ flex: '1 1 auto', minWidth: 0, textAlign: 'left', padding: 0,
6708
+ border: 'none', background: 'transparent', color: C.text,
6709
+ fontSize: '11px', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
6710
+ cursor: n.onCanvas ? 'pointer' : 'default',
6711
+ },
6712
+ onClick: () => { if (n.onCanvas) { focusNode(n.id); setSummaryOpen(false); } },
6713
+ }, n.label),
6714
+ h('span', { style: { ...S.summaryChip, color: kindMeta.color, borderColor: kindMeta.border, flex: '0 0 auto' } }, kindMeta.label),
6715
+ h('span', { style: { fontSize: '11px', color: C.dim, fontVariantNumeric: 'tabular-nums', flex: '0 0 auto' } }, formatDurationMs(n.durationMs)),
6716
+ n.childId && h('button', {
6717
+ type: 'button',
6718
+ title: t('runSummaryOpenChatTip'),
6719
+ style: { ...S.condAddBtn, padding: '0 5px', height: '18px', flex: '0 0 auto' },
6720
+ onClick: () => {
6721
+ setSummaryOpen(false);
6722
+ const targetNode = nodeById.get(n.id) || { id: n.id, label: n.label };
6723
+ openNodeSession(targetNode, n.childId);
6724
+ },
6725
+ }, '↗'),
6726
+ ),
6727
+ barPct > 0 && h('div', { style: S.summaryBarTrack },
6728
+ h('div', { style: { ...S.summaryBarFill, width: barPct + '%', background: sv.color } }),
6729
+ ),
6730
+ (n.model || n.fallbackUsed || n.sessionContinued || n.runs > 1 || n.status === 'reused' || n.reason) && h('div', {
6731
+ style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '4px' },
6732
+ },
6733
+ n.model && h('span', { style: S.summaryChip }, n.model),
6734
+ n.runs > 1 && h('span', { style: { ...S.summaryChip, color: '#d29922' } }, t('runSummaryRuns').replace('{n}', String(n.runs))),
6735
+ n.fallbackUsed && h('span', { style: { ...S.summaryChip, color: '#d29922' } }, t('runSummaryFallback')),
6736
+ n.sessionContinued && h('span', { style: { ...S.summaryChip, color: '#a371f7' } }, t('runSummaryContinued')),
6737
+ n.status === 'reused' && h('span', { style: { ...S.summaryChip, color: '#3fb950' } }, t('runSummaryReused')),
6738
+ n.reason && h('span', {
6739
+ style: {
6740
+ fontSize: '10px', lineHeight: '1.35',
6741
+ color: n.status === 'failed' ? '#e5534b' : C.dim,
6742
+ wordBreak: 'break-word',
6743
+ },
6744
+ }, n.reason),
6745
+ ),
6746
+ );
6747
+ }),
6748
+ ),
6749
+ runSummary.loops.length > 0 && h(React.Fragment, null,
6750
+ h('div', { style: { flex: '0 0 auto', fontSize: '11px', fontWeight: 600, color: C.dim, marginTop: '2px' } }, t('runSummaryLoopsHead')),
6751
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: '5px', flex: '0 0 auto' } },
6752
+ runSummary.loops.map((lp, idx) => h('div', { key: idx, style: S.summaryRow },
6753
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px' } },
6754
+ h('span', { style: { fontSize: '11px', fontWeight: 600, color: '#d29922', flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
6755
+ lp.fromLabel + ' ↺ ' + lp.toLabel),
6756
+ h('span', { style: { ...S.summaryChip, color: lp.exhausted ? '#e5534b' : '#d29922' } },
6757
+ lp.used + '/' + lp.max + (lp.exhausted ? ' · ' + t('runSummaryExhausted') : '')),
6758
+ ),
6759
+ (lp.rounds || []).map((r, rIdx) => h('div', {
6760
+ key: rIdx,
6761
+ style: { fontSize: '10px', color: C.dim, lineHeight: '1.4', paddingLeft: '6px', borderLeft: '2px solid ' + C.border },
6762
+ }, 'R' + r.round + ': ' + r.reason)),
6763
+ )),
6764
+ ),
6765
+ ),
6766
+ ),
6767
+ ),
6768
+ ),
6769
+ );
6770
+ })(),
5778
6771
  shortcutsOpen && (() => {
5779
6772
  const actionLabels = {
5780
6773
  addNode: t('scAddNode'),
@@ -5892,15 +6885,23 @@ window.__ModuleLoader__.load({
5892
6885
  stopBtn.visible && h('button', {
5893
6886
  type: 'button',
5894
6887
  disabled: stopBtn.disabled,
5895
- style: {
5896
- ...S.floatStop,
5897
- opacity: stopBtn.disabled ? 0.6 : 1,
5898
- cursor: stopBtn.disabled ? 'not-allowed' : 'pointer',
5899
- },
6888
+ style: stopBtn.active
6889
+ ? {
6890
+ ...S.floatStop,
6891
+ opacity: stopBtn.disabled ? 0.6 : 1,
6892
+ cursor: stopBtn.disabled ? 'not-allowed' : 'pointer',
6893
+ }
6894
+ : {
6895
+ ...S.floatStop,
6896
+ border: '1px solid ' + C.border,
6897
+ color: C.dim,
6898
+ opacity: 0.55,
6899
+ cursor: 'not-allowed',
6900
+ },
5900
6901
  title: stopBtn.title,
5901
- onMouseEnter: (e) => { if (!stopBtn.disabled) e.currentTarget.style.background = 'rgba(229,83,75,0.18)'; },
6902
+ onMouseEnter: (e) => { if (stopBtn.active && !stopBtn.disabled) e.currentTarget.style.background = 'rgba(229,83,75,0.18)'; },
5902
6903
  onMouseLeave: (e) => { e.currentTarget.style.background = C.elevated; },
5903
- onClick: () => { if (!stopBtn.disabled) stopWorkflow(); },
6904
+ onClick: () => { if (stopBtn.active && !stopBtn.disabled) stopWorkflow(); },
5904
6905
  }, stopBtn.label),
5905
6906
  ),
5906
6907
  addMenu && (() => {
@@ -6031,6 +7032,45 @@ window.__ModuleLoader__.load({
6031
7032
  menuRow('clr', t('clearCanvasBtn'), () => { setCtxMenu(null); clearCanvas(); }, { danger: true }),
6032
7033
  );
6033
7034
  })(),
7035
+ runSummary.hasData && (() => {
7036
+ const pillIcon = runSummary.status === 'done' ? '✓'
7037
+ : runSummary.status === 'running' ? '●'
7038
+ : runSummary.status === 'need-lead' ? '⏸'
7039
+ : '⏹';
7040
+ const pillColor = runSummary.status === 'done'
7041
+ ? (runSummary.failedCount ? '#d29922' : '#3fb950')
7042
+ : runSummary.status === 'running' || runSummary.status === 'need-lead'
7043
+ ? '#2f81f7'
7044
+ : '#e5534b';
7045
+ const elapsedStyle = { flex: '0 0 auto', color: C.dim, fontVariantNumeric: 'tabular-nums' };
7046
+ const elapsedText = runSummary.elapsedMs !== null ? ' · ' + formatDurationMs(runSummary.elapsedMs) : '';
7047
+ const loopText = runSummary.totalLoops > 0 ? ' · ↺' + runSummary.totalLoops : '';
7048
+ return h('button', {
7049
+ type: 'button',
7050
+ style: { ...S.floatSummaryBtn, borderColor: runSummary.isLive ? pillColor : C.border },
7051
+ title: t('runSummaryTip'),
7052
+ onMouseDown: (e) => e.stopPropagation(),
7053
+ onMouseEnter: (e) => { e.currentTarget.style.borderColor = pillColor; },
7054
+ onMouseLeave: (e) => { e.currentTarget.style.borderColor = runSummary.isLive ? pillColor : C.border; },
7055
+ onClick: () => {
7056
+ setMenuOpen(false);
7057
+ setPresetOpen(null);
7058
+ setCtxMenu(null);
7059
+ setAddMenu(null);
7060
+ setLoopEditEdgeId(null);
7061
+ setOpenModelFor(null);
7062
+ setSummaryNow(Date.now());
7063
+ setSummaryOpen(true);
7064
+ },
7065
+ },
7066
+ h('span', { style: { color: pillColor, flex: '0 0 auto' } }, pillIcon),
7067
+ h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 } },
7068
+ t('runSummaryBtn') + ' · ' + runSummary.doneCount + '/' + runSummary.totalCount + loopText),
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)),
7072
+ );
7073
+ })(),
6034
7074
  h('div', {
6035
7075
  style: S.floatZoomBar,
6036
7076
  onMouseDown: (e) => e.stopPropagation(),
@@ -6067,6 +7107,7 @@ window.__ModuleLoader__.load({
6067
7107
  style: {
6068
7108
  ...S.content, width: contentW, height: contentH, overflow: 'visible',
6069
7109
  transform: 'translate(' + view.x + 'px,' + view.y + 'px) scale(' + view.k + ')',
7110
+ willChange: panning ? 'transform' : undefined,
6070
7111
  transformOrigin: '0 0',
6071
7112
  },
6072
7113
  },
@@ -6336,7 +7377,7 @@ window.__ModuleLoader__.load({
6336
7377
  }),
6337
7378
  btn.label,
6338
7379
  ),
6339
- stopBtn.visible && h('button', {
7380
+ stopBtn.active && h('button', {
6340
7381
  type: 'button',
6341
7382
  disabled: stopBtn.disabled,
6342
7383
  style: {
@@ -6711,7 +7752,7 @@ window.__ModuleLoader__.load({
6711
7752
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
6712
7753
  }
6713
7754
  },
6714
- __test: { 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, 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 },
6715
7756
  };
6716
7757
  },
6717
7758
  });