dsh-workflow-canvas 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -37,6 +37,8 @@ window.__ModuleLoader__.load({
37
37
  const PORT = 12;
38
38
  const SOCKET_BAND_TOP = 176;
39
39
  const ROW_H = 18;
40
+ const COND_ROW_H = 20;
41
+ const BRANCH_COLORS = ['#3fb950', '#e5534b', '#2f81f7', '#d29922', '#a371f7', '#39c5cf', '#f778ba', '#f0883e'];
40
42
  const CONTENT_W = 2400;
41
43
  const CONTENT_H = 1600;
42
44
  /** World origin offset: keeps negative node coordinates inside the scroll area. */
@@ -101,13 +103,29 @@ window.__ModuleLoader__.load({
101
103
  const LANG_KEY = STORAGE_PREFIX + 'lang';
102
104
  const I18N = {
103
105
  zh: {
104
- addAgent: '+ 子代理', addLead: '+ Lead', undo: '↶ 撤销', sync: '↥ 同步',
106
+ addAgent: '+ 子代理', addLead: '+ Lead', addCond: '+ 条件', undo: '↶ 撤销', sync: '↥ 同步',
105
107
  enabled: '● 已启用', disabled: '○ 已禁用', presetName: '预设名', save: '☆ 保存',
106
108
  presets: '☰ 预设', unsaved: '有未同步改动', synced: '已同步',
107
109
  pickModel: '选择模型', defaultEffort: '默认',
108
110
  leadThis: 'Lead(本对话)',
109
- tipSocketOut: '拖出可断开 / 拖入可连接',
111
+ tipSocketOut: '通用输入口(接收 prompt / structured / session / 条件分支);拖出可断开最近一条连线',
110
112
  tipSocketIn: '从这里拖出连线 / 也可以把输入口拖到这里',
113
+ tipCondTrue: '条件满足(pass=true)时走这条分支,连到任意下游节点左侧入口',
114
+ tipCondFalse: '条件不满足(pass=false)时走这条分支,连到任意下游节点左侧入口',
115
+ tipBranchOut: '命中该分支时走这条连线,拖到任意下游节点左侧入口',
116
+ branchTrue: '是',
117
+ branchFalse: '否',
118
+ addBranch: '+ 分支',
119
+ branchPh: '分支名',
120
+ delBranchTip: '删除该分支(至少保留 2 路)',
121
+ matchSingle: '单选',
122
+ matchMulti: '多选',
123
+ tipMatchMode: '单选:最多命中 1 条最匹配分支(全不满足则跳过中间分支并直达最近 Lead);多选:所有满足条件的分支同时并行执行,全不满足则直达最近 Lead',
124
+ tipExpandEdit: '展开大输入框编辑',
125
+ tipExpandBranch: '展开大输入框编辑该分支的条件',
126
+ branchEditTitle: '分支条件',
127
+ condLabel: '条件',
128
+ condPh: '判断条件或分流规则:例如成功走「是」,失败走「否」',
111
129
  delNodeTip: '删除节点(可用 ↶ 撤销 找回)',
112
130
  deletedNode: '节点已删除,可点「撤销」找回',
113
131
  orphanTip: '未连线:运行时会被跳过',
@@ -127,7 +145,10 @@ window.__ModuleLoader__.load({
127
145
  fallbackModel: '备用',
128
146
  stPending: '未执行', stRunning: '进行中', stDone: '已完成', stFailed: '失败',
129
147
  stOrphan: '未连线', stLead: '由对话执行', stLeadReady: '待拍板',
130
- presetEmpty: '还没有保存过预设', del: '删除这个预设',
148
+ presetEmpty: '保存后可在任意新对话一键载入', del: '删除这个预设',
149
+ presetSaveTitle: '保存当前画布(可在新会话一键载入)',
150
+ presetNamePh: '起个名字后回车保存…',
151
+ myPresets: '我的预设(跨会话复用)',
131
152
  needName: '请先给预设起个名字', duplicate: '已存在,请换一个名字',
132
153
  savedPreset: '已保存预设', saveFailed: '保存失败(存储不可用)',
133
154
  loadedPreset: '已载入预设', invalidPreset: '预设内容无效', deletedPreset: '已删除预设',
@@ -153,18 +174,18 @@ window.__ModuleLoader__.load({
153
174
  tipToggle: '启用/禁用此画布(启用后我才能执行它)',
154
175
  helpBody: [
155
176
  '1. 在入口 Lead 里写「本次任务」,这是整张图的总目标。',
156
- '2. 点「+ 子代理」加节点,从右侧输出口拖到另一个节点左侧输入口即可连线。',
157
- '3. 连线有三种:prompt 传文本,structured 传 JSON,session 让下游接着上游的会话跑。',
158
- '4. 端口颜色即类型,只能同色相连;拖已连接的左口可以断开。',
159
- '5. 每个节点可设模型、推理强度、能力范围、备用模型、是否记忆。',
177
+ '2. 点「+ 子代理 / + Lead / + 条件」加节点,从右侧输出口拖到另一个节点左侧输入口即可连线。',
178
+ '3. 输出口决定连线类型:prompt(灰,纯文本)、structured(蓝,JSON)、session(紫,复用上游会话);条件节点支持多路分支(单选 switch/case 或多选并行,全不满足时跳过中间分支直达最近 Lead)。',
179
+ '4. 节点左侧为统一通用输入口,可直接接收任意颜色的连线;拖已连接的左口可断开最近一条连线。',
180
+ '5. 每个节点可设模型、推理强度、能力范围、备用模型、是否记忆;复杂任务/分工/条件可点 ⤢ 展开大框编辑。',
160
181
  '6. 连好后点「● 已启用」,然后对对话说「跑一次」,由我调用执行。',
161
182
  '7. 遇到 Lead 节点会暂停,我做完再把结果交回去继续。',
162
183
  '8. 没连线的节点显示为虚线,运行时会被跳过。',
163
184
  '9. 右键按住划过一条连线可以切断;可在「⋯」里关掉这个手势。',
164
- '10. 预设名 + ☆ 保存 可以把整张图存下来,新对话里从「☰ 预设」载入。',
185
+ '10. 点右上角「☰ 预设」顶部即可保存当前画布,开新对话时一键载入跨会话复用。',
165
186
  '11. 你可以直接让我改画布:说「把那三个节点的分工改成…」,我会就地修改,不动你摆的位置。',
166
187
  '12. session 线连到 Lead 时,我会在暂停那步拿到那个子代理的会话,可以继续追问它。',
167
- '13. 按住鼠标中键(或空格 + 左键)拖动画布平移;点击子代理节点右下角状态可直达它的对话记录。',
188
+ '13. 按住鼠标中键(或空格 + 左键)拖动画布平移;点击子代理节点左下角状态可直达它的对话记录。',
168
189
  '14. 快捷键:Shift+A 在光标处新建节点,Ctrl+D 复制选中节点,Delete 批量删除,Ctrl+Z 撤销,Esc 关闭弹窗。',
169
190
  ].join('\n'),
170
191
  openChat: '会话',
@@ -180,10 +201,23 @@ window.__ModuleLoader__.load({
180
201
  cycleBlocked: '不能形成环,已阻止连线',
181
202
  leadToLeadBlocked: 'Lead 节点不能直接连到另一个 Lead,请在中间放入子代理',
182
203
  builtinTemplates: '内置示例模板',
183
- myPresets: '我的预设',
184
204
  duplicatedNodes: '已复制节点',
185
205
  deletedNodes: '已删除节点(可用 ↶ 撤销)',
186
206
  addMenuTitle: '新建节点 (Shift+A)',
207
+ addMenuLinkTitle: '拖线新建并自动连线',
208
+ stPruned: '已跳过',
209
+ tipPruned: '未被条件分支命中,已跳过执行(不消耗额度)',
210
+ verdictReasonTitle: '条件判决理由',
211
+ verdictMatched: '命中分支:',
212
+ verdictFallback: '已跳过中间分支 → 转交 Lead:',
213
+ verdictNoReason: '(裁判未附额外说明)',
214
+ tipVerdictChip: '点击查看完整判断理由',
215
+ runBtn: '▶ 运行',
216
+ runBtnRunning: '进行中…',
217
+ runBtnWaiting: '⏸ 等待决策',
218
+ runStarted: '已向当前会话发起画布执行',
219
+ runFailed: '发起运行失败',
220
+ runSendUnavailable: '当前宿主不支持从画布直接发起对话,请在聊天框发送消息启动',
187
221
  fxLabel: '视觉效果',
188
222
  fxMinimal: '极简',
189
223
  fxStandard: '标准',
@@ -199,8 +233,8 @@ window.__ModuleLoader__.load({
199
233
  importNone: '剪贴板里没有可识别的画布数据',
200
234
  importBad: '画布数据格式不对',
201
235
  tipSync: '把当前画布同步给 Host(会在对话里留一条同步记录)',
202
- tipUndo: '撤销上一步结构改动', tipSave: '把当前画布保存为预设',
203
- tipPresets: '载入已保存的预设', tipModel: '推理等级(默认 = 该模型声明的 defaultEffort)',
236
+ tipUndo: '撤销上一步结构改动', tipSave: '把当前画布保存为预设(可在新会话载入)',
237
+ tipPresets: '保存当前画布、跨会话复用,或载入内置模板', tipModel: '推理等级(默认 = 该模型声明的 defaultEffort)',
204
238
  tipMemory: '记忆:复用这个节点上一次的会话(跨运行及重启后可恢复)',
205
239
  memLatest: '最新',
206
240
  memLatestOpt: '自动(最新记忆)',
@@ -213,13 +247,29 @@ window.__ModuleLoader__.load({
213
247
  lang: 'ZH',
214
248
  },
215
249
  en: {
216
- addAgent: '+ Subagent', addLead: '+ Lead', undo: '↶ Undo', sync: '↥ Sync',
250
+ addAgent: '+ Subagent', addLead: '+ Lead', addCond: '+ Condition', undo: '↶ Undo', sync: '↥ Sync',
217
251
  enabled: '● ON', disabled: '○ OFF', presetName: 'Preset name', save: '☆ Save',
218
252
  presets: '☰ Presets', unsaved: 'Unsaved changes', synced: 'Synced',
219
253
  pickModel: 'Pick a model', defaultEffort: 'default',
220
254
  leadThis: 'Lead (this chat)',
221
- tipSocketOut: 'Drag to detach / drop to connect',
255
+ tipSocketOut: 'Universal input (accepts prompt / structured / session / branch); drag away to detach latest link',
222
256
  tipSocketIn: 'Drag out to link, or drop an input here',
257
+ tipCondTrue: 'Runs when condition passes (pass=true); connect to any downstream input',
258
+ tipCondFalse: 'Runs when condition fails (pass=false); connect to any downstream input',
259
+ tipBranchOut: 'Runs when this branch matches; connect to any downstream input',
260
+ branchTrue: 'Yes',
261
+ branchFalse: 'No',
262
+ addBranch: '+ Case',
263
+ branchPh: 'Branch name',
264
+ delBranchTip: 'Remove this branch (minimum 2)',
265
+ matchSingle: 'Single',
266
+ matchMulti: 'Multi',
267
+ tipMatchMode: 'Single: pick at most 1 best-matching branch (if none match, skip branches and jump to nearest Lead). Multi: run all matching branches in parallel (if none match, jump to nearest Lead).',
268
+ tipExpandEdit: 'Expand larger editor',
269
+ tipExpandBranch: 'Expand larger editor for this branch condition',
270
+ branchEditTitle: 'Branch condition',
271
+ condLabel: 'Condition',
272
+ condPh: 'Condition or switch rule, e.g. pass vs minor fix vs rewrite',
223
273
  delNodeTip: 'Delete this node (undo with ↶)',
224
274
  deletedNode: 'Node deleted, use Undo to restore it',
225
275
  orphanTip: 'Unlinked: skipped when the canvas runs',
@@ -239,7 +289,10 @@ window.__ModuleLoader__.load({
239
289
  fallbackModel: 'Fallback',
240
290
  stPending: 'Pending', stRunning: 'Running', stDone: 'Done', stFailed: 'Failed',
241
291
  stOrphan: 'Unlinked', stLead: 'Runs in chat', stLeadReady: 'Ready',
242
- presetEmpty: 'No presets saved yet', del: 'Delete this preset',
292
+ presetEmpty: 'Saved canvases appear here in every new chat', del: 'Delete this preset',
293
+ presetSaveTitle: 'Save current canvas (reuse in any new chat)',
294
+ presetNamePh: 'Name this canvas…',
295
+ myPresets: 'Saved presets (all sessions)',
243
296
  needName: 'Name the preset first', duplicate: 'already exists, pick another name',
244
297
  savedPreset: 'Saved preset', saveFailed: 'Save failed (storage unavailable)',
245
298
  loadedPreset: 'Loaded preset', invalidPreset: 'Preset content is invalid', deletedPreset: 'Deleted preset',
@@ -265,18 +318,18 @@ window.__ModuleLoader__.load({
265
318
  tipToggle: 'Enable or disable this canvas (I can only run it while enabled)',
266
319
  helpBody: [
267
320
  '1. Write the overall task in the entry Lead node.',
268
- '2. Add nodes with the + buttons, then drag from a right socket to a left socket.',
269
- '3. Links carry text (prompt), JSON (structured), or continue the upstream session (session).',
270
- '4. Socket colour is the type; only matching types connect. Drag a connected input to detach.',
271
- '5. Each node sets model, reasoning, capability scope, fallback model and memory.',
321
+ '2. Add nodes with + Subagent / + Lead / + Condition, then drag from a right socket to a left socket.',
322
+ '3. Output sockets choose channel type: prompt (grey text), structured (blue JSON), session (purple warm session), or multi-way condition branches (single switch/case or parallel multi-match; jumps to nearest Lead if none match).',
323
+ '4. Every node has one universal left input that accepts any incoming wire; drag a connected input away to detach the latest wire.',
324
+ '5. Each node sets model, reasoning, capability scope, fallback model and memory; click ⤢ to expand a larger editor for long text.',
272
325
  '6. Press ● ON, then ask in chat to run the canvas.',
273
326
  '7. The run pauses at every Lead node so the conversation can do that step.',
274
327
  '8. Unlinked nodes are dashed and skipped at run time.',
275
328
  '9. Hold the right button and sweep across a link to cut it; turn the gesture off under ⋯.',
276
- '10. Name a preset and press ☆ Save to keep the canvas for other sessions.',
329
+ '10. Open ☰ Presets to save the current canvas at the top and load it in any new chat.',
277
330
  '11. You can ask me to edit the canvas; I patch it in place and keep your layout.',
278
331
  '12. A session link into a Lead step hands me that child agent, so I can follow up with it.',
279
- '13. Hold the middle mouse button (or Space + drag) to pan; click a subagent status badge to open its chat.',
332
+ '13. Hold the middle mouse button (or Space + drag) to pan; click a subagent status badge at the bottom-left to open its chat.',
280
333
  '14. Shortcuts: Shift+A adds a node at cursor, Ctrl+D duplicates, Delete removes selected, Ctrl+Z undoes, Esc closes popups.',
281
334
  ].join('\n'),
282
335
  openChat: 'Chat',
@@ -292,10 +345,23 @@ window.__ModuleLoader__.load({
292
345
  cycleBlocked: 'Cannot create a cycle',
293
346
  leadToLeadBlocked: 'Cannot link a Lead directly to another Lead; place a subagent in between',
294
347
  builtinTemplates: 'Starter templates',
295
- myPresets: 'Saved presets',
296
348
  duplicatedNodes: 'Duplicated nodes',
297
349
  deletedNodes: 'Deleted nodes (use Undo to restore)',
298
350
  addMenuTitle: 'Add node (Shift+A)',
351
+ addMenuLinkTitle: 'Create & connect node',
352
+ stPruned: 'Skipped',
353
+ tipPruned: 'Skipped because no matching condition branch routed here (0 tokens spent)',
354
+ verdictReasonTitle: 'Branch verdict',
355
+ verdictMatched: 'Matched: ',
356
+ verdictFallback: 'Skipped branches → Lead: ',
357
+ verdictNoReason: '(No extra reason provided)',
358
+ tipVerdictChip: 'Click to inspect verdict reason',
359
+ runBtn: '▶ Run',
360
+ runBtnRunning: 'Running…',
361
+ runBtnWaiting: '⏸ Awaiting Lead',
362
+ runStarted: 'Workflow run queued in this chat',
363
+ runFailed: 'Failed to start run',
364
+ runSendUnavailable: 'Direct canvas launch is unavailable in this host; send a message in chat to start',
299
365
  fxLabel: 'Visual effects',
300
366
  fxMinimal: 'Minimal',
301
367
  fxStandard: 'Standard',
@@ -311,8 +377,8 @@ window.__ModuleLoader__.load({
311
377
  importNone: 'No canvas data found in the clipboard',
312
378
  importBad: 'Canvas data is malformed',
313
379
  tipSync: 'Publish this canvas to the host (leaves one sync record in the chat)',
314
- tipUndo: 'Undo the last structural change', tipSave: 'Save this canvas as a preset',
315
- tipPresets: 'Load a saved preset', tipModel: 'Reasoning effort (default = the model\'s defaultEffort)',
380
+ tipUndo: 'Undo the last structural change', tipSave: 'Save this canvas as a preset (reusable in new chats)',
381
+ tipPresets: 'Save this canvas for new chats, or load a preset / starter template', tipModel: 'Reasoning effort (default = the model\'s defaultEffort)',
316
382
  tipMemory: 'Memory: reuse this node\'s previous session (persisted across runs and restarts)',
317
383
  memLatest: 'Latest',
318
384
  memLatestOpt: 'Auto (latest)',
@@ -428,6 +494,11 @@ window.__ModuleLoader__.load({
428
494
  padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
429
495
  color: C.text, whiteSpace: 'nowrap',
430
496
  },
497
+ addMenuRowDisabled: {
498
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px',
499
+ padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'not-allowed',
500
+ color: C.dim, opacity: 0.45, whiteSpace: 'nowrap',
501
+ },
431
502
  addMenuHint: { fontSize: '10px', color: C.dim },
432
503
  helpOverlay: {
433
504
  position: 'absolute', inset: '0', background: 'rgba(0,0,0,0.45)', zIndex: 90,
@@ -443,16 +514,22 @@ window.__ModuleLoader__.load({
443
514
  helpBody: { fontSize: '11px', lineHeight: '17px', color: C.dim },
444
515
  helpLine: { whiteSpace: 'pre-wrap' },
445
516
  presetBar: {
446
- marginLeft: 'auto', display: 'flex', flexDirection: 'column', alignItems: 'flex-end',
447
- gap: '3px', position: 'relative', flex: '0 0 auto',
517
+ marginLeft: 'auto', display: 'flex', alignItems: 'center',
518
+ gap: '6px', position: 'relative', flex: '0 0 auto',
448
519
  },
449
520
  presetRowTop: { display: 'flex', alignItems: 'center', gap: '5px' },
450
521
  presetMenu: {
451
- position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '190px',
452
- maxHeight: '260px', overflowY: 'auto', background: C.elevated,
453
- border: '1px solid ' + C.border, borderRadius: '6px', zIndex: 60, padding: '4px',
522
+ position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '236px',
523
+ maxHeight: '320px', overflowY: 'auto', background: C.elevated,
524
+ border: '1px solid ' + C.border, borderRadius: '6px', zIndex: 60, padding: '6px',
454
525
  boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
455
526
  },
527
+ presetSaveBox: {
528
+ padding: '2px 2px 8px', marginBottom: '6px',
529
+ borderBottom: '1px solid ' + C.border,
530
+ },
531
+ presetSaveTitle: { fontSize: '10px', color: C.dim, marginBottom: '5px' },
532
+ presetSaveRow: { display: 'flex', alignItems: 'center', gap: '5px' },
456
533
  presetRow: {
457
534
  display: 'flex', alignItems: 'center', gap: '6px', padding: '5px 6px',
458
535
  borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
@@ -463,7 +540,7 @@ window.__ModuleLoader__.load({
463
540
  background: 'transparent', color: '#e5534b', fontSize: '11px', cursor: 'pointer',
464
541
  },
465
542
  presetInput: {
466
- width: '92px', padding: '3px 6px', borderRadius: '5px', border: '1px solid ' + C.border,
543
+ flex: '1 1 auto', minWidth: '0', padding: '4px 7px', borderRadius: '5px', border: '1px solid ' + C.border,
467
544
  background: C.base, color: C.text, fontSize: '11px', outline: 'none', userSelect: 'text',
468
545
  },
469
546
  presetEmpty: { padding: '6px', fontSize: '10px', color: C.dim },
@@ -507,20 +584,20 @@ window.__ModuleLoader__.load({
507
584
  borderRadius: '10px 10px 0 0', zIndex: 2, pointerEvents: 'none',
508
585
  },
509
586
  statusChip: {
510
- position: 'absolute', right: '12px', bottom: '4px', fontSize: '10px', lineHeight: '14px',
511
- padding: '1px 5px', borderRadius: '999px',
587
+ position: 'absolute', left: '10px', bottom: '5px', fontSize: '10px', lineHeight: '14px',
588
+ padding: '1px 6px', borderRadius: '999px',
512
589
  color: C.dim, pointerEvents: 'none', zIndex: 3, whiteSpace: 'nowrap',
513
590
  display: 'inline-flex', alignItems: 'center', gap: '3px',
514
591
  },
515
592
  warnChip: {
516
- position: 'absolute', left: '12px', bottom: '4px', fontSize: '9px', lineHeight: '13px',
517
- padding: '1px 5px', borderRadius: '999px',
593
+ position: 'absolute', left: '10px', bottom: '5px', fontSize: '9px', lineHeight: '13px',
594
+ padding: '1px 6px', borderRadius: '999px',
518
595
  color: '#d29922', background: 'rgba(210,153,34,0.14)', border: '1px solid rgba(210,153,34,0.55)',
519
596
  pointerEvents: 'auto', zIndex: 5, whiteSpace: 'nowrap',
520
597
  display: 'inline-flex', alignItems: 'center', gap: '2px',
521
598
  },
522
599
  statusBtn: {
523
- position: 'absolute', right: '12px', bottom: '3px', fontSize: '10px', lineHeight: '14px',
600
+ position: 'absolute', left: '10px', bottom: '4px', fontSize: '10px', lineHeight: '14px',
524
601
  padding: '1px 6px', borderRadius: '999px', border: '1px solid ' + C.border,
525
602
  background: C.elevated, color: C.text, cursor: 'pointer', pointerEvents: 'auto',
526
603
  zIndex: 7, whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: '3px',
@@ -571,23 +648,72 @@ window.__ModuleLoader__.load({
571
648
  outline: 'none', userSelect: 'text',
572
649
  },
573
650
  rolePopover: {
574
- position: 'absolute', left: '100%', top: '0', marginLeft: '8px', width: '230px',
651
+ position: 'absolute', left: '100%', top: '0', marginLeft: '8px', width: '280px',
575
652
  background: C.elevated, border: '1px solid ' + C.border, borderRadius: '8px',
576
653
  boxShadow: '0 10px 26px rgba(0,0,0,0.45)', padding: '8px', zIndex: 70,
577
654
  },
578
655
  roleArea: {
579
- width: '100%', height: '96px', boxSizing: 'border-box', resize: 'none',
580
- background: C.base, color: C.text, fontSize: '11px', lineHeight: '15px',
581
- border: '1px solid ' + C.border, borderRadius: '5px', padding: '5px 6px',
656
+ width: '100%', height: '150px', boxSizing: 'border-box', resize: 'vertical',
657
+ background: C.base, color: C.text, fontSize: '11px', lineHeight: '16px',
658
+ border: '1px solid ' + C.border, borderRadius: '5px', padding: '6px 7px',
582
659
  outline: 'none', userSelect: 'text',
583
660
  },
584
- leadLabel: { position: 'absolute', left: '10px', right: '10px', top: '34px', height: '16px', display: 'flex', alignItems: 'center' },
661
+ leadLabel: {
662
+ position: 'absolute', left: '10px', right: '10px', top: '34px', height: '16px',
663
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
664
+ },
585
665
  task: {
586
666
  position: 'absolute', left: '10px', right: '10px', top: '51px', height: '116px',
587
667
  padding: '4px 6px', borderRadius: '5px', border: '1px solid ' + C.border,
588
668
  background: C.base, color: C.text, fontSize: '11px', resize: 'none', outline: 'none',
589
669
  lineHeight: '14px', boxSizing: 'border-box', userSelect: 'text',
590
670
  },
671
+ condLabelRow: {
672
+ position: 'absolute', left: '10px', right: '10px', top: '103px', height: '16px',
673
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '4px',
674
+ },
675
+ condBtnGroup: { display: 'inline-flex', alignItems: 'center', gap: '4px' },
676
+ condAddBtn: {
677
+ padding: '0 5px', height: '16px', borderRadius: '4px',
678
+ border: '1px solid ' + C.border, background: C.base, color: C.dim,
679
+ fontSize: '9px', lineHeight: '14px', cursor: 'pointer', outline: 'none',
680
+ },
681
+ condModeBtnOn: {
682
+ padding: '0 5px', height: '16px', borderRadius: '4px',
683
+ border: '1px solid ' + C.accent, background: C.hover, color: C.accent,
684
+ fontSize: '9px', lineHeight: '14px', cursor: 'pointer', outline: 'none',
685
+ },
686
+ condArea: {
687
+ position: 'absolute', left: '10px', right: '10px', top: '121px', height: '46px',
688
+ padding: '4px 6px', borderRadius: '5px', border: '1px solid ' + C.border,
689
+ background: C.base, color: C.text, fontSize: '11px', resize: 'none', outline: 'none',
690
+ lineHeight: '14px', boxSizing: 'border-box', userSelect: 'text',
691
+ },
692
+ condBranchRow: {
693
+ position: 'relative', height: COND_ROW_H + 'px',
694
+ display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
695
+ },
696
+ condBranchInput: {
697
+ width: '108px', height: '16px', boxSizing: 'border-box',
698
+ padding: '0 4px', borderRadius: '3px',
699
+ border: '1px solid ' + C.border, background: C.base, color: C.text,
700
+ fontSize: '10px', lineHeight: '14px', textAlign: 'right',
701
+ outline: 'none', userSelect: 'text',
702
+ },
703
+ condBranchExpand: {
704
+ width: '15px', height: '16px', padding: 0, marginRight: '2px',
705
+ border: '1px solid ' + C.border, borderRadius: '3px',
706
+ background: C.base, color: C.dim,
707
+ fontSize: '9px', lineHeight: '14px', cursor: 'pointer', flex: '0 0 auto',
708
+ },
709
+ condBranchDel: {
710
+ width: '14px', height: '16px', padding: 0, marginLeft: '2px',
711
+ border: 'none', background: 'transparent', color: C.dim,
712
+ fontSize: '11px', lineHeight: '14px', cursor: 'pointer', flex: '0 0 auto',
713
+ },
714
+ condBranchDelSpacer: {
715
+ width: '14px', height: '16px', marginLeft: '2px', flex: '0 0 auto',
716
+ },
591
717
 
592
718
  selectBtn: {
593
719
  flex: '1 1 auto', minWidth: '0', width: '100%', height: '18px', boxSizing: 'border-box',
@@ -640,6 +766,21 @@ window.__ModuleLoader__.load({
640
766
  position: 'absolute', left: '2px', top: '10px', bottom: '10px', width: '3px',
641
767
  borderRadius: '2px', zIndex: 3,
642
768
  },
769
+ verdictChip: {
770
+ position: 'absolute', left: '0', top: 'calc(100% + 5px)', maxWidth: NODE_W + 'px',
771
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
772
+ padding: '2px 8px', borderRadius: '999px', fontSize: '10px', lineHeight: '14px',
773
+ background: C.elevated, border: '1px solid ' + C.border, color: C.text,
774
+ cursor: 'pointer', userSelect: 'none', zIndex: 12,
775
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
776
+ boxShadow: '0 4px 12px rgba(0,0,0,0.32)',
777
+ },
778
+ verdictPopover: {
779
+ position: 'absolute', left: '0', top: 'calc(100% + 28px)', width: '272px',
780
+ background: C.elevated, border: '1px solid ' + C.border, borderRadius: '8px',
781
+ padding: '9px 10px', zIndex: 65, boxShadow: '0 14px 32px rgba(0,0,0,0.52)',
782
+ color: C.text, fontSize: '11px', lineHeight: '1.5', userSelect: 'text',
783
+ },
643
784
  };
644
785
 
645
786
  let hostCtx = null;
@@ -648,6 +789,158 @@ window.__ModuleLoader__.load({
648
789
  return SOCKET_BAND_TOP + i * ROW_H + ROW_H / 2;
649
790
  }
650
791
 
792
+ /**
793
+ * Determine which node kinds can legally receive a wire dragged out from `fromNode`.
794
+ * Mirrors the canvas invariant that Lead -> Lead direct links are forbidden.
795
+ */
796
+ function compatibleTargetsForWire(fromNode, _edgeType) {
797
+ const fromLead = Boolean(fromNode && fromNode.kind === 'lead');
798
+ return {
799
+ agent: true,
800
+ lead: !fromLead,
801
+ condition: true,
802
+ leadBlockedReason: fromLead ? 'leadToLeadBlocked' : '',
803
+ };
804
+ }
805
+
806
+ /** Format a compact verdict pill for a condition node decision snapshot. */
807
+ function conditionVerdictSummary(decision, lang) {
808
+ if (!decision || typeof decision !== 'object') return null;
809
+ const en = lang === 'en';
810
+ if (decision.failed) {
811
+ return {
812
+ tone: 'failed',
813
+ text: '⚠ ' + (en ? 'Judge failed' : '判定失败')
814
+ + (decision.fallbackLead ? ' → ' + decision.fallbackLead : ''),
815
+ };
816
+ }
817
+ const labels = Array.isArray(decision.branchLabels) && decision.branchLabels.length
818
+ ? decision.branchLabels
819
+ : (Array.isArray(decision.branches) ? decision.branches : []);
820
+ if (!labels.length) {
821
+ return {
822
+ tone: 'warn',
823
+ text: '⚠ ' + (en ? 'No match' : '未命中')
824
+ + (decision.fallbackLead ? ' → ' + decision.fallbackLead : ''),
825
+ };
826
+ }
827
+ return {
828
+ tone: 'ok',
829
+ text: '→ ' + labels.join(' · '),
830
+ };
831
+ }
832
+
833
+ /** Compute the Entry Lead "▶ Run" button state, label, disabled flag, and tooltip. */
834
+ function entryRunButtonState({ enabled, task, sessionRunning, waitingLead, triggering, lang }) {
835
+ const en = lang === 'en';
836
+ if (sessionRunning || triggering) {
837
+ return {
838
+ state: 'running',
839
+ disabled: true,
840
+ label: en ? 'Running…' : '进行中…',
841
+ title: en
842
+ ? 'Workflow is currently running; wait for this turn to finish'
843
+ : '工作流正在运行中,请等待本轮结束',
844
+ };
845
+ }
846
+ if (waitingLead) {
847
+ const wName = typeof waitingLead === 'object' && waitingLead && waitingLead.label
848
+ ? waitingLead.label
849
+ : '';
850
+ return {
851
+ state: 'waiting',
852
+ disabled: true,
853
+ label: en ? '⏸ Awaiting Lead' : '⏸ 等待决策',
854
+ title: en
855
+ ? 'Paused at intermediate Lead' + (wName ? ' "' + wName + '"' : '') + '; reply in chat to continue'
856
+ : '当前停在中间 Lead' + (wName ? '「' + wName + '」' : '') + ',请先在聊天室回复拍板继续',
857
+ };
858
+ }
859
+ if (!enabled) {
860
+ return {
861
+ state: 'disabled',
862
+ disabled: true,
863
+ label: en ? '▶ Run' : '▶ 运行',
864
+ title: en
865
+ ? 'Turn on ● ON in the top-left corner to enable this canvas first'
866
+ : '请先点亮左上角 ● ON 启用画布',
867
+ };
868
+ }
869
+ if (!String(task || '').trim()) {
870
+ return {
871
+ state: 'disabled',
872
+ disabled: true,
873
+ label: en ? '▶ Run' : '▶ 运行',
874
+ title: en
875
+ ? 'Fill in the Entry Lead task before running to avoid an empty run'
876
+ : '请先在入口节点填写任务内容,避免空跑',
877
+ };
878
+ }
879
+ return {
880
+ state: 'ready',
881
+ disabled: false,
882
+ label: en ? '▶ Run' : '▶ 运行',
883
+ title: en
884
+ ? 'Start the enabled workflow directly (auto-syncs unsaved edits). For retryFailed, reset, or clearing node memory, specify in chat.'
885
+ : '直接按当前画布起跑(会自动同步未保存改动)。如需断点续跑(retryFailed)、从头重跑(reset)或清理记忆节点,可在聊天中说明。',
886
+ };
887
+ }
888
+
889
+ function isCustomBranches(node) {
890
+ return Boolean(node && node.kind === 'condition' && Array.isArray(node.branches) && node.branches.length >= 2);
891
+ }
892
+
893
+ function conditionBranchesForUI(node, lang) {
894
+ if (isCustomBranches(node)) {
895
+ return node.branches.slice(0, 16).map((item, idx) => {
896
+ const id = typeof item === 'string'
897
+ ? (item.trim() || ('case_' + (idx + 1)))
898
+ : (String((item && (item.id || item.label)) || ('case_' + (idx + 1))).trim());
899
+ const label = typeof item === 'string'
900
+ ? (item.trim() || (lang === 'en' ? 'Case ' + (idx + 1) : '分支 ' + (idx + 1)))
901
+ : (item && item.label !== undefined ? String(item.label) : String((item && item.id) || ''));
902
+ return { id, label, color: BRANCH_COLORS[idx % BRANCH_COLORS.length], custom: true };
903
+ });
904
+ }
905
+ return [
906
+ { id: 'true', label: lang === 'en' ? 'Yes' : '是', color: '#3fb950', custom: false },
907
+ { id: 'false', label: lang === 'en' ? 'No' : '否', color: '#e5534b', custom: false },
908
+ ];
909
+ }
910
+
911
+ function nodeHeight(node) {
912
+ if (node && node.kind === 'condition') {
913
+ const count = isCustomBranches(node) ? Math.min(16, node.branches.length) : 2;
914
+ return Math.max(NODE_H, SOCKET_BAND_TOP + count * COND_ROW_H + 24);
915
+ }
916
+ return NODE_H;
917
+ }
918
+
919
+ function outputSocketY(fromNode, type, branch) {
920
+ const b = typeof branch === 'string' ? branch.trim() : '';
921
+ if (b || (fromNode && fromNode.kind === 'condition')) {
922
+ const list = conditionBranchesForUI(fromNode);
923
+ const idx = b ? Math.max(0, list.findIndex((x) => x.id === b)) : 0;
924
+ return SOCKET_BAND_TOP + idx * COND_ROW_H + COND_ROW_H / 2;
925
+ }
926
+ const idx = Math.max(0, SOCKET_TYPES.findIndex((t) => t.id === (type || 'prompt')));
927
+ return socketCenterY(idx);
928
+ }
929
+
930
+ function edgeColorFor(fromNode, edge) {
931
+ const b = edge && typeof edge.branch === 'string' ? edge.branch.trim() : '';
932
+ if (b) {
933
+ if (fromNode && fromNode.kind === 'condition') {
934
+ const hit = conditionBranchesForUI(fromNode).find((x) => x.id === b);
935
+ if (hit) return hit.color;
936
+ }
937
+ if (b === 'true') return '#3fb950';
938
+ if (b === 'false') return '#e5534b';
939
+ return '#2f81f7';
940
+ }
941
+ return (SOCKET_TYPES.find((sock) => sock.id === (edge && edge.type)) || SOCKET_TYPES[0]).color;
942
+ }
943
+
651
944
  function defaultNodes() {
652
945
  return [
653
946
  { id: 'lead', kind: 'lead', x: 40, y: 80, label: 'Lead', task: '', provider: '', model: '', role: '' },
@@ -687,24 +980,26 @@ window.__ModuleLoader__.load({
687
980
  return doc;
688
981
  }
689
982
 
690
- /** Control points of one link, in canvas coordinates. */
691
- function edgeCurve(from, to, type) {
692
- const idx = Math.max(0, SOCKET_TYPES.findIndex((t) => t.id === type));
693
- const y = socketCenterY(idx);
694
- const x1 = from.x + WORLD_PAD + NODE_W, y1 = from.y + WORLD_PAD + y;
695
- const x2 = to.x + WORLD_PAD, y2 = to.y + WORLD_PAD + y;
983
+ /** Control points of one link, in canvas coordinates. All inputs converge to the unified left socket (Row 0). */
984
+ function edgeCurve(from, to, typeOrEdge) {
985
+ const type = (typeOrEdge && typeof typeOrEdge === 'object') ? (typeOrEdge.type || 'prompt') : (typeOrEdge || 'prompt');
986
+ const branch = (typeOrEdge && typeof typeOrEdge === 'object') ? (typeOrEdge.branch || '') : '';
987
+ const x1 = from.x + WORLD_PAD + NODE_W;
988
+ const y1 = from.y + WORLD_PAD + outputSocketY(from, type, branch);
989
+ const x2 = to.x + WORLD_PAD;
990
+ const y2 = to.y + WORLD_PAD + socketCenterY(0);
696
991
  const dx = Math.max(40, Math.abs(x2 - x1) * 0.5);
697
992
  return { x1, y1, c1x: x1 + dx, c1y: y1, c2x: x2 - dx, c2y: y2, x2, y2 };
698
993
  }
699
994
 
700
- function edgePath(from, to, type) {
701
- const c = edgeCurve(from, to, type);
995
+ function edgePath(from, to, typeOrEdge) {
996
+ const c = edgeCurve(from, to, typeOrEdge);
702
997
  return 'M ' + c.x1 + ' ' + c.y1 + ' C ' + c.c1x + ' ' + c.c1y + ', ' + c.c2x + ' ' + c.c2y + ', ' + c.x2 + ' ' + c.y2;
703
998
  }
704
999
 
705
1000
  /** Shortest distance between a point and one link, sampled along the curve. */
706
- function distanceToEdge(point, from, to, type) {
707
- const c = edgeCurve(from, to, type);
1001
+ function distanceToEdge(point, from, to, typeOrEdge) {
1002
+ const c = edgeCurve(from, to, typeOrEdge);
708
1003
  let best = Infinity;
709
1004
  let prevX = c.x1;
710
1005
  let prevY = c.y1;
@@ -1028,6 +1323,63 @@ window.__ModuleLoader__.load({
1028
1323
  { id: 'a5', from: 'n_pick', to: 'n_exec', type: 'prompt' },
1029
1324
  { id: 'a6', from: 'n_exec', to: 'n_review', type: 'prompt' },
1030
1325
  ];
1326
+ const condNodes = [
1327
+ {
1328
+ id: 'lead', kind: 'lead', label: 'Lead', y: 0,
1329
+ task: en
1330
+ ? 'Run project tests and checks, then route automatically: if everything passes, draft release notes; if anything fails, diagnose root causes and propose a fix patch before final review.'
1331
+ : '先运行项目测试与构建自检,再根据结果自动分流:全部通过则整理发布说明;存在失败则定位根因并给出修复方案,最后由我终审。',
1332
+ provider: '', model: '', role: '',
1333
+ },
1334
+ {
1335
+ id: 'c_run', kind: 'agent', y: 0,
1336
+ label: en ? 'Run & Verify' : '执行与自检',
1337
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
1338
+ role: en
1339
+ ? 'Run tests/checks and report exact pass/fail status, error logs, and affected files.'
1340
+ : '执行测试或验证命令,如实汇报通过/失败状态、报错日志与受影响文件。',
1341
+ },
1342
+ {
1343
+ id: 'c_gate', kind: 'condition', y: 0,
1344
+ label: en ? 'Checks Passed?' : '是否通过?',
1345
+ provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false,
1346
+ role: en
1347
+ ? 'Return pass=true if upstream tests/checks all passed with no errors; return pass=false on any failure or incomplete delivery.'
1348
+ : '判断上游执行与自检是否全部通过且无报错;全部通过返回 true,存在失败或未完全交付返回 false。',
1349
+ },
1350
+ {
1351
+ id: 'c_yes', kind: 'agent', y: 0,
1352
+ label: en ? 'Pass: Draft Release' : '通过:整理交付',
1353
+ provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false,
1354
+ role: en
1355
+ ? 'Summarize verified changes and draft concise release notes ready to ship.'
1356
+ : '汇总已验证的改动内容,起草简洁清晰的发布说明与交付清单。',
1357
+ },
1358
+ {
1359
+ id: 'c_no', kind: 'agent', y: 100,
1360
+ label: en ? 'Fail: Diagnose & Fix' : '失败:定位修复',
1361
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
1362
+ role: en
1363
+ ? 'Inspect the failure logs, identify root causes, and implement or propose a targeted fix.'
1364
+ : '排查失败日志、定位根因,并完成或给出最小范围的修复补丁。',
1365
+ },
1366
+ {
1367
+ id: 'c_final', kind: 'lead', y: 0,
1368
+ label: en ? 'Lead Final Review' : 'Lead 终审',
1369
+ provider: '', model: '',
1370
+ role: en
1371
+ ? 'Review the chosen branch outcome and decide whether to ship or re-run.'
1372
+ : '查看命中的分支产出,确认可直接交付或安排下一轮修复。',
1373
+ },
1374
+ ];
1375
+ const condEdges = [
1376
+ { id: 'cd1', from: 'lead', to: 'c_run', type: 'prompt' },
1377
+ { id: 'cd2', from: 'c_run', to: 'c_gate', type: 'prompt' },
1378
+ { id: 'cd3', from: 'c_gate', to: 'c_yes', type: 'prompt', branch: 'true' },
1379
+ { id: 'cd4', from: 'c_gate', to: 'c_no', type: 'prompt', branch: 'false' },
1380
+ { id: 'cd5', from: 'c_yes', to: 'c_final', type: 'prompt' },
1381
+ { id: 'cd6', from: 'c_no', to: 'c_final', type: 'prompt' },
1382
+ ];
1031
1383
  return [
1032
1384
  {
1033
1385
  id: 'tpl-swe',
@@ -1047,6 +1399,12 @@ window.__ModuleLoader__.load({
1047
1399
  nodes: layoutGraph(abNodes, abEdges),
1048
1400
  edges: abEdges,
1049
1401
  },
1402
+ {
1403
+ id: 'tpl-cond',
1404
+ name: en ? 'Conditional: Run → Pass/Fail Branch → Review' : '条件分支:执行 → 判断分流 → 终审',
1405
+ nodes: layoutGraph(condNodes, condEdges),
1406
+ edges: condEdges,
1407
+ },
1050
1408
  ];
1051
1409
  }
1052
1410
 
@@ -1073,7 +1431,12 @@ window.__ModuleLoader__.load({
1073
1431
  const activeIds = new Set(active.map((n) => n.id));
1074
1432
  const planEdges = edges
1075
1433
  .filter((e) => (e.from === 'lead' || activeIds.has(e.from)) && activeIds.has(e.to))
1076
- .map((e) => ({ from: e.from, to: e.to, type: e.type || 'prompt' }));
1434
+ .map((e) => {
1435
+ const item = { from: e.from, to: e.to, type: e.type || 'prompt' };
1436
+ const b = typeof e.branch === 'string' ? e.branch.trim() : '';
1437
+ if (b) item.branch = b;
1438
+ return item;
1439
+ });
1077
1440
 
1078
1441
  const maxParallel = opts && Number.isFinite(Number(opts.maxParallel))
1079
1442
  ? Math.max(1, Math.min(8, Math.floor(Number(opts.maxParallel))))
@@ -1084,22 +1447,31 @@ window.__ModuleLoader__.load({
1084
1447
  task,
1085
1448
  maxParallel,
1086
1449
  skipped: skipped.map((n) => n.label || n.id),
1087
- nodes: active.map((n) => ({
1088
- id: n.id,
1089
- kind: n.kind === 'lead' ? 'lead' : 'agent',
1090
- label: n.label || n.id,
1091
- role: n.role || '',
1092
- provider: n.provider || '',
1093
- model: n.model || '',
1094
- reasoning: n.reasoning || '',
1095
- preset: n.preset === 'minimal' ? 'minimal' : 'standard',
1096
- keepSession: Boolean(n.keepSession),
1097
- memoryChildId: n.memoryChildId || '',
1098
- // A structured link is the only thing that decides this: no separate switch.
1099
- structured: planEdges.some((e) => e.from === n.id && e.type === 'structured'),
1100
- fallbackModel: n.fallbackModel || '',
1101
- fallbackProvider: n.fallbackProvider || '',
1102
- })),
1450
+ nodes: active.map((n) => {
1451
+ const out = {
1452
+ id: n.id,
1453
+ kind: n.kind === 'lead' ? 'lead' : (n.kind === 'condition' ? 'condition' : 'agent'),
1454
+ label: n.label || n.id,
1455
+ role: n.role || '',
1456
+ provider: n.provider || '',
1457
+ model: n.model || '',
1458
+ reasoning: n.reasoning || '',
1459
+ preset: n.kind === 'condition' ? 'minimal' : (n.preset === 'minimal' ? 'minimal' : 'standard'),
1460
+ keepSession: n.kind === 'condition' ? false : Boolean(n.keepSession),
1461
+ memoryChildId: n.kind === 'condition' ? '' : (n.memoryChildId || ''),
1462
+ // A structured link is the only thing that decides this: no separate switch.
1463
+ structured: planEdges.some((e) => e.from === n.id && e.type === 'structured'),
1464
+ fallbackModel: n.fallbackModel || '',
1465
+ fallbackProvider: n.fallbackProvider || '',
1466
+ };
1467
+ if (out.kind === 'condition' && isCustomBranches(n)) {
1468
+ out.branches = conditionBranchesForUI(n).map((b) => ({ id: b.id, label: b.label }));
1469
+ }
1470
+ if (out.kind === 'condition' && n.multiMatch) {
1471
+ out.multiMatch = true;
1472
+ }
1473
+ return out;
1474
+ }),
1103
1475
  edges: planEdges,
1104
1476
  },
1105
1477
  };
@@ -1161,6 +1533,16 @@ window.__ModuleLoader__.load({
1161
1533
  return PARALLEL_STEPS[(idx + 1) % PARALLEL_STEPS.length];
1162
1534
  }
1163
1535
 
1536
+ /** Pick 'left' or 'right' anchor so a wrapped toolbar dropdown never clips off the pane edge. */
1537
+ function dropdownAlign(btnRect, containerRect, menuWidth) {
1538
+ if (!btnRect || !containerRect) return 'right';
1539
+ const need = Number(menuWidth) || 200;
1540
+ const availLeft = btnRect.right - containerRect.left;
1541
+ const availRight = containerRect.right - btnRect.left;
1542
+ if (availLeft < need && availRight >= availLeft) return 'left';
1543
+ return 'right';
1544
+ }
1545
+
1164
1546
  /** Compute the next `{ k, x, y }` keeping the content point under `(mx, my)` fixed. */
1165
1547
  function zoomAroundPoint(cur, mx, my, deltaY, deltaMode) {
1166
1548
  if (!deltaY) return cur;
@@ -1288,6 +1670,8 @@ window.__ModuleLoader__.load({
1288
1670
  const [syncNote, setSyncNote] = useState('');
1289
1671
  const [roleEditFor, setRoleEditFor] = useState(null);
1290
1672
  const [menuOpen, setMenuOpen] = useState(false);
1673
+ const [menuAlign, setMenuAlign] = useState('right');
1674
+ const [presetAlign, setPresetAlign] = useState('right');
1291
1675
  const [helpOpen, setHelpOpen] = useState(false);
1292
1676
  const [cutMode, setCutMode] = useState(loadCutMode);
1293
1677
  const [fxLevel, setFxLevel] = useState(loadEffectLevel);
@@ -1330,7 +1714,13 @@ window.__ModuleLoader__.load({
1330
1714
  viewRef.current = view;
1331
1715
  const [statusById, setStatusById] = useState({});
1332
1716
  const [runsById, setRunsById] = useState({});
1717
+ const [runState, setRunState] = useState(null);
1718
+ const [decisionViewFor, setDecisionViewFor] = useState(null);
1333
1719
  const [sessionRunning, setSessionRunning] = useState(false);
1720
+ const [runTriggering, setRunTriggering] = useState(false);
1721
+ const runTriggeringRef = useRef(false);
1722
+ const pendingHandledRef = useRef(false);
1723
+ const lastNodePrefsRef = useRef({ provider: '', model: '', reasoning: '', preset: 'standard' });
1334
1724
  const [presets, setPresets] = useState(loadPresets);
1335
1725
  const [presetOpen, setPresetOpen] = useState(null);
1336
1726
  const [presetName, setPresetName] = useState('');
@@ -1428,25 +1818,89 @@ window.__ModuleLoader__.load({
1428
1818
  const pushPlan = (nextEnabled, overrideNodes, overrideEdges, overrideParallel) => {
1429
1819
  try {
1430
1820
  const face = sessionFace(sessionId);
1431
- if (!face || typeof face.command !== 'function') { flash(t('syncFailed')); return; }
1821
+ if (!face || typeof face.command !== 'function') { flash(t('syncFailed')); return Promise.resolve(false); }
1432
1822
  const curNodes = Array.isArray(overrideNodes) ? overrideNodes : nodesRef.current;
1433
1823
  const curEdges = Array.isArray(overrideEdges) ? overrideEdges : edgesRef.current;
1434
1824
  const sig = planSig(nextEnabled, curNodes, curEdges, overrideParallel);
1435
- if (sig === lastSync.current) { setDirty(false); flash(t('upToDate')); return; }
1825
+ if (sig === lastSync.current) { setDirty(false); flash(t('upToDate')); return Promise.resolve(true); }
1436
1826
  const line = '/canvas-sync ' + encodeURIComponent(sig);
1437
1827
  const hasStandardAgent = nextEnabled && curNodes.some((n) => n && n.kind !== 'lead' && (n.preset || 'standard') !== 'minimal');
1438
- face.command(line).then((ack) => {
1828
+ return face.command(line).then((ack) => {
1439
1829
  if (ack && ack.ok) {
1440
1830
  lastSync.current = sig;
1441
1831
  setDirty(false);
1832
+ setRunState(null);
1833
+ setDecisionViewFor(null);
1442
1834
  snapshotStaleCatalog();
1443
1835
  flash(hasStandardAgent ? t('syncedWithStdWarn') : t('syncedToHost'));
1444
- } else {
1445
- flash(t('syncFailed'));
1836
+ return true;
1446
1837
  }
1447
- }, () => flash(t('syncFailed')));
1838
+ flash(t('syncFailed'));
1839
+ return false;
1840
+ }, () => { flash(t('syncFailed')); return false; });
1448
1841
  } catch (_e) {
1449
1842
  flash(t('syncFailed'));
1843
+ return Promise.resolve(false);
1844
+ }
1845
+ };
1846
+
1847
+ const runFromEntry = async () => {
1848
+ if (runTriggeringRef.current || sessionRunning) return;
1849
+ const entry = nodesRef.current.find((n) => n.id === 'lead');
1850
+ const taskText = String((entry && entry.task) || '').trim();
1851
+ const waitingLead = runState
1852
+ ? (runState.waitingLead || null)
1853
+ : (leadReadyIds.size > 0 ? { id: Array.from(leadReadyIds)[0] } : null);
1854
+ const btn = entryRunButtonState({
1855
+ enabled,
1856
+ task: taskText,
1857
+ sessionRunning,
1858
+ waitingLead,
1859
+ triggering: runTriggeringRef.current,
1860
+ lang,
1861
+ });
1862
+ if (btn.disabled) { flash(btn.title); return; }
1863
+ const face = sessionFace(sessionId);
1864
+ const canPrompt = Boolean(face && typeof face.prompt === 'function');
1865
+ const canConvSend = Boolean(hostCtx && hostCtx.conversation && typeof hostCtx.conversation.send === 'function');
1866
+ if (!canPrompt && !canConvSend) { flash(t('runSendUnavailable')); return; }
1867
+ runTriggeringRef.current = true;
1868
+ setRunTriggering(true);
1869
+ let succeeded = false;
1870
+ try {
1871
+ if (dirty) {
1872
+ const ok = await pushPlan(true);
1873
+ if (!ok) {
1874
+ runTriggeringRef.current = false;
1875
+ setRunTriggering(false);
1876
+ return;
1877
+ }
1878
+ }
1879
+ const promptText = lang === 'en'
1880
+ ? 'Run the enabled workflow canvas for this task:\n' + taskText
1881
+ : '按当前已启用的画布执行以下任务:\n' + taskText;
1882
+ if (canPrompt) {
1883
+ const res = await face.prompt([{ type: 'text', text: promptText }], 'queue');
1884
+ if (res && res.ok === false) {
1885
+ throw new Error((res.error && res.error.message) || 'prompt failed');
1886
+ }
1887
+ } else {
1888
+ await hostCtx.conversation.send(promptText);
1889
+ }
1890
+ succeeded = true;
1891
+ flash(t('runStarted'));
1892
+ } catch (err) {
1893
+ flash(t('runFailed') + (err && err.message ? ': ' + String(err.message).slice(0, 60) : ''));
1894
+ } finally {
1895
+ if (!succeeded) {
1896
+ runTriggeringRef.current = false;
1897
+ setRunTriggering(false);
1898
+ } else {
1899
+ setTimeout(() => {
1900
+ runTriggeringRef.current = false;
1901
+ setRunTriggering(false);
1902
+ }, 1200);
1903
+ }
1450
1904
  }
1451
1905
  };
1452
1906
 
@@ -1737,7 +2191,8 @@ window.__ModuleLoader__.load({
1737
2191
  if (n.x < minX) minX = n.x;
1738
2192
  if (n.y < minY) minY = n.y;
1739
2193
  if (n.x + NODE_W > maxX) maxX = n.x + NODE_W;
1740
- if (n.y + NODE_H > maxY) maxY = n.y + NODE_H;
2194
+ const nh = nodeHeight(n);
2195
+ if (n.y + nh > maxY) maxY = n.y + nh;
1741
2196
  }
1742
2197
  if (!Number.isFinite(minX)) return;
1743
2198
  const cw = el.clientWidth || 1;
@@ -1823,34 +2278,78 @@ window.__ModuleLoader__.load({
1823
2278
  openRun(node, run);
1824
2279
  };
1825
2280
 
1826
- const addNode = (kind, atWorld) => {
2281
+ const addNode = (kind, atWorld, linkFrom) => {
2282
+ const normKind = kind === 'lead' ? 'lead' : (kind === 'condition' ? 'condition' : 'agent');
2283
+ if (linkFrom && linkFrom.fromId) {
2284
+ const srcNode = nodesRef.current.find((n) => n.id === linkFrom.fromId);
2285
+ const compat = compatibleTargetsForWire(srcNode, linkFrom.type);
2286
+ if ((normKind === 'lead' && !compat.lead)
2287
+ || (normKind === 'agent' && !compat.agent)
2288
+ || (normKind === 'condition' && !compat.condition)) {
2289
+ flash(t(compat.leadBlockedReason || 'leadToLeadBlocked'));
2290
+ return;
2291
+ }
2292
+ }
1827
2293
  pushSnapshot();
1828
2294
  const newId = 'n' + Date.now().toString(36) + Math.random().toString(36).slice(2, 4);
2295
+ const prefs = lastNodePrefsRef.current || {};
1829
2296
  setNodes((ns) => {
1830
2297
  const i = ns.length;
1831
2298
  const center = viewportCenterWorld();
1832
2299
  const x = atWorld && typeof atWorld.x === 'number'
1833
- ? Math.round(atWorld.x - NODE_W / 2)
2300
+ ? (linkFrom ? Math.round(atWorld.x) : Math.round(atWorld.x - NODE_W / 2))
1834
2301
  : center.x + 40 + (ns.length % 3) * 30;
1835
2302
  const y = atWorld && typeof atWorld.y === 'number'
1836
- ? Math.round(atWorld.y - NODE_H / 2)
2303
+ ? (linkFrom ? Math.round(atWorld.y - socketCenterY(0)) : Math.round(atWorld.y - NODE_H / 2))
1837
2304
  : center.y - NODE_H / 2 + (ns.length % 3) * 40;
1838
- return [...ns, {
2305
+ const defaultLabel = normKind === 'lead'
2306
+ ? 'Lead 步骤 ' + i
2307
+ : (normKind === 'condition' ? (lang === 'en' ? 'Condition ' + i : '条件判断 ' + i) : 'Node ' + i);
2308
+ const nextNode = {
1839
2309
  id: newId,
1840
- kind: kind === 'lead' ? 'lead' : 'agent',
2310
+ kind: normKind,
1841
2311
  x,
1842
2312
  y,
1843
- label: kind === 'lead' ? 'Lead 步骤 ' + i : 'Node ' + i,
1844
- provider: '',
1845
- model: '',
2313
+ label: defaultLabel,
2314
+ provider: normKind === 'lead' ? '' : (prefs.provider || ''),
2315
+ model: normKind === 'lead' ? '' : (prefs.model || ''),
2316
+ reasoning: normKind === 'lead' ? '' : (prefs.reasoning || ''),
2317
+ preset: normKind === 'condition' ? 'minimal' : (prefs.preset || 'standard'),
1846
2318
  role: '',
1847
- }];
2319
+ };
2320
+ return [...ns, nextNode];
1848
2321
  });
2322
+ if (linkFrom && linkFrom.fromId) {
2323
+ const type = linkFrom.type || 'prompt';
2324
+ const b = typeof linkFrom.branch === 'string' ? linkFrom.branch.trim() : '';
2325
+ setEdges((es) => {
2326
+ const nextEdge = {
2327
+ id: 'e' + Date.now().toString(36) + Math.random().toString(36).slice(2, 4),
2328
+ from: linkFrom.fromId,
2329
+ to: newId,
2330
+ type,
2331
+ };
2332
+ if (b) nextEdge.branch = b;
2333
+ return [...es, nextEdge];
2334
+ });
2335
+ }
1849
2336
  setSelectedIds([newId]);
1850
2337
  setAddMenu(null);
1851
2338
  };
1852
2339
 
1853
2340
  const updateNode = (id, patch) => {
2341
+ if (patch && ('provider' in patch || 'model' in patch || 'reasoning' in patch || 'preset' in patch)) {
2342
+ const cur = nodesRef.current.find((n) => n.id === id);
2343
+ if (cur && cur.kind !== 'lead') {
2344
+ const prev = lastNodePrefsRef.current || {};
2345
+ lastNodePrefsRef.current = {
2346
+ provider: 'provider' in patch ? (patch.provider || '') : prev.provider,
2347
+ model: 'model' in patch ? (patch.model || '') : prev.model,
2348
+ reasoning: 'reasoning' in patch ? (patch.reasoning || '') : prev.reasoning,
2349
+ preset: cur.kind === 'agent' && 'preset' in patch ? (patch.preset || 'standard') : prev.preset,
2350
+ };
2351
+ }
2352
+ }
1854
2353
  setNodes((ns) => ns.map((n) => (n.id === id ? { ...n, ...patch } : n)));
1855
2354
  };
1856
2355
 
@@ -2007,23 +2506,66 @@ window.__ModuleLoader__.load({
2007
2506
  e.stopPropagation();
2008
2507
  };
2009
2508
 
2010
- const onOutputDown = (e, id, type) => {
2509
+ const addConditionBranch = (node) => {
2510
+ const current = isCustomBranches(node)
2511
+ ? conditionBranchesForUI(node, lang).map((b) => ({ id: b.id, label: b.label }))
2512
+ : [
2513
+ { id: 'true', label: lang === 'en' ? 'Yes' : '是' },
2514
+ { id: 'false', label: lang === 'en' ? 'No' : '否' },
2515
+ ];
2516
+ if (current.length >= 16) return;
2517
+ pushSnapshot();
2518
+ const used = new Set(current.map((b) => b.id));
2519
+ let n = current.length + 1;
2520
+ while (used.has('case_' + n)) n += 1;
2521
+ const next = current.concat([{
2522
+ id: 'case_' + n,
2523
+ label: lang === 'en' ? 'Case ' + n : '分支 ' + n,
2524
+ }]);
2525
+ updateNode(node.id, { branches: next });
2526
+ };
2527
+
2528
+ const renameConditionBranch = (node, branchId, nextLabel) => {
2529
+ const current = isCustomBranches(node)
2530
+ ? conditionBranchesForUI(node, lang).map((b) => ({ id: b.id, label: b.label }))
2531
+ : [
2532
+ { id: 'true', label: lang === 'en' ? 'Yes' : '是' },
2533
+ { id: 'false', label: lang === 'en' ? 'No' : '否' },
2534
+ ];
2535
+ const next = current.map((b) => (b.id === branchId ? { ...b, label: nextLabel } : b));
2536
+ updateNode(node.id, { branches: next });
2537
+ };
2538
+
2539
+ const removeConditionBranch = (node, branchId) => {
2540
+ if (!isCustomBranches(node)) return;
2541
+ const current = conditionBranchesForUI(node, lang).map((b) => ({ id: b.id, label: b.label }));
2542
+ if (current.length <= 2) return;
2543
+ pushSnapshot();
2544
+ const next = current.filter((b) => b.id !== branchId);
2545
+ updateNode(node.id, { branches: next });
2546
+ setEdges((es) => es.filter((e) => !(e.from === node.id && e.branch === branchId)));
2547
+ };
2548
+
2549
+ const onOutputDown = (e, id, type, branch) => {
2011
2550
  const node = nodes.find((n) => n.id === id);
2012
2551
  if (!node) return;
2013
- const idx = SOCKET_TYPES.findIndex((t) => t.id === type);
2552
+ const b = typeof branch === 'string' ? branch.trim() : '';
2014
2553
  const sx = node.x + NODE_W;
2015
- const sy = node.y + socketCenterY(idx);
2016
- setPending({ dir: 'out', fromId: id, type, sx, sy, x: sx, y: sy });
2554
+ const sy = node.y + outputSocketY(node, type, b);
2555
+ const color = edgeColorFor(node, { type, branch: b });
2556
+ setPending({ dir: 'out', fromId: id, type, branch: b, color, sx, sy, x: sx, y: sy });
2017
2557
  setDragging(true);
2018
2558
  e.preventDefault();
2019
2559
  e.stopPropagation();
2020
2560
  };
2021
2561
 
2022
- /** Release over an output socket: completes a drag that started at an input. */
2023
- const onOutputUp = (e, id, type) => {
2024
- if (!pending || pending.dir !== 'in' || pending.type !== type) return;
2562
+ /** Release over an output socket: completes a drag that started at the unified left input. */
2563
+ const onOutputUp = (e, id, type, branch) => {
2564
+ if (!pending || pending.dir !== 'in') return;
2565
+ pendingHandledRef.current = true;
2025
2566
  e.preventDefault();
2026
2567
  e.stopPropagation();
2568
+ const b = typeof branch === 'string' ? branch.trim() : '';
2027
2569
  const toId = pending.toId;
2028
2570
  if (toId && toId !== id) {
2029
2571
  if (wouldCycle(nodesRef.current, edgesRef.current, id, toId)) {
@@ -2031,8 +2573,10 @@ window.__ModuleLoader__.load({
2031
2573
  } else {
2032
2574
  pushSnapshot();
2033
2575
  setEdges((es) => {
2034
- if (es.some((x) => x.from === id && x.to === toId && x.type === type)) return es;
2035
- return [...es, { id: 'e' + Date.now().toString(36), from: id, to: toId, type }];
2576
+ if (es.some((x) => x.from === id && x.to === toId && x.type === type && (x.branch || '') === b)) return es;
2577
+ const nextEdge = { id: 'e' + Date.now().toString(36), from: id, to: toId, type };
2578
+ if (b) nextEdge.branch = b;
2579
+ return [...es, nextEdge];
2036
2580
  });
2037
2581
  }
2038
2582
  }
@@ -2040,45 +2584,53 @@ window.__ModuleLoader__.load({
2040
2584
  setDragging(false);
2041
2585
  };
2042
2586
 
2043
- // Dragging a connected input detaches it; dragging a free input starts a
2044
- // link that finishes on an output socket of the same type.
2045
- const onInputDown = (e, id, type) => {
2587
+ // Unified left input: dragging a connected input detaches the latest wire;
2588
+ // dragging a free input starts a reverse wire that adopts whichever right output it drops onto.
2589
+ const onInputDown = (e, id) => {
2046
2590
  e.preventDefault();
2047
2591
  e.stopPropagation();
2048
- const link = edges.find((x) => x.to === id && x.type === type);
2049
- const idx = SOCKET_TYPES.findIndex((t) => t.id === type);
2592
+ const incoming = edges.filter((x) => x.to === id);
2593
+ const link = incoming[incoming.length - 1];
2050
2594
  if (!link) {
2051
2595
  const node = nodes.find((n) => n.id === id);
2052
2596
  if (!node) return;
2053
2597
  const sx = node.x;
2054
- const sy = node.y + socketCenterY(idx);
2055
- setPending({ dir: 'in', toId: id, type, sx, sy, x: sx, y: sy });
2598
+ const sy = node.y + socketCenterY(0);
2599
+ setPending({ dir: 'in', toId: id, type: 'prompt', branch: '', color: '#8a8f98', sx, sy, x: sx, y: sy });
2056
2600
  setDragging(true);
2057
2601
  return;
2058
2602
  }
2059
2603
  pushSnapshot();
2060
- setEdges((es) => es.filter((x) => !(x.to === id && x.type === type)));
2604
+ setEdges((es) => es.filter((x) => x.id !== link.id));
2061
2605
  const from = nodes.find((n) => n.id === link.from);
2062
2606
  if (!from) return;
2607
+ const b = typeof link.branch === 'string' ? link.branch.trim() : '';
2608
+ const linkType = link.type || 'prompt';
2063
2609
  const sx = from.x + NODE_W;
2064
- const sy = from.y + socketCenterY(idx);
2065
- setPending({ dir: 'out', fromId: link.from, type, sx, sy, x: sx, y: sy });
2610
+ const sy = from.y + outputSocketY(from, linkType, b);
2611
+ const color = edgeColorFor(from, link);
2612
+ setPending({ dir: 'out', fromId: link.from, type: linkType, branch: b, color, sx, sy, x: sx, y: sy });
2066
2613
  setDragging(true);
2067
2614
  };
2068
2615
 
2069
- const onInputUp = (e, id, type) => {
2070
- if (!pending || pending.dir !== 'out' || pending.type !== type) return;
2616
+ const onInputUp = (e, id) => {
2617
+ if (!pending || pending.dir !== 'out') return;
2618
+ pendingHandledRef.current = true;
2071
2619
  e.preventDefault();
2072
2620
  e.stopPropagation();
2073
2621
  if (pending.fromId !== id) {
2074
2622
  const fromId = pending.fromId;
2623
+ const type = pending.type || 'prompt';
2624
+ const b = typeof pending.branch === 'string' ? pending.branch.trim() : '';
2075
2625
  if (wouldCycle(nodesRef.current, edgesRef.current, fromId, id)) {
2076
2626
  flash(t('cycleBlocked'));
2077
2627
  } else {
2078
2628
  pushSnapshot();
2079
2629
  setEdges((es) => {
2080
- if (es.some((x) => x.from === fromId && x.to === id && x.type === type)) return es;
2081
- return [...es, { id: 'e' + Date.now().toString(36), from: fromId, to: id, type }];
2630
+ if (es.some((x) => x.from === fromId && x.to === id && x.type === type && (x.branch || '') === b)) return es;
2631
+ const nextEdge = { id: 'e' + Date.now().toString(36), from: fromId, to: id, type };
2632
+ if (b) nextEdge.branch = b;
2633
+ return [...es, nextEdge];
2082
2634
  });
2083
2635
  }
2084
2636
  }
@@ -2146,8 +2698,8 @@ window.__ModuleLoader__.load({
2146
2698
  const keyActionsRef = useRef(null);
2147
2699
  keyActionsRef.current = {
2148
2700
  undo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode,
2149
- addMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen,
2150
- setAddMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen,
2701
+ addMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, decisionViewFor,
2702
+ setAddMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setDecisionViewFor,
2151
2703
  };
2152
2704
  useEffect(() => {
2153
2705
  const isEditable = (target) => {
@@ -2159,7 +2711,7 @@ window.__ModuleLoader__.load({
2159
2711
  const act = keyActionsRef.current;
2160
2712
  if (!act) return;
2161
2713
  if (ev.key === 'Escape') {
2162
- if (act.addMenu || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen) {
2714
+ if (act.addMenu || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen || act.decisionViewFor) {
2163
2715
  ev.preventDefault();
2164
2716
  act.setAddMenu(null);
2165
2717
  act.setRoleEditFor(null);
@@ -2167,19 +2719,26 @@ window.__ModuleLoader__.load({
2167
2719
  act.setMenuOpen(false);
2168
2720
  act.setPresetOpen(null);
2169
2721
  act.setHelpOpen(false);
2722
+ act.setDecisionViewFor(null);
2170
2723
  }
2171
2724
  return;
2172
2725
  }
2173
2726
  if (isEditable(ev.target)) return;
2174
2727
  if (act.addMenu) {
2728
+ const lf = act.addMenu.linkFrom || null;
2175
2729
  if (ev.key === '1' || ev.key === 'Enter') {
2176
2730
  ev.preventDefault();
2177
- act.addNode('agent', { x: act.addMenu.wx, y: act.addMenu.wy });
2731
+ act.addNode('agent', { x: act.addMenu.wx, y: act.addMenu.wy }, lf);
2178
2732
  return;
2179
2733
  }
2180
2734
  if (ev.key === '2') {
2181
2735
  ev.preventDefault();
2182
- act.addNode('lead', { x: act.addMenu.wx, y: act.addMenu.wy });
2736
+ act.addNode('lead', { x: act.addMenu.wx, y: act.addMenu.wy }, lf);
2737
+ return;
2738
+ }
2739
+ if (ev.key === '3') {
2740
+ ev.preventDefault();
2741
+ act.addNode('condition', { x: act.addMenu.wx, y: act.addMenu.wy }, lf);
2183
2742
  return;
2184
2743
  }
2185
2744
  }
@@ -2242,7 +2801,7 @@ window.__ModuleLoader__.load({
2242
2801
  useEffect(() => {
2243
2802
  if (!dragging) return undefined;
2244
2803
  const move = (ev) => onCanvasMove(ev);
2245
- const up = () => onCanvasUp();
2804
+ const up = (ev) => onCanvasUp(ev);
2246
2805
  window.addEventListener('mousemove', move);
2247
2806
  window.addEventListener('mouseup', up);
2248
2807
  return () => {
@@ -2266,6 +2825,7 @@ window.__ModuleLoader__.load({
2266
2825
  }
2267
2826
  if (e.button !== 0) return;
2268
2827
  if (roleEditFor) setRoleEditFor(null);
2828
+ if (decisionViewFor) setDecisionViewFor(null);
2269
2829
  if (menuOpen) setMenuOpen(false);
2270
2830
  if (addMenu) setAddMenu(null);
2271
2831
  if (presetOpen) setPresetOpen(null);
@@ -2314,7 +2874,7 @@ window.__ModuleLoader__.load({
2314
2874
  const source = nodeMap.get(edge.from);
2315
2875
  const target = nodeMap.get(edge.to);
2316
2876
  if (!source || !target) continue;
2317
- if (distanceToEdge(canvasSpot, source, target, edge.type) <= threshold) {
2877
+ if (distanceToEdge(canvasSpot, source, target, edge) <= threshold) {
2318
2878
  cutHits.current.add(edge.id);
2319
2879
  }
2320
2880
  }
@@ -2334,7 +2894,7 @@ window.__ModuleLoader__.load({
2334
2894
  }
2335
2895
  };
2336
2896
 
2337
- const onCanvasUp = () => {
2897
+ const onCanvasUp = (ev) => {
2338
2898
  if (cutRef.current) {
2339
2899
  cutRef.current = null;
2340
2900
  setDragging(false);
@@ -2357,6 +2917,39 @@ window.__ModuleLoader__.load({
2357
2917
  setPanning(false);
2358
2918
  }
2359
2919
  nodeDrag.current = null;
2920
+ const handled = pendingHandledRef.current;
2921
+ pendingHandledRef.current = false;
2922
+ if (!handled && pending && pending.dir === 'out') {
2923
+ const dist = Math.hypot(pending.x - pending.sx, pending.y - pending.sy);
2924
+ const wrap = canvasWrapRef.current;
2925
+ if (dist >= 16 && wrap) {
2926
+ const wrapRect = wrap.getBoundingClientRect();
2927
+ const cx = ev && typeof ev.clientX === 'number' ? ev.clientX : (wrapRect.left + wrapRect.width / 2);
2928
+ const cy = ev && typeof ev.clientY === 'number' ? ev.clientY : (wrapRect.top + wrapRect.height / 2);
2929
+ const sx = Math.max(8, Math.min(wrapRect.width - 176, cx - wrapRect.left));
2930
+ const sy = Math.max(8, Math.min(wrapRect.height - 110, cy - wrapRect.top));
2931
+ setAddMenu({
2932
+ sx,
2933
+ sy,
2934
+ wx: pending.x,
2935
+ wy: pending.y,
2936
+ linkFrom: {
2937
+ fromId: pending.fromId,
2938
+ type: pending.type || 'prompt',
2939
+ branch: pending.branch || '',
2940
+ color: pending.color || '#8a8f98',
2941
+ sx: pending.sx,
2942
+ sy: pending.sy,
2943
+ x: pending.x,
2944
+ y: pending.y,
2945
+ },
2946
+ });
2947
+ setMenuOpen(false);
2948
+ setPresetOpen(null);
2949
+ setOpenModelFor(null);
2950
+ setDecisionViewFor(null);
2951
+ }
2952
+ }
2360
2953
  setPending(null);
2361
2954
  setDragging(false);
2362
2955
  };
@@ -2372,7 +2965,6 @@ window.__ModuleLoader__.load({
2372
2965
  if (!savePresets(next)) { flash(t('saveFailed')); return; }
2373
2966
  setPresets(next);
2374
2967
  setPresetName('');
2375
- setPresetOpen(null);
2376
2968
  flash(t('savedPreset') + ': ' + name);
2377
2969
  };
2378
2970
 
@@ -2427,21 +3019,28 @@ window.__ModuleLoader__.load({
2427
3019
  return kept.concat(incoming);
2428
3020
  });
2429
3021
  setEdges((existing) => {
2430
- const incoming = rawIncomingEdges.map((e, i) => ({
2431
- id: e.id || 'e' + i + '-' + Math.random().toString(36).slice(2, 6),
2432
- from: e.from,
2433
- to: e.to,
2434
- type: e.type || 'prompt',
2435
- }));
3022
+ const incoming = rawIncomingEdges.map((e, i) => {
3023
+ const item = {
3024
+ id: e.id || 'e' + i + '-' + Math.random().toString(36).slice(2, 6),
3025
+ from: e.from,
3026
+ to: e.to,
3027
+ type: e.type || 'prompt',
3028
+ };
3029
+ const b = typeof e.branch === 'string' ? e.branch.trim() : '';
3030
+ if (b) item.branch = b;
3031
+ return item;
3032
+ });
2436
3033
  if (!merge) return incoming;
2437
3034
  const rawDrops = Array.isArray(doc.removeEdges) ? doc.removeEdges : [];
2438
3035
  const matchesDrop = (e) => rawDrops.some((r) => r
2439
3036
  && String(r.from) === e.from
2440
3037
  && String(r.to) === e.to
2441
- && (!r.type || r.type === e.type));
3038
+ && (!r.type || r.type === e.type)
3039
+ && (!r.branch || r.branch === e.branch));
2442
3040
  const kept = existing.filter((e) => !matchesDrop(e) && !removedNodes.has(e.from) && !removedNodes.has(e.to));
2443
- const seen = new Set(kept.map((e) => e.from + '>' + e.to + '|' + e.type));
2444
- const added = incoming.filter((e) => !removedNodes.has(e.from) && !removedNodes.has(e.to) && !seen.has(e.from + '>' + e.to + '|' + e.type));
3041
+ const keyOf = (e) => e.from + '>' + e.to + '|' + e.type + '|' + (e.branch || '');
3042
+ const seen = new Set(kept.map(keyOf));
3043
+ const added = incoming.filter((e) => !removedNodes.has(e.from) && !removedNodes.has(e.to) && !seen.has(keyOf(e)));
2445
3044
  return kept.concat(added);
2446
3045
  });
2447
3046
  setSelectedIds([]);
@@ -2474,8 +3073,16 @@ window.__ModuleLoader__.load({
2474
3073
  '.dsh/canvas/session-' + bare + '.json',
2475
3074
  '.dsh/canvas/' + bare + '.json',
2476
3075
  ].filter((v, i, all) => all.indexOf(v) === i);
3076
+ const runPaths = [
3077
+ '.dsh/canvas/' + String(sessionId) + '.run.json',
3078
+ '.dsh/canvas/session-' + bare + '.run.json',
3079
+ '.dsh/canvas/' + bare + '.run.json',
3080
+ ].filter((v, i, all) => all.indexOf(v) === i);
3081
+ setRunState(null);
3082
+ setDecisionViewFor(null);
2477
3083
  let alive = true;
2478
3084
  let lastText = '';
3085
+ let lastRunText = '';
2479
3086
  const tick = async () => {
2480
3087
  try {
2481
3088
  let text = '';
@@ -2490,30 +3097,51 @@ window.__ModuleLoader__.load({
2490
3097
  setSyncNote(t('syncReadFail') + String((err && err.message) || err).slice(0, 80));
2491
3098
  }
2492
3099
  }
2493
- if (!text) return;
2494
- if (text === lastText) return;
2495
- lastText = text;
2496
- const doc = JSON.parse(text);
2497
- const canvas = doc && doc.canvas;
2498
- // A canvas the user has edited more recently wins over an old file.
2499
- try {
2500
- const raw = window.localStorage.getItem(storageKey(sessionId));
2501
- const local = raw ? JSON.parse(raw) : null;
2502
- if (local && typeof local.at === 'number' && typeof doc.at === 'number' && local.at > doc.at) {
2503
- lastText = text;
2504
- return;
3100
+ if (text && text !== lastText) {
3101
+ lastText = text;
3102
+ const doc = JSON.parse(text);
3103
+ const canvas = doc && doc.canvas;
3104
+ // A canvas the user has edited more recently wins over an old file.
3105
+ let staleLocal = false;
3106
+ try {
3107
+ const raw = window.localStorage.getItem(storageKey(sessionId));
3108
+ const local = raw ? JSON.parse(raw) : null;
3109
+ if (local && typeof local.at === 'number' && typeof doc.at === 'number' && local.at > doc.at) {
3110
+ staleLocal = true;
3111
+ }
3112
+ } catch (_e) { /* ignore */ }
3113
+ if (!staleLocal) {
3114
+ const valid = canvas && Array.isArray(canvas.nodes)
3115
+ && (canvas.mode === 'merge' || canvas.nodes.length > 0)
3116
+ && canvas.nodes.every((n) => n && typeof n.id === 'string');
3117
+ if (valid && applyCanvasDoc(canvas, doc.at, true)) {
3118
+ flash(t('generated'));
3119
+ setSyncNote(t('syncApplied'));
3120
+ setTimeout(() => setSyncNote(''), 4000);
3121
+ }
3122
+ else setSyncNote(t('syncBadFile'));
2505
3123
  }
2506
- } catch (_e) { /* ignore */ }
2507
- const valid = canvas && Array.isArray(canvas.nodes)
2508
- && (canvas.mode === 'merge' || canvas.nodes.length > 0)
2509
- && canvas.nodes.every((n) => n && typeof n.id === 'string');
2510
- if (valid && applyCanvasDoc(canvas, doc.at, true)) {
2511
- flash(t('generated'));
2512
- setSyncNote(t('syncApplied'));
2513
- setTimeout(() => setSyncNote(''), 4000);
2514
3124
  }
2515
- else setSyncNote(t('syncBadFile'));
2516
3125
  } catch (_e) { /* file absent or not readable yet */ }
3126
+ try {
3127
+ let runText = '';
3128
+ for (const rp of runPaths) {
3129
+ try {
3130
+ const res = await wf.read(sessionId, rp, {}, new AbortController().signal);
3131
+ if (!alive) return;
3132
+ const payload = res && res.ok === false ? null : (res && res.value !== undefined ? res.value : res);
3133
+ const read = payload && (typeof payload.text === 'string' ? payload.text : '');
3134
+ if (read) { runText = read; break; }
3135
+ } catch (_e) { /* ignore */ }
3136
+ }
3137
+ if (runText && runText !== lastRunText) {
3138
+ lastRunText = runText;
3139
+ const parsed = JSON.parse(runText);
3140
+ if (parsed && typeof parsed === 'object') {
3141
+ setRunState(parsed.status === 'idle' ? null : parsed);
3142
+ }
3143
+ }
3144
+ } catch (_e) { /* run state file absent or not readable yet */ }
2517
3145
  };
2518
3146
  const timer = setInterval(tick, 1500);
2519
3147
  tick();
@@ -2679,9 +3307,9 @@ window.__ModuleLoader__.load({
2679
3307
  const memoryToggle = (node) => {
2680
3308
  const runInfo = runsById[node.id];
2681
3309
  const history = (runInfo && Array.isArray(runInfo.history)) ? runInfo.history : [];
2682
- const showPicker = Boolean(node.keepSession);
3310
+ const isOn = Boolean(node.keepSession);
2683
3311
  const key = 'm:' + node.id;
2684
- const isOpen = openModelFor === key;
3312
+ const isOpen = isOn && openModelFor === key;
2685
3313
  const pickedItem = node.memoryChildId
2686
3314
  ? history.find((item) => item.childId === node.memoryChildId)
2687
3315
  : undefined;
@@ -2689,15 +3317,15 @@ window.__ModuleLoader__.load({
2689
3317
  ? t('memLatest')
2690
3318
  : (pickedItem ? ('#' + pickedItem.index) : String(node.memoryChildId).slice(-6));
2691
3319
  const toggleBtn = h('button', {
2692
- style: showPicker
2693
- ? { ...(node.keepSession ? S.toggleSwitchOn : S.toggleSwitch), flex: '0 0 34px', width: '34px' }
2694
- : (node.keepSession ? S.toggleSwitchOn : S.toggleSwitch),
3320
+ style: isOn ? S.toggleSwitchOn : S.toggleSwitch,
2695
3321
  type: 'button',
2696
3322
  title: t('tipMemory'),
2697
3323
  onMouseDown: (e) => e.stopPropagation(),
2698
- onClick: () => updateNode(node.id, { keepSession: !node.keepSession }),
2699
- }, node.keepSession ? t('on') : t('off'));
2700
- if (!showPicker) return toggleBtn;
3324
+ onClick: () => {
3325
+ if (isOn && openModelFor === key) setOpenModelFor(null);
3326
+ updateNode(node.id, { keepSession: !isOn });
3327
+ },
3328
+ }, isOn ? t('on') : t('off'));
2701
3329
  const rows = [
2702
3330
  h('div', {
2703
3331
  key: 'latest',
@@ -2721,18 +3349,24 @@ window.__ModuleLoader__.load({
2721
3349
  ];
2722
3350
  return h('div', { style: { display: 'flex', alignItems: 'center', gap: '4px', flex: '1 1 auto', minWidth: 0 } },
2723
3351
  toggleBtn,
2724
- h('div', { ref: isOpen ? dropdownRef : undefined, style: { position: 'relative', flex: '1 1 auto', minWidth: 0 } },
3352
+ h('div', { ref: isOpen ? dropdownRef : undefined, style: { position: 'relative', flex: '0 0 64px', width: '64px' } },
2725
3353
  h('button', {
2726
- style: S.selectBtn,
3354
+ style: isOn
3355
+ ? { ...S.selectBtn, borderColor: C.accent }
3356
+ : { ...S.selectBtn, borderColor: C.border, color: C.dim, opacity: 0.55, cursor: 'not-allowed' },
2727
3357
  type: 'button',
3358
+ disabled: !isOn,
2728
3359
  title: t('tipMemoryPick'),
2729
3360
  onMouseDown: (e) => e.stopPropagation(),
2730
- onClick: () => setOpenModelFor(isOpen ? null : key),
3361
+ onClick: () => { if (isOn) setOpenModelFor(isOpen ? null : key); },
2731
3362
  },
2732
3363
  h('span', { style: S.selectText }, pickLabel),
2733
3364
  h('span', { style: S.caret }, '▾'),
2734
3365
  ),
2735
- isOpen && h('div', { style: S.menu, onMouseDown: (e) => e.stopPropagation() }, rows),
3366
+ isOpen && h('div', {
3367
+ style: { ...S.menu, left: 'auto', right: 0, minWidth: '150px' },
3368
+ onMouseDown: (e) => e.stopPropagation(),
3369
+ }, rows),
2736
3370
  ),
2737
3371
  );
2738
3372
  };
@@ -2818,15 +3452,24 @@ window.__ModuleLoader__.load({
2818
3452
 
2819
3453
  const fxName = (level) => (level === 'minimal' ? t('fxMinimal') : (level === 'vivid' ? t('fxVivid') : t('fxStandard')));
2820
3454
  const selectedSet = new Set(selectedIds);
2821
- const connectedIn = new Set();
3455
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
3456
+ const inColorByNode = new Map();
3457
+ const inCountByNode = new Map();
3458
+ const inPriority = (e) => (e.type === 'session-ref' ? 3 : (e.type === 'structured' ? 2 : (e.branch ? 1.5 : 1)));
3459
+ const inPrioByNode = new Map();
2822
3460
  const connectedOut = new Set();
2823
3461
  for (const e of edges) {
2824
3462
  const type = e.type || 'prompt';
2825
- connectedOut.add(e.from + '|' + type);
2826
- connectedIn.add(e.to + '|' + type);
3463
+ const b = typeof e.branch === 'string' ? e.branch.trim() : '';
3464
+ connectedOut.add(e.from + '|' + (b ? 'branch:' + b : type));
3465
+ inCountByNode.set(e.to, (inCountByNode.get(e.to) || 0) + 1);
3466
+ const prio = inPriority(e);
3467
+ if (!inPrioByNode.has(e.to) || prio >= inPrioByNode.get(e.to)) {
3468
+ inPrioByNode.set(e.to, prio);
3469
+ inColorByNode.set(e.to, edgeColorFor(nodeById.get(e.from), e));
3470
+ }
2827
3471
  }
2828
3472
  const reachableIds = reachableFrom(nodes, edges);
2829
- const nodeById = new Map(nodes.map((n) => [n.id, n]));
2830
3473
  const soloLeadIds = soloLeadNodeIds(nodes, edges);
2831
3474
  const deadEndIds = deadEndNodeIds(nodes, edges);
2832
3475
 
@@ -2838,6 +3481,7 @@ window.__ModuleLoader__.load({
2838
3481
  // settles to "Done" once the turn ends.
2839
3482
  const leadReadyIds = new Set();
2840
3483
  const leadDoneIds = new Set();
3484
+ const hasCondNode = nodes.some((x) => x.kind === 'condition');
2841
3485
  if (enabled) {
2842
3486
  for (const n of nodes) {
2843
3487
  if (n.kind !== 'lead' || n.id === 'lead' || !reachableIds.has(n.id)) continue;
@@ -2847,7 +3491,10 @@ window.__ModuleLoader__.load({
2847
3491
  if (!upIds.length) continue;
2848
3492
  const upAgents = upIds.filter((id) => nodeById.get(id).kind !== 'lead');
2849
3493
  if (!upAgents.length) continue;
2850
- const allUpDone = upAgents.every((id) => statusById[id] === 'done' || statusById[id] === 'failed');
3494
+ const anyUpRunning = upAgents.some((id) => statusById[id] === 'running');
3495
+ const allUpDone = hasCondNode
3496
+ ? (!anyUpRunning && upAgents.some((id) => statusById[id] === 'done' || statusById[id] === 'failed'))
3497
+ : upAgents.every((id) => statusById[id] === 'done' || statusById[id] === 'failed');
2851
3498
  if (!allUpDone) continue;
2852
3499
  const downIds = edges.filter((e) => e.from === n.id).map((e) => e.to);
2853
3500
  if (!downIds.length) {
@@ -2861,13 +3508,21 @@ window.__ModuleLoader__.load({
2861
3508
  }
2862
3509
  }
2863
3510
 
3511
+ const decisionsById = (enabled && runState && runState.decisions && typeof runState.decisions === 'object')
3512
+ ? runState.decisions
3513
+ : {};
3514
+ const prunedSet = new Set(enabled && runState && Array.isArray(runState.pruned) ? runState.pruned : []);
3515
+ const blockedEdgeSet = new Set(enabled && runState && Array.isArray(runState.blockedEdges) ? runState.blockedEdges : []);
3516
+ const edgeKeyForState = (e) => String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
3517
+
2864
3518
  const edgeEls = edges.map((edge) => {
2865
3519
  const from = nodeById.get(edge.from);
2866
3520
  const to = nodeById.get(edge.to);
2867
3521
  if (!from || !to) return null;
2868
- const color = (SOCKET_TYPES.find((sock) => sock.id === edge.type) || SOCKET_TYPES[0]).color;
2869
- const d = edgePath(from, to, edge.type);
3522
+ const color = edgeColorFor(from, edge);
3523
+ const d = edgePath(from, to, edge);
2870
3524
  const highlighted = cutVictims.includes(edge.id);
3525
+ const isPrunedEdge = !highlighted && (blockedEdgeSet.has(edgeKeyForState(edge)) || prunedSet.has(edge.from) || prunedSet.has(edge.to));
2871
3526
  const hasSel = selectedSet.size > 0;
2872
3527
  const linkedToSel = hasSel && (selectedSet.has(edge.from) || selectedSet.has(edge.to));
2873
3528
  const toRunning = enabled && statusById[edge.to] === 'running';
@@ -2875,7 +3530,7 @@ window.__ModuleLoader__.load({
2875
3530
  || from.kind === 'lead'
2876
3531
  || statusById[edge.from] === 'done'
2877
3532
  || statusById[edge.from] === 'failed';
2878
- const isFlowing = enabled && !highlighted && (
3533
+ const isFlowing = enabled && !highlighted && !isPrunedEdge && (
2879
3534
  (toRunning && fromReady)
2880
3535
  || (leadReadyIds.has(edge.to) && (statusById[edge.from] === 'done' || statusById[edge.from] === 'failed'))
2881
3536
  );
@@ -2888,11 +3543,11 @@ window.__ModuleLoader__.load({
2888
3543
  || statusById[edge.to] === 'failed'
2889
3544
  || leadReadyIds.has(edge.to)
2890
3545
  || leadDoneIds.has(edge.to);
2891
- const isCompletedLink = enabled && !highlighted && fromSettled && toSettled;
2892
- const dimmed = hasSel && !linkedToSel && !highlighted && !isFlowing;
3546
+ const isCompletedLink = enabled && !highlighted && !isPrunedEdge && fromSettled && toSettled;
3547
+ const dimmed = isPrunedEdge || (hasSel && !linkedToSel && !highlighted && !isFlowing);
2893
3548
  const strokeColor = highlighted ? '#e5534b' : color;
2894
3549
  const baseWidth = highlighted ? 3 : (linkedToSel || isFlowing ? 2.6 : 2);
2895
- const baseOpacity = dimmed ? 0.26 : (isFlowing || linkedToSel ? 1 : (isCompletedLink ? 0.92 : 0.78));
3550
+ const baseOpacity = isPrunedEdge ? 0.22 : (dimmed ? 0.26 : (isFlowing || linkedToSel ? 1 : (isCompletedLink ? 0.92 : 0.78)));
2896
3551
  const useGlow = fxLevel === 'vivid' && !dimmed;
2897
3552
  const showDashFlow = isFlowing && fxLevel !== 'minimal';
2898
3553
  const showBead = isFlowing && fxLevel === 'vivid';
@@ -2921,6 +3576,7 @@ window.__ModuleLoader__.load({
2921
3576
  stroke: strokeColor,
2922
3577
  strokeWidth: baseWidth,
2923
3578
  strokeOpacity: showDashFlow ? 0.35 : baseOpacity,
3579
+ strokeDasharray: isPrunedEdge ? '4 4' : undefined,
2924
3580
  fill: 'none',
2925
3581
  }),
2926
3582
  showDashFlow && fxLevel === 'vivid' && h('path', {
@@ -2954,26 +3610,118 @@ window.__ModuleLoader__.load({
2954
3610
 
2955
3611
  const renderBand = (node) => {
2956
3612
  const isEntry = node.id === 'lead';
3613
+ const inColor = inColorByNode.get(node.id) || null;
3614
+ const inCount = inCountByNode.get(node.id) || 0;
3615
+ const inText = inCount > 1 ? 'in ×' + inCount : 'in';
3616
+ const unifiedInSocket = !isEntry && h('div', {
3617
+ style: {
3618
+ ...S.socket,
3619
+ top: (ROW_H - PORT) / 2,
3620
+ left: -PORT / 2,
3621
+ borderColor: inColor || C.border,
3622
+ background: inColor || C.elevated,
3623
+ boxShadow: inColor
3624
+ ? (fxLevel === 'vivid' ? '0 0 6px ' + inColor : '0 0 0 2px ' + C.elevated)
3625
+ : '0 0 0 3px transparent',
3626
+ },
3627
+ title: t('tipSocketOut'),
3628
+ onMouseDown: (e) => onInputDown(e, node.id),
3629
+ onMouseUp: (e) => onInputUp(e, node.id),
3630
+ });
3631
+ if (node.kind === 'condition') {
3632
+ const branches = conditionBranchesForUI(node, lang);
3633
+ const condDec = decisionsById[node.id] || null;
3634
+ const matchedBranchIds = condDec && Array.isArray(condDec.branches) ? new Set(condDec.branches) : null;
3635
+ return h('div', { style: S.band },
3636
+ unifiedInSocket,
3637
+ h('span', { style: { ...S.rowLabel, position: 'absolute', left: '12px', top: '3px', pointerEvents: 'none' } }, inText),
3638
+ branches.map((b) => {
3639
+ const outLinked = connectedOut.has(node.id + '|branch:' + b.id);
3640
+ const isMatchedBranch = Boolean(matchedBranchIds && matchedBranchIds.has(b.id));
3641
+ const isUnmatchedBranch = Boolean(matchedBranchIds && !matchedBranchIds.has(b.id));
3642
+ const outTip = !b.custom
3643
+ ? (b.id === 'true' ? t('tipCondTrue') : t('tipCondFalse'))
3644
+ : t('tipBranchOut');
3645
+ const editKey = 'branch:' + node.id + ':' + b.id;
3646
+ return h('div', { key: b.id, style: { ...S.condBranchRow, opacity: isUnmatchedBranch ? 0.48 : 1 } },
3647
+ h('div', {
3648
+ style: { display: 'flex', alignItems: 'center', marginRight: '10px' },
3649
+ onMouseDown: (e) => e.stopPropagation(),
3650
+ },
3651
+ h('button', {
3652
+ type: 'button',
3653
+ style: S.condBranchExpand,
3654
+ title: t('tipExpandBranch'),
3655
+ onMouseEnter: (e) => { e.currentTarget.style.color = C.text; e.currentTarget.style.borderColor = b.color; },
3656
+ onMouseLeave: (e) => { e.currentTarget.style.color = C.dim; e.currentTarget.style.borderColor = C.border; },
3657
+ onClick: () => setRoleEditFor(roleEditFor === editKey ? null : editKey),
3658
+ }, '⤢'),
3659
+ h('input', {
3660
+ style: {
3661
+ ...S.condBranchInput,
3662
+ borderRight: '2px solid ' + b.color,
3663
+ borderColor: isMatchedBranch ? b.color : C.border,
3664
+ },
3665
+ value: b.label,
3666
+ placeholder: t('branchPh'),
3667
+ onFocus: () => setSelectedIds([node.id]),
3668
+ onChange: (e) => renameConditionBranch(node, b.id, e.target.value),
3669
+ }),
3670
+ branches.length > 2
3671
+ ? h('button', {
3672
+ type: 'button',
3673
+ style: S.condBranchDel,
3674
+ title: t('delBranchTip'),
3675
+ onMouseEnter: (e) => { e.currentTarget.style.color = '#e5534b'; },
3676
+ onMouseLeave: (e) => { e.currentTarget.style.color = C.dim; },
3677
+ onClick: () => removeConditionBranch(node, b.id),
3678
+ }, '×')
3679
+ : h('span', { style: S.condBranchDelSpacer }),
3680
+ ),
3681
+ roleEditFor === editKey && h('div', {
3682
+ style: { ...S.rolePopover, top: '-8px' },
3683
+ onMouseDown: (e) => e.stopPropagation(),
3684
+ },
3685
+ h('div', {
3686
+ style: { display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px', fontSize: '10px', color: C.dim },
3687
+ },
3688
+ h('span', { style: { width: '7px', height: '7px', borderRadius: '50%', background: b.color, flex: '0 0 auto' } }),
3689
+ h('span', null, t('branchEditTitle')),
3690
+ ),
3691
+ h('textarea', {
3692
+ style: S.roleArea,
3693
+ value: b.label,
3694
+ placeholder: t('branchPh'),
3695
+ autoFocus: true,
3696
+ onChange: (e) => renameConditionBranch(node, b.id, e.target.value),
3697
+ }),
3698
+ ),
3699
+ h('div', {
3700
+ style: {
3701
+ ...S.socket,
3702
+ top: (COND_ROW_H - PORT) / 2,
3703
+ right: -PORT / 2,
3704
+ borderColor: b.color,
3705
+ background: outLinked ? b.color : C.elevated,
3706
+ boxShadow: outLinked
3707
+ ? (fxLevel === 'vivid' ? '0 0 6px ' + b.color : '0 0 0 2px ' + C.elevated)
3708
+ : '0 0 0 3px transparent',
3709
+ },
3710
+ title: outTip,
3711
+ onMouseDown: (e) => onOutputDown(e, node.id, 'prompt', b.id),
3712
+ onMouseUp: (e) => onOutputUp(e, node.id, 'prompt', b.id),
3713
+ }),
3714
+ );
3715
+ }),
3716
+ );
3717
+ }
2957
3718
  return h('div', { style: S.band },
3719
+ unifiedInSocket,
3720
+ !isEntry && h('span', { style: { ...S.rowLabel, position: 'absolute', left: '12px', top: '3px', pointerEvents: 'none' } }, inText),
2958
3721
  SOCKET_TYPES.map((sock) => {
2959
- const inLinked = connectedIn.has(node.id + '|' + sock.id);
2960
3722
  const outLinked = connectedOut.has(node.id + '|' + sock.id);
2961
3723
  return h('div', { key: sock.id, style: S.row },
2962
- h('span', { style: S.rowLabel }, sock.label),
2963
- !isEntry && h('div', {
2964
- style: {
2965
- ...S.socket,
2966
- left: -PORT / 2,
2967
- borderColor: sock.color,
2968
- background: inLinked ? sock.color : C.elevated,
2969
- boxShadow: inLinked
2970
- ? (fxLevel === 'vivid' ? '0 0 6px ' + sock.color : '0 0 0 2px ' + C.elevated)
2971
- : '0 0 0 3px transparent',
2972
- },
2973
- title: t('tipSocketOut'),
2974
- onMouseDown: (e) => onInputDown(e, node.id, sock.id),
2975
- onMouseUp: (e) => onInputUp(e, node.id, sock.id),
2976
- }),
3724
+ h('span', { style: { ...S.rowLabel, position: 'absolute', right: '12px' } }, sock.label),
2977
3725
  h('div', {
2978
3726
  style: {
2979
3727
  ...S.socket,
@@ -2996,7 +3744,7 @@ window.__ModuleLoader__.load({
2996
3744
  // The canvas grows with its nodes so links past the original size are
2997
3745
  // still painted instead of being clipped by the SVG viewport.
2998
3746
  const contentW = Math.max(CONTENT_W, WORLD_PAD + Math.max(0, ...nodes.map((n) => n.x + NODE_W)) + 400);
2999
- const contentH = Math.max(CONTENT_H, WORLD_PAD + Math.max(0, ...nodes.map((n) => n.y + NODE_H)) + 400);
3747
+ const contentH = Math.max(CONTENT_H, WORLD_PAD + Math.max(0, ...nodes.map((n) => n.y + nodeHeight(n))) + 400);
3000
3748
 
3001
3749
  const hitTest = (m) => {
3002
3750
  const left = Math.min(m.x1, m.x2);
@@ -3004,7 +3752,7 @@ window.__ModuleLoader__.load({
3004
3752
  const top = Math.min(m.y1, m.y2);
3005
3753
  const bottom = Math.max(m.y1, m.y2);
3006
3754
  return nodes
3007
- .filter((n) => n.x + NODE_W >= left && n.x <= right && n.y + NODE_H >= top && n.y <= bottom)
3755
+ .filter((n) => n.x + NODE_W >= left && n.x <= right && n.y + nodeHeight(n) >= top && n.y <= bottom)
3008
3756
  .map((n) => n.id);
3009
3757
  };
3010
3758
 
@@ -3017,6 +3765,7 @@ window.__ModuleLoader__.load({
3017
3765
  h('div', { style: S.toolbar },
3018
3766
  h('button', { style: S.btn, onClick: () => addNode('agent'), type: 'button' }, t('addAgent')),
3019
3767
  h('button', { style: S.btn, onClick: () => addNode('lead'), type: 'button' }, t('addLead')),
3768
+ h('button', { style: S.btn, onClick: () => addNode('condition'), type: 'button' }, t('addCond')),
3020
3769
  h('span', { style: S.toolSep }),
3021
3770
  h('button', { style: S.btn, onClick: undo, type: 'button', title: t('tipUndo') }, t('undo')),
3022
3771
  h('button', {
@@ -3053,9 +3802,25 @@ window.__ModuleLoader__.load({
3053
3802
  type: 'button',
3054
3803
  title: t('tipMore'),
3055
3804
  onMouseDown: (e) => e.stopPropagation(),
3056
- onClick: () => setMenuOpen(!menuOpen),
3805
+ onClick: (e) => {
3806
+ const next = !menuOpen;
3807
+ if (next) {
3808
+ setPresetOpen(null);
3809
+ const rootRect = rootElRef.current && rootElRef.current.getBoundingClientRect();
3810
+ const btnRect = e.currentTarget && e.currentTarget.getBoundingClientRect();
3811
+ setMenuAlign(dropdownAlign(btnRect, rootRect, 204));
3812
+ }
3813
+ setMenuOpen(next);
3814
+ },
3057
3815
  }, '⋯'),
3058
- menuOpen && h('div', { style: S.moreMenu, onMouseDown: (e) => e.stopPropagation() },
3816
+ menuOpen && h('div', {
3817
+ style: {
3818
+ ...S.moreMenu,
3819
+ left: menuAlign === 'left' ? 0 : 'auto',
3820
+ right: menuAlign === 'left' ? 'auto' : 0,
3821
+ },
3822
+ onMouseDown: (e) => e.stopPropagation(),
3823
+ },
3059
3824
  h('div', {
3060
3825
  style: S.moreRow,
3061
3826
  onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
@@ -3136,47 +3901,64 @@ window.__ModuleLoader__.load({
3136
3901
  ),
3137
3902
  ),
3138
3903
  h('div', { style: S.presetBar },
3139
- h('div', { style: S.presetRowTop },
3140
- h('input', {
3141
- style: S.presetInput,
3142
- value: presetName,
3143
- placeholder: t('presetName'),
3144
- onMouseDown: (e) => e.stopPropagation(),
3145
- onChange: (e) => setPresetName(e.target.value),
3146
- onKeyDown: (e) => { if (e.key === 'Enter') savePresetNow(); },
3147
- }),
3148
- h('button', { style: S.btn, onClick: savePresetNow, type: 'button', title: t('tipSave') }, t('save')),
3149
- (() => {
3150
- const names = Object.keys(presets);
3151
- return h('button', {
3152
- style: S.btn,
3153
- onClick: () => setPresetOpen(presetOpen === 'menu' ? null : 'menu'),
3154
- type: 'button',
3155
- title: t('tipPresets'),
3156
- }, t('presets') + (names.length ? ' (' + names.length + ')' : ''));
3157
- })(),
3158
- ),
3159
- // Feedback for saving / loading / syncing sits right under the name field.
3160
- h('span', { style: S.status },
3161
- status || (enabled ? (dirty ? t('unsaved') : t('synced')) : '')),
3904
+ (() => {
3905
+ const feedback = status || (enabled ? (dirty ? t('unsaved') : t('synced')) : '');
3906
+ return feedback ? h('span', { style: S.status, title: feedback }, feedback) : null;
3907
+ })(),
3908
+ (() => {
3909
+ const names = Object.keys(presets);
3910
+ return h('button', {
3911
+ style: S.btn,
3912
+ onClick: (e) => {
3913
+ const next = presetOpen === 'menu' ? null : 'menu';
3914
+ if (next) {
3915
+ setMenuOpen(false);
3916
+ const rootRect = rootElRef.current && rootElRef.current.getBoundingClientRect();
3917
+ const btnRect = e.currentTarget && e.currentTarget.getBoundingClientRect();
3918
+ setPresetAlign(dropdownAlign(btnRect, rootRect, 248));
3919
+ }
3920
+ setPresetOpen(next);
3921
+ },
3922
+ type: 'button',
3923
+ title: t('tipPresets'),
3924
+ }, t('presets') + (names.length ? ' (' + names.length + ')' : ''));
3925
+ })(),
3162
3926
  presetOpen === 'menu' && (() => {
3163
3927
  const names = Object.keys(presets);
3164
3928
  const templates = builtinTemplates(lang);
3165
- return h('div', { style: S.presetMenu, onMouseDown: (e) => e.stopPropagation() },
3929
+ return h('div', {
3930
+ style: {
3931
+ ...S.presetMenu,
3932
+ left: presetAlign === 'left' ? 0 : 'auto',
3933
+ right: presetAlign === 'left' ? 'auto' : 0,
3934
+ },
3935
+ onMouseDown: (e) => e.stopPropagation(),
3936
+ },
3937
+ h('div', { style: S.presetSaveBox },
3938
+ h('div', { style: S.presetSaveTitle }, t('presetSaveTitle')),
3939
+ h('div', { style: S.presetSaveRow },
3940
+ h('input', {
3941
+ style: S.presetInput,
3942
+ value: presetName,
3943
+ placeholder: t('presetNamePh'),
3944
+ onMouseDown: (e) => e.stopPropagation(),
3945
+ onChange: (e) => setPresetName(e.target.value),
3946
+ onKeyDown: (e) => { if (e.key === 'Enter') savePresetNow(); },
3947
+ }),
3948
+ h('button', {
3949
+ style: { ...S.btn, padding: '4px 8px', fontSize: '11px' },
3950
+ onClick: savePresetNow,
3951
+ type: 'button',
3952
+ title: t('tipSave'),
3953
+ }, t('save')),
3954
+ ),
3955
+ ),
3166
3956
  h('div', {
3167
3957
  style: { ...S.presetRow, color: C.accent, fontWeight: 500, borderBottom: '1px solid ' + C.border, marginBottom: '4px', paddingBottom: '6px', borderRadius: '4px 4px 0 0' },
3168
3958
  onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3169
3959
  onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
3170
3960
  onClick: () => clearCanvas(),
3171
3961
  }, h('span', { style: S.presetRowText }, t('newBlankCanvas'))),
3172
- h('div', { style: S.menuHead }, t('builtinTemplates')),
3173
- templates.map((tpl) => h('div', {
3174
- key: tpl.id,
3175
- style: S.presetRow,
3176
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3177
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
3178
- onClick: () => applyTemplate(tpl),
3179
- }, h('span', { style: S.presetRowText, title: tpl.name }, tpl.name))),
3180
3962
  h('div', { style: S.menuHead }, t('myPresets')),
3181
3963
  names.length
3182
3964
  ? names.map((name) => h('div', {
@@ -3189,6 +3971,14 @@ window.__ModuleLoader__.load({
3189
3971
  h('button', { style: S.presetDel, type: 'button', title: t('del'), onClick: () => deletePreset(name) }, '×'),
3190
3972
  ))
3191
3973
  : h('div', { style: S.presetEmpty }, t('presetEmpty')),
3974
+ h('div', { style: S.menuHead }, t('builtinTemplates')),
3975
+ templates.map((tpl) => h('div', {
3976
+ key: tpl.id,
3977
+ style: S.presetRow,
3978
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3979
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
3980
+ onClick: () => applyTemplate(tpl),
3981
+ }, h('span', { style: S.presetRowText, title: tpl.name }, tpl.name))),
3192
3982
  );
3193
3983
  })(),
3194
3984
  ),
@@ -3233,24 +4023,36 @@ window.__ModuleLoader__.load({
3233
4023
  }),
3234
4024
  h('span', null, (enabled ? t('enabled') : t('disabled')).replace(/^[●○]\s*/, '')),
3235
4025
  ),
3236
- addMenu && h('div', {
3237
- style: { ...S.addMenu, left: addMenu.sx + 'px', top: addMenu.sy + 'px' },
3238
- onMouseDown: (e) => e.stopPropagation(),
3239
- },
3240
- h('div', { style: S.addMenuHead }, t('addMenuTitle')),
3241
- h('div', {
3242
- style: S.addMenuRow,
3243
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3244
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
3245
- onClick: () => addNode('agent', { x: addMenu.wx, y: addMenu.wy }),
3246
- }, h('span', null, t('addAgent')), h('span', { style: S.addMenuHint }, '1')),
3247
- h('div', {
3248
- style: S.addMenuRow,
3249
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3250
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
3251
- onClick: () => addNode('lead', { x: addMenu.wx, y: addMenu.wy }),
3252
- }, h('span', null, t('addLead')), h('span', { style: S.addMenuHint }, '2')),
3253
- ),
4026
+ addMenu && (() => {
4027
+ const lf = addMenu.linkFrom || null;
4028
+ const srcNode = lf && lf.fromId ? nodeById.get(lf.fromId) : null;
4029
+ const compat = lf ? compatibleTargetsForWire(srcNode, lf.type) : { agent: true, lead: true, condition: true, leadBlockedReason: '' };
4030
+ return h('div', {
4031
+ style: { ...S.addMenu, left: addMenu.sx + 'px', top: addMenu.sy + 'px' },
4032
+ onMouseDown: (e) => e.stopPropagation(),
4033
+ },
4034
+ h('div', { style: S.addMenuHead }, lf ? t('addMenuLinkTitle') : t('addMenuTitle')),
4035
+ h('div', {
4036
+ style: S.addMenuRow,
4037
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
4038
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
4039
+ onClick: () => addNode('agent', { x: addMenu.wx, y: addMenu.wy }, lf),
4040
+ }, h('span', null, t('addAgent')), h('span', { style: S.addMenuHint }, '1')),
4041
+ h('div', {
4042
+ style: compat.lead ? S.addMenuRow : S.addMenuRowDisabled,
4043
+ title: compat.lead ? undefined : t(compat.leadBlockedReason || 'leadToLeadBlocked'),
4044
+ onMouseEnter: (e) => { if (compat.lead) e.currentTarget.style.background = C.hover; },
4045
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
4046
+ onClick: () => { if (compat.lead) addNode('lead', { x: addMenu.wx, y: addMenu.wy }, lf); },
4047
+ }, h('span', null, t('addLead')), h('span', { style: S.addMenuHint }, '2')),
4048
+ h('div', {
4049
+ style: S.addMenuRow,
4050
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
4051
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
4052
+ onClick: () => addNode('condition', { x: addMenu.wx, y: addMenu.wy }, lf),
4053
+ }, h('span', null, t('addCond')), h('span', { style: S.addMenuHint }, '3')),
4054
+ );
4055
+ })(),
3254
4056
  h('div', {
3255
4057
  ref: canvasElRef,
3256
4058
  style: {
@@ -3286,15 +4088,17 @@ window.__ModuleLoader__.load({
3286
4088
  strokeWidth: 1,
3287
4089
  strokeDasharray: '4 3',
3288
4090
  }),
3289
- pending && (() => {
3290
- const color = (SOCKET_TYPES.find((t) => t.id === pending.type) || SOCKET_TYPES[0]).color;
3291
- const d = 'M ' + (pending.sx + WORLD_PAD) + ' ' + (pending.sy + WORLD_PAD) + ' L ' + (pending.x + WORLD_PAD) + ' ' + (pending.y + WORLD_PAD);
4091
+ (pending || (addMenu && addMenu.linkFrom)) && (() => {
4092
+ const wire = pending || addMenu.linkFrom;
4093
+ const color = wire.color || (SOCKET_TYPES.find((t) => t.id === wire.type) || SOCKET_TYPES[0]).color;
4094
+ const d = 'M ' + (wire.sx + WORLD_PAD) + ' ' + (wire.sy + WORLD_PAD) + ' L ' + (wire.x + WORLD_PAD) + ' ' + (wire.y + WORLD_PAD);
3292
4095
  return h('path', { d, stroke: color, strokeWidth: 2, strokeDasharray: '4 4', fill: 'none' });
3293
4096
  })(),
3294
4097
  ),
3295
4098
  nodes.map((node) => {
3296
4099
  const isEntry = node.id === 'lead';
3297
4100
  const isLeadKind = node.kind === 'lead';
4101
+ const isCondKind = node.kind === 'condition';
3298
4102
  const roleInput = (style) => h('div', { style },
3299
4103
  h('span', { style: S.fieldLabel }, t('role')),
3300
4104
  h('input', {
@@ -3334,21 +4138,28 @@ window.__ModuleLoader__.load({
3334
4138
  const topBarBg = (isRunning || isLeadReady) && fxLevel === 'vivid'
3335
4139
  ? (isLeadKind
3336
4140
  ? 'linear-gradient(90deg, #2f81f7 0%, #79c0ff 50%, #2f81f7 100%)'
3337
- : 'linear-gradient(90deg, #2f81f7 0%, #58d580 50%, #2f81f7 100%)')
3338
- : (isFailed ? '#e5534b' : (isLeadKind ? '#2f81f7' : '#3fb950'));
4141
+ : (isCondKind
4142
+ ? 'linear-gradient(90deg, #d29922 0%, #f2cc60 50%, #d29922 100%)'
4143
+ : 'linear-gradient(90deg, #2f81f7 0%, #58d580 50%, #2f81f7 100%)'))
4144
+ : (isFailed ? '#e5534b' : (isLeadKind ? '#2f81f7' : (isCondKind ? '#d29922' : '#3fb950')));
4145
+ const isPruned = enabled && prunedSet.has(node.id);
4146
+ const condDecision = isCondKind ? (decisionsById[node.id] || null) : null;
4147
+ const verdictInfo = condDecision ? conditionVerdictSummary(condDecision, lang) : null;
3339
4148
  return h('div', {
3340
4149
  key: node.id,
3341
4150
  'data-node': node.id,
3342
4151
  className: nodeClass,
3343
4152
  style: {
3344
4153
  ...S.node,
4154
+ height: nodeHeight(node),
3345
4155
  left: node.x + WORLD_PAD,
3346
4156
  top: node.y + WORLD_PAD,
3347
4157
  ...(isLeadKind ? S.leadNode : null),
3348
- ...(isInactive ? S.orphanNode : null),
4158
+ ...(isInactive || isPruned ? S.orphanNode : null),
3349
4159
  ...(stateStyle || null),
4160
+ ...(decisionViewFor === node.id ? { zIndex: 40 } : null),
3350
4161
  },
3351
- title: isOrphan ? t('orphanTip') : (isSoloLead ? t('tipSoloLead') : (isDeadEnd ? t('tipDeadEnd') : undefined)),
4162
+ title: isPruned ? t('tipPruned') : (isOrphan ? t('orphanTip') : (isSoloLead ? t('tipSoloLead') : (isDeadEnd ? t('tipDeadEnd') : undefined))),
3352
4163
  onMouseDown: (e) => onNodeDown(e, node.id),
3353
4164
  },
3354
4165
  h('div', {
@@ -3360,67 +4171,117 @@ window.__ModuleLoader__.load({
3360
4171
  }),
3361
4172
  h('div', { style: S.nodeHeader }),
3362
4173
  h('div', { style: S.bandDivider }),
3363
- isDeadEnd && h('div', {
3364
- style: S.warnChip,
3365
- title: t('tipDeadEnd'),
3366
- onMouseDown: (e) => e.stopPropagation(),
3367
- }, '⚠ ', t('stDeadEnd')),
3368
- (() => {
3369
- const latestRun = !isLeadKind ? runsById[node.id] : null;
3370
- const statusColor = isLeadReady ? '#2f81f7'
3371
- : isLeadDone ? '#3fb950'
3372
- : isLeadKind ? C.dim
3373
- : nodeStatus === 'running' ? '#2f81f7'
3374
- : nodeStatus === 'failed' ? '#e5534b'
3375
- : nodeStatus === 'done' ? '#3fb950' : C.dim;
3376
- const statusTint = isLeadReady || nodeStatus === 'running'
3377
- ? 'rgba(47,129,247,0.14)'
3378
- : nodeStatus === 'failed'
3379
- ? 'rgba(229,83,75,0.14)'
3380
- : isDone
4174
+ isEntry
4175
+ ? (() => {
4176
+ const waitingLead = runState
4177
+ ? (runState.waitingLead || null)
4178
+ : (leadReadyIds.size > 0 ? { id: Array.from(leadReadyIds)[0] } : null);
4179
+ const btn = entryRunButtonState({
4180
+ enabled,
4181
+ task: node.task || '',
4182
+ sessionRunning,
4183
+ waitingLead,
4184
+ triggering: runTriggering,
4185
+ lang,
4186
+ });
4187
+ const isReady = btn.state === 'ready';
4188
+ const isRun = btn.state === 'running';
4189
+ const isWait = btn.state === 'waiting';
4190
+ const color = isReady ? '#3fb950' : (isRun ? '#2f81f7' : (isWait ? '#d29922' : C.dim));
4191
+ const bg = isReady
3381
4192
  ? 'rgba(63,185,80,0.14)'
3382
- : 'transparent';
3383
- const statusLabel = isOrphan ? t('stOrphan')
3384
- : isSoloLead ? t('stSoloLead')
3385
- : isLeadReady ? t('stLeadReady')
3386
- : isLeadDone ? t('stDone')
3387
- : isLeadKind ? t('stLead')
3388
- : nodeStatus === 'running' ? t('stRunning')
3389
- : nodeStatus === 'failed' ? t('stFailed')
3390
- : nodeStatus === 'done' ? t('stDone') : t('stPending');
3391
- const glyph = nodeStatus === 'running'
3392
- ? h('span', {
3393
- className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
3394
- style: { width: '6px', height: '6px', borderRadius: '50%', background: statusColor, flex: '0 0 auto' },
3395
- })
3396
- : isLeadReady ? h('span', { className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined }, '⏸')
3397
- : isDone ? '✓'
3398
- : nodeStatus === 'failed' ? '✕' : null;
3399
- if (latestRun) {
3400
- const label = enabled ? statusLabel : t('openChat');
3401
- const color = enabled ? statusColor : C.accent;
3402
- const bg = enabled && statusTint !== 'transparent' ? statusTint : C.elevated;
3403
- return h('button', {
3404
- type: 'button',
3405
- style: { ...S.statusBtn, color, background: bg, borderColor: color === C.dim ? C.border : color },
3406
- title: t('tipOpenRun'),
4193
+ : (isRun ? 'rgba(47,129,247,0.14)' : (isWait ? 'rgba(210,153,34,0.14)' : C.elevated));
4194
+ const borderColor = isReady
4195
+ ? 'rgba(63,185,80,0.6)'
4196
+ : (isRun ? 'rgba(47,129,247,0.6)' : (isWait ? 'rgba(210,153,34,0.6)' : C.border));
4197
+ return h('button', {
4198
+ type: 'button',
4199
+ disabled: btn.disabled,
4200
+ style: {
4201
+ ...S.statusBtn,
4202
+ color,
4203
+ background: bg,
4204
+ borderColor,
4205
+ opacity: btn.state === 'disabled' ? 0.55 : 1,
4206
+ cursor: btn.disabled ? 'not-allowed' : 'pointer',
4207
+ fontWeight: isReady ? 600 : 500,
4208
+ },
4209
+ title: btn.title,
4210
+ onMouseDown: (e) => e.stopPropagation(),
4211
+ onMouseEnter: (e) => { if (!btn.disabled) e.currentTarget.style.background = 'rgba(63,185,80,0.24)'; },
4212
+ onMouseLeave: (e) => { e.currentTarget.style.background = bg; },
4213
+ onClick: (e) => { e.stopPropagation(); if (!btn.disabled) runFromEntry(); },
4214
+ },
4215
+ isRun && h('span', {
4216
+ className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
4217
+ style: { width: '6px', height: '6px', borderRadius: '50%', background: color, flex: '0 0 auto' },
4218
+ }),
4219
+ btn.label,
4220
+ );
4221
+ })()
4222
+ : isDeadEnd
4223
+ ? h('div', {
4224
+ style: S.warnChip,
4225
+ title: t('tipDeadEnd'),
3407
4226
  onMouseDown: (e) => e.stopPropagation(),
3408
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3409
- onMouseLeave: (e) => { e.currentTarget.style.background = bg; },
3410
- onClick: (e) => { e.stopPropagation(); openNodeSession(node); },
3411
- }, enabled ? glyph : null, label, ' ↗');
3412
- }
3413
- if (!enabled) return null;
3414
- return h('div', {
3415
- style: {
3416
- ...S.statusChip,
3417
- color: statusColor,
3418
- background: statusTint,
3419
- border: statusTint !== 'transparent' ? ('1px solid ' + statusColor) : 'none',
3420
- },
3421
- title: isLeadReady ? t('tipLeadReady') : (isLeadKind ? t('tipLead') : (isOrphan ? t('tipOrphan') : t('tipStatus'))),
3422
- }, glyph, statusLabel);
3423
- })(),
4227
+ }, '⚠ ', t('stDeadEnd'))
4228
+ : (() => {
4229
+ const latestRun = !isLeadKind ? runsById[node.id] : null;
4230
+ const statusColor = isLeadReady ? '#2f81f7'
4231
+ : isLeadDone ? '#3fb950'
4232
+ : isLeadKind ? C.dim
4233
+ : nodeStatus === 'running' ? '#2f81f7'
4234
+ : nodeStatus === 'failed' ? '#e5534b'
4235
+ : nodeStatus === 'done' ? '#3fb950' : C.dim;
4236
+ const statusTint = isLeadReady || nodeStatus === 'running'
4237
+ ? 'rgba(47,129,247,0.14)'
4238
+ : nodeStatus === 'failed'
4239
+ ? 'rgba(229,83,75,0.14)'
4240
+ : isDone
4241
+ ? 'rgba(63,185,80,0.14)'
4242
+ : 'transparent';
4243
+ const statusLabel = isPruned ? t('stPruned')
4244
+ : isOrphan ? t('stOrphan')
4245
+ : isSoloLead ? t('stSoloLead')
4246
+ : isLeadReady ? t('stLeadReady')
4247
+ : isLeadDone ? t('stDone')
4248
+ : isLeadKind ? t('stLead')
4249
+ : nodeStatus === 'running' ? t('stRunning')
4250
+ : nodeStatus === 'failed' ? t('stFailed')
4251
+ : nodeStatus === 'done' ? t('stDone') : t('stPending');
4252
+ const glyph = nodeStatus === 'running'
4253
+ ? h('span', {
4254
+ className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
4255
+ style: { width: '6px', height: '6px', borderRadius: '50%', background: statusColor, flex: '0 0 auto' },
4256
+ })
4257
+ : isLeadReady ? h('span', { className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined }, '⏸')
4258
+ : isDone ? '✓'
4259
+ : nodeStatus === 'failed' ? '✕' : null;
4260
+ if (latestRun) {
4261
+ const label = enabled ? statusLabel : t('openChat');
4262
+ const color = enabled ? statusColor : C.accent;
4263
+ const bg = enabled && statusTint !== 'transparent' ? statusTint : C.elevated;
4264
+ return h('button', {
4265
+ type: 'button',
4266
+ style: { ...S.statusBtn, color, background: bg, borderColor: color === C.dim ? C.border : color },
4267
+ title: t('tipOpenRun'),
4268
+ onMouseDown: (e) => e.stopPropagation(),
4269
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
4270
+ onMouseLeave: (e) => { e.currentTarget.style.background = bg; },
4271
+ onClick: (e) => { e.stopPropagation(); openNodeSession(node); },
4272
+ }, enabled ? glyph : null, label, ' ↗');
4273
+ }
4274
+ if (!enabled) return null;
4275
+ return h('div', {
4276
+ style: {
4277
+ ...S.statusChip,
4278
+ color: statusColor,
4279
+ background: statusTint,
4280
+ border: statusTint !== 'transparent' ? ('1px solid ' + statusColor) : 'none',
4281
+ },
4282
+ title: isLeadReady ? t('tipLeadReady') : (isLeadKind ? t('tipLead') : (isOrphan ? t('tipOrphan') : t('tipStatus'))),
4283
+ }, glyph, statusLabel);
4284
+ })(),
3424
4285
  isEntry
3425
4286
  ? h('div', { style: S.titleReadonly }, t('leadThis'))
3426
4287
  : h('input', {
@@ -3432,7 +4293,16 @@ window.__ModuleLoader__.load({
3432
4293
  }),
3433
4294
  isEntry
3434
4295
  ? h(React.Fragment, null,
3435
- h('div', { style: S.leadLabel }, h('span', { style: S.fieldLabel }, t('task'))),
4296
+ h('div', { style: S.leadLabel },
4297
+ h('span', { style: S.fieldLabel }, t('task')),
4298
+ h('button', {
4299
+ type: 'button',
4300
+ style: S.condAddBtn,
4301
+ title: t('tipExpandEdit'),
4302
+ onMouseDown: (e) => e.stopPropagation(),
4303
+ onClick: () => setRoleEditFor(roleEditFor === node.id ? null : node.id),
4304
+ }, '⤢'),
4305
+ ),
3436
4306
  h('textarea', {
3437
4307
  style: S.task,
3438
4308
  value: node.task || '',
@@ -3441,10 +4311,31 @@ window.__ModuleLoader__.load({
3441
4311
  onFocus: () => setSelectedIds([node.id]),
3442
4312
  onChange: (e) => updateNode(node.id, { task: e.target.value }),
3443
4313
  }),
4314
+ roleEditFor === node.id && h('div', {
4315
+ style: S.rolePopover,
4316
+ onMouseDown: (e) => e.stopPropagation(),
4317
+ },
4318
+ h('textarea', {
4319
+ style: S.roleArea,
4320
+ value: node.task || '',
4321
+ placeholder: t('taskPh'),
4322
+ autoFocus: true,
4323
+ onChange: (e) => updateNode(node.id, { task: e.target.value }),
4324
+ }),
4325
+ ),
3444
4326
  )
3445
4327
  : isLeadKind
3446
4328
  ? h(React.Fragment, null,
3447
- h('div', { style: S.leadLabel }, h('span', { style: S.fieldLabel }, t('role'))),
4329
+ h('div', { style: S.leadLabel },
4330
+ h('span', { style: S.fieldLabel }, t('role')),
4331
+ h('button', {
4332
+ type: 'button',
4333
+ style: S.condAddBtn,
4334
+ title: t('tipExpandEdit'),
4335
+ onMouseDown: (e) => e.stopPropagation(),
4336
+ onClick: () => setRoleEditFor(roleEditFor === node.id ? null : node.id),
4337
+ }, '⤢'),
4338
+ ),
3448
4339
  h('textarea', {
3449
4340
  style: S.task,
3450
4341
  value: node.role || '',
@@ -3453,8 +4344,82 @@ window.__ModuleLoader__.load({
3453
4344
  onFocus: () => setSelectedIds([node.id]),
3454
4345
  onChange: (e) => updateNode(node.id, { role: e.target.value }),
3455
4346
  }),
4347
+ roleEditFor === node.id && h('div', {
4348
+ style: S.rolePopover,
4349
+ onMouseDown: (e) => e.stopPropagation(),
4350
+ },
4351
+ h('textarea', {
4352
+ style: S.roleArea,
4353
+ value: node.role || '',
4354
+ placeholder: t('rolePhLead'),
4355
+ autoFocus: true,
4356
+ onChange: (e) => updateNode(node.id, { role: e.target.value }),
4357
+ }),
4358
+ ),
3456
4359
  )
3457
- : h(React.Fragment, null,
4360
+ : isCondKind
4361
+ ? h(React.Fragment, null,
4362
+ h('div', { style: S.fieldModel },
4363
+ h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('model')),
4364
+ modelControl(node),
4365
+ ),
4366
+ h('div', { style: S.fieldReason },
4367
+ h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('reason')),
4368
+ reasoningControl(node),
4369
+ ),
4370
+ h('div', { style: S.fieldScope },
4371
+ h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('fallbackModel')),
4372
+ fallbackControl(node),
4373
+ ),
4374
+ h('div', { style: S.condLabelRow },
4375
+ h('span', { style: S.fieldLabel }, t('condLabel')),
4376
+ h('div', { style: S.condBtnGroup },
4377
+ h('button', {
4378
+ type: 'button',
4379
+ style: node.multiMatch ? S.condModeBtnOn : S.condAddBtn,
4380
+ title: t('tipMatchMode'),
4381
+ onMouseDown: (e) => e.stopPropagation(),
4382
+ onClick: () => updateNode(node.id, { multiMatch: !node.multiMatch }),
4383
+ }, node.multiMatch ? t('matchMulti') : t('matchSingle')),
4384
+ h('button', {
4385
+ type: 'button',
4386
+ style: S.condAddBtn,
4387
+ title: t('tipExpandEdit'),
4388
+ onMouseDown: (e) => e.stopPropagation(),
4389
+ onClick: () => setRoleEditFor(roleEditFor === node.id ? null : node.id),
4390
+ }, '⤢'),
4391
+ conditionBranchesForUI(node, lang).length < 16 && h('button', {
4392
+ type: 'button',
4393
+ style: S.condAddBtn,
4394
+ onMouseDown: (e) => e.stopPropagation(),
4395
+ onMouseEnter: (e) => { e.currentTarget.style.color = C.text; e.currentTarget.style.borderColor = C.accent; },
4396
+ onMouseLeave: (e) => { e.currentTarget.style.color = C.dim; e.currentTarget.style.borderColor = C.border; },
4397
+ onClick: () => addConditionBranch(node),
4398
+ }, t('addBranch')),
4399
+ ),
4400
+ ),
4401
+ h('textarea', {
4402
+ style: S.condArea,
4403
+ value: node.role || '',
4404
+ placeholder: t('condPh'),
4405
+ onMouseDown: (e) => e.stopPropagation(),
4406
+ onFocus: () => setSelectedIds([node.id]),
4407
+ onChange: (e) => updateNode(node.id, { role: e.target.value }),
4408
+ }),
4409
+ roleEditFor === node.id && h('div', {
4410
+ style: S.rolePopover,
4411
+ onMouseDown: (e) => e.stopPropagation(),
4412
+ },
4413
+ h('textarea', {
4414
+ style: S.roleArea,
4415
+ value: node.role || '',
4416
+ placeholder: t('condPh'),
4417
+ autoFocus: true,
4418
+ onChange: (e) => updateNode(node.id, { role: e.target.value }),
4419
+ }),
4420
+ ),
4421
+ )
4422
+ : h(React.Fragment, null,
3458
4423
  h('div', { style: S.fieldModel },
3459
4424
  h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('model')),
3460
4425
  modelControl(node),
@@ -3477,15 +4442,29 @@ window.__ModuleLoader__.load({
3477
4442
  ),
3478
4443
  h('div', { style: S.fieldRole },
3479
4444
  h('span', { style: lang === 'en' ? S.fieldLabelEn : S.fieldLabel }, t('role')),
3480
- h('button', {
3481
- style: S.selectBtn,
3482
- type: 'button',
3483
- title: t('rolePhAgent'),
3484
- onMouseDown: (e) => e.stopPropagation(),
3485
- onClick: () => setRoleEditFor(roleEditFor === node.id ? null : node.id),
3486
- },
3487
- h('span', { style: S.selectText }, node.role || t('rolePhAgent')),
3488
- h('span', { style: S.caret }, '✎'),
4445
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '4px', flex: '1 1 auto', minWidth: 0 } },
4446
+ h('input', {
4447
+ style: {
4448
+ flex: '1 1 auto', minWidth: 0, height: '18px', boxSizing: 'border-box',
4449
+ padding: '0 5px', borderRadius: '4px',
4450
+ border: '1px solid ' + C.border, background: C.base, color: C.text,
4451
+ fontSize: '10px', lineHeight: '14px', outline: 'none', userSelect: 'text',
4452
+ },
4453
+ value: node.role || '',
4454
+ placeholder: t('rolePhAgent'),
4455
+ onMouseDown: (e) => e.stopPropagation(),
4456
+ onFocus: () => setSelectedIds([node.id]),
4457
+ onChange: (e) => updateNode(node.id, { role: e.target.value }),
4458
+ }),
4459
+ h('button', {
4460
+ style: { ...S.condAddBtn, height: '18px', padding: '0 5px', flex: '0 0 auto' },
4461
+ type: 'button',
4462
+ title: t('tipExpandEdit'),
4463
+ onMouseDown: (e) => e.stopPropagation(),
4464
+ onMouseEnter: (e) => { e.currentTarget.style.color = C.text; e.currentTarget.style.borderColor = C.accent; },
4465
+ onMouseLeave: (e) => { e.currentTarget.style.color = C.dim; e.currentTarget.style.borderColor = C.border; },
4466
+ onClick: () => setRoleEditFor(roleEditFor === node.id ? null : node.id),
4467
+ }, '⤢'),
3489
4468
  ),
3490
4469
  ),
3491
4470
  roleEditFor === node.id && h('div', {
@@ -3507,6 +4486,44 @@ window.__ModuleLoader__.load({
3507
4486
  onMouseDown: (e) => e.stopPropagation(),
3508
4487
  onClick: () => deleteNode(node.id),
3509
4488
  }, '×'),
4489
+ verdictInfo && h('button', {
4490
+ type: 'button',
4491
+ style: {
4492
+ ...S.verdictChip,
4493
+ color: verdictInfo.tone === 'failed' ? '#e5534b' : (verdictInfo.tone === 'warn' ? '#d29922' : '#3fb950'),
4494
+ borderColor: verdictInfo.tone === 'failed' ? 'rgba(229,83,75,0.65)' : (verdictInfo.tone === 'warn' ? 'rgba(210,153,34,0.65)' : 'rgba(63,185,80,0.55)'),
4495
+ },
4496
+ title: (condDecision && condDecision.reason ? condDecision.reason + '\n' : '') + t('tipVerdictChip'),
4497
+ onMouseDown: (e) => e.stopPropagation(),
4498
+ onClick: (e) => {
4499
+ e.stopPropagation();
4500
+ setDecisionViewFor(decisionViewFor === node.id ? null : node.id);
4501
+ },
4502
+ }, verdictInfo.text),
4503
+ decisionViewFor === node.id && condDecision && h('div', {
4504
+ style: S.verdictPopover,
4505
+ onMouseDown: (e) => e.stopPropagation(),
4506
+ },
4507
+ h('div', {
4508
+ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '5px', fontWeight: 600, fontSize: '11px' },
4509
+ },
4510
+ h('span', null, t('verdictReasonTitle')),
4511
+ h('button', {
4512
+ type: 'button',
4513
+ style: { background: 'transparent', border: 'none', color: C.dim, cursor: 'pointer', fontSize: '12px', padding: '0 2px' },
4514
+ onClick: () => setDecisionViewFor(null),
4515
+ }, '×'),
4516
+ ),
4517
+ Array.isArray(condDecision.branchLabels) && condDecision.branchLabels.length > 0 && h('div', {
4518
+ style: { fontSize: '10px', color: '#3fb950', marginBottom: '4px' },
4519
+ }, t('verdictMatched') + condDecision.branchLabels.join(' · ')),
4520
+ condDecision.fallbackLead && h('div', {
4521
+ style: { fontSize: '10px', color: '#d29922', marginBottom: '4px' },
4522
+ }, t('verdictFallback') + condDecision.fallbackLead),
4523
+ h('div', {
4524
+ style: { maxHeight: '140px', overflowY: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word', color: C.text, fontSize: '11px' },
4525
+ }, (condDecision.reason && String(condDecision.reason).trim()) || t('verdictNoReason')),
4526
+ ),
3510
4527
  renderBand(node),
3511
4528
  );
3512
4529
  }),
@@ -3545,7 +4562,7 @@ window.__ModuleLoader__.load({
3545
4562
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
3546
4563
  }
3547
4564
  },
3548
- __test: { topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, zoomAroundPoint, scrubZoom, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, distanceToEdge, edgeCurve },
4565
+ __test: { topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, distanceToEdge, edgeCurve, compatibleTargetsForWire, conditionVerdictSummary, entryRunButtonState },
3549
4566
  };
3550
4567
  },
3551
4568
  });