dsh-workflow-canvas 1.4.1 → 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',
@@ -51,6 +53,9 @@ window.__ModuleLoader__.load({
51
53
  const ROW_H = 18;
52
54
  const COND_ROW_H = 20;
53
55
  const BRANCH_COLORS = ['#3fb950', '#e5534b', '#2f81f7', '#d29922', '#a371f7', '#39c5cf', '#f778ba', '#f0883e'];
56
+ const LOOP_COLORS = ['#f0883e', '#39c5cf', '#f778ba', '#a371f7', '#d29922'];
57
+ const MAX_LOOP_ITERATIONS = 10;
58
+ const DEFAULT_LOOP_ITERATIONS = 3;
54
59
  const CONTENT_W = 2400;
55
60
  const CONTENT_H = 1600;
56
61
  /** World origin offset: keeps negative node coordinates inside the scroll area. */
@@ -116,7 +121,7 @@ window.__ModuleLoader__.load({
116
121
  const I18N = {
117
122
  zh: {
118
123
  addAgent: '+ 子代理', addLead: '+ Lead', addCond: '+ 条件', undo: '↶ 撤销', redo: '↷ 重做', sync: '↥ 同步',
119
- enabled: '● 已启用', disabled: '○ 已禁用', presetName: '预设名', save: '☆ 保存',
124
+ enabled: '● 已启用', disabled: '○ 已禁用', save: '☆ 保存',
120
125
  presets: '☰ 预设', unsaved: '有未同步改动', synced: '已同步',
121
126
  pickModel: '选择模型', loadingModels: '加载中…', defaultEffort: '默认',
122
127
  leadThis: 'Lead(本对话)',
@@ -125,8 +130,6 @@ window.__ModuleLoader__.load({
125
130
  tipCondTrue: '条件满足(pass=true)时走这条分支,连到任意下游节点左侧入口',
126
131
  tipCondFalse: '条件不满足(pass=false)时走这条分支,连到任意下游节点左侧入口',
127
132
  tipBranchOut: '命中该分支时走这条连线,拖到任意下游节点左侧入口',
128
- branchTrue: '是',
129
- branchFalse: '否',
130
133
  addBranch: '+ 分支',
131
134
  branchPh: '分支名',
132
135
  delBranchTip: '删除该分支(至少保留 2 路)',
@@ -148,11 +151,10 @@ window.__ModuleLoader__.load({
148
151
  syncBadFile: '文件内容无效',
149
152
  generated: '已从对话生成画布',
150
153
  dupName: '已存在,请换一个名字',
151
- guideDesc: '画一张子代理流程图',
152
154
  model: '模型', reason: '推理', role: '分工', task: '任务', taskPh: '本次任务:例如把这批反馈归类并给出建议',
153
155
  rolePhLead: '我自己这一步做什么', rolePhAgent: '这个子代理做什么',
154
- memory: '记忆', scope: '能力', retry: '重试', jsonOut: 'JSON 输出',
155
- sep: ': ', on: '开', off: '关', allTools: '默认(全部工具)', none: '无',
156
+ memory: '记忆', scope: '能力',
157
+ sep: ': ', on: '开', off: '关', none: '无',
156
158
  scopeMinimal: 'minimal(只读思考)', scopeStandard: 'standard(全部工具)',
157
159
  fallbackModel: '备用',
158
160
  stPending: '未执行', stRunning: '进行中', stDone: '已完成', stFailed: '失败',
@@ -161,21 +163,19 @@ window.__ModuleLoader__.load({
161
163
  presetSaveTitle: '保存当前画布(可在新会话一键载入)',
162
164
  presetNamePh: '起个名字后回车保存…',
163
165
  myPresets: '我的预设(跨会话复用)',
164
- needName: '请先给预设起个名字', duplicate: '已存在,请换一个名字',
166
+ needName: '请先给预设起个名字',
165
167
  savedPreset: '已保存预设', saveFailed: '保存失败(存储不可用)',
166
168
  loadedPreset: '已载入预设', invalidPreset: '预设内容无效', deletedPreset: '已删除预设',
167
169
  syncFailed: '同步失败', upToDate: '已是最新', syncedToHost: '已同步到 Host',
168
170
  syncedWithStdWarn: '已同步(含可写/命令节点,请确认主对话权限已放开)',
169
171
  cannotOpen: '无法打开会话', undoDone: '已撤销', undoNone: '没有可撤销的操作', redoDone: '已重做', redoNone: '没有可重做的操作',
170
- leadLocked: '入口 Lead 不能删除', modelsMissing: '模型列表未加载',
172
+ leadLocked: '入口 Lead 不能删除',
171
173
  tipLead: 'Lead 步骤在对话里执行,画布不追踪其状态',
172
174
  tipOrphan: '未连线:运行时会被跳过', tipStatus: '子代理节点的运行状态',
173
- tipZoom: '滚轮缩放(以光标为中心)',
174
175
  tipResetZoom: '点击回到 100% 并聚焦 Lead;左右拖拽可连续缩放',
175
176
  tipLocate: '自适应缩放并居中,让所有节点完整显示在视野内',
176
177
  locate: '⊡ 全览',
177
178
  importBtn: '⇩ 导入',
178
- tipImport: '从剪贴板导入模型生成的画布(先复制聊天里的画布 JSON)',
179
179
  importOk: '已导入画布,共 ',
180
180
  tipMore: '更多',
181
181
  help: '使用说明',
@@ -187,18 +187,18 @@ window.__ModuleLoader__.load({
187
187
  helpBody: [
188
188
  '1. 在入口 Lead 里写「本次任务」,这是整张图的总目标。',
189
189
  '2. 点「+ 子代理 / + Lead / + 条件」加节点,从右侧输出口拖到另一个节点左侧输入口即可连线。',
190
- '3. 输出口决定连线类型:prompt(灰,纯文本)、structured(蓝,JSON)、session(紫,复用上游会话);条件节点支持多路分支(单选 switch/case 或多选并行,全不满足时跳过中间分支直达最近 Lead)。',
190
+ '3. 输出口决定连线类型:prompt(灰,纯文本)、structured(蓝,JSON)、session(紫,复用上游会话);条件节点支持多路分支,并可将分支连回上游(或多选节点右键「↺ 设为回环」)实现带反馈的受控重试(点 ↺ 徽章可调 1–10 次,超限自动交 Lead 熔断)。',
191
191
  '4. 节点左侧为统一通用输入口,可直接接收任意颜色的连线;拖已连接的左口可断开最近一条连线。',
192
192
  '5. 每个节点可设模型、推理强度、能力范围、备用模型、是否记忆;复杂任务/分工/条件可点 ⤢ 展开大框编辑。',
193
- '6. 连好后点「● 已启用」,然后对对话说「跑一次」,由我调用执行。',
194
- '7. 遇到 Lead 节点会暂停,我做完再把结果交回去继续。',
193
+ '6. 连好后点左上角「● 已启用」,可直接点入口节点「▶ 运行」或在对话说「跑一次」开跑;运行中或停在「⏸ 待拍板」时,点左上角或入口节点旁的「⏹ 终止」即可一键中止全部子代理并解除等待状态。',
194
+ '7. 遇到 Lead 节点会暂停,我做完再把结果交回去继续(或在对话里说「取消」即可结束流程)。',
195
195
  '8. 没连线的节点显示为虚线,运行时会被跳过。',
196
- '9. 右键单击节点 / 连线 / 空白处可弹出快捷菜单(含线上插点、复制删除、新建节点等);按住右键划过连线可切断(可在「⋯」开关)。',
197
- '10. 点右上角「☰ 预设」顶部即可保存当前画布,开新对话时一键载入跨会话复用。',
196
+ '9. 右键单击节点 / 连线 / 空白处可弹出快捷菜单(含线上插点、设为回环、复制删除、新建节点等);按住右键划过连线可切断(可在「⋯」开关)。',
197
+ '10. 点右上角「☰ 预设」可保存当前画布(连同横/竖排方向),多会话实时同步并支持点 ↻ 刷新;切换横/竖排会自动记住默认偏好供新会话沿用。',
198
198
  '11. 你可以直接让我改画布:说「把那三个节点的分工改成…」,我会就地修改,不动你摆的位置。',
199
199
  '12. session 线连到 Lead 时,我会在暂停那步拿到那个子代理的会话,可以继续追问它。',
200
200
  '13. 按住鼠标中键(或空格 + 左键)拖动画布平移;点击子代理节点左下角状态可直达它的对话记录。',
201
- '14. 快捷键:默认 Shift+A 新建节点,Shift+D 复制节点与连线,Delete 删除,Ctrl+Z 撤销,Esc 关闭弹窗(可在「⋯ → 快捷键设置」自定义)。',
201
+ '14. 快捷键与历史:顶栏提供 ↶ 撤销 / ↷ 重做按钮(支持撤销节点移动与横竖排切换);默认 Shift+A 新建,Shift+D 复制,Delete 删除,Ctrl+Z / Ctrl+Shift+Z(Ctrl+Y)撤销重做,Esc 关闭弹窗(可在「⋯ → 快捷键设置」自定义)。',
202
202
  ].join('\n'),
203
203
  openChat: '会话',
204
204
  tipOpenRun: '点击打开该子代理的对话记录',
@@ -224,9 +224,13 @@ window.__ModuleLoader__.load({
224
224
  verdictFallback: '已跳过中间分支 → 转交 Lead:',
225
225
  verdictNoReason: '(裁判未附额外说明)',
226
226
  tipVerdictChip: '点击查看完整判断理由',
227
- runBtn: '▶ 运行',
228
- runBtnRunning: '进行中…',
229
- runBtnWaiting: '⏸ 等待决策',
227
+ stopSent: '已发送终止指令',
228
+ stopWaitingDone: '已结束等待拍板并终止流程',
229
+ stopFailed: '终止请求失败',
230
+ refreshPresetsTip: '刷新预设列表',
231
+ presetsRefreshed: '预设列表已刷新',
232
+ presetDirTB: '竖',
233
+ presetDirLR: '横',
230
234
  runStarted: '已向当前会话发起画布执行',
231
235
  runFailed: '发起运行失败',
232
236
  runSendUnavailable: '当前宿主不支持从画布直接发起对话,请在聊天框发送消息启动',
@@ -256,6 +260,19 @@ window.__ModuleLoader__.load({
256
260
  ctxInsertAgent: '在此插入子代理',
257
261
  ctxInsertCond: '在此插入条件节点',
258
262
  ctxLangToggle: '界面语言',
263
+ ctxMakeLoop: '↺ 设为回环',
264
+ ctxMakeLoopAuto: '↺ 设为回环(自动补条件)',
265
+ ctxEditLoop: '↺ 修改回环次数',
266
+ ctxRemoveLoop: '取消回环',
267
+ loopCreated: '已创建回环(默认最多重试 3 次,点 ↺ 徽章可调)',
268
+ loopCreatedAutoCond: '已自动补条件节点并创建回环(点 ↺ 徽章可调次数)',
269
+ loopOverlap: '不支持交叉或重叠的回环',
270
+ loopModalTitle: '最大重试次数 (1–10)',
271
+ loopTipPill: '点击调整最大回环重试次数(1–10)或取消回环',
272
+ loopAutoCondLabel: '是否通过?',
273
+ loopAutoCondRole: '判断上游步骤是否执行成功并达到预期;全部达标走「是」,未达标或报错走「否」回环重做。',
274
+ loopRetryBranch: '重做',
275
+ loopPrunedNotice: '(内部连线断开,已清理失效回环)',
259
276
  shortcutsMenu: '⌨ 快捷键设置',
260
277
  shortcutsTitle: '快捷键设置',
261
278
  shortcutsHint: '点击右侧按键框后按下新组合键;按 Esc 取消录制,点 × 清除绑定。',
@@ -297,12 +314,10 @@ window.__ModuleLoader__.load({
297
314
  tipMemoryPick: '选择要续接的历史子会话(默认自动沿用最新记忆)',
298
315
  tipPreset: '能力范围(点一下切换,受主对话权限上限约束):standard = 全部工具(读写文件、跑命令、子代理、工作流、网页、办公);minimal = 只读思考(文件读写关闭,没有子代理/工作流/网页)',
299
316
  tipFallback: '失败重试:该节点出错时自动换一个模型再跑一次',
300
- tipStructured: 'JSON 输出:要求该节点返回 JSON 对象,structured 连线会把结果作为 JSON 传给下游',
301
- lang: 'ZH',
302
317
  },
303
318
  en: {
304
319
  addAgent: '+ Subagent', addLead: '+ Lead', addCond: '+ Condition', undo: '↶ Undo', redo: '↷ Redo', sync: '↥ Sync',
305
- enabled: '● ON', disabled: '○ OFF', presetName: 'Preset name', save: '☆ Save',
320
+ enabled: '● ON', disabled: '○ OFF', save: '☆ Save',
306
321
  presets: '☰ Presets', unsaved: 'Unsaved changes', synced: 'Synced',
307
322
  pickModel: 'Pick a model', loadingModels: 'Loading…', defaultEffort: 'default',
308
323
  leadThis: 'Lead (this chat)',
@@ -311,8 +326,6 @@ window.__ModuleLoader__.load({
311
326
  tipCondTrue: 'Runs when condition passes (pass=true); connect to any downstream input',
312
327
  tipCondFalse: 'Runs when condition fails (pass=false); connect to any downstream input',
313
328
  tipBranchOut: 'Runs when this branch matches; connect to any downstream input',
314
- branchTrue: 'Yes',
315
- branchFalse: 'No',
316
329
  addBranch: '+ Case',
317
330
  branchPh: 'Branch name',
318
331
  delBranchTip: 'Remove this branch (minimum 2)',
@@ -334,11 +347,10 @@ window.__ModuleLoader__.load({
334
347
  syncBadFile: 'File content is invalid',
335
348
  generated: 'Canvas generated from chat',
336
349
  dupName: 'already exists, pick another name',
337
- guideDesc: 'Sketch a subagent workflow',
338
350
  model: 'Model', reason: 'Reasoning', role: 'Role', task: 'Task', taskPh: 'Task, e.g. classify these reports and suggest actions',
339
351
  rolePhLead: 'What I do in this step', rolePhAgent: 'What this subagent does',
340
- memory: 'Memory', scope: 'Scope', retry: 'Retry', jsonOut: 'JSON out',
341
- sep: ': ', on: 'on', off: 'off', allTools: 'default (all tools)', none: 'none',
352
+ memory: 'Memory', scope: 'Scope',
353
+ sep: ': ', on: 'on', off: 'off', none: 'none',
342
354
  scopeMinimal: 'minimal (read-only thinking)', scopeStandard: 'standard (all tools)',
343
355
  fallbackModel: 'Fallback',
344
356
  stPending: 'Pending', stRunning: 'Running', stDone: 'Done', stFailed: 'Failed',
@@ -347,21 +359,19 @@ window.__ModuleLoader__.load({
347
359
  presetSaveTitle: 'Save current canvas (reuse in any new chat)',
348
360
  presetNamePh: 'Name this canvas…',
349
361
  myPresets: 'Saved presets (all sessions)',
350
- needName: 'Name the preset first', duplicate: 'already exists, pick another name',
362
+ needName: 'Name the preset first',
351
363
  savedPreset: 'Saved preset', saveFailed: 'Save failed (storage unavailable)',
352
364
  loadedPreset: 'Loaded preset', invalidPreset: 'Preset content is invalid', deletedPreset: 'Deleted preset',
353
365
  syncFailed: 'Sync failed', upToDate: 'Already up to date', syncedToHost: 'Synced to host',
354
366
  syncedWithStdWarn: 'Synced (has write/tool nodes — check main chat permission mode)',
355
367
  cannotOpen: 'Cannot open the session', undoDone: 'Undone', undoNone: 'Nothing to undo', redoDone: 'Redone', redoNone: 'Nothing to redo',
356
- leadLocked: 'The entry Lead cannot be deleted', modelsMissing: 'Model list is not loaded',
368
+ leadLocked: 'The entry Lead cannot be deleted',
357
369
  tipLead: 'Lead steps run in the chat; the canvas does not track them',
358
370
  tipOrphan: 'Unlinked: skipped when the canvas runs', tipStatus: 'Subagent run status',
359
- tipZoom: 'Wheel zooms around the cursor',
360
371
  tipResetZoom: 'Click to reset to 100% on Lead; drag left/right to scrub zoom',
361
372
  tipLocate: 'Fit all nodes into the visible canvas',
362
373
  locate: '⊡ Fit',
363
374
  importBtn: '⇩ Import',
364
- tipImport: 'Import a model-generated canvas from the clipboard (copy the canvas JSON from chat first)',
365
375
  importOk: 'Canvas imported, ',
366
376
  tipMore: 'More',
367
377
  help: 'How to use',
@@ -373,18 +383,18 @@ window.__ModuleLoader__.load({
373
383
  helpBody: [
374
384
  '1. Write the overall task in the entry Lead node.',
375
385
  '2. Add nodes with + Subagent / + Lead / + Condition, then drag from a right socket to a left socket.',
376
- '3. Output sockets choose channel type: prompt (grey text), structured (blue JSON), session (purple warm session), or multi-way condition branches (single switch/case or parallel multi-match; jumps to nearest Lead if none match).',
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).',
377
387
  '4. Every node has one universal left input that accepts any incoming wire; drag a connected input away to detach the latest wire.',
378
388
  '5. Each node sets model, reasoning, capability scope, fallback model and memory; click ⤢ to expand a larger editor for long text.',
379
- '6. Press ● ON, then ask in chat to run the canvas.',
380
- '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).',
381
391
  '8. Unlinked nodes are dashed and skipped at run time.',
382
- '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 ⋯).',
383
- '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.',
384
394
  '11. You can ask me to edit the canvas; I patch it in place and keep your layout.',
385
395
  '12. A session link into a Lead step hands me that child agent, so I can follow up with it.',
386
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.',
387
- '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).',
388
398
  ].join('\n'),
389
399
  openChat: 'Chat',
390
400
  tipOpenRun: 'Click to open this subagent conversation',
@@ -410,9 +420,13 @@ window.__ModuleLoader__.load({
410
420
  verdictFallback: 'Skipped branches → Lead: ',
411
421
  verdictNoReason: '(No extra reason provided)',
412
422
  tipVerdictChip: 'Click to inspect verdict reason',
413
- runBtn: '▶ Run',
414
- runBtnRunning: 'Running…',
415
- 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',
416
430
  runStarted: 'Workflow run queued in this chat',
417
431
  runFailed: 'Failed to start run',
418
432
  runSendUnavailable: 'Direct canvas launch is unavailable in this host; send a message in chat to start',
@@ -442,6 +456,19 @@ window.__ModuleLoader__.load({
442
456
  ctxInsertAgent: 'Insert Subagent here',
443
457
  ctxInsertCond: 'Insert Condition here',
444
458
  ctxLangToggle: 'Language',
459
+ ctxMakeLoop: '↺ Create loop',
460
+ ctxMakeLoopAuto: '↺ Create loop (+ Condition)',
461
+ ctxEditLoop: '↺ Edit loop retries',
462
+ ctxRemoveLoop: 'Remove loop',
463
+ loopCreated: 'Loop created (max 3 retries; click ↺ pill to edit)',
464
+ loopCreatedAutoCond: 'Added condition gate & created loop (click ↺ pill to edit)',
465
+ loopOverlap: 'Overlapping or crossing loops are not supported',
466
+ loopModalTitle: 'Max retries (1–10)',
467
+ loopTipPill: 'Click to adjust max loop retries (1–10) or remove loop',
468
+ loopAutoCondLabel: 'Checks Passed?',
469
+ loopAutoCondRole: 'Return pass=true if upstream succeeded and meets expectations; return pass=false to retry.',
470
+ loopRetryBranch: 'Retry',
471
+ loopPrunedNotice: ' (removed broken loop)',
445
472
  shortcutsMenu: '⌨ Shortcuts',
446
473
  shortcutsTitle: 'Keyboard Shortcuts',
447
474
  shortcutsHint: 'Click a key button then press a new combo. Press Esc to cancel, or × to clear.',
@@ -483,8 +510,6 @@ window.__ModuleLoader__.load({
483
510
  tipMemoryPick: 'Pick which past child session to resume (defaults to latest)',
484
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)',
485
512
  tipFallback: 'Retry: when this node fails, rerun it once on another model',
486
- tipStructured: 'JSON output: require an object result; structured links pass it downstream as JSON',
487
- lang: 'EN',
488
513
  },
489
514
  };
490
515
 
@@ -538,32 +563,31 @@ window.__ModuleLoader__.load({
538
563
  width: '1px', height: '16px', background: C.border, opacity: 0.65,
539
564
  flex: '0 0 auto', margin: '0 2px',
540
565
  },
541
- toggleOn: {
542
- padding: '5px 12px', borderRadius: '6px', border: '1px solid ' + C.accent,
543
- background: 'transparent', color: C.accent, fontSize: '12px', fontWeight: 600,
544
- cursor: 'pointer', whiteSpace: 'nowrap',
545
- },
546
- toggleOff: {
547
- padding: '5px 12px', borderRadius: '6px', border: '1px solid ' + C.border,
548
- background: 'transparent', color: C.dim, fontSize: '12px',
549
- cursor: 'pointer', whiteSpace: 'nowrap',
550
- },
551
566
  status: {
552
567
  fontSize: '11px', color: C.dim,
553
- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%',
568
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '160px',
554
569
  },
555
- floatOn: {
570
+ floatTopLeft: {
556
571
  position: 'absolute', top: '10px', left: '10px', zIndex: 30,
572
+ display: 'inline-flex', alignItems: 'center', gap: '6px',
573
+ },
574
+ floatOn: {
557
575
  padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.accent,
558
576
  background: C.elevated, color: C.accent, fontSize: '11px', fontWeight: 600,
559
577
  cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
560
578
  },
561
579
  floatOff: {
562
- position: 'absolute', top: '10px', left: '10px', zIndex: 30,
563
580
  padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.border,
564
581
  background: C.elevated, color: C.dim, fontSize: '11px', fontWeight: 600,
565
582
  cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
566
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
+ },
567
591
  floatZoomBar: {
568
592
  position: 'absolute', right: '10px', bottom: '10px', zIndex: 30,
569
593
  display: 'inline-flex', alignItems: 'center', gap: '4px',
@@ -579,6 +603,39 @@ window.__ModuleLoader__.load({
579
603
  ctxDivider: {
580
604
  height: '1px', background: C.border, opacity: 0.65, margin: '3px 4px',
581
605
  },
606
+ loopPill: {
607
+ position: 'absolute', transform: 'translate(-50%, -50%)', zIndex: 18,
608
+ padding: '2px 7px', borderRadius: '999px',
609
+ background: C.elevated, color: C.text,
610
+ fontSize: '10px', fontWeight: 600, lineHeight: '14px',
611
+ cursor: 'pointer', whiteSpace: 'nowrap',
612
+ boxShadow: '0 2px 8px rgba(0,0,0,0.28)',
613
+ display: 'inline-flex', alignItems: 'center', gap: '3px',
614
+ },
615
+ loopPopover: {
616
+ position: 'absolute', left: '50%', top: 'calc(100% + 6px)', transform: 'translateX(-50%)',
617
+ zIndex: 60, minWidth: '154px', padding: '8px', borderRadius: '7px',
618
+ background: C.elevated, color: C.text, border: '1px solid ' + C.border,
619
+ boxShadow: '0 10px 26px rgba(0,0,0,0.34)',
620
+ },
621
+ loopStepBtn: {
622
+ width: '24px', height: '24px', padding: 0, borderRadius: '5px',
623
+ border: '1px solid ' + C.border, background: C.base, color: C.text,
624
+ fontSize: '13px', lineHeight: '22px', cursor: 'pointer', textAlign: 'center',
625
+ },
626
+ loopNumInput: {
627
+ width: '44px', height: '24px', boxSizing: 'border-box', textAlign: 'center',
628
+ borderRadius: '5px', border: '1px solid ' + C.border,
629
+ background: C.base, color: C.text, fontSize: '12px', fontWeight: 600,
630
+ outline: 'none', userSelect: 'text',
631
+ },
632
+ loopNodeTag: {
633
+ position: 'absolute', left: '10px', top: '-11px', zIndex: 9,
634
+ padding: '0 5px', height: '15px', lineHeight: '15px', borderRadius: '999px',
635
+ background: C.elevated, fontSize: '9px', fontWeight: 700,
636
+ pointerEvents: 'none', whiteSpace: 'nowrap',
637
+ boxShadow: '0 1px 4px rgba(0,0,0,0.26)',
638
+ },
582
639
  canvasWrap: {
583
640
  position: 'relative', flex: '1 1 auto', minHeight: '0',
584
641
  display: 'flex', flexDirection: 'column',
@@ -643,7 +700,6 @@ window.__ModuleLoader__.load({
643
700
  marginLeft: 'auto', display: 'flex', alignItems: 'center',
644
701
  gap: '6px', position: 'relative', flex: '0 0 auto',
645
702
  },
646
- presetRowTop: { display: 'flex', alignItems: 'center', gap: '5px' },
647
703
  presetMenu: {
648
704
  position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '236px',
649
705
  maxHeight: '320px', overflowY: 'auto', background: C.elevated, color: C.text,
@@ -736,12 +792,6 @@ window.__ModuleLoader__.load({
736
792
  fieldFallback: { position: 'absolute', left: '10px', right: '10px', top: '101px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
737
793
  fieldMemory: { position: 'absolute', left: '10px', right: '10px', top: '123px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
738
794
  fieldRole: { position: 'absolute', left: '10px', right: '10px', top: '145px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
739
- fieldRoleTop: { position: 'absolute', left: '10px', right: '10px', top: '34px', height: '24px', display: 'flex', alignItems: 'center', gap: '6px' },
740
- optRow: {
741
- position: 'absolute', left: '10px', right: '10px', top: '114px', height: '18px',
742
- display: 'flex', alignItems: 'center', gap: '5px', fontSize: '9px', color: C.dim,
743
- overflow: 'hidden',
744
- },
745
795
 
746
796
  toggleSwitch: {
747
797
  flex: '1 1 auto', width: '100%', height: '18px', boxSizing: 'border-box', padding: '0 5px', borderRadius: '4px',
@@ -753,18 +803,6 @@ window.__ModuleLoader__.load({
753
803
  border: '1px solid ' + C.accent, background: C.base, color: C.accent,
754
804
  fontSize: '10px', cursor: 'pointer', outline: 'none', textAlign: 'center', lineHeight: '14px',
755
805
  },
756
- optChip: {
757
- flex: '0 0 auto', padding: '2px 6px', borderRadius: '4px',
758
- border: '1px solid ' + C.border, background: 'transparent', color: C.dim,
759
- fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '12px',
760
- outline: 'none',
761
- },
762
- optChipOn: {
763
- flex: '0 0 auto', padding: '2px 6px', borderRadius: '4px',
764
- border: '1px solid ' + C.accent, background: C.hover, color: C.accent,
765
- fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '12px',
766
- outline: 'none',
767
- },
768
806
  fieldLabel: { flex: '0 0 30px', width: '30px', fontSize: '9px', color: C.dim, whiteSpace: 'nowrap' },
769
807
  fieldLabelEn: { flex: '0 0 46px', width: '46px', fontSize: '9px', color: C.dim, whiteSpace: 'nowrap' },
770
808
 
@@ -848,12 +886,6 @@ window.__ModuleLoader__.load({
848
886
  background: C.base, color: C.text, fontSize: '10px', cursor: 'pointer', textAlign: 'left',
849
887
  lineHeight: '14px',
850
888
  },
851
- reasonChip: {
852
- flex: '0 0 auto', maxWidth: '44px', padding: '3px 4px', borderRadius: '5px',
853
- border: '1px solid ' + C.border, background: 'transparent', color: C.dim,
854
- fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap',
855
- overflow: 'hidden', textOverflow: 'ellipsis',
856
- },
857
889
  selectText: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
858
890
  caret: { flex: '0 0 auto', color: C.dim, fontSize: '9px' },
859
891
  menu: {
@@ -883,14 +915,6 @@ window.__ModuleLoader__.load({
883
915
  color: '#e5534b', fontSize: '12px', lineHeight: '16px', textAlign: 'center',
884
916
  cursor: 'pointer', zIndex: 8, userSelect: 'none',
885
917
  },
886
- runsBadge: {
887
- position: 'absolute', right: '10px', bottom: '2px', fontSize: '9px',
888
- color: C.accent, cursor: 'pointer', userSelect: 'none', zIndex: 4,
889
- },
890
- statusBar: {
891
- position: 'absolute', left: '2px', top: '10px', bottom: '10px', width: '3px',
892
- borderRadius: '2px', zIndex: 3,
893
- },
894
918
  verdictChip: {
895
919
  position: 'absolute', left: '0', top: 'calc(100% + 5px)', maxWidth: NODE_W + 'px',
896
920
  display: 'inline-flex', alignItems: 'center', gap: '4px',
@@ -1102,6 +1126,91 @@ window.__ModuleLoader__.load({
1102
1126
  };
1103
1127
  }
1104
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
+
1105
1214
  function isCustomBranches(node) {
1106
1215
  return Boolean(node && node.kind === 'condition' && Array.isArray(node.branches) && node.branches.length >= 2);
1107
1216
  }
@@ -1227,6 +1336,263 @@ window.__ModuleLoader__.load({
1227
1336
  return doc;
1228
1337
  }
1229
1338
 
1339
+ function normalizeMaxIterationsUI(val) {
1340
+ const n = Number(val);
1341
+ if (!Number.isFinite(n)) return DEFAULT_LOOP_ITERATIONS;
1342
+ return Math.max(1, Math.min(MAX_LOOP_ITERATIONS, Math.floor(n)));
1343
+ }
1344
+
1345
+ function forwardEdgesUI(edges) {
1346
+ return (Array.isArray(edges) ? edges : []).filter((e) => e && !e.loop);
1347
+ }
1348
+
1349
+ /** Nodes strictly inside a loop edge (`descendants(to) ∩ ancestors(from)` over forward edges). */
1350
+ function loopMemberIdsUI(nodes, edges, loopEdge) {
1351
+ if (!loopEdge || !loopEdge.from || !loopEdge.to || loopEdge.to === 'lead') return new Set();
1352
+ const fwd = new Map();
1353
+ const rev = new Map();
1354
+ for (const e of forwardEdgesUI(edges)) {
1355
+ if (!e.from || !e.to) continue;
1356
+ if (!fwd.has(e.from)) fwd.set(e.from, []);
1357
+ fwd.get(e.from).push(e.to);
1358
+ if (!rev.has(e.to)) rev.set(e.to, []);
1359
+ rev.get(e.to).push(e.from);
1360
+ }
1361
+ const desc = new Set([loopEdge.to]);
1362
+ const q1 = [loopEdge.to];
1363
+ for (let i = 0; i < q1.length; i += 1) {
1364
+ for (const next of fwd.get(q1[i]) || []) {
1365
+ if (!desc.has(next)) { desc.add(next); q1.push(next); }
1366
+ }
1367
+ }
1368
+ if (!desc.has(loopEdge.from)) return new Set();
1369
+ const anc = new Set([loopEdge.from]);
1370
+ const q2 = [loopEdge.from];
1371
+ for (let i = 0; i < q2.length; i += 1) {
1372
+ for (const prev of rev.get(q2[i]) || []) {
1373
+ if (!anc.has(prev)) { anc.add(prev); q2.push(prev); }
1374
+ }
1375
+ }
1376
+ const members = new Set();
1377
+ for (const id of desc) {
1378
+ if (anc.has(id)) members.add(id);
1379
+ }
1380
+ return members;
1381
+ }
1382
+
1383
+ /** Compute loop visual groups (per-node color & per-edge metadata) from active loop edges. */
1384
+ function loopGroupsForUI(nodes, edges) {
1385
+ const byNode = new Map();
1386
+ const byEdge = new Map();
1387
+ let idx = 0;
1388
+ for (const e of edges || []) {
1389
+ if (!e || e.loop !== true) continue;
1390
+ const members = loopMemberIdsUI(nodes, edges, e);
1391
+ const color = LOOP_COLORS[idx % LOOP_COLORS.length];
1392
+ const info = {
1393
+ edge: e,
1394
+ color,
1395
+ index: idx + 1,
1396
+ members,
1397
+ maxIterations: normalizeMaxIterationsUI(e.maxIterations),
1398
+ };
1399
+ byEdge.set(e.id || (e.from + '->' + e.to), info);
1400
+ for (const nid of members) {
1401
+ if (!byNode.has(nid)) byNode.set(nid, info);
1402
+ }
1403
+ idx += 1;
1404
+ }
1405
+ return { byNode, byEdge };
1406
+ }
1407
+
1408
+ /** Remove any loop edge whose forward ancestor path was broken by an edge or node deletion. */
1409
+ function pruneInvalidLoopEdges(nodes, edges) {
1410
+ const list = Array.isArray(nodes) ? nodes : [];
1411
+ const all = Array.isArray(edges) ? edges : [];
1412
+ let removedCount = 0;
1413
+ const kept = all.filter((e) => {
1414
+ if (!e || e.loop !== true) return true;
1415
+ const ok = loopMemberIdsUI(list, all, e).size > 0;
1416
+ if (!ok) removedCount += 1;
1417
+ return ok;
1418
+ });
1419
+ return { edges: kept, removedCount };
1420
+ }
1421
+
1422
+ /** Check whether dragging from `fromId` to `toId` is a valid controlled loop back-edge. */
1423
+ function canLinkAsLoop(nodes, edges, fromId, toId) {
1424
+ const list = Array.isArray(nodes) ? nodes : [];
1425
+ const fromNode = list.find((n) => n && n.id === fromId);
1426
+ if (!fromNode || fromNode.kind !== 'condition') return { ok: false, reason: 'loopNotCondition' };
1427
+ if (!toId || toId === 'lead' || toId === fromId) return { ok: false, reason: 'loopToLead' };
1428
+ const members = loopMemberIdsUI(list, edges, { from: fromId, to: toId, loop: true });
1429
+ if (!members.size) return { ok: false, reason: 'loopNotAncestor' };
1430
+ const existing = loopGroupsForUI(list, edges);
1431
+ for (const mid of members) {
1432
+ if (existing.byNode.has(mid)) return { ok: false, reason: 'loopOverlap' };
1433
+ }
1434
+ return { ok: true, members };
1435
+ }
1436
+
1437
+ /**
1438
+ * Validate a multi-selected (or single non-condition) subgraph for one-click "Create loop".
1439
+ * Requires a single-entry, single-exit connected subgraph with no overlap with existing loops.
1440
+ */
1441
+ function analyzeLoopSelection(nodes, edges, selectedIds) {
1442
+ const list = Array.isArray(nodes) ? nodes : [];
1443
+ const byId = new Map(list.map((n) => [n.id, n]));
1444
+ const selIds = Array.from(new Set((selectedIds || []).filter((id) => id && id !== 'lead' && byId.has(id))));
1445
+ if (!selIds.length) return { ok: false, reason: 'loopNeedNodes' };
1446
+ const selSet = new Set(selIds);
1447
+ const existing = loopGroupsForUI(list, edges);
1448
+ for (const id of selIds) {
1449
+ if (existing.byNode.has(id)) return { ok: false, reason: 'loopOverlap' };
1450
+ }
1451
+ if (selIds.length === 1) {
1452
+ const only = byId.get(selIds[0]);
1453
+ if (only.kind === 'condition') return { ok: false, reason: 'loopCondAlone' };
1454
+ return { ok: true, entryId: only.id, exitId: only.id, needsAutoCondition: true };
1455
+ }
1456
+ const fwd = new Map(selIds.map((id) => [id, []]));
1457
+ const rev = new Map(selIds.map((id) => [id, []]));
1458
+ const undir = new Map(selIds.map((id) => [id, []]));
1459
+ for (const e of forwardEdgesUI(edges)) {
1460
+ if (!selSet.has(e.from) || !selSet.has(e.to)) continue;
1461
+ fwd.get(e.from).push(e.to);
1462
+ rev.get(e.to).push(e.from);
1463
+ undir.get(e.from).push(e.to);
1464
+ undir.get(e.to).push(e.from);
1465
+ }
1466
+ // Must be weakly connected
1467
+ const visited = new Set([selIds[0]]);
1468
+ const q = [selIds[0]];
1469
+ for (let i = 0; i < q.length; i += 1) {
1470
+ for (const nb of undir.get(q[i]) || []) {
1471
+ if (!visited.has(nb)) { visited.add(nb); q.push(nb); }
1472
+ }
1473
+ }
1474
+ if (visited.size !== selIds.length) return { ok: false, reason: 'loopDisconnected' };
1475
+ const entries = selIds.filter((id) => (rev.get(id) || []).length === 0);
1476
+ const exits = selIds.filter((id) => (fwd.get(id) || []).length === 0);
1477
+ if (entries.length !== 1 || exits.length !== 1) return { ok: false, reason: 'loopMultiEnds' };
1478
+ const entryId = entries[0];
1479
+ const exitId = exits[0];
1480
+ // Verify entry reaches exit
1481
+ const reach = new Set([entryId]);
1482
+ const rq = [entryId];
1483
+ for (let i = 0; i < rq.length; i += 1) {
1484
+ for (const nx of fwd.get(rq[i]) || []) {
1485
+ if (!reach.has(nx)) { reach.add(nx); rq.push(nx); }
1486
+ }
1487
+ }
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
+ }
1495
+ const exitNode = byId.get(exitId);
1496
+ return {
1497
+ ok: true,
1498
+ entryId,
1499
+ exitId,
1500
+ needsAutoCondition: exitNode.kind !== 'condition',
1501
+ };
1502
+ }
1503
+
1504
+ /**
1505
+ * Build a clean rounded bypass-rail SVG path for a controlled loop back-edge so it
1506
+ * routes outside all loop member cards instead of cutting across card bodies.
1507
+ */
1508
+ function loopEdgeArc(from, to, edge, direction, nodes, edges) {
1509
+ const type = (edge && edge.type) || 'prompt';
1510
+ const branch = (edge && edge.branch) || '';
1511
+ const p1 = outputSocketPos(from, type, branch, direction);
1512
+ const p2 = inputSocketPos(to, direction);
1513
+ const x1 = p1.x + WORLD_PAD;
1514
+ const y1 = p1.y + WORLD_PAD;
1515
+ const x2 = p2.x + WORLD_PAD;
1516
+ const y2 = p2.y + WORLD_PAD;
1517
+
1518
+ const list = Array.isArray(nodes) ? nodes : [from, to];
1519
+ const byId = new Map(list.map((n) => [n.id, n]));
1520
+ const memberIds = loopMemberIdsUI(list, edges || [], edge);
1521
+ const boxNodes = memberIds.size
1522
+ ? Array.from(memberIds).map((id) => byId.get(id)).filter(Boolean)
1523
+ : [from, to];
1524
+ let minX = Infinity;
1525
+ let maxX = -Infinity;
1526
+ let minY = Infinity;
1527
+ for (const n of boxNodes) {
1528
+ minX = Math.min(minX, n.x + WORLD_PAD);
1529
+ maxX = Math.max(maxX, n.x + WORLD_PAD + NODE_W);
1530
+ minY = Math.min(minY, n.y + WORLD_PAD);
1531
+ }
1532
+
1533
+ const buildRoundedPath = (pts, radius) => {
1534
+ if (pts.length < 2) return '';
1535
+ let d = 'M ' + pts[0].x + ' ' + pts[0].y;
1536
+ for (let i = 1; i < pts.length - 1; i += 1) {
1537
+ const prev = pts[i - 1];
1538
+ const cur = pts[i];
1539
+ const next = pts[i + 1];
1540
+ const d1 = Math.hypot(cur.x - prev.x, cur.y - prev.y);
1541
+ const d2 = Math.hypot(next.x - cur.x, next.y - cur.y);
1542
+ const r = Math.min(radius, d1 * 0.45, d2 * 0.45);
1543
+ if (r < 1) {
1544
+ d += ' L ' + cur.x + ' ' + cur.y;
1545
+ } else {
1546
+ const ax = cur.x - ((cur.x - prev.x) / d1) * r;
1547
+ const ay = cur.y - ((cur.y - prev.y) / d1) * r;
1548
+ const bx = cur.x + ((next.x - cur.x) / d2) * r;
1549
+ const by = cur.y + ((next.y - cur.y) / d2) * r;
1550
+ d += ' L ' + ax.toFixed(1) + ' ' + ay.toFixed(1)
1551
+ + ' Q ' + cur.x.toFixed(1) + ' ' + cur.y.toFixed(1) + ' ' + bx.toFixed(1) + ' ' + by.toFixed(1);
1552
+ }
1553
+ }
1554
+ const last = pts[pts.length - 1];
1555
+ d += ' L ' + last.x + ' ' + last.y;
1556
+ return d;
1557
+ };
1558
+
1559
+ if (direction === 'tb') {
1560
+ const onLeft = Boolean(from && from.tbSide === 'left');
1561
+ const railX = onLeft ? (Math.min(x1, minX) - 42) : (Math.max(x1, maxX) + 42);
1562
+ const topY = Math.min(y2, minY) - 34;
1563
+ const points = [
1564
+ { x: x1, y: y1 },
1565
+ { x: railX, y: y1 },
1566
+ { x: railX, y: topY },
1567
+ { x: x2, y: topY },
1568
+ { x: x2, y: y2 },
1569
+ ];
1570
+ return {
1571
+ path: buildRoundedPath(points, 16),
1572
+ points,
1573
+ midX: railX,
1574
+ midY: Math.round((y1 + topY) / 2),
1575
+ };
1576
+ }
1577
+ const rightX = Math.max(x1, maxX) + 34;
1578
+ const leftX = Math.min(x2, minX) - 34;
1579
+ const topY = Math.min(y1, y2, minY) - 38;
1580
+ const points = [
1581
+ { x: x1, y: y1 },
1582
+ { x: rightX, y: y1 },
1583
+ { x: rightX, y: topY },
1584
+ { x: leftX, y: topY },
1585
+ { x: leftX, y: y2 },
1586
+ { x: x2, y: y2 },
1587
+ ];
1588
+ return {
1589
+ path: buildRoundedPath(points, 16),
1590
+ points,
1591
+ midX: Math.round((rightX + leftX) / 2),
1592
+ midY: topY,
1593
+ };
1594
+ }
1595
+
1230
1596
  /** Control points of one link, in canvas coordinates. Supports horizontal (lr) and vertical (tb) flow. */
1231
1597
  function edgeCurve(from, to, typeOrEdge, direction) {
1232
1598
  const type = (typeOrEdge && typeof typeOrEdge === 'object') ? (typeOrEdge.type || 'prompt') : (typeOrEdge || 'prompt');
@@ -1265,13 +1631,24 @@ window.__ModuleLoader__.load({
1265
1631
  return { x1, y1, c1x: x1 + dx, c1y: y1, c2x: x2 - dx, c2y: y2, x2, y2 };
1266
1632
  }
1267
1633
 
1268
- function edgePath(from, to, typeOrEdge, direction) {
1634
+ function edgePath(from, to, typeOrEdge, direction, nodes, edges) {
1635
+ if (typeOrEdge && typeof typeOrEdge === 'object' && typeOrEdge.loop) {
1636
+ return loopEdgeArc(from, to, typeOrEdge, direction, nodes, edges).path;
1637
+ }
1269
1638
  const c = edgeCurve(from, to, typeOrEdge, direction);
1270
1639
  return 'M ' + c.x1 + ' ' + c.y1 + ' C ' + c.c1x + ' ' + c.c1y + ', ' + c.c2x + ' ' + c.c2y + ', ' + c.x2 + ' ' + c.y2;
1271
1640
  }
1272
1641
 
1273
- /** Shortest distance between a point and one link, sampled along the curve. */
1274
- function distanceToEdge(point, from, to, typeOrEdge, direction) {
1642
+ /** Shortest distance between a point and one link, sampled along the curve (or bypass rail for loops). */
1643
+ function distanceToEdge(point, from, to, typeOrEdge, direction, nodes, edges) {
1644
+ if (typeOrEdge && typeof typeOrEdge === 'object' && typeOrEdge.loop) {
1645
+ const pts = loopEdgeArc(from, to, typeOrEdge, direction, nodes, edges).points;
1646
+ let best = Infinity;
1647
+ for (let i = 1; i < pts.length; i += 1) {
1648
+ best = Math.min(best, distanceToSegment(point, pts[i - 1].x, pts[i - 1].y, pts[i].x, pts[i].y));
1649
+ }
1650
+ return best;
1651
+ }
1275
1652
  const c = edgeCurve(from, to, typeOrEdge, direction);
1276
1653
  let best = Infinity;
1277
1654
  let prevX = c.x1;
@@ -1301,15 +1678,15 @@ window.__ModuleLoader__.load({
1301
1678
  function topoOrder(nodes, edges) {
1302
1679
  const indeg = new Map(nodes.map((n) => [n.id, 0]));
1303
1680
  const adj = new Map(nodes.map((n) => [n.id, []]));
1304
- for (const e of edges) {
1681
+ for (const e of forwardEdgesUI(edges)) {
1305
1682
  if (!indeg.has(e.from) || !indeg.has(e.to)) continue;
1306
1683
  indeg.set(e.to, indeg.get(e.to) + 1);
1307
1684
  adj.get(e.from).push(e.to);
1308
1685
  }
1309
1686
  const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
1310
1687
  const out = [];
1311
- while (queue.length) {
1312
- const id = queue.shift();
1688
+ for (let i = 0; i < queue.length; i += 1) {
1689
+ const id = queue[i];
1313
1690
  out.push(id);
1314
1691
  for (const next of adj.get(id)) {
1315
1692
  indeg.set(next, indeg.get(next) - 1);
@@ -1319,10 +1696,10 @@ window.__ModuleLoader__.load({
1319
1696
  return out.length === nodes.length ? out : null;
1320
1697
  }
1321
1698
 
1322
- /** Ids reachable from the entry Lead via O(V + E) BFS; every other node is skipped at run time. */
1699
+ /** Ids reachable from the entry Lead via O(V + E) BFS over forward edges; every other node is skipped at run time. */
1323
1700
  function reachableFrom(nodes, edges) {
1324
1701
  const adj = new Map();
1325
- for (const e of edges || []) {
1702
+ for (const e of forwardEdgesUI(edges)) {
1326
1703
  if (!e || !e.from || !e.to) continue;
1327
1704
  if (!adj.has(e.from)) adj.set(e.from, []);
1328
1705
  adj.get(e.from).push(e.to);
@@ -1345,7 +1722,7 @@ window.__ModuleLoader__.load({
1345
1722
  */
1346
1723
  function soloLeadNodeIds(nodes, edges) {
1347
1724
  const list = Array.isArray(nodes) ? nodes : [];
1348
- const linkList = Array.isArray(edges) ? edges : [];
1725
+ const linkList = forwardEdgesUI(edges);
1349
1726
  const reachable = reachableFrom(list, linkList);
1350
1727
  const byId = new Map(list.map((n) => [n.id, n]));
1351
1728
  const out = new Set();
@@ -1370,13 +1747,14 @@ window.__ModuleLoader__.load({
1370
1747
  function deadEndNodeIds(nodes, edges) {
1371
1748
  const list = Array.isArray(nodes) ? nodes : [];
1372
1749
  const linkList = Array.isArray(edges) ? edges : [];
1373
- const reachable = reachableFrom(list, linkList);
1374
- const soloLeads = soloLeadNodeIds(list, linkList);
1750
+ const fwdLinks = forwardEdgesUI(linkList);
1751
+ const reachable = reachableFrom(list, fwdLinks);
1752
+ const soloLeads = soloLeadNodeIds(list, fwdLinks);
1375
1753
  const downstreamLeads = list.filter((n) => n.kind === 'lead' && n.id !== 'lead' && reachable.has(n.id) && !soloLeads.has(n.id));
1376
1754
  if (!downstreamLeads.length) return new Set();
1377
1755
  const hasOut = new Set(linkList.map((e) => e.from));
1378
1756
  const parents = new Map();
1379
- for (const e of linkList) {
1757
+ for (const e of fwdLinks) {
1380
1758
  if (!parents.has(e.to)) parents.set(e.to, []);
1381
1759
  parents.get(e.to).push(e.from);
1382
1760
  }
@@ -1400,18 +1778,18 @@ window.__ModuleLoader__.load({
1400
1778
  return out;
1401
1779
  }
1402
1780
 
1403
- /** True when adding `fromId -> toId` would create a cycle or point into entry Lead. */
1781
+ /** True when adding `fromId -> toId` would create a cycle over forward edges or point into entry Lead. */
1404
1782
  function wouldCycle(nodes, edges, fromId, toId) {
1405
1783
  if (!fromId || !toId || fromId === toId || toId === 'lead') return true;
1406
1784
  const adj = new Map();
1407
- for (const e of edges || []) {
1785
+ for (const e of forwardEdgesUI(edges)) {
1408
1786
  if (!adj.has(e.from)) adj.set(e.from, []);
1409
1787
  adj.get(e.from).push(e.to);
1410
1788
  }
1411
1789
  const seen = new Set([toId]);
1412
1790
  const queue = [toId];
1413
- while (queue.length) {
1414
- const cur = queue.shift();
1791
+ for (let i = 0; i < queue.length; i += 1) {
1792
+ const cur = queue[i];
1415
1793
  if (cur === fromId) return true;
1416
1794
  for (const next of adj.get(cur) || []) {
1417
1795
  if (!seen.has(next)) { seen.add(next); queue.push(next); }
@@ -1420,10 +1798,10 @@ window.__ModuleLoader__.load({
1420
1798
  return false;
1421
1799
  }
1422
1800
 
1423
- /** Tidy a DAG into symmetrical left-to-right columns by longest-path depth. */
1801
+ /** Tidy a DAG into symmetrical columns/rows by longest-path depth (ignoring loop back-edges). */
1424
1802
  function layoutGraph(nodes, edges, direction) {
1425
1803
  const list = Array.isArray(nodes) ? nodes : [];
1426
- const linkList = Array.isArray(edges) ? edges : [];
1804
+ const linkList = forwardEdgesUI(edges);
1427
1805
  if (!list.length) return [];
1428
1806
  const reachable = reachableFrom(list, linkList);
1429
1807
  const depth = new Map(list.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
@@ -1466,14 +1844,16 @@ window.__ModuleLoader__.load({
1466
1844
  }
1467
1845
  } else {
1468
1846
  const COL_PITCH = 300;
1469
- const ROW_PITCH = 262;
1847
+ const ROW_GAP = 28;
1470
1848
  const MID_Y = 320;
1471
1849
  for (const [col, colNodes] of columns.entries()) {
1472
1850
  const ordered = colNodes.slice().sort((a, b) => (a.y || 0) - (b.y || 0));
1473
- const totalH = (ordered.length - 1) * ROW_PITCH + NODE_H;
1474
- 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);
1475
1854
  ordered.forEach((n, row) => {
1476
- 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;
1477
1857
  });
1478
1858
  }
1479
1859
  }
@@ -1673,6 +2053,54 @@ window.__ModuleLoader__.load({
1673
2053
  { id: 'cd5', from: 'c_yes', to: 'c_final', type: 'prompt' },
1674
2054
  { id: 'cd6', from: 'c_no', to: 'c_final', type: 'prompt' },
1675
2055
  ];
2056
+ const loopNodes = [
2057
+ {
2058
+ id: 'lead', kind: 'lead', label: 'Lead', y: 0,
2059
+ task: en
2060
+ ? 'Implement the requested change and verify with tests: if checks fail, automatically loop back with feedback to fix (up to 3 retries), then hand off to me for final review.'
2061
+ : '实现目标功能并跑测试验证:若测试或检查不通过,自动带着失败原因回环修改(最多 3 次),全部通过后交我终审交付。',
2062
+ provider: '', model: '', role: '',
2063
+ },
2064
+ {
2065
+ id: 'lp_impl', kind: 'agent', y: 0,
2066
+ label: en ? 'Implement' : '编写实现',
2067
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
2068
+ role: en
2069
+ ? 'Implement the requested change cleanly. When invoked on a retry round, focus directly on fixing the reported issues and list modified files.'
2070
+ : '按需求完成代码或文档实现;若处于回环修正轮次,针对打回理由直接定点修复并列出改动清单。',
2071
+ },
2072
+ {
2073
+ id: 'lp_test', kind: 'agent', y: 0,
2074
+ label: en ? 'Test & Verify' : '测试与检查',
2075
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
2076
+ role: en
2077
+ ? 'Run tests/lint/checks against the implementation and report exact pass/fail status, error logs, and remaining defects.'
2078
+ : '对实现结果运行单测、构建或逐项核验,如实汇报通过情况、具体报错日志与遗留缺陷。',
2079
+ },
2080
+ {
2081
+ id: 'lp_gate', kind: 'condition', y: 0,
2082
+ label: en ? 'Checks Passed?' : '是否通过?',
2083
+ provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false,
2084
+ role: en
2085
+ ? 'Return pass=true only if all tests/checks passed with no unresolved defects; otherwise return pass=false with a concise, actionable fix reason.'
2086
+ : '仅当测试与检查全部通过且无未解决缺陷时返回 true;否则返回 false,并在理由里写清下一轮需修复的具体问题。',
2087
+ },
2088
+ {
2089
+ id: 'lp_final', kind: 'lead', y: 0,
2090
+ label: en ? 'Lead Final Review' : 'Lead 终审',
2091
+ provider: '', model: '',
2092
+ role: en
2093
+ ? 'Review the verified result (or the round-by-round summary if retries exhausted) and decide whether to ship or intervene.'
2094
+ : '审阅最终通过的改动摘要(或回环达上限后的历次失败记录),确认交付或拍板下一步处理。',
2095
+ },
2096
+ ];
2097
+ const loopEdges = [
2098
+ { id: 'lp1', from: 'lead', to: 'lp_impl', type: 'prompt' },
2099
+ { id: 'lp2', from: 'lp_impl', to: 'lp_test', type: 'prompt' },
2100
+ { id: 'lp3', from: 'lp_test', to: 'lp_gate', type: 'prompt' },
2101
+ { id: 'lp4', from: 'lp_gate', to: 'lp_final', type: 'prompt', branch: 'true' },
2102
+ { id: 'lp5', from: 'lp_gate', to: 'lp_impl', type: 'prompt', branch: 'false', loop: true, maxIterations: 3 },
2103
+ ];
1676
2104
  return [
1677
2105
  {
1678
2106
  id: 'tpl-swe',
@@ -1698,6 +2126,12 @@ window.__ModuleLoader__.load({
1698
2126
  nodes: layoutGraph(condNodes, condEdges, direction),
1699
2127
  edges: condEdges,
1700
2128
  },
2129
+ {
2130
+ id: 'tpl-loop',
2131
+ name: en ? 'Retry Loop: Implement → Test ↺ Fix → Review' : '循环重试:实现 → 测试验收 ↺ 自动修复 → 终审',
2132
+ nodes: layoutGraph(loopNodes, loopEdges, direction),
2133
+ edges: loopEdges,
2134
+ },
1701
2135
  ];
1702
2136
  }
1703
2137
 
@@ -1722,12 +2156,17 @@ window.__ModuleLoader__.load({
1722
2156
  }
1723
2157
 
1724
2158
  const activeIds = new Set(active.map((n) => n.id));
1725
- const planEdges = edges
1726
- .filter((e) => (e.from === 'lead' || activeIds.has(e.from)) && activeIds.has(e.to))
2159
+ const candidateEdges = edges.filter((e) => (e.from === 'lead' || activeIds.has(e.from)) && activeIds.has(e.to));
2160
+ const { edges: validEdges } = pruneInvalidLoopEdges(active, candidateEdges);
2161
+ const planEdges = validEdges
1727
2162
  .map((e) => {
1728
2163
  const item = { from: e.from, to: e.to, type: e.type || 'prompt' };
1729
2164
  const b = typeof e.branch === 'string' ? e.branch.trim() : '';
1730
2165
  if (b) item.branch = b;
2166
+ if (e.loop === true) {
2167
+ item.loop = true;
2168
+ item.maxIterations = normalizeMaxIterationsUI(e.maxIterations);
2169
+ }
1731
2170
  return item;
1732
2171
  });
1733
2172
 
@@ -1959,6 +2398,37 @@ window.__ModuleLoader__.load({
1959
2398
  return { k, x: cx - lx * k, y: cy - ly * k };
1960
2399
  }
1961
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
+
1962
2432
  function loadPresets() {
1963
2433
  try {
1964
2434
  const raw = window.localStorage.getItem(PRESET_KEY);
@@ -1973,6 +2443,16 @@ window.__ModuleLoader__.load({
1973
2443
  function savePresets(presets) {
1974
2444
  try {
1975
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 */ }
1976
2456
  return true;
1977
2457
  } catch (_e) {
1978
2458
  return false;
@@ -2053,8 +2533,15 @@ window.__ModuleLoader__.load({
2053
2533
  const sessionId = props && props.sessionId;
2054
2534
  const stored = useRef(loadDoc(sessionId));
2055
2535
  const initial = stored.current;
2056
-
2057
- 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
+ });
2058
2545
  const [edges, setEdges] = useState(() => (initial ? initial.edges : defaultEdges()));
2059
2546
  const [selectedIds, setSelectedIds] = useState([]);
2060
2547
  const [marquee, setMarquee] = useState(null);
@@ -2088,7 +2575,7 @@ window.__ModuleLoader__.load({
2088
2575
  const [modelsLoading, setModelsLoading] = useState(() => cachedModels.length === 0);
2089
2576
  const [openModelFor, setOpenModelFor] = useState(null);
2090
2577
  const [enabled, setEnabled] = useState(() => Boolean(initial && initial.enabled));
2091
- const [direction, setDirection] = useState(() => (initial && initial.direction === 'tb' ? 'tb' : 'lr'));
2578
+ const [direction, setDirection] = useState(initialDir);
2092
2579
  const directionRef = useRef(direction);
2093
2580
  directionRef.current = direction;
2094
2581
 
@@ -2100,15 +2587,17 @@ window.__ModuleLoader__.load({
2100
2587
  const lastMouseRef = useRef(null);
2101
2588
  const [addMenu, setAddMenu] = useState(null);
2102
2589
  const [ctxMenu, setCtxMenu] = useState(null);
2590
+ const [loopEditEdgeId, setLoopEditEdgeId] = useState(null);
2591
+ const [loopDraft, setLoopDraft] = useState('');
2103
2592
  const rightClickRef = useRef(null);
2104
2593
  const nodeDrag = useRef(null);
2105
2594
  const panDrag = useRef(null);
2595
+ const zoomScrubbing = useRef(false);
2106
2596
  const [panning, setPanning] = useState(false);
2107
2597
  const spaceDown = useRef(false);
2108
2598
  const [spaceHeld, setSpaceHeld] = useState(false);
2109
2599
  const statusTimer = useRef(null);
2110
2600
  const dropdownRef = useRef(null);
2111
- const syncTimer = useRef(null);
2112
2601
  const lastSync = useRef('');
2113
2602
  const historyRef = useRef([]);
2114
2603
  const redoRef = useRef([]);
@@ -2124,11 +2613,50 @@ window.__ModuleLoader__.load({
2124
2613
  const [sessionRunning, setSessionRunning] = useState(false);
2125
2614
  const [runTriggering, setRunTriggering] = useState(false);
2126
2615
  const runTriggeringRef = useRef(false);
2616
+ const [stopping, setStopping] = useState(false);
2617
+ const stoppingRef = useRef(false);
2127
2618
  const pendingHandledRef = useRef(false);
2128
2619
  const lastNodePrefsRef = useRef({ provider: '', model: '', reasoning: '', preset: 'standard' });
2129
2620
  const [presets, setPresets] = useState(loadPresets);
2130
2621
  const [presetOpen, setPresetOpen] = useState(null);
2131
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]);
2132
2660
  const [lang, setLang] = useState(loadLang);
2133
2661
  const t = (key) => (I18N[lang] && I18N[lang][key]) || I18N.zh[key] || key;
2134
2662
  const toggleLang = () => {
@@ -2235,7 +2763,7 @@ window.__ModuleLoader__.load({
2235
2763
  const sig = planSig(nextEnabled, curNodes, curEdges, overrideParallel);
2236
2764
  if (sig === lastSync.current) { setDirty(false); flash(t('upToDate')); return Promise.resolve(true); }
2237
2765
  const line = '/canvas-sync ' + encodeURIComponent(sig);
2238
- 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');
2239
2767
  return face.command(line).then((ack) => {
2240
2768
  if (ack && ack.ok) {
2241
2769
  lastSync.current = sig;
@@ -2315,6 +2843,109 @@ window.__ModuleLoader__.load({
2315
2843
  }
2316
2844
  };
2317
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
+
2318
2949
  // Sync the moment a user message starts a turn, so this turn's tool call
2319
2950
  // already sees the latest canvas. Falls back to the turn end if the start
2320
2951
  // edge was missed; `dirty` clears on success so only one fires.
@@ -2407,7 +3038,8 @@ window.__ModuleLoader__.load({
2407
3038
  if (child && child.running) {
2408
3039
  if (entry.id) staleChildIds.current.delete(entry.id);
2409
3040
  nextStatus[nodeId] = 'running';
2410
- } 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.
2411
3043
  if (timing && timing.lastTurnCompleted === false) nextStatus[nodeId] = 'failed';
2412
3044
  else nextStatus[nodeId] = 'done';
2413
3045
  }
@@ -2495,11 +3127,12 @@ window.__ModuleLoader__.load({
2495
3127
  return null;
2496
3128
  };
2497
3129
  const onWheel = (e) => {
2498
- if (!e.deltaY) return;
3130
+ if (!e.deltaY || zoomScrubbing.current) return;
2499
3131
  if (!e.ctrlKey && findScrollableChild(e.target, e.deltaY)) return;
2500
3132
  e.preventDefault();
2501
3133
  absorbScroll();
2502
3134
  setCtxMenu(null);
3135
+ setLoopEditEdgeId(null);
2503
3136
  const rect = el.getBoundingClientRect();
2504
3137
  const mx = e.clientX - rect.left;
2505
3138
  const my = e.clientY - rect.top;
@@ -2569,6 +3202,7 @@ window.__ModuleLoader__.load({
2569
3202
  const startX = e.clientX;
2570
3203
  const startView = { ...viewRef.current };
2571
3204
  let moved = false;
3205
+ zoomScrubbing.current = true;
2572
3206
  const prevCursor = typeof document !== 'undefined' && document.body ? document.body.style.cursor : '';
2573
3207
  const onMove = (ev) => {
2574
3208
  const dx = ev.clientX - startX;
@@ -2580,13 +3214,20 @@ window.__ModuleLoader__.load({
2580
3214
  commitView(scrubZoom(startView, cx, cy, dx));
2581
3215
  };
2582
3216
  const onUp = () => {
3217
+ zoomScrubbing.current = false;
2583
3218
  window.removeEventListener('mousemove', onMove);
2584
3219
  window.removeEventListener('mouseup', onUp);
3220
+ window.removeEventListener('blur', onBlurScrub);
2585
3221
  if (typeof document !== 'undefined' && document.body) document.body.style.cursor = prevCursor;
2586
3222
  if (!moved) focusLead(1);
2587
3223
  };
3224
+ const onBlurScrub = () => {
3225
+ moved = true;
3226
+ onUp();
3227
+ };
2588
3228
  window.addEventListener('mousemove', onMove);
2589
3229
  window.addEventListener('mouseup', onUp);
3230
+ window.addEventListener('blur', onBlurScrub);
2590
3231
  };
2591
3232
 
2592
3233
  /** Zoom and pan so every node sits comfortably inside the viewport. */
@@ -2607,12 +3248,15 @@ window.__ModuleLoader__.load({
2607
3248
  if (n.y + nh > maxY) maxY = n.y + nh;
2608
3249
  }
2609
3250
  if (!Number.isFinite(minX)) return;
3251
+ const hasLoopEdges = edgesRef.current.some((e) => e && e.loop === true);
3252
+ const isTB = directionRef.current === 'tb';
2610
3253
  const cw = el.clientWidth || 1;
2611
3254
  const chh = el.clientHeight || 1;
2612
- const padX = 36;
2613
- const padTop = 44;
3255
+ const padLeft = 36;
3256
+ const padRight = hasLoopEdges && isTB ? 84 : 36;
3257
+ const padTop = hasLoopEdges && !isTB ? 78 : 44;
2614
3258
  const padBottom = 36;
2615
- const availW = Math.max(80, cw - padX * 2);
3259
+ const availW = Math.max(80, cw - padLeft - padRight);
2616
3260
  const availH = Math.max(80, chh - padTop - padBottom);
2617
3261
  const bw = Math.max(NODE_W, maxX - minX);
2618
3262
  const bh = Math.max(NODE_H, maxY - minY);
@@ -2623,7 +3267,7 @@ window.__ModuleLoader__.load({
2623
3267
  el.scrollTop = 0;
2624
3268
  commitView({
2625
3269
  k,
2626
- x: cw / 2 - (cx + WORLD_PAD) * k,
3270
+ x: padLeft + (cw - padLeft - padRight) / 2 - (cx + WORLD_PAD) * k,
2627
3271
  y: padTop + (chh - padTop - padBottom) / 2 - (cy + WORLD_PAD) * k,
2628
3272
  });
2629
3273
  };
@@ -2646,7 +3290,11 @@ window.__ModuleLoader__.load({
2646
3290
 
2647
3291
  // Snapshot before every structural change so a mis-click can be undone/redone.
2648
3292
  const pushSnapshot = () => {
2649
- 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
+ });
2650
3298
  if (historyRef.current.length > 50) historyRef.current.shift();
2651
3299
  redoRef.current = [];
2652
3300
  };
@@ -2654,8 +3302,16 @@ window.__ModuleLoader__.load({
2654
3302
  const undo = () => {
2655
3303
  const prev = historyRef.current.pop();
2656
3304
  if (!prev) { flash(t('undoNone')); return; }
2657
- 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
+ });
2658
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
+ }
2659
3315
  setNodes(prev.nodes);
2660
3316
  setEdges(prev.edges);
2661
3317
  setSelectedIds([]);
@@ -2665,8 +3321,16 @@ window.__ModuleLoader__.load({
2665
3321
  const redo = () => {
2666
3322
  const next = redoRef.current.pop();
2667
3323
  if (!next) { flash(t('redoNone')); return; }
2668
- 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
+ });
2669
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
+ }
2670
3334
  setNodes(next.nodes);
2671
3335
  setEdges(next.edges);
2672
3336
  setSelectedIds([]);
@@ -2766,9 +3430,125 @@ window.__ModuleLoader__.load({
2766
3430
 
2767
3431
  const deleteEdgeById = (edgeId) => {
2768
3432
  pushSnapshot();
2769
- setEdges((es) => es.filter((e) => e.id !== edgeId));
3433
+ const remaining = edgesRef.current.filter((e) => e.id !== edgeId);
3434
+ const { edges: cleaned, removedCount } = pruneInvalidLoopEdges(nodesRef.current, remaining);
3435
+ setEdges(cleaned);
2770
3436
  setCtxMenu(null);
2771
- flash(t('linkCut') + ' ×1');
3437
+ setLoopEditEdgeId(null);
3438
+ flash(t('linkCut') + ' ×1' + (removedCount > 0 ? t('loopPrunedNotice') : ''));
3439
+ };
3440
+
3441
+ const openLoopEditor = (edge) => {
3442
+ if (!edge) { setLoopEditEdgeId(null); return; }
3443
+ setLoopDraft(String(normalizeMaxIterationsUI(edge.maxIterations)));
3444
+ setLoopEditEdgeId(edge.id);
3445
+ };
3446
+
3447
+ const updateLoopMaxIterations = (edgeId, nextVal) => {
3448
+ const clamped = normalizeMaxIterationsUI(nextVal);
3449
+ const cur = edgesRef.current.find((e) => e.id === edgeId);
3450
+ setLoopDraft(String(clamped));
3451
+ if (cur && cur.loop === true && normalizeMaxIterationsUI(cur.maxIterations) === clamped) return;
3452
+ pushSnapshot();
3453
+ setEdges((es) => es.map((e) => (e.id === edgeId ? { ...e, loop: true, maxIterations: clamped } : e)));
3454
+ };
3455
+
3456
+ const createLoopFromSelection = (selIds) => {
3457
+ const curNodes = nodesRef.current;
3458
+ const curEdges = edgesRef.current;
3459
+ const check = analyzeLoopSelection(curNodes, curEdges, selIds);
3460
+ if (!check.ok) {
3461
+ flash(check.reason === 'loopOverlap' ? t('loopOverlap') : t('cycleBlocked'));
3462
+ setCtxMenu(null);
3463
+ return;
3464
+ }
3465
+ pushSnapshot();
3466
+ const stamp = Date.now().toString(36);
3467
+ const exitNode = curNodes.find((n) => n.id === check.exitId);
3468
+ if (!exitNode) { setCtxMenu(null); return; }
3469
+
3470
+ if (check.needsAutoCondition) {
3471
+ const condId = 'n' + stamp + Math.random().toString(36).slice(2, 4);
3472
+ const isTB = directionRef.current === 'tb';
3473
+ const condX = isTB ? (exitNode.x || 0) : ((exitNode.x || 0) + 292);
3474
+ const condY = isTB ? ((exitNode.y || 0) + nodeHeight(exitNode) + 64) : (exitNode.y || 0);
3475
+ const prefs = lastNodePrefsRef.current || {};
3476
+ const condNode = {
3477
+ id: condId,
3478
+ kind: 'condition',
3479
+ x: condX,
3480
+ y: condY,
3481
+ label: t('loopAutoCondLabel'),
3482
+ provider: prefs.provider || '',
3483
+ model: prefs.model || '',
3484
+ reasoning: prefs.reasoning || '',
3485
+ preset: 'minimal',
3486
+ role: t('loopAutoCondRole'),
3487
+ };
3488
+ setNodes((ns) => ns.concat([condNode]));
3489
+ setEdges((es) => {
3490
+ const updated = [];
3491
+ let seq = 0;
3492
+ for (const e of es) {
3493
+ if (!e.loop && e.from === check.exitId) {
3494
+ if (e.type === 'session-ref') {
3495
+ // Preserve warm session-ref from exitNode as a condition-gated side channel,
3496
+ // and add a clean prompt wire from the new condition's `true` branch.
3497
+ updated.push(e);
3498
+ updated.push({ id: 'e' + stamp + 't' + (seq++), from: condId, to: e.to, type: 'prompt', branch: 'true' });
3499
+ } else {
3500
+ updated.push({ ...e, from: condId, type: 'prompt', branch: 'true' });
3501
+ }
3502
+ } else {
3503
+ updated.push(e);
3504
+ }
3505
+ }
3506
+ return updated.concat([
3507
+ { id: 'e' + stamp + 'f', from: check.exitId, to: condId, type: 'prompt' },
3508
+ {
3509
+ id: 'e' + stamp + 'l',
3510
+ from: condId,
3511
+ to: check.entryId,
3512
+ type: 'prompt',
3513
+ branch: 'false',
3514
+ loop: true,
3515
+ maxIterations: DEFAULT_LOOP_ITERATIONS,
3516
+ },
3517
+ ]);
3518
+ });
3519
+ setSelectedIds([condId]);
3520
+ setCtxMenu(null);
3521
+ flash(t('loopCreatedAutoCond'));
3522
+ return;
3523
+ }
3524
+
3525
+ const branches = conditionBranchesForUI(exitNode, lang);
3526
+ const usedBranchIds = new Set(curEdges.filter((e) => e.from === exitNode.id).map((e) => (e.branch || branches[0].id)));
3527
+ let chosenBranchId = '';
3528
+ if (!isCustomBranches(exitNode) && !usedBranchIds.has('false')) {
3529
+ chosenBranchId = 'false';
3530
+ } else {
3531
+ for (let i = branches.length - 1; i >= 0; i -= 1) {
3532
+ if (!usedBranchIds.has(branches[i].id)) { chosenBranchId = branches[i].id; break; }
3533
+ }
3534
+ }
3535
+ if (!chosenBranchId) {
3536
+ chosenBranchId = 'c' + stamp.slice(-4);
3537
+ const nextBranches = branches.map((b) => ({ id: b.id, label: b.label }))
3538
+ .concat([{ id: chosenBranchId, label: t('loopRetryBranch') }]);
3539
+ setNodes((ns) => ns.map((n) => (n.id === exitNode.id ? { ...n, branches: nextBranches } : n)));
3540
+ }
3541
+ setEdges((es) => es.concat([{
3542
+ id: 'e' + stamp + 'l',
3543
+ from: exitNode.id,
3544
+ to: check.entryId,
3545
+ type: 'prompt',
3546
+ branch: chosenBranchId,
3547
+ loop: true,
3548
+ maxIterations: DEFAULT_LOOP_ITERATIONS,
3549
+ }]));
3550
+ setCtxMenu(null);
3551
+ flash(t('loopCreated'));
2772
3552
  };
2773
3553
 
2774
3554
  const insertNodeOnEdge = (edgeId, kind, atWorld) => {
@@ -2839,9 +3619,13 @@ window.__ModuleLoader__.load({
2839
3619
  const deleteNode = (id) => {
2840
3620
  if (id === 'lead') { flash(t('leadLocked')); return; }
2841
3621
  pushSnapshot();
2842
- setNodes((ns) => ns.filter((n) => n.id !== id));
2843
- setEdges((es) => es.filter((e) => e.from !== id && e.to !== id));
3622
+ const nextNodes = nodesRef.current.filter((n) => n.id !== id);
3623
+ const remainingEdges = edgesRef.current.filter((e) => e.from !== id && e.to !== id);
3624
+ const { edges: cleaned } = pruneInvalidLoopEdges(nextNodes, remainingEdges);
3625
+ setNodes(nextNodes);
3626
+ setEdges(cleaned);
2844
3627
  setSelectedIds([]);
3628
+ setLoopEditEdgeId(null);
2845
3629
  flash(t('deletedNode'));
2846
3630
  };
2847
3631
 
@@ -2852,9 +3636,13 @@ window.__ModuleLoader__.load({
2852
3636
  if (!targets.length) { flash(t('leadLocked')); return; }
2853
3637
  const drop = new Set(targets);
2854
3638
  pushSnapshot();
2855
- setNodes((ns) => ns.filter((n) => !drop.has(n.id)));
2856
- setEdges((es) => es.filter((e) => !drop.has(e.from) && !drop.has(e.to)));
3639
+ const nextNodes = nodesRef.current.filter((n) => !drop.has(n.id));
3640
+ const remainingEdges = edgesRef.current.filter((e) => !drop.has(e.from) && !drop.has(e.to));
3641
+ const { edges: cleaned } = pruneInvalidLoopEdges(nextNodes, remainingEdges);
3642
+ setNodes(nextNodes);
3643
+ setEdges(cleaned);
2857
3644
  setSelectedIds([]);
3645
+ setLoopEditEdgeId(null);
2858
3646
  flash(targets.length === 1 ? t('deletedNode') : t('deletedNodes') + ' ×' + targets.length);
2859
3647
  };
2860
3648
 
@@ -2882,11 +3670,13 @@ window.__ModuleLoader__.load({
2882
3670
 
2883
3671
  const toggleDirection = () => {
2884
3672
  const nextDir = directionRef.current === 'tb' ? 'lr' : 'tb';
2885
- setDirection(nextDir);
2886
3673
  const curNodes = nodesRef.current;
2887
3674
  const curEdges = edgesRef.current;
3675
+ if (curNodes.length) pushSnapshot();
3676
+ directionRef.current = nextDir;
3677
+ setDirection(nextDir);
3678
+ saveDefaultDirection(nextDir);
2888
3679
  if (curNodes.length) {
2889
- pushSnapshot();
2890
3680
  const next = layoutGraph(curNodes, curEdges, nextDir);
2891
3681
  setNodes(next);
2892
3682
  setTimeout(() => fitView(next), 0);
@@ -2920,7 +3710,7 @@ window.__ModuleLoader__.load({
2920
3710
  const { runs: _runs, ...rest } = n;
2921
3711
  return rest;
2922
3712
  });
2923
- 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);
2924
3714
  const fallbackCopy = () => {
2925
3715
  try {
2926
3716
  const ta = document.createElement('textarea');
@@ -2986,6 +3776,7 @@ window.__ModuleLoader__.load({
2986
3776
  setOpenModelFor(null);
2987
3777
  setAddMenu(null);
2988
3778
  setCtxMenu(null);
3779
+ setLoopEditEdgeId(null);
2989
3780
  e.preventDefault();
2990
3781
  e.stopPropagation();
2991
3782
  if (toggledOff) return;
@@ -3017,6 +3808,7 @@ window.__ModuleLoader__.load({
3017
3808
  setRoleEditFor(null);
3018
3809
  setDecisionViewFor(null);
3019
3810
  setRefsEditFor(null);
3811
+ setLoopEditEdgeId(null);
3020
3812
  };
3021
3813
 
3022
3814
  const addNodeRef = (node) => {
@@ -3075,8 +3867,12 @@ window.__ModuleLoader__.load({
3075
3867
  if (current.length <= 2) return;
3076
3868
  pushSnapshot();
3077
3869
  const next = current.filter((b) => b.id !== branchId);
3078
- updateNode(node.id, { branches: next });
3079
- 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);
3080
3876
  };
3081
3877
 
3082
3878
  const onOutputDown = (e, id, type, branch) => {
@@ -3093,38 +3889,62 @@ window.__ModuleLoader__.load({
3093
3889
  e.stopPropagation();
3094
3890
  };
3095
3891
 
3096
- /** Release over an output socket: completes a drag that started at the unified left input. */
3097
- const onOutputUp = (e, id, type, branch) => {
3098
- if (!pending || pending.dir !== 'in') return;
3099
- pendingHandledRef.current = true;
3100
- e.preventDefault();
3101
- e.stopPropagation();
3892
+ const tryAddEdge = (fromId, toId, type, branch, preferredMaxIter) => {
3893
+ if (!fromId || !toId || fromId === toId) return;
3102
3894
  const b = typeof branch === 'string' ? branch.trim() : '';
3103
- const toId = pending.toId;
3104
- if (toId && toId !== id) {
3105
- if (wouldCycle(nodesRef.current, edgesRef.current, id, toId)) {
3106
- flash(t('cycleBlocked'));
3107
- } else {
3895
+ if (wouldCycle(nodesRef.current, edgesRef.current, fromId, toId)) {
3896
+ const loopOk = canLinkAsLoop(nodesRef.current, edgesRef.current, fromId, toId);
3897
+ if (loopOk.ok) {
3108
3898
  pushSnapshot();
3899
+ const loopBranch = b || 'false';
3900
+ const maxIter = normalizeMaxIterationsUI(preferredMaxIter);
3109
3901
  setEdges((es) => {
3110
- if (es.some((x) => x.from === id && x.to === toId && x.type === type && (x.branch || '') === b)) return es;
3111
- const nextEdge = { id: 'e' + Date.now().toString(36), from: id, to: toId, type };
3112
- if (b) nextEdge.branch = b;
3113
- return [...es, nextEdge];
3902
+ if (es.some((x) => x.from === fromId && x.to === toId && (x.branch || '') === loopBranch)) return es;
3903
+ return [...es, {
3904
+ id: 'e' + Date.now().toString(36),
3905
+ from: fromId,
3906
+ to: toId,
3907
+ type: 'prompt',
3908
+ branch: loopBranch,
3909
+ loop: true,
3910
+ maxIterations: maxIter,
3911
+ }];
3114
3912
  });
3913
+ flash(t('loopCreated'));
3914
+ } else {
3915
+ flash(loopOk.reason === 'loopOverlap' ? t('loopOverlap') : t('cycleBlocked'));
3115
3916
  }
3917
+ return;
3116
3918
  }
3919
+ pushSnapshot();
3920
+ setEdges((es) => {
3921
+ if (es.some((x) => x.from === fromId && x.to === toId && x.type === type && (x.branch || '') === b)) return es;
3922
+ const nextEdge = { id: 'e' + Date.now().toString(36), from: fromId, to: toId, type };
3923
+ if (b) nextEdge.branch = b;
3924
+ return [...es, nextEdge];
3925
+ });
3926
+ };
3927
+
3928
+ /** Release over an output socket: completes a drag that started at the unified left input. */
3929
+ const onOutputUp = (e, id, type, branch) => {
3930
+ if (!pending || pending.dir !== 'in') return;
3931
+ pendingHandledRef.current = true;
3932
+ e.preventDefault();
3933
+ e.stopPropagation();
3934
+ tryAddEdge(id, pending.toId, type || 'prompt', branch, pending.maxIterations);
3117
3935
  setPending(null);
3118
3936
  setDragging(false);
3119
3937
  };
3120
3938
 
3121
- // Unified left input: dragging a connected input detaches the latest wire;
3939
+ // Unified left input: dragging a connected input detaches the latest forward wire
3940
+ // (preferring non-loop incoming links so loop back-edges aren't accidentally pulled);
3122
3941
  // dragging a free input starts a reverse wire that adopts whichever right output it drops onto.
3123
3942
  const onInputDown = (e, id) => {
3124
3943
  e.preventDefault();
3125
3944
  e.stopPropagation();
3126
3945
  const incoming = edges.filter((x) => x.to === id);
3127
- const link = incoming[incoming.length - 1];
3946
+ const forwardIncoming = incoming.filter((x) => !x.loop);
3947
+ const link = forwardIncoming.length ? forwardIncoming[forwardIncoming.length - 1] : incoming[incoming.length - 1];
3128
3948
  if (!link) {
3129
3949
  const node = nodes.find((n) => n.id === id);
3130
3950
  if (!node) return;
@@ -3136,7 +3956,9 @@ window.__ModuleLoader__.load({
3136
3956
  return;
3137
3957
  }
3138
3958
  pushSnapshot();
3139
- setEdges((es) => es.filter((x) => x.id !== link.id));
3959
+ const remaining = edgesRef.current.filter((x) => x.id !== link.id);
3960
+ const { edges: cleaned } = pruneInvalidLoopEdges(nodesRef.current, remaining);
3961
+ setEdges(cleaned);
3140
3962
  const from = nodes.find((n) => n.id === link.from);
3141
3963
  if (!from) return;
3142
3964
  const b = typeof link.branch === 'string' ? link.branch.trim() : '';
@@ -3145,7 +3967,18 @@ window.__ModuleLoader__.load({
3145
3967
  const sx = pos.x;
3146
3968
  const sy = pos.y;
3147
3969
  const color = edgeColorFor(from, link);
3148
- setPending({ dir: 'out', fromId: link.from, type: linkType, branch: b, color, sx, sy, x: sx, y: sy });
3970
+ setPending({
3971
+ dir: 'out',
3972
+ fromId: link.from,
3973
+ type: linkType,
3974
+ branch: b,
3975
+ maxIterations: link.loop ? normalizeMaxIterationsUI(link.maxIterations) : undefined,
3976
+ color,
3977
+ sx,
3978
+ sy,
3979
+ x: sx,
3980
+ y: sy,
3981
+ });
3149
3982
  setDragging(true);
3150
3983
  };
3151
3984
 
@@ -3154,22 +3987,7 @@ window.__ModuleLoader__.load({
3154
3987
  pendingHandledRef.current = true;
3155
3988
  e.preventDefault();
3156
3989
  e.stopPropagation();
3157
- if (pending.fromId !== id) {
3158
- const fromId = pending.fromId;
3159
- const type = pending.type || 'prompt';
3160
- const b = typeof pending.branch === 'string' ? pending.branch.trim() : '';
3161
- if (wouldCycle(nodesRef.current, edgesRef.current, fromId, id)) {
3162
- flash(t('cycleBlocked'));
3163
- } else {
3164
- pushSnapshot();
3165
- setEdges((es) => {
3166
- if (es.some((x) => x.from === fromId && x.to === id && x.type === type && (x.branch || '') === b)) return es;
3167
- const nextEdge = { id: 'e' + Date.now().toString(36), from: fromId, to: id, type };
3168
- if (b) nextEdge.branch = b;
3169
- return [...es, nextEdge];
3170
- });
3171
- }
3172
- }
3990
+ tryAddEdge(pending.fromId, id, pending.type || 'prompt', pending.branch, pending.maxIterations);
3173
3991
  setPending(null);
3174
3992
  setDragging(false);
3175
3993
  };
@@ -3192,8 +4010,7 @@ window.__ModuleLoader__.load({
3192
4010
  ev.preventDefault();
3193
4011
  ev.stopPropagation();
3194
4012
  try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
3195
- const cur = viewRef.current;
3196
- panDrag.current = { startX: ev.clientX, startY: ev.clientY, originX: cur.x, originY: cur.y };
4013
+ panDrag.current = { lastX: ev.clientX, lastY: ev.clientY };
3197
4014
  setPanning(true);
3198
4015
  setDragging(true);
3199
4016
  };
@@ -3234,8 +4051,8 @@ window.__ModuleLoader__.load({
3234
4051
  const keyActionsRef = useRef(null);
3235
4052
  keyActionsRef.current = {
3236
4053
  undo, redo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode, fitView, autoLayout, toggleDirection, flash, t,
3237
- addMenu, ctxMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, shortcutsOpen, recordingAction, decisionViewFor, refsEditFor,
3238
- setAddMenu, setCtxMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
4054
+ addMenu, ctxMenu, loopEditEdgeId, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, shortcutsOpen, recordingAction, decisionViewFor, refsEditFor,
4055
+ setAddMenu, setCtxMenu, setLoopEditEdgeId, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
3239
4056
  };
3240
4057
  useEffect(() => {
3241
4058
  const isEditable = (target) => {
@@ -3264,10 +4081,11 @@ window.__ModuleLoader__.load({
3264
4081
  return;
3265
4082
  }
3266
4083
  if (ev.key === 'Escape') {
3267
- if (act.addMenu || act.ctxMenu || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen || act.shortcutsOpen || act.decisionViewFor || act.refsEditFor) {
4084
+ if (act.addMenu || act.ctxMenu || act.loopEditEdgeId || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen || act.shortcutsOpen || act.decisionViewFor || act.refsEditFor) {
3268
4085
  ev.preventDefault();
3269
4086
  act.setAddMenu(null);
3270
4087
  act.setCtxMenu(null);
4088
+ act.setLoopEditEdgeId(null);
3271
4089
  act.setRoleEditFor(null);
3272
4090
  act.setOpenModelFor(null);
3273
4091
  act.setMenuOpen(false);
@@ -3358,11 +4176,27 @@ window.__ModuleLoader__.load({
3358
4176
  if (!dragging) return undefined;
3359
4177
  const move = (ev) => onCanvasMove(ev);
3360
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
+ };
3361
4193
  window.addEventListener('mousemove', move);
3362
4194
  window.addEventListener('mouseup', up);
4195
+ window.addEventListener('blur', cancelDrag);
3363
4196
  return () => {
3364
4197
  window.removeEventListener('mousemove', move);
3365
4198
  window.removeEventListener('mouseup', up);
4199
+ window.removeEventListener('blur', cancelDrag);
3366
4200
  };
3367
4201
  }, [dragging, marquee, pending]);
3368
4202
 
@@ -3382,6 +4216,7 @@ window.__ModuleLoader__.load({
3382
4216
  if (menuOpen) setMenuOpen(false);
3383
4217
  if (addMenu) setAddMenu(null);
3384
4218
  if (ctxMenu) setCtxMenu(null);
4219
+ if (loopEditEdgeId) setLoopEditEdgeId(null);
3385
4220
  if (presetOpen) setPresetOpen(null);
3386
4221
  e.preventDefault();
3387
4222
  try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
@@ -3394,10 +4229,9 @@ window.__ModuleLoader__.load({
3394
4229
 
3395
4230
  const onCanvasMove = (e) => {
3396
4231
  if (panDrag.current) {
3397
- const pan = panDrag.current;
3398
- const dx = e.clientX - pan.startX;
3399
- const dy = e.clientY - pan.startY;
3400
- 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);
3401
4235
  return;
3402
4236
  }
3403
4237
  if (rightClickRef.current && !rightClickRef.current.moved) {
@@ -3416,7 +4250,11 @@ window.__ModuleLoader__.load({
3416
4250
  const drag = nodeDrag.current;
3417
4251
  const dx = p.x - drag.startX;
3418
4252
  const dy = p.y - drag.startY;
3419
- 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
+ }
3420
4258
  const byId = new Map(drag.origins.map((o) => [o.id, o]));
3421
4259
  setNodes((ns) => ns.map((n) => {
3422
4260
  const origin = byId.get(n.id);
@@ -3439,7 +4277,7 @@ window.__ModuleLoader__.load({
3439
4277
  const source = nodeMap.get(edge.from);
3440
4278
  const target = nodeMap.get(edge.to);
3441
4279
  if (!source || !target) continue;
3442
- if (distanceToEdge(canvasSpot, source, target, edge, directionRef.current) <= threshold) {
4280
+ if (distanceToEdge(canvasSpot, source, target, edge, directionRef.current, nodes, edges) <= threshold) {
3443
4281
  cutHits.current.add(edge.id);
3444
4282
  }
3445
4283
  }
@@ -3478,7 +4316,7 @@ window.__ModuleLoader__.load({
3478
4316
  const source = nodeMap.get(edge.from);
3479
4317
  const target = nodeMap.get(edge.to);
3480
4318
  if (!source || !target) continue;
3481
- const dist = distanceToEdge(canvasSpot, source, target, edge, directionRef.current);
4319
+ const dist = distanceToEdge(canvasSpot, source, target, edge, directionRef.current, nodesRef.current, edgesRef.current);
3482
4320
  if (dist <= threshold && dist < bestDist) {
3483
4321
  bestDist = dist;
3484
4322
  hitEdge = edge;
@@ -3491,6 +4329,7 @@ window.__ModuleLoader__.load({
3491
4329
  setRoleEditFor(null);
3492
4330
  setDecisionViewFor(null);
3493
4331
  setRefsEditFor(null);
4332
+ setLoopEditEdgeId(null);
3494
4333
  if (hitEdge) {
3495
4334
  const pos = clampMenuPos(cx, cy, wrapRect.width, wrapRect.height, 180, 120);
3496
4335
  setCtxMenu({ kind: 'edge', edgeId: hitEdge.id, sx: pos.sx, sy: pos.sy, wx: rc.start.x, wy: rc.start.y });
@@ -3511,8 +4350,10 @@ window.__ModuleLoader__.load({
3511
4350
  cutHits.current = new Set();
3512
4351
  if (victims.length) {
3513
4352
  pushSnapshot();
3514
- setEdges((es) => es.filter((x) => !victimIds.has(x.id)));
3515
- flash(t('linkCut') + ' ×' + victims.length);
4353
+ const remaining = edgesRef.current.filter((x) => !victimIds.has(x.id));
4354
+ const { edges: cleaned, removedCount } = pruneInvalidLoopEdges(nodesRef.current, remaining);
4355
+ setEdges(cleaned);
4356
+ flash(t('linkCut') + ' ×' + victims.length + (removedCount > 0 ? t('loopPrunedNotice') : ''));
3516
4357
  }
3517
4358
  }
3518
4359
  if (cutPath.length) { setCutPath([]); setCutVictims([]); }
@@ -3565,11 +4406,22 @@ window.__ModuleLoader__.load({
3565
4406
  const savePresetNow = () => {
3566
4407
  const name = presetName.trim();
3567
4408
  if (!name) { flash(t('needName')); return; }
3568
- if (Object.prototype.hasOwnProperty.call(presets, name)) {
4409
+ const latest = loadPresets();
4410
+ if (Object.prototype.hasOwnProperty.call(latest, name)) {
4411
+ setPresets(latest);
3569
4412
  flash('"' + name + '" ' + t('dupName'));
3570
4413
  return;
3571
4414
  }
3572
- 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
+ };
3573
4425
  if (!savePresets(next)) { flash(t('saveFailed')); return; }
3574
4426
  setPresets(next);
3575
4427
  setPresetName('');
@@ -3591,6 +4443,12 @@ window.__ModuleLoader__.load({
3591
4443
  if (typeof doc.enabled === 'boolean') {
3592
4444
  setEnabled(doc.enabled);
3593
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
+ }
3594
4452
  const removedNodes = new Set(doc.removeNodes || []);
3595
4453
  const rawIncomingEdges = Array.isArray(doc.edges) ? doc.edges : [];
3596
4454
  setNodes((existing) => {
@@ -3632,10 +4490,19 @@ window.__ModuleLoader__.load({
3632
4490
  addedCount += 1;
3633
4491
  }
3634
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
+ }
3635
4502
  return { ...prev, ...n, x, y };
3636
4503
  });
3637
4504
  if (!merge) {
3638
- return isTB ? layoutGraph(incoming, rawIncomingEdges, 'tb') : incoming;
4505
+ return (isTB && !(hasExplicitDir && allHaveCoords)) ? layoutGraph(incoming, rawIncomingEdges, 'tb') : incoming;
3639
4506
  }
3640
4507
  const touched = new Set(incoming.map((n) => n.id));
3641
4508
  const kept = existing
@@ -3659,6 +4526,10 @@ window.__ModuleLoader__.load({
3659
4526
  };
3660
4527
  const b = typeof e.branch === 'string' ? e.branch.trim() : '';
3661
4528
  if (b) item.branch = b;
4529
+ if (e.loop === true) {
4530
+ item.loop = true;
4531
+ item.maxIterations = normalizeMaxIterationsUI(e.maxIterations);
4532
+ }
3662
4533
  return item;
3663
4534
  });
3664
4535
  if (!merge) return incoming;
@@ -3668,8 +4539,20 @@ window.__ModuleLoader__.load({
3668
4539
  && String(r.to) === e.to
3669
4540
  && (!r.type || r.type === e.type)
3670
4541
  && (!r.branch || r.branch === e.branch));
3671
- const kept = existing.filter((e) => !matchesDrop(e) && !removedNodes.has(e.from) && !removedNodes.has(e.to));
3672
4542
  const keyOf = (e) => e.from + '>' + e.to + '|' + e.type + '|' + (e.branch || '');
4543
+ const incomingByKey = new Map(incoming.map((e) => [keyOf(e), e]));
4544
+ const kept = existing
4545
+ .filter((e) => !matchesDrop(e) && !removedNodes.has(e.from) && !removedNodes.has(e.to))
4546
+ .map((e) => {
4547
+ const inc = incomingByKey.get(keyOf(e));
4548
+ if (!inc) return e;
4549
+ if (inc.loop) return { ...e, loop: true, maxIterations: inc.maxIterations };
4550
+ if (e.loop && !inc.loop) {
4551
+ const { loop: _l, maxIterations: _m, ...rest } = e;
4552
+ return rest;
4553
+ }
4554
+ return e;
4555
+ });
3673
4556
  const seen = new Set(kept.map(keyOf));
3674
4557
  const added = incoming.filter((e) => !removedNodes.has(e.from) && !removedNodes.has(e.to) && !seen.has(keyOf(e)));
3675
4558
  return kept.concat(added);
@@ -3802,20 +4685,31 @@ window.__ModuleLoader__.load({
3802
4685
  };
3803
4686
 
3804
4687
  const applyPreset = (name) => {
3805
- const preset = presets[name];
4688
+ const latest = loadPresets();
4689
+ const preset = latest[name] || presets[name];
3806
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 }));
3807
4697
  pushSnapshot();
4698
+ if (preset.direction === 'tb' || preset.direction === 'lr') {
4699
+ directionRef.current = preset.direction;
4700
+ setDirection(preset.direction);
4701
+ }
3808
4702
  if (enabled) {
3809
4703
  skipDirtyOnce.current = true;
3810
- pushPlan(true, preset.nodes, preset.edges);
4704
+ pushPlan(true, clonedNodes, clonedEdges);
3811
4705
  }
3812
- setNodes(preset.nodes);
3813
- setEdges(preset.edges);
4706
+ setNodes(clonedNodes);
4707
+ setEdges(clonedEdges);
3814
4708
  setSelectedIds([]);
3815
4709
  snapshotStaleCatalog();
3816
4710
  setRunsById({});
3817
4711
  setPresetOpen(null);
3818
- setTimeout(() => fitView(preset.nodes), 0);
4712
+ setTimeout(() => fitView(clonedNodes), 0);
3819
4713
  flash(t('loadedPreset') + ': ' + name);
3820
4714
  };
3821
4715
 
@@ -3839,7 +4733,8 @@ window.__ModuleLoader__.load({
3839
4733
  };
3840
4734
 
3841
4735
  const deletePreset = (name) => {
3842
- const next = { ...presets };
4736
+ const latest = loadPresets();
4737
+ const next = { ...latest };
3843
4738
  delete next[name];
3844
4739
  savePresets(next);
3845
4740
  setPresets(next);
@@ -3872,12 +4767,6 @@ window.__ModuleLoader__.load({
3872
4767
  const ids = ((hit && hit.efforts) || []).map((e) => e.id);
3873
4768
  return ['', ...(ids.length ? ids : REASONING_FALLBACK)];
3874
4769
  };
3875
- const reasoningLabel = (node) => {
3876
- if (!node.reasoning) return t('defaultEffort');
3877
- const hit = modelEntry(node);
3878
- const found = hit && hit.efforts ? hit.efforts.find((e) => e.id === node.reasoning) : undefined;
3879
- return (found && (found.name || found.id)) || node.reasoning;
3880
- };
3881
4770
 
3882
4771
  const scopeToggle = (node) => {
3883
4772
  const wide = (node.preset || 'standard') !== 'minimal';
@@ -4097,7 +4986,7 @@ window.__ModuleLoader__.load({
4097
4986
  const nodeById = new Map(nodes.map((n) => [n.id, n]));
4098
4987
  const inColorByNode = new Map();
4099
4988
  const inCountByNode = new Map();
4100
- const inPriority = (e) => (e.type === 'session-ref' ? 3 : (e.type === 'structured' ? 2 : (e.branch ? 1.5 : 1)));
4989
+ const inPriority = (e) => (e.loop ? 0.5 : (e.type === 'session-ref' ? 3 : (e.type === 'structured' ? 2 : (e.branch ? 1.5 : 1))));
4101
4990
  const inPrioByNode = new Map();
4102
4991
  const connectedOut = new Set();
4103
4992
  for (const e of edges) {
@@ -4115,66 +5004,70 @@ window.__ModuleLoader__.load({
4115
5004
  const soloLeadIds = soloLeadNodeIds(nodes, edges);
4116
5005
  const deadEndIds = deadEndNodeIds(nodes, edges);
4117
5006
 
4118
- // Lead nodes are never spawned, so their status is derived from graph state:
4119
- // - Intermediate Lead (has downstream): glows "Ready" until any child starts,
4120
- // then settles to "Done".
4121
- // - Terminal Lead (no downstream): Host finishes in one shot, so it glows only
4122
- // while the main conversation is still streaming (`sessionRunning`), then
4123
- // settles to "Done" once the turn ends.
4124
- const leadReadyIds = new Set();
4125
- const leadDoneIds = new Set();
4126
- const hasCondNode = nodes.some((x) => x.kind === 'condition');
4127
- if (enabled) {
4128
- if (runState && runState.waitingLead && runState.waitingLead.id) {
4129
- leadReadyIds.add(runState.waitingLead.id);
4130
- }
4131
- if (runState && Array.isArray(runState.done)) {
4132
- for (const did of runState.done) {
4133
- const dn = nodeById.get(did);
4134
- if (dn && dn.kind === 'lead' && dn.id !== 'lead') leadDoneIds.add(did);
4135
- }
4136
- }
4137
- for (const n of nodes) {
4138
- if (n.kind !== 'lead' || n.id === 'lead' || !reachableIds.has(n.id)) continue;
4139
- if (leadReadyIds.has(n.id) || leadDoneIds.has(n.id)) continue;
4140
- const upIds = edges
4141
- .filter((e) => e.to === n.id && e.from !== 'lead' && nodeById.has(e.from))
4142
- .map((e) => e.from);
4143
- if (!upIds.length) continue;
4144
- const upAgents = upIds.filter((id) => nodeById.get(id).kind !== 'lead');
4145
- if (!upAgents.length) continue;
4146
- const anyUpRunning = upAgents.some((id) => statusById[id] === 'running');
4147
- const allUpDone = hasCondNode
4148
- ? (!anyUpRunning && upAgents.some((id) => statusById[id] === 'done' || statusById[id] === 'failed'))
4149
- : upAgents.every((id) => statusById[id] === 'done' || statusById[id] === 'failed');
4150
- if (!allUpDone) continue;
4151
- const downIds = edges.filter((e) => e.from === n.id).map((e) => e.to);
4152
- if (!downIds.length) {
4153
- if (sessionRunning) leadReadyIds.add(n.id);
4154
- else leadDoneIds.add(n.id);
4155
- } else {
4156
- const anyDownStarted = downIds.some((id) => Boolean(statusById[id]));
4157
- if (!anyDownStarted) leadReadyIds.add(n.id);
4158
- else leadDoneIds.add(n.id);
4159
- }
4160
- }
4161
- }
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
+ });
4162
5032
 
4163
5033
  const decisionsById = (enabled && runState && runState.decisions && typeof runState.decisions === 'object')
4164
5034
  ? runState.decisions
4165
5035
  : {};
4166
5036
  const prunedSet = new Set(enabled && runState && Array.isArray(runState.pruned) ? runState.pruned : []);
4167
5037
  const blockedEdgeSet = new Set(enabled && runState && Array.isArray(runState.blockedEdges) ? runState.blockedEdges : []);
5038
+ const loopCountsMap = (enabled && runState && runState.loopCounts && typeof runState.loopCounts === 'object')
5039
+ ? runState.loopCounts
5040
+ : {};
5041
+ const nodeAttemptsMap = (enabled && runState && runState.nodeAttempts && typeof runState.nodeAttempts === 'object')
5042
+ ? runState.nodeAttempts
5043
+ : {};
5044
+ const loopGroups = loopGroupsForUI(nodes, edges);
4168
5045
  const edgeKeyForState = (e) => String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
5046
+ const loopPillItems = [];
4169
5047
 
4170
5048
  const edgeEls = edges.map((edge) => {
4171
5049
  const from = nodeById.get(edge.from);
4172
5050
  const to = nodeById.get(edge.to);
4173
5051
  if (!from || !to) return null;
4174
- const color = edgeColorFor(from, edge);
4175
- const d = edgePath(from, to, edge, direction);
5052
+ const isLoop = edge.loop === true;
5053
+ const loopInfo = isLoop ? loopGroups.byEdge.get(edge.id || (edge.from + '->' + edge.to)) : null;
5054
+ const color = isLoop ? ((loopInfo && loopInfo.color) || '#f0883e') : edgeColorFor(from, edge);
5055
+ const loopArc = isLoop ? loopEdgeArc(from, to, edge, direction, nodes, edges) : null;
5056
+ const d = loopArc ? loopArc.path : edgePath(from, to, edge, direction, nodes, edges);
4176
5057
  const highlighted = cutVictims.includes(edge.id);
4177
5058
  const isPrunedEdge = !highlighted && (blockedEdgeSet.has(edgeKeyForState(edge)) || prunedSet.has(edge.from) || prunedSet.has(edge.to));
5059
+ if (loopArc) {
5060
+ const live = loopCountsMap[edge.id] || loopCountsMap[edgeKeyForState(edge)] || null;
5061
+ loopPillItems.push({
5062
+ edge,
5063
+ color,
5064
+ midX: loopArc.midX,
5065
+ midY: loopArc.midY,
5066
+ maxIterations: normalizeMaxIterationsUI(edge.maxIterations),
5067
+ liveCount: live ? Number(live.count || 0) : 0,
5068
+ dimmed: isPrunedEdge,
5069
+ });
5070
+ }
4178
5071
  const hasSel = selectedSet.size > 0;
4179
5072
  const linkedToSel = hasSel && (selectedSet.has(edge.from) || selectedSet.has(edge.to));
4180
5073
  const toRunning = enabled && statusById[edge.to] === 'running';
@@ -4198,11 +5091,24 @@ window.__ModuleLoader__.load({
4198
5091
  const isCompletedLink = enabled && !highlighted && !isPrunedEdge && fromSettled && toSettled;
4199
5092
  const dimmed = isPrunedEdge || (hasSel && !linkedToSel && !highlighted && !isFlowing);
4200
5093
  const strokeColor = highlighted ? '#e5534b' : color;
4201
- const baseWidth = highlighted ? 3 : (linkedToSel || isFlowing ? 2.6 : 2);
4202
- const baseOpacity = isPrunedEdge ? 0.22 : (dimmed ? 0.26 : (isFlowing || linkedToSel ? 1 : (isCompletedLink ? 0.92 : 0.78)));
5094
+ const baseWidth = highlighted ? 3 : (linkedToSel || isFlowing || isLoop ? 2.4 : 2);
5095
+ const baseOpacity = isPrunedEdge ? 0.22 : (dimmed ? 0.26 : (isFlowing || linkedToSel || isLoop ? 0.96 : (isCompletedLink ? 0.92 : 0.78)));
4203
5096
  const useGlow = fxLevel === 'vivid' && !dimmed;
4204
5097
  const showDashFlow = isFlowing && fxLevel !== 'minimal';
4205
5098
  const showBead = isFlowing && fxLevel === 'vivid';
5099
+ // Arrowhead on loop entry point so the retry direction is unmistakable
5100
+ let loopArrow = null;
5101
+ if (loopArc && loopArc.points.length >= 2) {
5102
+ const endPt = loopArc.points[loopArc.points.length - 1];
5103
+ const prevPt = loopArc.points[loopArc.points.length - 2];
5104
+ const ang = Math.atan2(endPt.y - prevPt.y, endPt.x - prevPt.x);
5105
+ const sz = 7;
5106
+ const ax1 = endPt.x - sz * Math.cos(ang - 0.5);
5107
+ const ay1 = endPt.y - sz * Math.sin(ang - 0.5);
5108
+ const ax2 = endPt.x - sz * Math.cos(ang + 0.5);
5109
+ const ay2 = endPt.y - sz * Math.sin(ang + 0.5);
5110
+ loopArrow = endPt.x.toFixed(1) + ',' + endPt.y.toFixed(1) + ' ' + ax1.toFixed(1) + ',' + ay1.toFixed(1) + ' ' + ax2.toFixed(1) + ',' + ay2.toFixed(1);
5111
+ }
4206
5112
 
4207
5113
  return h('g', { key: edge.id, style: { pointerEvents: 'none' } },
4208
5114
  // Vector halo layers instead of an SVG objectBoundingBox <filter>, which
@@ -4228,9 +5134,14 @@ window.__ModuleLoader__.load({
4228
5134
  stroke: strokeColor,
4229
5135
  strokeWidth: baseWidth,
4230
5136
  strokeOpacity: showDashFlow ? 0.35 : baseOpacity,
4231
- strokeDasharray: isPrunedEdge ? '4 4' : undefined,
5137
+ strokeDasharray: isLoop ? '6 4' : (isPrunedEdge ? '4 4' : undefined),
4232
5138
  fill: 'none',
4233
5139
  }),
5140
+ loopArrow && h('polygon', {
5141
+ points: loopArrow,
5142
+ fill: strokeColor,
5143
+ fillOpacity: baseOpacity,
5144
+ }),
4234
5145
  showDashFlow && fxLevel === 'vivid' && h('path', {
4235
5146
  d,
4236
5147
  className: 'dsh-wc-edge-flow',
@@ -4549,6 +5460,39 @@ window.__ModuleLoader__.load({
4549
5460
  h('button', { style: S.btn, onClick: () => addNode('lead'), type: 'button' }, t('addLead')),
4550
5461
  h('button', { style: S.btn, onClick: () => addNode('condition'), type: 'button' }, t('addCond')),
4551
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 }),
4552
5496
  h('button', {
4553
5497
  style: enabled && dirty ? S.btnDirty : S.btn,
4554
5498
  onClick: () => pushPlan(enabled),
@@ -4574,8 +5518,11 @@ window.__ModuleLoader__.load({
4574
5518
  onClick: (e) => {
4575
5519
  const next = presetOpen === 'menu' ? null : 'menu';
4576
5520
  if (next) {
5521
+ refreshPresets(false);
4577
5522
  setMenuOpen(false);
4578
5523
  setCtxMenu(null);
5524
+ setLoopEditEdgeId(null);
5525
+ setOpenModelFor(null);
4579
5526
  const rootRect = rootElRef.current && rootElRef.current.getBoundingClientRect();
4580
5527
  const btnRect = e.currentTarget && e.currentTarget.getBoundingClientRect();
4581
5528
  setPresetAlign(dropdownAlign(btnRect, rootRect, 248));
@@ -4622,17 +5569,45 @@ window.__ModuleLoader__.load({
4622
5569
  onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
4623
5570
  onClick: () => clearCanvas(),
4624
5571
  }, h('span', { style: S.presetRowText }, t('newBlankCanvas'))),
4625
- h('div', { style: S.menuHead }, t('myPresets')),
4626
- names.length
4627
- ? names.map((name) => h('div', {
4628
- key: name,
4629
- style: S.presetRow,
4630
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
4631
- 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',
4632
5583
  },
4633
- h('span', { style: S.presetRowText, onClick: () => applyPreset(name) }, name),
4634
- h('button', { style: S.presetDel, type: 'button', title: t('del'), onClick: () => deletePreset(name) }, '×'),
4635
- ))
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
+ })
4636
5611
  : h('div', { style: S.presetEmpty }, t('presetEmpty')),
4637
5612
  h('div', { style: S.menuHead }, t('builtinTemplates')),
4638
5613
  templates.map((tpl) => h('div', {
@@ -4655,6 +5630,8 @@ window.__ModuleLoader__.load({
4655
5630
  if (next) {
4656
5631
  setPresetOpen(null);
4657
5632
  setCtxMenu(null);
5633
+ setLoopEditEdgeId(null);
5634
+ setOpenModelFor(null);
4658
5635
  const rootRect = rootElRef.current && rootElRef.current.getBoundingClientRect();
4659
5636
  const btnRect = e.currentTarget && e.currentTarget.getBoundingClientRect();
4660
5637
  setMenuAlign(dropdownAlign(btnRect, rootRect, 204));
@@ -4886,31 +5863,45 @@ window.__ModuleLoader__.load({
4886
5863
  if (tag !== 'INPUT' && tag !== 'TEXTAREA') e.preventDefault();
4887
5864
  },
4888
5865
  },
4889
- h('button', {
4890
- style: enabled
4891
- ? {
4892
- ...S.floatOn,
4893
- display: 'inline-flex',
4894
- alignItems: 'center',
4895
- gap: '6px',
4896
- lineHeight: '14px',
4897
- boxShadow: fxLevel === 'vivid'
4898
- ? '0 0 14px rgba(47,129,247,0.35), 0 4px 14px rgba(0,0,0,0.35)'
4899
- : S.floatOn.boxShadow,
4900
- }
4901
- : { ...S.floatOff, display: 'inline-flex', alignItems: 'center', gap: '6px', lineHeight: '14px' },
4902
- type: 'button',
4903
- onMouseDown: (e) => e.stopPropagation(),
4904
- onClick: toggleEnabled,
4905
- title: t('tipToggle'),
4906
- },
4907
- h('span', {
4908
- className: enabled && fxLevel === 'vivid' ? 'dsh-wc-dot-live' : undefined,
5866
+ h('div', { style: S.floatTopLeft, onMouseDown: (e) => e.stopPropagation() },
5867
+ h('button', {
4909
5868
  style: enabled
4910
- ? { width: '7px', height: '7px', borderRadius: '50%', background: C.accent, flex: '0 0 auto' }
4911
- : { width: '7px', height: '7px', borderRadius: '50%', border: '1.5px solid ' + C.dim, boxSizing: 'border-box', flex: '0 0 auto' },
4912
- }),
4913
- 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),
4914
5905
  ),
4915
5906
  addMenu && (() => {
4916
5907
  const lf = addMenu.linkFrom || null;
@@ -4958,11 +5949,14 @@ window.__ModuleLoader__.load({
4958
5949
  const target = nodeById.get(ctxMenu.nodeId);
4959
5950
  if (!target) return null;
4960
5951
  const multiSel = selectedIds.length > 1 && selectedSet.has(target.id);
4961
- const nonLeadCount = (multiSel ? selectedIds : [target.id]).filter((id) => id !== 'lead').length;
5952
+ const selList = multiSel ? selectedIds : [target.id];
5953
+ const nonLeadCount = selList.filter((id) => id !== 'lead').length;
4962
5954
  const suffix = nonLeadCount > 1 ? ' ×' + nonLeadCount : '';
4963
5955
  const latestRun = target.kind !== 'lead' ? runsById[target.id] : null;
5956
+ const existingLoop = loopGroups.byNode.get(target.id) || null;
5957
+ const loopCheck = !existingLoop ? analyzeLoopSelection(nodes, edges, selList) : { ok: false };
4964
5958
  return h('div', {
4965
- style: { ...S.addMenu, minWidth: '172px', left: ctxMenu.sx + 'px', top: ctxMenu.sy + 'px' },
5959
+ style: { ...S.addMenu, minWidth: '176px', left: ctxMenu.sx + 'px', top: ctxMenu.sy + 'px' },
4966
5960
  onMouseDown: (e) => e.stopPropagation(),
4967
5961
  onContextMenu: (e) => e.preventDefault(),
4968
5962
  },
@@ -4970,6 +5964,18 @@ window.__ModuleLoader__.load({
4970
5964
  menuRow('edit', t('ctxEditText'), () => { setCtxMenu(null); setRoleEditFor(target.id); }),
4971
5965
  menuRow('refs', t('ctxManageRefs'), () => { setCtxMenu(null); setRefsEditFor(target.id); }),
4972
5966
  latestRun && menuRow('chat', t('ctxOpenChat'), () => { setCtxMenu(null); openNodeSession(target); }),
5967
+ existingLoop && h('div', { style: S.ctxDivider }),
5968
+ existingLoop && menuRow('edit-loop', t('ctxEditLoop'), () => {
5969
+ setCtxMenu(null);
5970
+ openLoopEditor(existingLoop.edge);
5971
+ }),
5972
+ existingLoop && menuRow('rm-loop', t('ctxRemoveLoop'), () => deleteEdgeById(existingLoop.edge.id), { danger: true }),
5973
+ !existingLoop && loopCheck.ok && h('div', { style: S.ctxDivider }),
5974
+ !existingLoop && loopCheck.ok && menuRow(
5975
+ 'make-loop',
5976
+ loopCheck.needsAutoCondition ? t('ctxMakeLoopAuto') : t('ctxMakeLoop'),
5977
+ () => createLoopFromSelection(selList),
5978
+ ),
4973
5979
  nonLeadCount > 0 && h('div', { style: S.ctxDivider }),
4974
5980
  nonLeadCount > 0 && menuRow('dup', t('ctxDup') + suffix, () => { setCtxMenu(null); duplicateSelected(); }, { hint: shortcuts.duplicate || '' }),
4975
5981
  nonLeadCount > 0 && menuRow('del', t('ctxDelNode') + suffix, () => {
@@ -4988,10 +5994,21 @@ window.__ModuleLoader__.load({
4988
5994
  onContextMenu: (e) => e.preventDefault(),
4989
5995
  },
4990
5996
  h('div', { style: S.addMenuHead }, t('ctxEdgeTitle')),
4991
- menuRow('ins-agent', t('ctxInsertAgent'), () => insertNodeOnEdge(targetEdge.id, 'agent', { x: ctxMenu.wx, y: ctxMenu.wy })),
4992
- menuRow('ins-cond', t('ctxInsertCond'), () => insertNodeOnEdge(targetEdge.id, 'condition', { x: ctxMenu.wx, y: ctxMenu.wy })),
4993
- h('div', { style: S.ctxDivider }),
4994
- menuRow('del-edge', t('ctxDelEdge'), () => deleteEdgeById(targetEdge.id), { danger: true }),
5997
+ targetEdge.loop
5998
+ ? h(React.Fragment, null,
5999
+ menuRow('edit-loop', t('ctxEditLoop'), () => {
6000
+ setCtxMenu(null);
6001
+ openLoopEditor(targetEdge);
6002
+ }),
6003
+ h('div', { style: S.ctxDivider }),
6004
+ menuRow('rm-loop', t('ctxRemoveLoop'), () => deleteEdgeById(targetEdge.id), { danger: true }),
6005
+ )
6006
+ : h(React.Fragment, null,
6007
+ menuRow('ins-agent', t('ctxInsertAgent'), () => insertNodeOnEdge(targetEdge.id, 'agent', { x: ctxMenu.wx, y: ctxMenu.wy })),
6008
+ menuRow('ins-cond', t('ctxInsertCond'), () => insertNodeOnEdge(targetEdge.id, 'condition', { x: ctxMenu.wx, y: ctxMenu.wy })),
6009
+ h('div', { style: S.ctxDivider }),
6010
+ menuRow('del-edge', t('ctxDelEdge'), () => deleteEdgeById(targetEdge.id), { danger: true }),
6011
+ ),
4995
6012
  );
4996
6013
  }
4997
6014
  return h('div', {
@@ -5079,21 +6096,105 @@ window.__ModuleLoader__.load({
5079
6096
  return h('path', { d, stroke: color, strokeWidth: 2, strokeDasharray: '4 4', fill: 'none' });
5080
6097
  })(),
5081
6098
  ),
6099
+ loopPillItems.map((item) => {
6100
+ const isOpen = loopEditEdgeId === item.edge.id;
6101
+ const pillText = item.liveCount > 0
6102
+ ? ('↺ ' + item.liveCount + '/' + item.maxIterations)
6103
+ : ('↺ ×' + item.maxIterations);
6104
+ const commitLoopDraft = (closeAfter) => {
6105
+ const v = parseInt(String(loopDraft || '').trim(), 10);
6106
+ if (Number.isFinite(v)) updateLoopMaxIterations(item.edge.id, v);
6107
+ else setLoopDraft(String(item.maxIterations));
6108
+ if (closeAfter) setLoopEditEdgeId(null);
6109
+ };
6110
+ return h('div', {
6111
+ key: 'loop-pill-' + item.edge.id,
6112
+ style: {
6113
+ ...S.loopPill,
6114
+ left: item.midX + 'px',
6115
+ top: item.midY + 'px',
6116
+ border: '1.5px solid ' + item.color,
6117
+ color: item.color,
6118
+ opacity: item.dimmed && !isOpen ? 0.42 : 1,
6119
+ zIndex: isOpen ? 55 : 18,
6120
+ },
6121
+ title: t('loopTipPill'),
6122
+ onMouseDown: (e) => e.stopPropagation(),
6123
+ onContextMenu: (e) => {
6124
+ e.preventDefault();
6125
+ e.stopPropagation();
6126
+ if (isOpen) setLoopEditEdgeId(null);
6127
+ else openLoopEditor(item.edge);
6128
+ },
6129
+ onClick: (e) => {
6130
+ e.stopPropagation();
6131
+ setCtxMenu(null);
6132
+ if (isOpen) setLoopEditEdgeId(null);
6133
+ else openLoopEditor(item.edge);
6134
+ },
6135
+ },
6136
+ h('span', null, pillText),
6137
+ isOpen && h('div', {
6138
+ style: S.loopPopover,
6139
+ onMouseDown: (e) => e.stopPropagation(),
6140
+ onClick: (e) => e.stopPropagation(),
6141
+ },
6142
+ h('div', {
6143
+ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px', fontSize: '10px', color: C.dim },
6144
+ },
6145
+ h('span', null, t('loopModalTitle')),
6146
+ h('button', {
6147
+ type: 'button',
6148
+ style: { background: 'transparent', border: 'none', color: C.dim, cursor: 'pointer', fontSize: '12px', padding: '0 2px' },
6149
+ onClick: () => setLoopEditEdgeId(null),
6150
+ }, '×'),
6151
+ ),
6152
+ h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', marginBottom: '7px' } },
6153
+ h('button', {
6154
+ type: 'button',
6155
+ style: S.loopStepBtn,
6156
+ disabled: item.maxIterations <= 1,
6157
+ onClick: () => updateLoopMaxIterations(item.edge.id, item.maxIterations - 1),
6158
+ }, '−'),
6159
+ h('input', {
6160
+ type: 'text',
6161
+ inputMode: 'numeric',
6162
+ style: S.loopNumInput,
6163
+ value: loopDraft,
6164
+ onChange: (e) => {
6165
+ const raw = e.target.value.replace(/[^\d]/g, '').slice(0, 2);
6166
+ setLoopDraft(raw);
6167
+ },
6168
+ onBlur: () => commitLoopDraft(false),
6169
+ onKeyDown: (e) => {
6170
+ if (e.key === 'Enter') {
6171
+ e.preventDefault();
6172
+ commitLoopDraft(true);
6173
+ } else if (e.key === 'Escape') {
6174
+ e.preventDefault();
6175
+ setLoopEditEdgeId(null);
6176
+ }
6177
+ },
6178
+ }),
6179
+ h('button', {
6180
+ type: 'button',
6181
+ style: S.loopStepBtn,
6182
+ disabled: item.maxIterations >= MAX_LOOP_ITERATIONS,
6183
+ onClick: () => updateLoopMaxIterations(item.edge.id, item.maxIterations + 1),
6184
+ }, '+'),
6185
+ ),
6186
+ h('button', {
6187
+ type: 'button',
6188
+ style: { ...S.btn, width: '100%', padding: '3px 6px', fontSize: '10px', color: '#e5534b', textAlign: 'center' },
6189
+ onClick: () => deleteEdgeById(item.edge.id),
6190
+ }, t('ctxRemoveLoop')),
6191
+ ),
6192
+ );
6193
+ }),
5082
6194
  nodes.map((node) => {
5083
6195
  const isEntry = node.id === 'lead';
5084
6196
  const isLeadKind = node.kind === 'lead';
5085
6197
  const isCondKind = node.kind === 'condition';
5086
- const roleInput = (style) => h('div', { style },
5087
- h('span', { style: S.fieldLabel }, t('role')),
5088
- h('input', {
5089
- style: S.input,
5090
- value: node.role || '',
5091
- placeholder: isLeadKind ? t('rolePhLead') : t('rolePhAgent'),
5092
- onMouseDown: (e) => e.stopPropagation(),
5093
- onFocus: () => setSelectedIds([node.id]),
5094
- onChange: (e) => updateNode(node.id, { role: e.target.value }),
5095
- }),
5096
- );
5097
6198
  const isOrphan = node.id !== 'lead' && !reachableIds.has(node.id);
5098
6199
  const isSoloLead = soloLeadIds.has(node.id);
5099
6200
  const isDeadEnd = deadEndIds.has(node.id);
@@ -5127,11 +6228,19 @@ window.__ModuleLoader__.load({
5127
6228
  : 'linear-gradient(90deg, #2f81f7 0%, #58d580 50%, #2f81f7 100%)'))
5128
6229
  : (isFailed ? '#e5534b' : (isLeadKind ? '#2f81f7' : (isCondKind ? '#d29922' : '#3fb950')));
5129
6230
  const isPruned = enabled && prunedSet.has(node.id);
6231
+ const nodeLoop = loopGroups.byNode.get(node.id) || null;
6232
+ const nodeAttempt = nodeAttemptsMap[node.id] || null;
5130
6233
  const condDecision = isCondKind ? (decisionsById[node.id] || null) : null;
5131
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.
5132
6237
  const hasOpenPopover = decisionViewFor === node.id
5133
6238
  || refsEditFor === node.id
5134
6239
  || roleEditFor === node.id
6240
+ || openModelFor === node.id
6241
+ || openModelFor === ('r:' + node.id)
6242
+ || openModelFor === ('f:' + node.id)
6243
+ || openModelFor === ('m:' + node.id)
5135
6244
  || (typeof roleEditFor === 'string' && roleEditFor.includes(':' + node.id + ':'));
5136
6245
  return h('div', {
5137
6246
  key: node.id,
@@ -5145,12 +6254,22 @@ window.__ModuleLoader__.load({
5145
6254
  ...(isLeadKind ? S.leadNode : null),
5146
6255
  ...(isInactive || isPruned ? S.orphanNode : null),
5147
6256
  ...(stateStyle || null),
6257
+ ...(nodeLoop ? { outline: '1.5px dashed ' + nodeLoop.color, outlineOffset: '3px' } : null),
5148
6258
  ...(hasOpenPopover ? { zIndex: 40 } : null),
5149
6259
  },
5150
6260
  title: isPruned ? t('tipPruned') : (isOrphan ? t('orphanTip') : (isSoloLead ? t('tipSoloLead') : (isDeadEnd ? t('tipDeadEnd') : undefined))),
5151
6261
  onMouseDown: (e) => onNodeDown(e, node.id),
5152
6262
  onContextMenu: (e) => onNodeContextMenu(e, node),
5153
6263
  },
6264
+ nodeLoop && h('div', {
6265
+ style: {
6266
+ ...S.loopNodeTag,
6267
+ color: nodeLoop.color,
6268
+ border: '1px solid ' + nodeLoop.color,
6269
+ },
6270
+ }, nodeAttempt && nodeAttempt.retry > 0
6271
+ ? ('↺ ' + nodeAttempt.retry + '/' + nodeAttempt.max)
6272
+ : ('↺' + nodeLoop.index)),
5154
6273
  h('div', {
5155
6274
  className: (isRunning || isLeadReady) && fxLevel === 'vivid' ? 'dsh-wc-topbar-vivid' : undefined,
5156
6275
  style: {
@@ -5162,14 +6281,11 @@ window.__ModuleLoader__.load({
5162
6281
  h('div', { style: S.bandDivider }),
5163
6282
  isEntry
5164
6283
  ? (() => {
5165
- const waitingLead = runState
5166
- ? (runState.waitingLead || null)
5167
- : (leadReadyIds.size > 0 ? { id: Array.from(leadReadyIds)[0] } : null);
5168
6284
  const btn = entryRunButtonState({
5169
6285
  enabled,
5170
6286
  task: node.task || '',
5171
6287
  sessionRunning,
5172
- waitingLead,
6288
+ waitingLead: activeWaitingLead,
5173
6289
  triggering: runTriggering,
5174
6290
  lang,
5175
6291
  });
@@ -5183,35 +6299,67 @@ window.__ModuleLoader__.load({
5183
6299
  const borderColor = isReady
5184
6300
  ? 'rgba(63,185,80,0.6)'
5185
6301
  : (isRun ? 'rgba(47,129,247,0.6)' : (isWait ? 'rgba(210,153,34,0.6)' : C.border));
5186
- return h('button', {
5187
- type: 'button',
5188
- disabled: btn.disabled,
6302
+ const bottomOffset = direction === 'tb' ? '28px' : '4px';
6303
+ return h('div', {
5189
6304
  style: {
5190
- ...S.statusBtn,
5191
- bottom: direction === 'tb' ? '28px' : '4px',
5192
- color,
5193
- background: bg,
5194
- borderColor,
5195
- opacity: btn.state === 'disabled' ? 0.55 : 1,
5196
- cursor: btn.disabled ? 'not-allowed' : 'pointer',
5197
- 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',
5198
6312
  },
5199
- title: btn.title,
5200
6313
  onMouseDown: (e) => e.stopPropagation(),
5201
- onMouseEnter: (e) => { if (!btn.disabled) e.currentTarget.style.background = 'rgba(63,185,80,0.24)'; },
5202
- onMouseLeave: (e) => { e.currentTarget.style.background = bg; },
5203
- onClick: (e) => { e.stopPropagation(); if (!btn.disabled) runFromEntry(); },
5204
6314
  },
5205
- isRun && h('span', {
5206
- className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
5207
- style: { width: '6px', height: '6px', borderRadius: '50%', background: color, flex: '0 0 auto' },
5208
- }),
5209
- 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 ? '…' : '⏹'),
5210
6358
  );
5211
6359
  })()
5212
6360
  : isDeadEnd
5213
6361
  ? h('div', {
5214
- style: S.warnChip,
6362
+ style: { ...S.warnChip, bottom: (direction === 'tb' && !isCondKind) ? '28px' : '5px' },
5215
6363
  title: t('tipDeadEnd'),
5216
6364
  onMouseDown: (e) => e.stopPropagation(),
5217
6365
  }, '⚠ ', t('stDeadEnd'))
@@ -5556,13 +6704,14 @@ window.__ModuleLoader__.load({
5556
6704
  scope.effect(() => scope.slots.inject('sidebar.right.pane.tab', () => scope.slots.register({
5557
6705
  name: 'sidebar.right.pane.tab',
5558
6706
  key: TAB_ID,
5559
- }, (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');
5560
6709
  });
5561
6710
  } catch (error) {
5562
6711
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
5563
6712
  }
5564
6713
  },
5565
- __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 },
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 },
5566
6715
  };
5567
6716
  },
5568
6717
  });