dsh-workflow-canvas 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -31,15 +31,59 @@ window.__ModuleLoader__.load({
31
31
  const PRESET_KEY = STORAGE_PREFIX + 'presets';
32
32
 
33
33
  const NODE_W = 216;
34
- const NODE_H = 224;
34
+ const NODE_H = 234;
35
35
  const PORT = 12;
36
- const SOCKET_BAND_TOP = 168;
36
+ const SOCKET_BAND_TOP = 176;
37
37
  const ROW_H = 18;
38
38
  const CONTENT_W = 2400;
39
39
  const CONTENT_H = 1600;
40
40
  /** World origin offset: keeps negative node coordinates inside the scroll area. */
41
41
  const WORLD_PAD = 2000;
42
42
 
43
+ const FX_KEY = STORAGE_PREFIX + 'fx';
44
+ const FX_LEVELS = ['minimal', 'standard', 'vivid'];
45
+ const STYLE_ID = 'dsh-workflow-canvas-styles';
46
+
47
+ /** Inject scoped CSS keyframes once; never touches host selectors. */
48
+ function ensureStyles() {
49
+ try {
50
+ if (typeof document === 'undefined' || !document.head) return;
51
+ if (document.getElementById(STYLE_ID)) return;
52
+ const style = document.createElement('style');
53
+ style.id = STYLE_ID;
54
+ style.textContent = [
55
+ '@keyframes dsh-wc-pulse-ring {',
56
+ ' 0%, 100% { box-shadow: 0 0 0 1px rgba(47,129,247,0.45), 0 0 10px rgba(47,129,247,0.16); }',
57
+ ' 50% { box-shadow: 0 0 0 2px rgba(47,129,247,0.8), 0 0 18px rgba(47,129,247,0.34); }',
58
+ '}',
59
+ '@keyframes dsh-wc-pulse-vivid {',
60
+ ' 0%, 100% { box-shadow: 0 0 0 2px rgba(47,129,247,0.55), 0 0 14px rgba(47,129,247,0.28); }',
61
+ ' 50% { box-shadow: 0 0 0 3px rgba(47,129,247,0.92), 0 0 28px rgba(47,129,247,0.52); }',
62
+ '}',
63
+ '@keyframes dsh-wc-dash {',
64
+ ' from { stroke-dashoffset: 28; }',
65
+ ' to { stroke-dashoffset: 0; }',
66
+ '}',
67
+ '@keyframes dsh-wc-shimmer {',
68
+ ' 0% { background-position: 200% 0; }',
69
+ ' 100% { background-position: -200% 0; }',
70
+ '}',
71
+ '@keyframes dsh-wc-dot {',
72
+ ' 0%, 100% { opacity: 1; transform: scale(1); }',
73
+ ' 50% { opacity: 0.42; transform: scale(0.82); }',
74
+ '}',
75
+ '.dsh-wc-node { transition: box-shadow 180ms ease, border-color 180ms ease, opacity 180ms ease; }',
76
+ '.dsh-wc-node:hover { box-shadow: 0 4px 16px rgba(0,0,0,0.24); }',
77
+ '.dsh-wc-running-std { animation: dsh-wc-pulse-ring 2.1s ease-in-out infinite; }',
78
+ '.dsh-wc-running-vivid { animation: dsh-wc-pulse-vivid 1.65s ease-in-out infinite; }',
79
+ '.dsh-wc-topbar-vivid { background-size: 220% 100% !important; animation: dsh-wc-shimmer 1.8s linear infinite; }',
80
+ '.dsh-wc-edge-flow { stroke-dasharray: 8 6; animation: dsh-wc-dash 0.8s linear infinite; }',
81
+ '.dsh-wc-dot-live { display: inline-block; animation: dsh-wc-dot 1.5s ease-in-out infinite; }',
82
+ ].join('\n');
83
+ document.head.appendChild(style);
84
+ } catch (_e) { /* non-DOM or restricted host */ }
85
+ }
86
+
43
87
  // One socket per channel type: a link can only join the same type.
44
88
  const SOCKET_TYPES = [
45
89
  { id: 'prompt', label: 'prompt', color: '#8a8f98' },
@@ -78,7 +122,7 @@ window.__ModuleLoader__.load({
78
122
  scopeMinimal: 'minimal(只读思考)', scopeStandard: 'standard(全部工具)',
79
123
  fallbackModel: '备用',
80
124
  stPending: '未执行', stRunning: '进行中', stDone: '已完成', stFailed: '失败',
81
- stOrphan: '未连线', stLead: '由对话执行',
125
+ stOrphan: '未连线', stLead: '由对话执行', stLeadReady: '待拍板',
82
126
  presetEmpty: '还没有保存过预设', del: '删除这个预设',
83
127
  needName: '请先给预设起个名字', duplicate: '已存在,请换一个名字',
84
128
  savedPreset: '已保存预设', saveFailed: '保存失败(存储不可用)',
@@ -89,9 +133,9 @@ window.__ModuleLoader__.load({
89
133
  tipLead: 'Lead 步骤在对话里执行,画布不追踪其状态',
90
134
  tipOrphan: '未连线:运行时会被跳过', tipStatus: '子代理节点的运行状态',
91
135
  tipZoom: '滚轮缩放(以光标为中心)',
92
- tipResetZoom: '回到 100% 并把画面中心拉到 Lead 节点',
93
- tipLocate: '把画面中心拉到 Lead(本对话)节点',
94
- locate: '◎ 定位',
136
+ tipResetZoom: '点击回到 100% 并聚焦 Lead;左右拖拽可连续缩放',
137
+ tipLocate: '自适应缩放并居中,让所有节点完整显示在视野内',
138
+ locate: '⊡ 全览',
95
139
  importBtn: '⇩ 导入',
96
140
  tipImport: '从剪贴板导入模型生成的画布(先复制聊天里的画布 JSON)',
97
141
  importOk: '已导入画布,共 ',
@@ -115,13 +159,33 @@ window.__ModuleLoader__.load({
115
159
  '10. 预设名 + ☆ 保存 可以把整张图存下来,新对话里从「☰ 预设」载入。',
116
160
  '11. 你可以直接让我改画布:说「把那三个节点的分工改成…」,我会就地修改,不动你摆的位置。',
117
161
  '12. session 线连到 Lead 时,我会在暂停那步拿到那个子代理的会话,可以继续追问它。',
162
+ '13. 按住鼠标中键(或空格 + 左键)拖动画布平移;点击子代理节点右下角状态可直达它的对话记录。',
163
+ '14. 快捷键:Shift+A 在光标处新建节点,Ctrl+D 复制选中节点,Delete 批量删除,Ctrl+Z 撤销,Esc 关闭弹窗。',
118
164
  ].join('\n'),
165
+ openChat: '会话',
166
+ tipOpenRun: '点击打开该子代理的对话记录',
167
+ exportBtn: '⇧ 复制 JSON',
168
+ exportOk: '已复制画布 JSON 到剪贴板',
169
+ exportFail: '复制失败(剪贴板不可用)',
170
+ autoLayoutBtn: '⊞ 自动排版',
171
+ layoutDone: '已自动整理布局',
172
+ cycleBlocked: '不能形成环,已阻止连线',
173
+ builtinTemplates: '内置示例模板',
174
+ myPresets: '我的预设',
175
+ duplicatedNodes: '已复制节点',
176
+ deletedNodes: '已删除节点(可用 ↶ 撤销)',
177
+ addMenuTitle: '新建节点 (Shift+A)',
178
+ fxLabel: '视觉效果',
179
+ fxMinimal: '极简',
180
+ fxStandard: '标准',
181
+ fxVivid: '炫酷',
182
+ tipLeadReady: '上游节点已全部完成,正等待在对话里拍板继续',
119
183
  importNone: '剪贴板里没有可识别的画布数据',
120
184
  importBad: '画布数据格式不对',
121
185
  tipSync: '把当前画布同步给 Host(会在对话里留一条同步记录)',
122
186
  tipUndo: '撤销上一步结构改动', tipSave: '把当前画布保存为预设',
123
187
  tipPresets: '载入已保存的预设', tipModel: '推理等级(默认 = 该模型声明的 defaultEffort)',
124
- tipMemory: '记忆:复用这个节点上一次的会话(仅同一进程内有效)',
188
+ tipMemory: '记忆:复用这个节点上一次的会话(跨运行及重启后可恢复)',
125
189
  tipPreset: '能力范围(点一下切换):standard = 全部工具(读写文件、跑命令、子代理、工作流、网页、办公);minimal = 只读思考(文件读写关闭,没有子代理/工作流/网页)',
126
190
  tipFallback: '失败重试:该节点出错时自动换一个模型再跑一次',
127
191
  tipStructured: 'JSON 输出:要求该节点返回 JSON 对象,structured 连线会把结果作为 JSON 传给下游',
@@ -153,7 +217,7 @@ window.__ModuleLoader__.load({
153
217
  scopeMinimal: 'minimal (read-only thinking)', scopeStandard: 'standard (all tools)',
154
218
  fallbackModel: 'Fallback',
155
219
  stPending: 'Pending', stRunning: 'Running', stDone: 'Done', stFailed: 'Failed',
156
- stOrphan: 'Unlinked', stLead: 'Runs in chat',
220
+ stOrphan: 'Unlinked', stLead: 'Runs in chat', stLeadReady: 'Ready',
157
221
  presetEmpty: 'No presets saved yet', del: 'Delete this preset',
158
222
  needName: 'Name the preset first', duplicate: 'already exists, pick another name',
159
223
  savedPreset: 'Saved preset', saveFailed: 'Save failed (storage unavailable)',
@@ -164,9 +228,9 @@ window.__ModuleLoader__.load({
164
228
  tipLead: 'Lead steps run in the chat; the canvas does not track them',
165
229
  tipOrphan: 'Unlinked: skipped when the canvas runs', tipStatus: 'Subagent run status',
166
230
  tipZoom: 'Wheel zooms around the cursor',
167
- tipResetZoom: 'Reset to 100% and centre the view on the Lead node',
168
- tipLocate: 'Centre the view on the Lead (this conversation) node',
169
- locate: '◎ Locate',
231
+ tipResetZoom: 'Click to reset to 100% on Lead; drag left/right to scrub zoom',
232
+ tipLocate: 'Fit all nodes into the visible canvas',
233
+ locate: '⊡ Fit',
170
234
  importBtn: '⇩ Import',
171
235
  tipImport: 'Import a model-generated canvas from the clipboard (copy the canvas JSON from chat first)',
172
236
  importOk: 'Canvas imported, ',
@@ -190,13 +254,33 @@ window.__ModuleLoader__.load({
190
254
  '10. Name a preset and press ☆ Save to keep the canvas for other sessions.',
191
255
  '11. You can ask me to edit the canvas; I patch it in place and keep your layout.',
192
256
  '12. A session link into a Lead step hands me that child agent, so I can follow up with it.',
257
+ '13. Hold the middle mouse button (or Space + drag) to pan; click a subagent status badge to open its chat.',
258
+ '14. Shortcuts: Shift+A adds a node at cursor, Ctrl+D duplicates, Delete removes selected, Ctrl+Z undoes, Esc closes popups.',
193
259
  ].join('\n'),
260
+ openChat: 'Chat',
261
+ tipOpenRun: 'Click to open this subagent conversation',
262
+ exportBtn: '⇧ Copy JSON',
263
+ exportOk: 'Canvas JSON copied to clipboard',
264
+ exportFail: 'Copy failed (clipboard unavailable)',
265
+ autoLayoutBtn: '⊞ Auto layout',
266
+ layoutDone: 'Layout tidied',
267
+ cycleBlocked: 'Cannot create a cycle',
268
+ builtinTemplates: 'Starter templates',
269
+ myPresets: 'Saved presets',
270
+ duplicatedNodes: 'Duplicated nodes',
271
+ deletedNodes: 'Deleted nodes (use Undo to restore)',
272
+ addMenuTitle: 'Add node (Shift+A)',
273
+ fxLabel: 'Visual effects',
274
+ fxMinimal: 'Minimal',
275
+ fxStandard: 'Standard',
276
+ fxVivid: 'Vivid',
277
+ tipLeadReady: 'Upstream steps are done; waiting for Lead in chat',
194
278
  importNone: 'No canvas data found in the clipboard',
195
279
  importBad: 'Canvas data is malformed',
196
280
  tipSync: 'Publish this canvas to the host (leaves one sync record in the chat)',
197
281
  tipUndo: 'Undo the last structural change', tipSave: 'Save this canvas as a preset',
198
282
  tipPresets: 'Load a saved preset', tipModel: 'Reasoning effort (default = the model\'s defaultEffort)',
199
- tipMemory: 'Memory: reuse this node\'s previous session (same process only)',
283
+ tipMemory: 'Memory: reuse this node\'s previous session (persisted across runs and restarts)',
200
284
  tipPreset: 'Capability (click to toggle): standard = all tools (files, shells, subagents, workflow, web, office); minimal = read-only thinking (no file writes, no subagents/workflow/web)',
201
285
  tipFallback: 'Retry: when this node fails, rerun it once on another model',
202
286
  tipStructured: 'JSON output: require an object result; structured links pass it downstream as JSON',
@@ -236,13 +320,22 @@ window.__ModuleLoader__.load({
236
320
  background: C.base, color: C.text, fontSize: '13px',
237
321
  },
238
322
  toolbar: {
239
- display: 'flex', alignItems: 'center', gap: '6px',
323
+ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '6px',
240
324
  padding: '8px 10px', borderBottom: '1px solid ' + C.border, flex: '0 0 auto',
241
325
  },
242
326
  btn: {
243
327
  padding: '5px 10px', borderRadius: '6px', border: '1px solid ' + C.border,
244
328
  background: C.raised, color: C.text, fontSize: '12px', cursor: 'pointer', whiteSpace: 'nowrap',
245
329
  },
330
+ btnDirty: {
331
+ padding: '5px 10px', borderRadius: '6px', border: '1px solid ' + C.accent,
332
+ background: C.raised, color: C.accent, fontSize: '12px', fontWeight: 600,
333
+ cursor: 'pointer', whiteSpace: 'nowrap',
334
+ },
335
+ toolSep: {
336
+ width: '1px', height: '16px', background: C.border, opacity: 0.65,
337
+ flex: '0 0 auto', margin: '0 2px',
338
+ },
246
339
  toggleOn: {
247
340
  padding: '5px 12px', borderRadius: '6px', border: '1px solid ' + C.accent,
248
341
  background: 'transparent', color: C.accent, fontSize: '12px', fontWeight: 600,
@@ -258,17 +351,21 @@ window.__ModuleLoader__.load({
258
351
  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%',
259
352
  },
260
353
  floatOn: {
261
- position: 'absolute', top: '52px', left: '10px', zIndex: 30,
354
+ position: 'absolute', top: '10px', left: '10px', zIndex: 30,
262
355
  padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.accent,
263
356
  background: C.elevated, color: C.accent, fontSize: '11px', fontWeight: 600,
264
357
  cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
265
358
  },
266
359
  floatOff: {
267
- position: 'absolute', top: '52px', left: '10px', zIndex: 30,
360
+ position: 'absolute', top: '10px', left: '10px', zIndex: 30,
268
361
  padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.border,
269
362
  background: C.elevated, color: C.dim, fontSize: '11px', fontWeight: 600,
270
363
  cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
271
364
  },
365
+ canvasWrap: {
366
+ position: 'relative', flex: '1 1 auto', minHeight: '0',
367
+ display: 'flex', flexDirection: 'column',
368
+ },
272
369
  moreBar: { position: 'relative', flex: '0 0 auto' },
273
370
  moreMenu: {
274
371
  position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '190px',
@@ -279,6 +376,21 @@ window.__ModuleLoader__.load({
279
376
  padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
280
377
  whiteSpace: 'nowrap', color: C.text,
281
378
  },
379
+ addMenu: {
380
+ position: 'absolute', minWidth: '164px',
381
+ background: C.elevated, border: '1px solid ' + C.border, borderRadius: '7px',
382
+ zIndex: 85, padding: '4px', boxShadow: '0 12px 30px rgba(0,0,0,0.5)',
383
+ },
384
+ addMenuHead: {
385
+ padding: '4px 8px 3px', fontSize: '10px', color: C.dim,
386
+ borderBottom: '1px solid ' + C.border, marginBottom: '3px',
387
+ },
388
+ addMenuRow: {
389
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px',
390
+ padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
391
+ color: C.text, whiteSpace: 'nowrap',
392
+ },
393
+ addMenuHint: { fontSize: '10px', color: C.dim },
282
394
  helpOverlay: {
283
395
  position: 'absolute', inset: '0', background: 'rgba(0,0,0,0.45)', zIndex: 90,
284
396
  display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '12px',
@@ -318,45 +430,64 @@ window.__ModuleLoader__.load({
318
430
  },
319
431
  presetEmpty: { padding: '6px', fontSize: '10px', color: C.dim },
320
432
  syncNote: { fontSize: '10px', color: C.dim, maxWidth: '140px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
321
- canvas: { position: 'relative', flex: '1 1 auto', overflow: 'auto', minHeight: '0', userSelect: 'none' },
322
- content: { position: 'relative', width: CONTENT_W, height: CONTENT_H },
433
+ canvas: { position: 'relative', flex: '1 1 auto', overflow: 'hidden', minHeight: '0', userSelect: 'none' },
434
+ content: { position: 'absolute', left: 0, top: 0, width: CONTENT_W, height: CONTENT_H },
323
435
 
324
436
  node: {
325
437
  position: 'absolute', width: NODE_W, height: NODE_H, boxSizing: 'border-box',
326
438
  borderRadius: '10px', border: '1px solid ' + C.border,
327
439
  background: C.raised, color: C.text, cursor: 'grab',
328
- boxShadow: '0 1px 4px rgba(0,0,0,0.3)',
440
+ boxShadow: '0 2px 8px rgba(0,0,0,0.22)',
329
441
  },
330
- nodeSel: { border: '2px solid ' + C.accent },
442
+ nodeSel: { border: '2px solid ' + C.accent, boxShadow: '0 4px 18px rgba(47,129,247,0.22)' },
331
443
  leadNode: {},
332
444
  orphanNode: { border: '1px dashed ' + C.dim, opacity: 0.65 },
445
+ nodeHeader: {
446
+ position: 'absolute', left: 0, right: 0, top: '4px', height: '26px',
447
+ background: 'rgba(128,128,128,0.07)',
448
+ borderBottom: '1px solid rgba(128,128,128,0.18)',
449
+ pointerEvents: 'none', zIndex: 1,
450
+ },
451
+ bandDivider: {
452
+ position: 'absolute', left: '10px', right: '10px', top: (SOCKET_BAND_TOP - 3) + 'px',
453
+ height: '1px', background: 'rgba(128,128,128,0.18)', pointerEvents: 'none', zIndex: 1,
454
+ },
333
455
 
334
456
  title: {
335
- position: 'absolute', left: '10px', right: '10px', top: '10px', height: '18px',
336
- fontWeight: 600, fontSize: '13px', lineHeight: '18px',
457
+ position: 'absolute', left: '10px', right: '10px', top: '8px', height: '18px',
458
+ fontWeight: 600, fontSize: '12px', lineHeight: '18px',
337
459
  border: 'none', background: 'transparent', color: C.text, padding: 0, margin: 0,
338
- outline: 'none', boxSizing: 'border-box', userSelect: 'text',
460
+ outline: 'none', boxSizing: 'border-box', userSelect: 'text', zIndex: 2,
339
461
  },
340
462
  titleReadonly: {
341
- position: 'absolute', left: '10px', right: '10px', top: '10px', height: '18px',
342
- fontWeight: 600, fontSize: '13px', lineHeight: '18px',
343
- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
463
+ position: 'absolute', left: '10px', right: '10px', top: '8px', height: '18px',
464
+ fontWeight: 600, fontSize: '12px', lineHeight: '18px',
465
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', zIndex: 2,
344
466
  },
345
467
  topBar: {
346
468
  position: 'absolute', left: 0, right: 0, top: 0, height: '4px',
347
469
  borderRadius: '10px 10px 0 0', zIndex: 2, pointerEvents: 'none',
348
470
  },
349
471
  statusChip: {
350
- position: 'absolute', right: '10px', bottom: '3px', fontSize: '9px', lineHeight: '14px',
472
+ position: 'absolute', right: '12px', bottom: '4px', fontSize: '10px', lineHeight: '14px',
473
+ padding: '1px 5px', borderRadius: '999px',
351
474
  color: C.dim, pointerEvents: 'none', zIndex: 3, whiteSpace: 'nowrap',
475
+ display: 'inline-flex', alignItems: 'center', gap: '3px',
476
+ },
477
+ statusBtn: {
478
+ position: 'absolute', right: '12px', bottom: '3px', fontSize: '10px', lineHeight: '14px',
479
+ padding: '1px 6px', borderRadius: '999px', border: '1px solid ' + C.border,
480
+ background: C.elevated, color: C.text, cursor: 'pointer', pointerEvents: 'auto',
481
+ zIndex: 7, whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: '3px',
482
+ outline: 'none', fontWeight: 500,
352
483
  },
353
484
 
354
- fieldModel: { position: 'absolute', left: '10px', right: '10px', top: '28px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
355
- fieldReason: { position: 'absolute', left: '10px', right: '10px', top: '50px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
356
- fieldScope: { position: 'absolute', left: '10px', right: '10px', top: '72px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
357
- fieldFallback: { position: 'absolute', left: '10px', right: '10px', top: '94px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
358
- fieldMemory: { position: 'absolute', left: '10px', right: '10px', top: '116px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
359
- fieldRole: { position: 'absolute', left: '10px', right: '10px', top: '138px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
485
+ fieldModel: { position: 'absolute', left: '10px', right: '10px', top: '35px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
486
+ fieldReason: { position: 'absolute', left: '10px', right: '10px', top: '57px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
487
+ fieldScope: { position: 'absolute', left: '10px', right: '10px', top: '79px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
488
+ fieldFallback: { position: 'absolute', left: '10px', right: '10px', top: '101px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
489
+ fieldMemory: { position: 'absolute', left: '10px', right: '10px', top: '123px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
490
+ fieldRole: { position: 'absolute', left: '10px', right: '10px', top: '145px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
360
491
  fieldRoleTop: { position: 'absolute', left: '10px', right: '10px', top: '34px', height: '24px', display: 'flex', alignItems: 'center', gap: '6px' },
361
492
  optRow: {
362
493
  position: 'absolute', left: '10px', right: '10px', top: '114px', height: '18px',
@@ -386,7 +517,8 @@ window.__ModuleLoader__.load({
386
517
  fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '12px',
387
518
  outline: 'none',
388
519
  },
389
- fieldLabel: { flex: '0 0 30px', width: '30px', fontSize: '9px', color: C.dim },
520
+ fieldLabel: { flex: '0 0 30px', width: '30px', fontSize: '9px', color: C.dim, whiteSpace: 'nowrap' },
521
+ fieldLabelEn: { flex: '0 0 46px', width: '46px', fontSize: '9px', color: C.dim, whiteSpace: 'nowrap' },
390
522
 
391
523
  input: {
392
524
  flex: '1 1 auto', minWidth: '0', padding: '3px 6px', borderRadius: '5px',
@@ -404,9 +536,9 @@ window.__ModuleLoader__.load({
404
536
  border: '1px solid ' + C.border, borderRadius: '5px', padding: '5px 6px',
405
537
  outline: 'none', userSelect: 'text',
406
538
  },
407
- leadLabel: { position: 'absolute', left: '10px', right: '10px', top: '26px', height: '16px', display: 'flex', alignItems: 'center' },
539
+ leadLabel: { position: 'absolute', left: '10px', right: '10px', top: '34px', height: '16px', display: 'flex', alignItems: 'center' },
408
540
  task: {
409
- position: 'absolute', left: '10px', right: '10px', top: '44px', height: '118px',
541
+ position: 'absolute', left: '10px', right: '10px', top: '51px', height: '116px',
410
542
  padding: '4px 6px', borderRadius: '5px', border: '1px solid ' + C.border,
411
543
  background: C.base, color: C.text, fontSize: '11px', resize: 'none', outline: 'none',
412
544
  lineHeight: '14px', boxSizing: 'border-box', userSelect: 'text',
@@ -473,9 +605,9 @@ window.__ModuleLoader__.load({
473
605
 
474
606
  function defaultNodes() {
475
607
  return [
476
- { id: 'lead', kind: 'lead', x: 30, y: 30, label: 'Lead', task: '', provider: '', model: '', role: '' },
477
- { id: 'n1', kind: 'agent', x: 40, y: 230, label: 'Classifier', provider: '', model: 'deepseek-v4-flash', role: '把请求分类' },
478
- { id: 'n2', kind: 'agent', x: 340, y: 420, label: 'Executor', provider: '', model: 'deepseek-v4-pro', role: '执行方案' },
608
+ { id: 'lead', kind: 'lead', x: 40, y: 80, label: 'Lead', task: '', provider: '', model: '', role: '' },
609
+ { id: 'n1', kind: 'agent', x: 340, y: 80, label: pick('步骤 1:分析', 'Step 1: Analyze'), provider: '', model: '', role: pick('拆解任务并给出思路', 'Break down the task and propose an approach') },
610
+ { id: 'n2', kind: 'agent', x: 640, y: 80, label: pick('步骤 2:执行', 'Step 2: Execute'), provider: '', model: '', role: pick('按上游思路完成输出', 'Execute the plan from upstream') },
479
611
  ];
480
612
  }
481
613
 
@@ -690,12 +822,228 @@ window.__ModuleLoader__.load({
690
822
  return set;
691
823
  }
692
824
 
825
+ /** True when adding `fromId -> toId` would create a cycle or point into entry Lead. */
826
+ function wouldCycle(nodes, edges, fromId, toId) {
827
+ if (!fromId || !toId || fromId === toId || toId === 'lead') return true;
828
+ const adj = new Map();
829
+ for (const e of edges || []) {
830
+ if (!adj.has(e.from)) adj.set(e.from, []);
831
+ adj.get(e.from).push(e.to);
832
+ }
833
+ const seen = new Set([toId]);
834
+ const queue = [toId];
835
+ while (queue.length) {
836
+ const cur = queue.shift();
837
+ if (cur === fromId) return true;
838
+ for (const next of adj.get(cur) || []) {
839
+ if (!seen.has(next)) { seen.add(next); queue.push(next); }
840
+ }
841
+ }
842
+ return false;
843
+ }
844
+
845
+ /** Tidy a DAG into symmetrical left-to-right columns by longest-path depth. */
846
+ function layoutGraph(nodes, edges) {
847
+ const list = Array.isArray(nodes) ? nodes : [];
848
+ const linkList = Array.isArray(edges) ? edges : [];
849
+ if (!list.length) return [];
850
+ const reachable = reachableFrom(list, linkList);
851
+ const depth = new Map(list.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
852
+ for (let pass = 0; pass < list.length; pass += 1) {
853
+ let changed = false;
854
+ for (const e of linkList) {
855
+ if (!reachable.has(e.from) || !reachable.has(e.to) || e.to === 'lead') continue;
856
+ const next = Math.min(list.length, (depth.get(e.from) || 0) + 1);
857
+ if (next > (depth.get(e.to) || 0)) { depth.set(e.to, next); changed = true; }
858
+ }
859
+ if (!changed) break;
860
+ }
861
+ let maxDepth = 0;
862
+ for (const n of list) {
863
+ if (reachable.has(n.id)) maxDepth = Math.max(maxDepth, depth.get(n.id) || 0);
864
+ }
865
+ const columns = new Map();
866
+ for (const n of list) {
867
+ const col = reachable.has(n.id) ? (depth.get(n.id) || 0) : maxDepth + 1;
868
+ if (!columns.has(col)) columns.set(col, []);
869
+ columns.get(col).push(n);
870
+ }
871
+ const posById = new Map();
872
+ const COL_PITCH = 300;
873
+ const ROW_PITCH = 262;
874
+ const MID_Y = 320;
875
+ for (const [col, colNodes] of columns.entries()) {
876
+ const ordered = colNodes.slice().sort((a, b) => (a.y || 0) - (b.y || 0));
877
+ const totalH = (ordered.length - 1) * ROW_PITCH + NODE_H;
878
+ const startY = Math.round(MID_Y - totalH / 2);
879
+ ordered.forEach((n, row) => {
880
+ posById.set(n.id, { x: 40 + col * COL_PITCH, y: startY + row * ROW_PITCH });
881
+ });
882
+ }
883
+ return list.map((n) => {
884
+ const p = posById.get(n.id);
885
+ return p ? { ...n, x: p.x, y: p.y } : { ...n };
886
+ });
887
+ }
888
+
889
+ /** Starter templates shipped with the plugin so new users can try one click away. */
890
+ function builtinTemplates(lang) {
891
+ const en = lang === 'en';
892
+ const sweNodes = [
893
+ {
894
+ id: 'lead', kind: 'lead', label: 'Lead', y: 0,
895
+ task: en
896
+ ? 'Add a rate-limiting middleware to this service: scan codebase patterns and API constraints in parallel, synthesize a structured change spec, pause for my sign-off, implement core code and tests/docs in parallel, run an independent review, and hand off for final ship check.'
897
+ : '给现有项目新增「请求限流中间件」:先并行摸清代码库结构与接口约束,收敛结构化变更方案,我拍板后并行完成核心实现与单测文档,最后独立审查并交我终审交付。',
898
+ provider: '', model: '', role: '',
899
+ },
900
+ {
901
+ id: 'swe_risk', kind: 'agent', y: 0,
902
+ label: en ? 'Constraints & Risks' : '约束与风险',
903
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
904
+ role: en
905
+ ? 'Read-only audit of public APIs, error semantics, config conventions and test gaps; list invariants that must not break.'
906
+ : '只读排查相关接口契约、错误码约定、配置方式与测试覆盖缺口,列出绝不能破坏的边界与不变量(不改文件)。',
907
+ },
908
+ {
909
+ id: 'swe_scan', kind: 'agent', y: 100,
910
+ label: en ? 'Codebase Scan' : '代码库摸底',
911
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: true,
912
+ role: en
913
+ ? 'Read-only scan to locate entry points, middleware chain, key symbols and local conventions; output an impacted file map.'
914
+ : '只读定位相关模块入口、中间件链路、关键符号和代码风格约定,输出受影响文件清单(不改文件,保留会话供实现复用)。',
915
+ },
916
+ {
917
+ id: 'swe_spec', kind: 'agent', y: 0,
918
+ label: en ? 'Change Spec' : '变更方案',
919
+ provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false,
920
+ role: en
921
+ ? 'Pure reasoning: merge both scans into a structured JSON spec { filesToChange, publicApi, edgeCases, testPlan, nonGoals }.'
922
+ : '纯推理收敛两份摸底结果,输出结构化 JSON 方案(含 filesToChange、publicApi、edgeCases、testPlan 与 nonGoals)。',
923
+ },
924
+ {
925
+ id: 'swe_plan_gate', kind: 'lead', y: 0,
926
+ label: en ? 'Lead Sign-Off' : 'Lead 拍板',
927
+ provider: '', model: '',
928
+ role: en
929
+ ? 'Review the structured spec, lock down scope and non-goals, and split file ownership cleanly for parallel implementation.'
930
+ : '评审结构化变更方案,敲定实现边界与不做的事,明确源码与测试/文档的改动范围后放行。',
931
+ },
932
+ {
933
+ id: 'swe_tests', kind: 'agent', y: 0,
934
+ label: en ? 'Tests & Docs' : '单测与文档',
935
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
936
+ role: en
937
+ ? 'Edit test files and docs only (never touch source code): write unit/edge-case tests and usage notes matching the signed-off spec.'
938
+ : '仅修改测试文件与使用文档(绝不改业务源码):按拍板方案补齐边界单测用例与配置说明,确保无写冲突。',
939
+ },
940
+ {
941
+ id: 'swe_impl', kind: 'agent', y: 100,
942
+ label: en ? 'Core Implement' : '核心实现',
943
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: true,
944
+ role: en
945
+ ? 'Continue inside the Codebase Scan session: edit source files only to implement the approved spec, run checks, and summarize changed files.'
946
+ : '延续「代码库摸底」热会话直接动手(免重复扫库):仅修改业务源码落实拍板方案,自测并汇报改动清单。',
947
+ },
948
+ {
949
+ id: 'swe_review', kind: 'agent', y: 0,
950
+ label: en ? 'Code Review' : '独立审查',
951
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
952
+ role: en
953
+ ? 'Fresh-context review (do not edit code): run the full test suite, inspect git diff for regressions and edge cases, and output a structured JSON verdict.'
954
+ : '全新上下文独立审查(不改代码):运行完整测试套件并审查 diff,排查回归风险与边界遗漏,输出结构化审查结论。',
955
+ },
956
+ {
957
+ id: 'swe_ship_gate', kind: 'lead', y: 0,
958
+ label: en ? 'Lead Ship Gate' : 'Lead 终审',
959
+ provider: '', model: '',
960
+ role: en
961
+ ? 'Decide ship vs fix from the review verdict; if minor fixes are needed, message the handed-over Core Implement session directly.'
962
+ : '依据结构化审查结论拍板是否交付;若有小问题,直接通过交接的「核心实现」紫线会话下达就地修复。',
963
+ },
964
+ ];
965
+ const sweEdges = [
966
+ { id: 's1', from: 'lead', to: 'swe_risk', type: 'prompt' },
967
+ { id: 's2', from: 'lead', to: 'swe_scan', type: 'prompt' },
968
+ { id: 's3', from: 'swe_risk', to: 'swe_spec', type: 'prompt' },
969
+ { id: 's4', from: 'swe_scan', to: 'swe_spec', type: 'prompt' },
970
+ { id: 's5', from: 'swe_spec', to: 'swe_plan_gate', type: 'structured' },
971
+ { id: 's6', from: 'swe_plan_gate', to: 'swe_tests', type: 'prompt' },
972
+ { id: 's7', from: 'swe_plan_gate', to: 'swe_impl', type: 'prompt' },
973
+ { id: 's8', from: 'swe_scan', to: 'swe_impl', type: 'session-ref' },
974
+ { id: 's9', from: 'swe_tests', to: 'swe_review', type: 'prompt' },
975
+ { id: 's10', from: 'swe_impl', to: 'swe_review', type: 'prompt' },
976
+ { id: 's11', from: 'swe_review', to: 'swe_ship_gate', type: 'structured' },
977
+ { id: 's12', from: 'swe_impl', to: 'swe_ship_gate', type: 'session-ref' },
978
+ ];
979
+ const prdNodes = [
980
+ { id: 'lead', kind: 'lead', label: 'Lead', task: en ? 'Turn this PRD into an implementation plan: run three parallel researches (competitors, feasibility, cost), synthesize a structured plan, pause for my decision, then build code, docs and a test checklist in parallel before my final review.' : '把这份 PRD 变成可实施方案:先并行做三项调研(竞品、技术可行性、成本),合成一份结构化方案,我拍板后并行产出代码与文档、并按方案生成测试清单,最后我终审。', provider: '', model: '', role: '' },
981
+ { id: 'n_comp', kind: 'agent', label: en ? 'Competitors' : '竞品调研', provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false, role: en ? 'Research how similar products solve this and list key trade-offs.' : '调研同类产品的做法,列出优缺点与差异化机会。' },
982
+ { id: 'n_tech', kind: 'agent', label: en ? 'Feasibility' : '技术可行性', provider: '', model: '', reasoning: '', preset: 'standard', keepSession: true, role: en ? 'Assess whether our current stack can support it and identify key risks.' : '评估现有技术栈能否实现,指出核心难点与依赖。' },
983
+ { id: 'n_cost', kind: 'agent', label: en ? 'Cost Estimate' : '成本估算', provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false, role: en ? 'Estimate effort, timeline, and external dependencies.' : '估算人力、时间与依赖,给出保守与乐观两档评估。' },
984
+ { id: 'n_synth', kind: 'agent', label: en ? 'Plan Synthesis' : '方案合成', provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false, role: en ? 'Merge the three research inputs into one actionable structured plan with options, steps and risks.' : '合并三份调研为一份可执行的结构化方案(含备选路线、steps 与 risks)。' },
985
+ { id: 'n_decide', kind: 'lead', label: en ? 'Lead Decision' : 'Lead 拍板', provider: '', model: '', role: en ? 'Pick one route from the synthesized plan and define scope & non-goals.' : '从合成方案里选定一条路线,写清实施边界与不做的事。' },
986
+ { id: 'n_tests', kind: 'agent', label: en ? 'Test Checklist' : '测试清单', provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false, role: en ? 'Continue from the synthesized plan and derive acceptance tests covering steps & risks.' : '基于方案中的 steps 与 risks 生成可验证的验收测试清单。' },
987
+ { id: 'n_code', kind: 'agent', label: en ? 'Write Code' : '写代码', provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false, role: en ? 'Implement the core changes following the approved plan.' : '按拍板后的方案实现核心改动并自测。' },
988
+ { id: 'n_docs', kind: 'agent', label: en ? 'Write Docs' : '写文档', provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false, role: en ? 'Write user-facing usage notes and changelog.' : '写使用说明与变更记录,面向使用者而非开发者。' },
989
+ { id: 'n_final', kind: 'lead', label: en ? 'Lead Final Review' : 'Lead 终审', provider: '', model: '', role: en ? 'Verify code, docs and test checklist align with the plan and give a ship/no-ship call.' : '核对代码、文档、测试清单三者是否对齐方案,给出能否交付的结论。' },
990
+ ];
991
+ const prdEdges = [
992
+ { id: 't1', from: 'lead', to: 'n_comp', type: 'prompt' },
993
+ { id: 't2', from: 'lead', to: 'n_tech', type: 'prompt' },
994
+ { id: 't3', from: 'lead', to: 'n_cost', type: 'prompt' },
995
+ { id: 't4', from: 'n_comp', to: 'n_synth', type: 'prompt' },
996
+ { id: 't5', from: 'n_tech', to: 'n_synth', type: 'prompt' },
997
+ { id: 't6', from: 'n_cost', to: 'n_synth', type: 'prompt' },
998
+ { id: 't7', from: 'n_synth', to: 'n_decide', type: 'structured' },
999
+ { id: 't8', from: 'n_synth', to: 'n_tests', type: 'session-ref' },
1000
+ { id: 't9', from: 'n_decide', to: 'n_code', type: 'prompt' },
1001
+ { id: 't10', from: 'n_decide', to: 'n_docs', type: 'prompt' },
1002
+ { id: 't11', from: 'n_code', to: 'n_final', type: 'prompt' },
1003
+ { id: 't12', from: 'n_tests', to: 'n_final', type: 'prompt' },
1004
+ { id: 't13', from: 'n_docs', to: 'n_final', type: 'prompt' },
1005
+ ];
1006
+ const abNodes = [
1007
+ { id: 'lead', kind: 'lead', label: 'Lead', task: '', provider: '', model: '', role: '' },
1008
+ { id: 'n_a', kind: 'agent', label: en ? 'Option A (Safe)' : '方案 A(稳健)', provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false, role: en ? 'Propose a low-risk, minimal-change solution.' : '提出低风险、改动最小的稳健方案。' },
1009
+ { id: 'n_b', kind: 'agent', label: en ? 'Option B (Bold)' : '方案 B(创新)', provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false, role: en ? 'Propose a high-leverage alternative with better long-term payoff.' : '提出上限更高、长期收益更大的进阶方案。' },
1010
+ { id: 'n_pick', kind: 'lead', label: en ? 'Lead Pick' : 'Lead 拍板', provider: '', model: '', role: en ? 'Compare both options and pick the direction to execute.' : '对比两份方案,选定最终路线并补充约束。' },
1011
+ { id: 'n_exec', kind: 'agent', label: en ? 'Execute' : '执行落地', provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false, role: en ? 'Deliver the chosen solution end to end.' : '按照拍板路线完成最终交付。' },
1012
+ ];
1013
+ const abEdges = [
1014
+ { id: 'a1', from: 'lead', to: 'n_a', type: 'prompt' },
1015
+ { id: 'a2', from: 'lead', to: 'n_b', type: 'prompt' },
1016
+ { id: 'a3', from: 'n_a', to: 'n_pick', type: 'prompt' },
1017
+ { id: 'a4', from: 'n_b', to: 'n_pick', type: 'prompt' },
1018
+ { id: 'a5', from: 'n_pick', to: 'n_exec', type: 'prompt' },
1019
+ ];
1020
+ return [
1021
+ {
1022
+ id: 'tpl-swe',
1023
+ name: en ? 'SWE Delivery: Scan → Sign-Off → Build → Review' : '软件工程:摸底 → 拍板 → 并行实现 → 独立审查',
1024
+ nodes: layoutGraph(sweNodes, sweEdges),
1025
+ edges: sweEdges,
1026
+ },
1027
+ {
1028
+ id: 'tpl-prd',
1029
+ name: en ? 'PRD Research → Decide → Build → Review' : 'PRD 调研 → 拍板 → 并行产出 → 终审',
1030
+ nodes: layoutGraph(prdNodes, prdEdges),
1031
+ edges: prdEdges,
1032
+ },
1033
+ {
1034
+ id: 'tpl-ab',
1035
+ name: en ? 'Parallel Options → Decide → Execute' : '并行方案对比 → 拍板 → 执行',
1036
+ nodes: layoutGraph(abNodes, abEdges),
1037
+ edges: abEdges,
1038
+ },
1039
+ ];
1040
+ }
1041
+
693
1042
  /** Everything the Host executor needs; no prompts are pre-rendered here. */
694
1043
  function buildPlan(nodes, edges) {
695
1044
  const entry = nodes.find((n) => n.id === 'lead');
696
1045
  if (!entry) return { error: '缺少入口 Lead 节点' };
697
1046
  const task = String(entry.task || '').trim();
698
- if (!task) return { error: '请先在 Lead 节点填写「本次任务」' };
699
1047
  const rest = nodes.filter((n) => n.id !== 'lead');
700
1048
  if (!rest.length) return { error: '画布上还没有可执行的节点' };
701
1049
  // Nodes the entry Lead cannot reach are skipped rather than refused; the
@@ -752,6 +1100,53 @@ window.__ModuleLoader__.load({
752
1100
  } catch (_e) { /* ignore */ }
753
1101
  }
754
1102
 
1103
+ function loadEffectLevel() {
1104
+ try {
1105
+ const saved = window.localStorage.getItem(FX_KEY);
1106
+ if (FX_LEVELS.includes(saved)) return saved;
1107
+ if (typeof window !== 'undefined' && typeof window.matchMedia === 'function'
1108
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
1109
+ return 'minimal';
1110
+ }
1111
+ } catch (_e) { /* ignore */ }
1112
+ return 'standard';
1113
+ }
1114
+
1115
+ function saveEffectLevel(level) {
1116
+ try {
1117
+ if (FX_LEVELS.includes(level)) window.localStorage.setItem(FX_KEY, level);
1118
+ } catch (_e) { /* ignore */ }
1119
+ }
1120
+
1121
+ function nextEffectLevel(cur) {
1122
+ const idx = FX_LEVELS.indexOf(cur);
1123
+ return FX_LEVELS[(idx + 1) % FX_LEVELS.length];
1124
+ }
1125
+
1126
+ /** Compute the next `{ k, x, y }` keeping the content point under `(mx, my)` fixed. */
1127
+ function zoomAroundPoint(cur, mx, my, deltaY, deltaMode) {
1128
+ if (!deltaY) return cur;
1129
+ let dy = deltaY;
1130
+ if (deltaMode === 1) dy *= 32;
1131
+ else if (deltaMode === 2) dy *= 300;
1132
+ dy = Math.max(-150, Math.min(150, dy));
1133
+ const factor = Math.pow(1.0012, -dy);
1134
+ const k = Math.min(3, Math.max(0.2, cur.k * factor));
1135
+ if (k === cur.k) return cur;
1136
+ const lx = (mx - cur.x) / cur.k;
1137
+ const ly = (my - cur.y) / cur.k;
1138
+ return { k, x: mx - lx * k, y: my - ly * k };
1139
+ }
1140
+
1141
+ /** Compute `{ k, x, y }` when scrubbing zoom horizontally by `dx` around `(cx, cy)`. */
1142
+ function scrubZoom(startView, cx, cy, dx) {
1143
+ const k = Math.min(3, Math.max(0.2, startView.k * Math.pow(1.005, dx)));
1144
+ if (k === startView.k) return startView;
1145
+ const lx = (cx - startView.x) / startView.k;
1146
+ const ly = (cy - startView.y) / startView.k;
1147
+ return { k, x: cx - lx * k, y: cy - ly * k };
1148
+ }
1149
+
755
1150
  function loadPresets() {
756
1151
  try {
757
1152
  const raw = window.localStorage.getItem(PRESET_KEY);
@@ -857,6 +1252,8 @@ window.__ModuleLoader__.load({
857
1252
  const [menuOpen, setMenuOpen] = useState(false);
858
1253
  const [helpOpen, setHelpOpen] = useState(false);
859
1254
  const [cutMode, setCutMode] = useState(loadCutMode);
1255
+ const [fxLevel, setFxLevel] = useState(loadEffectLevel);
1256
+ useEffect(() => { ensureStyles(); }, []);
860
1257
  const cutRef = useRef(null);
861
1258
  /** Timestamp of the remote document being applied, so saving it does not bump the clock. */
862
1259
  const applyStamp = useRef(null);
@@ -869,9 +1266,19 @@ window.__ModuleLoader__.load({
869
1266
  const [openModelFor, setOpenModelFor] = useState(null);
870
1267
  const [enabled, setEnabled] = useState(() => Boolean(initial && initial.enabled));
871
1268
 
1269
+ const rootElRef = useRef(null);
1270
+ const canvasWrapRef = useRef(null);
872
1271
  const contentRef = useRef(null);
873
1272
  const canvasElRef = useRef(null);
874
- const nodeDrag = useRef(null); const statusTimer = useRef(null);
1273
+ const pointerInsideRoot = useRef(false);
1274
+ const lastMouseRef = useRef(null);
1275
+ const [addMenu, setAddMenu] = useState(null);
1276
+ const nodeDrag = useRef(null);
1277
+ const panDrag = useRef(null);
1278
+ const [panning, setPanning] = useState(false);
1279
+ const spaceDown = useRef(false);
1280
+ const [spaceHeld, setSpaceHeld] = useState(false);
1281
+ const statusTimer = useRef(null);
875
1282
  const dropdownRef = useRef(null);
876
1283
  const syncTimer = useRef(null);
877
1284
  const lastSync = useRef('');
@@ -881,6 +1288,7 @@ window.__ModuleLoader__.load({
881
1288
  const viewRef = useRef(view);
882
1289
  viewRef.current = view;
883
1290
  const [statusById, setStatusById] = useState({});
1291
+ const [runsById, setRunsById] = useState({});
884
1292
  const [presets, setPresets] = useState(loadPresets);
885
1293
  const [presetOpen, setPresetOpen] = useState(null);
886
1294
  const [presetName, setPresetName] = useState('');
@@ -893,6 +1301,10 @@ window.__ModuleLoader__.load({
893
1301
  };
894
1302
  const nodesRef = useRef(nodes);
895
1303
  nodesRef.current = nodes;
1304
+ const edgesRef = useRef(edges);
1305
+ edgesRef.current = edges;
1306
+ const selectedIdsRef = useRef(selectedIds);
1307
+ selectedIdsRef.current = selectedIds;
896
1308
 
897
1309
  useEffect(() => {
898
1310
  const stamp = applyStamp.current;
@@ -1004,47 +1416,76 @@ window.__ModuleLoader__.load({
1004
1416
  statusTimer.current = setTimeout(() => setStatus(''), 3200);
1005
1417
  };
1006
1418
 
1007
- // Live node status for subagent nodes only: the catalog lists children by
1008
- // `label#nodeId`. Lead steps run inside the conversation, so the canvas
1009
- // cannot observe them and must not pretend to.
1419
+ const NODE_MARK = /#([^\s#]+)$/;
1420
+
1421
+ const readCatalog = () => {
1422
+ try {
1423
+ const sessions = hostCtx && hostCtx.sessions;
1424
+ if (!sessions || !sessionId) return { status: null, runs: null };
1425
+ const state = sessions.list.getSnapshot();
1426
+ const proj = state && state.projectionsBySession && state.projectionsBySession[sessionId];
1427
+ const catalog = proj && proj.values && proj.values.subagentCatalog;
1428
+ if (!Array.isArray(catalog)) return { status: null, runs: null };
1429
+ const known = new Set(nodesRef.current.map((n) => n.id));
1430
+ const nextStatus = {};
1431
+ const nextRuns = {};
1432
+ for (const entry of catalog) {
1433
+ const label = String(entry.label || entry.name || entry.description || '');
1434
+ const m = NODE_MARK.exec(label);
1435
+ if (!m || !known.has(m[1])) continue;
1436
+ const nodeId = m[1];
1437
+ const child = state.byId && state.byId[entry.id];
1438
+ const timingProj = state.projectionsBySession && state.projectionsBySession[entry.id];
1439
+ const timing = timingProj && timingProj.values && timingProj.values.subagentTiming;
1440
+ if (child && child.running) nextStatus[nodeId] = 'running';
1441
+ else if (timing && timing.lastTurnCompleted === false) nextStatus[nodeId] = 'failed';
1442
+ else nextStatus[nodeId] = 'done';
1443
+ if (entry.id) {
1444
+ const prev = nextRuns[nodeId];
1445
+ nextRuns[nodeId] = {
1446
+ childId: entry.id,
1447
+ label,
1448
+ mode: entry.mode || 'continuable',
1449
+ count: prev ? prev.count + 1 : 1,
1450
+ };
1451
+ }
1452
+ }
1453
+ return { status: nextStatus, runs: nextRuns };
1454
+ } catch (_e) {
1455
+ return { status: null, runs: null };
1456
+ }
1457
+ };
1458
+
1459
+ // Live node status & child session links for subagent nodes only: the
1460
+ // catalog lists children by `label#nodeId`. Lead steps run inside the
1461
+ // conversation, so the canvas cannot observe them and must not pretend to.
1010
1462
  useEffect(() => {
1011
1463
  const sessions = hostCtx && hostCtx.sessions;
1012
1464
  const face = sessionFace(sessionId);
1013
1465
  if (!sessions || !sessionId || !face || typeof face.subscribe !== 'function') return undefined;
1014
1466
  let timer = null;
1015
1467
  const read = () => {
1016
- try {
1017
- const state = sessions.list.getSnapshot();
1018
- const proj = state && state.projectionsBySession && state.projectionsBySession[sessionId];
1019
- const catalog = proj && proj.values && proj.values.subagentCatalog;
1020
- if (!Array.isArray(catalog)) return;
1021
- const known = new Set(nodesRef.current.map((n) => n.id));
1022
- const next = {};
1023
- for (const entry of catalog) {
1024
- const m = NODE_MARK.exec(String(entry.label || ''));
1025
- if (!m || !known.has(m[1])) continue;
1026
- const child = state.byId && state.byId[entry.id];
1027
- const timingProj = state.projectionsBySession && state.projectionsBySession[entry.id];
1028
- const timing = timingProj && timingProj.values && timingProj.values.subagentTiming;
1029
- if (child && child.running) next[m[1]] = 'running';
1030
- else if (timing && timing.lastTurnCompleted === false) next[m[1]] = 'failed';
1031
- else next[m[1]] = 'done';
1032
- }
1033
- setStatusById(next);
1034
- } catch (_e) { /* ignore */ }
1468
+ const { status: nextStatus, runs: nextRuns } = readCatalog();
1469
+ if (nextStatus) setStatusById(nextStatus);
1470
+ if (nextRuns) setRunsById(nextRuns);
1035
1471
  };
1036
1472
  const stop = () => { if (timer) { clearInterval(timer); timer = null; } };
1037
1473
  let wasRunning = false;
1038
1474
  try { wasRunning = Boolean(face.getSnapshot().running); } catch (_e) { wasRunning = false; }
1039
- if (wasRunning) { read(); timer = setInterval(read, 700); }
1475
+ read();
1476
+ if (wasRunning) timer = setInterval(read, 700);
1040
1477
  const onSnapshot = () => {
1041
1478
  let running = false;
1042
1479
  try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
1043
1480
  // A new turn means a new run: drop the previous run's statuses first.
1044
1481
  if (running && !wasRunning) setStatusById({});
1482
+ const finished = !running && wasRunning;
1045
1483
  wasRunning = running;
1046
1484
  if (running && !timer) { read(); timer = setInterval(read, 700); }
1047
1485
  if (!running && timer) { stop(); read(); }
1486
+ if (finished && typeof sessions.refreshProjections === 'function') {
1487
+ Promise.resolve(sessions.refreshProjections(sessionId)).then(read, () => {});
1488
+ }
1048
1489
  };
1049
1490
  let unsub;
1050
1491
  try { unsub = face.subscribe(onSnapshot); } catch (_e) { unsub = undefined; }
@@ -1054,26 +1495,60 @@ window.__ModuleLoader__.load({
1054
1495
  };
1055
1496
  }, [sessionId]);
1056
1497
 
1498
+ /** Synchronously update `viewRef` and schedule React render so rapid events never read stale state. */
1499
+ const commitView = (next) => {
1500
+ viewRef.current = next;
1501
+ setView(next);
1502
+ };
1503
+
1057
1504
  // Zoom with the wheel, anchored on the cursor: the content point under the
1058
- // pointer stays under it while the scale changes.
1505
+ // pointer stays under it while the scale changes. Also absorbs any browser
1506
+ // focus-induced scroll on the hidden-overflow canvas so coordinates never drift.
1059
1507
  useEffect(() => {
1060
1508
  const el = canvasElRef.current;
1061
1509
  if (!el) return undefined;
1510
+ const absorbScroll = () => {
1511
+ if (el.scrollLeft === 0 && el.scrollTop === 0) return;
1512
+ const sx = el.scrollLeft;
1513
+ const sy = el.scrollTop;
1514
+ el.scrollLeft = 0;
1515
+ el.scrollTop = 0;
1516
+ const cur = viewRef.current;
1517
+ commitView({ k: cur.k, x: cur.x - sx, y: cur.y - sy });
1518
+ };
1519
+ const findScrollableChild = (target, dy) => {
1520
+ let node = target instanceof Element ? target : null;
1521
+ while (node && node !== el) {
1522
+ const overflowY = window.getComputedStyle ? window.getComputedStyle(node).overflowY : '';
1523
+ const scrollable = (node.tagName === 'TEXTAREA' || overflowY === 'auto' || overflowY === 'scroll')
1524
+ && node.scrollHeight > node.clientHeight + 1;
1525
+ if (scrollable) {
1526
+ const atTop = node.scrollTop <= 0;
1527
+ const atBottom = node.scrollTop + node.clientHeight >= node.scrollHeight - 1;
1528
+ if ((dy < 0 && !atTop) || (dy > 0 && !atBottom)) return node;
1529
+ }
1530
+ node = node.parentElement;
1531
+ }
1532
+ return null;
1533
+ };
1062
1534
  const onWheel = (e) => {
1535
+ if (!e.deltaY) return;
1536
+ if (!e.ctrlKey && findScrollableChild(e.target, e.deltaY)) return;
1063
1537
  e.preventDefault();
1538
+ absorbScroll();
1064
1539
  const rect = el.getBoundingClientRect();
1065
1540
  const mx = e.clientX - rect.left;
1066
1541
  const my = e.clientY - rect.top;
1067
1542
  const cur = viewRef.current;
1068
- const factor = e.deltaY < 0 ? 1.12 : 1 / 1.12;
1069
- const k = Math.min(3, Math.max(0.2, cur.k * factor));
1070
- if (k === cur.k) return;
1071
- const lx = (mx - cur.x) / cur.k;
1072
- const ly = (my - cur.y) / cur.k;
1073
- setView({ k, x: mx - lx * k, y: my - ly * k });
1543
+ const next = zoomAroundPoint(cur, mx, my, e.deltaY, e.deltaMode);
1544
+ if (next !== cur) commitView(next);
1074
1545
  };
1546
+ el.addEventListener('scroll', absorbScroll);
1075
1547
  el.addEventListener('wheel', onWheel, { passive: false });
1076
- return () => el.removeEventListener('wheel', onWheel);
1548
+ return () => {
1549
+ el.removeEventListener('scroll', absorbScroll);
1550
+ el.removeEventListener('wheel', onWheel);
1551
+ };
1077
1552
  }, []);
1078
1553
 
1079
1554
  const pointTo = (e) => {
@@ -1092,13 +1567,13 @@ window.__ModuleLoader__.load({
1092
1567
  const k = nextK || viewRef.current.k || 1;
1093
1568
  const cw = el.clientWidth || 1;
1094
1569
  const chh = el.clientHeight || 1;
1095
- setView({
1570
+ el.scrollLeft = 0;
1571
+ el.scrollTop = 0;
1572
+ commitView({
1096
1573
  k,
1097
1574
  x: cw / 2 - (wx + WORLD_PAD) * k,
1098
1575
  y: chh / 2 - (wy + WORLD_PAD) * k,
1099
1576
  });
1100
- el.scrollLeft = 0;
1101
- el.scrollTop = 0;
1102
1577
  };
1103
1578
 
1104
1579
  /** World coordinate currently sitting in the middle of the viewport. */
@@ -1113,23 +1588,91 @@ window.__ModuleLoader__.load({
1113
1588
  };
1114
1589
  };
1115
1590
 
1116
- const focusLead = () => {
1591
+ const focusLead = (nextK) => {
1117
1592
  const lead = nodes.find((n) => n.id === 'lead');
1118
1593
  if (!lead) return;
1119
- centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2);
1594
+ centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2, nextK);
1595
+ };
1596
+
1597
+ /** Horizontal drag scrubber on the percentage pill; pure click resets to 100% on Lead. */
1598
+ const onZoomPillDown = (e) => {
1599
+ if (e.button !== 0) return;
1600
+ e.preventDefault();
1601
+ e.stopPropagation();
1602
+ const el = canvasElRef.current;
1603
+ const cx = ((el && el.clientWidth) || 800) / 2;
1604
+ const cy = ((el && el.clientHeight) || 600) / 2;
1605
+ const startX = e.clientX;
1606
+ const startView = { ...viewRef.current };
1607
+ let moved = false;
1608
+ const prevCursor = typeof document !== 'undefined' && document.body ? document.body.style.cursor : '';
1609
+ const onMove = (ev) => {
1610
+ const dx = ev.clientX - startX;
1611
+ if (!moved && Math.abs(dx) < 3) return;
1612
+ if (!moved) {
1613
+ moved = true;
1614
+ if (typeof document !== 'undefined' && document.body) document.body.style.cursor = 'ew-resize';
1615
+ }
1616
+ commitView(scrubZoom(startView, cx, cy, dx));
1617
+ };
1618
+ const onUp = () => {
1619
+ window.removeEventListener('mousemove', onMove);
1620
+ window.removeEventListener('mouseup', onUp);
1621
+ if (typeof document !== 'undefined' && document.body) document.body.style.cursor = prevCursor;
1622
+ if (!moved) focusLead(1);
1623
+ };
1624
+ window.addEventListener('mousemove', onMove);
1625
+ window.addEventListener('mouseup', onUp);
1626
+ };
1627
+
1628
+ /** Zoom and pan so every node sits comfortably inside the viewport. */
1629
+ const fitView = (targetNodes) => {
1630
+ const el = canvasElRef.current;
1631
+ const list = Array.isArray(targetNodes) && targetNodes.length ? targetNodes : nodesRef.current;
1632
+ if (!el || !list.length) return;
1633
+ let minX = Infinity;
1634
+ let minY = Infinity;
1635
+ let maxX = -Infinity;
1636
+ let maxY = -Infinity;
1637
+ for (const n of list) {
1638
+ if (!n || typeof n.x !== 'number' || typeof n.y !== 'number') continue;
1639
+ if (n.x < minX) minX = n.x;
1640
+ if (n.y < minY) minY = n.y;
1641
+ if (n.x + NODE_W > maxX) maxX = n.x + NODE_W;
1642
+ if (n.y + NODE_H > maxY) maxY = n.y + NODE_H;
1643
+ }
1644
+ if (!Number.isFinite(minX)) return;
1645
+ const cw = el.clientWidth || 1;
1646
+ const chh = el.clientHeight || 1;
1647
+ const padX = 36;
1648
+ const padTop = 44;
1649
+ const padBottom = 36;
1650
+ const availW = Math.max(80, cw - padX * 2);
1651
+ const availH = Math.max(80, chh - padTop - padBottom);
1652
+ const bw = Math.max(NODE_W, maxX - minX);
1653
+ const bh = Math.max(NODE_H, maxY - minY);
1654
+ const k = Math.max(0.2, Math.min(1, Math.min(availW / bw, availH / bh)));
1655
+ const cx = (minX + maxX) / 2;
1656
+ const cy = (minY + maxY) / 2;
1657
+ el.scrollLeft = 0;
1658
+ el.scrollTop = 0;
1659
+ commitView({
1660
+ k,
1661
+ x: cw / 2 - (cx + WORLD_PAD) * k,
1662
+ y: padTop + (chh - padTop - padBottom) / 2 - (cy + WORLD_PAD) * k,
1663
+ });
1120
1664
  };
1121
1665
 
1122
1666
  // The world origin is padded, so the initial viewport would otherwise show
1123
- // empty space. Centre on the entry Lead the first time the pane mounts.
1667
+ // empty space. Fit all nodes into view the first time the pane mounts.
1124
1668
  const didCenter = useRef(false);
1125
1669
  useEffect(() => {
1126
1670
  if (didCenter.current) return;
1127
- const lead = nodesRef.current.find((n) => n.id === 'lead');
1128
- if (!lead) return;
1671
+ if (!nodesRef.current.length) return;
1129
1672
  didCenter.current = true;
1130
1673
  const raf = typeof requestAnimationFrame === 'function'
1131
- ? requestAnimationFrame(() => centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2))
1132
- : setTimeout(() => centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2), 0);
1674
+ ? requestAnimationFrame(() => fitView(nodesRef.current))
1675
+ : setTimeout(() => fitView(nodesRef.current), 0);
1133
1676
  return () => {
1134
1677
  if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(raf);
1135
1678
  else clearTimeout(raf);
@@ -1151,77 +1694,62 @@ window.__ModuleLoader__.load({
1151
1694
  flash(t('undoDone'));
1152
1695
  };
1153
1696
 
1154
- const NODE_MARK = /#([A-Za-z0-9_]+)/;
1155
-
1156
- /** Match this canvas's spawned subagent sessions back to their nodes. */
1157
- const refreshRuns = async () => {
1158
- try {
1159
- const sessions = hostCtx && hostCtx.sessions;
1160
- if (!sessions || !sessionId) { flash('没有会话上下文'); return; }
1161
- try { await sessions.refreshProjections(sessionId); } catch (_e) { /* ignore */ }
1162
- const state = sessions.list.getSnapshot();
1163
- const proj = state && state.projectionsBySession && state.projectionsBySession[sessionId];
1164
- const values = proj && (proj.values || (proj.state === 'ready' ? proj.values : undefined));
1165
- const catalog = values && values.subagentCatalog;
1166
- if (!Array.isArray(catalog)) {
1167
- flash('读不到子代理目录(' + (proj ? '没有 subagentCatalog' : '没有该会话投影') + ')');
1168
- return;
1169
- }
1170
- if (!catalog.length) { flash('子代理目录是空的(这次运行可能没产生子会话)'); return; }
1171
- const known = new Set(nodes.map((n) => n.id));
1172
- const byNode = new Map();
1173
- const samples = [];
1174
- for (const entry of catalog) {
1175
- const label = String(entry.label || entry.name || entry.description || '');
1176
- if (samples.length < 2) samples.push(label || '(无 label)');
1177
- const m = NODE_MARK.exec(label);
1178
- if (!m) continue;
1179
- const nodeId = m[1];
1180
- if (!known.has(nodeId)) continue;
1181
- if (!byNode.has(nodeId)) byNode.set(nodeId, []);
1182
- byNode.get(nodeId).push({ childId: entry.id, label, mode: entry.mode || 'continuable' });
1183
- }
1184
- if (!byNode.size) {
1185
- flash('目录 ' + catalog.length + ' 项但没有带 #节点id 的,示例:' + samples.join(' / '));
1186
- return;
1187
- }
1188
- setNodes((ns) => ns.map((n) => (byNode.has(n.id) ? { ...n, runs: byNode.get(n.id) } : n)));
1189
- flash('已同步 ' + byNode.size + ' 个节点的运行记录');
1190
- } catch (_e) {
1191
- flash('同步运行记录失败:' + String((_e && _e.message) || _e));
1192
- }
1193
- };
1194
-
1195
1697
  const openRun = (node, run) => {
1196
1698
  try {
1197
1699
  const sr = hostCtx && hostCtx.sidebarRight;
1198
- if (!sr || typeof sr.openResource !== 'function') { flash('无法打开会话'); return; }
1700
+ if (!sr || typeof sr.openResource !== 'function') { flash(t('cannotOpen')); return; }
1199
1701
  const addr = 'dsh-resource://subagentchat/session/' + encodeURIComponent(run.childId)
1200
1702
  + '?parent=' + encodeURIComponent(sessionId)
1201
1703
  + '&mode=' + encodeURIComponent(run.mode || 'continuable');
1202
1704
  sr.openResource(addr, { kind: 'subagentchat', preferNewPane: true });
1203
1705
  } catch (_e) {
1204
- flash('打开会话失败');
1706
+ flash(t('cannotOpen'));
1707
+ }
1708
+ };
1709
+
1710
+ const openNodeSession = async (node) => {
1711
+ let run = runsById[node.id];
1712
+ if (!run) {
1713
+ const sessions = hostCtx && hostCtx.sessions;
1714
+ if (sessions && sessionId && typeof sessions.refreshProjections === 'function') {
1715
+ try { await sessions.refreshProjections(sessionId); } catch (_e) { /* ignore */ }
1716
+ }
1717
+ const { status: nextStatus, runs: nextRuns } = readCatalog();
1718
+ if (nextStatus) setStatusById(nextStatus);
1719
+ if (nextRuns) {
1720
+ setRunsById(nextRuns);
1721
+ run = nextRuns[node.id];
1722
+ }
1205
1723
  }
1724
+ if (!run) { flash(t('cannotOpen')); return; }
1725
+ openRun(node, run);
1206
1726
  };
1207
1727
 
1208
- const addNode = (kind) => {
1728
+ const addNode = (kind, atWorld) => {
1209
1729
  pushSnapshot();
1730
+ const newId = 'n' + Date.now().toString(36) + Math.random().toString(36).slice(2, 4);
1210
1731
  setNodes((ns) => {
1211
1732
  const i = ns.length;
1212
1733
  const center = viewportCenterWorld();
1734
+ const x = atWorld && typeof atWorld.x === 'number'
1735
+ ? Math.round(atWorld.x - NODE_W / 2)
1736
+ : center.x + 40 + (ns.length % 3) * 30;
1737
+ const y = atWorld && typeof atWorld.y === 'number'
1738
+ ? Math.round(atWorld.y - NODE_H / 2)
1739
+ : center.y - NODE_H / 2 + (ns.length % 3) * 40;
1213
1740
  return [...ns, {
1214
- id: 'n' + Date.now().toString(36),
1741
+ id: newId,
1215
1742
  kind: kind === 'lead' ? 'lead' : 'agent',
1216
- // New nodes land near the middle of the viewport, nudged right.
1217
- x: center.x + 40 + (ns.length % 3) * 30,
1218
- y: center.y - NODE_H / 2 + (ns.length % 3) * 40,
1743
+ x,
1744
+ y,
1219
1745
  label: kind === 'lead' ? 'Lead 步骤 ' + i : 'Node ' + i,
1220
1746
  provider: '',
1221
1747
  model: '',
1222
1748
  role: '',
1223
1749
  }];
1224
1750
  });
1751
+ setSelectedIds([newId]);
1752
+ setAddMenu(null);
1225
1753
  };
1226
1754
 
1227
1755
  const updateNode = (id, patch) => {
@@ -1237,8 +1765,110 @@ window.__ModuleLoader__.load({
1237
1765
  flash(t('deletedNode'));
1238
1766
  };
1239
1767
 
1768
+ const deleteSelected = () => {
1769
+ const curSel = selectedIdsRef.current;
1770
+ if (!curSel.length) return;
1771
+ const targets = curSel.filter((id) => id !== 'lead');
1772
+ if (!targets.length) { flash(t('leadLocked')); return; }
1773
+ const drop = new Set(targets);
1774
+ pushSnapshot();
1775
+ setNodes((ns) => ns.filter((n) => !drop.has(n.id)));
1776
+ setEdges((es) => es.filter((e) => !drop.has(e.from) && !drop.has(e.to)));
1777
+ setSelectedIds([]);
1778
+ flash(targets.length === 1 ? t('deletedNode') : t('deletedNodes') + ' ×' + targets.length);
1779
+ };
1780
+
1781
+ const duplicateSelected = () => {
1782
+ const curSel = selectedIdsRef.current;
1783
+ const curNodes = nodesRef.current;
1784
+ const sources = curSel
1785
+ .filter((id) => id !== 'lead')
1786
+ .map((id) => curNodes.find((n) => n.id === id))
1787
+ .filter(Boolean);
1788
+ if (!sources.length) return;
1789
+ pushSnapshot();
1790
+ const stamp = Date.now().toString(36);
1791
+ const clones = sources.map((src, idx) => {
1792
+ const { runs: _runs, ...rest } = src;
1793
+ return {
1794
+ ...rest,
1795
+ id: 'n' + stamp + '_' + idx + Math.random().toString(36).slice(2, 4),
1796
+ x: (src.x || 0) + 28,
1797
+ y: (src.y || 0) + 28,
1798
+ };
1799
+ });
1800
+ setNodes((ns) => ns.concat(clones));
1801
+ setSelectedIds(clones.map((c) => c.id));
1802
+ flash(t('duplicatedNodes') + ' ×' + clones.length);
1803
+ };
1804
+
1805
+ const autoLayout = () => {
1806
+ const curNodes = nodesRef.current;
1807
+ const curEdges = edgesRef.current;
1808
+ if (!curNodes.length) return;
1809
+ pushSnapshot();
1810
+ const next = layoutGraph(curNodes, curEdges);
1811
+ setNodes(next);
1812
+ setTimeout(() => fitView(next), 0);
1813
+ flash(t('layoutDone'));
1814
+ };
1815
+
1816
+ const exportToClipboard = () => {
1817
+ const cleanNodes = nodesRef.current.map((n) => {
1818
+ const { runs: _runs, ...rest } = n;
1819
+ return rest;
1820
+ });
1821
+ const text = JSON.stringify({ nodes: cleanNodes, edges: edgesRef.current }, null, 2);
1822
+ const fallbackCopy = () => {
1823
+ try {
1824
+ const ta = document.createElement('textarea');
1825
+ ta.value = text;
1826
+ ta.style.position = 'fixed';
1827
+ ta.style.opacity = '0';
1828
+ document.body.appendChild(ta);
1829
+ ta.select();
1830
+ const ok = document.execCommand && document.execCommand('copy');
1831
+ document.body.removeChild(ta);
1832
+ flash(ok ? t('exportOk') : t('exportFail'));
1833
+ } catch (_e) {
1834
+ flash(t('exportFail'));
1835
+ }
1836
+ };
1837
+ try {
1838
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1839
+ navigator.clipboard.writeText(text).then(() => flash(t('exportOk')), fallbackCopy);
1840
+ return;
1841
+ }
1842
+ } catch (_e) { /* fall through */ }
1843
+ fallbackCopy();
1844
+ };
1845
+
1846
+ const openAddMenuAtCursor = () => {
1847
+ const wrap = canvasWrapRef.current;
1848
+ const content = contentRef.current;
1849
+ if (!wrap || !content) return;
1850
+ const wrapRect = wrap.getBoundingClientRect();
1851
+ const contentRect = content.getBoundingClientRect();
1852
+ const k = viewRef.current.k || 1;
1853
+ const mouse = lastMouseRef.current;
1854
+ const insideWrap = mouse
1855
+ && mouse.clientX >= wrapRect.left && mouse.clientX <= wrapRect.right
1856
+ && mouse.clientY >= wrapRect.top && mouse.clientY <= wrapRect.bottom;
1857
+ const cx = insideWrap ? mouse.clientX : (wrapRect.left + wrapRect.width / 2);
1858
+ const cy = insideWrap ? mouse.clientY : (wrapRect.top + wrapRect.height / 2);
1859
+ const sx = Math.max(8, Math.min(wrapRect.width - 176, cx - wrapRect.left));
1860
+ const sy = Math.max(8, Math.min(wrapRect.height - 96, cy - wrapRect.top));
1861
+ const wx = (cx - contentRect.left) / k - WORLD_PAD;
1862
+ const wy = (cy - contentRect.top) / k - WORLD_PAD;
1863
+ setAddMenu({ sx, sy, wx, wy });
1864
+ setMenuOpen(false);
1865
+ setPresetOpen(null);
1866
+ setOpenModelFor(null);
1867
+ };
1868
+
1240
1869
  /** Dragging any selected node moves the whole selection together. */
1241
1870
  const onNodeDown = (e, id) => {
1871
+ if (e.button !== 0 || spaceDown.current) return;
1242
1872
  if (!contentRef.current) return;
1243
1873
  const node = nodes.find((n) => n.id === id);
1244
1874
  if (!node) return;
@@ -1252,6 +1882,7 @@ window.__ModuleLoader__.load({
1252
1882
  nodeDrag.current = { origins, startX: p.x, startY: p.y, moved: false };
1253
1883
  setDragging(true);
1254
1884
  setOpenModelFor(null);
1885
+ setAddMenu(null);
1255
1886
  e.preventDefault();
1256
1887
  e.stopPropagation();
1257
1888
  };
@@ -1275,11 +1906,15 @@ window.__ModuleLoader__.load({
1275
1906
  e.stopPropagation();
1276
1907
  const toId = pending.toId;
1277
1908
  if (toId && toId !== id) {
1278
- pushSnapshot();
1279
- setEdges((es) => {
1280
- if (es.some((x) => x.from === id && x.to === toId && x.type === type)) return es;
1281
- return [...es, { id: 'e' + Date.now().toString(36), from: id, to: toId, type }];
1282
- });
1909
+ if (wouldCycle(nodesRef.current, edgesRef.current, id, toId)) {
1910
+ flash(t('cycleBlocked'));
1911
+ } else {
1912
+ pushSnapshot();
1913
+ setEdges((es) => {
1914
+ if (es.some((x) => x.from === id && x.to === toId && x.type === type)) return es;
1915
+ return [...es, { id: 'e' + Date.now().toString(36), from: id, to: toId, type }];
1916
+ });
1917
+ }
1283
1918
  }
1284
1919
  setPending(null);
1285
1920
  setDragging(false);
@@ -1317,16 +1952,147 @@ window.__ModuleLoader__.load({
1317
1952
  e.stopPropagation();
1318
1953
  if (pending.fromId !== id) {
1319
1954
  const fromId = pending.fromId;
1320
- pushSnapshot();
1321
- setEdges((es) => {
1322
- if (es.some((x) => x.from === fromId && x.to === id && x.type === type)) return es;
1323
- return [...es, { id: 'e' + Date.now().toString(36), from: fromId, to: id, type }];
1324
- });
1955
+ if (wouldCycle(nodesRef.current, edgesRef.current, fromId, id)) {
1956
+ flash(t('cycleBlocked'));
1957
+ } else {
1958
+ pushSnapshot();
1959
+ setEdges((es) => {
1960
+ if (es.some((x) => x.from === fromId && x.to === id && x.type === type)) return es;
1961
+ return [...es, { id: 'e' + Date.now().toString(36), from: fromId, to: id, type }];
1962
+ });
1963
+ }
1325
1964
  }
1326
1965
  setPending(null);
1327
1966
  setDragging(false);
1328
1967
  };
1329
1968
 
1969
+ // Middle-mouse drag (or Space + left-drag) pans the canvas from anywhere inside it.
1970
+ useEffect(() => {
1971
+ const inside = (ev) => {
1972
+ const el = canvasElRef.current;
1973
+ return Boolean(el) && ev.target instanceof Node && el.contains(ev.target);
1974
+ };
1975
+ const isEditable = (target) => {
1976
+ if (!target || !(target instanceof HTMLElement)) return false;
1977
+ const tag = target.tagName;
1978
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
1979
+ };
1980
+ const onDown = (ev) => {
1981
+ if (!inside(ev)) return;
1982
+ const wantPan = ev.button === 1 || (ev.button === 0 && spaceDown.current);
1983
+ if (!wantPan) return;
1984
+ ev.preventDefault();
1985
+ ev.stopPropagation();
1986
+ try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
1987
+ const cur = viewRef.current;
1988
+ panDrag.current = { startX: ev.clientX, startY: ev.clientY, originX: cur.x, originY: cur.y };
1989
+ setPanning(true);
1990
+ setDragging(true);
1991
+ };
1992
+ const onAuxClick = (ev) => {
1993
+ if (ev.button === 1 && inside(ev)) ev.preventDefault();
1994
+ };
1995
+ const onKeyDown = (ev) => {
1996
+ if (ev.code === 'Space' && !isEditable(ev.target)) {
1997
+ spaceDown.current = true;
1998
+ setSpaceHeld(true);
1999
+ }
2000
+ };
2001
+ const onKeyUp = (ev) => {
2002
+ if (ev.code === 'Space') {
2003
+ spaceDown.current = false;
2004
+ setSpaceHeld(false);
2005
+ }
2006
+ };
2007
+ const onBlur = () => {
2008
+ spaceDown.current = false;
2009
+ setSpaceHeld(false);
2010
+ };
2011
+ window.addEventListener('mousedown', onDown, true);
2012
+ window.addEventListener('auxclick', onAuxClick, true);
2013
+ window.addEventListener('keydown', onKeyDown);
2014
+ window.addEventListener('keyup', onKeyUp);
2015
+ window.addEventListener('blur', onBlur);
2016
+ return () => {
2017
+ window.removeEventListener('mousedown', onDown, true);
2018
+ window.removeEventListener('auxclick', onAuxClick, true);
2019
+ window.removeEventListener('keydown', onKeyDown);
2020
+ window.removeEventListener('keyup', onKeyUp);
2021
+ window.removeEventListener('blur', onBlur);
2022
+ };
2023
+ }, []);
2024
+
2025
+ // Canvas keyboard shortcuts (Blender-style Shift+A, Ctrl+Z, Ctrl+D, Delete, Esc).
2026
+ const keyActionsRef = useRef(null);
2027
+ keyActionsRef.current = {
2028
+ undo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode,
2029
+ addMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen,
2030
+ setAddMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen,
2031
+ };
2032
+ useEffect(() => {
2033
+ const isEditable = (target) => {
2034
+ if (!target || !(target instanceof HTMLElement)) return false;
2035
+ const tag = target.tagName;
2036
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
2037
+ };
2038
+ const onKey = (ev) => {
2039
+ const act = keyActionsRef.current;
2040
+ if (!act) return;
2041
+ if (ev.key === 'Escape') {
2042
+ if (act.addMenu || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen) {
2043
+ ev.preventDefault();
2044
+ act.setAddMenu(null);
2045
+ act.setRoleEditFor(null);
2046
+ act.setOpenModelFor(null);
2047
+ act.setMenuOpen(false);
2048
+ act.setPresetOpen(null);
2049
+ act.setHelpOpen(false);
2050
+ }
2051
+ return;
2052
+ }
2053
+ if (isEditable(ev.target)) return;
2054
+ if (act.addMenu) {
2055
+ if (ev.key === '1' || ev.key === 'Enter') {
2056
+ ev.preventDefault();
2057
+ act.addNode('agent', { x: act.addMenu.wx, y: act.addMenu.wy });
2058
+ return;
2059
+ }
2060
+ if (ev.key === '2') {
2061
+ ev.preventDefault();
2062
+ act.addNode('lead', { x: act.addMenu.wx, y: act.addMenu.wy });
2063
+ return;
2064
+ }
2065
+ }
2066
+ const root = rootElRef.current;
2067
+ const activeInRoot = Boolean(root && document.activeElement && root.contains(document.activeElement));
2068
+ if (!pointerInsideRoot.current && !activeInRoot) return;
2069
+ const mod = ev.ctrlKey || ev.metaKey;
2070
+ if (!mod && !ev.altKey && ev.shiftKey && (ev.key === 'A' || ev.key === 'a')) {
2071
+ ev.preventDefault();
2072
+ act.openAddMenuAtCursor();
2073
+ return;
2074
+ }
2075
+ if (mod && !ev.shiftKey && !ev.altKey && (ev.key === 'z' || ev.key === 'Z')) {
2076
+ ev.preventDefault();
2077
+ act.undo();
2078
+ return;
2079
+ }
2080
+ if (mod && !ev.shiftKey && !ev.altKey && (ev.key === 'd' || ev.key === 'D')) {
2081
+ ev.preventDefault();
2082
+ act.duplicateSelected();
2083
+ return;
2084
+ }
2085
+ if (!mod && !ev.altKey && (ev.key === 'Delete' || ev.key === 'Backspace')) {
2086
+ if (selectedIdsRef.current.length) {
2087
+ ev.preventDefault();
2088
+ act.deleteSelected();
2089
+ }
2090
+ }
2091
+ };
2092
+ window.addEventListener('keydown', onKey);
2093
+ return () => window.removeEventListener('keydown', onKey);
2094
+ }, []);
2095
+
1330
2096
  // Suppress the host context menu over the canvas while cutting is on.
1331
2097
  useEffect(() => {
1332
2098
  if (!cutMode) return undefined;
@@ -1340,7 +2106,9 @@ window.__ModuleLoader__.load({
1340
2106
  ev.preventDefault();
1341
2107
  const start = pointTo(ev);
1342
2108
  cutRef.current = start;
2109
+ cutHits.current = new Set();
1343
2110
  setCutPath([start]);
2111
+ setCutVictims([]);
1344
2112
  setDragging(true);
1345
2113
  };
1346
2114
  window.addEventListener('contextmenu', onCtx, true);
@@ -1379,6 +2147,8 @@ window.__ModuleLoader__.load({
1379
2147
  if (e.button !== 0) return;
1380
2148
  if (roleEditFor) setRoleEditFor(null);
1381
2149
  if (menuOpen) setMenuOpen(false);
2150
+ if (addMenu) setAddMenu(null);
2151
+ if (presetOpen) setPresetOpen(null);
1382
2152
  e.preventDefault();
1383
2153
  try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
1384
2154
  const p = pointTo(e);
@@ -1389,6 +2159,13 @@ window.__ModuleLoader__.load({
1389
2159
  };
1390
2160
 
1391
2161
  const onCanvasMove = (e) => {
2162
+ if (panDrag.current) {
2163
+ const pan = panDrag.current;
2164
+ const dx = e.clientX - pan.startX;
2165
+ const dy = e.clientY - pan.startY;
2166
+ commitView({ k: viewRef.current.k, x: pan.originX + dx, y: pan.originY + dy });
2167
+ return;
2168
+ }
1392
2169
  if (nodeDrag.current) {
1393
2170
  const p = pointTo(e);
1394
2171
  const drag = nodeDrag.current;
@@ -1454,6 +2231,10 @@ window.__ModuleLoader__.load({
1454
2231
  setSelectedIds(hitTest(marquee));
1455
2232
  setMarquee(null);
1456
2233
  }
2234
+ if (panDrag.current) {
2235
+ panDrag.current = null;
2236
+ setPanning(false);
2237
+ }
1457
2238
  nodeDrag.current = null;
1458
2239
  setPending(null);
1459
2240
  setDragging(false);
@@ -1475,68 +2256,69 @@ window.__ModuleLoader__.load({
1475
2256
  };
1476
2257
 
1477
2258
  /** Load a canvas document produced by the model. */
1478
- const applyCanvasDoc = (doc) => {
2259
+ const applyCanvasDoc = (doc, remoteAt) => {
1479
2260
  if (!doc || !Array.isArray(doc.nodes)) return false;
1480
2261
  const merge = doc.mode === 'merge';
1481
2262
  if (!merge && !doc.nodes.length) return false;
1482
2263
  pushSnapshot();
1483
- applyStamp.current = typeof doc.at === 'number' ? doc.at : null;
2264
+ const stamp = typeof remoteAt === 'number' ? remoteAt : (typeof doc.at === 'number' ? doc.at : null);
2265
+ applyStamp.current = stamp;
2266
+ const removedNodes = new Set(doc.removeNodes || []);
2267
+ const rawIncomingEdges = Array.isArray(doc.edges) ? doc.edges : [];
1484
2268
  setNodes((existing) => {
1485
2269
  const byId = new Map(existing.map((n) => [n.id, n]));
2270
+ const placed = new Map(existing.map((n) => [n.id, { x: n.x, y: n.y }]));
2271
+ let addedCount = 0;
1486
2272
  const incoming = doc.nodes.map((n, i) => {
1487
2273
  const prev = byId.get(n.id) || {};
1488
- return {
1489
- ...prev,
1490
- ...n,
1491
- // keep the position the user placed, unless the document sets one
1492
- x: typeof n.x === 'number' ? n.x : (typeof prev.x === 'number' ? prev.x : 60 + i * 300),
1493
- y: typeof n.y === 'number' ? n.y : (typeof prev.y === 'number' ? prev.y : 80),
1494
- };
2274
+ let x = typeof n.x === 'number' ? n.x : prev.x;
2275
+ let y = typeof n.y === 'number' ? n.y : prev.y;
2276
+ if (typeof x !== 'number' || typeof y !== 'number') {
2277
+ // Place a newly patched node to the right of its first upstream node when possible.
2278
+ const parentEdge = rawIncomingEdges.find((e) => e && e.to === n.id && placed.has(e.from));
2279
+ if (parentEdge) {
2280
+ const parentPos = placed.get(parentEdge.from);
2281
+ const siblingCount = Array.from(placed.values()).filter((p) => Math.abs(p.x - (parentPos.x + 300)) < 40).length;
2282
+ x = parentPos.x + 300;
2283
+ y = parentPos.y + siblingCount * 240;
2284
+ } else {
2285
+ const leadPos = placed.get('lead') || { x: 40, y: 80 };
2286
+ x = merge ? leadPos.x + 300 : 60 + i * 300;
2287
+ y = merge ? leadPos.y + (addedCount + 1) * 240 : 80;
2288
+ }
2289
+ addedCount += 1;
2290
+ }
2291
+ placed.set(n.id, { x, y });
2292
+ return { ...prev, ...n, x, y };
1495
2293
  });
1496
2294
  if (!merge) return incoming;
1497
2295
  const touched = new Set(incoming.map((n) => n.id));
1498
- const removed = new Set(doc.removeNodes || []);
1499
- const kept = existing.filter((n) => !touched.has(n.id) && !removed.has(n.id));
2296
+ const kept = existing.filter((n) => !touched.has(n.id) && !removedNodes.has(n.id));
1500
2297
  return kept.concat(incoming);
1501
2298
  });
1502
2299
  setEdges((existing) => {
1503
- const incoming = (Array.isArray(doc.edges) ? doc.edges : []).map((e, i) => ({
2300
+ const incoming = rawIncomingEdges.map((e, i) => ({
1504
2301
  id: e.id || 'e' + i + '-' + Math.random().toString(36).slice(2, 6),
1505
2302
  from: e.from,
1506
2303
  to: e.to,
1507
2304
  type: e.type || 'prompt',
1508
2305
  }));
1509
2306
  if (!merge) return incoming;
1510
- const drop = new Set((doc.removeEdges || []).map((e) => String(e.from) + '>' + String(e.to)));
1511
- const kept = existing.filter((e) => !drop.has(e.from + '>' + e.to));
2307
+ const rawDrops = Array.isArray(doc.removeEdges) ? doc.removeEdges : [];
2308
+ const matchesDrop = (e) => rawDrops.some((r) => r
2309
+ && String(r.from) === e.from
2310
+ && String(r.to) === e.to
2311
+ && (!r.type || r.type === e.type));
2312
+ const kept = existing.filter((e) => !matchesDrop(e) && !removedNodes.has(e.from) && !removedNodes.has(e.to));
1512
2313
  const seen = new Set(kept.map((e) => e.from + '>' + e.to + '|' + e.type));
1513
- const added = incoming.filter((e) => !seen.has(e.from + '>' + e.to + '|' + e.type));
2314
+ const added = incoming.filter((e) => !removedNodes.has(e.from) && !removedNodes.has(e.to) && !seen.has(e.from + '>' + e.to + '|' + e.type));
1514
2315
  return kept.concat(added);
1515
2316
  });
1516
2317
  setSelectedIds([]);
1517
2318
  setStatusById({});
1518
- // Remember what the remote document claimed, so re-reading it on the next
1519
- // start does not resurrect nodes the user has deleted since.
1520
- if (typeof doc.at === 'number') {
1521
- try {
1522
- const key = storageKey(sessionId);
1523
- const raw = window.localStorage.getItem(key);
1524
- const local = raw ? JSON.parse(raw) : {};
1525
- if (!local || typeof local.at !== 'number' || local.at <= doc.at) {
1526
- window.localStorage.setItem(key, JSON.stringify({
1527
- nodes: doc.nodes,
1528
- edges: Array.isArray(doc.edges) ? doc.edges : [],
1529
- enabled: Boolean(local && local.enabled),
1530
- at: doc.at,
1531
- }));
1532
- }
1533
- } catch (_e) { /* storage unavailable */ }
1534
- }
1535
- const lead = doc.nodes.find((n) => n.id === 'lead') || doc.nodes[0];
1536
- if (lead) {
1537
- const lx = typeof lead.x === 'number' ? lead.x : 60;
1538
- const ly = typeof lead.y === 'number' ? lead.y : 80;
1539
- setTimeout(() => centerOn(lx + NODE_W / 2, ly + NODE_H / 2), 0);
2319
+ if (!merge) {
2320
+ setRunsById({});
2321
+ setTimeout(() => fitView(nodesRef.current), 0);
1540
2322
  }
1541
2323
  return true;
1542
2324
  };
@@ -1592,9 +2374,10 @@ window.__ModuleLoader__.load({
1592
2374
  return;
1593
2375
  }
1594
2376
  } catch (_e) { /* ignore */ }
1595
- const valid = canvas && Array.isArray(canvas.nodes) && canvas.nodes.length
2377
+ const valid = canvas && Array.isArray(canvas.nodes)
2378
+ && (canvas.mode === 'merge' || canvas.nodes.length > 0)
1596
2379
  && canvas.nodes.every((n) => n && typeof n.id === 'string');
1597
- if (valid && applyCanvasDoc(canvas)) {
2380
+ if (valid && applyCanvasDoc(canvas, doc.at)) {
1598
2381
  flash(t('generated'));
1599
2382
  setSyncNote(t('syncApplied'));
1600
2383
  setTimeout(() => setSyncNote(''), 4000);
@@ -1636,10 +2419,27 @@ window.__ModuleLoader__.load({
1636
2419
  setEdges(preset.edges);
1637
2420
  setSelectedIds([]);
1638
2421
  setStatusById({});
2422
+ setRunsById({});
1639
2423
  setPresetOpen(null);
2424
+ setTimeout(() => fitView(preset.nodes), 0);
1640
2425
  flash(t('loadedPreset') + ': ' + name);
1641
2426
  };
1642
2427
 
2428
+ const applyTemplate = (tpl) => {
2429
+ if (!tpl || !Array.isArray(tpl.nodes) || !Array.isArray(tpl.edges)) return;
2430
+ const clonedNodes = tpl.nodes.map((n) => ({ ...n }));
2431
+ const clonedEdges = tpl.edges.map((e) => ({ ...e }));
2432
+ pushSnapshot();
2433
+ setNodes(clonedNodes);
2434
+ setEdges(clonedEdges);
2435
+ setSelectedIds([]);
2436
+ setStatusById({});
2437
+ setRunsById({});
2438
+ setPresetOpen(null);
2439
+ setTimeout(() => fitView(clonedNodes), 0);
2440
+ flash(t('loadedPreset') + ': ' + tpl.name);
2441
+ };
2442
+
1643
2443
  const deletePreset = (name) => {
1644
2444
  const next = { ...presets };
1645
2445
  delete next[name];
@@ -1656,10 +2456,17 @@ window.__ModuleLoader__.load({
1656
2456
  };
1657
2457
 
1658
2458
  const modelValue = (node) => (node.provider ? node.provider + '::' : '') + (node.model || '');
1659
- const modelEntry = (node) => models.find((m) => m.provider + '::' + m.model === modelValue(node));
2459
+ const modelEntry = (node) => {
2460
+ if (!node || !node.model) return undefined;
2461
+ if (node.provider) {
2462
+ const exact = models.find((m) => m.provider === node.provider && m.model === node.model);
2463
+ if (exact) return exact;
2464
+ }
2465
+ return models.find((m) => m.model === node.model);
2466
+ };
1660
2467
  const modelLabel = (node) => {
1661
2468
  const hit = modelEntry(node);
1662
- return hit ? hit.modelName : (node.model || t('pickModel'));
2469
+ return hit ? (hit.modelName || hit.model) : (node.model || t('pickModel'));
1663
2470
  };
1664
2471
  // Reasoning ids are adapter-declared per model; '' means "use the model default".
1665
2472
  const reasoningOptions = (node) => {
@@ -1688,7 +2495,10 @@ window.__ModuleLoader__.load({
1688
2495
  const key = 'f:' + node.id;
1689
2496
  const isOpen = openModelFor === key;
1690
2497
  const current = node.fallbackModel;
1691
- const shown = models.find((m) => m.model === current);
2498
+ const shown = current
2499
+ ? ((node.fallbackProvider && models.find((m) => m.provider === node.fallbackProvider && m.model === current))
2500
+ || models.find((m) => m.model === current))
2501
+ : undefined;
1692
2502
  const rows = [];
1693
2503
  rows.push(h('div', {
1694
2504
  key: 'none',
@@ -1701,7 +2511,7 @@ window.__ModuleLoader__.load({
1701
2511
  rows.push(h('div', { key: 'h-' + m.provider, style: S.menuHead }, m.providerName || m.provider));
1702
2512
  lastProvider = m.provider;
1703
2513
  }
1704
- const picked = m.model === current;
2514
+ const picked = shown ? (m.provider === shown.provider && m.model === shown.model) : (m.model === current);
1705
2515
  rows.push(h('div', {
1706
2516
  key: m.provider + '::' + m.model,
1707
2517
  style: picked ? { ...S.menuRow, background: C.hover, color: C.accent } : S.menuRow,
@@ -1774,6 +2584,7 @@ window.__ModuleLoader__.load({
1774
2584
  });
1775
2585
  }
1776
2586
  const current = modelValue(node);
2587
+ const matched = modelEntry(node);
1777
2588
  const isOpen = openModelFor === node.id;
1778
2589
  const rows = [];
1779
2590
  let lastProvider = null;
@@ -1782,7 +2593,9 @@ window.__ModuleLoader__.load({
1782
2593
  rows.push(h('div', { key: 'h-' + m.provider, style: S.menuHead }, m.providerName || m.provider));
1783
2594
  lastProvider = m.provider;
1784
2595
  }
1785
- const selectedRow = m.provider + '::' + m.model === current;
2596
+ const selectedRow = matched
2597
+ ? (m.provider === matched.provider && m.model === matched.model)
2598
+ : (m.provider + '::' + m.model === current);
1786
2599
  rows.push(h('div', {
1787
2600
  key: m.provider + '::' + m.model,
1788
2601
  style: selectedRow ? { ...S.menuRow, background: C.hover, color: C.accent } : S.menuRow,
@@ -1808,46 +2621,136 @@ window.__ModuleLoader__.load({
1808
2621
  );
1809
2622
  };
1810
2623
 
2624
+ const fxName = (level) => (level === 'minimal' ? t('fxMinimal') : (level === 'vivid' ? t('fxVivid') : t('fxStandard')));
2625
+ const selectedSet = new Set(selectedIds);
2626
+ const connectedIn = new Set();
2627
+ const connectedOut = new Set();
2628
+ for (const e of edges) {
2629
+ const type = e.type || 'prompt';
2630
+ connectedOut.add(e.from + '|' + type);
2631
+ connectedIn.add(e.to + '|' + type);
2632
+ }
2633
+ const reachableIds = reachableFrom(nodes, edges);
2634
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
2635
+
2636
+ // Identify intermediate/final Lead nodes whose upstream subagents are all
2637
+ // finished and whose downstream has not started yet ("Ready for Lead").
2638
+ const leadReadyIds = new Set();
2639
+ if (enabled) {
2640
+ for (const n of nodes) {
2641
+ if (n.kind !== 'lead' || n.id === 'lead' || !reachableIds.has(n.id)) continue;
2642
+ const upIds = edges
2643
+ .filter((e) => e.to === n.id && e.from !== 'lead' && nodeById.has(e.from))
2644
+ .map((e) => e.from);
2645
+ if (!upIds.length) continue;
2646
+ const upAgents = upIds.filter((id) => nodeById.get(id).kind !== 'lead');
2647
+ if (!upAgents.length) continue;
2648
+ const allUpDone = upAgents.every((id) => statusById[id] === 'done');
2649
+ const downIds = edges.filter((e) => e.from === n.id).map((e) => e.to);
2650
+ const anyDownStarted = downIds.some((id) => Boolean(statusById[id]));
2651
+ if (allUpDone && !anyDownStarted) leadReadyIds.add(n.id);
2652
+ }
2653
+ }
2654
+
1811
2655
  const edgeEls = edges.map((edge) => {
1812
- const from = nodes.find((n) => n.id === edge.from);
1813
- const to = nodes.find((n) => n.id === edge.to);
2656
+ const from = nodeById.get(edge.from);
2657
+ const to = nodeById.get(edge.to);
1814
2658
  if (!from || !to) return null;
1815
- const color = (SOCKET_TYPES.find((t) => t.id === edge.type) || SOCKET_TYPES[0]).color;
2659
+ const color = (SOCKET_TYPES.find((sock) => sock.id === edge.type) || SOCKET_TYPES[0]).color;
1816
2660
  const d = edgePath(from, to, edge.type);
1817
2661
  const highlighted = cutVictims.includes(edge.id);
1818
- return h('path', {
1819
- key: edge.id,
1820
- d,
1821
- stroke: highlighted ? '#e5534b' : color,
1822
- strokeWidth: highlighted ? 3 : 2,
1823
- fill: 'none',
1824
- style: { pointerEvents: 'none' },
1825
- });
2662
+ const hasSel = selectedSet.size > 0;
2663
+ const linkedToSel = hasSel && (selectedSet.has(edge.from) || selectedSet.has(edge.to));
2664
+ const toRunning = enabled && statusById[edge.to] === 'running';
2665
+ const fromReady = edge.from === 'lead'
2666
+ || from.kind === 'lead'
2667
+ || statusById[edge.from] === 'done';
2668
+ const isFlowing = enabled && !highlighted && (
2669
+ (toRunning && fromReady)
2670
+ || (leadReadyIds.has(edge.to) && statusById[edge.from] === 'done')
2671
+ );
2672
+ const isCompletedLink = enabled && !highlighted && statusById[edge.from] === 'done'
2673
+ && (statusById[edge.to] === 'done' || statusById[edge.to] === 'running' || leadReadyIds.has(edge.to));
2674
+ const dimmed = hasSel && !linkedToSel && !highlighted && !isFlowing;
2675
+ const baseWidth = highlighted ? 3 : (linkedToSel || isFlowing ? 2.6 : 2);
2676
+ const baseOpacity = dimmed ? 0.26 : (isFlowing || linkedToSel ? 1 : (isCompletedLink ? 0.92 : 0.78));
2677
+ const useGlow = fxLevel === 'vivid' && !dimmed && (highlighted || isFlowing || linkedToSel || edge.type !== 'prompt');
2678
+ const showDashFlow = isFlowing && fxLevel !== 'minimal';
2679
+ const showBead = isFlowing && fxLevel === 'vivid';
2680
+
2681
+ return h('g', { key: edge.id, style: { pointerEvents: 'none' } },
2682
+ h('path', {
2683
+ d,
2684
+ stroke: highlighted ? '#e5534b' : color,
2685
+ strokeWidth: baseWidth,
2686
+ strokeOpacity: showDashFlow ? 0.35 : baseOpacity,
2687
+ fill: 'none',
2688
+ filter: useGlow ? 'url(#dsh-wc-glow)' : undefined,
2689
+ }),
2690
+ showDashFlow && h('path', {
2691
+ d,
2692
+ className: 'dsh-wc-edge-flow',
2693
+ stroke: color,
2694
+ strokeWidth: fxLevel === 'vivid' ? 2.8 : 2.4,
2695
+ strokeLinecap: 'round',
2696
+ fill: 'none',
2697
+ filter: fxLevel === 'vivid' ? 'url(#dsh-wc-glow)' : undefined,
2698
+ }),
2699
+ showBead && h('circle', {
2700
+ r: 3.3,
2701
+ fill: color,
2702
+ filter: 'url(#dsh-wc-glow)',
2703
+ },
2704
+ h('animateMotion', {
2705
+ dur: '1.25s',
2706
+ repeatCount: 'indefinite',
2707
+ path: d,
2708
+ }),
2709
+ ),
2710
+ );
1826
2711
  });
1827
2712
 
1828
2713
  const renderBand = (node) => {
1829
2714
  const isEntry = node.id === 'lead';
1830
2715
  return h('div', { style: S.band },
1831
- SOCKET_TYPES.map((sock) => h('div', { key: sock.id, style: S.row },
1832
- h('span', { style: S.rowLabel }, sock.label),
1833
- !isEntry && h('div', {
1834
- style: { ...S.socket, left: -PORT / 2, borderColor: sock.color },
1835
- title: t('tipSocketOut'),
1836
- onMouseDown: (e) => onInputDown(e, node.id, sock.id),
1837
- onMouseUp: (e) => onInputUp(e, node.id, sock.id),
1838
- }),
1839
- h('div', {
1840
- style: { ...S.socket, right: -PORT / 2, borderColor: sock.color },
1841
- title: t('tipSocketIn'),
1842
- onMouseDown: (e) => onOutputDown(e, node.id, sock.id),
1843
- onMouseUp: (e) => onOutputUp(e, node.id, sock.id),
1844
- }),
1845
- )),
2716
+ SOCKET_TYPES.map((sock) => {
2717
+ const inLinked = connectedIn.has(node.id + '|' + sock.id);
2718
+ const outLinked = connectedOut.has(node.id + '|' + sock.id);
2719
+ return h('div', { key: sock.id, style: S.row },
2720
+ h('span', { style: S.rowLabel }, sock.label),
2721
+ !isEntry && h('div', {
2722
+ style: {
2723
+ ...S.socket,
2724
+ left: -PORT / 2,
2725
+ borderColor: sock.color,
2726
+ background: inLinked ? sock.color : C.elevated,
2727
+ boxShadow: inLinked
2728
+ ? (fxLevel === 'vivid' ? '0 0 6px ' + sock.color : '0 0 0 2px ' + C.elevated)
2729
+ : '0 0 0 3px transparent',
2730
+ },
2731
+ title: t('tipSocketOut'),
2732
+ onMouseDown: (e) => onInputDown(e, node.id, sock.id),
2733
+ onMouseUp: (e) => onInputUp(e, node.id, sock.id),
2734
+ }),
2735
+ h('div', {
2736
+ style: {
2737
+ ...S.socket,
2738
+ right: -PORT / 2,
2739
+ borderColor: sock.color,
2740
+ background: outLinked ? sock.color : C.elevated,
2741
+ boxShadow: outLinked
2742
+ ? (fxLevel === 'vivid' ? '0 0 6px ' + sock.color : '0 0 0 2px ' + C.elevated)
2743
+ : '0 0 0 3px transparent',
2744
+ },
2745
+ title: t('tipSocketIn'),
2746
+ onMouseDown: (e) => onOutputDown(e, node.id, sock.id),
2747
+ onMouseUp: (e) => onOutputUp(e, node.id, sock.id),
2748
+ }),
2749
+ );
2750
+ }),
1846
2751
  );
1847
2752
  };
1848
2753
 
1849
- const reachableIds = reachableFrom(nodes, edges);
1850
-
1851
2754
  // The canvas grows with its nodes so links past the original size are
1852
2755
  // still painted instead of being clipped by the SVG viewport.
1853
2756
  const contentW = Math.max(CONTENT_W, WORLD_PAD + Math.max(0, ...nodes.map((n) => n.x + NODE_W)) + 400);
@@ -1863,31 +2766,39 @@ window.__ModuleLoader__.load({
1863
2766
  .map((n) => n.id);
1864
2767
  };
1865
2768
 
1866
- return h('div', { style: S.root },
2769
+ return h('div', {
2770
+ ref: rootElRef,
2771
+ style: S.root,
2772
+ onMouseEnter: () => { pointerInsideRoot.current = true; },
2773
+ onMouseLeave: () => { pointerInsideRoot.current = false; },
2774
+ },
1867
2775
  h('div', { style: S.toolbar },
1868
2776
  h('button', { style: S.btn, onClick: () => addNode('agent'), type: 'button' }, t('addAgent')),
1869
2777
  h('button', { style: S.btn, onClick: () => addNode('lead'), type: 'button' }, t('addLead')),
2778
+ h('span', { style: S.toolSep }),
1870
2779
  h('button', { style: S.btn, onClick: undo, type: 'button', title: t('tipUndo') }, t('undo')),
1871
2780
  h('button', {
1872
- style: S.btn,
2781
+ style: enabled && dirty ? S.btnDirty : S.btn,
1873
2782
  onClick: () => pushPlan(enabled),
1874
2783
  type: 'button',
1875
2784
  title: t('tipSync'),
1876
2785
  }, t('sync')),
1877
-
2786
+ h('span', { style: S.toolSep }),
1878
2787
  h('button', {
1879
2788
  style: S.btn,
1880
- onClick: focusLead,
2789
+ onClick: () => fitView(),
1881
2790
  type: 'button',
1882
2791
  title: t('tipLocate'),
1883
2792
  }, t('locate')),
1884
2793
  h('button', {
1885
- style: S.btn,
1886
- onClick: () => focusLead(),
2794
+ style: { ...S.btn, cursor: 'ew-resize', minWidth: '50px', textAlign: 'center', fontVariantNumeric: 'tabular-nums' },
2795
+ onMouseDown: onZoomPillDown,
2796
+ onKeyDown: (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); focusLead(1); } },
1887
2797
  type: 'button',
1888
2798
  title: t('tipResetZoom'),
1889
2799
  }, Math.round(view.k * 100) + '%'),
1890
2800
  syncNote ? h('span', { style: S.syncNote, title: syncNote }, syncNote) : null,
2801
+ h('span', { style: S.toolSep }),
1891
2802
  h('button', {
1892
2803
  style: S.btn,
1893
2804
  onClick: toggleLang,
@@ -1913,8 +2824,25 @@ window.__ModuleLoader__.load({
1913
2824
  style: S.moreRow,
1914
2825
  onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1915
2826
  onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1916
- onClick: () => { setMenuOpen(false); setHelpOpen(true); },
1917
- }, t('help')),
2827
+ onClick: () => { setMenuOpen(false); exportToClipboard(); },
2828
+ }, t('exportBtn')),
2829
+ h('div', {
2830
+ style: S.moreRow,
2831
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
2832
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
2833
+ onClick: () => { setMenuOpen(false); autoLayout(); },
2834
+ }, t('autoLayoutBtn')),
2835
+ h('div', {
2836
+ style: S.moreRow,
2837
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
2838
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
2839
+ onClick: () => {
2840
+ const next = nextEffectLevel(fxLevel);
2841
+ setFxLevel(next);
2842
+ saveEffectLevel(next);
2843
+ flash(t('fxLabel') + t('sep') + fxName(next));
2844
+ },
2845
+ }, t('fxLabel') + t('sep') + fxName(fxLevel)),
1918
2846
  h('div', {
1919
2847
  style: S.moreRow,
1920
2848
  onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
@@ -1925,6 +2853,12 @@ window.__ModuleLoader__.load({
1925
2853
  saveCutMode(next);
1926
2854
  },
1927
2855
  }, t('cutLinks') + t('sep') + (cutMode ? t('on') : t('off'))),
2856
+ h('div', {
2857
+ style: S.moreRow,
2858
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
2859
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
2860
+ onClick: () => { setMenuOpen(false); setHelpOpen(true); },
2861
+ }, t('help')),
1928
2862
  ),
1929
2863
  ),
1930
2864
  h('div', { style: S.presetBar },
@@ -1953,7 +2887,17 @@ window.__ModuleLoader__.load({
1953
2887
  status || (enabled ? (dirty ? t('unsaved') : t('synced')) : '')),
1954
2888
  presetOpen === 'menu' && (() => {
1955
2889
  const names = Object.keys(presets);
2890
+ const templates = builtinTemplates(lang);
1956
2891
  return h('div', { style: S.presetMenu, onMouseDown: (e) => e.stopPropagation() },
2892
+ h('div', { style: S.menuHead }, t('builtinTemplates')),
2893
+ templates.map((tpl) => h('div', {
2894
+ key: tpl.id,
2895
+ style: S.presetRow,
2896
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
2897
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
2898
+ onClick: () => applyTemplate(tpl),
2899
+ }, h('span', { style: S.presetRowText, title: tpl.name }, tpl.name))),
2900
+ h('div', { style: S.menuHead }, t('myPresets')),
1957
2901
  names.length
1958
2902
  ? names.map((name) => h('div', {
1959
2903
  key: name,
@@ -1978,14 +2922,63 @@ window.__ModuleLoader__.load({
1978
2922
  h('div', { style: S.helpBody }, t('helpBody').split('\n').map((line, i) => h('div', { key: i, style: S.helpLine }, line))),
1979
2923
  ),
1980
2924
  ),
1981
- h('button', {
1982
- style: enabled ? S.floatOn : S.floatOff,
1983
- type: 'button',
1984
- onMouseDown: (e) => e.stopPropagation(),
1985
- onClick: toggleEnabled,
1986
- title: t('tipToggle'),
1987
- }, enabled ? t('enabled') : t('disabled')),
1988
- h('div', { ref: canvasElRef, style: S.canvas, onMouseDown: onCanvasDown },
2925
+ h('div', {
2926
+ ref: canvasWrapRef,
2927
+ style: S.canvasWrap,
2928
+ onMouseMove: (e) => { lastMouseRef.current = { clientX: e.clientX, clientY: e.clientY }; },
2929
+ },
2930
+ h('button', {
2931
+ style: enabled
2932
+ ? {
2933
+ ...S.floatOn,
2934
+ display: 'inline-flex',
2935
+ alignItems: 'center',
2936
+ gap: '6px',
2937
+ lineHeight: '14px',
2938
+ boxShadow: fxLevel === 'vivid'
2939
+ ? '0 0 14px rgba(47,129,247,0.35), 0 4px 14px rgba(0,0,0,0.35)'
2940
+ : S.floatOn.boxShadow,
2941
+ }
2942
+ : { ...S.floatOff, display: 'inline-flex', alignItems: 'center', gap: '6px', lineHeight: '14px' },
2943
+ type: 'button',
2944
+ onMouseDown: (e) => e.stopPropagation(),
2945
+ onClick: toggleEnabled,
2946
+ title: t('tipToggle'),
2947
+ },
2948
+ h('span', {
2949
+ className: enabled && fxLevel === 'vivid' ? 'dsh-wc-dot-live' : undefined,
2950
+ style: enabled
2951
+ ? { width: '7px', height: '7px', borderRadius: '50%', background: C.accent, flex: '0 0 auto' }
2952
+ : { width: '7px', height: '7px', borderRadius: '50%', border: '1.5px solid ' + C.dim, boxSizing: 'border-box', flex: '0 0 auto' },
2953
+ }),
2954
+ h('span', null, (enabled ? t('enabled') : t('disabled')).replace(/^[●○]\s*/, '')),
2955
+ ),
2956
+ addMenu && h('div', {
2957
+ style: { ...S.addMenu, left: addMenu.sx + 'px', top: addMenu.sy + 'px' },
2958
+ onMouseDown: (e) => e.stopPropagation(),
2959
+ },
2960
+ h('div', { style: S.addMenuHead }, t('addMenuTitle')),
2961
+ h('div', {
2962
+ style: S.addMenuRow,
2963
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
2964
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
2965
+ onClick: () => addNode('agent', { x: addMenu.wx, y: addMenu.wy }),
2966
+ }, h('span', null, t('addAgent')), h('span', { style: S.addMenuHint }, '1')),
2967
+ h('div', {
2968
+ style: S.addMenuRow,
2969
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
2970
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
2971
+ onClick: () => addNode('lead', { x: addMenu.wx, y: addMenu.wy }),
2972
+ }, h('span', null, t('addLead')), h('span', { style: S.addMenuHint }, '2')),
2973
+ ),
2974
+ h('div', {
2975
+ ref: canvasElRef,
2976
+ style: {
2977
+ ...S.canvas,
2978
+ cursor: panning ? 'grabbing' : (spaceHeld ? 'grab' : undefined),
2979
+ },
2980
+ onMouseDown: onCanvasDown,
2981
+ },
1989
2982
  h('div', {
1990
2983
  ref: contentRef,
1991
2984
  style: {
@@ -1995,6 +2988,15 @@ window.__ModuleLoader__.load({
1995
2988
  },
1996
2989
  },
1997
2990
  h('svg', { width: contentW, height: contentH, style: { position: 'absolute', left: 0, top: 0, pointerEvents: 'none', overflow: 'visible' } },
2991
+ fxLevel === 'vivid' && h('defs', null,
2992
+ h('filter', { id: 'dsh-wc-glow', x: '-30%', y: '-30%', width: '160%', height: '160%' },
2993
+ h('feGaussianBlur', { stdDeviation: '2.2', result: 'blur' }),
2994
+ h('feMerge', null,
2995
+ h('feMergeNode', { in: 'blur' }),
2996
+ h('feMergeNode', { in: 'SourceGraphic' }),
2997
+ ),
2998
+ ),
2999
+ ),
1998
3000
  h('g', null, edgeEls),
1999
3001
  cutPath.length > 1 && h('polyline', {
2000
3002
  points: cutPath.map((pt) => (pt.x + WORLD_PAD) + ',' + (pt.y + WORLD_PAD)).join(' '),
@@ -2034,35 +3036,106 @@ window.__ModuleLoader__.load({
2034
3036
  }),
2035
3037
  );
2036
3038
  const isOrphan = node.id !== 'lead' && !reachableIds.has(node.id);
3039
+ const isSelected = selectedSet.has(node.id);
3040
+ const nodeStatus = enabled ? statusById[node.id] : undefined;
3041
+ const isLeadReady = leadReadyIds.has(node.id);
3042
+ const isRunning = !isLeadKind && nodeStatus === 'running';
3043
+ const isDone = !isLeadKind && nodeStatus === 'done';
3044
+ const isFailed = !isLeadKind && nodeStatus === 'failed';
3045
+ const isPulsing = (isRunning || isLeadReady) && fxLevel !== 'minimal';
3046
+ const nodeClass = 'dsh-wc-node'
3047
+ + (isPulsing ? (fxLevel === 'vivid' ? ' dsh-wc-running-vivid' : ' dsh-wc-running-std') : '');
3048
+ const stateStyle = isSelected
3049
+ ? S.nodeSel
3050
+ : isRunning || isLeadReady
3051
+ ? { border: '1.5px solid #2f81f7' }
3052
+ : isFailed
3053
+ ? { border: '1.5px solid rgba(229,83,75,0.8)', boxShadow: '0 0 12px rgba(229,83,75,0.18)' }
3054
+ : isDone
3055
+ ? { border: '1px solid rgba(63,185,80,0.55)' }
3056
+ : null;
3057
+ const topBarBg = (isRunning || isLeadReady) && fxLevel === 'vivid'
3058
+ ? (isLeadKind
3059
+ ? 'linear-gradient(90deg, #2f81f7 0%, #79c0ff 50%, #2f81f7 100%)'
3060
+ : 'linear-gradient(90deg, #2f81f7 0%, #58d580 50%, #2f81f7 100%)')
3061
+ : (isFailed ? '#e5534b' : (isLeadKind ? '#2f81f7' : '#3fb950'));
2037
3062
  return h('div', {
2038
3063
  key: node.id,
2039
3064
  'data-node': node.id,
2040
- style: selectedIds.includes(node.id)
2041
- ? { ...S.node, left: node.x + WORLD_PAD, top: node.y + WORLD_PAD, ...(isLeadKind ? S.leadNode : null), ...(isOrphan ? S.orphanNode : null), ...S.nodeSel }
2042
- : { ...S.node, left: node.x + WORLD_PAD, top: node.y + WORLD_PAD, ...(isLeadKind ? S.leadNode : null), ...(isOrphan ? S.orphanNode : null) },
3065
+ className: nodeClass,
3066
+ style: {
3067
+ ...S.node,
3068
+ left: node.x + WORLD_PAD,
3069
+ top: node.y + WORLD_PAD,
3070
+ ...(isLeadKind ? S.leadNode : null),
3071
+ ...(isOrphan ? S.orphanNode : null),
3072
+ ...(stateStyle || null),
3073
+ },
2043
3074
  title: isOrphan ? t('orphanTip') : undefined,
2044
3075
  onMouseDown: (e) => onNodeDown(e, node.id),
2045
3076
  },
2046
3077
  h('div', {
3078
+ className: (isRunning || isLeadReady) && fxLevel === 'vivid' ? 'dsh-wc-topbar-vivid' : undefined,
2047
3079
  style: {
2048
3080
  ...S.topBar,
2049
- background: isLeadKind ? '#2f81f7' : '#3fb950',
3081
+ background: topBarBg,
2050
3082
  },
2051
3083
  }),
2052
- enabled && h('div', {
2053
- style: {
2054
- ...S.statusChip,
2055
- color: isLeadKind ? C.dim
2056
- : statusById[node.id] === 'running' ? '#2f81f7'
2057
- : statusById[node.id] === 'failed' ? '#e5534b'
2058
- : statusById[node.id] === 'done' ? '#3fb950' : C.dim,
2059
- },
2060
- title: isLeadKind ? t('tipLead') : (isOrphan ? t('tipOrphan') : t('tipStatus')),
2061
- }, isOrphan ? t('stOrphan')
2062
- : isLeadKind ? t('stLead')
2063
- : statusById[node.id] === 'running' ? t('stRunning')
2064
- : statusById[node.id] === 'failed' ? t('stFailed')
2065
- : statusById[node.id] === 'done' ? t('stDone') : t('stPending')),
3084
+ h('div', { style: S.nodeHeader }),
3085
+ h('div', { style: S.bandDivider }),
3086
+ (() => {
3087
+ const latestRun = !isLeadKind ? runsById[node.id] : null;
3088
+ const statusColor = isLeadReady ? '#2f81f7'
3089
+ : isLeadKind ? C.dim
3090
+ : nodeStatus === 'running' ? '#2f81f7'
3091
+ : nodeStatus === 'failed' ? '#e5534b'
3092
+ : nodeStatus === 'done' ? '#3fb950' : C.dim;
3093
+ const statusTint = isLeadReady || nodeStatus === 'running'
3094
+ ? 'rgba(47,129,247,0.14)'
3095
+ : nodeStatus === 'failed'
3096
+ ? 'rgba(229,83,75,0.14)'
3097
+ : nodeStatus === 'done'
3098
+ ? 'rgba(63,185,80,0.14)'
3099
+ : 'transparent';
3100
+ const statusLabel = isOrphan ? t('stOrphan')
3101
+ : isLeadReady ? t('stLeadReady')
3102
+ : isLeadKind ? t('stLead')
3103
+ : nodeStatus === 'running' ? t('stRunning')
3104
+ : nodeStatus === 'failed' ? t('stFailed')
3105
+ : nodeStatus === 'done' ? t('stDone') : t('stPending');
3106
+ const glyph = nodeStatus === 'running'
3107
+ ? h('span', {
3108
+ className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
3109
+ style: { width: '6px', height: '6px', borderRadius: '50%', background: statusColor, flex: '0 0 auto' },
3110
+ })
3111
+ : isLeadReady ? h('span', { className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined }, '⏸')
3112
+ : nodeStatus === 'done' ? '✓'
3113
+ : nodeStatus === 'failed' ? '✕' : null;
3114
+ if (latestRun) {
3115
+ const label = enabled ? statusLabel : t('openChat');
3116
+ const color = enabled ? statusColor : C.accent;
3117
+ const bg = enabled && statusTint !== 'transparent' ? statusTint : C.elevated;
3118
+ return h('button', {
3119
+ type: 'button',
3120
+ style: { ...S.statusBtn, color, background: bg, borderColor: color === C.dim ? C.border : color },
3121
+ title: t('tipOpenRun'),
3122
+ onMouseDown: (e) => e.stopPropagation(),
3123
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3124
+ onMouseLeave: (e) => { e.currentTarget.style.background = bg; },
3125
+ onClick: (e) => { e.stopPropagation(); openNodeSession(node); },
3126
+ }, enabled ? glyph : null, label, ' ↗');
3127
+ }
3128
+ if (!enabled) return null;
3129
+ return h('div', {
3130
+ style: {
3131
+ ...S.statusChip,
3132
+ color: statusColor,
3133
+ background: statusTint,
3134
+ border: statusTint !== 'transparent' ? ('1px solid ' + statusColor) : 'none',
3135
+ },
3136
+ title: isLeadReady ? t('tipLeadReady') : (isLeadKind ? t('tipLead') : (isOrphan ? t('tipOrphan') : t('tipStatus'))),
3137
+ }, glyph, statusLabel);
3138
+ })(),
2066
3139
  isEntry
2067
3140
  ? h('div', { style: S.titleReadonly }, t('leadThis'))
2068
3141
  : h('input', {
@@ -2098,27 +3171,27 @@ window.__ModuleLoader__.load({
2098
3171
  )
2099
3172
  : h(React.Fragment, null,
2100
3173
  h('div', { style: S.fieldModel },
2101
- h('span', { style: S.fieldLabel }, t('model')),
3174
+ h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('model')),
2102
3175
  modelControl(node),
2103
3176
  ),
2104
3177
  h('div', { style: S.fieldReason },
2105
- h('span', { style: S.fieldLabel }, t('reason')),
3178
+ h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('reason')),
2106
3179
  reasoningControl(node),
2107
3180
  ),
2108
3181
  h('div', { style: S.fieldScope },
2109
- h('span', { style: S.fieldLabel }, t('scope')),
3182
+ h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('scope')),
2110
3183
  scopeToggle(node),
2111
3184
  ),
2112
3185
  h('div', { style: S.fieldFallback },
2113
- h('span', { style: S.fieldLabel }, t('fallbackModel')),
3186
+ h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('fallbackModel')),
2114
3187
  fallbackControl(node),
2115
3188
  ),
2116
3189
  h('div', { style: S.fieldMemory },
2117
- h('span', { style: S.fieldLabel }, t('memory')),
3190
+ h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('memory')),
2118
3191
  memoryToggle(node),
2119
3192
  ),
2120
3193
  h('div', { style: S.fieldRole },
2121
- h('span', { style: S.fieldLabel }, t('role')),
3194
+ h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('role')),
2122
3195
  h('button', {
2123
3196
  style: S.selectBtn,
2124
3197
  type: 'button',
@@ -2154,6 +3227,7 @@ window.__ModuleLoader__.load({
2154
3227
  }),
2155
3228
  ),
2156
3229
  ),
3230
+ ),
2157
3231
  );
2158
3232
  }
2159
3233
 
@@ -2186,7 +3260,7 @@ window.__ModuleLoader__.load({
2186
3260
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
2187
3261
  }
2188
3262
  },
2189
- __test: { topoOrder, buildWorkflowScript, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, distanceToEdge, edgeCurve },
3263
+ __test: { topoOrder, wouldCycle, layoutGraph, builtinTemplates, nextEffectLevel, zoomAroundPoint, scrubZoom, buildWorkflowScript, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, distanceToEdge, edgeCurve },
2190
3264
  };
2191
3265
  },
2192
3266
  });