dsh-workflow-canvas 1.5.0 → 1.5.5

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
200
  '13. 按住鼠标中键(或空格 + 左键)拖动画布平移;点击子代理节点左下角状态可直达它的对话记录。',
204
- '14. 快捷键:默认 Shift+A 新建节点,Shift+D 复制节点与连线,Delete 删除,Ctrl+Z 撤销,Esc 关闭弹窗(可在「⋯ → 快捷键设置」自定义)。',
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,10 @@ window.__ModuleLoader__.load({
313
314
  tipMemoryPick: '选择要续接的历史子会话(默认自动沿用最新记忆)',
314
315
  tipPreset: '能力范围(点一下切换,受主对话权限上限约束):standard = 全部工具(读写文件、跑命令、子代理、工作流、网页、办公);minimal = 只读思考(文件读写关闭,没有子代理/工作流/网页)',
315
316
  tipFallback: '失败重试:该节点出错时自动换一个模型再跑一次',
316
- tipStructured: 'JSON 输出:要求该节点返回 JSON 对象,structured 连线会把结果作为 JSON 传给下游',
317
- lang: 'ZH',
318
317
  },
319
318
  en: {
320
319
  addAgent: '+ Subagent', addLead: '+ Lead', addCond: '+ Condition', undo: '↶ Undo', redo: '↷ Redo', sync: '↥ Sync',
321
- enabled: '● ON', disabled: '○ OFF', presetName: 'Preset name', save: '☆ Save',
320
+ enabled: '● ON', disabled: '○ OFF', save: '☆ Save',
322
321
  presets: '☰ Presets', unsaved: 'Unsaved changes', synced: 'Synced',
323
322
  pickModel: 'Pick a model', loadingModels: 'Loading…', defaultEffort: 'default',
324
323
  leadThis: 'Lead (this chat)',
@@ -327,8 +326,6 @@ window.__ModuleLoader__.load({
327
326
  tipCondTrue: 'Runs when condition passes (pass=true); connect to any downstream input',
328
327
  tipCondFalse: 'Runs when condition fails (pass=false); connect to any downstream input',
329
328
  tipBranchOut: 'Runs when this branch matches; connect to any downstream input',
330
- branchTrue: 'Yes',
331
- branchFalse: 'No',
332
329
  addBranch: '+ Case',
333
330
  branchPh: 'Branch name',
334
331
  delBranchTip: 'Remove this branch (minimum 2)',
@@ -350,11 +347,10 @@ window.__ModuleLoader__.load({
350
347
  syncBadFile: 'File content is invalid',
351
348
  generated: 'Canvas generated from chat',
352
349
  dupName: 'already exists, pick another name',
353
- guideDesc: 'Sketch a subagent workflow',
354
350
  model: 'Model', reason: 'Reasoning', role: 'Role', task: 'Task', taskPh: 'Task, e.g. classify these reports and suggest actions',
355
351
  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',
352
+ memory: 'Memory', scope: 'Scope',
353
+ sep: ': ', on: 'on', off: 'off', none: 'none',
358
354
  scopeMinimal: 'minimal (read-only thinking)', scopeStandard: 'standard (all tools)',
359
355
  fallbackModel: 'Fallback',
360
356
  stPending: 'Pending', stRunning: 'Running', stDone: 'Done', stFailed: 'Failed',
@@ -363,21 +359,19 @@ window.__ModuleLoader__.load({
363
359
  presetSaveTitle: 'Save current canvas (reuse in any new chat)',
364
360
  presetNamePh: 'Name this canvas…',
365
361
  myPresets: 'Saved presets (all sessions)',
366
- needName: 'Name the preset first', duplicate: 'already exists, pick another name',
362
+ needName: 'Name the preset first',
367
363
  savedPreset: 'Saved preset', saveFailed: 'Save failed (storage unavailable)',
368
364
  loadedPreset: 'Loaded preset', invalidPreset: 'Preset content is invalid', deletedPreset: 'Deleted preset',
369
365
  syncFailed: 'Sync failed', upToDate: 'Already up to date', syncedToHost: 'Synced to host',
370
366
  syncedWithStdWarn: 'Synced (has write/tool nodes — check main chat permission mode)',
371
367
  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',
368
+ leadLocked: 'The entry Lead cannot be deleted',
373
369
  tipLead: 'Lead steps run in the chat; the canvas does not track them',
374
370
  tipOrphan: 'Unlinked: skipped when the canvas runs', tipStatus: 'Subagent run status',
375
- tipZoom: 'Wheel zooms around the cursor',
376
371
  tipResetZoom: 'Click to reset to 100% on Lead; drag left/right to scrub zoom',
377
372
  tipLocate: 'Fit all nodes into the visible canvas',
378
373
  locate: '⊡ Fit',
379
374
  importBtn: '⇩ Import',
380
- tipImport: 'Import a model-generated canvas from the clipboard (copy the canvas JSON from chat first)',
381
375
  importOk: 'Canvas imported, ',
382
376
  tipMore: 'More',
383
377
  help: 'How to use',
@@ -392,15 +386,15 @@ window.__ModuleLoader__.load({
392
386
  '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
387
  '4. Every node has one universal left input that accepts any incoming wire; drag a connected input away to detach the latest wire.',
394
388
  '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.',
389
+ '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.',
390
+ '7. The run pauses at intermediate Lead nodes for your decision (reply to continue, or ask to cancel / click ⏹ Stop).',
397
391
  '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.',
392
+ '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 ⋯).',
393
+ '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
394
  '11. You can ask me to edit the canvas; I patch it in place and keep your layout.',
401
395
  '12. A session link into a Lead step hands me that child agent, so I can follow up with it.',
402
396
  '13. Hold the middle mouse button (or Space + drag) to pan; click a subagent status badge at the bottom-left to open its chat.',
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).',
397
+ '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
398
  ].join('\n'),
405
399
  openChat: 'Chat',
406
400
  tipOpenRun: 'Click to open this subagent conversation',
@@ -426,9 +420,13 @@ window.__ModuleLoader__.load({
426
420
  verdictFallback: 'Skipped branches → Lead: ',
427
421
  verdictNoReason: '(No extra reason provided)',
428
422
  tipVerdictChip: 'Click to inspect verdict reason',
429
- runBtn: '▶ Run',
430
- runBtnRunning: 'Running…',
431
- runBtnWaiting: '⏸ Awaiting Lead',
423
+ stopSent: 'Stop signal sent',
424
+ stopWaitingDone: 'Cancelled awaiting Lead gate',
425
+ stopFailed: 'Failed to stop workflow',
426
+ refreshPresetsTip: 'Refresh presets',
427
+ presetsRefreshed: 'Presets refreshed',
428
+ presetDirTB: 'V',
429
+ presetDirLR: 'H',
432
430
  runStarted: 'Workflow run queued in this chat',
433
431
  runFailed: 'Failed to start run',
434
432
  runSendUnavailable: 'Direct canvas launch is unavailable in this host; send a message in chat to start',
@@ -512,8 +510,6 @@ window.__ModuleLoader__.load({
512
510
  tipMemoryPick: 'Pick which past child session to resume (defaults to latest)',
513
511
  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
512
  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',
517
513
  },
518
514
  };
519
515
 
@@ -567,32 +563,31 @@ window.__ModuleLoader__.load({
567
563
  width: '1px', height: '16px', background: C.border, opacity: 0.65,
568
564
  flex: '0 0 auto', margin: '0 2px',
569
565
  },
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
566
  status: {
581
567
  fontSize: '11px', color: C.dim,
582
- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%',
568
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '160px',
583
569
  },
584
- floatOn: {
570
+ floatTopLeft: {
585
571
  position: 'absolute', top: '10px', left: '10px', zIndex: 30,
572
+ display: 'inline-flex', alignItems: 'center', gap: '6px',
573
+ },
574
+ floatOn: {
586
575
  padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.accent,
587
576
  background: C.elevated, color: C.accent, fontSize: '11px', fontWeight: 600,
588
577
  cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
589
578
  },
590
579
  floatOff: {
591
- position: 'absolute', top: '10px', left: '10px', zIndex: 30,
592
580
  padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.border,
593
581
  background: C.elevated, color: C.dim, fontSize: '11px', fontWeight: 600,
594
582
  cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
595
583
  },
584
+ floatStop: {
585
+ padding: '5px 10px', borderRadius: '999px', border: '1px solid rgba(229,83,75,0.75)',
586
+ background: C.elevated, color: '#e5534b', fontSize: '11px', fontWeight: 600,
587
+ cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
588
+ display: 'inline-flex', alignItems: 'center', gap: '5px', lineHeight: '14px',
589
+ whiteSpace: 'nowrap',
590
+ },
596
591
  floatZoomBar: {
597
592
  position: 'absolute', right: '10px', bottom: '10px', zIndex: 30,
598
593
  display: 'inline-flex', alignItems: 'center', gap: '4px',
@@ -705,7 +700,6 @@ window.__ModuleLoader__.load({
705
700
  marginLeft: 'auto', display: 'flex', alignItems: 'center',
706
701
  gap: '6px', position: 'relative', flex: '0 0 auto',
707
702
  },
708
- presetRowTop: { display: 'flex', alignItems: 'center', gap: '5px' },
709
703
  presetMenu: {
710
704
  position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '236px',
711
705
  maxHeight: '320px', overflowY: 'auto', background: C.elevated, color: C.text,
@@ -798,12 +792,6 @@ window.__ModuleLoader__.load({
798
792
  fieldFallback: { position: 'absolute', left: '10px', right: '10px', top: '101px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
799
793
  fieldMemory: { position: 'absolute', left: '10px', right: '10px', top: '123px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
800
794
  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
795
 
808
796
  toggleSwitch: {
809
797
  flex: '1 1 auto', width: '100%', height: '18px', boxSizing: 'border-box', padding: '0 5px', borderRadius: '4px',
@@ -815,18 +803,6 @@ window.__ModuleLoader__.load({
815
803
  border: '1px solid ' + C.accent, background: C.base, color: C.accent,
816
804
  fontSize: '10px', cursor: 'pointer', outline: 'none', textAlign: 'center', lineHeight: '14px',
817
805
  },
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
806
  fieldLabel: { flex: '0 0 30px', width: '30px', fontSize: '9px', color: C.dim, whiteSpace: 'nowrap' },
831
807
  fieldLabelEn: { flex: '0 0 46px', width: '46px', fontSize: '9px', color: C.dim, whiteSpace: 'nowrap' },
832
808
 
@@ -910,12 +886,6 @@ window.__ModuleLoader__.load({
910
886
  background: C.base, color: C.text, fontSize: '10px', cursor: 'pointer', textAlign: 'left',
911
887
  lineHeight: '14px',
912
888
  },
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
889
  selectText: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
920
890
  caret: { flex: '0 0 auto', color: C.dim, fontSize: '9px' },
921
891
  menu: {
@@ -945,14 +915,6 @@ window.__ModuleLoader__.load({
945
915
  color: '#e5534b', fontSize: '12px', lineHeight: '16px', textAlign: 'center',
946
916
  cursor: 'pointer', zIndex: 8, userSelect: 'none',
947
917
  },
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
918
  verdictChip: {
957
919
  position: 'absolute', left: '0', top: 'calc(100% + 5px)', maxWidth: NODE_W + 'px',
958
920
  display: 'inline-flex', alignItems: 'center', gap: '4px',
@@ -1164,6 +1126,91 @@ window.__ModuleLoader__.load({
1164
1126
  };
1165
1127
  }
1166
1128
 
1129
+ /** Compute unified Stop button visibility, label and tooltip across running & waitingLead states. */
1130
+ function stopButtonState({ sessionRunning, runningNodesCount, waitingLead, triggering, stopping, lang }) {
1131
+ const en = lang === 'en';
1132
+ const hasRunning = Boolean(sessionRunning || triggering || Number(runningNodesCount) > 0);
1133
+ const hasWaiting = Boolean(waitingLead);
1134
+ if (!hasRunning && !hasWaiting) {
1135
+ return { visible: false, disabled: true, mode: 'idle', label: '', title: '' };
1136
+ }
1137
+ const mode = hasRunning ? 'running' : 'waiting';
1138
+ return {
1139
+ visible: true,
1140
+ disabled: Boolean(stopping),
1141
+ mode,
1142
+ label: stopping
1143
+ ? (en ? 'Stopping…' : '终止中…')
1144
+ : (en ? '⏹ Stop' : '⏹ 终止'),
1145
+ title: mode === 'waiting'
1146
+ ? (en ? 'Cancel the paused Lead gate and end this workflow run' : '结束当前等待拍板状态并终止本轮流程')
1147
+ : (en ? 'Stop all running workflow tasks and subagents' : '一键终止全部正在运行的任务与子代理'),
1148
+ };
1149
+ }
1150
+
1151
+ /**
1152
+ * Derive Lead node ready/done sets cleanly, respecting authoritative `runState.status`
1153
+ * (`halted` / `done` / `idle` / `need-lead`) so a stopped or completed workflow can never
1154
+ * falsely re-enter "Awaiting Lead" from historical subagent statuses.
1155
+ */
1156
+ function deriveLeadStatuses({ enabled, nodes, edges, statusById, sessionRunning, runState, reachableIds }) {
1157
+ const leadReadyIds = new Set();
1158
+ const leadDoneIds = new Set();
1159
+ if (!enabled) return { leadReadyIds, leadDoneIds };
1160
+
1161
+ const nodeList = Array.isArray(nodes) ? nodes : [];
1162
+ const edgeList = forwardEdgesUI(edges);
1163
+ const nodeById = new Map(nodeList.map((n) => [n.id, n]));
1164
+ const reach = reachableIds || reachableFrom(nodeList, edgeList);
1165
+ const stMap = statusById || {};
1166
+
1167
+ if (runState && Array.isArray(runState.done)) {
1168
+ for (const did of runState.done) {
1169
+ const dn = nodeById.get(did);
1170
+ if (dn && dn.kind === 'lead' && dn.id !== 'lead') leadDoneIds.add(did);
1171
+ }
1172
+ }
1173
+ if (runState && runState.status === 'need-lead' && runState.waitingLead && runState.waitingLead.id) {
1174
+ leadReadyIds.add(runState.waitingLead.id);
1175
+ } else if (runState && !runState.status && runState.waitingLead && runState.waitingLead.id) {
1176
+ leadReadyIds.add(runState.waitingLead.id);
1177
+ }
1178
+
1179
+ // If the backend reported a terminal or explicit paused runState, treat it as authoritative
1180
+ // instead of guessing ready Leads from historical child statuses.
1181
+ const authoritativeStatus = runState && typeof runState.status === 'string' ? runState.status : '';
1182
+ if (authoritativeStatus === 'halted' || authoritativeStatus === 'done' || authoritativeStatus === 'idle' || authoritativeStatus === 'need-lead') {
1183
+ return { leadReadyIds, leadDoneIds };
1184
+ }
1185
+
1186
+ const hasCondNode = nodeList.some((x) => x && x.kind === 'condition');
1187
+ for (const n of nodeList) {
1188
+ if (!n || n.kind !== 'lead' || n.id === 'lead' || !reach.has(n.id)) continue;
1189
+ if (leadReadyIds.has(n.id) || leadDoneIds.has(n.id)) continue;
1190
+ const upIds = edgeList
1191
+ .filter((e) => e.to === n.id && e.from !== 'lead' && nodeById.has(e.from))
1192
+ .map((e) => e.from);
1193
+ if (!upIds.length) continue;
1194
+ const upAgents = upIds.filter((id) => nodeById.get(id).kind !== 'lead');
1195
+ if (!upAgents.length) continue;
1196
+ const anyUpRunning = upAgents.some((id) => stMap[id] === 'running');
1197
+ const allUpDone = hasCondNode
1198
+ ? (!anyUpRunning && upAgents.some((id) => stMap[id] === 'done' || stMap[id] === 'failed'))
1199
+ : upAgents.every((id) => stMap[id] === 'done' || stMap[id] === 'failed');
1200
+ if (!allUpDone) continue;
1201
+ const downIds = edgeList.filter((e) => e.from === n.id).map((e) => e.to);
1202
+ if (!downIds.length) {
1203
+ if (sessionRunning) leadReadyIds.add(n.id);
1204
+ else leadDoneIds.add(n.id);
1205
+ } else {
1206
+ const anyDownStarted = downIds.some((id) => Boolean(stMap[id]));
1207
+ if (!anyDownStarted) leadReadyIds.add(n.id);
1208
+ else leadDoneIds.add(n.id);
1209
+ }
1210
+ }
1211
+ return { leadReadyIds, leadDoneIds };
1212
+ }
1213
+
1167
1214
  function isCustomBranches(node) {
1168
1215
  return Boolean(node && node.kind === 'condition' && Array.isArray(node.branches) && node.branches.length >= 2);
1169
1216
  }
@@ -1439,6 +1486,12 @@ window.__ModuleLoader__.load({
1439
1486
  }
1440
1487
  }
1441
1488
  if (!reach.has(exitId)) return { ok: false, reason: 'loopDisconnected' };
1489
+ // Verify the full runtime loop body (`descendants(entry) ∩ ancestors(exit)` across the
1490
+ // entire graph) never pulls in a node already owned by another loop.
1491
+ const fullMembers = loopMemberIdsUI(list, edges, { from: exitId, to: entryId, loop: true });
1492
+ for (const mid of fullMembers) {
1493
+ if (existing.byNode.has(mid)) return { ok: false, reason: 'loopOverlap' };
1494
+ }
1442
1495
  const exitNode = byId.get(exitId);
1443
1496
  return {
1444
1497
  ok: true,
@@ -1632,8 +1685,8 @@ window.__ModuleLoader__.load({
1632
1685
  }
1633
1686
  const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
1634
1687
  const out = [];
1635
- while (queue.length) {
1636
- const id = queue.shift();
1688
+ for (let i = 0; i < queue.length; i += 1) {
1689
+ const id = queue[i];
1637
1690
  out.push(id);
1638
1691
  for (const next of adj.get(id)) {
1639
1692
  indeg.set(next, indeg.get(next) - 1);
@@ -1735,8 +1788,8 @@ window.__ModuleLoader__.load({
1735
1788
  }
1736
1789
  const seen = new Set([toId]);
1737
1790
  const queue = [toId];
1738
- while (queue.length) {
1739
- const cur = queue.shift();
1791
+ for (let i = 0; i < queue.length; i += 1) {
1792
+ const cur = queue[i];
1740
1793
  if (cur === fromId) return true;
1741
1794
  for (const next of adj.get(cur) || []) {
1742
1795
  if (!seen.has(next)) { seen.add(next); queue.push(next); }
@@ -1791,14 +1844,16 @@ window.__ModuleLoader__.load({
1791
1844
  }
1792
1845
  } else {
1793
1846
  const COL_PITCH = 300;
1794
- const ROW_PITCH = 262;
1847
+ const ROW_GAP = 28;
1795
1848
  const MID_Y = 320;
1796
1849
  for (const [col, colNodes] of columns.entries()) {
1797
1850
  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);
1851
+ const heights = ordered.map((n) => nodeHeight(n));
1852
+ const totalH = heights.reduce((sum, hVal) => sum + hVal, 0) + Math.max(0, ordered.length - 1) * ROW_GAP;
1853
+ let cursorY = Math.round(MID_Y - totalH / 2);
1800
1854
  ordered.forEach((n, row) => {
1801
- posById.set(n.id, { x: 40 + col * COL_PITCH, y: startY + row * ROW_PITCH });
1855
+ posById.set(n.id, { x: 40 + col * COL_PITCH, y: cursorY });
1856
+ cursorY += heights[row] + ROW_GAP;
1802
1857
  });
1803
1858
  }
1804
1859
  }
@@ -2343,6 +2398,37 @@ window.__ModuleLoader__.load({
2343
2398
  return { k, x: cx - lx * k, y: cy - ly * k };
2344
2399
  }
2345
2400
 
2401
+ /**
2402
+ * Apply one incremental pan step on top of the latest live `curView` so concurrent
2403
+ * wheel zoom anchor shifts are never overwritten by stale drag origins.
2404
+ */
2405
+ function applyPanStep(curView, pan, clientX, clientY) {
2406
+ const dx = clientX - pan.lastX;
2407
+ const dy = clientY - pan.lastY;
2408
+ return {
2409
+ view: { k: curView.k, x: curView.x + dx, y: curView.y + dy },
2410
+ pan: { lastX: clientX, lastY: clientY },
2411
+ };
2412
+ }
2413
+
2414
+ function normalizeDirection(val) {
2415
+ return val === 'tb' ? 'tb' : 'lr';
2416
+ }
2417
+
2418
+ function loadDefaultDirection() {
2419
+ try {
2420
+ return normalizeDirection(window.localStorage.getItem(DIRECTION_KEY));
2421
+ } catch (_e) {
2422
+ return 'lr';
2423
+ }
2424
+ }
2425
+
2426
+ function saveDefaultDirection(dir) {
2427
+ try {
2428
+ window.localStorage.setItem(DIRECTION_KEY, normalizeDirection(dir));
2429
+ } catch (_e) { /* ignore */ }
2430
+ }
2431
+
2346
2432
  function loadPresets() {
2347
2433
  try {
2348
2434
  const raw = window.localStorage.getItem(PRESET_KEY);
@@ -2357,6 +2443,16 @@ window.__ModuleLoader__.load({
2357
2443
  function savePresets(presets) {
2358
2444
  try {
2359
2445
  window.localStorage.setItem(PRESET_KEY, JSON.stringify(presets));
2446
+ // Native `storage` events only fire across separate windows, not across keepMounted
2447
+ // session tabs inside the same Electron window; broadcast a custom event for instant sync.
2448
+ try {
2449
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
2450
+ const ev = typeof CustomEvent === 'function'
2451
+ ? new CustomEvent(PRESET_CHANGE_EVENT)
2452
+ : { type: PRESET_CHANGE_EVENT };
2453
+ window.dispatchEvent(ev);
2454
+ }
2455
+ } catch (_evErr) { /* ignore in non-DOM test env */ }
2360
2456
  return true;
2361
2457
  } catch (_e) {
2362
2458
  return false;
@@ -2437,8 +2533,15 @@ window.__ModuleLoader__.load({
2437
2533
  const sessionId = props && props.sessionId;
2438
2534
  const stored = useRef(loadDoc(sessionId));
2439
2535
  const initial = stored.current;
2440
-
2441
- const [nodes, setNodes] = useState(() => (initial ? initial.nodes : defaultNodes()));
2536
+ const initialDir = (initial && (initial.direction === 'tb' || initial.direction === 'lr'))
2537
+ ? initial.direction
2538
+ : loadDefaultDirection();
2539
+
2540
+ const [nodes, setNodes] = useState(() => {
2541
+ if (initial) return initial.nodes;
2542
+ const dn = defaultNodes();
2543
+ return initialDir === 'tb' ? layoutGraph(dn, defaultEdges(), 'tb') : dn;
2544
+ });
2442
2545
  const [edges, setEdges] = useState(() => (initial ? initial.edges : defaultEdges()));
2443
2546
  const [selectedIds, setSelectedIds] = useState([]);
2444
2547
  const [marquee, setMarquee] = useState(null);
@@ -2472,7 +2575,7 @@ window.__ModuleLoader__.load({
2472
2575
  const [modelsLoading, setModelsLoading] = useState(() => cachedModels.length === 0);
2473
2576
  const [openModelFor, setOpenModelFor] = useState(null);
2474
2577
  const [enabled, setEnabled] = useState(() => Boolean(initial && initial.enabled));
2475
- const [direction, setDirection] = useState(() => (initial && initial.direction === 'tb' ? 'tb' : 'lr'));
2578
+ const [direction, setDirection] = useState(initialDir);
2476
2579
  const directionRef = useRef(direction);
2477
2580
  directionRef.current = direction;
2478
2581
 
@@ -2489,12 +2592,12 @@ window.__ModuleLoader__.load({
2489
2592
  const rightClickRef = useRef(null);
2490
2593
  const nodeDrag = useRef(null);
2491
2594
  const panDrag = useRef(null);
2595
+ const zoomScrubbing = useRef(false);
2492
2596
  const [panning, setPanning] = useState(false);
2493
2597
  const spaceDown = useRef(false);
2494
2598
  const [spaceHeld, setSpaceHeld] = useState(false);
2495
2599
  const statusTimer = useRef(null);
2496
2600
  const dropdownRef = useRef(null);
2497
- const syncTimer = useRef(null);
2498
2601
  const lastSync = useRef('');
2499
2602
  const historyRef = useRef([]);
2500
2603
  const redoRef = useRef([]);
@@ -2510,11 +2613,50 @@ window.__ModuleLoader__.load({
2510
2613
  const [sessionRunning, setSessionRunning] = useState(false);
2511
2614
  const [runTriggering, setRunTriggering] = useState(false);
2512
2615
  const runTriggeringRef = useRef(false);
2616
+ const [stopping, setStopping] = useState(false);
2617
+ const stoppingRef = useRef(false);
2513
2618
  const pendingHandledRef = useRef(false);
2514
2619
  const lastNodePrefsRef = useRef({ provider: '', model: '', reasoning: '', preset: 'standard' });
2515
2620
  const [presets, setPresets] = useState(loadPresets);
2516
2621
  const [presetOpen, setPresetOpen] = useState(null);
2517
2622
  const [presetName, setPresetName] = useState('');
2623
+
2624
+ const refreshPresets = (announce) => {
2625
+ const latest = loadPresets();
2626
+ setPresets(latest);
2627
+ if (announce) flash(t('presetsRefreshed'));
2628
+ return latest;
2629
+ };
2630
+
2631
+ // Keep preset list fresh across mounted session tabs (same window + cross-window).
2632
+ useEffect(() => {
2633
+ const sync = () => setPresets(loadPresets());
2634
+ const onStorage = (ev) => {
2635
+ if (!ev || ev.key === PRESET_KEY || ev.key === null) sync();
2636
+ };
2637
+ const onVis = () => {
2638
+ if (typeof document !== 'undefined' && document.visibilityState === 'visible') sync();
2639
+ };
2640
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
2641
+ window.addEventListener('storage', onStorage);
2642
+ window.addEventListener(PRESET_CHANGE_EVENT, sync);
2643
+ window.addEventListener('focus', sync);
2644
+ }
2645
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
2646
+ document.addEventListener('visibilitychange', onVis);
2647
+ }
2648
+ sync();
2649
+ return () => {
2650
+ if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
2651
+ window.removeEventListener('storage', onStorage);
2652
+ window.removeEventListener(PRESET_CHANGE_EVENT, sync);
2653
+ window.removeEventListener('focus', sync);
2654
+ }
2655
+ if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
2656
+ document.removeEventListener('visibilitychange', onVis);
2657
+ }
2658
+ };
2659
+ }, [sessionId]);
2518
2660
  const [lang, setLang] = useState(loadLang);
2519
2661
  const t = (key) => (I18N[lang] && I18N[lang][key]) || I18N.zh[key] || key;
2520
2662
  const toggleLang = () => {
@@ -2621,7 +2763,7 @@ window.__ModuleLoader__.load({
2621
2763
  const sig = planSig(nextEnabled, curNodes, curEdges, overrideParallel);
2622
2764
  if (sig === lastSync.current) { setDirty(false); flash(t('upToDate')); return Promise.resolve(true); }
2623
2765
  const line = '/canvas-sync ' + encodeURIComponent(sig);
2624
- const hasStandardAgent = nextEnabled && curNodes.some((n) => n && n.kind !== 'lead' && (n.preset || 'standard') !== 'minimal');
2766
+ const hasStandardAgent = nextEnabled && curNodes.some((n) => n && n.kind !== 'lead' && n.kind !== 'condition' && (n.preset || 'standard') !== 'minimal');
2625
2767
  return face.command(line).then((ack) => {
2626
2768
  if (ack && ack.ok) {
2627
2769
  lastSync.current = sig;
@@ -2701,6 +2843,109 @@ window.__ModuleLoader__.load({
2701
2843
  }
2702
2844
  };
2703
2845
 
2846
+ /**
2847
+ * Unified Stop action for both in-flight executions (#11) and paused Lead gates (#13),
2848
+ * using DSH 0.2.2 verified APIs:
2849
+ * - `face.command('/canvas-stop')` (executes concurrently even while running; triggers
2850
+ * backend `subagents.interrupt` + `drainDescendants([agent])` + `agent.cancel` + clears waitingLead)
2851
+ * - `remote.subagents.interruptByUser(childId)` for every live subagent
2852
+ * - `face.cancel()` / `remote.session.cancel({ sessionId })` for the root session turn
2853
+ */
2854
+ const stopWorkflow = async () => {
2855
+ if (stoppingRef.current) return;
2856
+ stoppingRef.current = true;
2857
+ setStopping(true);
2858
+ const wasWaitingOnly = !sessionRunning && !runTriggeringRef.current
2859
+ && !Object.values(statusById).some((s) => s === 'running');
2860
+ // Resolved lazily rather than via hard `inject` so missing namespaces on older hosts never block plugin load.
2861
+ const resolveRemoteSubagents = () => {
2862
+ try {
2863
+ if (hostCtx && typeof hostCtx.get === 'function') {
2864
+ const svc = hostCtx.get('remote.subagents');
2865
+ if (svc) return svc;
2866
+ }
2867
+ } catch (_e) { /* absent */ }
2868
+ try {
2869
+ return (hostCtx && hostCtx.remote && hostCtx.remote.subagents) || null;
2870
+ } catch (_e) {
2871
+ return null;
2872
+ }
2873
+ };
2874
+ try {
2875
+ const runningChildIds = new Set();
2876
+ try {
2877
+ const sessions = hostCtx && hostCtx.sessions;
2878
+ if (sessions && sessionId && sessions.list && typeof sessions.list.getSnapshot === 'function') {
2879
+ const snap = sessions.list.getSnapshot();
2880
+ const proj = snap && snap.projectionsBySession && snap.projectionsBySession[sessionId];
2881
+ const catalog = proj && proj.values && proj.values.subagentCatalog;
2882
+ if (Array.isArray(catalog)) {
2883
+ for (const entry of catalog) {
2884
+ if (!entry || !entry.id) continue;
2885
+ const child = snap.byId && snap.byId[entry.id];
2886
+ if (child && child.running) runningChildIds.add(String(entry.id));
2887
+ }
2888
+ }
2889
+ }
2890
+ } catch (_e) { /* ignore */ }
2891
+ for (const [nid, st] of Object.entries(statusById)) {
2892
+ if (st === 'running' && runsById[nid] && runsById[nid].childId) {
2893
+ runningChildIds.add(String(runsById[nid].childId));
2894
+ }
2895
+ }
2896
+
2897
+ const face = sessionFace(sessionId);
2898
+ const tasks = [];
2899
+
2900
+ // 1) Fire `/canvas-stop` immediately (runs concurrently even while a turn is active).
2901
+ if (face && typeof face.command === 'function') {
2902
+ tasks.push(Promise.resolve().then(() => face.command('/canvas-stop')).catch(() => {}));
2903
+ }
2904
+
2905
+ // 2) Interrupt every running child subagent via `remote.subagents.interruptByUser(childId)`.
2906
+ const remoteSub = resolveRemoteSubagents();
2907
+ if (remoteSub && typeof remoteSub.interruptByUser === 'function') {
2908
+ for (const cid of runningChildIds) {
2909
+ tasks.push(Promise.resolve().then(() => remoteSub.interruptByUser(cid)).catch(() => {}));
2910
+ }
2911
+ }
2912
+
2913
+ // 3) Cancel the running root session turn (never call session.cancel on subagents).
2914
+ if (sessionRunning || runTriggeringRef.current) {
2915
+ if (face && typeof face.cancel === 'function') {
2916
+ tasks.push(Promise.resolve().then(() => face.cancel()).catch(() => {}));
2917
+ } else {
2918
+ const remoteSess = hostCtx && hostCtx.remote && hostCtx.remote.session;
2919
+ if (remoteSess && typeof remoteSess.cancel === 'function' && sessionId) {
2920
+ tasks.push(Promise.resolve().then(() => remoteSess.cancel({ sessionId })).catch(() => {}));
2921
+ }
2922
+ }
2923
+ }
2924
+
2925
+ await Promise.all(tasks);
2926
+ runTriggeringRef.current = false;
2927
+ setRunTriggering(false);
2928
+ setRunState((prev) => ({
2929
+ ...(prev || {}),
2930
+ status: 'halted',
2931
+ waitingLead: null,
2932
+ }));
2933
+ setStatusById((prev) => {
2934
+ const next = {};
2935
+ for (const [k, v] of Object.entries(prev || {})) {
2936
+ if (v !== 'running') next[k] = v;
2937
+ }
2938
+ return next;
2939
+ });
2940
+ flash(wasWaitingOnly ? t('stopWaitingDone') : t('stopSent'));
2941
+ } catch (_err) {
2942
+ flash(t('stopFailed'));
2943
+ } finally {
2944
+ stoppingRef.current = false;
2945
+ setStopping(false);
2946
+ }
2947
+ };
2948
+
2704
2949
  // Sync the moment a user message starts a turn, so this turn's tool call
2705
2950
  // already sees the latest canvas. Falls back to the turn end if the start
2706
2951
  // edge was missed; `dirty` clears on success so only one fires.
@@ -2793,7 +3038,8 @@ window.__ModuleLoader__.load({
2793
3038
  if (child && child.running) {
2794
3039
  if (entry.id) staleChildIds.current.delete(entry.id);
2795
3040
  nextStatus[nodeId] = 'running';
2796
- } else if (!entry.id || !staleChildIds.current.has(entry.id)) {
3041
+ } else if (nextStatus[nodeId] !== 'running' && (!entry.id || !staleChildIds.current.has(entry.id))) {
3042
+ // Keep 'running' sticky across catalog entries so prior retry rounds never mask an active child.
2797
3043
  if (timing && timing.lastTurnCompleted === false) nextStatus[nodeId] = 'failed';
2798
3044
  else nextStatus[nodeId] = 'done';
2799
3045
  }
@@ -2881,7 +3127,7 @@ window.__ModuleLoader__.load({
2881
3127
  return null;
2882
3128
  };
2883
3129
  const onWheel = (e) => {
2884
- if (!e.deltaY) return;
3130
+ if (!e.deltaY || zoomScrubbing.current) return;
2885
3131
  if (!e.ctrlKey && findScrollableChild(e.target, e.deltaY)) return;
2886
3132
  e.preventDefault();
2887
3133
  absorbScroll();
@@ -2956,6 +3202,7 @@ window.__ModuleLoader__.load({
2956
3202
  const startX = e.clientX;
2957
3203
  const startView = { ...viewRef.current };
2958
3204
  let moved = false;
3205
+ zoomScrubbing.current = true;
2959
3206
  const prevCursor = typeof document !== 'undefined' && document.body ? document.body.style.cursor : '';
2960
3207
  const onMove = (ev) => {
2961
3208
  const dx = ev.clientX - startX;
@@ -2967,13 +3214,20 @@ window.__ModuleLoader__.load({
2967
3214
  commitView(scrubZoom(startView, cx, cy, dx));
2968
3215
  };
2969
3216
  const onUp = () => {
3217
+ zoomScrubbing.current = false;
2970
3218
  window.removeEventListener('mousemove', onMove);
2971
3219
  window.removeEventListener('mouseup', onUp);
3220
+ window.removeEventListener('blur', onBlurScrub);
2972
3221
  if (typeof document !== 'undefined' && document.body) document.body.style.cursor = prevCursor;
2973
3222
  if (!moved) focusLead(1);
2974
3223
  };
3224
+ const onBlurScrub = () => {
3225
+ moved = true;
3226
+ onUp();
3227
+ };
2975
3228
  window.addEventListener('mousemove', onMove);
2976
3229
  window.addEventListener('mouseup', onUp);
3230
+ window.addEventListener('blur', onBlurScrub);
2977
3231
  };
2978
3232
 
2979
3233
  /** Zoom and pan so every node sits comfortably inside the viewport. */
@@ -2994,12 +3248,15 @@ window.__ModuleLoader__.load({
2994
3248
  if (n.y + nh > maxY) maxY = n.y + nh;
2995
3249
  }
2996
3250
  if (!Number.isFinite(minX)) return;
3251
+ const hasLoopEdges = edgesRef.current.some((e) => e && e.loop === true);
3252
+ const isTB = directionRef.current === 'tb';
2997
3253
  const cw = el.clientWidth || 1;
2998
3254
  const chh = el.clientHeight || 1;
2999
- const padX = 36;
3000
- const padTop = 44;
3255
+ const padLeft = 36;
3256
+ const padRight = hasLoopEdges && isTB ? 84 : 36;
3257
+ const padTop = hasLoopEdges && !isTB ? 78 : 44;
3001
3258
  const padBottom = 36;
3002
- const availW = Math.max(80, cw - padX * 2);
3259
+ const availW = Math.max(80, cw - padLeft - padRight);
3003
3260
  const availH = Math.max(80, chh - padTop - padBottom);
3004
3261
  const bw = Math.max(NODE_W, maxX - minX);
3005
3262
  const bh = Math.max(NODE_H, maxY - minY);
@@ -3010,7 +3267,7 @@ window.__ModuleLoader__.load({
3010
3267
  el.scrollTop = 0;
3011
3268
  commitView({
3012
3269
  k,
3013
- x: cw / 2 - (cx + WORLD_PAD) * k,
3270
+ x: padLeft + (cw - padLeft - padRight) / 2 - (cx + WORLD_PAD) * k,
3014
3271
  y: padTop + (chh - padTop - padBottom) / 2 - (cy + WORLD_PAD) * k,
3015
3272
  });
3016
3273
  };
@@ -3033,7 +3290,11 @@ window.__ModuleLoader__.load({
3033
3290
 
3034
3291
  // Snapshot before every structural change so a mis-click can be undone/redone.
3035
3292
  const pushSnapshot = () => {
3036
- historyRef.current.push({ nodes: nodesRef.current, edges: edgesRef.current });
3293
+ historyRef.current.push({
3294
+ nodes: nodesRef.current,
3295
+ edges: edgesRef.current,
3296
+ direction: directionRef.current,
3297
+ });
3037
3298
  if (historyRef.current.length > 50) historyRef.current.shift();
3038
3299
  redoRef.current = [];
3039
3300
  };
@@ -3041,8 +3302,16 @@ window.__ModuleLoader__.load({
3041
3302
  const undo = () => {
3042
3303
  const prev = historyRef.current.pop();
3043
3304
  if (!prev) { flash(t('undoNone')); return; }
3044
- redoRef.current.push({ nodes: nodesRef.current, edges: edgesRef.current });
3305
+ redoRef.current.push({
3306
+ nodes: nodesRef.current,
3307
+ edges: edgesRef.current,
3308
+ direction: directionRef.current,
3309
+ });
3045
3310
  if (redoRef.current.length > 50) redoRef.current.shift();
3311
+ if (prev.direction === 'tb' || prev.direction === 'lr') {
3312
+ directionRef.current = prev.direction;
3313
+ setDirection(prev.direction);
3314
+ }
3046
3315
  setNodes(prev.nodes);
3047
3316
  setEdges(prev.edges);
3048
3317
  setSelectedIds([]);
@@ -3052,8 +3321,16 @@ window.__ModuleLoader__.load({
3052
3321
  const redo = () => {
3053
3322
  const next = redoRef.current.pop();
3054
3323
  if (!next) { flash(t('redoNone')); return; }
3055
- historyRef.current.push({ nodes: nodesRef.current, edges: edgesRef.current });
3324
+ historyRef.current.push({
3325
+ nodes: nodesRef.current,
3326
+ edges: edgesRef.current,
3327
+ direction: directionRef.current,
3328
+ });
3056
3329
  if (historyRef.current.length > 50) historyRef.current.shift();
3330
+ if (next.direction === 'tb' || next.direction === 'lr') {
3331
+ directionRef.current = next.direction;
3332
+ setDirection(next.direction);
3333
+ }
3057
3334
  setNodes(next.nodes);
3058
3335
  setEdges(next.edges);
3059
3336
  setSelectedIds([]);
@@ -3393,11 +3670,13 @@ window.__ModuleLoader__.load({
3393
3670
 
3394
3671
  const toggleDirection = () => {
3395
3672
  const nextDir = directionRef.current === 'tb' ? 'lr' : 'tb';
3396
- setDirection(nextDir);
3397
3673
  const curNodes = nodesRef.current;
3398
3674
  const curEdges = edgesRef.current;
3675
+ if (curNodes.length) pushSnapshot();
3676
+ directionRef.current = nextDir;
3677
+ setDirection(nextDir);
3678
+ saveDefaultDirection(nextDir);
3399
3679
  if (curNodes.length) {
3400
- pushSnapshot();
3401
3680
  const next = layoutGraph(curNodes, curEdges, nextDir);
3402
3681
  setNodes(next);
3403
3682
  setTimeout(() => fitView(next), 0);
@@ -3431,7 +3710,7 @@ window.__ModuleLoader__.load({
3431
3710
  const { runs: _runs, ...rest } = n;
3432
3711
  return rest;
3433
3712
  });
3434
- const text = JSON.stringify({ nodes: cleanNodes, edges: edgesRef.current }, null, 2);
3713
+ const text = JSON.stringify({ nodes: cleanNodes, edges: edgesRef.current, direction: directionRef.current }, null, 2);
3435
3714
  const fallbackCopy = () => {
3436
3715
  try {
3437
3716
  const ta = document.createElement('textarea');
@@ -3588,8 +3867,12 @@ window.__ModuleLoader__.load({
3588
3867
  if (current.length <= 2) return;
3589
3868
  pushSnapshot();
3590
3869
  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)));
3870
+ const nextNodes = nodesRef.current.map((n) => (n.id === node.id ? { ...n, branches: next } : n));
3871
+ const remainingEdges = edgesRef.current.filter((e) => !(e.from === node.id && e.branch === branchId));
3872
+ const { edges: cleaned } = pruneInvalidLoopEdges(nextNodes, remainingEdges);
3873
+ setNodes(nextNodes);
3874
+ setEdges(cleaned);
3875
+ setLoopEditEdgeId(null);
3593
3876
  };
3594
3877
 
3595
3878
  const onOutputDown = (e, id, type, branch) => {
@@ -3727,8 +4010,7 @@ window.__ModuleLoader__.load({
3727
4010
  ev.preventDefault();
3728
4011
  ev.stopPropagation();
3729
4012
  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 };
4013
+ panDrag.current = { lastX: ev.clientX, lastY: ev.clientY };
3732
4014
  setPanning(true);
3733
4015
  setDragging(true);
3734
4016
  };
@@ -3894,11 +4176,27 @@ window.__ModuleLoader__.load({
3894
4176
  if (!dragging) return undefined;
3895
4177
  const move = (ev) => onCanvasMove(ev);
3896
4178
  const up = (ev) => onCanvasUp(ev);
4179
+ const cancelDrag = () => {
4180
+ panDrag.current = null;
4181
+ nodeDrag.current = null;
4182
+ rightClickRef.current = null;
4183
+ cutRef.current = null;
4184
+ cutHits.current = new Set();
4185
+ pendingHandledRef.current = false;
4186
+ setPanning(false);
4187
+ setCutPath([]);
4188
+ setCutVictims([]);
4189
+ setMarquee(null);
4190
+ setPending(null);
4191
+ setDragging(false);
4192
+ };
3897
4193
  window.addEventListener('mousemove', move);
3898
4194
  window.addEventListener('mouseup', up);
4195
+ window.addEventListener('blur', cancelDrag);
3899
4196
  return () => {
3900
4197
  window.removeEventListener('mousemove', move);
3901
4198
  window.removeEventListener('mouseup', up);
4199
+ window.removeEventListener('blur', cancelDrag);
3902
4200
  };
3903
4201
  }, [dragging, marquee, pending]);
3904
4202
 
@@ -3931,10 +4229,9 @@ window.__ModuleLoader__.load({
3931
4229
 
3932
4230
  const onCanvasMove = (e) => {
3933
4231
  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 });
4232
+ const stepped = applyPanStep(viewRef.current, panDrag.current, e.clientX, e.clientY);
4233
+ panDrag.current = stepped.pan;
4234
+ commitView(stepped.view);
3938
4235
  return;
3939
4236
  }
3940
4237
  if (rightClickRef.current && !rightClickRef.current.moved) {
@@ -3953,7 +4250,11 @@ window.__ModuleLoader__.load({
3953
4250
  const drag = nodeDrag.current;
3954
4251
  const dx = p.x - drag.startX;
3955
4252
  const dy = p.y - drag.startY;
3956
- if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) drag.moved = true;
4253
+ // Snapshot once on first actual move (>0.5px) so pure selection clicks do not pollute undo history.
4254
+ if (!drag.moved && (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5)) {
4255
+ pushSnapshot();
4256
+ drag.moved = true;
4257
+ }
3957
4258
  const byId = new Map(drag.origins.map((o) => [o.id, o]));
3958
4259
  setNodes((ns) => ns.map((n) => {
3959
4260
  const origin = byId.get(n.id);
@@ -4105,11 +4406,22 @@ window.__ModuleLoader__.load({
4105
4406
  const savePresetNow = () => {
4106
4407
  const name = presetName.trim();
4107
4408
  if (!name) { flash(t('needName')); return; }
4108
- if (Object.prototype.hasOwnProperty.call(presets, name)) {
4409
+ const latest = loadPresets();
4410
+ if (Object.prototype.hasOwnProperty.call(latest, name)) {
4411
+ setPresets(latest);
4109
4412
  flash('"' + name + '" ' + t('dupName'));
4110
4413
  return;
4111
4414
  }
4112
- const next = { ...presets, [name]: { nodes, edges } };
4415
+ const savedNodes = nodesRef.current.map((n) => ({
4416
+ ...n,
4417
+ ...(Array.isArray(n.refs) ? { refs: n.refs.slice() } : null),
4418
+ ...(Array.isArray(n.branches) ? { branches: n.branches.map((b) => ({ ...b })) } : null),
4419
+ }));
4420
+ const savedEdges = edgesRef.current.map((e) => ({ ...e }));
4421
+ const next = {
4422
+ ...latest,
4423
+ [name]: { nodes: savedNodes, edges: savedEdges, direction: directionRef.current },
4424
+ };
4113
4425
  if (!savePresets(next)) { flash(t('saveFailed')); return; }
4114
4426
  setPresets(next);
4115
4427
  setPresetName('');
@@ -4131,6 +4443,12 @@ window.__ModuleLoader__.load({
4131
4443
  if (typeof doc.enabled === 'boolean') {
4132
4444
  setEnabled(doc.enabled);
4133
4445
  }
4446
+ const hasExplicitDir = !merge && (doc.direction === 'tb' || doc.direction === 'lr');
4447
+ const allHaveCoords = !merge && doc.nodes.every((n) => n && typeof n.x === 'number' && typeof n.y === 'number');
4448
+ if (hasExplicitDir) {
4449
+ directionRef.current = doc.direction;
4450
+ setDirection(doc.direction);
4451
+ }
4134
4452
  const removedNodes = new Set(doc.removeNodes || []);
4135
4453
  const rawIncomingEdges = Array.isArray(doc.edges) ? doc.edges : [];
4136
4454
  setNodes((existing) => {
@@ -4172,10 +4490,19 @@ window.__ModuleLoader__.load({
4172
4490
  addedCount += 1;
4173
4491
  }
4174
4492
  placed.set(n.id, { x, y });
4493
+ if (merge && fromRemote) {
4494
+ // Host merge patches deliver complete canonical node fields; explicitly clear
4495
+ // optional fields that were deleted by `canvas_patch` while keeping visual state.
4496
+ const merged = { ...prev, ...n, x, y };
4497
+ if (!('refs' in n)) delete merged.refs;
4498
+ if (!('branches' in n)) delete merged.branches;
4499
+ if (!('multiMatch' in n)) delete merged.multiMatch;
4500
+ return merged;
4501
+ }
4175
4502
  return { ...prev, ...n, x, y };
4176
4503
  });
4177
4504
  if (!merge) {
4178
- return isTB ? layoutGraph(incoming, rawIncomingEdges, 'tb') : incoming;
4505
+ return (isTB && !(hasExplicitDir && allHaveCoords)) ? layoutGraph(incoming, rawIncomingEdges, 'tb') : incoming;
4179
4506
  }
4180
4507
  const touched = new Set(incoming.map((n) => n.id));
4181
4508
  const kept = existing
@@ -4358,20 +4685,31 @@ window.__ModuleLoader__.load({
4358
4685
  };
4359
4686
 
4360
4687
  const applyPreset = (name) => {
4361
- const preset = presets[name];
4688
+ const latest = loadPresets();
4689
+ const preset = latest[name] || presets[name];
4362
4690
  if (!preset || !Array.isArray(preset.nodes) || !Array.isArray(preset.edges)) { flash(t('invalidPreset')); return; }
4691
+ const clonedNodes = preset.nodes.map((n) => ({
4692
+ ...n,
4693
+ ...(Array.isArray(n.refs) ? { refs: n.refs.slice() } : null),
4694
+ ...(Array.isArray(n.branches) ? { branches: n.branches.map((b) => ({ ...b })) } : null),
4695
+ }));
4696
+ const clonedEdges = preset.edges.map((e) => ({ ...e }));
4363
4697
  pushSnapshot();
4698
+ if (preset.direction === 'tb' || preset.direction === 'lr') {
4699
+ directionRef.current = preset.direction;
4700
+ setDirection(preset.direction);
4701
+ }
4364
4702
  if (enabled) {
4365
4703
  skipDirtyOnce.current = true;
4366
- pushPlan(true, preset.nodes, preset.edges);
4704
+ pushPlan(true, clonedNodes, clonedEdges);
4367
4705
  }
4368
- setNodes(preset.nodes);
4369
- setEdges(preset.edges);
4706
+ setNodes(clonedNodes);
4707
+ setEdges(clonedEdges);
4370
4708
  setSelectedIds([]);
4371
4709
  snapshotStaleCatalog();
4372
4710
  setRunsById({});
4373
4711
  setPresetOpen(null);
4374
- setTimeout(() => fitView(preset.nodes), 0);
4712
+ setTimeout(() => fitView(clonedNodes), 0);
4375
4713
  flash(t('loadedPreset') + ': ' + name);
4376
4714
  };
4377
4715
 
@@ -4395,7 +4733,8 @@ window.__ModuleLoader__.load({
4395
4733
  };
4396
4734
 
4397
4735
  const deletePreset = (name) => {
4398
- const next = { ...presets };
4736
+ const latest = loadPresets();
4737
+ const next = { ...latest };
4399
4738
  delete next[name];
4400
4739
  savePresets(next);
4401
4740
  setPresets(next);
@@ -4428,12 +4767,6 @@ window.__ModuleLoader__.load({
4428
4767
  const ids = ((hit && hit.efforts) || []).map((e) => e.id);
4429
4768
  return ['', ...(ids.length ? ids : REASONING_FALLBACK)];
4430
4769
  };
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
4770
 
4438
4771
  const scopeToggle = (node) => {
4439
4772
  const wide = (node.preset || 'standard') !== 'minimal';
@@ -4671,50 +5004,31 @@ window.__ModuleLoader__.load({
4671
5004
  const soloLeadIds = soloLeadNodeIds(nodes, edges);
4672
5005
  const deadEndIds = deadEndNodeIds(nodes, edges);
4673
5006
 
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
- }
5007
+ // Lead nodes are never spawned, so their status is derived via `deriveLeadStatuses`,
5008
+ // honoring authoritative backend `runState.status` (`halted` / `done` / `need-lead`).
5009
+ const { leadReadyIds, leadDoneIds } = deriveLeadStatuses({
5010
+ enabled,
5011
+ nodes,
5012
+ edges,
5013
+ statusById,
5014
+ sessionRunning,
5015
+ runState,
5016
+ reachableIds,
5017
+ });
5018
+ const activeWaitingLead = runState
5019
+ ? (runState.waitingLead || null)
5020
+ : (leadReadyIds.size > 0 ? { id: Array.from(leadReadyIds)[0] } : null);
5021
+ const runningNodesCount = enabled
5022
+ ? Object.values(statusById).filter((s) => s === 'running').length
5023
+ : 0;
5024
+ const stopBtn = stopButtonState({
5025
+ sessionRunning,
5026
+ runningNodesCount,
5027
+ waitingLead: activeWaitingLead,
5028
+ triggering: runTriggering,
5029
+ stopping,
5030
+ lang,
5031
+ });
4718
5032
 
4719
5033
  const decisionsById = (enabled && runState && runState.decisions && typeof runState.decisions === 'object')
4720
5034
  ? runState.decisions
@@ -5146,6 +5460,39 @@ window.__ModuleLoader__.load({
5146
5460
  h('button', { style: S.btn, onClick: () => addNode('lead'), type: 'button' }, t('addLead')),
5147
5461
  h('button', { style: S.btn, onClick: () => addNode('condition'), type: 'button' }, t('addCond')),
5148
5462
  h('span', { style: S.toolSep }),
5463
+ (() => {
5464
+ const canUndo = historyRef.current.length > 0;
5465
+ const canRedo = redoRef.current.length > 0;
5466
+ const undoHint = shortcuts.undo ? (' (' + shortcuts.undo + ')') : '';
5467
+ const redoHint = shortcuts.redo ? (' (' + shortcuts.redo + ')') : '';
5468
+ return h(React.Fragment, null,
5469
+ h('button', {
5470
+ style: {
5471
+ ...S.btn,
5472
+ padding: '4px 6px',
5473
+ opacity: canUndo ? 1 : 0.42,
5474
+ cursor: canUndo ? 'pointer' : 'default',
5475
+ },
5476
+ disabled: !canUndo,
5477
+ onClick: undo,
5478
+ type: 'button',
5479
+ title: t('tipUndo') + undoHint,
5480
+ }, '↶'),
5481
+ h('button', {
5482
+ style: {
5483
+ ...S.btn,
5484
+ padding: '4px 6px',
5485
+ opacity: canRedo ? 1 : 0.42,
5486
+ cursor: canRedo ? 'pointer' : 'default',
5487
+ },
5488
+ disabled: !canRedo,
5489
+ onClick: redo,
5490
+ type: 'button',
5491
+ title: t('tipRedo') + redoHint,
5492
+ }, '↷'),
5493
+ );
5494
+ })(),
5495
+ h('span', { style: S.toolSep }),
5149
5496
  h('button', {
5150
5497
  style: enabled && dirty ? S.btnDirty : S.btn,
5151
5498
  onClick: () => pushPlan(enabled),
@@ -5171,8 +5518,11 @@ window.__ModuleLoader__.load({
5171
5518
  onClick: (e) => {
5172
5519
  const next = presetOpen === 'menu' ? null : 'menu';
5173
5520
  if (next) {
5521
+ refreshPresets(false);
5174
5522
  setMenuOpen(false);
5175
5523
  setCtxMenu(null);
5524
+ setLoopEditEdgeId(null);
5525
+ setOpenModelFor(null);
5176
5526
  const rootRect = rootElRef.current && rootElRef.current.getBoundingClientRect();
5177
5527
  const btnRect = e.currentTarget && e.currentTarget.getBoundingClientRect();
5178
5528
  setPresetAlign(dropdownAlign(btnRect, rootRect, 248));
@@ -5219,17 +5569,45 @@ window.__ModuleLoader__.load({
5219
5569
  onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
5220
5570
  onClick: () => clearCanvas(),
5221
5571
  }, 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'; },
5572
+ h('div', {
5573
+ style: { ...S.menuHead, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '6px' },
5574
+ },
5575
+ h('span', null, t('myPresets')),
5576
+ h('button', {
5577
+ type: 'button',
5578
+ title: t('refreshPresetsTip'),
5579
+ style: {
5580
+ padding: '0 4px', borderRadius: '4px', border: '1px solid ' + C.border,
5581
+ background: 'transparent', color: C.dim, fontSize: '10px', lineHeight: '14px',
5582
+ cursor: 'pointer', flex: '0 0 auto',
5229
5583
  },
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
- ))
5584
+ onMouseEnter: (e) => { e.currentTarget.style.color = C.text; e.currentTarget.style.borderColor = C.accent; },
5585
+ onMouseLeave: (e) => { e.currentTarget.style.color = C.dim; e.currentTarget.style.borderColor = C.border; },
5586
+ onClick: (e) => { e.stopPropagation(); refreshPresets(true); },
5587
+ }, '↻'),
5588
+ ),
5589
+ names.length
5590
+ ? names.map((name) => {
5591
+ const pItem = presets[name];
5592
+ const pDir = pItem && (pItem.direction === 'tb' || pItem.direction === 'lr') ? pItem.direction : '';
5593
+ return h('div', {
5594
+ key: name,
5595
+ style: S.presetRow,
5596
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
5597
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
5598
+ },
5599
+ h('span', { style: S.presetRowText, onClick: () => applyPreset(name) }, name),
5600
+ pDir && h('span', {
5601
+ style: {
5602
+ flex: '0 0 auto', fontSize: '9px', lineHeight: '13px',
5603
+ padding: '0 4px', borderRadius: '3px',
5604
+ border: '1px solid ' + C.border, color: C.dim,
5605
+ },
5606
+ title: pDir === 'tb' ? t('dirTB') : t('dirLR'),
5607
+ }, pDir === 'tb' ? t('presetDirTB') : t('presetDirLR')),
5608
+ h('button', { style: S.presetDel, type: 'button', title: t('del'), onClick: () => deletePreset(name) }, '×'),
5609
+ );
5610
+ })
5233
5611
  : h('div', { style: S.presetEmpty }, t('presetEmpty')),
5234
5612
  h('div', { style: S.menuHead }, t('builtinTemplates')),
5235
5613
  templates.map((tpl) => h('div', {
@@ -5252,6 +5630,8 @@ window.__ModuleLoader__.load({
5252
5630
  if (next) {
5253
5631
  setPresetOpen(null);
5254
5632
  setCtxMenu(null);
5633
+ setLoopEditEdgeId(null);
5634
+ setOpenModelFor(null);
5255
5635
  const rootRect = rootElRef.current && rootElRef.current.getBoundingClientRect();
5256
5636
  const btnRect = e.currentTarget && e.currentTarget.getBoundingClientRect();
5257
5637
  setMenuAlign(dropdownAlign(btnRect, rootRect, 204));
@@ -5483,31 +5863,45 @@ window.__ModuleLoader__.load({
5483
5863
  if (tag !== 'INPUT' && tag !== 'TEXTAREA') e.preventDefault();
5484
5864
  },
5485
5865
  },
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,
5866
+ h('div', { style: S.floatTopLeft, onMouseDown: (e) => e.stopPropagation() },
5867
+ h('button', {
5506
5868
  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*/, '')),
5869
+ ? {
5870
+ ...S.floatOn,
5871
+ display: 'inline-flex',
5872
+ alignItems: 'center',
5873
+ gap: '6px',
5874
+ lineHeight: '14px',
5875
+ boxShadow: fxLevel === 'vivid'
5876
+ ? '0 0 14px rgba(47,129,247,0.35), 0 4px 14px rgba(0,0,0,0.35)'
5877
+ : S.floatOn.boxShadow,
5878
+ }
5879
+ : { ...S.floatOff, display: 'inline-flex', alignItems: 'center', gap: '6px', lineHeight: '14px' },
5880
+ type: 'button',
5881
+ onClick: toggleEnabled,
5882
+ title: t('tipToggle'),
5883
+ },
5884
+ h('span', {
5885
+ className: enabled && fxLevel === 'vivid' ? 'dsh-wc-dot-live' : undefined,
5886
+ style: enabled
5887
+ ? { width: '7px', height: '7px', borderRadius: '50%', background: C.accent, flex: '0 0 auto' }
5888
+ : { width: '7px', height: '7px', borderRadius: '50%', border: '1.5px solid ' + C.dim, boxSizing: 'border-box', flex: '0 0 auto' },
5889
+ }),
5890
+ h('span', null, (enabled ? t('enabled') : t('disabled')).replace(/^[●○]\s*/, '')),
5891
+ ),
5892
+ stopBtn.visible && h('button', {
5893
+ type: 'button',
5894
+ disabled: stopBtn.disabled,
5895
+ style: {
5896
+ ...S.floatStop,
5897
+ opacity: stopBtn.disabled ? 0.6 : 1,
5898
+ cursor: stopBtn.disabled ? 'not-allowed' : 'pointer',
5899
+ },
5900
+ title: stopBtn.title,
5901
+ onMouseEnter: (e) => { if (!stopBtn.disabled) e.currentTarget.style.background = 'rgba(229,83,75,0.18)'; },
5902
+ onMouseLeave: (e) => { e.currentTarget.style.background = C.elevated; },
5903
+ onClick: () => { if (!stopBtn.disabled) stopWorkflow(); },
5904
+ }, stopBtn.label),
5511
5905
  ),
5512
5906
  addMenu && (() => {
5513
5907
  const lf = addMenu.linkFrom || null;
@@ -5801,17 +6195,6 @@ window.__ModuleLoader__.load({
5801
6195
  const isEntry = node.id === 'lead';
5802
6196
  const isLeadKind = node.kind === 'lead';
5803
6197
  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
6198
  const isOrphan = node.id !== 'lead' && !reachableIds.has(node.id);
5816
6199
  const isSoloLead = soloLeadIds.has(node.id);
5817
6200
  const isDeadEnd = deadEndIds.has(node.id);
@@ -5849,9 +6232,15 @@ window.__ModuleLoader__.load({
5849
6232
  const nodeAttempt = nodeAttemptsMap[node.id] || null;
5850
6233
  const condDecision = isCondKind ? (decisionsById[node.id] || null) : null;
5851
6234
  const verdictInfo = condDecision ? conditionVerdictSummary(condDecision, lang) : null;
6235
+ // Lift the whole card to zIndex 40 while any popover or dropdown is open so
6236
+ // later-DOM cards below (especially in vertical layout) and loop pills never paint over it.
5852
6237
  const hasOpenPopover = decisionViewFor === node.id
5853
6238
  || refsEditFor === node.id
5854
6239
  || roleEditFor === node.id
6240
+ || openModelFor === node.id
6241
+ || openModelFor === ('r:' + node.id)
6242
+ || openModelFor === ('f:' + node.id)
6243
+ || openModelFor === ('m:' + node.id)
5855
6244
  || (typeof roleEditFor === 'string' && roleEditFor.includes(':' + node.id + ':'));
5856
6245
  return h('div', {
5857
6246
  key: node.id,
@@ -5892,14 +6281,11 @@ window.__ModuleLoader__.load({
5892
6281
  h('div', { style: S.bandDivider }),
5893
6282
  isEntry
5894
6283
  ? (() => {
5895
- const waitingLead = runState
5896
- ? (runState.waitingLead || null)
5897
- : (leadReadyIds.size > 0 ? { id: Array.from(leadReadyIds)[0] } : null);
5898
6284
  const btn = entryRunButtonState({
5899
6285
  enabled,
5900
6286
  task: node.task || '',
5901
6287
  sessionRunning,
5902
- waitingLead,
6288
+ waitingLead: activeWaitingLead,
5903
6289
  triggering: runTriggering,
5904
6290
  lang,
5905
6291
  });
@@ -5913,35 +6299,67 @@ window.__ModuleLoader__.load({
5913
6299
  const borderColor = isReady
5914
6300
  ? 'rgba(63,185,80,0.6)'
5915
6301
  : (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,
6302
+ const bottomOffset = direction === 'tb' ? '28px' : '4px';
6303
+ return h('div', {
5919
6304
  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,
6305
+ position: 'absolute',
6306
+ left: '10px',
6307
+ bottom: bottomOffset,
6308
+ zIndex: 7,
6309
+ display: 'inline-flex',
6310
+ alignItems: 'center',
6311
+ gap: '4px',
5928
6312
  },
5929
- title: btn.title,
5930
6313
  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
6314
  },
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,
6315
+ h('button', {
6316
+ type: 'button',
6317
+ disabled: btn.disabled,
6318
+ style: {
6319
+ ...S.statusBtn,
6320
+ position: 'static',
6321
+ color,
6322
+ background: bg,
6323
+ borderColor,
6324
+ opacity: btn.state === 'disabled' ? 0.55 : 1,
6325
+ cursor: btn.disabled ? 'not-allowed' : 'pointer',
6326
+ fontWeight: isReady ? 600 : 500,
6327
+ },
6328
+ title: btn.title,
6329
+ onMouseEnter: (e) => { if (!btn.disabled) e.currentTarget.style.background = 'rgba(63,185,80,0.24)'; },
6330
+ onMouseLeave: (e) => { e.currentTarget.style.background = bg; },
6331
+ onClick: (e) => { e.stopPropagation(); if (!btn.disabled) runFromEntry(); },
6332
+ },
6333
+ isRun && h('span', {
6334
+ className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
6335
+ style: { width: '6px', height: '6px', borderRadius: '50%', background: color, flex: '0 0 auto' },
6336
+ }),
6337
+ btn.label,
6338
+ ),
6339
+ stopBtn.visible && h('button', {
6340
+ type: 'button',
6341
+ disabled: stopBtn.disabled,
6342
+ style: {
6343
+ ...S.statusBtn,
6344
+ position: 'static',
6345
+ padding: '1px 5px',
6346
+ color: '#e5534b',
6347
+ background: 'rgba(229,83,75,0.14)',
6348
+ borderColor: 'rgba(229,83,75,0.65)',
6349
+ opacity: stopBtn.disabled ? 0.6 : 1,
6350
+ cursor: stopBtn.disabled ? 'not-allowed' : 'pointer',
6351
+ fontWeight: 600,
6352
+ },
6353
+ title: stopBtn.title,
6354
+ onMouseEnter: (e) => { if (!stopBtn.disabled) e.currentTarget.style.background = 'rgba(229,83,75,0.24)'; },
6355
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'rgba(229,83,75,0.14)'; },
6356
+ onClick: (e) => { e.stopPropagation(); if (!stopBtn.disabled) stopWorkflow(); },
6357
+ }, stopBtn.disabled ? '…' : '⏹'),
5940
6358
  );
5941
6359
  })()
5942
6360
  : isDeadEnd
5943
6361
  ? h('div', {
5944
- style: S.warnChip,
6362
+ style: { ...S.warnChip, bottom: (direction === 'tb' && !isCondKind) ? '28px' : '5px' },
5945
6363
  title: t('tipDeadEnd'),
5946
6364
  onMouseDown: (e) => e.stopPropagation(),
5947
6365
  }, '⚠ ', t('stDeadEnd'))
@@ -6286,13 +6704,14 @@ window.__ModuleLoader__.load({
6286
6704
  scope.effect(() => scope.slots.inject('sidebar.right.pane.tab', () => scope.slots.register({
6287
6705
  name: 'sidebar.right.pane.tab',
6288
6706
  key: TAB_ID,
6289
- }, (props) => h(CanvasBoundary, null, h(WorkflowCanvas, props)))), 'workflow-canvas: tab body');
6707
+ // Key by sessionId so keepMounted reuse across session switches can never overwrite another session's storage.
6708
+ }, (props) => h(CanvasBoundary, null, h(WorkflowCanvas, { ...props, key: (props && props.sessionId) || '__global__' })))), 'workflow-canvas: tab body');
6290
6709
  });
6291
6710
  } catch (error) {
6292
6711
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
6293
6712
  }
6294
6713
  },
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 },
6714
+ __test: { topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, applyPanStep, normalizeDirection, loadDefaultDirection, saveDefaultDirection, loadPresets, savePresets, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, distanceToEdge, edgeCurve, compatibleTargetsForWire, conditionVerdictSummary, entryRunButtonState, stopButtonState, deriveLeadStatuses, outputSocketX, inputSocketPos, outputSocketPos, normalizeRefsUI, clampMenuPos, cloneSelection, nextSelectionOnNodeClick, DEFAULT_SHORTCUTS, normalizeShortcut, formatShortcutFromEvent, matchesShortcut, applyShortcutBinding, normalizeMaxIterationsUI, loopMemberIdsUI, loopGroupsForUI, pruneInvalidLoopEdges, canLinkAsLoop, analyzeLoopSelection, loopEdgeArc },
6296
6715
  };
6297
6716
  },
6298
6717
  });