dsh-workflow-canvas 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -31,6 +31,8 @@ window.__ModuleLoader__.load({
31
31
  const KIND = 'workflow';
32
32
  const STORAGE_PREFIX = 'dsh-workflow-canvas:v1:';
33
33
  const PRESET_KEY = STORAGE_PREFIX + 'presets';
34
+ const PRESET_CHANGE_EVENT = 'dsh-wc-presets-changed';
35
+ const DIRECTION_KEY = STORAGE_PREFIX + 'direction';
34
36
  const SHORTCUTS_KEY = STORAGE_PREFIX + 'shortcuts';
35
37
  const DEFAULT_SHORTCUTS = {
36
38
  addNode: 'Shift+A',
@@ -119,7 +121,7 @@ window.__ModuleLoader__.load({
119
121
  const I18N = {
120
122
  zh: {
121
123
  addAgent: '+ 子代理', addLead: '+ Lead', addCond: '+ 条件', undo: '↶ 撤销', redo: '↷ 重做', sync: '↥ 同步',
122
- enabled: '● 已启用', disabled: '○ 已禁用', presetName: '预设名', save: '☆ 保存',
124
+ enabled: '● 已启用', disabled: '○ 已禁用', save: '☆ 保存',
123
125
  presets: '☰ 预设', unsaved: '有未同步改动', synced: '已同步',
124
126
  pickModel: '选择模型', loadingModels: '加载中…', defaultEffort: '默认',
125
127
  leadThis: 'Lead(本对话)',
@@ -128,8 +130,6 @@ window.__ModuleLoader__.load({
128
130
  tipCondTrue: '条件满足(pass=true)时走这条分支,连到任意下游节点左侧入口',
129
131
  tipCondFalse: '条件不满足(pass=false)时走这条分支,连到任意下游节点左侧入口',
130
132
  tipBranchOut: '命中该分支时走这条连线,拖到任意下游节点左侧入口',
131
- branchTrue: '是',
132
- branchFalse: '否',
133
133
  addBranch: '+ 分支',
134
134
  branchPh: '分支名',
135
135
  delBranchTip: '删除该分支(至少保留 2 路)',
@@ -151,11 +151,10 @@ window.__ModuleLoader__.load({
151
151
  syncBadFile: '文件内容无效',
152
152
  generated: '已从对话生成画布',
153
153
  dupName: '已存在,请换一个名字',
154
- guideDesc: '画一张子代理流程图',
155
154
  model: '模型', reason: '推理', role: '分工', task: '任务', taskPh: '本次任务:例如把这批反馈归类并给出建议',
156
155
  rolePhLead: '我自己这一步做什么', rolePhAgent: '这个子代理做什么',
157
- memory: '记忆', scope: '能力', retry: '重试', jsonOut: 'JSON 输出',
158
- sep: ': ', on: '开', off: '关', allTools: '默认(全部工具)', none: '无',
156
+ memory: '记忆', scope: '能力',
157
+ sep: ': ', on: '开', off: '关', none: '无',
159
158
  scopeMinimal: 'minimal(只读思考)', scopeStandard: 'standard(全部工具)',
160
159
  fallbackModel: '备用',
161
160
  stPending: '未执行', stRunning: '进行中', stDone: '已完成', stFailed: '失败',
@@ -164,21 +163,19 @@ window.__ModuleLoader__.load({
164
163
  presetSaveTitle: '保存当前画布(可在新会话一键载入)',
165
164
  presetNamePh: '起个名字后回车保存…',
166
165
  myPresets: '我的预设(跨会话复用)',
167
- needName: '请先给预设起个名字', duplicate: '已存在,请换一个名字',
166
+ needName: '请先给预设起个名字',
168
167
  savedPreset: '已保存预设', saveFailed: '保存失败(存储不可用)',
169
168
  loadedPreset: '已载入预设', invalidPreset: '预设内容无效', deletedPreset: '已删除预设',
170
169
  syncFailed: '同步失败', upToDate: '已是最新', syncedToHost: '已同步到 Host',
171
170
  syncedWithStdWarn: '已同步(含可写/命令节点,请确认主对话权限已放开)',
172
171
  cannotOpen: '无法打开会话', undoDone: '已撤销', undoNone: '没有可撤销的操作', redoDone: '已重做', redoNone: '没有可重做的操作',
173
- leadLocked: '入口 Lead 不能删除', modelsMissing: '模型列表未加载',
172
+ leadLocked: '入口 Lead 不能删除',
174
173
  tipLead: 'Lead 步骤在对话里执行,画布不追踪其状态',
175
174
  tipOrphan: '未连线:运行时会被跳过', tipStatus: '子代理节点的运行状态',
176
- tipZoom: '滚轮缩放(以光标为中心)',
177
175
  tipResetZoom: '点击回到 100% 并聚焦 Lead;左右拖拽可连续缩放',
178
176
  tipLocate: '自适应缩放并居中,让所有节点完整显示在视野内',
179
177
  locate: '⊡ 全览',
180
178
  importBtn: '⇩ 导入',
181
- tipImport: '从剪贴板导入模型生成的画布(先复制聊天里的画布 JSON)',
182
179
  importOk: '已导入画布,共 ',
183
180
  tipMore: '更多',
184
181
  help: '使用说明',
@@ -193,15 +190,15 @@ window.__ModuleLoader__.load({
193
190
  '3. 输出口决定连线类型:prompt(灰,纯文本)、structured(蓝,JSON)、session(紫,复用上游会话);条件节点支持多路分支,并可将分支连回上游(或多选节点右键「↺ 设为回环」)实现带反馈的受控重试(点 ↺ 徽章可调 1–10 次,超限自动交 Lead 熔断)。',
194
191
  '4. 节点左侧为统一通用输入口,可直接接收任意颜色的连线;拖已连接的左口可断开最近一条连线。',
195
192
  '5. 每个节点可设模型、推理强度、能力范围、备用模型、是否记忆;复杂任务/分工/条件可点 ⤢ 展开大框编辑。',
196
- '6. 连好后点「● 已启用」,然后对对话说「跑一次」,由我调用执行。',
197
- '7. 遇到 Lead 节点会暂停,我做完再把结果交回去继续。',
193
+ '6. 连好后点左上角「● 已启用」,可直接点入口节点「▶ 运行」或在对话说「跑一次」开跑;运行中或停在「⏸ 待拍板」时,点左上角或入口节点旁的「⏹ 终止」即可一键中止全部子代理并解除等待状态。',
194
+ '7. 遇到 Lead 节点会暂停,我做完再把结果交回去继续(或在对话里说「取消」即可结束流程)。',
198
195
  '8. 没连线的节点显示为虚线,运行时会被跳过。',
199
- '9. 右键单击节点 / 连线 / 空白处可弹出快捷菜单(含线上插点、复制删除、新建节点等);按住右键划过连线可切断(可在「⋯」开关)。',
200
- '10. 点右上角「☰ 预设」顶部即可保存当前画布,开新对话时一键载入跨会话复用。',
196
+ '9. 右键单击节点 / 连线 / 空白处可弹出快捷菜单(含线上插点、设为回环、复制删除、新建节点等);按住右键划过连线可切断(可在「⋯」开关)。',
197
+ '10. 点右上角「☰ 预设」可保存当前画布(连同横/竖排方向),多会话实时同步并支持点 ↻ 刷新;切换横/竖排会自动记住默认偏好供新会话沿用。',
201
198
  '11. 你可以直接让我改画布:说「把那三个节点的分工改成…」,我会就地修改,不动你摆的位置。',
202
199
  '12. session 线连到 Lead 时,我会在暂停那步拿到那个子代理的会话,可以继续追问它。',
203
- '13. 按住鼠标中键(或空格 + 左键)拖动画布平移;点击子代理节点左下角状态可直达它的对话记录。',
204
- '14. 快捷键:默认 Shift+A 新建节点,Shift+D 复制节点与连线,Delete 删除,Ctrl+Z 撤销,Esc 关闭弹窗(可在「⋯ → 快捷键设置」自定义)。',
200
+ '13. 按住鼠标中键(或空格 + 左键)拖动画布平移;点击子代理节点左下角状态可直达它的对话记录;运行后左下角「复盘」胶囊(或「⋯ → 📊 执行复盘」)可查看耗时、分支与回环记录并复制 Markdown(零额外 Token)。',
201
+ '14. 快捷键与历史:顶栏提供 ↶ 撤销 / ↷ 重做按钮(支持撤销节点移动与横竖排切换);默认 Shift+A 新建,Shift+D 复制,Delete 删除,Ctrl+Z / Ctrl+Shift+Z(Ctrl+Y)撤销重做,Esc 关闭弹窗(可在「⋯ → 快捷键设置」自定义)。',
205
202
  ].join('\n'),
206
203
  openChat: '会话',
207
204
  tipOpenRun: '点击打开该子代理的对话记录',
@@ -227,9 +224,13 @@ window.__ModuleLoader__.load({
227
224
  verdictFallback: '已跳过中间分支 → 转交 Lead:',
228
225
  verdictNoReason: '(裁判未附额外说明)',
229
226
  tipVerdictChip: '点击查看完整判断理由',
230
- runBtn: '▶ 运行',
231
- runBtnRunning: '进行中…',
232
- runBtnWaiting: '⏸ 等待决策',
227
+ stopSent: '已发送终止指令',
228
+ stopWaitingDone: '已结束等待拍板并终止流程',
229
+ stopFailed: '终止请求失败',
230
+ refreshPresetsTip: '刷新预设列表',
231
+ presetsRefreshed: '预设列表已刷新',
232
+ presetDirTB: '竖',
233
+ presetDirLR: '横',
233
234
  runStarted: '已向当前会话发起画布执行',
234
235
  runFailed: '发起运行失败',
235
236
  runSendUnavailable: '当前宿主不支持从画布直接发起对话,请在聊天框发送消息启动',
@@ -313,12 +314,38 @@ window.__ModuleLoader__.load({
313
314
  tipMemoryPick: '选择要续接的历史子会话(默认自动沿用最新记忆)',
314
315
  tipPreset: '能力范围(点一下切换,受主对话权限上限约束):standard = 全部工具(读写文件、跑命令、子代理、工作流、网页、办公);minimal = 只读思考(文件读写关闭,没有子代理/工作流/网页)',
315
316
  tipFallback: '失败重试:该节点出错时自动换一个模型再跑一次',
316
- tipStructured: 'JSON 输出:要求该节点返回 JSON 对象,structured 连线会把结果作为 JSON 传给下游',
317
- lang: 'ZH',
317
+ runSummaryBtn: '复盘',
318
+ runSummaryMenu: '📊 执行复盘',
319
+ runSummaryTitle: '执行复盘摘要',
320
+ runSummaryEmpty: '当前会话还没有运行记录',
321
+ runSummaryCopy: '⧉ 复制 MD',
322
+ runSummaryCopied: '已复制 Markdown 复盘报告',
323
+ runSummaryElapsed: '总耗时',
324
+ runSummaryDone: '已完成',
325
+ runSummaryLoops: '回环重试',
326
+ runSummaryParallel: '并发上限',
327
+ runSummaryNodesHead: '节点耗时与状态',
328
+ runSummaryLoopsHead: '回环记录',
329
+ runSummaryFallback: '备用回退',
330
+ runSummaryContinued: '续接会话',
331
+ runSummaryReused: '缓存复用',
332
+ runSummaryRuns: '{n} 轮',
333
+ runSummaryExhausted: '已达上限',
334
+ runSummaryFocusTip: '点击居中定位到该节点',
335
+ runSummaryOpenChatTip: '打开该子代理会话',
336
+ runSummaryTip: '查看本次工作流耗时、节点状态、条件分支与回环复盘(零额外 Token)',
337
+ runStRunning: '运行中',
338
+ runStDone: '已完成',
339
+ runStWaiting: '待拍板',
340
+ runStHalted: '已终止',
341
+ runStFailed: '失败',
342
+ runStEmpty: '空输出',
343
+ runStPruned: '跳过',
344
+ runStPending: '未启动',
318
345
  },
319
346
  en: {
320
347
  addAgent: '+ Subagent', addLead: '+ Lead', addCond: '+ Condition', undo: '↶ Undo', redo: '↷ Redo', sync: '↥ Sync',
321
- enabled: '● ON', disabled: '○ OFF', presetName: 'Preset name', save: '☆ Save',
348
+ enabled: '● ON', disabled: '○ OFF', save: '☆ Save',
322
349
  presets: '☰ Presets', unsaved: 'Unsaved changes', synced: 'Synced',
323
350
  pickModel: 'Pick a model', loadingModels: 'Loading…', defaultEffort: 'default',
324
351
  leadThis: 'Lead (this chat)',
@@ -327,8 +354,6 @@ window.__ModuleLoader__.load({
327
354
  tipCondTrue: 'Runs when condition passes (pass=true); connect to any downstream input',
328
355
  tipCondFalse: 'Runs when condition fails (pass=false); connect to any downstream input',
329
356
  tipBranchOut: 'Runs when this branch matches; connect to any downstream input',
330
- branchTrue: 'Yes',
331
- branchFalse: 'No',
332
357
  addBranch: '+ Case',
333
358
  branchPh: 'Branch name',
334
359
  delBranchTip: 'Remove this branch (minimum 2)',
@@ -350,11 +375,10 @@ window.__ModuleLoader__.load({
350
375
  syncBadFile: 'File content is invalid',
351
376
  generated: 'Canvas generated from chat',
352
377
  dupName: 'already exists, pick another name',
353
- guideDesc: 'Sketch a subagent workflow',
354
378
  model: 'Model', reason: 'Reasoning', role: 'Role', task: 'Task', taskPh: 'Task, e.g. classify these reports and suggest actions',
355
379
  rolePhLead: 'What I do in this step', rolePhAgent: 'What this subagent does',
356
- memory: 'Memory', scope: 'Scope', retry: 'Retry', jsonOut: 'JSON out',
357
- sep: ': ', on: 'on', off: 'off', allTools: 'default (all tools)', none: 'none',
380
+ memory: 'Memory', scope: 'Scope',
381
+ sep: ': ', on: 'on', off: 'off', none: 'none',
358
382
  scopeMinimal: 'minimal (read-only thinking)', scopeStandard: 'standard (all tools)',
359
383
  fallbackModel: 'Fallback',
360
384
  stPending: 'Pending', stRunning: 'Running', stDone: 'Done', stFailed: 'Failed',
@@ -363,21 +387,19 @@ window.__ModuleLoader__.load({
363
387
  presetSaveTitle: 'Save current canvas (reuse in any new chat)',
364
388
  presetNamePh: 'Name this canvas…',
365
389
  myPresets: 'Saved presets (all sessions)',
366
- needName: 'Name the preset first', duplicate: 'already exists, pick another name',
390
+ needName: 'Name the preset first',
367
391
  savedPreset: 'Saved preset', saveFailed: 'Save failed (storage unavailable)',
368
392
  loadedPreset: 'Loaded preset', invalidPreset: 'Preset content is invalid', deletedPreset: 'Deleted preset',
369
393
  syncFailed: 'Sync failed', upToDate: 'Already up to date', syncedToHost: 'Synced to host',
370
394
  syncedWithStdWarn: 'Synced (has write/tool nodes — check main chat permission mode)',
371
395
  cannotOpen: 'Cannot open the session', undoDone: 'Undone', undoNone: 'Nothing to undo', redoDone: 'Redone', redoNone: 'Nothing to redo',
372
- leadLocked: 'The entry Lead cannot be deleted', modelsMissing: 'Model list is not loaded',
396
+ leadLocked: 'The entry Lead cannot be deleted',
373
397
  tipLead: 'Lead steps run in the chat; the canvas does not track them',
374
398
  tipOrphan: 'Unlinked: skipped when the canvas runs', tipStatus: 'Subagent run status',
375
- tipZoom: 'Wheel zooms around the cursor',
376
399
  tipResetZoom: 'Click to reset to 100% on Lead; drag left/right to scrub zoom',
377
400
  tipLocate: 'Fit all nodes into the visible canvas',
378
401
  locate: '⊡ Fit',
379
402
  importBtn: '⇩ Import',
380
- tipImport: 'Import a model-generated canvas from the clipboard (copy the canvas JSON from chat first)',
381
403
  importOk: 'Canvas imported, ',
382
404
  tipMore: 'More',
383
405
  help: 'How to use',
@@ -392,15 +414,15 @@ window.__ModuleLoader__.load({
392
414
  '3. Output sockets choose channel type: prompt (grey text), structured (blue JSON), session (purple warm session), or multi-way condition branches; wire a condition branch back upstream (or right-click selected nodes → ↺ Create loop) for bounded feedback retries (click the ↺ pill for 1–10 retries).',
393
415
  '4. Every node has one universal left input that accepts any incoming wire; drag a connected input away to detach the latest wire.',
394
416
  '5. Each node sets model, reasoning, capability scope, fallback model and memory; click ⤢ to expand a larger editor for long text.',
395
- '6. Press ● ON, then ask in chat to run the canvas.',
396
- '7. The run pauses at every Lead node so the conversation can do that step.',
417
+ '6. Press ● ON, then click ▶ Run on the Entry Lead or ask in chat to start; while running or paused at a Lead gate, click ⏹ Stop beside ● ON (or on the Entry card) to abort all running subagents and clear the pause.',
418
+ '7. The run pauses at intermediate Lead nodes for your decision (reply to continue, or ask to cancel / click ⏹ Stop).',
397
419
  '8. Unlinked nodes are dashed and skipped at run time.',
398
- '9. Right-click a node, wire, or blank canvas for context actions (insert on wire, duplicate/delete, add nodes); right-drag across a wire to cut it (toggle under ⋯).',
399
- '10. Open ☰ Presets to save the current canvas at the top and load it in any new chat.',
420
+ '9. Right-click a node, wire, or blank canvas for context actions (insert on wire, create loop, duplicate/delete, add nodes); right-drag across a wire to cut it (toggle under ⋯).',
421
+ '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.',
400
422
  '11. You can ask me to edit the canvas; I patch it in place and keep your layout.',
401
423
  '12. A session link into a Lead step hands me that child agent, so I can follow up with it.',
402
- '13. Hold the middle mouse button (or Space + drag) to pan; click a subagent status badge at the bottom-left to open its chat.',
403
- '14. Shortcuts: Shift+A adds a node at cursor, Shift+D duplicates nodes & links, Delete removes selected, Ctrl+Z undoes, Esc closes popups (customizable under ⋯ → Shortcuts).',
424
+ '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).',
425
+ '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).',
404
426
  ].join('\n'),
405
427
  openChat: 'Chat',
406
428
  tipOpenRun: 'Click to open this subagent conversation',
@@ -426,9 +448,13 @@ window.__ModuleLoader__.load({
426
448
  verdictFallback: 'Skipped branches → Lead: ',
427
449
  verdictNoReason: '(No extra reason provided)',
428
450
  tipVerdictChip: 'Click to inspect verdict reason',
429
- runBtn: '▶ Run',
430
- runBtnRunning: 'Running…',
431
- runBtnWaiting: '⏸ Awaiting Lead',
451
+ stopSent: 'Stop signal sent',
452
+ stopWaitingDone: 'Cancelled awaiting Lead gate',
453
+ stopFailed: 'Failed to stop workflow',
454
+ refreshPresetsTip: 'Refresh presets',
455
+ presetsRefreshed: 'Presets refreshed',
456
+ presetDirTB: 'V',
457
+ presetDirLR: 'H',
432
458
  runStarted: 'Workflow run queued in this chat',
433
459
  runFailed: 'Failed to start run',
434
460
  runSendUnavailable: 'Direct canvas launch is unavailable in this host; send a message in chat to start',
@@ -512,8 +538,34 @@ window.__ModuleLoader__.load({
512
538
  tipMemoryPick: 'Pick which past child session to resume (defaults to latest)',
513
539
  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)',
514
540
  tipFallback: 'Retry: when this node fails, rerun it once on another model',
515
- tipStructured: 'JSON output: require an object result; structured links pass it downstream as JSON',
516
- lang: 'EN',
541
+ runSummaryBtn: 'Summary',
542
+ runSummaryMenu: '📊 Run summary',
543
+ runSummaryTitle: 'Run Summary',
544
+ runSummaryEmpty: 'No workflow run recorded in this session yet',
545
+ runSummaryCopy: '⧉ Copy MD',
546
+ runSummaryCopied: 'Copied Markdown run summary',
547
+ runSummaryElapsed: 'Elapsed',
548
+ runSummaryDone: 'Completed',
549
+ runSummaryLoops: 'Loop retries',
550
+ runSummaryParallel: 'Max parallel',
551
+ runSummaryNodesHead: 'Node timeline',
552
+ runSummaryLoopsHead: 'Loop history',
553
+ runSummaryFallback: 'Fallback',
554
+ runSummaryContinued: 'Continued',
555
+ runSummaryReused: 'Cached',
556
+ runSummaryRuns: '{n} runs',
557
+ runSummaryExhausted: 'Exhausted',
558
+ runSummaryFocusTip: 'Click to focus this node on canvas',
559
+ runSummaryOpenChatTip: 'Open child session',
560
+ runSummaryTip: 'Inspect run timing, node status, branch verdicts & retry history (zero extra tokens)',
561
+ runStRunning: 'Running',
562
+ runStDone: 'Completed',
563
+ runStWaiting: 'Awaiting Lead',
564
+ runStHalted: 'Halted',
565
+ runStFailed: 'Failed',
566
+ runStEmpty: 'Empty',
567
+ runStPruned: 'Skipped',
568
+ runStPending: 'Pending',
517
569
  },
518
570
  };
519
571
 
@@ -567,32 +619,31 @@ window.__ModuleLoader__.load({
567
619
  width: '1px', height: '16px', background: C.border, opacity: 0.65,
568
620
  flex: '0 0 auto', margin: '0 2px',
569
621
  },
570
- toggleOn: {
571
- padding: '5px 12px', borderRadius: '6px', border: '1px solid ' + C.accent,
572
- background: 'transparent', color: C.accent, fontSize: '12px', fontWeight: 600,
573
- cursor: 'pointer', whiteSpace: 'nowrap',
574
- },
575
- toggleOff: {
576
- padding: '5px 12px', borderRadius: '6px', border: '1px solid ' + C.border,
577
- background: 'transparent', color: C.dim, fontSize: '12px',
578
- cursor: 'pointer', whiteSpace: 'nowrap',
579
- },
580
622
  status: {
581
623
  fontSize: '11px', color: C.dim,
582
- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%',
624
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '160px',
583
625
  },
584
- floatOn: {
626
+ floatTopLeft: {
585
627
  position: 'absolute', top: '10px', left: '10px', zIndex: 30,
628
+ display: 'inline-flex', alignItems: 'center', gap: '6px',
629
+ },
630
+ floatOn: {
586
631
  padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.accent,
587
632
  background: C.elevated, color: C.accent, fontSize: '11px', fontWeight: 600,
588
633
  cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
589
634
  },
590
635
  floatOff: {
591
- position: 'absolute', top: '10px', left: '10px', zIndex: 30,
592
636
  padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.border,
593
637
  background: C.elevated, color: C.dim, fontSize: '11px', fontWeight: 600,
594
638
  cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
595
639
  },
640
+ floatStop: {
641
+ padding: '5px 10px', borderRadius: '999px', border: '1px solid rgba(229,83,75,0.75)',
642
+ background: C.elevated, color: '#e5534b', fontSize: '11px', fontWeight: 600,
643
+ cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
644
+ display: 'inline-flex', alignItems: 'center', gap: '5px', lineHeight: '14px',
645
+ whiteSpace: 'nowrap',
646
+ },
596
647
  floatZoomBar: {
597
648
  position: 'absolute', right: '10px', bottom: '10px', zIndex: 30,
598
649
  display: 'inline-flex', alignItems: 'center', gap: '4px',
@@ -605,6 +656,45 @@ window.__ModuleLoader__.load({
605
656
  background: 'transparent', color: C.text, fontSize: '11px',
606
657
  cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '16px',
607
658
  },
659
+ floatSummaryBtn: {
660
+ position: 'absolute', left: '10px', bottom: '10px', zIndex: 30,
661
+ display: 'inline-flex', alignItems: 'center', gap: '5px',
662
+ padding: '4px 10px', borderRadius: '999px',
663
+ background: C.elevated, color: C.text, border: '1px solid ' + C.border,
664
+ fontSize: '11px', fontWeight: 600, lineHeight: '16px',
665
+ cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.28)',
666
+ maxWidth: 'calc(100% - 118px)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
667
+ fontVariantNumeric: 'tabular-nums',
668
+ },
669
+ summaryKpiRow: {
670
+ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(84px, 1fr))', gap: '6px',
671
+ marginBottom: '10px', flex: '0 0 auto',
672
+ },
673
+ summaryKpi: {
674
+ padding: '6px 8px', borderRadius: '6px',
675
+ background: C.raised, border: '1px solid ' + C.border,
676
+ display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0,
677
+ },
678
+ summaryRow: {
679
+ padding: '7px 8px', borderRadius: '6px', flex: '0 0 auto',
680
+ background: C.raised, border: '1px solid ' + C.border,
681
+ display: 'flex', flexDirection: 'column', gap: '4px',
682
+ },
683
+ summaryBarTrack: {
684
+ width: '100%', height: '3px', borderRadius: '2px',
685
+ background: C.border, overflow: 'hidden', opacity: 0.75,
686
+ },
687
+ summaryBarFill: {
688
+ height: '100%', borderRadius: '2px',
689
+ transition: 'width 180ms ease',
690
+ },
691
+ summaryChip: {
692
+ display: 'inline-flex', alignItems: 'center', gap: '3px',
693
+ padding: '1px 5px', borderRadius: '4px',
694
+ border: '1px solid ' + C.border, background: C.base,
695
+ color: C.dim, fontSize: '10px', lineHeight: '13px',
696
+ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
697
+ },
608
698
  ctxDivider: {
609
699
  height: '1px', background: C.border, opacity: 0.65, margin: '3px 4px',
610
700
  },
@@ -705,7 +795,6 @@ window.__ModuleLoader__.load({
705
795
  marginLeft: 'auto', display: 'flex', alignItems: 'center',
706
796
  gap: '6px', position: 'relative', flex: '0 0 auto',
707
797
  },
708
- presetRowTop: { display: 'flex', alignItems: 'center', gap: '5px' },
709
798
  presetMenu: {
710
799
  position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '236px',
711
800
  maxHeight: '320px', overflowY: 'auto', background: C.elevated, color: C.text,
@@ -798,12 +887,6 @@ window.__ModuleLoader__.load({
798
887
  fieldFallback: { position: 'absolute', left: '10px', right: '10px', top: '101px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
799
888
  fieldMemory: { position: 'absolute', left: '10px', right: '10px', top: '123px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
800
889
  fieldRole: { position: 'absolute', left: '10px', right: '10px', top: '145px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
801
- fieldRoleTop: { position: 'absolute', left: '10px', right: '10px', top: '34px', height: '24px', display: 'flex', alignItems: 'center', gap: '6px' },
802
- optRow: {
803
- position: 'absolute', left: '10px', right: '10px', top: '114px', height: '18px',
804
- display: 'flex', alignItems: 'center', gap: '5px', fontSize: '9px', color: C.dim,
805
- overflow: 'hidden',
806
- },
807
890
 
808
891
  toggleSwitch: {
809
892
  flex: '1 1 auto', width: '100%', height: '18px', boxSizing: 'border-box', padding: '0 5px', borderRadius: '4px',
@@ -815,18 +898,6 @@ window.__ModuleLoader__.load({
815
898
  border: '1px solid ' + C.accent, background: C.base, color: C.accent,
816
899
  fontSize: '10px', cursor: 'pointer', outline: 'none', textAlign: 'center', lineHeight: '14px',
817
900
  },
818
- optChip: {
819
- flex: '0 0 auto', padding: '2px 6px', borderRadius: '4px',
820
- border: '1px solid ' + C.border, background: 'transparent', color: C.dim,
821
- fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '12px',
822
- outline: 'none',
823
- },
824
- optChipOn: {
825
- flex: '0 0 auto', padding: '2px 6px', borderRadius: '4px',
826
- border: '1px solid ' + C.accent, background: C.hover, color: C.accent,
827
- fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '12px',
828
- outline: 'none',
829
- },
830
901
  fieldLabel: { flex: '0 0 30px', width: '30px', fontSize: '9px', color: C.dim, whiteSpace: 'nowrap' },
831
902
  fieldLabelEn: { flex: '0 0 46px', width: '46px', fontSize: '9px', color: C.dim, whiteSpace: 'nowrap' },
832
903
 
@@ -910,12 +981,6 @@ window.__ModuleLoader__.load({
910
981
  background: C.base, color: C.text, fontSize: '10px', cursor: 'pointer', textAlign: 'left',
911
982
  lineHeight: '14px',
912
983
  },
913
- reasonChip: {
914
- flex: '0 0 auto', maxWidth: '44px', padding: '3px 4px', borderRadius: '5px',
915
- border: '1px solid ' + C.border, background: 'transparent', color: C.dim,
916
- fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap',
917
- overflow: 'hidden', textOverflow: 'ellipsis',
918
- },
919
984
  selectText: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
920
985
  caret: { flex: '0 0 auto', color: C.dim, fontSize: '9px' },
921
986
  menu: {
@@ -945,14 +1010,6 @@ window.__ModuleLoader__.load({
945
1010
  color: '#e5534b', fontSize: '12px', lineHeight: '16px', textAlign: 'center',
946
1011
  cursor: 'pointer', zIndex: 8, userSelect: 'none',
947
1012
  },
948
- runsBadge: {
949
- position: 'absolute', right: '10px', bottom: '2px', fontSize: '9px',
950
- color: C.accent, cursor: 'pointer', userSelect: 'none', zIndex: 4,
951
- },
952
- statusBar: {
953
- position: 'absolute', left: '2px', top: '10px', bottom: '10px', width: '3px',
954
- borderRadius: '2px', zIndex: 3,
955
- },
956
1013
  verdictChip: {
957
1014
  position: 'absolute', left: '0', top: 'calc(100% + 5px)', maxWidth: NODE_W + 'px',
958
1015
  display: 'inline-flex', alignItems: 'center', gap: '4px',
@@ -1164,6 +1221,321 @@ window.__ModuleLoader__.load({
1164
1221
  };
1165
1222
  }
1166
1223
 
1224
+ /** Compute unified Stop button state across idle, running & waitingLead modes. */
1225
+ function stopButtonState({ sessionRunning, runningNodesCount, waitingLead, triggering, stopping, lang }) {
1226
+ const en = lang === 'en';
1227
+ const hasRunning = Boolean(sessionRunning || triggering || Number(runningNodesCount) > 0);
1228
+ const hasWaiting = Boolean(waitingLead);
1229
+ if (!hasRunning && !hasWaiting) {
1230
+ return {
1231
+ visible: true,
1232
+ active: false,
1233
+ disabled: true,
1234
+ mode: 'idle',
1235
+ label: en ? '⏹ Stop' : '⏹ 终止',
1236
+ title: en ? 'No running or paused workflow to stop' : '当前没有运行中或等待拍板的任务',
1237
+ };
1238
+ }
1239
+ const mode = hasRunning ? 'running' : 'waiting';
1240
+ return {
1241
+ visible: true,
1242
+ active: true,
1243
+ disabled: Boolean(stopping),
1244
+ mode,
1245
+ label: stopping
1246
+ ? (en ? 'Stopping…' : '终止中…')
1247
+ : (en ? '⏹ Stop' : '⏹ 终止'),
1248
+ title: mode === 'waiting'
1249
+ ? (en ? 'Cancel the paused Lead gate and end this workflow run' : '结束当前等待拍板状态并终止本轮流程')
1250
+ : (en ? 'Stop all running workflow tasks and subagents' : '一键终止全部正在运行的任务与子代理'),
1251
+ };
1252
+ }
1253
+
1254
+ /**
1255
+ * Derive Lead node ready/done sets cleanly, respecting authoritative `runState.status`
1256
+ * (`halted` / `done` / `idle` / `need-lead`) so a stopped or completed workflow can never
1257
+ * falsely re-enter "Awaiting Lead" from historical subagent statuses.
1258
+ */
1259
+ function deriveLeadStatuses({ enabled, nodes, edges, statusById, sessionRunning, runState, reachableIds }) {
1260
+ const leadReadyIds = new Set();
1261
+ const leadDoneIds = new Set();
1262
+ if (!enabled) return { leadReadyIds, leadDoneIds };
1263
+
1264
+ const nodeList = Array.isArray(nodes) ? nodes : [];
1265
+ const edgeList = forwardEdgesUI(edges);
1266
+ const nodeById = new Map(nodeList.map((n) => [n.id, n]));
1267
+ const reach = reachableIds || reachableFrom(nodeList, edgeList);
1268
+ const stMap = statusById || {};
1269
+
1270
+ if (runState && Array.isArray(runState.done)) {
1271
+ for (const did of runState.done) {
1272
+ const dn = nodeById.get(did);
1273
+ if (dn && dn.kind === 'lead' && dn.id !== 'lead') leadDoneIds.add(did);
1274
+ }
1275
+ }
1276
+ if (runState && runState.status === 'need-lead' && runState.waitingLead && runState.waitingLead.id) {
1277
+ leadReadyIds.add(runState.waitingLead.id);
1278
+ } else if (runState && !runState.status && runState.waitingLead && runState.waitingLead.id) {
1279
+ leadReadyIds.add(runState.waitingLead.id);
1280
+ }
1281
+
1282
+ // If the backend reported a terminal or explicit paused runState, treat it as authoritative
1283
+ // instead of guessing ready Leads from historical child statuses.
1284
+ const authoritativeStatus = runState && typeof runState.status === 'string' ? runState.status : '';
1285
+ if (authoritativeStatus === 'halted' || authoritativeStatus === 'done' || authoritativeStatus === 'idle' || authoritativeStatus === 'need-lead') {
1286
+ return { leadReadyIds, leadDoneIds };
1287
+ }
1288
+
1289
+ const hasCondNode = nodeList.some((x) => x && x.kind === 'condition');
1290
+ for (const n of nodeList) {
1291
+ if (!n || n.kind !== 'lead' || n.id === 'lead' || !reach.has(n.id)) continue;
1292
+ if (leadReadyIds.has(n.id) || leadDoneIds.has(n.id)) continue;
1293
+ const upIds = edgeList
1294
+ .filter((e) => e.to === n.id && e.from !== 'lead' && nodeById.has(e.from))
1295
+ .map((e) => e.from);
1296
+ if (!upIds.length) continue;
1297
+ const upAgents = upIds.filter((id) => nodeById.get(id).kind !== 'lead');
1298
+ if (!upAgents.length) continue;
1299
+ const anyUpRunning = upAgents.some((id) => stMap[id] === 'running');
1300
+ const allUpDone = hasCondNode
1301
+ ? (!anyUpRunning && upAgents.some((id) => stMap[id] === 'done' || stMap[id] === 'failed'))
1302
+ : upAgents.every((id) => stMap[id] === 'done' || stMap[id] === 'failed');
1303
+ if (!allUpDone) continue;
1304
+ const downIds = edgeList.filter((e) => e.from === n.id).map((e) => e.to);
1305
+ if (!downIds.length) {
1306
+ if (sessionRunning) leadReadyIds.add(n.id);
1307
+ else leadDoneIds.add(n.id);
1308
+ } else {
1309
+ const anyDownStarted = downIds.some((id) => Boolean(stMap[id]));
1310
+ if (!anyDownStarted) leadReadyIds.add(n.id);
1311
+ else leadDoneIds.add(n.id);
1312
+ }
1313
+ }
1314
+ return { leadReadyIds, leadDoneIds };
1315
+ }
1316
+
1317
+ /** Format millisecond durations cleanly for badges, KPI cards and Markdown tables. */
1318
+ function formatDurationMs(ms) {
1319
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return '—';
1320
+ if (ms < 1000) return Math.round(ms) + 'ms';
1321
+ if (ms < 60000) return (ms / 1000).toFixed(1) + 's';
1322
+ const totalSec = Math.round(ms / 1000);
1323
+ const min = Math.floor(totalSec / 60);
1324
+ const sec = totalSec % 60;
1325
+ if (min < 60) return min + 'm ' + sec + 's';
1326
+ const hr = Math.floor(min / 60);
1327
+ const remMin = min % 60;
1328
+ return hr + 'h ' + remMin + 'm';
1329
+ }
1330
+
1331
+ /**
1332
+ * Normalize `.run.json` telemetry into a UI/Markdown view model.
1333
+ * Supports both v1.6 `runState.summary` and older `.run.json` files without `summary`.
1334
+ */
1335
+ function buildRunSummaryView({ runState, nodes, runsById, now, fallbackTiming }) {
1336
+ if (!runState || typeof runState !== 'object' || runState.status === 'idle') {
1337
+ return { hasData: false };
1338
+ }
1339
+ const clock = typeof now === 'number' ? now : Date.now();
1340
+ const canvasNodes = Array.isArray(nodes) ? nodes : [];
1341
+ const byCanvasId = new Map(canvasNodes.map((n) => [n.id, n]));
1342
+ const runMap = runsById && typeof runsById === 'object' ? runsById : {};
1343
+ const sum = runState.summary && typeof runState.summary === 'object' ? runState.summary : null;
1344
+ const status = runState.status || (sum && sum.status) || 'running';
1345
+ const waitingLead = runState.waitingLead || null;
1346
+ const isLive = status === 'running' || status === 'need-lead';
1347
+
1348
+ let rows = [];
1349
+ let minNodeStart = null;
1350
+ let maxNodeEnd = null;
1351
+ if (sum && Array.isArray(sum.nodes) && sum.nodes.length > 0) {
1352
+ rows = sum.nodes.map((entry) => {
1353
+ if (typeof entry.startedAt === 'number' && (minNodeStart === null || entry.startedAt < minNodeStart)) {
1354
+ minNodeStart = entry.startedAt;
1355
+ }
1356
+ if (typeof entry.endedAt === 'number' && (maxNodeEnd === null || entry.endedAt > maxNodeEnd)) {
1357
+ maxNodeEnd = entry.endedAt;
1358
+ }
1359
+ const baseMs = typeof entry.durationMs === 'number' ? entry.durationMs : 0;
1360
+ const liveExtra = (entry.status === 'running' || entry.status === 'waiting')
1361
+ && typeof entry.startedAt === 'number' && !entry.endedAt
1362
+ ? Math.max(0, clock - entry.startedAt)
1363
+ : 0;
1364
+ const totalMs = baseMs + liveExtra;
1365
+ const canvasNode = byCanvasId.get(entry.id);
1366
+ const childRun = runMap[entry.id] || null;
1367
+ const entryStatus = entry.status || 'pending';
1368
+ const isUnrun = entryStatus === 'pruned' || (entryStatus === 'pending' && totalMs === 0);
1369
+ const isZeroLead = (entry.kind || (canvasNode && canvasNode.kind)) === 'lead' && totalMs === 0 && entryStatus !== 'running' && entryStatus !== 'waiting';
1370
+ return {
1371
+ id: entry.id,
1372
+ label: entry.label || (canvasNode && canvasNode.label) || entry.id,
1373
+ kind: entry.kind || (canvasNode && canvasNode.kind) || 'agent',
1374
+ status: entryStatus,
1375
+ durationMs: (isUnrun || isZeroLead) ? null : totalMs,
1376
+ runs: typeof entry.runs === 'number' ? entry.runs : 0,
1377
+ model: entry.model || '',
1378
+ fallbackUsed: Boolean(entry.fallbackUsed),
1379
+ sessionContinued: Boolean(entry.sessionContinued),
1380
+ childId: isUnrun ? '' : (entry.childId || (childRun && childRun.childId) || ''),
1381
+ reason: entry.reason || '',
1382
+ onCanvas: Boolean(canvasNode),
1383
+ };
1384
+ });
1385
+ } else {
1386
+ // Graceful fallback for older `.run.json` payloads written before `summary` existed.
1387
+ const doneSet = new Set(Array.isArray(runState.done) ? runState.done : []);
1388
+ const prunedSet = new Set(Array.isArray(runState.pruned) ? runState.pruned : []);
1389
+ const decisions = runState.decisions && typeof runState.decisions === 'object' ? runState.decisions : {};
1390
+ rows = canvasNodes.filter((n) => n && n.id !== 'lead').map((n) => {
1391
+ const dec = decisions[n.id] || null;
1392
+ const childRun = runMap[n.id] || null;
1393
+ let st = 'pending';
1394
+ if (prunedSet.has(n.id)) st = 'pruned';
1395
+ else if (status === 'need-lead' && waitingLead && waitingLead.id === n.id) st = 'waiting';
1396
+ else if (dec && dec.failed) st = 'failed';
1397
+ else if (doneSet.has(n.id)) st = 'done';
1398
+ const reason = dec
1399
+ ? ((Array.isArray(dec.branchLabels) && dec.branchLabels.length ? dec.branchLabels.join(', ') : (dec.branchLabel || ''))
1400
+ + (dec.reason ? ' — ' + dec.reason : ''))
1401
+ : '';
1402
+ return {
1403
+ id: n.id,
1404
+ label: n.label || n.id,
1405
+ kind: n.kind || 'agent',
1406
+ status: st,
1407
+ durationMs: null,
1408
+ runs: doneSet.has(n.id) ? 1 : 0,
1409
+ model: n.model || '',
1410
+ fallbackUsed: false,
1411
+ sessionContinued: false,
1412
+ childId: (st === 'pruned' || st === 'pending') ? '' : ((childRun && childRun.childId) || ''),
1413
+ reason,
1414
+ onCanvas: true,
1415
+ };
1416
+ });
1417
+ }
1418
+
1419
+ if (!rows.length) return { hasData: false };
1420
+
1421
+ let doneCount = 0;
1422
+ let failedCount = 0;
1423
+ let prunedCount = 0;
1424
+ let runningCount = 0;
1425
+ let maxNodeMs = 0;
1426
+ for (const r of rows) {
1427
+ if (r.status === 'done' || r.status === 'reused') doneCount += 1;
1428
+ else if (r.status === 'failed' || r.status === 'empty') failedCount += 1;
1429
+ else if (r.status === 'pruned') prunedCount += 1;
1430
+ else if (r.status === 'running' || r.status === 'waiting') runningCount += 1;
1431
+ if (typeof r.durationMs === 'number' && r.durationMs > maxNodeMs) maxNodeMs = r.durationMs;
1432
+ }
1433
+
1434
+ const fb = fallbackTiming && typeof fallbackTiming === 'object' ? fallbackTiming : null;
1435
+ const startedAt = (sum && typeof sum.startedAt === 'number')
1436
+ ? sum.startedAt
1437
+ : (minNodeStart !== null ? minNodeStart : (fb && typeof fb.startedAt === 'number' ? fb.startedAt : null));
1438
+ const endedAt = (sum && typeof sum.endedAt === 'number')
1439
+ ? sum.endedAt
1440
+ : (!isLive && maxNodeEnd !== null
1441
+ ? maxNodeEnd
1442
+ : (!isLive && fb && typeof fb.endedAt === 'number' ? fb.endedAt : null));
1443
+ const elapsedMs = startedAt !== null
1444
+ ? Math.max(0, (endedAt !== null ? endedAt : (isLive ? clock : (runState.at || clock))) - startedAt)
1445
+ : (maxNodeMs > 0 ? maxNodeMs : null);
1446
+
1447
+ const loops = sum && Array.isArray(sum.loops) ? sum.loops : [];
1448
+ const totalLoops = sum && typeof sum.totalLoops === 'number'
1449
+ ? sum.totalLoops
1450
+ : loops.reduce((acc, l) => acc + (Number(l && l.used) || 0), 0);
1451
+
1452
+ return {
1453
+ hasData: true,
1454
+ status,
1455
+ isLive,
1456
+ waitingLead,
1457
+ haltedReason: (sum && sum.haltedReason) || '',
1458
+ maxParallel: (sum && typeof sum.maxParallel === 'number') ? sum.maxParallel : null,
1459
+ elapsedMs,
1460
+ totalCount: rows.length,
1461
+ doneCount,
1462
+ failedCount,
1463
+ prunedCount,
1464
+ runningCount,
1465
+ maxNodeMs,
1466
+ totalLoops,
1467
+ loops,
1468
+ nodes: rows,
1469
+ };
1470
+ }
1471
+
1472
+ /** Render a deterministic GitHub-Flavored Markdown report from a run summary view. */
1473
+ function formatRunSummaryMarkdown(view, lang) {
1474
+ if (!view || !view.hasData) return '';
1475
+ const en = lang === 'en';
1476
+ const dict = I18N[en ? 'en' : 'zh'];
1477
+ const statusLabel = (st) => {
1478
+ if (st === 'done') return dict.runStDone;
1479
+ if (st === 'reused') return dict.runSummaryReused;
1480
+ if (st === 'running') return dict.runStRunning;
1481
+ if (st === 'waiting' || st === 'need-lead') return dict.runStWaiting;
1482
+ if (st === 'halted') return dict.runStHalted;
1483
+ if (st === 'failed') return dict.runStFailed;
1484
+ if (st === 'empty') return dict.runStEmpty;
1485
+ if (st === 'pruned') return dict.runStPruned;
1486
+ return dict.runStPending;
1487
+ };
1488
+ const kindLabel = (k) => (k === 'condition' ? (en ? 'Condition' : '条件') : (k === 'lead' ? 'Lead' : (en ? 'Subagent' : '子代理')));
1489
+ const esc = (s) => String(s || '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
1490
+ const lines = [
1491
+ '### ' + dict.runSummaryTitle,
1492
+ '',
1493
+ '- **' + (en ? 'Status' : '状态') + '**: ' + statusLabel(view.status)
1494
+ + (view.waitingLead && view.waitingLead.label ? ' (' + view.waitingLead.label + ')' : ''),
1495
+ '- **' + dict.runSummaryElapsed + '**: ' + formatDurationMs(view.elapsedMs),
1496
+ '- **' + (en ? 'Nodes' : '节点') + '**: ' + view.doneCount + '/' + view.totalCount
1497
+ + (view.failedCount ? ' · ' + view.failedCount + ' ' + dict.runStFailed : '')
1498
+ + (view.prunedCount ? ' · ' + view.prunedCount + ' ' + dict.runStPruned : ''),
1499
+ '- **' + dict.runSummaryLoops + '**: ' + view.totalLoops
1500
+ + (view.maxParallel ? ' · **' + dict.runSummaryParallel + '**: ×' + view.maxParallel : ''),
1501
+ ];
1502
+ if (view.haltedReason) {
1503
+ lines.push('- **' + (en ? 'Halt reason' : '终止原因') + '**: ' + esc(view.haltedReason));
1504
+ }
1505
+ lines.push('');
1506
+ lines.push(en
1507
+ ? '| Node | Type | Status | Duration | Runs | Notes |'
1508
+ : '| 节点 | 类型 | 状态 | 耗时 | 轮次 | 备注 |');
1509
+ lines.push('| :--- | :--- | :--- | ---: | ---: | :--- |');
1510
+ for (const n of view.nodes) {
1511
+ const notes = [];
1512
+ if (n.model) notes.push(n.model);
1513
+ if (n.fallbackUsed) notes.push(dict.runSummaryFallback);
1514
+ if (n.sessionContinued) notes.push(dict.runSummaryContinued);
1515
+ if (n.reason) notes.push(n.reason);
1516
+ lines.push(
1517
+ '| ' + esc(n.label)
1518
+ + ' | ' + kindLabel(n.kind)
1519
+ + ' | ' + statusLabel(n.status)
1520
+ + ' | ' + formatDurationMs(n.durationMs)
1521
+ + ' | ' + (n.runs > 0 ? String(n.runs) : '—')
1522
+ + ' | ' + esc(notes.join(' · '))
1523
+ + ' |',
1524
+ );
1525
+ }
1526
+ if (view.loops && view.loops.length) {
1527
+ lines.push('');
1528
+ lines.push('#### ' + dict.runSummaryLoopsHead);
1529
+ for (const lp of view.loops) {
1530
+ lines.push('- **' + esc(lp.fromLabel) + ' ↺ ' + esc(lp.toLabel) + '** (' + lp.used + '/' + lp.max + (lp.exhausted ? ' · ' + dict.runSummaryExhausted : '') + ')');
1531
+ for (const r of (lp.rounds || [])) {
1532
+ lines.push(' - R' + r.round + ': ' + esc(r.reason));
1533
+ }
1534
+ }
1535
+ }
1536
+ return lines.join('\n');
1537
+ }
1538
+
1167
1539
  function isCustomBranches(node) {
1168
1540
  return Boolean(node && node.kind === 'condition' && Array.isArray(node.branches) && node.branches.length >= 2);
1169
1541
  }
@@ -1439,6 +1811,12 @@ window.__ModuleLoader__.load({
1439
1811
  }
1440
1812
  }
1441
1813
  if (!reach.has(exitId)) return { ok: false, reason: 'loopDisconnected' };
1814
+ // Verify the full runtime loop body (`descendants(entry) ∩ ancestors(exit)` across the
1815
+ // entire graph) never pulls in a node already owned by another loop.
1816
+ const fullMembers = loopMemberIdsUI(list, edges, { from: exitId, to: entryId, loop: true });
1817
+ for (const mid of fullMembers) {
1818
+ if (existing.byNode.has(mid)) return { ok: false, reason: 'loopOverlap' };
1819
+ }
1442
1820
  const exitNode = byId.get(exitId);
1443
1821
  return {
1444
1822
  ok: true,
@@ -1632,8 +2010,8 @@ window.__ModuleLoader__.load({
1632
2010
  }
1633
2011
  const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
1634
2012
  const out = [];
1635
- while (queue.length) {
1636
- const id = queue.shift();
2013
+ for (let i = 0; i < queue.length; i += 1) {
2014
+ const id = queue[i];
1637
2015
  out.push(id);
1638
2016
  for (const next of adj.get(id)) {
1639
2017
  indeg.set(next, indeg.get(next) - 1);
@@ -1735,8 +2113,8 @@ window.__ModuleLoader__.load({
1735
2113
  }
1736
2114
  const seen = new Set([toId]);
1737
2115
  const queue = [toId];
1738
- while (queue.length) {
1739
- const cur = queue.shift();
2116
+ for (let i = 0; i < queue.length; i += 1) {
2117
+ const cur = queue[i];
1740
2118
  if (cur === fromId) return true;
1741
2119
  for (const next of adj.get(cur) || []) {
1742
2120
  if (!seen.has(next)) { seen.add(next); queue.push(next); }
@@ -1791,14 +2169,16 @@ window.__ModuleLoader__.load({
1791
2169
  }
1792
2170
  } else {
1793
2171
  const COL_PITCH = 300;
1794
- const ROW_PITCH = 262;
2172
+ const ROW_GAP = 28;
1795
2173
  const MID_Y = 320;
1796
2174
  for (const [col, colNodes] of columns.entries()) {
1797
2175
  const ordered = colNodes.slice().sort((a, b) => (a.y || 0) - (b.y || 0));
1798
- const totalH = (ordered.length - 1) * ROW_PITCH + NODE_H;
1799
- const startY = Math.round(MID_Y - totalH / 2);
2176
+ const heights = ordered.map((n) => nodeHeight(n));
2177
+ const totalH = heights.reduce((sum, hVal) => sum + hVal, 0) + Math.max(0, ordered.length - 1) * ROW_GAP;
2178
+ let cursorY = Math.round(MID_Y - totalH / 2);
1800
2179
  ordered.forEach((n, row) => {
1801
- posById.set(n.id, { x: 40 + col * COL_PITCH, y: startY + row * ROW_PITCH });
2180
+ posById.set(n.id, { x: 40 + col * COL_PITCH, y: cursorY });
2181
+ cursorY += heights[row] + ROW_GAP;
1802
2182
  });
1803
2183
  }
1804
2184
  }
@@ -2002,50 +2382,100 @@ window.__ModuleLoader__.load({
2002
2382
  {
2003
2383
  id: 'lead', kind: 'lead', label: 'Lead', y: 0,
2004
2384
  task: en
2005
- ? '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.'
2006
- : '实现目标功能并跑测试验证:若测试或检查不通过,自动带着失败原因回环修改(最多 3 次),全部通过后交我终审交付。',
2385
+ ? '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.'
2386
+ : '端到端交付 OAuth 登录模块:先并行摸底代码库与安全约束,我拍板后并行开发实现与文档用例;质量门禁未通过则带反馈自动回环修复(最多 3 轮),通过后直达终审交付。',
2387
+ refs: ['AGENTS.md', 'docs/auth-spec.md'],
2007
2388
  provider: '', model: '', role: '',
2008
2389
  },
2390
+ {
2391
+ id: 'lp_scan', kind: 'agent', y: 0,
2392
+ label: en ? 'Codebase Scan' : '代码库摸底',
2393
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: true,
2394
+ role: en
2395
+ ? 'Locate auth routes, session middleware and conventions; keep warm session for Core Implement.'
2396
+ : '定位鉴权路由、会话中间件与工程约定,保留热会话供核心实现无缝续接。',
2397
+ },
2398
+ {
2399
+ id: 'lp_risk', kind: 'agent', y: 100,
2400
+ label: en ? 'Security Spec' : '安全与约束',
2401
+ provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false,
2402
+ refs: ['docs/security.md'],
2403
+ role: en
2404
+ ? 'Read-only threat check (CSRF, PKCE, token rotation); output structured JSON spec.'
2405
+ : '只读梳理 CSRF、PKCE 与令牌轮换约束,输出结构化 JSON 方案。',
2406
+ },
2407
+ {
2408
+ id: 'lp_signoff', kind: 'lead', y: 0,
2409
+ label: en ? 'Lead Sign-Off' : 'Lead 拍板',
2410
+ provider: '', model: '',
2411
+ role: en
2412
+ ? 'Review structured spec, confirm scope and non-goals, then release parallel delivery.'
2413
+ : '评审结构化安全方案,锁定改动边界与不做的事,放行并行实现。',
2414
+ },
2009
2415
  {
2010
2416
  id: 'lp_impl', kind: 'agent', y: 0,
2011
- label: en ? 'Implement' : '编写实现',
2012
- provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
2417
+ label: en ? 'Core Implement' : '核心实现与自测',
2418
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: true,
2013
2419
  role: en
2014
- ? 'Implement the requested change cleanly. When invoked on a retry round, focus directly on fixing the reported issues and list modified files.'
2015
- : '按需求完成代码或文档实现;若处于回环修正轮次,针对打回理由直接定点修复并列出改动清单。',
2420
+ ? 'Continue inside scan session to implement OAuth flow and run tests; on retry rounds fix reported defects directly.'
2421
+ : '沿用摸底热会话实现 OAuth 流程并跑测试;若被打回则按反馈定点修复。',
2016
2422
  },
2017
2423
  {
2018
- id: 'lp_test', kind: 'agent', y: 0,
2019
- label: en ? 'Test & Verify' : '测试与检查',
2424
+ id: 'lp_docs', kind: 'agent', y: 100,
2425
+ label: en ? 'Docs & Checklist' : '文档与验收清单',
2020
2426
  provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
2021
2427
  role: en
2022
- ? 'Run tests/lint/checks against the implementation and report exact pass/fail status, error logs, and remaining defects.'
2023
- : '对实现结果运行单测、构建或逐项核验,如实汇报通过情况、具体报错日志与遗留缺陷。',
2428
+ ? 'Update config docs and acceptance checklist in parallel (never touch source files).'
2429
+ : '并行补齐配置文档与验收清单(不改业务源码,与回环实现互不干扰)。',
2024
2430
  },
2025
2431
  {
2026
2432
  id: 'lp_gate', kind: 'condition', y: 0,
2027
- label: en ? 'Checks Passed?' : '是否通过?',
2433
+ label: en ? 'Quality Gate' : '质量门禁',
2028
2434
  provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false,
2435
+ branches: [
2436
+ { id: 'true', label: en ? 'Pass' : '通过', when: en ? 'All tests and security checks passed' : '单测与安全核验全部通过' },
2437
+ { id: 'false', label: en ? 'Fix Loop' : '打回修复', when: en ? 'Any test failed or defect remains' : '存在测试失败或未解决缺陷' },
2438
+ ],
2029
2439
  role: en
2030
- ? 'Return pass=true only if all tests/checks passed with no unresolved defects; otherwise return pass=false with a concise, actionable fix reason.'
2031
- : '仅当测试与检查全部通过且无未解决缺陷时返回 true;否则返回 false,并在理由里写清下一轮需修复的具体问题。',
2440
+ ? 'Verify test results and security checklist; route to Pass only when clean, otherwise return actionable fix feedback.'
2441
+ : '核验测试结果与安全清单;全部通过走「通过」,否则走「打回修复」并附具体修复理由。',
2032
2442
  },
2033
2443
  {
2034
2444
  id: 'lp_final', kind: 'lead', y: 0,
2035
- label: en ? 'Lead Final Review' : 'Lead 终审',
2445
+ label: en ? 'Lead Ship Gate' : 'Lead 终审交付',
2036
2446
  provider: '', model: '',
2037
2447
  role: en
2038
- ? 'Review the verified result (or the round-by-round summary if retries exhausted) and decide whether to ship or intervene.'
2039
- : '审阅最终通过的改动摘要(或回环达上限后的历次失败记录),确认交付或拍板下一步处理。',
2448
+ ? 'Combine verified implementation and docs into final release summary.'
2449
+ : '汇聚通过门禁的实现与文档,给出最终交付结论。',
2040
2450
  },
2041
2451
  ];
2042
2452
  const loopEdges = [
2043
- { id: 'lp1', from: 'lead', to: 'lp_impl', type: 'prompt' },
2044
- { id: 'lp2', from: 'lp_impl', to: 'lp_test', type: 'prompt' },
2045
- { id: 'lp3', from: 'lp_test', to: 'lp_gate', type: 'prompt' },
2046
- { id: 'lp4', from: 'lp_gate', to: 'lp_final', type: 'prompt', branch: 'true' },
2047
- { id: 'lp5', from: 'lp_gate', to: 'lp_impl', type: 'prompt', branch: 'false', loop: true, maxIterations: 3 },
2453
+ { id: 'lp1', from: 'lead', to: 'lp_scan', type: 'prompt' },
2454
+ { id: 'lp2', from: 'lead', to: 'lp_risk', type: 'prompt' },
2455
+ { id: 'lp3', from: 'lp_scan', to: 'lp_signoff', type: 'prompt' },
2456
+ { id: 'lp4', from: 'lp_risk', to: 'lp_signoff', type: 'structured' },
2457
+ { id: 'lp5', from: 'lp_signoff', to: 'lp_impl', type: 'prompt' },
2458
+ { id: 'lp6', from: 'lp_scan', to: 'lp_impl', type: 'session-ref' },
2459
+ { id: 'lp7', from: 'lp_signoff', to: 'lp_docs', type: 'prompt' },
2460
+ { id: 'lp8', from: 'lp_impl', to: 'lp_gate', type: 'prompt' },
2461
+ { id: 'lp9', from: 'lp_gate', to: 'lp_final', type: 'prompt', branch: 'true' },
2462
+ { id: 'lp10', from: 'lp_gate', to: 'lp_impl', type: 'prompt', branch: 'false', loop: true, maxIterations: 3 },
2463
+ { id: 'lp11', from: 'lp_docs', to: 'lp_final', type: 'prompt' },
2048
2464
  ];
2465
+ // Align the loop pair (lp_impl -> lp_gate) on the outer rail side (top in lr, right in tb)
2466
+ // so the dashed loop frame and outer bypass arc never overlap the parallel bypass node lp_docs.
2467
+ const loopLaid = layoutGraph(loopNodes, loopEdges, direction).map((n) => ({ ...n }));
2468
+ const lpById = new Map(loopLaid.map((n) => [n.id, n]));
2469
+ if (direction === 'tb') {
2470
+ const leftX = Math.min(lpById.get('lp_impl').x, lpById.get('lp_docs').x);
2471
+ const rightX = Math.max(lpById.get('lp_impl').x, lpById.get('lp_docs').x);
2472
+ lpById.get('lp_docs').x = leftX;
2473
+ lpById.get('lp_impl').x = rightX;
2474
+ lpById.get('lp_gate').x = rightX;
2475
+ } else {
2476
+ lpById.get('lp_gate').y = lpById.get('lp_impl').y - 8;
2477
+ lpById.get('lp_docs').y = Math.max(lpById.get('lp_docs').y, lpById.get('lp_gate').y + nodeHeight(lpById.get('lp_gate')) + 64);
2478
+ }
2049
2479
  return [
2050
2480
  {
2051
2481
  id: 'tpl-swe',
@@ -2073,8 +2503,8 @@ window.__ModuleLoader__.load({
2073
2503
  },
2074
2504
  {
2075
2505
  id: 'tpl-loop',
2076
- name: en ? 'Retry Loop: Implement → Test ↺ Fix → Review' : '循环重试:实现 → 测试验收 ↺ 自动修复 → 终审',
2077
- nodes: layoutGraph(loopNodes, loopEdges, direction),
2506
+ name: en ? 'Full Showcase: Parallel → Gate → Loop ↺ Fix → Ship' : '全功能回环:并行摸底 → 拍板 → 实现 ↺ 门禁 → 终审',
2507
+ nodes: loopLaid,
2078
2508
  edges: loopEdges,
2079
2509
  },
2080
2510
  ];
@@ -2343,6 +2773,37 @@ window.__ModuleLoader__.load({
2343
2773
  return { k, x: cx - lx * k, y: cy - ly * k };
2344
2774
  }
2345
2775
 
2776
+ /**
2777
+ * Apply one incremental pan step on top of the latest live `curView` so concurrent
2778
+ * wheel zoom anchor shifts are never overwritten by stale drag origins.
2779
+ */
2780
+ function applyPanStep(curView, pan, clientX, clientY) {
2781
+ const dx = clientX - pan.lastX;
2782
+ const dy = clientY - pan.lastY;
2783
+ return {
2784
+ view: { k: curView.k, x: curView.x + dx, y: curView.y + dy },
2785
+ pan: { lastX: clientX, lastY: clientY },
2786
+ };
2787
+ }
2788
+
2789
+ function normalizeDirection(val) {
2790
+ return val === 'tb' ? 'tb' : 'lr';
2791
+ }
2792
+
2793
+ function loadDefaultDirection() {
2794
+ try {
2795
+ return normalizeDirection(window.localStorage.getItem(DIRECTION_KEY));
2796
+ } catch (_e) {
2797
+ return 'lr';
2798
+ }
2799
+ }
2800
+
2801
+ function saveDefaultDirection(dir) {
2802
+ try {
2803
+ window.localStorage.setItem(DIRECTION_KEY, normalizeDirection(dir));
2804
+ } catch (_e) { /* ignore */ }
2805
+ }
2806
+
2346
2807
  function loadPresets() {
2347
2808
  try {
2348
2809
  const raw = window.localStorage.getItem(PRESET_KEY);
@@ -2357,6 +2818,16 @@ window.__ModuleLoader__.load({
2357
2818
  function savePresets(presets) {
2358
2819
  try {
2359
2820
  window.localStorage.setItem(PRESET_KEY, JSON.stringify(presets));
2821
+ // Native `storage` events only fire across separate windows, not across keepMounted
2822
+ // session tabs inside the same Electron window; broadcast a custom event for instant sync.
2823
+ try {
2824
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
2825
+ const ev = typeof CustomEvent === 'function'
2826
+ ? new CustomEvent(PRESET_CHANGE_EVENT)
2827
+ : { type: PRESET_CHANGE_EVENT };
2828
+ window.dispatchEvent(ev);
2829
+ }
2830
+ } catch (_evErr) { /* ignore in non-DOM test env */ }
2360
2831
  return true;
2361
2832
  } catch (_e) {
2362
2833
  return false;
@@ -2437,8 +2908,15 @@ window.__ModuleLoader__.load({
2437
2908
  const sessionId = props && props.sessionId;
2438
2909
  const stored = useRef(loadDoc(sessionId));
2439
2910
  const initial = stored.current;
2440
-
2441
- const [nodes, setNodes] = useState(() => (initial ? initial.nodes : defaultNodes()));
2911
+ const initialDir = (initial && (initial.direction === 'tb' || initial.direction === 'lr'))
2912
+ ? initial.direction
2913
+ : loadDefaultDirection();
2914
+
2915
+ const [nodes, setNodes] = useState(() => {
2916
+ if (initial) return initial.nodes;
2917
+ const dn = defaultNodes();
2918
+ return initialDir === 'tb' ? layoutGraph(dn, defaultEdges(), 'tb') : dn;
2919
+ });
2442
2920
  const [edges, setEdges] = useState(() => (initial ? initial.edges : defaultEdges()));
2443
2921
  const [selectedIds, setSelectedIds] = useState([]);
2444
2922
  const [marquee, setMarquee] = useState(null);
@@ -2449,6 +2927,9 @@ window.__ModuleLoader__.load({
2449
2927
  const [menuAlign, setMenuAlign] = useState('right');
2450
2928
  const [presetAlign, setPresetAlign] = useState('right');
2451
2929
  const [helpOpen, setHelpOpen] = useState(false);
2930
+ const [summaryOpen, setSummaryOpen] = useState(false);
2931
+ const [summaryNow, setSummaryNow] = useState(() => Date.now());
2932
+ const clientRunTimingRef = useRef({ startedAt: null, endedAt: null, prevStatus: '', runAt: null });
2452
2933
  const [shortcuts, setShortcuts] = useState(loadShortcuts);
2453
2934
  const shortcutsRef = useRef(shortcuts);
2454
2935
  shortcutsRef.current = shortcuts;
@@ -2472,7 +2953,7 @@ window.__ModuleLoader__.load({
2472
2953
  const [modelsLoading, setModelsLoading] = useState(() => cachedModels.length === 0);
2473
2954
  const [openModelFor, setOpenModelFor] = useState(null);
2474
2955
  const [enabled, setEnabled] = useState(() => Boolean(initial && initial.enabled));
2475
- const [direction, setDirection] = useState(() => (initial && initial.direction === 'tb' ? 'tb' : 'lr'));
2956
+ const [direction, setDirection] = useState(initialDir);
2476
2957
  const directionRef = useRef(direction);
2477
2958
  directionRef.current = direction;
2478
2959
 
@@ -2489,12 +2970,12 @@ window.__ModuleLoader__.load({
2489
2970
  const rightClickRef = useRef(null);
2490
2971
  const nodeDrag = useRef(null);
2491
2972
  const panDrag = useRef(null);
2973
+ const zoomScrubbing = useRef(false);
2492
2974
  const [panning, setPanning] = useState(false);
2493
2975
  const spaceDown = useRef(false);
2494
2976
  const [spaceHeld, setSpaceHeld] = useState(false);
2495
2977
  const statusTimer = useRef(null);
2496
2978
  const dropdownRef = useRef(null);
2497
- const syncTimer = useRef(null);
2498
2979
  const lastSync = useRef('');
2499
2980
  const historyRef = useRef([]);
2500
2981
  const redoRef = useRef([]);
@@ -2510,11 +2991,50 @@ window.__ModuleLoader__.load({
2510
2991
  const [sessionRunning, setSessionRunning] = useState(false);
2511
2992
  const [runTriggering, setRunTriggering] = useState(false);
2512
2993
  const runTriggeringRef = useRef(false);
2994
+ const [stopping, setStopping] = useState(false);
2995
+ const stoppingRef = useRef(false);
2513
2996
  const pendingHandledRef = useRef(false);
2514
2997
  const lastNodePrefsRef = useRef({ provider: '', model: '', reasoning: '', preset: 'standard' });
2515
2998
  const [presets, setPresets] = useState(loadPresets);
2516
2999
  const [presetOpen, setPresetOpen] = useState(null);
2517
3000
  const [presetName, setPresetName] = useState('');
3001
+
3002
+ const refreshPresets = (announce) => {
3003
+ const latest = loadPresets();
3004
+ setPresets(latest);
3005
+ if (announce) flash(t('presetsRefreshed'));
3006
+ return latest;
3007
+ };
3008
+
3009
+ // Keep preset list fresh across mounted session tabs (same window + cross-window).
3010
+ useEffect(() => {
3011
+ const sync = () => setPresets(loadPresets());
3012
+ const onStorage = (ev) => {
3013
+ if (!ev || ev.key === PRESET_KEY || ev.key === null) sync();
3014
+ };
3015
+ const onVis = () => {
3016
+ if (typeof document !== 'undefined' && document.visibilityState === 'visible') sync();
3017
+ };
3018
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
3019
+ window.addEventListener('storage', onStorage);
3020
+ window.addEventListener(PRESET_CHANGE_EVENT, sync);
3021
+ window.addEventListener('focus', sync);
3022
+ }
3023
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
3024
+ document.addEventListener('visibilitychange', onVis);
3025
+ }
3026
+ sync();
3027
+ return () => {
3028
+ if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
3029
+ window.removeEventListener('storage', onStorage);
3030
+ window.removeEventListener(PRESET_CHANGE_EVENT, sync);
3031
+ window.removeEventListener('focus', sync);
3032
+ }
3033
+ if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
3034
+ document.removeEventListener('visibilitychange', onVis);
3035
+ }
3036
+ };
3037
+ }, [sessionId]);
2518
3038
  const [lang, setLang] = useState(loadLang);
2519
3039
  const t = (key) => (I18N[lang] && I18N[lang][key]) || I18N.zh[key] || key;
2520
3040
  const toggleLang = () => {
@@ -2621,7 +3141,7 @@ window.__ModuleLoader__.load({
2621
3141
  const sig = planSig(nextEnabled, curNodes, curEdges, overrideParallel);
2622
3142
  if (sig === lastSync.current) { setDirty(false); flash(t('upToDate')); return Promise.resolve(true); }
2623
3143
  const line = '/canvas-sync ' + encodeURIComponent(sig);
2624
- const hasStandardAgent = nextEnabled && curNodes.some((n) => n && n.kind !== 'lead' && (n.preset || 'standard') !== 'minimal');
3144
+ const hasStandardAgent = nextEnabled && curNodes.some((n) => n && n.kind !== 'lead' && n.kind !== 'condition' && (n.preset || 'standard') !== 'minimal');
2625
3145
  return face.command(line).then((ack) => {
2626
3146
  if (ack && ack.ok) {
2627
3147
  lastSync.current = sig;
@@ -2701,6 +3221,113 @@ window.__ModuleLoader__.load({
2701
3221
  }
2702
3222
  };
2703
3223
 
3224
+ /**
3225
+ * Unified Stop action for both in-flight executions (#11) and paused Lead gates (#13),
3226
+ * using DSH 0.2.2 verified APIs:
3227
+ * - `face.command('/canvas-stop')` (executes concurrently even while running; triggers
3228
+ * backend `subagents.interrupt` + `drainDescendants([agent])` + `agent.cancel` + clears waitingLead)
3229
+ * - `remote.subagents.interruptByUser(childId)` for every live subagent
3230
+ * - `face.cancel()` / `remote.session.cancel({ sessionId })` for the root session turn
3231
+ */
3232
+ const stopWorkflow = async () => {
3233
+ if (stoppingRef.current) return;
3234
+ stoppingRef.current = true;
3235
+ setStopping(true);
3236
+ const wasWaitingOnly = !sessionRunning && !runTriggeringRef.current
3237
+ && !Object.values(statusById).some((s) => s === 'running');
3238
+ // Resolved lazily rather than via hard `inject` so missing namespaces on older hosts never block plugin load.
3239
+ const resolveRemoteSubagents = () => {
3240
+ try {
3241
+ if (hostCtx && typeof hostCtx.get === 'function') {
3242
+ const svc = hostCtx.get('remote.subagents');
3243
+ if (svc) return svc;
3244
+ }
3245
+ } catch (_e) { /* absent */ }
3246
+ try {
3247
+ return (hostCtx && hostCtx.remote && hostCtx.remote.subagents) || null;
3248
+ } catch (_e) {
3249
+ return null;
3250
+ }
3251
+ };
3252
+ try {
3253
+ const runningChildIds = new Set();
3254
+ try {
3255
+ const sessions = hostCtx && hostCtx.sessions;
3256
+ if (sessions && sessionId && sessions.list && typeof sessions.list.getSnapshot === 'function') {
3257
+ const snap = sessions.list.getSnapshot();
3258
+ const proj = snap && snap.projectionsBySession && snap.projectionsBySession[sessionId];
3259
+ const catalog = proj && proj.values && proj.values.subagentCatalog;
3260
+ if (Array.isArray(catalog)) {
3261
+ for (const entry of catalog) {
3262
+ if (!entry || !entry.id) continue;
3263
+ const child = snap.byId && snap.byId[entry.id];
3264
+ if (child && child.running) runningChildIds.add(String(entry.id));
3265
+ }
3266
+ }
3267
+ }
3268
+ } catch (_e) { /* ignore */ }
3269
+ for (const [nid, st] of Object.entries(statusById)) {
3270
+ if (st === 'running' && runsById[nid] && runsById[nid].childId) {
3271
+ runningChildIds.add(String(runsById[nid].childId));
3272
+ }
3273
+ }
3274
+
3275
+ const face = sessionFace(sessionId);
3276
+ const tasks = [];
3277
+
3278
+ // 1) Fire `/canvas-stop` immediately (runs concurrently even while a turn is active).
3279
+ if (face && typeof face.command === 'function') {
3280
+ tasks.push(Promise.resolve().then(() => face.command('/canvas-stop')).catch(() => {}));
3281
+ }
3282
+
3283
+ // 2) Interrupt every running child subagent via `remote.subagents.interruptByUser(childId)`.
3284
+ const remoteSub = resolveRemoteSubagents();
3285
+ if (remoteSub && typeof remoteSub.interruptByUser === 'function') {
3286
+ for (const cid of runningChildIds) {
3287
+ tasks.push(Promise.resolve().then(() => remoteSub.interruptByUser(cid)).catch(() => {}));
3288
+ }
3289
+ }
3290
+
3291
+ // 3) Cancel the running root session turn (never call session.cancel on subagents).
3292
+ if (sessionRunning || runTriggeringRef.current) {
3293
+ if (face && typeof face.cancel === 'function') {
3294
+ tasks.push(Promise.resolve().then(() => face.cancel()).catch(() => {}));
3295
+ } else {
3296
+ const remoteSess = hostCtx && hostCtx.remote && hostCtx.remote.session;
3297
+ if (remoteSess && typeof remoteSess.cancel === 'function' && sessionId) {
3298
+ tasks.push(Promise.resolve().then(() => remoteSess.cancel({ sessionId })).catch(() => {}));
3299
+ }
3300
+ }
3301
+ }
3302
+
3303
+ await Promise.all(tasks);
3304
+ runTriggeringRef.current = false;
3305
+ setRunTriggering(false);
3306
+ const stopNow = Date.now();
3307
+ setRunState((prev) => ({
3308
+ ...(prev || {}),
3309
+ status: 'halted',
3310
+ waitingLead: null,
3311
+ ...(prev && prev.summary
3312
+ ? { summary: { ...prev.summary, status: 'halted', endedAt: prev.summary.endedAt || stopNow } }
3313
+ : {}),
3314
+ }));
3315
+ setStatusById((prev) => {
3316
+ const next = {};
3317
+ for (const [k, v] of Object.entries(prev || {})) {
3318
+ if (v !== 'running') next[k] = v;
3319
+ }
3320
+ return next;
3321
+ });
3322
+ flash(wasWaitingOnly ? t('stopWaitingDone') : t('stopSent'));
3323
+ } catch (_err) {
3324
+ flash(t('stopFailed'));
3325
+ } finally {
3326
+ stoppingRef.current = false;
3327
+ setStopping(false);
3328
+ }
3329
+ };
3330
+
2704
3331
  // Sync the moment a user message starts a turn, so this turn's tool call
2705
3332
  // already sees the latest canvas. Falls back to the turn end if the start
2706
3333
  // edge was missed; `dirty` clears on success so only one fires.
@@ -2793,7 +3420,8 @@ window.__ModuleLoader__.load({
2793
3420
  if (child && child.running) {
2794
3421
  if (entry.id) staleChildIds.current.delete(entry.id);
2795
3422
  nextStatus[nodeId] = 'running';
2796
- } else if (!entry.id || !staleChildIds.current.has(entry.id)) {
3423
+ } else if (nextStatus[nodeId] !== 'running' && (!entry.id || !staleChildIds.current.has(entry.id))) {
3424
+ // Keep 'running' sticky across catalog entries so prior retry rounds never mask an active child.
2797
3425
  if (timing && timing.lastTurnCompleted === false) nextStatus[nodeId] = 'failed';
2798
3426
  else nextStatus[nodeId] = 'done';
2799
3427
  }
@@ -2881,7 +3509,7 @@ window.__ModuleLoader__.load({
2881
3509
  return null;
2882
3510
  };
2883
3511
  const onWheel = (e) => {
2884
- if (!e.deltaY) return;
3512
+ if (!e.deltaY || zoomScrubbing.current) return;
2885
3513
  if (!e.ctrlKey && findScrollableChild(e.target, e.deltaY)) return;
2886
3514
  e.preventDefault();
2887
3515
  absorbScroll();
@@ -2945,6 +3573,13 @@ window.__ModuleLoader__.load({
2945
3573
  centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2, nextK);
2946
3574
  };
2947
3575
 
3576
+ const focusNode = (nodeId) => {
3577
+ const target = nodesRef.current.find((n) => n.id === nodeId);
3578
+ if (!target) return;
3579
+ setSelectedIds([target.id]);
3580
+ centerOn(target.x + NODE_W / 2, target.y + nodeHeight(target) / 2);
3581
+ };
3582
+
2948
3583
  /** Horizontal drag scrubber on the percentage pill; pure click resets to 100% on Lead. */
2949
3584
  const onZoomPillDown = (e) => {
2950
3585
  if (e.button !== 0) return;
@@ -2956,6 +3591,7 @@ window.__ModuleLoader__.load({
2956
3591
  const startX = e.clientX;
2957
3592
  const startView = { ...viewRef.current };
2958
3593
  let moved = false;
3594
+ zoomScrubbing.current = true;
2959
3595
  const prevCursor = typeof document !== 'undefined' && document.body ? document.body.style.cursor : '';
2960
3596
  const onMove = (ev) => {
2961
3597
  const dx = ev.clientX - startX;
@@ -2967,13 +3603,20 @@ window.__ModuleLoader__.load({
2967
3603
  commitView(scrubZoom(startView, cx, cy, dx));
2968
3604
  };
2969
3605
  const onUp = () => {
3606
+ zoomScrubbing.current = false;
2970
3607
  window.removeEventListener('mousemove', onMove);
2971
3608
  window.removeEventListener('mouseup', onUp);
3609
+ window.removeEventListener('blur', onBlurScrub);
2972
3610
  if (typeof document !== 'undefined' && document.body) document.body.style.cursor = prevCursor;
2973
3611
  if (!moved) focusLead(1);
2974
3612
  };
3613
+ const onBlurScrub = () => {
3614
+ moved = true;
3615
+ onUp();
3616
+ };
2975
3617
  window.addEventListener('mousemove', onMove);
2976
3618
  window.addEventListener('mouseup', onUp);
3619
+ window.addEventListener('blur', onBlurScrub);
2977
3620
  };
2978
3621
 
2979
3622
  /** Zoom and pan so every node sits comfortably inside the viewport. */
@@ -2994,12 +3637,15 @@ window.__ModuleLoader__.load({
2994
3637
  if (n.y + nh > maxY) maxY = n.y + nh;
2995
3638
  }
2996
3639
  if (!Number.isFinite(minX)) return;
3640
+ const hasLoopEdges = edgesRef.current.some((e) => e && e.loop === true);
3641
+ const isTB = directionRef.current === 'tb';
2997
3642
  const cw = el.clientWidth || 1;
2998
3643
  const chh = el.clientHeight || 1;
2999
- const padX = 36;
3000
- const padTop = 44;
3644
+ const padLeft = 36;
3645
+ const padRight = hasLoopEdges && isTB ? 84 : 36;
3646
+ const padTop = hasLoopEdges && !isTB ? 78 : 44;
3001
3647
  const padBottom = 36;
3002
- const availW = Math.max(80, cw - padX * 2);
3648
+ const availW = Math.max(80, cw - padLeft - padRight);
3003
3649
  const availH = Math.max(80, chh - padTop - padBottom);
3004
3650
  const bw = Math.max(NODE_W, maxX - minX);
3005
3651
  const bh = Math.max(NODE_H, maxY - minY);
@@ -3010,7 +3656,7 @@ window.__ModuleLoader__.load({
3010
3656
  el.scrollTop = 0;
3011
3657
  commitView({
3012
3658
  k,
3013
- x: cw / 2 - (cx + WORLD_PAD) * k,
3659
+ x: padLeft + (cw - padLeft - padRight) / 2 - (cx + WORLD_PAD) * k,
3014
3660
  y: padTop + (chh - padTop - padBottom) / 2 - (cy + WORLD_PAD) * k,
3015
3661
  });
3016
3662
  };
@@ -3033,7 +3679,11 @@ window.__ModuleLoader__.load({
3033
3679
 
3034
3680
  // Snapshot before every structural change so a mis-click can be undone/redone.
3035
3681
  const pushSnapshot = () => {
3036
- historyRef.current.push({ nodes: nodesRef.current, edges: edgesRef.current });
3682
+ historyRef.current.push({
3683
+ nodes: nodesRef.current,
3684
+ edges: edgesRef.current,
3685
+ direction: directionRef.current,
3686
+ });
3037
3687
  if (historyRef.current.length > 50) historyRef.current.shift();
3038
3688
  redoRef.current = [];
3039
3689
  };
@@ -3041,8 +3691,16 @@ window.__ModuleLoader__.load({
3041
3691
  const undo = () => {
3042
3692
  const prev = historyRef.current.pop();
3043
3693
  if (!prev) { flash(t('undoNone')); return; }
3044
- redoRef.current.push({ nodes: nodesRef.current, edges: edgesRef.current });
3694
+ redoRef.current.push({
3695
+ nodes: nodesRef.current,
3696
+ edges: edgesRef.current,
3697
+ direction: directionRef.current,
3698
+ });
3045
3699
  if (redoRef.current.length > 50) redoRef.current.shift();
3700
+ if (prev.direction === 'tb' || prev.direction === 'lr') {
3701
+ directionRef.current = prev.direction;
3702
+ setDirection(prev.direction);
3703
+ }
3046
3704
  setNodes(prev.nodes);
3047
3705
  setEdges(prev.edges);
3048
3706
  setSelectedIds([]);
@@ -3052,8 +3710,16 @@ window.__ModuleLoader__.load({
3052
3710
  const redo = () => {
3053
3711
  const next = redoRef.current.pop();
3054
3712
  if (!next) { flash(t('redoNone')); return; }
3055
- historyRef.current.push({ nodes: nodesRef.current, edges: edgesRef.current });
3713
+ historyRef.current.push({
3714
+ nodes: nodesRef.current,
3715
+ edges: edgesRef.current,
3716
+ direction: directionRef.current,
3717
+ });
3056
3718
  if (historyRef.current.length > 50) historyRef.current.shift();
3719
+ if (next.direction === 'tb' || next.direction === 'lr') {
3720
+ directionRef.current = next.direction;
3721
+ setDirection(next.direction);
3722
+ }
3057
3723
  setNodes(next.nodes);
3058
3724
  setEdges(next.edges);
3059
3725
  setSelectedIds([]);
@@ -3073,7 +3739,7 @@ window.__ModuleLoader__.load({
3073
3739
  }
3074
3740
  };
3075
3741
 
3076
- const openNodeSession = async (node) => {
3742
+ const openNodeSession = async (node, fallbackChildId) => {
3077
3743
  let run = runsById[node.id];
3078
3744
  if (!run) {
3079
3745
  const sessions = hostCtx && hostCtx.sessions;
@@ -3087,6 +3753,9 @@ window.__ModuleLoader__.load({
3087
3753
  run = nextRuns[node.id];
3088
3754
  }
3089
3755
  }
3756
+ if (!run && fallbackChildId) {
3757
+ run = { childId: fallbackChildId, mode: 'local', label: node.label || node.id };
3758
+ }
3090
3759
  if (!run) { flash(t('cannotOpen')); return; }
3091
3760
  openRun(node, run);
3092
3761
  };
@@ -3393,11 +4062,13 @@ window.__ModuleLoader__.load({
3393
4062
 
3394
4063
  const toggleDirection = () => {
3395
4064
  const nextDir = directionRef.current === 'tb' ? 'lr' : 'tb';
3396
- setDirection(nextDir);
3397
4065
  const curNodes = nodesRef.current;
3398
4066
  const curEdges = edgesRef.current;
4067
+ if (curNodes.length) pushSnapshot();
4068
+ directionRef.current = nextDir;
4069
+ setDirection(nextDir);
4070
+ saveDefaultDirection(nextDir);
3399
4071
  if (curNodes.length) {
3400
- pushSnapshot();
3401
4072
  const next = layoutGraph(curNodes, curEdges, nextDir);
3402
4073
  setNodes(next);
3403
4074
  setTimeout(() => fitView(next), 0);
@@ -3426,12 +4097,7 @@ window.__ModuleLoader__.load({
3426
4097
  flash(t('clearedCanvas'));
3427
4098
  };
3428
4099
 
3429
- const exportToClipboard = () => {
3430
- const cleanNodes = nodesRef.current.map((n) => {
3431
- const { runs: _runs, ...rest } = n;
3432
- return rest;
3433
- });
3434
- const text = JSON.stringify({ nodes: cleanNodes, edges: edgesRef.current }, null, 2);
4100
+ const copyTextToClipboard = (text, okMsg) => {
3435
4101
  const fallbackCopy = () => {
3436
4102
  try {
3437
4103
  const ta = document.createElement('textarea');
@@ -3442,20 +4108,35 @@ window.__ModuleLoader__.load({
3442
4108
  ta.select();
3443
4109
  const ok = document.execCommand && document.execCommand('copy');
3444
4110
  document.body.removeChild(ta);
3445
- flash(ok ? t('exportOk') : t('exportFail'));
4111
+ flash(ok ? okMsg : t('exportFail'));
3446
4112
  } catch (_e) {
3447
4113
  flash(t('exportFail'));
3448
4114
  }
3449
4115
  };
3450
4116
  try {
3451
4117
  if (navigator.clipboard && navigator.clipboard.writeText) {
3452
- navigator.clipboard.writeText(text).then(() => flash(t('exportOk')), fallbackCopy);
4118
+ navigator.clipboard.writeText(text).then(() => flash(okMsg), fallbackCopy);
3453
4119
  return;
3454
4120
  }
3455
4121
  } catch (_e) { /* fall through */ }
3456
4122
  fallbackCopy();
3457
4123
  };
3458
4124
 
4125
+ const exportToClipboard = () => {
4126
+ const cleanNodes = nodesRef.current.map((n) => {
4127
+ const { runs: _runs, ...rest } = n;
4128
+ return rest;
4129
+ });
4130
+ const text = JSON.stringify({ nodes: cleanNodes, edges: edgesRef.current, direction: directionRef.current }, null, 2);
4131
+ copyTextToClipboard(text, t('exportOk'));
4132
+ };
4133
+
4134
+ const copyRunSummary = (view) => {
4135
+ const md = formatRunSummaryMarkdown(view, lang);
4136
+ if (!md) { flash(t('runSummaryEmpty')); return; }
4137
+ copyTextToClipboard(md, t('runSummaryCopied'));
4138
+ };
4139
+
3459
4140
  const openAddMenuAtCursor = () => {
3460
4141
  const wrap = canvasWrapRef.current;
3461
4142
  const content = contentRef.current;
@@ -3588,8 +4269,12 @@ window.__ModuleLoader__.load({
3588
4269
  if (current.length <= 2) return;
3589
4270
  pushSnapshot();
3590
4271
  const next = current.filter((b) => b.id !== branchId);
3591
- updateNode(node.id, { branches: next });
3592
- setEdges((es) => es.filter((e) => !(e.from === node.id && e.branch === branchId)));
4272
+ const nextNodes = nodesRef.current.map((n) => (n.id === node.id ? { ...n, branches: next } : n));
4273
+ const remainingEdges = edgesRef.current.filter((e) => !(e.from === node.id && e.branch === branchId));
4274
+ const { edges: cleaned } = pruneInvalidLoopEdges(nextNodes, remainingEdges);
4275
+ setNodes(nextNodes);
4276
+ setEdges(cleaned);
4277
+ setLoopEditEdgeId(null);
3593
4278
  };
3594
4279
 
3595
4280
  const onOutputDown = (e, id, type, branch) => {
@@ -3727,8 +4412,7 @@ window.__ModuleLoader__.load({
3727
4412
  ev.preventDefault();
3728
4413
  ev.stopPropagation();
3729
4414
  try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
3730
- const cur = viewRef.current;
3731
- panDrag.current = { startX: ev.clientX, startY: ev.clientY, originX: cur.x, originY: cur.y };
4415
+ panDrag.current = { lastX: ev.clientX, lastY: ev.clientY };
3732
4416
  setPanning(true);
3733
4417
  setDragging(true);
3734
4418
  };
@@ -3769,9 +4453,16 @@ window.__ModuleLoader__.load({
3769
4453
  const keyActionsRef = useRef(null);
3770
4454
  keyActionsRef.current = {
3771
4455
  undo, redo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode, fitView, autoLayout, toggleDirection, flash, t,
3772
- addMenu, ctxMenu, loopEditEdgeId, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, shortcutsOpen, recordingAction, decisionViewFor, refsEditFor,
3773
- setAddMenu, setCtxMenu, setLoopEditEdgeId, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
4456
+ addMenu, ctxMenu, loopEditEdgeId, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, summaryOpen, shortcutsOpen, recordingAction, decisionViewFor, refsEditFor,
4457
+ setAddMenu, setCtxMenu, setLoopEditEdgeId, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setSummaryOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
3774
4458
  };
4459
+ const summaryIsLive = Boolean(runState && (runState.status === 'running' || runState.status === 'need-lead'));
4460
+ useEffect(() => {
4461
+ if (!summaryIsLive) return undefined;
4462
+ setSummaryNow(Date.now());
4463
+ const timer = setInterval(() => setSummaryNow(Date.now()), 1000);
4464
+ return () => clearInterval(timer);
4465
+ }, [summaryIsLive, summaryOpen]);
3775
4466
  useEffect(() => {
3776
4467
  const isEditable = (target) => {
3777
4468
  if (!target || !(target instanceof HTMLElement)) return false;
@@ -3799,7 +4490,7 @@ window.__ModuleLoader__.load({
3799
4490
  return;
3800
4491
  }
3801
4492
  if (ev.key === 'Escape') {
3802
- if (act.addMenu || act.ctxMenu || act.loopEditEdgeId || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen || act.shortcutsOpen || act.decisionViewFor || act.refsEditFor) {
4493
+ 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) {
3803
4494
  ev.preventDefault();
3804
4495
  act.setAddMenu(null);
3805
4496
  act.setCtxMenu(null);
@@ -3809,6 +4500,7 @@ window.__ModuleLoader__.load({
3809
4500
  act.setMenuOpen(false);
3810
4501
  act.setPresetOpen(null);
3811
4502
  act.setHelpOpen(false);
4503
+ act.setSummaryOpen(false);
3812
4504
  act.setShortcutsOpen(false);
3813
4505
  act.setRecordingAction(null);
3814
4506
  act.setDecisionViewFor(null);
@@ -3816,7 +4508,7 @@ window.__ModuleLoader__.load({
3816
4508
  }
3817
4509
  return;
3818
4510
  }
3819
- if (act.shortcutsOpen) return;
4511
+ if (act.shortcutsOpen || act.summaryOpen || act.helpOpen) return;
3820
4512
  if (isEditable(ev.target)) return;
3821
4513
  if (act.addMenu) {
3822
4514
  const lf = act.addMenu.linkFrom || null;
@@ -3894,11 +4586,27 @@ window.__ModuleLoader__.load({
3894
4586
  if (!dragging) return undefined;
3895
4587
  const move = (ev) => onCanvasMove(ev);
3896
4588
  const up = (ev) => onCanvasUp(ev);
4589
+ const cancelDrag = () => {
4590
+ panDrag.current = null;
4591
+ nodeDrag.current = null;
4592
+ rightClickRef.current = null;
4593
+ cutRef.current = null;
4594
+ cutHits.current = new Set();
4595
+ pendingHandledRef.current = false;
4596
+ setPanning(false);
4597
+ setCutPath([]);
4598
+ setCutVictims([]);
4599
+ setMarquee(null);
4600
+ setPending(null);
4601
+ setDragging(false);
4602
+ };
3897
4603
  window.addEventListener('mousemove', move);
3898
4604
  window.addEventListener('mouseup', up);
4605
+ window.addEventListener('blur', cancelDrag);
3899
4606
  return () => {
3900
4607
  window.removeEventListener('mousemove', move);
3901
4608
  window.removeEventListener('mouseup', up);
4609
+ window.removeEventListener('blur', cancelDrag);
3902
4610
  };
3903
4611
  }, [dragging, marquee, pending]);
3904
4612
 
@@ -3931,10 +4639,9 @@ window.__ModuleLoader__.load({
3931
4639
 
3932
4640
  const onCanvasMove = (e) => {
3933
4641
  if (panDrag.current) {
3934
- const pan = panDrag.current;
3935
- const dx = e.clientX - pan.startX;
3936
- const dy = e.clientY - pan.startY;
3937
- commitView({ k: viewRef.current.k, x: pan.originX + dx, y: pan.originY + dy });
4642
+ const stepped = applyPanStep(viewRef.current, panDrag.current, e.clientX, e.clientY);
4643
+ panDrag.current = stepped.pan;
4644
+ commitView(stepped.view);
3938
4645
  return;
3939
4646
  }
3940
4647
  if (rightClickRef.current && !rightClickRef.current.moved) {
@@ -3953,7 +4660,11 @@ window.__ModuleLoader__.load({
3953
4660
  const drag = nodeDrag.current;
3954
4661
  const dx = p.x - drag.startX;
3955
4662
  const dy = p.y - drag.startY;
3956
- if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) drag.moved = true;
4663
+ // Snapshot once on first actual move (>0.5px) so pure selection clicks do not pollute undo history.
4664
+ if (!drag.moved && (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5)) {
4665
+ pushSnapshot();
4666
+ drag.moved = true;
4667
+ }
3957
4668
  const byId = new Map(drag.origins.map((o) => [o.id, o]));
3958
4669
  setNodes((ns) => ns.map((n) => {
3959
4670
  const origin = byId.get(n.id);
@@ -4105,11 +4816,22 @@ window.__ModuleLoader__.load({
4105
4816
  const savePresetNow = () => {
4106
4817
  const name = presetName.trim();
4107
4818
  if (!name) { flash(t('needName')); return; }
4108
- if (Object.prototype.hasOwnProperty.call(presets, name)) {
4819
+ const latest = loadPresets();
4820
+ if (Object.prototype.hasOwnProperty.call(latest, name)) {
4821
+ setPresets(latest);
4109
4822
  flash('"' + name + '" ' + t('dupName'));
4110
4823
  return;
4111
4824
  }
4112
- const next = { ...presets, [name]: { nodes, edges } };
4825
+ const savedNodes = nodesRef.current.map((n) => ({
4826
+ ...n,
4827
+ ...(Array.isArray(n.refs) ? { refs: n.refs.slice() } : null),
4828
+ ...(Array.isArray(n.branches) ? { branches: n.branches.map((b) => ({ ...b })) } : null),
4829
+ }));
4830
+ const savedEdges = edgesRef.current.map((e) => ({ ...e }));
4831
+ const next = {
4832
+ ...latest,
4833
+ [name]: { nodes: savedNodes, edges: savedEdges, direction: directionRef.current },
4834
+ };
4113
4835
  if (!savePresets(next)) { flash(t('saveFailed')); return; }
4114
4836
  setPresets(next);
4115
4837
  setPresetName('');
@@ -4131,6 +4853,12 @@ window.__ModuleLoader__.load({
4131
4853
  if (typeof doc.enabled === 'boolean') {
4132
4854
  setEnabled(doc.enabled);
4133
4855
  }
4856
+ const hasExplicitDir = !merge && (doc.direction === 'tb' || doc.direction === 'lr');
4857
+ const allHaveCoords = !merge && doc.nodes.every((n) => n && typeof n.x === 'number' && typeof n.y === 'number');
4858
+ if (hasExplicitDir) {
4859
+ directionRef.current = doc.direction;
4860
+ setDirection(doc.direction);
4861
+ }
4134
4862
  const removedNodes = new Set(doc.removeNodes || []);
4135
4863
  const rawIncomingEdges = Array.isArray(doc.edges) ? doc.edges : [];
4136
4864
  setNodes((existing) => {
@@ -4172,10 +4900,19 @@ window.__ModuleLoader__.load({
4172
4900
  addedCount += 1;
4173
4901
  }
4174
4902
  placed.set(n.id, { x, y });
4903
+ if (merge && fromRemote) {
4904
+ // Host merge patches deliver complete canonical node fields; explicitly clear
4905
+ // optional fields that were deleted by `canvas_patch` while keeping visual state.
4906
+ const merged = { ...prev, ...n, x, y };
4907
+ if (!('refs' in n)) delete merged.refs;
4908
+ if (!('branches' in n)) delete merged.branches;
4909
+ if (!('multiMatch' in n)) delete merged.multiMatch;
4910
+ return merged;
4911
+ }
4175
4912
  return { ...prev, ...n, x, y };
4176
4913
  });
4177
4914
  if (!merge) {
4178
- return isTB ? layoutGraph(incoming, rawIncomingEdges, 'tb') : incoming;
4915
+ return (isTB && !(hasExplicitDir && allHaveCoords)) ? layoutGraph(incoming, rawIncomingEdges, 'tb') : incoming;
4179
4916
  }
4180
4917
  const touched = new Set(incoming.map((n) => n.id));
4181
4918
  const kept = existing
@@ -4358,20 +5095,31 @@ window.__ModuleLoader__.load({
4358
5095
  };
4359
5096
 
4360
5097
  const applyPreset = (name) => {
4361
- const preset = presets[name];
5098
+ const latest = loadPresets();
5099
+ const preset = latest[name] || presets[name];
4362
5100
  if (!preset || !Array.isArray(preset.nodes) || !Array.isArray(preset.edges)) { flash(t('invalidPreset')); return; }
5101
+ const clonedNodes = preset.nodes.map((n) => ({
5102
+ ...n,
5103
+ ...(Array.isArray(n.refs) ? { refs: n.refs.slice() } : null),
5104
+ ...(Array.isArray(n.branches) ? { branches: n.branches.map((b) => ({ ...b })) } : null),
5105
+ }));
5106
+ const clonedEdges = preset.edges.map((e) => ({ ...e }));
4363
5107
  pushSnapshot();
5108
+ if (preset.direction === 'tb' || preset.direction === 'lr') {
5109
+ directionRef.current = preset.direction;
5110
+ setDirection(preset.direction);
5111
+ }
4364
5112
  if (enabled) {
4365
5113
  skipDirtyOnce.current = true;
4366
- pushPlan(true, preset.nodes, preset.edges);
5114
+ pushPlan(true, clonedNodes, clonedEdges);
4367
5115
  }
4368
- setNodes(preset.nodes);
4369
- setEdges(preset.edges);
5116
+ setNodes(clonedNodes);
5117
+ setEdges(clonedEdges);
4370
5118
  setSelectedIds([]);
4371
5119
  snapshotStaleCatalog();
4372
5120
  setRunsById({});
4373
5121
  setPresetOpen(null);
4374
- setTimeout(() => fitView(preset.nodes), 0);
5122
+ setTimeout(() => fitView(clonedNodes), 0);
4375
5123
  flash(t('loadedPreset') + ': ' + name);
4376
5124
  };
4377
5125
 
@@ -4395,7 +5143,8 @@ window.__ModuleLoader__.load({
4395
5143
  };
4396
5144
 
4397
5145
  const deletePreset = (name) => {
4398
- const next = { ...presets };
5146
+ const latest = loadPresets();
5147
+ const next = { ...latest };
4399
5148
  delete next[name];
4400
5149
  savePresets(next);
4401
5150
  setPresets(next);
@@ -4428,12 +5177,6 @@ window.__ModuleLoader__.load({
4428
5177
  const ids = ((hit && hit.efforts) || []).map((e) => e.id);
4429
5178
  return ['', ...(ids.length ? ids : REASONING_FALLBACK)];
4430
5179
  };
4431
- const reasoningLabel = (node) => {
4432
- if (!node.reasoning) return t('defaultEffort');
4433
- const hit = modelEntry(node);
4434
- const found = hit && hit.efforts ? hit.efforts.find((e) => e.id === node.reasoning) : undefined;
4435
- return (found && (found.name || found.id)) || node.reasoning;
4436
- };
4437
5180
 
4438
5181
  const scopeToggle = (node) => {
4439
5182
  const wide = (node.preset || 'standard') !== 'minimal';
@@ -4671,50 +5414,31 @@ window.__ModuleLoader__.load({
4671
5414
  const soloLeadIds = soloLeadNodeIds(nodes, edges);
4672
5415
  const deadEndIds = deadEndNodeIds(nodes, edges);
4673
5416
 
4674
- // Lead nodes are never spawned, so their status is derived from graph state:
4675
- // - Intermediate Lead (has downstream): glows "Ready" until any child starts,
4676
- // then settles to "Done".
4677
- // - Terminal Lead (no downstream): Host finishes in one shot, so it glows only
4678
- // while the main conversation is still streaming (`sessionRunning`), then
4679
- // settles to "Done" once the turn ends.
4680
- const leadReadyIds = new Set();
4681
- const leadDoneIds = new Set();
4682
- const hasCondNode = nodes.some((x) => x.kind === 'condition');
4683
- if (enabled) {
4684
- if (runState && runState.waitingLead && runState.waitingLead.id) {
4685
- leadReadyIds.add(runState.waitingLead.id);
4686
- }
4687
- if (runState && Array.isArray(runState.done)) {
4688
- for (const did of runState.done) {
4689
- const dn = nodeById.get(did);
4690
- if (dn && dn.kind === 'lead' && dn.id !== 'lead') leadDoneIds.add(did);
4691
- }
4692
- }
4693
- for (const n of nodes) {
4694
- if (n.kind !== 'lead' || n.id === 'lead' || !reachableIds.has(n.id)) continue;
4695
- if (leadReadyIds.has(n.id) || leadDoneIds.has(n.id)) continue;
4696
- const upIds = edges
4697
- .filter((e) => e.to === n.id && e.from !== 'lead' && nodeById.has(e.from))
4698
- .map((e) => e.from);
4699
- if (!upIds.length) continue;
4700
- const upAgents = upIds.filter((id) => nodeById.get(id).kind !== 'lead');
4701
- if (!upAgents.length) continue;
4702
- const anyUpRunning = upAgents.some((id) => statusById[id] === 'running');
4703
- const allUpDone = hasCondNode
4704
- ? (!anyUpRunning && upAgents.some((id) => statusById[id] === 'done' || statusById[id] === 'failed'))
4705
- : upAgents.every((id) => statusById[id] === 'done' || statusById[id] === 'failed');
4706
- if (!allUpDone) continue;
4707
- const downIds = edges.filter((e) => e.from === n.id).map((e) => e.to);
4708
- if (!downIds.length) {
4709
- if (sessionRunning) leadReadyIds.add(n.id);
4710
- else leadDoneIds.add(n.id);
4711
- } else {
4712
- const anyDownStarted = downIds.some((id) => Boolean(statusById[id]));
4713
- if (!anyDownStarted) leadReadyIds.add(n.id);
4714
- else leadDoneIds.add(n.id);
4715
- }
4716
- }
4717
- }
5417
+ // Lead nodes are never spawned, so their status is derived via `deriveLeadStatuses`,
5418
+ // honoring authoritative backend `runState.status` (`halted` / `done` / `need-lead`).
5419
+ const { leadReadyIds, leadDoneIds } = deriveLeadStatuses({
5420
+ enabled,
5421
+ nodes,
5422
+ edges,
5423
+ statusById,
5424
+ sessionRunning,
5425
+ runState,
5426
+ reachableIds,
5427
+ });
5428
+ const activeWaitingLead = runState
5429
+ ? (runState.waitingLead || null)
5430
+ : (leadReadyIds.size > 0 ? { id: Array.from(leadReadyIds)[0] } : null);
5431
+ const runningNodesCount = enabled
5432
+ ? Object.values(statusById).filter((s) => s === 'running').length
5433
+ : 0;
5434
+ const stopBtn = stopButtonState({
5435
+ sessionRunning,
5436
+ runningNodesCount,
5437
+ waitingLead: activeWaitingLead,
5438
+ triggering: runTriggering,
5439
+ stopping,
5440
+ lang,
5441
+ });
4718
5442
 
4719
5443
  const decisionsById = (enabled && runState && runState.decisions && typeof runState.decisions === 'object')
4720
5444
  ? runState.decisions
@@ -4727,6 +5451,51 @@ window.__ModuleLoader__.load({
4727
5451
  const nodeAttemptsMap = (enabled && runState && runState.nodeAttempts && typeof runState.nodeAttempts === 'object')
4728
5452
  ? runState.nodeAttempts
4729
5453
  : {};
5454
+ // Client-side fallback wall-clock tracking in case an older backend `.run.json` omits `summary.startedAt`.
5455
+ // Never synthesize startedAt from `runState.at` (which is the write/finish timestamp of `.run.json`).
5456
+ (() => {
5457
+ const curSt = runState && typeof runState.status === 'string' ? runState.status : '';
5458
+ const curAt = runState && typeof runState.at === 'number' ? runState.at : null;
5459
+ const tr = clientRunTimingRef.current;
5460
+ if (!curSt || curSt === 'idle') {
5461
+ tr.startedAt = null;
5462
+ tr.endedAt = null;
5463
+ tr.runAt = null;
5464
+ tr.prevStatus = curSt;
5465
+ } else if (curSt === 'running' && tr.prevStatus !== 'running' && tr.prevStatus !== 'need-lead') {
5466
+ tr.startedAt = (runState && runState.summary && typeof runState.summary.startedAt === 'number')
5467
+ ? runState.summary.startedAt
5468
+ : Date.now();
5469
+ tr.endedAt = null;
5470
+ tr.runAt = curAt;
5471
+ tr.prevStatus = curSt;
5472
+ } else if (curSt === 'done' || curSt === 'halted') {
5473
+ if (tr.prevStatus === 'running' || tr.prevStatus === 'need-lead') {
5474
+ if (tr.startedAt !== null) {
5475
+ tr.endedAt = (runState && runState.summary && typeof runState.summary.endedAt === 'number')
5476
+ ? runState.summary.endedAt
5477
+ : Date.now();
5478
+ tr.runAt = curAt;
5479
+ }
5480
+ } else if (curAt !== null && tr.runAt !== null && curAt !== tr.runAt) {
5481
+ // A fresh terminal `.run.json` arrived without observing a `running` poll in between:
5482
+ // drop any prior run's client clock rather than mixing two different runs.
5483
+ tr.startedAt = null;
5484
+ tr.endedAt = null;
5485
+ tr.runAt = curAt;
5486
+ }
5487
+ tr.prevStatus = curSt;
5488
+ } else {
5489
+ tr.prevStatus = curSt;
5490
+ }
5491
+ })();
5492
+ const runSummary = buildRunSummaryView({
5493
+ runState,
5494
+ nodes,
5495
+ runsById,
5496
+ now: summaryNow,
5497
+ fallbackTiming: clientRunTimingRef.current,
5498
+ });
4730
5499
  const loopGroups = loopGroupsForUI(nodes, edges);
4731
5500
  const edgeKeyForState = (e) => String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
4732
5501
  const loopPillItems = [];
@@ -5146,6 +5915,39 @@ window.__ModuleLoader__.load({
5146
5915
  h('button', { style: S.btn, onClick: () => addNode('lead'), type: 'button' }, t('addLead')),
5147
5916
  h('button', { style: S.btn, onClick: () => addNode('condition'), type: 'button' }, t('addCond')),
5148
5917
  h('span', { style: S.toolSep }),
5918
+ (() => {
5919
+ const canUndo = historyRef.current.length > 0;
5920
+ const canRedo = redoRef.current.length > 0;
5921
+ const undoHint = shortcuts.undo ? (' (' + shortcuts.undo + ')') : '';
5922
+ const redoHint = shortcuts.redo ? (' (' + shortcuts.redo + ')') : '';
5923
+ return h(React.Fragment, null,
5924
+ h('button', {
5925
+ style: {
5926
+ ...S.btn,
5927
+ padding: '4px 6px',
5928
+ opacity: canUndo ? 1 : 0.42,
5929
+ cursor: canUndo ? 'pointer' : 'default',
5930
+ },
5931
+ disabled: !canUndo,
5932
+ onClick: undo,
5933
+ type: 'button',
5934
+ title: t('tipUndo') + undoHint,
5935
+ }, '↶'),
5936
+ h('button', {
5937
+ style: {
5938
+ ...S.btn,
5939
+ padding: '4px 6px',
5940
+ opacity: canRedo ? 1 : 0.42,
5941
+ cursor: canRedo ? 'pointer' : 'default',
5942
+ },
5943
+ disabled: !canRedo,
5944
+ onClick: redo,
5945
+ type: 'button',
5946
+ title: t('tipRedo') + redoHint,
5947
+ }, '↷'),
5948
+ );
5949
+ })(),
5950
+ h('span', { style: S.toolSep }),
5149
5951
  h('button', {
5150
5952
  style: enabled && dirty ? S.btnDirty : S.btn,
5151
5953
  onClick: () => pushPlan(enabled),
@@ -5171,8 +5973,11 @@ window.__ModuleLoader__.load({
5171
5973
  onClick: (e) => {
5172
5974
  const next = presetOpen === 'menu' ? null : 'menu';
5173
5975
  if (next) {
5976
+ refreshPresets(false);
5174
5977
  setMenuOpen(false);
5175
5978
  setCtxMenu(null);
5979
+ setLoopEditEdgeId(null);
5980
+ setOpenModelFor(null);
5176
5981
  const rootRect = rootElRef.current && rootElRef.current.getBoundingClientRect();
5177
5982
  const btnRect = e.currentTarget && e.currentTarget.getBoundingClientRect();
5178
5983
  setPresetAlign(dropdownAlign(btnRect, rootRect, 248));
@@ -5219,17 +6024,45 @@ window.__ModuleLoader__.load({
5219
6024
  onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
5220
6025
  onClick: () => clearCanvas(),
5221
6026
  }, h('span', { style: S.presetRowText }, t('newBlankCanvas'))),
5222
- h('div', { style: S.menuHead }, t('myPresets')),
5223
- names.length
5224
- ? names.map((name) => h('div', {
5225
- key: name,
5226
- style: S.presetRow,
5227
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
5228
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
6027
+ h('div', {
6028
+ style: { ...S.menuHead, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '6px' },
6029
+ },
6030
+ h('span', null, t('myPresets')),
6031
+ h('button', {
6032
+ type: 'button',
6033
+ title: t('refreshPresetsTip'),
6034
+ style: {
6035
+ padding: '0 4px', borderRadius: '4px', border: '1px solid ' + C.border,
6036
+ background: 'transparent', color: C.dim, fontSize: '10px', lineHeight: '14px',
6037
+ cursor: 'pointer', flex: '0 0 auto',
5229
6038
  },
5230
- h('span', { style: S.presetRowText, onClick: () => applyPreset(name) }, name),
5231
- h('button', { style: S.presetDel, type: 'button', title: t('del'), onClick: () => deletePreset(name) }, '×'),
5232
- ))
6039
+ onMouseEnter: (e) => { e.currentTarget.style.color = C.text; e.currentTarget.style.borderColor = C.accent; },
6040
+ onMouseLeave: (e) => { e.currentTarget.style.color = C.dim; e.currentTarget.style.borderColor = C.border; },
6041
+ onClick: (e) => { e.stopPropagation(); refreshPresets(true); },
6042
+ }, '↻'),
6043
+ ),
6044
+ names.length
6045
+ ? names.map((name) => {
6046
+ const pItem = presets[name];
6047
+ const pDir = pItem && (pItem.direction === 'tb' || pItem.direction === 'lr') ? pItem.direction : '';
6048
+ return h('div', {
6049
+ key: name,
6050
+ style: S.presetRow,
6051
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
6052
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
6053
+ },
6054
+ h('span', { style: S.presetRowText, onClick: () => applyPreset(name) }, name),
6055
+ pDir && h('span', {
6056
+ style: {
6057
+ flex: '0 0 auto', fontSize: '9px', lineHeight: '13px',
6058
+ padding: '0 4px', borderRadius: '3px',
6059
+ border: '1px solid ' + C.border, color: C.dim,
6060
+ },
6061
+ title: pDir === 'tb' ? t('dirTB') : t('dirLR'),
6062
+ }, pDir === 'tb' ? t('presetDirTB') : t('presetDirLR')),
6063
+ h('button', { style: S.presetDel, type: 'button', title: t('del'), onClick: () => deletePreset(name) }, '×'),
6064
+ );
6065
+ })
5233
6066
  : h('div', { style: S.presetEmpty }, t('presetEmpty')),
5234
6067
  h('div', { style: S.menuHead }, t('builtinTemplates')),
5235
6068
  templates.map((tpl) => h('div', {
@@ -5252,6 +6085,8 @@ window.__ModuleLoader__.load({
5252
6085
  if (next) {
5253
6086
  setPresetOpen(null);
5254
6087
  setCtxMenu(null);
6088
+ setLoopEditEdgeId(null);
6089
+ setOpenModelFor(null);
5255
6090
  const rootRect = rootElRef.current && rootElRef.current.getBoundingClientRect();
5256
6091
  const btnRect = e.currentTarget && e.currentTarget.getBoundingClientRect();
5257
6092
  setMenuAlign(dropdownAlign(btnRect, rootRect, 204));
@@ -5367,6 +6202,12 @@ window.__ModuleLoader__.load({
5367
6202
  onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
5368
6203
  onClick: () => { toggleLang(); },
5369
6204
  }, t('ctxLangToggle') + t('sep') + (lang === 'zh' ? '中文' : 'EN')),
6205
+ h('div', {
6206
+ style: S.moreRow,
6207
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
6208
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
6209
+ onClick: () => { setMenuOpen(false); setSummaryNow(Date.now()); setSummaryOpen(true); },
6210
+ }, t('runSummaryMenu')),
5370
6211
  h('div', {
5371
6212
  style: S.moreRow,
5372
6213
  onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
@@ -5395,6 +6236,165 @@ window.__ModuleLoader__.load({
5395
6236
  h('div', { style: S.helpBody }, t('helpBody').split('\n').map((line, i) => h('div', { key: i, style: S.helpLine }, line))),
5396
6237
  ),
5397
6238
  ),
6239
+ summaryOpen && (() => {
6240
+ const stVisual = (st) => {
6241
+ if (st === 'done') return { icon: '✓', color: '#3fb950', label: t('runStDone') };
6242
+ if (st === 'reused') return { icon: '⚡', color: '#3fb950', label: t('runSummaryReused') };
6243
+ if (st === 'running') return { icon: '●', color: '#2f81f7', label: t('runStRunning') };
6244
+ if (st === 'waiting' || st === 'need-lead') return { icon: '⏸', color: '#2f81f7', label: t('runStWaiting') };
6245
+ if (st === 'halted') return { icon: '⏹', color: '#e5534b', label: t('runStHalted') };
6246
+ if (st === 'failed') return { icon: '✕', color: '#e5534b', label: t('runStFailed') };
6247
+ if (st === 'empty') return { icon: '⚠', color: '#d29922', label: t('runStEmpty') };
6248
+ if (st === 'pruned') return { icon: '↷', color: C.dim, label: t('runStPruned') };
6249
+ return { icon: '○', color: C.dim, label: t('runStPending') };
6250
+ };
6251
+ const topSt = runSummary.hasData ? stVisual(runSummary.status) : null;
6252
+ return h('div', {
6253
+ style: S.helpOverlay,
6254
+ onMouseDown: (e) => { e.stopPropagation(); if (e.target === e.currentTarget) setSummaryOpen(false); },
6255
+ },
6256
+ h('div', { style: { ...S.helpCard, maxWidth: '460px', display: 'flex', flexDirection: 'column', maxHeight: '82%', overflow: 'hidden' } },
6257
+ h('div', { style: { ...S.helpHead, flex: '0 0 auto' } },
6258
+ h('span', { style: { ...S.helpTitle, display: 'inline-flex', alignItems: 'center', gap: '6px', minWidth: 0 } },
6259
+ h('span', null, t('runSummaryTitle')),
6260
+ topSt && h('span', {
6261
+ style: {
6262
+ fontSize: '10px', fontWeight: 600, padding: '1px 6px', borderRadius: '999px',
6263
+ color: topSt.color, border: '1px solid ' + topSt.color,
6264
+ whiteSpace: 'nowrap',
6265
+ },
6266
+ }, topSt.icon + ' ' + topSt.label),
6267
+ ),
6268
+ runSummary.hasData && h('button', {
6269
+ style: S.btn,
6270
+ type: 'button',
6271
+ onClick: () => copyRunSummary(runSummary),
6272
+ }, t('runSummaryCopy')),
6273
+ h('button', {
6274
+ style: S.btn,
6275
+ type: 'button',
6276
+ onClick: () => setSummaryOpen(false),
6277
+ }, t('close')),
6278
+ ),
6279
+ !runSummary.hasData
6280
+ ? h('div', { style: { padding: '18px 8px', textAlign: 'center', color: C.dim, fontSize: '12px' } }, t('runSummaryEmpty'))
6281
+ : h(React.Fragment, null,
6282
+ h('div', { style: S.summaryKpiRow },
6283
+ h('div', { style: S.summaryKpi },
6284
+ h('span', { style: { fontSize: '10px', color: C.dim } }, t('runSummaryElapsed')),
6285
+ h('span', { style: { fontSize: '13px', fontWeight: 600, color: C.text, fontVariantNumeric: 'tabular-nums' } }, formatDurationMs(runSummary.elapsedMs)),
6286
+ ),
6287
+ h('div', { style: S.summaryKpi },
6288
+ h('span', { style: { fontSize: '10px', color: C.dim } }, t('runSummaryDone')),
6289
+ h('span', { style: { fontSize: '13px', fontWeight: 600, color: runSummary.failedCount ? '#e5534b' : '#3fb950', fontVariantNumeric: 'tabular-nums' } },
6290
+ runSummary.doneCount + '/' + runSummary.totalCount),
6291
+ ),
6292
+ h('div', { style: S.summaryKpi },
6293
+ h('span', { style: { fontSize: '10px', color: C.dim } }, t('runSummaryLoops')),
6294
+ h('span', { style: { fontSize: '13px', fontWeight: 600, color: runSummary.totalLoops ? '#d29922' : C.text, fontVariantNumeric: 'tabular-nums' } }, String(runSummary.totalLoops)),
6295
+ ),
6296
+ h('div', { style: S.summaryKpi },
6297
+ h('span', { style: { fontSize: '10px', color: C.dim } }, t('runSummaryParallel')),
6298
+ h('span', { style: { fontSize: '13px', fontWeight: 600, color: C.text, fontVariantNumeric: 'tabular-nums' } }, '×' + (runSummary.maxParallel || maxParallel)),
6299
+ ),
6300
+ ),
6301
+ h('div', { style: { flex: '1 1 auto', minHeight: 0, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '8px', paddingRight: '2px' } },
6302
+ runSummary.haltedReason && h('div', {
6303
+ style: {
6304
+ flex: '0 0 auto', padding: '6px 8px', borderRadius: '6px', fontSize: '11px', lineHeight: '1.45',
6305
+ color: '#e5534b', background: 'rgba(229,83,75,0.12)', border: '1px solid rgba(229,83,75,0.4)',
6306
+ },
6307
+ }, '⏹ ' + runSummary.haltedReason),
6308
+ runSummary.status === 'need-lead' && runSummary.waitingLead && h('div', {
6309
+ style: {
6310
+ flex: '0 0 auto', padding: '6px 8px', borderRadius: '6px', fontSize: '11px', lineHeight: '1.45',
6311
+ color: '#2f81f7', background: 'rgba(47,129,247,0.12)', border: '1px solid rgba(47,129,247,0.4)',
6312
+ },
6313
+ }, '⏸ ' + t('runStWaiting') + ': ' + (runSummary.waitingLead.label || runSummary.waitingLead.id)),
6314
+ h('div', { style: { flex: '0 0 auto', fontSize: '11px', fontWeight: 600, color: C.dim } }, t('runSummaryNodesHead')),
6315
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: '5px' } },
6316
+ runSummary.nodes.map((n) => {
6317
+ const sv = stVisual(n.status);
6318
+ const barPct = (typeof n.durationMs === 'number' && n.durationMs > 0 && runSummary.maxNodeMs > 0)
6319
+ ? Math.max(4, Math.min(100, Math.round((n.durationMs / runSummary.maxNodeMs) * 100)))
6320
+ : 0;
6321
+ const kindMeta = n.kind === 'condition'
6322
+ ? { label: lang === 'en' ? 'Cond' : '条件', color: '#d29922', border: 'rgba(210,153,34,0.45)' }
6323
+ : n.kind === 'lead'
6324
+ ? { label: 'Lead', color: '#2f81f7', border: 'rgba(47,129,247,0.45)' }
6325
+ : { label: lang === 'en' ? 'Agent' : '子代理', color: '#3fb950', border: 'rgba(63,185,80,0.45)' };
6326
+ return h('div', { key: n.id, style: S.summaryRow },
6327
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0 } },
6328
+ h('span', { style: { color: sv.color, fontSize: '11px', fontWeight: 700, flex: '0 0 auto' }, title: sv.label }, sv.icon),
6329
+ h('button', {
6330
+ type: 'button',
6331
+ disabled: !n.onCanvas,
6332
+ title: n.onCanvas ? t('runSummaryFocusTip') : undefined,
6333
+ style: {
6334
+ flex: '1 1 auto', minWidth: 0, textAlign: 'left', padding: 0,
6335
+ border: 'none', background: 'transparent', color: C.text,
6336
+ fontSize: '11px', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
6337
+ cursor: n.onCanvas ? 'pointer' : 'default',
6338
+ },
6339
+ onClick: () => { if (n.onCanvas) { focusNode(n.id); setSummaryOpen(false); } },
6340
+ }, n.label),
6341
+ h('span', { style: { ...S.summaryChip, color: kindMeta.color, borderColor: kindMeta.border, flex: '0 0 auto' } }, kindMeta.label),
6342
+ h('span', { style: { fontSize: '11px', color: C.dim, fontVariantNumeric: 'tabular-nums', flex: '0 0 auto' } }, formatDurationMs(n.durationMs)),
6343
+ n.childId && h('button', {
6344
+ type: 'button',
6345
+ title: t('runSummaryOpenChatTip'),
6346
+ style: { ...S.condAddBtn, padding: '0 5px', height: '18px', flex: '0 0 auto' },
6347
+ onClick: () => {
6348
+ setSummaryOpen(false);
6349
+ const targetNode = nodeById.get(n.id) || { id: n.id, label: n.label };
6350
+ openNodeSession(targetNode, n.childId);
6351
+ },
6352
+ }, '↗'),
6353
+ ),
6354
+ barPct > 0 && h('div', { style: S.summaryBarTrack },
6355
+ h('div', { style: { ...S.summaryBarFill, width: barPct + '%', background: sv.color } }),
6356
+ ),
6357
+ (n.model || n.fallbackUsed || n.sessionContinued || n.runs > 1 || n.status === 'reused' || n.reason) && h('div', {
6358
+ style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '4px' },
6359
+ },
6360
+ n.model && h('span', { style: S.summaryChip }, n.model),
6361
+ n.runs > 1 && h('span', { style: { ...S.summaryChip, color: '#d29922' } }, t('runSummaryRuns').replace('{n}', String(n.runs))),
6362
+ n.fallbackUsed && h('span', { style: { ...S.summaryChip, color: '#d29922' } }, t('runSummaryFallback')),
6363
+ n.sessionContinued && h('span', { style: { ...S.summaryChip, color: '#a371f7' } }, t('runSummaryContinued')),
6364
+ n.status === 'reused' && h('span', { style: { ...S.summaryChip, color: '#3fb950' } }, t('runSummaryReused')),
6365
+ n.reason && h('span', {
6366
+ style: {
6367
+ fontSize: '10px', lineHeight: '1.35',
6368
+ color: n.status === 'failed' ? '#e5534b' : C.dim,
6369
+ wordBreak: 'break-word',
6370
+ },
6371
+ }, n.reason),
6372
+ ),
6373
+ );
6374
+ }),
6375
+ ),
6376
+ runSummary.loops.length > 0 && h(React.Fragment, null,
6377
+ h('div', { style: { flex: '0 0 auto', fontSize: '11px', fontWeight: 600, color: C.dim, marginTop: '2px' } }, t('runSummaryLoopsHead')),
6378
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: '5px', flex: '0 0 auto' } },
6379
+ runSummary.loops.map((lp, idx) => h('div', { key: idx, style: S.summaryRow },
6380
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '6px' } },
6381
+ h('span', { style: { fontSize: '11px', fontWeight: 600, color: '#d29922', flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
6382
+ lp.fromLabel + ' ↺ ' + lp.toLabel),
6383
+ h('span', { style: { ...S.summaryChip, color: lp.exhausted ? '#e5534b' : '#d29922' } },
6384
+ lp.used + '/' + lp.max + (lp.exhausted ? ' · ' + t('runSummaryExhausted') : '')),
6385
+ ),
6386
+ (lp.rounds || []).map((r, rIdx) => h('div', {
6387
+ key: rIdx,
6388
+ style: { fontSize: '10px', color: C.dim, lineHeight: '1.4', paddingLeft: '6px', borderLeft: '2px solid ' + C.border },
6389
+ }, 'R' + r.round + ': ' + r.reason)),
6390
+ )),
6391
+ ),
6392
+ ),
6393
+ ),
6394
+ ),
6395
+ ),
6396
+ );
6397
+ })(),
5398
6398
  shortcutsOpen && (() => {
5399
6399
  const actionLabels = {
5400
6400
  addNode: t('scAddNode'),
@@ -5483,31 +6483,53 @@ window.__ModuleLoader__.load({
5483
6483
  if (tag !== 'INPUT' && tag !== 'TEXTAREA') e.preventDefault();
5484
6484
  },
5485
6485
  },
5486
- h('button', {
5487
- style: enabled
5488
- ? {
5489
- ...S.floatOn,
5490
- display: 'inline-flex',
5491
- alignItems: 'center',
5492
- gap: '6px',
5493
- lineHeight: '14px',
5494
- boxShadow: fxLevel === 'vivid'
5495
- ? '0 0 14px rgba(47,129,247,0.35), 0 4px 14px rgba(0,0,0,0.35)'
5496
- : S.floatOn.boxShadow,
5497
- }
5498
- : { ...S.floatOff, display: 'inline-flex', alignItems: 'center', gap: '6px', lineHeight: '14px' },
5499
- type: 'button',
5500
- onMouseDown: (e) => e.stopPropagation(),
5501
- onClick: toggleEnabled,
5502
- title: t('tipToggle'),
5503
- },
5504
- h('span', {
5505
- className: enabled && fxLevel === 'vivid' ? 'dsh-wc-dot-live' : undefined,
6486
+ h('div', { style: S.floatTopLeft, onMouseDown: (e) => e.stopPropagation() },
6487
+ h('button', {
5506
6488
  style: enabled
5507
- ? { width: '7px', height: '7px', borderRadius: '50%', background: C.accent, flex: '0 0 auto' }
5508
- : { width: '7px', height: '7px', borderRadius: '50%', border: '1.5px solid ' + C.dim, boxSizing: 'border-box', flex: '0 0 auto' },
5509
- }),
5510
- h('span', null, (enabled ? t('enabled') : t('disabled')).replace(/^[●○]\s*/, '')),
6489
+ ? {
6490
+ ...S.floatOn,
6491
+ display: 'inline-flex',
6492
+ alignItems: 'center',
6493
+ gap: '6px',
6494
+ lineHeight: '14px',
6495
+ boxShadow: fxLevel === 'vivid'
6496
+ ? '0 0 14px rgba(47,129,247,0.35), 0 4px 14px rgba(0,0,0,0.35)'
6497
+ : S.floatOn.boxShadow,
6498
+ }
6499
+ : { ...S.floatOff, display: 'inline-flex', alignItems: 'center', gap: '6px', lineHeight: '14px' },
6500
+ type: 'button',
6501
+ onClick: toggleEnabled,
6502
+ title: t('tipToggle'),
6503
+ },
6504
+ h('span', {
6505
+ className: enabled && fxLevel === 'vivid' ? 'dsh-wc-dot-live' : undefined,
6506
+ style: enabled
6507
+ ? { width: '7px', height: '7px', borderRadius: '50%', background: C.accent, flex: '0 0 auto' }
6508
+ : { width: '7px', height: '7px', borderRadius: '50%', border: '1.5px solid ' + C.dim, boxSizing: 'border-box', flex: '0 0 auto' },
6509
+ }),
6510
+ h('span', null, (enabled ? t('enabled') : t('disabled')).replace(/^[●○]\s*/, '')),
6511
+ ),
6512
+ stopBtn.visible && h('button', {
6513
+ type: 'button',
6514
+ disabled: stopBtn.disabled,
6515
+ style: stopBtn.active
6516
+ ? {
6517
+ ...S.floatStop,
6518
+ opacity: stopBtn.disabled ? 0.6 : 1,
6519
+ cursor: stopBtn.disabled ? 'not-allowed' : 'pointer',
6520
+ }
6521
+ : {
6522
+ ...S.floatStop,
6523
+ border: '1px solid ' + C.border,
6524
+ color: C.dim,
6525
+ opacity: 0.55,
6526
+ cursor: 'not-allowed',
6527
+ },
6528
+ title: stopBtn.title,
6529
+ onMouseEnter: (e) => { if (stopBtn.active && !stopBtn.disabled) e.currentTarget.style.background = 'rgba(229,83,75,0.18)'; },
6530
+ onMouseLeave: (e) => { e.currentTarget.style.background = C.elevated; },
6531
+ onClick: () => { if (stopBtn.active && !stopBtn.disabled) stopWorkflow(); },
6532
+ }, stopBtn.label),
5511
6533
  ),
5512
6534
  addMenu && (() => {
5513
6535
  const lf = addMenu.linkFrom || null;
@@ -5637,6 +6659,42 @@ window.__ModuleLoader__.load({
5637
6659
  menuRow('clr', t('clearCanvasBtn'), () => { setCtxMenu(null); clearCanvas(); }, { danger: true }),
5638
6660
  );
5639
6661
  })(),
6662
+ runSummary.hasData && (() => {
6663
+ const pillIcon = runSummary.status === 'done' ? '✓'
6664
+ : runSummary.status === 'running' ? '●'
6665
+ : runSummary.status === 'need-lead' ? '⏸'
6666
+ : '⏹';
6667
+ const pillColor = runSummary.status === 'done'
6668
+ ? (runSummary.failedCount ? '#d29922' : '#3fb950')
6669
+ : runSummary.status === 'running' || runSummary.status === 'need-lead'
6670
+ ? '#2f81f7'
6671
+ : '#e5534b';
6672
+ const elapsedText = runSummary.elapsedMs !== null ? ' · ' + formatDurationMs(runSummary.elapsedMs) : '';
6673
+ const loopText = runSummary.totalLoops > 0 ? ' · ↺' + runSummary.totalLoops : '';
6674
+ return h('button', {
6675
+ type: 'button',
6676
+ style: { ...S.floatSummaryBtn, borderColor: runSummary.isLive ? pillColor : C.border },
6677
+ title: t('runSummaryTip'),
6678
+ onMouseDown: (e) => e.stopPropagation(),
6679
+ onMouseEnter: (e) => { e.currentTarget.style.borderColor = pillColor; },
6680
+ onMouseLeave: (e) => { e.currentTarget.style.borderColor = runSummary.isLive ? pillColor : C.border; },
6681
+ onClick: () => {
6682
+ setMenuOpen(false);
6683
+ setPresetOpen(null);
6684
+ setCtxMenu(null);
6685
+ setAddMenu(null);
6686
+ setLoopEditEdgeId(null);
6687
+ setOpenModelFor(null);
6688
+ setSummaryNow(Date.now());
6689
+ setSummaryOpen(true);
6690
+ },
6691
+ },
6692
+ h('span', { style: { color: pillColor, flex: '0 0 auto' } }, pillIcon),
6693
+ h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 } },
6694
+ t('runSummaryBtn') + ' · ' + runSummary.doneCount + '/' + runSummary.totalCount + loopText),
6695
+ elapsedText && h('span', { style: { flex: '0 0 auto', color: C.dim, fontVariantNumeric: 'tabular-nums' } }, elapsedText),
6696
+ );
6697
+ })(),
5640
6698
  h('div', {
5641
6699
  style: S.floatZoomBar,
5642
6700
  onMouseDown: (e) => e.stopPropagation(),
@@ -5801,17 +6859,6 @@ window.__ModuleLoader__.load({
5801
6859
  const isEntry = node.id === 'lead';
5802
6860
  const isLeadKind = node.kind === 'lead';
5803
6861
  const isCondKind = node.kind === 'condition';
5804
- const roleInput = (style) => h('div', { style },
5805
- h('span', { style: S.fieldLabel }, t('role')),
5806
- h('input', {
5807
- style: S.input,
5808
- value: node.role || '',
5809
- placeholder: isLeadKind ? t('rolePhLead') : t('rolePhAgent'),
5810
- onMouseDown: (e) => e.stopPropagation(),
5811
- onFocus: () => setSelectedIds([node.id]),
5812
- onChange: (e) => updateNode(node.id, { role: e.target.value }),
5813
- }),
5814
- );
5815
6862
  const isOrphan = node.id !== 'lead' && !reachableIds.has(node.id);
5816
6863
  const isSoloLead = soloLeadIds.has(node.id);
5817
6864
  const isDeadEnd = deadEndIds.has(node.id);
@@ -5849,9 +6896,15 @@ window.__ModuleLoader__.load({
5849
6896
  const nodeAttempt = nodeAttemptsMap[node.id] || null;
5850
6897
  const condDecision = isCondKind ? (decisionsById[node.id] || null) : null;
5851
6898
  const verdictInfo = condDecision ? conditionVerdictSummary(condDecision, lang) : null;
6899
+ // Lift the whole card to zIndex 40 while any popover or dropdown is open so
6900
+ // later-DOM cards below (especially in vertical layout) and loop pills never paint over it.
5852
6901
  const hasOpenPopover = decisionViewFor === node.id
5853
6902
  || refsEditFor === node.id
5854
6903
  || roleEditFor === node.id
6904
+ || openModelFor === node.id
6905
+ || openModelFor === ('r:' + node.id)
6906
+ || openModelFor === ('f:' + node.id)
6907
+ || openModelFor === ('m:' + node.id)
5855
6908
  || (typeof roleEditFor === 'string' && roleEditFor.includes(':' + node.id + ':'));
5856
6909
  return h('div', {
5857
6910
  key: node.id,
@@ -5892,14 +6945,11 @@ window.__ModuleLoader__.load({
5892
6945
  h('div', { style: S.bandDivider }),
5893
6946
  isEntry
5894
6947
  ? (() => {
5895
- const waitingLead = runState
5896
- ? (runState.waitingLead || null)
5897
- : (leadReadyIds.size > 0 ? { id: Array.from(leadReadyIds)[0] } : null);
5898
6948
  const btn = entryRunButtonState({
5899
6949
  enabled,
5900
6950
  task: node.task || '',
5901
6951
  sessionRunning,
5902
- waitingLead,
6952
+ waitingLead: activeWaitingLead,
5903
6953
  triggering: runTriggering,
5904
6954
  lang,
5905
6955
  });
@@ -5913,35 +6963,67 @@ window.__ModuleLoader__.load({
5913
6963
  const borderColor = isReady
5914
6964
  ? 'rgba(63,185,80,0.6)'
5915
6965
  : (isRun ? 'rgba(47,129,247,0.6)' : (isWait ? 'rgba(210,153,34,0.6)' : C.border));
5916
- return h('button', {
5917
- type: 'button',
5918
- disabled: btn.disabled,
6966
+ const bottomOffset = direction === 'tb' ? '28px' : '4px';
6967
+ return h('div', {
5919
6968
  style: {
5920
- ...S.statusBtn,
5921
- bottom: direction === 'tb' ? '28px' : '4px',
5922
- color,
5923
- background: bg,
5924
- borderColor,
5925
- opacity: btn.state === 'disabled' ? 0.55 : 1,
5926
- cursor: btn.disabled ? 'not-allowed' : 'pointer',
5927
- fontWeight: isReady ? 600 : 500,
6969
+ position: 'absolute',
6970
+ left: '10px',
6971
+ bottom: bottomOffset,
6972
+ zIndex: 7,
6973
+ display: 'inline-flex',
6974
+ alignItems: 'center',
6975
+ gap: '4px',
5928
6976
  },
5929
- title: btn.title,
5930
6977
  onMouseDown: (e) => e.stopPropagation(),
5931
- onMouseEnter: (e) => { if (!btn.disabled) e.currentTarget.style.background = 'rgba(63,185,80,0.24)'; },
5932
- onMouseLeave: (e) => { e.currentTarget.style.background = bg; },
5933
- onClick: (e) => { e.stopPropagation(); if (!btn.disabled) runFromEntry(); },
5934
6978
  },
5935
- isRun && h('span', {
5936
- className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
5937
- style: { width: '6px', height: '6px', borderRadius: '50%', background: color, flex: '0 0 auto' },
5938
- }),
5939
- btn.label,
6979
+ h('button', {
6980
+ type: 'button',
6981
+ disabled: btn.disabled,
6982
+ style: {
6983
+ ...S.statusBtn,
6984
+ position: 'static',
6985
+ color,
6986
+ background: bg,
6987
+ borderColor,
6988
+ opacity: btn.state === 'disabled' ? 0.55 : 1,
6989
+ cursor: btn.disabled ? 'not-allowed' : 'pointer',
6990
+ fontWeight: isReady ? 600 : 500,
6991
+ },
6992
+ title: btn.title,
6993
+ onMouseEnter: (e) => { if (!btn.disabled) e.currentTarget.style.background = 'rgba(63,185,80,0.24)'; },
6994
+ onMouseLeave: (e) => { e.currentTarget.style.background = bg; },
6995
+ onClick: (e) => { e.stopPropagation(); if (!btn.disabled) runFromEntry(); },
6996
+ },
6997
+ isRun && h('span', {
6998
+ className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
6999
+ style: { width: '6px', height: '6px', borderRadius: '50%', background: color, flex: '0 0 auto' },
7000
+ }),
7001
+ btn.label,
7002
+ ),
7003
+ stopBtn.active && h('button', {
7004
+ type: 'button',
7005
+ disabled: stopBtn.disabled,
7006
+ style: {
7007
+ ...S.statusBtn,
7008
+ position: 'static',
7009
+ padding: '1px 5px',
7010
+ color: '#e5534b',
7011
+ background: 'rgba(229,83,75,0.14)',
7012
+ borderColor: 'rgba(229,83,75,0.65)',
7013
+ opacity: stopBtn.disabled ? 0.6 : 1,
7014
+ cursor: stopBtn.disabled ? 'not-allowed' : 'pointer',
7015
+ fontWeight: 600,
7016
+ },
7017
+ title: stopBtn.title,
7018
+ onMouseEnter: (e) => { if (!stopBtn.disabled) e.currentTarget.style.background = 'rgba(229,83,75,0.24)'; },
7019
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'rgba(229,83,75,0.14)'; },
7020
+ onClick: (e) => { e.stopPropagation(); if (!stopBtn.disabled) stopWorkflow(); },
7021
+ }, stopBtn.disabled ? '…' : '⏹'),
5940
7022
  );
5941
7023
  })()
5942
7024
  : isDeadEnd
5943
7025
  ? h('div', {
5944
- style: S.warnChip,
7026
+ style: { ...S.warnChip, bottom: (direction === 'tb' && !isCondKind) ? '28px' : '5px' },
5945
7027
  title: t('tipDeadEnd'),
5946
7028
  onMouseDown: (e) => e.stopPropagation(),
5947
7029
  }, '⚠ ', t('stDeadEnd'))
@@ -6286,13 +7368,14 @@ window.__ModuleLoader__.load({
6286
7368
  scope.effect(() => scope.slots.inject('sidebar.right.pane.tab', () => scope.slots.register({
6287
7369
  name: 'sidebar.right.pane.tab',
6288
7370
  key: TAB_ID,
6289
- }, (props) => h(CanvasBoundary, null, h(WorkflowCanvas, props)))), 'workflow-canvas: tab body');
7371
+ // Key by sessionId so keepMounted reuse across session switches can never overwrite another session's storage.
7372
+ }, (props) => h(CanvasBoundary, null, h(WorkflowCanvas, { ...props, key: (props && props.sessionId) || '__global__' })))), 'workflow-canvas: tab body');
6290
7373
  });
6291
7374
  } catch (error) {
6292
7375
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
6293
7376
  }
6294
7377
  },
6295
- __test: { topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, distanceToEdge, edgeCurve, compatibleTargetsForWire, conditionVerdictSummary, entryRunButtonState, outputSocketX, inputSocketPos, outputSocketPos, normalizeRefsUI, clampMenuPos, cloneSelection, nextSelectionOnNodeClick, DEFAULT_SHORTCUTS, normalizeShortcut, formatShortcutFromEvent, matchesShortcut, applyShortcutBinding, normalizeMaxIterationsUI, loopMemberIdsUI, loopGroupsForUI, pruneInvalidLoopEdges, canLinkAsLoop, analyzeLoopSelection, loopEdgeArc },
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 },
6296
7379
  };
6297
7380
  },
6298
7381
  });