dsh-workflow-canvas 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -83,6 +83,7 @@ Drop a **Condition** node anywhere in the graph to route downstream automaticall
83
83
 
84
84
  - Supports default binary **`Yes / No`**, multi-way **`switch/case`** via **`+ Case`** (e.g. `Pass / Minor Fix / Rewrite`), and **`Single / Multi`** match modes.
85
85
  - Unchosen branches are pruned automatically without spawning; if zero branches match or the condition node itself fails, it never guesses — it skips intermediate branches and hands off to the nearest downstream Lead.
86
+ - Once judged, a compact verdict pill appears right under the condition card (click to inspect the full verdict reason), while unchosen branch edges and skipped nodes dim automatically.
86
87
 
87
88
  ![3-way switch/case conditional routing and automatic branch pruning](docs/images/condition-switch-run.gif)
88
89
 
@@ -90,10 +91,10 @@ Drop a **Condition** node anywhere in the graph to route downstream automaticall
90
91
 
91
92
  ### 5. Enable and run
92
93
 
93
- Press **`● ON`** at the top-left of the canvas, then send your task in chat (while enabled, a per-session runtime context notifies the agent automatically):
94
+ Press **`● ON`** at the top-left of the canvas, then either click **`▶ Run`** directly on the Entry Lead card (when its task is filled) or send your task in chat (while enabled, a per-session runtime context notifies the agent automatically):
94
95
 
95
- - If the entry Lead's task is blank, your chat message is passed as `task`.
96
- - At an intermediate **Lead** node, the canvas shows **`⏸ Ready`** and hands control to chat; once you reply, downstream nodes resume automatically through the final Lead review.
96
+ - If the entry Lead's task is blank, `▶ Run` stays disabled with a hint and you can still send your chat message directly as `task`.
97
+ - At an intermediate **Lead** node, the canvas shows **`⏸ Ready`** (and Entry Lead shows `⏸ Awaiting Lead`) while handing control to chat; once you reply, downstream nodes resume automatically through the final Lead review.
97
98
  - Re-running in the same chat supports `reset: true`; if any node has saved **Memory**, the agent confirms whether to keep memory or clear it (`clearMemory: true`).
98
99
 
99
100
  ![Auto-run enabled canvas, pause at Lead decision, and finish](docs/images/lead-pause-resume.gif)
@@ -119,7 +120,7 @@ Active nodes glow blue with animated flow wires and turn green when done. **Clic
119
120
 
120
121
  | Control / Shortcut | Action |
121
122
  |---|---|
122
- | `Shift+A` | Add a node at the cursor (`1` = Subagent, `2` = Lead, `3` = Condition) |
123
+ | `Shift+A` / Drag-wire drop | Add a node at cursor, or drag from an output socket onto blank canvas to create & auto-connect (`1` Subagent, `2` Lead, `3` Condition) |
123
124
  | Middle-drag / `Space` + left-drag | Pan the canvas |
124
125
  | Wheel / `⊡ Fit` / `100%` pill | Zoom around cursor / fit all nodes / click to reset 100%, drag left-right to scrub zoom |
125
126
  | Marquee drag + `Ctrl+D` / `Delete` | Multi-select move, duplicate (with settings), or batch delete |
package/README.zh.md CHANGED
@@ -83,6 +83,7 @@
83
83
 
84
84
  - 支持默认二分支 **`是 / 否`**、点击 **`+ 分支`** 扩展多路 **`switch/case`**(如 `通过 / 小修 / 重做`),以及 **`单选 / 多选`** 两种匹配模式。
85
85
  - 未命中的分支自动剪枝跳过、不消耗额度;所有分支均未命中或条件节点自身失败时,不擅自乱选,直接转交最近下游 Lead 处理。
86
+ - 判决完成后,条件节点下方会直接显示命中分支标签(点击可查看完整判断理由),未命中的分支连线与被跳过节点自动淡化标示。
86
87
 
87
88
  ![三路 switch/case 条件分支判断与自动剪枝](docs/images/condition-switch-run.gif)
88
89
 
@@ -90,10 +91,10 @@
90
91
 
91
92
  ### 5. 启用与运行
92
93
 
93
- 连好图后,点画布左上角的 **`● 已启用`**,然后在聊天框直接发任务即可(启用状态下插件会按会话自动注入上下文,无需额外提示调用工具):
94
+ 连好图后,点画布左上角的 **`● 已启用`**,既可以在入口 Lead 节点填好任务后直接点左下角的 **`▶ 运行`** 一键起跑,也可以在聊天框直接发任务(启用状态下插件会按会话自动注入上下文,无需额外提示调用工具):
94
95
 
95
- - 入口 Lead 的任务栏可填可不填;留空时,聊天框发出的任务会自动作为 `task` 传入。
96
- - 跑到中间 Lead 时,画布亮起 **`⏸ 待拍板`** 并交回主对话;回复后下游自动续跑到终审完成。
96
+ - 入口 Lead 的任务栏可填可不填;点卡片 **`▶ 运行`** 需已启用且任务非空,留空时也可直接在聊天框发送任务作为 `task` 传入。
97
+ - 跑到中间 Lead 时,画布亮起 **`⏸ 待拍板`**(入口按钮同步变为 `⏸ 等待决策`)并交回主对话;回复后下游自动续跑到终审完成。
97
98
  - 同一对话重跑支持 `reset: true`;若画布含已产生历史会话的记忆节点,Agent 会在重跑前确认保留记忆还是清空记忆(`clearMemory: true`)。
98
99
 
99
100
  ![启用即跑、Lead 暂停拍板与自动续跑交付](docs/images/lead-pause-resume.gif)
@@ -120,7 +121,7 @@
120
121
 
121
122
  | 操作 / 快捷键 | 效果 |
122
123
  |---|---|
123
- | `Shift+A` | 在鼠标位置新建节点(按 `1` 加子代理,`2` 加 Lead,`3` 加条件) |
124
+ | `Shift+A` / 拖线松手 | 在光标处新建节点,或从输出口拖线至空白处松手就地新建并自动连线(`1` 子代理,`2` Lead,`3` 条件) |
124
125
  | 鼠标中键拖拽 / `Space` + 左键拖拽 | 平移画布 |
125
126
  | 滚轮 / `⊡ 全览` / `100%` 按钮 | 光标处缩放 / 一键居中看全图 / 点击回 100%,左右拖可连续缩放 |
126
127
  | 左键框选 + `Ctrl+D` / `Delete` | 批量移动、批量复制(连同参数配置)或批量删除 |
package/client.js CHANGED
@@ -106,7 +106,7 @@ window.__ModuleLoader__.load({
106
106
  addAgent: '+ 子代理', addLead: '+ Lead', addCond: '+ 条件', undo: '↶ 撤销', sync: '↥ 同步',
107
107
  enabled: '● 已启用', disabled: '○ 已禁用', presetName: '预设名', save: '☆ 保存',
108
108
  presets: '☰ 预设', unsaved: '有未同步改动', synced: '已同步',
109
- pickModel: '选择模型', defaultEffort: '默认',
109
+ pickModel: '选择模型', loadingModels: '加载中…', defaultEffort: '默认',
110
110
  leadThis: 'Lead(本对话)',
111
111
  tipSocketOut: '通用输入口(接收 prompt / structured / session / 条件分支);拖出可断开最近一条连线',
112
112
  tipSocketIn: '从这里拖出连线 / 也可以把输入口拖到这里',
@@ -204,6 +204,20 @@ window.__ModuleLoader__.load({
204
204
  duplicatedNodes: '已复制节点',
205
205
  deletedNodes: '已删除节点(可用 ↶ 撤销)',
206
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: '当前宿主不支持从画布直接发起对话,请在聊天框发送消息启动',
207
221
  fxLabel: '视觉效果',
208
222
  fxMinimal: '极简',
209
223
  fxStandard: '标准',
@@ -236,7 +250,7 @@ window.__ModuleLoader__.load({
236
250
  addAgent: '+ Subagent', addLead: '+ Lead', addCond: '+ Condition', undo: '↶ Undo', sync: '↥ Sync',
237
251
  enabled: '● ON', disabled: '○ OFF', presetName: 'Preset name', save: '☆ Save',
238
252
  presets: '☰ Presets', unsaved: 'Unsaved changes', synced: 'Synced',
239
- pickModel: 'Pick a model', defaultEffort: 'default',
253
+ pickModel: 'Pick a model', loadingModels: 'Loading…', defaultEffort: 'default',
240
254
  leadThis: 'Lead (this chat)',
241
255
  tipSocketOut: 'Universal input (accepts prompt / structured / session / branch); drag away to detach latest link',
242
256
  tipSocketIn: 'Drag out to link, or drop an input here',
@@ -334,6 +348,20 @@ window.__ModuleLoader__.load({
334
348
  duplicatedNodes: 'Duplicated nodes',
335
349
  deletedNodes: 'Deleted nodes (use Undo to restore)',
336
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',
337
365
  fxLabel: 'Visual effects',
338
366
  fxMinimal: 'Minimal',
339
367
  fxStandard: 'Standard',
@@ -383,7 +411,9 @@ window.__ModuleLoader__.load({
383
411
  dim: 'var(--dsw-alias-label-tertiary, rgba(140,140,140,0.95))',
384
412
  border: 'var(--dsw-alias-border-l2, rgba(128,128,128,0.4))',
385
413
  raised: 'var(--dsw-alias-bg-layer-1, rgba(128,128,128,0.10))',
386
- elevated: 'var(--dsw-alias-bg-elevated, #2a2b2f)',
414
+ // Chain through host surface tokens before falling back to CSS Canvas so popups
415
+ // stay readable in both light and dark themes (never hardcode a dark hex fallback).
416
+ elevated: 'var(--dsw-alias-bg-elevated, var(--dsw-alias-bg-popover, var(--dsw-alias-bg-layer-2, var(--dsw-alias-bg-base, Canvas))))',
387
417
  base: 'var(--dsw-alias-bg-base, transparent)',
388
418
  hover: 'var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,0.18))',
389
419
  accent: 'var(--dsw-alias-brand-primary, #2f81f7)',
@@ -445,8 +475,8 @@ window.__ModuleLoader__.load({
445
475
  moreBar: { position: 'relative', flex: '0 0 auto' },
446
476
  moreMenu: {
447
477
  position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '190px',
448
- background: C.elevated, border: '1px solid ' + C.border, borderRadius: '6px',
449
- zIndex: 80, padding: '4px', boxShadow: '0 10px 26px rgba(0,0,0,0.45)',
478
+ background: C.elevated, color: C.text, border: '1px solid ' + C.border, borderRadius: '6px',
479
+ zIndex: 80, padding: '4px', boxShadow: '0 10px 26px rgba(0,0,0,0.28)',
450
480
  },
451
481
  moreRow: {
452
482
  padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
@@ -454,8 +484,8 @@ window.__ModuleLoader__.load({
454
484
  },
455
485
  addMenu: {
456
486
  position: 'absolute', minWidth: '164px',
457
- background: C.elevated, border: '1px solid ' + C.border, borderRadius: '7px',
458
- zIndex: 85, padding: '4px', boxShadow: '0 12px 30px rgba(0,0,0,0.5)',
487
+ background: C.elevated, color: C.text, border: '1px solid ' + C.border, borderRadius: '7px',
488
+ zIndex: 85, padding: '4px', boxShadow: '0 12px 30px rgba(0,0,0,0.28)',
459
489
  },
460
490
  addMenuHead: {
461
491
  padding: '4px 8px 3px', fontSize: '10px', color: C.dim,
@@ -466,6 +496,11 @@ window.__ModuleLoader__.load({
466
496
  padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
467
497
  color: C.text, whiteSpace: 'nowrap',
468
498
  },
499
+ addMenuRowDisabled: {
500
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px',
501
+ padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'not-allowed',
502
+ color: C.dim, opacity: 0.45, whiteSpace: 'nowrap',
503
+ },
469
504
  addMenuHint: { fontSize: '10px', color: C.dim },
470
505
  helpOverlay: {
471
506
  position: 'absolute', inset: '0', background: 'rgba(0,0,0,0.45)', zIndex: 90,
@@ -473,8 +508,8 @@ window.__ModuleLoader__.load({
473
508
  },
474
509
  helpCard: {
475
510
  width: '100%', maxWidth: '420px', maxHeight: '100%', overflow: 'auto',
476
- background: C.elevated, border: '1px solid ' + C.border, borderRadius: '8px',
477
- boxShadow: '0 16px 40px rgba(0,0,0,0.5)', padding: '12px',
511
+ background: C.elevated, color: C.text, border: '1px solid ' + C.border, borderRadius: '8px',
512
+ boxShadow: '0 16px 40px rgba(0,0,0,0.32)', padding: '12px',
478
513
  },
479
514
  helpHead: { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' },
480
515
  helpTitle: { flex: '1 1 auto', fontSize: '13px', fontWeight: 600, color: C.text },
@@ -487,9 +522,9 @@ window.__ModuleLoader__.load({
487
522
  presetRowTop: { display: 'flex', alignItems: 'center', gap: '5px' },
488
523
  presetMenu: {
489
524
  position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '236px',
490
- maxHeight: '320px', overflowY: 'auto', background: C.elevated,
525
+ maxHeight: '320px', overflowY: 'auto', background: C.elevated, color: C.text,
491
526
  border: '1px solid ' + C.border, borderRadius: '6px', zIndex: 60, padding: '6px',
492
- boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
527
+ boxShadow: '0 8px 24px rgba(0,0,0,0.28)',
493
528
  },
494
529
  presetSaveBox: {
495
530
  padding: '2px 2px 8px', marginBottom: '6px',
@@ -616,8 +651,8 @@ window.__ModuleLoader__.load({
616
651
  },
617
652
  rolePopover: {
618
653
  position: 'absolute', left: '100%', top: '0', marginLeft: '8px', width: '280px',
619
- background: C.elevated, border: '1px solid ' + C.border, borderRadius: '8px',
620
- boxShadow: '0 10px 26px rgba(0,0,0,0.45)', padding: '8px', zIndex: 70,
654
+ background: C.elevated, color: C.text, border: '1px solid ' + C.border, borderRadius: '8px',
655
+ boxShadow: '0 10px 26px rgba(0,0,0,0.28)', padding: '8px', zIndex: 70,
621
656
  },
622
657
  roleArea: {
623
658
  width: '100%', height: '150px', boxSizing: 'border-box', resize: 'vertical',
@@ -699,13 +734,13 @@ window.__ModuleLoader__.load({
699
734
  caret: { flex: '0 0 auto', color: C.dim, fontSize: '9px' },
700
735
  menu: {
701
736
  position: 'absolute', left: 0, right: 0, top: '100%', marginTop: '4px',
702
- maxHeight: '220px', overflowY: 'auto', background: C.elevated,
737
+ maxHeight: '220px', overflowY: 'auto', background: C.elevated, color: C.text,
703
738
  border: '1px solid ' + C.border, borderRadius: '6px',
704
- boxShadow: '0 8px 24px rgba(0,0,0,0.4)', zIndex: 50, padding: '4px',
739
+ boxShadow: '0 8px 24px rgba(0,0,0,0.28)', zIndex: 50, padding: '4px',
705
740
  },
706
741
  menuRow: {
707
742
  padding: '3px 7px', borderRadius: '4px', fontSize: '10px', cursor: 'pointer',
708
- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
743
+ color: C.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
709
744
  },
710
745
  menuHead: { padding: '6px 8px 2px', fontSize: '10px', color: C.dim, textTransform: 'uppercase', letterSpacing: '0.04em' },
711
746
 
@@ -733,14 +768,127 @@ window.__ModuleLoader__.load({
733
768
  position: 'absolute', left: '2px', top: '10px', bottom: '10px', width: '3px',
734
769
  borderRadius: '2px', zIndex: 3,
735
770
  },
771
+ verdictChip: {
772
+ position: 'absolute', left: '0', top: 'calc(100% + 5px)', maxWidth: NODE_W + 'px',
773
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
774
+ padding: '2px 8px', borderRadius: '999px', fontSize: '10px', lineHeight: '14px',
775
+ background: C.elevated, border: '1px solid ' + C.border, color: C.text,
776
+ cursor: 'pointer', userSelect: 'none', zIndex: 12,
777
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
778
+ boxShadow: '0 4px 12px rgba(0,0,0,0.32)',
779
+ },
780
+ verdictPopover: {
781
+ position: 'absolute', left: '0', top: 'calc(100% + 28px)', width: '272px',
782
+ background: C.elevated, border: '1px solid ' + C.border, borderRadius: '8px',
783
+ padding: '9px 10px', zIndex: 65, boxShadow: '0 14px 32px rgba(0,0,0,0.52)',
784
+ color: C.text, fontSize: '11px', lineHeight: '1.5', userSelect: 'text',
785
+ },
736
786
  };
737
787
 
738
788
  let hostCtx = null;
789
+ let cachedModels = [];
739
790
 
740
791
  function socketCenterY(i) {
741
792
  return SOCKET_BAND_TOP + i * ROW_H + ROW_H / 2;
742
793
  }
743
794
 
795
+ /**
796
+ * Determine which node kinds can legally receive a wire dragged out from `fromNode`.
797
+ * Mirrors the canvas invariant that Lead -> Lead direct links are forbidden.
798
+ */
799
+ function compatibleTargetsForWire(fromNode, _edgeType) {
800
+ const fromLead = Boolean(fromNode && fromNode.kind === 'lead');
801
+ return {
802
+ agent: true,
803
+ lead: !fromLead,
804
+ condition: true,
805
+ leadBlockedReason: fromLead ? 'leadToLeadBlocked' : '',
806
+ };
807
+ }
808
+
809
+ /** Format a compact verdict pill for a condition node decision snapshot. */
810
+ function conditionVerdictSummary(decision, lang) {
811
+ if (!decision || typeof decision !== 'object') return null;
812
+ const en = lang === 'en';
813
+ if (decision.failed) {
814
+ return {
815
+ tone: 'failed',
816
+ text: '⚠ ' + (en ? 'Judge failed' : '判定失败')
817
+ + (decision.fallbackLead ? ' → ' + decision.fallbackLead : ''),
818
+ };
819
+ }
820
+ const labels = Array.isArray(decision.branchLabels) && decision.branchLabels.length
821
+ ? decision.branchLabels
822
+ : (Array.isArray(decision.branches) ? decision.branches : []);
823
+ if (!labels.length) {
824
+ return {
825
+ tone: 'warn',
826
+ text: '⚠ ' + (en ? 'No match' : '未命中')
827
+ + (decision.fallbackLead ? ' → ' + decision.fallbackLead : ''),
828
+ };
829
+ }
830
+ return {
831
+ tone: 'ok',
832
+ text: '→ ' + labels.join(' · '),
833
+ };
834
+ }
835
+
836
+ /** Compute the Entry Lead "▶ Run" button state, label, disabled flag, and tooltip. */
837
+ function entryRunButtonState({ enabled, task, sessionRunning, waitingLead, triggering, lang }) {
838
+ const en = lang === 'en';
839
+ if (sessionRunning || triggering) {
840
+ return {
841
+ state: 'running',
842
+ disabled: true,
843
+ label: en ? 'Running…' : '进行中…',
844
+ title: en
845
+ ? 'Workflow is currently running; wait for this turn to finish'
846
+ : '工作流正在运行中,请等待本轮结束',
847
+ };
848
+ }
849
+ if (waitingLead) {
850
+ const wName = typeof waitingLead === 'object' && waitingLead && waitingLead.label
851
+ ? waitingLead.label
852
+ : '';
853
+ return {
854
+ state: 'waiting',
855
+ disabled: true,
856
+ label: en ? '⏸ Awaiting Lead' : '⏸ 等待决策',
857
+ title: en
858
+ ? 'Paused at intermediate Lead' + (wName ? ' "' + wName + '"' : '') + '; reply in chat to continue'
859
+ : '当前停在中间 Lead' + (wName ? '「' + wName + '」' : '') + ',请先在聊天室回复拍板继续',
860
+ };
861
+ }
862
+ if (!enabled) {
863
+ return {
864
+ state: 'disabled',
865
+ disabled: true,
866
+ label: en ? '▶ Run' : '▶ 运行',
867
+ title: en
868
+ ? 'Turn on ● ON in the top-left corner to enable this canvas first'
869
+ : '请先点亮左上角 ● ON 启用画布',
870
+ };
871
+ }
872
+ if (!String(task || '').trim()) {
873
+ return {
874
+ state: 'disabled',
875
+ disabled: true,
876
+ label: en ? '▶ Run' : '▶ 运行',
877
+ title: en
878
+ ? 'Fill in the Entry Lead task before running to avoid an empty run'
879
+ : '请先在入口节点填写任务内容,避免空跑',
880
+ };
881
+ }
882
+ return {
883
+ state: 'ready',
884
+ disabled: false,
885
+ label: en ? '▶ Run' : '▶ 运行',
886
+ title: en
887
+ ? 'Start the enabled workflow directly (auto-syncs unsaved edits). For retryFailed, reset, or clearing node memory, specify in chat.'
888
+ : '直接按当前画布起跑(会自动同步未保存改动)。如需断点续跑(retryFailed)、从头重跑(reset)或清理记忆节点,可在聊天中说明。',
889
+ };
890
+ }
891
+
744
892
  function isCustomBranches(node) {
745
893
  return Boolean(node && node.kind === 'condition' && Array.isArray(node.branches) && node.branches.length >= 2);
746
894
  }
@@ -1542,7 +1690,8 @@ window.__ModuleLoader__.load({
1542
1690
  const cutHits = useRef(new Set());
1543
1691
  const [pending, setPending] = useState(null);
1544
1692
  const [status, setStatus] = useState('');
1545
- const [models, setModels] = useState([]);
1693
+ const [models, setModels] = useState(() => cachedModels);
1694
+ const [modelsLoading, setModelsLoading] = useState(() => cachedModels.length === 0);
1546
1695
  const [openModelFor, setOpenModelFor] = useState(null);
1547
1696
  const [enabled, setEnabled] = useState(() => Boolean(initial && initial.enabled));
1548
1697
 
@@ -1569,7 +1718,13 @@ window.__ModuleLoader__.load({
1569
1718
  viewRef.current = view;
1570
1719
  const [statusById, setStatusById] = useState({});
1571
1720
  const [runsById, setRunsById] = useState({});
1721
+ const [runState, setRunState] = useState(null);
1722
+ const [decisionViewFor, setDecisionViewFor] = useState(null);
1572
1723
  const [sessionRunning, setSessionRunning] = useState(false);
1724
+ const [runTriggering, setRunTriggering] = useState(false);
1725
+ const runTriggeringRef = useRef(false);
1726
+ const pendingHandledRef = useRef(false);
1727
+ const lastNodePrefsRef = useRef({ provider: '', model: '', reasoning: '', preset: 'standard' });
1573
1728
  const [presets, setPresets] = useState(loadPresets);
1574
1729
  const [presetOpen, setPresetOpen] = useState(null);
1575
1730
  const [presetName, setPresetName] = useState('');
@@ -1631,7 +1786,10 @@ window.__ModuleLoader__.load({
1631
1786
  useEffect(() => {
1632
1787
  let alive = true;
1633
1788
  const remote = hostCtx && hostCtx.remote && hostCtx.remote.session;
1634
- if (!remote || typeof remote.modelCatalog !== 'function') return undefined;
1789
+ if (!remote || typeof remote.modelCatalog !== 'function') {
1790
+ setModelsLoading(false);
1791
+ return undefined;
1792
+ }
1635
1793
  remote.modelCatalog().then((res) => {
1636
1794
  if (!alive || !res || !res.ok) return;
1637
1795
  const flat = [];
@@ -1647,8 +1805,11 @@ window.__ModuleLoader__.load({
1647
1805
  });
1648
1806
  }
1649
1807
  }
1808
+ cachedModels = flat;
1650
1809
  setModels(flat);
1651
- }).catch(() => {});
1810
+ }).catch(() => {}).finally(() => {
1811
+ if (alive) setModelsLoading(false);
1812
+ });
1652
1813
  return () => { alive = false; };
1653
1814
  }, []);
1654
1815
 
@@ -1667,25 +1828,89 @@ window.__ModuleLoader__.load({
1667
1828
  const pushPlan = (nextEnabled, overrideNodes, overrideEdges, overrideParallel) => {
1668
1829
  try {
1669
1830
  const face = sessionFace(sessionId);
1670
- if (!face || typeof face.command !== 'function') { flash(t('syncFailed')); return; }
1831
+ if (!face || typeof face.command !== 'function') { flash(t('syncFailed')); return Promise.resolve(false); }
1671
1832
  const curNodes = Array.isArray(overrideNodes) ? overrideNodes : nodesRef.current;
1672
1833
  const curEdges = Array.isArray(overrideEdges) ? overrideEdges : edgesRef.current;
1673
1834
  const sig = planSig(nextEnabled, curNodes, curEdges, overrideParallel);
1674
- if (sig === lastSync.current) { setDirty(false); flash(t('upToDate')); return; }
1835
+ if (sig === lastSync.current) { setDirty(false); flash(t('upToDate')); return Promise.resolve(true); }
1675
1836
  const line = '/canvas-sync ' + encodeURIComponent(sig);
1676
1837
  const hasStandardAgent = nextEnabled && curNodes.some((n) => n && n.kind !== 'lead' && (n.preset || 'standard') !== 'minimal');
1677
- face.command(line).then((ack) => {
1838
+ return face.command(line).then((ack) => {
1678
1839
  if (ack && ack.ok) {
1679
1840
  lastSync.current = sig;
1680
1841
  setDirty(false);
1842
+ setRunState(null);
1843
+ setDecisionViewFor(null);
1681
1844
  snapshotStaleCatalog();
1682
1845
  flash(hasStandardAgent ? t('syncedWithStdWarn') : t('syncedToHost'));
1683
- } else {
1684
- flash(t('syncFailed'));
1846
+ return true;
1685
1847
  }
1686
- }, () => flash(t('syncFailed')));
1848
+ flash(t('syncFailed'));
1849
+ return false;
1850
+ }, () => { flash(t('syncFailed')); return false; });
1687
1851
  } catch (_e) {
1688
1852
  flash(t('syncFailed'));
1853
+ return Promise.resolve(false);
1854
+ }
1855
+ };
1856
+
1857
+ const runFromEntry = async () => {
1858
+ if (runTriggeringRef.current || sessionRunning) return;
1859
+ const entry = nodesRef.current.find((n) => n.id === 'lead');
1860
+ const taskText = String((entry && entry.task) || '').trim();
1861
+ const waitingLead = runState
1862
+ ? (runState.waitingLead || null)
1863
+ : (leadReadyIds.size > 0 ? { id: Array.from(leadReadyIds)[0] } : null);
1864
+ const btn = entryRunButtonState({
1865
+ enabled,
1866
+ task: taskText,
1867
+ sessionRunning,
1868
+ waitingLead,
1869
+ triggering: runTriggeringRef.current,
1870
+ lang,
1871
+ });
1872
+ if (btn.disabled) { flash(btn.title); return; }
1873
+ const face = sessionFace(sessionId);
1874
+ const canPrompt = Boolean(face && typeof face.prompt === 'function');
1875
+ const canConvSend = Boolean(hostCtx && hostCtx.conversation && typeof hostCtx.conversation.send === 'function');
1876
+ if (!canPrompt && !canConvSend) { flash(t('runSendUnavailable')); return; }
1877
+ runTriggeringRef.current = true;
1878
+ setRunTriggering(true);
1879
+ let succeeded = false;
1880
+ try {
1881
+ if (dirty) {
1882
+ const ok = await pushPlan(true);
1883
+ if (!ok) {
1884
+ runTriggeringRef.current = false;
1885
+ setRunTriggering(false);
1886
+ return;
1887
+ }
1888
+ }
1889
+ const promptText = lang === 'en'
1890
+ ? 'Run the enabled workflow canvas for this task:\n' + taskText
1891
+ : '按当前已启用的画布执行以下任务:\n' + taskText;
1892
+ if (canPrompt) {
1893
+ const res = await face.prompt([{ type: 'text', text: promptText }], 'queue');
1894
+ if (res && res.ok === false) {
1895
+ throw new Error((res.error && res.error.message) || 'prompt failed');
1896
+ }
1897
+ } else {
1898
+ await hostCtx.conversation.send(promptText);
1899
+ }
1900
+ succeeded = true;
1901
+ flash(t('runStarted'));
1902
+ } catch (err) {
1903
+ flash(t('runFailed') + (err && err.message ? ': ' + String(err.message).slice(0, 60) : ''));
1904
+ } finally {
1905
+ if (!succeeded) {
1906
+ runTriggeringRef.current = false;
1907
+ setRunTriggering(false);
1908
+ } else {
1909
+ setTimeout(() => {
1910
+ runTriggeringRef.current = false;
1911
+ setRunTriggering(false);
1912
+ }, 1200);
1913
+ }
1689
1914
  }
1690
1915
  };
1691
1916
 
@@ -2063,39 +2288,78 @@ window.__ModuleLoader__.load({
2063
2288
  openRun(node, run);
2064
2289
  };
2065
2290
 
2066
- const addNode = (kind, atWorld) => {
2291
+ const addNode = (kind, atWorld, linkFrom) => {
2292
+ const normKind = kind === 'lead' ? 'lead' : (kind === 'condition' ? 'condition' : 'agent');
2293
+ if (linkFrom && linkFrom.fromId) {
2294
+ const srcNode = nodesRef.current.find((n) => n.id === linkFrom.fromId);
2295
+ const compat = compatibleTargetsForWire(srcNode, linkFrom.type);
2296
+ if ((normKind === 'lead' && !compat.lead)
2297
+ || (normKind === 'agent' && !compat.agent)
2298
+ || (normKind === 'condition' && !compat.condition)) {
2299
+ flash(t(compat.leadBlockedReason || 'leadToLeadBlocked'));
2300
+ return;
2301
+ }
2302
+ }
2067
2303
  pushSnapshot();
2068
2304
  const newId = 'n' + Date.now().toString(36) + Math.random().toString(36).slice(2, 4);
2305
+ const prefs = lastNodePrefsRef.current || {};
2069
2306
  setNodes((ns) => {
2070
2307
  const i = ns.length;
2071
2308
  const center = viewportCenterWorld();
2072
2309
  const x = atWorld && typeof atWorld.x === 'number'
2073
- ? Math.round(atWorld.x - NODE_W / 2)
2310
+ ? (linkFrom ? Math.round(atWorld.x) : Math.round(atWorld.x - NODE_W / 2))
2074
2311
  : center.x + 40 + (ns.length % 3) * 30;
2075
2312
  const y = atWorld && typeof atWorld.y === 'number'
2076
- ? Math.round(atWorld.y - NODE_H / 2)
2313
+ ? (linkFrom ? Math.round(atWorld.y - socketCenterY(0)) : Math.round(atWorld.y - NODE_H / 2))
2077
2314
  : center.y - NODE_H / 2 + (ns.length % 3) * 40;
2078
- const normKind = kind === 'lead' ? 'lead' : (kind === 'condition' ? 'condition' : 'agent');
2079
2315
  const defaultLabel = normKind === 'lead'
2080
2316
  ? 'Lead 步骤 ' + i
2081
2317
  : (normKind === 'condition' ? (lang === 'en' ? 'Condition ' + i : '条件判断 ' + i) : 'Node ' + i);
2082
- return [...ns, {
2318
+ const nextNode = {
2083
2319
  id: newId,
2084
2320
  kind: normKind,
2085
2321
  x,
2086
2322
  y,
2087
2323
  label: defaultLabel,
2088
- provider: '',
2089
- model: '',
2090
- preset: normKind === 'condition' ? 'minimal' : 'standard',
2324
+ provider: normKind === 'lead' ? '' : (prefs.provider || ''),
2325
+ model: normKind === 'lead' ? '' : (prefs.model || ''),
2326
+ reasoning: normKind === 'lead' ? '' : (prefs.reasoning || ''),
2327
+ preset: normKind === 'condition' ? 'minimal' : (prefs.preset || 'standard'),
2091
2328
  role: '',
2092
- }];
2329
+ };
2330
+ return [...ns, nextNode];
2093
2331
  });
2332
+ if (linkFrom && linkFrom.fromId) {
2333
+ const type = linkFrom.type || 'prompt';
2334
+ const b = typeof linkFrom.branch === 'string' ? linkFrom.branch.trim() : '';
2335
+ setEdges((es) => {
2336
+ const nextEdge = {
2337
+ id: 'e' + Date.now().toString(36) + Math.random().toString(36).slice(2, 4),
2338
+ from: linkFrom.fromId,
2339
+ to: newId,
2340
+ type,
2341
+ };
2342
+ if (b) nextEdge.branch = b;
2343
+ return [...es, nextEdge];
2344
+ });
2345
+ }
2094
2346
  setSelectedIds([newId]);
2095
2347
  setAddMenu(null);
2096
2348
  };
2097
2349
 
2098
2350
  const updateNode = (id, patch) => {
2351
+ if (patch && ('provider' in patch || 'model' in patch || 'reasoning' in patch || 'preset' in patch)) {
2352
+ const cur = nodesRef.current.find((n) => n.id === id);
2353
+ if (cur && cur.kind !== 'lead') {
2354
+ const prev = lastNodePrefsRef.current || {};
2355
+ lastNodePrefsRef.current = {
2356
+ provider: 'provider' in patch ? (patch.provider || '') : prev.provider,
2357
+ model: 'model' in patch ? (patch.model || '') : prev.model,
2358
+ reasoning: 'reasoning' in patch ? (patch.reasoning || '') : prev.reasoning,
2359
+ preset: cur.kind === 'agent' && 'preset' in patch ? (patch.preset || 'standard') : prev.preset,
2360
+ };
2361
+ }
2362
+ }
2099
2363
  setNodes((ns) => ns.map((n) => (n.id === id ? { ...n, ...patch } : n)));
2100
2364
  };
2101
2365
 
@@ -2308,6 +2572,7 @@ window.__ModuleLoader__.load({
2308
2572
  /** Release over an output socket: completes a drag that started at the unified left input. */
2309
2573
  const onOutputUp = (e, id, type, branch) => {
2310
2574
  if (!pending || pending.dir !== 'in') return;
2575
+ pendingHandledRef.current = true;
2311
2576
  e.preventDefault();
2312
2577
  e.stopPropagation();
2313
2578
  const b = typeof branch === 'string' ? branch.trim() : '';
@@ -2360,6 +2625,7 @@ window.__ModuleLoader__.load({
2360
2625
 
2361
2626
  const onInputUp = (e, id) => {
2362
2627
  if (!pending || pending.dir !== 'out') return;
2628
+ pendingHandledRef.current = true;
2363
2629
  e.preventDefault();
2364
2630
  e.stopPropagation();
2365
2631
  if (pending.fromId !== id) {
@@ -2442,8 +2708,8 @@ window.__ModuleLoader__.load({
2442
2708
  const keyActionsRef = useRef(null);
2443
2709
  keyActionsRef.current = {
2444
2710
  undo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode,
2445
- addMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen,
2446
- setAddMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen,
2711
+ addMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, decisionViewFor,
2712
+ setAddMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setDecisionViewFor,
2447
2713
  };
2448
2714
  useEffect(() => {
2449
2715
  const isEditable = (target) => {
@@ -2455,7 +2721,7 @@ window.__ModuleLoader__.load({
2455
2721
  const act = keyActionsRef.current;
2456
2722
  if (!act) return;
2457
2723
  if (ev.key === 'Escape') {
2458
- if (act.addMenu || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen) {
2724
+ if (act.addMenu || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen || act.decisionViewFor) {
2459
2725
  ev.preventDefault();
2460
2726
  act.setAddMenu(null);
2461
2727
  act.setRoleEditFor(null);
@@ -2463,24 +2729,26 @@ window.__ModuleLoader__.load({
2463
2729
  act.setMenuOpen(false);
2464
2730
  act.setPresetOpen(null);
2465
2731
  act.setHelpOpen(false);
2732
+ act.setDecisionViewFor(null);
2466
2733
  }
2467
2734
  return;
2468
2735
  }
2469
2736
  if (isEditable(ev.target)) return;
2470
2737
  if (act.addMenu) {
2738
+ const lf = act.addMenu.linkFrom || null;
2471
2739
  if (ev.key === '1' || ev.key === 'Enter') {
2472
2740
  ev.preventDefault();
2473
- act.addNode('agent', { x: act.addMenu.wx, y: act.addMenu.wy });
2741
+ act.addNode('agent', { x: act.addMenu.wx, y: act.addMenu.wy }, lf);
2474
2742
  return;
2475
2743
  }
2476
2744
  if (ev.key === '2') {
2477
2745
  ev.preventDefault();
2478
- act.addNode('lead', { x: act.addMenu.wx, y: act.addMenu.wy });
2746
+ act.addNode('lead', { x: act.addMenu.wx, y: act.addMenu.wy }, lf);
2479
2747
  return;
2480
2748
  }
2481
2749
  if (ev.key === '3') {
2482
2750
  ev.preventDefault();
2483
- act.addNode('condition', { x: act.addMenu.wx, y: act.addMenu.wy });
2751
+ act.addNode('condition', { x: act.addMenu.wx, y: act.addMenu.wy }, lf);
2484
2752
  return;
2485
2753
  }
2486
2754
  }
@@ -2543,7 +2811,7 @@ window.__ModuleLoader__.load({
2543
2811
  useEffect(() => {
2544
2812
  if (!dragging) return undefined;
2545
2813
  const move = (ev) => onCanvasMove(ev);
2546
- const up = () => onCanvasUp();
2814
+ const up = (ev) => onCanvasUp(ev);
2547
2815
  window.addEventListener('mousemove', move);
2548
2816
  window.addEventListener('mouseup', up);
2549
2817
  return () => {
@@ -2567,6 +2835,7 @@ window.__ModuleLoader__.load({
2567
2835
  }
2568
2836
  if (e.button !== 0) return;
2569
2837
  if (roleEditFor) setRoleEditFor(null);
2838
+ if (decisionViewFor) setDecisionViewFor(null);
2570
2839
  if (menuOpen) setMenuOpen(false);
2571
2840
  if (addMenu) setAddMenu(null);
2572
2841
  if (presetOpen) setPresetOpen(null);
@@ -2635,7 +2904,7 @@ window.__ModuleLoader__.load({
2635
2904
  }
2636
2905
  };
2637
2906
 
2638
- const onCanvasUp = () => {
2907
+ const onCanvasUp = (ev) => {
2639
2908
  if (cutRef.current) {
2640
2909
  cutRef.current = null;
2641
2910
  setDragging(false);
@@ -2658,6 +2927,39 @@ window.__ModuleLoader__.load({
2658
2927
  setPanning(false);
2659
2928
  }
2660
2929
  nodeDrag.current = null;
2930
+ const handled = pendingHandledRef.current;
2931
+ pendingHandledRef.current = false;
2932
+ if (!handled && pending && pending.dir === 'out') {
2933
+ const dist = Math.hypot(pending.x - pending.sx, pending.y - pending.sy);
2934
+ const wrap = canvasWrapRef.current;
2935
+ if (dist >= 16 && wrap) {
2936
+ const wrapRect = wrap.getBoundingClientRect();
2937
+ const cx = ev && typeof ev.clientX === 'number' ? ev.clientX : (wrapRect.left + wrapRect.width / 2);
2938
+ const cy = ev && typeof ev.clientY === 'number' ? ev.clientY : (wrapRect.top + wrapRect.height / 2);
2939
+ const sx = Math.max(8, Math.min(wrapRect.width - 176, cx - wrapRect.left));
2940
+ const sy = Math.max(8, Math.min(wrapRect.height - 110, cy - wrapRect.top));
2941
+ setAddMenu({
2942
+ sx,
2943
+ sy,
2944
+ wx: pending.x,
2945
+ wy: pending.y,
2946
+ linkFrom: {
2947
+ fromId: pending.fromId,
2948
+ type: pending.type || 'prompt',
2949
+ branch: pending.branch || '',
2950
+ color: pending.color || '#8a8f98',
2951
+ sx: pending.sx,
2952
+ sy: pending.sy,
2953
+ x: pending.x,
2954
+ y: pending.y,
2955
+ },
2956
+ });
2957
+ setMenuOpen(false);
2958
+ setPresetOpen(null);
2959
+ setOpenModelFor(null);
2960
+ setDecisionViewFor(null);
2961
+ }
2962
+ }
2661
2963
  setPending(null);
2662
2964
  setDragging(false);
2663
2965
  };
@@ -2781,8 +3083,16 @@ window.__ModuleLoader__.load({
2781
3083
  '.dsh/canvas/session-' + bare + '.json',
2782
3084
  '.dsh/canvas/' + bare + '.json',
2783
3085
  ].filter((v, i, all) => all.indexOf(v) === i);
3086
+ const runPaths = [
3087
+ '.dsh/canvas/' + String(sessionId) + '.run.json',
3088
+ '.dsh/canvas/session-' + bare + '.run.json',
3089
+ '.dsh/canvas/' + bare + '.run.json',
3090
+ ].filter((v, i, all) => all.indexOf(v) === i);
3091
+ setRunState(null);
3092
+ setDecisionViewFor(null);
2784
3093
  let alive = true;
2785
3094
  let lastText = '';
3095
+ let lastRunText = '';
2786
3096
  const tick = async () => {
2787
3097
  try {
2788
3098
  let text = '';
@@ -2797,30 +3107,51 @@ window.__ModuleLoader__.load({
2797
3107
  setSyncNote(t('syncReadFail') + String((err && err.message) || err).slice(0, 80));
2798
3108
  }
2799
3109
  }
2800
- if (!text) return;
2801
- if (text === lastText) return;
2802
- lastText = text;
2803
- const doc = JSON.parse(text);
2804
- const canvas = doc && doc.canvas;
2805
- // A canvas the user has edited more recently wins over an old file.
2806
- try {
2807
- const raw = window.localStorage.getItem(storageKey(sessionId));
2808
- const local = raw ? JSON.parse(raw) : null;
2809
- if (local && typeof local.at === 'number' && typeof doc.at === 'number' && local.at > doc.at) {
2810
- lastText = text;
2811
- return;
3110
+ if (text && text !== lastText) {
3111
+ lastText = text;
3112
+ const doc = JSON.parse(text);
3113
+ const canvas = doc && doc.canvas;
3114
+ // A canvas the user has edited more recently wins over an old file.
3115
+ let staleLocal = false;
3116
+ try {
3117
+ const raw = window.localStorage.getItem(storageKey(sessionId));
3118
+ const local = raw ? JSON.parse(raw) : null;
3119
+ if (local && typeof local.at === 'number' && typeof doc.at === 'number' && local.at > doc.at) {
3120
+ staleLocal = true;
3121
+ }
3122
+ } catch (_e) { /* ignore */ }
3123
+ if (!staleLocal) {
3124
+ const valid = canvas && Array.isArray(canvas.nodes)
3125
+ && (canvas.mode === 'merge' || canvas.nodes.length > 0)
3126
+ && canvas.nodes.every((n) => n && typeof n.id === 'string');
3127
+ if (valid && applyCanvasDoc(canvas, doc.at, true)) {
3128
+ flash(t('generated'));
3129
+ setSyncNote(t('syncApplied'));
3130
+ setTimeout(() => setSyncNote(''), 4000);
3131
+ }
3132
+ else setSyncNote(t('syncBadFile'));
2812
3133
  }
2813
- } catch (_e) { /* ignore */ }
2814
- const valid = canvas && Array.isArray(canvas.nodes)
2815
- && (canvas.mode === 'merge' || canvas.nodes.length > 0)
2816
- && canvas.nodes.every((n) => n && typeof n.id === 'string');
2817
- if (valid && applyCanvasDoc(canvas, doc.at, true)) {
2818
- flash(t('generated'));
2819
- setSyncNote(t('syncApplied'));
2820
- setTimeout(() => setSyncNote(''), 4000);
2821
3134
  }
2822
- else setSyncNote(t('syncBadFile'));
2823
3135
  } catch (_e) { /* file absent or not readable yet */ }
3136
+ try {
3137
+ let runText = '';
3138
+ for (const rp of runPaths) {
3139
+ try {
3140
+ const res = await wf.read(sessionId, rp, {}, new AbortController().signal);
3141
+ if (!alive) return;
3142
+ const payload = res && res.ok === false ? null : (res && res.value !== undefined ? res.value : res);
3143
+ const read = payload && (typeof payload.text === 'string' ? payload.text : '');
3144
+ if (read) { runText = read; break; }
3145
+ } catch (_e) { /* ignore */ }
3146
+ }
3147
+ if (runText && runText !== lastRunText) {
3148
+ lastRunText = runText;
3149
+ const parsed = JSON.parse(runText);
3150
+ if (parsed && typeof parsed === 'object') {
3151
+ setRunState(parsed.status === 'idle' ? null : parsed);
3152
+ }
3153
+ }
3154
+ } catch (_e) { /* run state file absent or not readable yet */ }
2824
3155
  };
2825
3156
  const timer = setInterval(tick, 1500);
2826
3157
  tick();
@@ -3083,6 +3414,17 @@ window.__ModuleLoader__.load({
3083
3414
 
3084
3415
  const modelControl = (node) => {
3085
3416
  if (!models.length) {
3417
+ if (modelsLoading) {
3418
+ return h('button', {
3419
+ type: 'button',
3420
+ disabled: true,
3421
+ style: { ...S.selectBtn, color: C.dim, cursor: 'default' },
3422
+ onMouseDown: (e) => e.stopPropagation(),
3423
+ },
3424
+ h('span', { style: S.selectText }, node.model || t('loadingModels')),
3425
+ h('span', { style: S.caret }, '▾'),
3426
+ );
3427
+ }
3086
3428
  return h('input', {
3087
3429
  style: S.input,
3088
3430
  value: node.model || '',
@@ -3187,6 +3529,13 @@ window.__ModuleLoader__.load({
3187
3529
  }
3188
3530
  }
3189
3531
 
3532
+ const decisionsById = (enabled && runState && runState.decisions && typeof runState.decisions === 'object')
3533
+ ? runState.decisions
3534
+ : {};
3535
+ const prunedSet = new Set(enabled && runState && Array.isArray(runState.pruned) ? runState.pruned : []);
3536
+ const blockedEdgeSet = new Set(enabled && runState && Array.isArray(runState.blockedEdges) ? runState.blockedEdges : []);
3537
+ const edgeKeyForState = (e) => String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
3538
+
3190
3539
  const edgeEls = edges.map((edge) => {
3191
3540
  const from = nodeById.get(edge.from);
3192
3541
  const to = nodeById.get(edge.to);
@@ -3194,6 +3543,7 @@ window.__ModuleLoader__.load({
3194
3543
  const color = edgeColorFor(from, edge);
3195
3544
  const d = edgePath(from, to, edge);
3196
3545
  const highlighted = cutVictims.includes(edge.id);
3546
+ const isPrunedEdge = !highlighted && (blockedEdgeSet.has(edgeKeyForState(edge)) || prunedSet.has(edge.from) || prunedSet.has(edge.to));
3197
3547
  const hasSel = selectedSet.size > 0;
3198
3548
  const linkedToSel = hasSel && (selectedSet.has(edge.from) || selectedSet.has(edge.to));
3199
3549
  const toRunning = enabled && statusById[edge.to] === 'running';
@@ -3201,7 +3551,7 @@ window.__ModuleLoader__.load({
3201
3551
  || from.kind === 'lead'
3202
3552
  || statusById[edge.from] === 'done'
3203
3553
  || statusById[edge.from] === 'failed';
3204
- const isFlowing = enabled && !highlighted && (
3554
+ const isFlowing = enabled && !highlighted && !isPrunedEdge && (
3205
3555
  (toRunning && fromReady)
3206
3556
  || (leadReadyIds.has(edge.to) && (statusById[edge.from] === 'done' || statusById[edge.from] === 'failed'))
3207
3557
  );
@@ -3214,11 +3564,11 @@ window.__ModuleLoader__.load({
3214
3564
  || statusById[edge.to] === 'failed'
3215
3565
  || leadReadyIds.has(edge.to)
3216
3566
  || leadDoneIds.has(edge.to);
3217
- const isCompletedLink = enabled && !highlighted && fromSettled && toSettled;
3218
- const dimmed = hasSel && !linkedToSel && !highlighted && !isFlowing;
3567
+ const isCompletedLink = enabled && !highlighted && !isPrunedEdge && fromSettled && toSettled;
3568
+ const dimmed = isPrunedEdge || (hasSel && !linkedToSel && !highlighted && !isFlowing);
3219
3569
  const strokeColor = highlighted ? '#e5534b' : color;
3220
3570
  const baseWidth = highlighted ? 3 : (linkedToSel || isFlowing ? 2.6 : 2);
3221
- const baseOpacity = dimmed ? 0.26 : (isFlowing || linkedToSel ? 1 : (isCompletedLink ? 0.92 : 0.78));
3571
+ const baseOpacity = isPrunedEdge ? 0.22 : (dimmed ? 0.26 : (isFlowing || linkedToSel ? 1 : (isCompletedLink ? 0.92 : 0.78)));
3222
3572
  const useGlow = fxLevel === 'vivid' && !dimmed;
3223
3573
  const showDashFlow = isFlowing && fxLevel !== 'minimal';
3224
3574
  const showBead = isFlowing && fxLevel === 'vivid';
@@ -3247,6 +3597,7 @@ window.__ModuleLoader__.load({
3247
3597
  stroke: strokeColor,
3248
3598
  strokeWidth: baseWidth,
3249
3599
  strokeOpacity: showDashFlow ? 0.35 : baseOpacity,
3600
+ strokeDasharray: isPrunedEdge ? '4 4' : undefined,
3250
3601
  fill: 'none',
3251
3602
  }),
3252
3603
  showDashFlow && fxLevel === 'vivid' && h('path', {
@@ -3300,16 +3651,20 @@ window.__ModuleLoader__.load({
3300
3651
  });
3301
3652
  if (node.kind === 'condition') {
3302
3653
  const branches = conditionBranchesForUI(node, lang);
3654
+ const condDec = decisionsById[node.id] || null;
3655
+ const matchedBranchIds = condDec && Array.isArray(condDec.branches) ? new Set(condDec.branches) : null;
3303
3656
  return h('div', { style: S.band },
3304
3657
  unifiedInSocket,
3305
3658
  h('span', { style: { ...S.rowLabel, position: 'absolute', left: '12px', top: '3px', pointerEvents: 'none' } }, inText),
3306
3659
  branches.map((b) => {
3307
3660
  const outLinked = connectedOut.has(node.id + '|branch:' + b.id);
3661
+ const isMatchedBranch = Boolean(matchedBranchIds && matchedBranchIds.has(b.id));
3662
+ const isUnmatchedBranch = Boolean(matchedBranchIds && !matchedBranchIds.has(b.id));
3308
3663
  const outTip = !b.custom
3309
3664
  ? (b.id === 'true' ? t('tipCondTrue') : t('tipCondFalse'))
3310
3665
  : t('tipBranchOut');
3311
3666
  const editKey = 'branch:' + node.id + ':' + b.id;
3312
- return h('div', { key: b.id, style: S.condBranchRow },
3667
+ return h('div', { key: b.id, style: { ...S.condBranchRow, opacity: isUnmatchedBranch ? 0.48 : 1 } },
3313
3668
  h('div', {
3314
3669
  style: { display: 'flex', alignItems: 'center', marginRight: '10px' },
3315
3670
  onMouseDown: (e) => e.stopPropagation(),
@@ -3323,7 +3678,11 @@ window.__ModuleLoader__.load({
3323
3678
  onClick: () => setRoleEditFor(roleEditFor === editKey ? null : editKey),
3324
3679
  }, '⤢'),
3325
3680
  h('input', {
3326
- style: { ...S.condBranchInput, borderRight: '2px solid ' + b.color },
3681
+ style: {
3682
+ ...S.condBranchInput,
3683
+ borderRight: '2px solid ' + b.color,
3684
+ borderColor: isMatchedBranch ? b.color : C.border,
3685
+ },
3327
3686
  value: b.label,
3328
3687
  placeholder: t('branchPh'),
3329
3688
  onFocus: () => setSelectedIds([node.id]),
@@ -3685,30 +4044,36 @@ window.__ModuleLoader__.load({
3685
4044
  }),
3686
4045
  h('span', null, (enabled ? t('enabled') : t('disabled')).replace(/^[●○]\s*/, '')),
3687
4046
  ),
3688
- addMenu && h('div', {
3689
- style: { ...S.addMenu, left: addMenu.sx + 'px', top: addMenu.sy + 'px' },
3690
- onMouseDown: (e) => e.stopPropagation(),
3691
- },
3692
- h('div', { style: S.addMenuHead }, t('addMenuTitle')),
3693
- h('div', {
3694
- style: S.addMenuRow,
3695
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3696
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
3697
- onClick: () => addNode('agent', { x: addMenu.wx, y: addMenu.wy }),
3698
- }, h('span', null, t('addAgent')), h('span', { style: S.addMenuHint }, '1')),
3699
- h('div', {
3700
- style: S.addMenuRow,
3701
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3702
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
3703
- onClick: () => addNode('lead', { x: addMenu.wx, y: addMenu.wy }),
3704
- }, h('span', null, t('addLead')), h('span', { style: S.addMenuHint }, '2')),
3705
- h('div', {
3706
- style: S.addMenuRow,
3707
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
3708
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
3709
- onClick: () => addNode('condition', { x: addMenu.wx, y: addMenu.wy }),
3710
- }, h('span', null, t('addCond')), h('span', { style: S.addMenuHint }, '3')),
3711
- ),
4047
+ addMenu && (() => {
4048
+ const lf = addMenu.linkFrom || null;
4049
+ const srcNode = lf && lf.fromId ? nodeById.get(lf.fromId) : null;
4050
+ const compat = lf ? compatibleTargetsForWire(srcNode, lf.type) : { agent: true, lead: true, condition: true, leadBlockedReason: '' };
4051
+ return h('div', {
4052
+ style: { ...S.addMenu, left: addMenu.sx + 'px', top: addMenu.sy + 'px' },
4053
+ onMouseDown: (e) => e.stopPropagation(),
4054
+ },
4055
+ h('div', { style: S.addMenuHead }, lf ? t('addMenuLinkTitle') : t('addMenuTitle')),
4056
+ h('div', {
4057
+ style: S.addMenuRow,
4058
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
4059
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
4060
+ onClick: () => addNode('agent', { x: addMenu.wx, y: addMenu.wy }, lf),
4061
+ }, h('span', null, t('addAgent')), h('span', { style: S.addMenuHint }, '1')),
4062
+ h('div', {
4063
+ style: compat.lead ? S.addMenuRow : S.addMenuRowDisabled,
4064
+ title: compat.lead ? undefined : t(compat.leadBlockedReason || 'leadToLeadBlocked'),
4065
+ onMouseEnter: (e) => { if (compat.lead) e.currentTarget.style.background = C.hover; },
4066
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
4067
+ onClick: () => { if (compat.lead) addNode('lead', { x: addMenu.wx, y: addMenu.wy }, lf); },
4068
+ }, h('span', null, t('addLead')), h('span', { style: S.addMenuHint }, '2')),
4069
+ h('div', {
4070
+ style: S.addMenuRow,
4071
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
4072
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
4073
+ onClick: () => addNode('condition', { x: addMenu.wx, y: addMenu.wy }, lf),
4074
+ }, h('span', null, t('addCond')), h('span', { style: S.addMenuHint }, '3')),
4075
+ );
4076
+ })(),
3712
4077
  h('div', {
3713
4078
  ref: canvasElRef,
3714
4079
  style: {
@@ -3744,9 +4109,10 @@ window.__ModuleLoader__.load({
3744
4109
  strokeWidth: 1,
3745
4110
  strokeDasharray: '4 3',
3746
4111
  }),
3747
- pending && (() => {
3748
- const color = pending.color || (SOCKET_TYPES.find((t) => t.id === pending.type) || SOCKET_TYPES[0]).color;
3749
- const d = 'M ' + (pending.sx + WORLD_PAD) + ' ' + (pending.sy + WORLD_PAD) + ' L ' + (pending.x + WORLD_PAD) + ' ' + (pending.y + WORLD_PAD);
4112
+ (pending || (addMenu && addMenu.linkFrom)) && (() => {
4113
+ const wire = pending || addMenu.linkFrom;
4114
+ const color = wire.color || (SOCKET_TYPES.find((t) => t.id === wire.type) || SOCKET_TYPES[0]).color;
4115
+ const d = 'M ' + (wire.sx + WORLD_PAD) + ' ' + (wire.sy + WORLD_PAD) + ' L ' + (wire.x + WORLD_PAD) + ' ' + (wire.y + WORLD_PAD);
3750
4116
  return h('path', { d, stroke: color, strokeWidth: 2, strokeDasharray: '4 4', fill: 'none' });
3751
4117
  })(),
3752
4118
  ),
@@ -3797,6 +4163,9 @@ window.__ModuleLoader__.load({
3797
4163
  ? 'linear-gradient(90deg, #d29922 0%, #f2cc60 50%, #d29922 100%)'
3798
4164
  : 'linear-gradient(90deg, #2f81f7 0%, #58d580 50%, #2f81f7 100%)'))
3799
4165
  : (isFailed ? '#e5534b' : (isLeadKind ? '#2f81f7' : (isCondKind ? '#d29922' : '#3fb950')));
4166
+ const isPruned = enabled && prunedSet.has(node.id);
4167
+ const condDecision = isCondKind ? (decisionsById[node.id] || null) : null;
4168
+ const verdictInfo = condDecision ? conditionVerdictSummary(condDecision, lang) : null;
3800
4169
  return h('div', {
3801
4170
  key: node.id,
3802
4171
  'data-node': node.id,
@@ -3807,10 +4176,11 @@ window.__ModuleLoader__.load({
3807
4176
  left: node.x + WORLD_PAD,
3808
4177
  top: node.y + WORLD_PAD,
3809
4178
  ...(isLeadKind ? S.leadNode : null),
3810
- ...(isInactive ? S.orphanNode : null),
4179
+ ...(isInactive || isPruned ? S.orphanNode : null),
3811
4180
  ...(stateStyle || null),
4181
+ ...(decisionViewFor === node.id ? { zIndex: 40 } : null),
3812
4182
  },
3813
- title: isOrphan ? t('orphanTip') : (isSoloLead ? t('tipSoloLead') : (isDeadEnd ? t('tipDeadEnd') : undefined)),
4183
+ title: isPruned ? t('tipPruned') : (isOrphan ? t('orphanTip') : (isSoloLead ? t('tipSoloLead') : (isDeadEnd ? t('tipDeadEnd') : undefined))),
3814
4184
  onMouseDown: (e) => onNodeDown(e, node.id),
3815
4185
  },
3816
4186
  h('div', {
@@ -3822,7 +4192,55 @@ window.__ModuleLoader__.load({
3822
4192
  }),
3823
4193
  h('div', { style: S.nodeHeader }),
3824
4194
  h('div', { style: S.bandDivider }),
3825
- isDeadEnd
4195
+ isEntry
4196
+ ? (() => {
4197
+ const waitingLead = runState
4198
+ ? (runState.waitingLead || null)
4199
+ : (leadReadyIds.size > 0 ? { id: Array.from(leadReadyIds)[0] } : null);
4200
+ const btn = entryRunButtonState({
4201
+ enabled,
4202
+ task: node.task || '',
4203
+ sessionRunning,
4204
+ waitingLead,
4205
+ triggering: runTriggering,
4206
+ lang,
4207
+ });
4208
+ const isReady = btn.state === 'ready';
4209
+ const isRun = btn.state === 'running';
4210
+ const isWait = btn.state === 'waiting';
4211
+ const color = isReady ? '#3fb950' : (isRun ? '#2f81f7' : (isWait ? '#d29922' : C.dim));
4212
+ const bg = isReady
4213
+ ? 'rgba(63,185,80,0.14)'
4214
+ : (isRun ? 'rgba(47,129,247,0.14)' : (isWait ? 'rgba(210,153,34,0.14)' : C.elevated));
4215
+ const borderColor = isReady
4216
+ ? 'rgba(63,185,80,0.6)'
4217
+ : (isRun ? 'rgba(47,129,247,0.6)' : (isWait ? 'rgba(210,153,34,0.6)' : C.border));
4218
+ return h('button', {
4219
+ type: 'button',
4220
+ disabled: btn.disabled,
4221
+ style: {
4222
+ ...S.statusBtn,
4223
+ color,
4224
+ background: bg,
4225
+ borderColor,
4226
+ opacity: btn.state === 'disabled' ? 0.55 : 1,
4227
+ cursor: btn.disabled ? 'not-allowed' : 'pointer',
4228
+ fontWeight: isReady ? 600 : 500,
4229
+ },
4230
+ title: btn.title,
4231
+ onMouseDown: (e) => e.stopPropagation(),
4232
+ onMouseEnter: (e) => { if (!btn.disabled) e.currentTarget.style.background = 'rgba(63,185,80,0.24)'; },
4233
+ onMouseLeave: (e) => { e.currentTarget.style.background = bg; },
4234
+ onClick: (e) => { e.stopPropagation(); if (!btn.disabled) runFromEntry(); },
4235
+ },
4236
+ isRun && h('span', {
4237
+ className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
4238
+ style: { width: '6px', height: '6px', borderRadius: '50%', background: color, flex: '0 0 auto' },
4239
+ }),
4240
+ btn.label,
4241
+ );
4242
+ })()
4243
+ : isDeadEnd
3826
4244
  ? h('div', {
3827
4245
  style: S.warnChip,
3828
4246
  title: t('tipDeadEnd'),
@@ -3843,14 +4261,15 @@ window.__ModuleLoader__.load({
3843
4261
  : isDone
3844
4262
  ? 'rgba(63,185,80,0.14)'
3845
4263
  : 'transparent';
3846
- const statusLabel = isOrphan ? t('stOrphan')
3847
- : isSoloLead ? t('stSoloLead')
3848
- : isLeadReady ? t('stLeadReady')
3849
- : isLeadDone ? t('stDone')
3850
- : isLeadKind ? t('stLead')
3851
- : nodeStatus === 'running' ? t('stRunning')
3852
- : nodeStatus === 'failed' ? t('stFailed')
3853
- : nodeStatus === 'done' ? t('stDone') : t('stPending');
4264
+ const statusLabel = isPruned ? t('stPruned')
4265
+ : isOrphan ? t('stOrphan')
4266
+ : isSoloLead ? t('stSoloLead')
4267
+ : isLeadReady ? t('stLeadReady')
4268
+ : isLeadDone ? t('stDone')
4269
+ : isLeadKind ? t('stLead')
4270
+ : nodeStatus === 'running' ? t('stRunning')
4271
+ : nodeStatus === 'failed' ? t('stFailed')
4272
+ : nodeStatus === 'done' ? t('stDone') : t('stPending');
3854
4273
  const glyph = nodeStatus === 'running'
3855
4274
  ? h('span', {
3856
4275
  className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
@@ -4088,6 +4507,44 @@ window.__ModuleLoader__.load({
4088
4507
  onMouseDown: (e) => e.stopPropagation(),
4089
4508
  onClick: () => deleteNode(node.id),
4090
4509
  }, '×'),
4510
+ verdictInfo && h('button', {
4511
+ type: 'button',
4512
+ style: {
4513
+ ...S.verdictChip,
4514
+ color: verdictInfo.tone === 'failed' ? '#e5534b' : (verdictInfo.tone === 'warn' ? '#d29922' : '#3fb950'),
4515
+ 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)'),
4516
+ },
4517
+ title: (condDecision && condDecision.reason ? condDecision.reason + '\n' : '') + t('tipVerdictChip'),
4518
+ onMouseDown: (e) => e.stopPropagation(),
4519
+ onClick: (e) => {
4520
+ e.stopPropagation();
4521
+ setDecisionViewFor(decisionViewFor === node.id ? null : node.id);
4522
+ },
4523
+ }, verdictInfo.text),
4524
+ decisionViewFor === node.id && condDecision && h('div', {
4525
+ style: S.verdictPopover,
4526
+ onMouseDown: (e) => e.stopPropagation(),
4527
+ },
4528
+ h('div', {
4529
+ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '5px', fontWeight: 600, fontSize: '11px' },
4530
+ },
4531
+ h('span', null, t('verdictReasonTitle')),
4532
+ h('button', {
4533
+ type: 'button',
4534
+ style: { background: 'transparent', border: 'none', color: C.dim, cursor: 'pointer', fontSize: '12px', padding: '0 2px' },
4535
+ onClick: () => setDecisionViewFor(null),
4536
+ }, '×'),
4537
+ ),
4538
+ Array.isArray(condDecision.branchLabels) && condDecision.branchLabels.length > 0 && h('div', {
4539
+ style: { fontSize: '10px', color: '#3fb950', marginBottom: '4px' },
4540
+ }, t('verdictMatched') + condDecision.branchLabels.join(' · ')),
4541
+ condDecision.fallbackLead && h('div', {
4542
+ style: { fontSize: '10px', color: '#d29922', marginBottom: '4px' },
4543
+ }, t('verdictFallback') + condDecision.fallbackLead),
4544
+ h('div', {
4545
+ style: { maxHeight: '140px', overflowY: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word', color: C.text, fontSize: '11px' },
4546
+ }, (condDecision.reason && String(condDecision.reason).trim()) || t('verdictNoReason')),
4547
+ ),
4091
4548
  renderBand(node),
4092
4549
  );
4093
4550
  }),
@@ -4126,7 +4583,7 @@ window.__ModuleLoader__.load({
4126
4583
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
4127
4584
  }
4128
4585
  },
4129
- __test: { topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, distanceToEdge, edgeCurve },
4586
+ __test: { topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, distanceToEdge, edgeCurve, compatibleTargetsForWire, conditionVerdictSummary, entryRunButtonState },
4130
4587
  };
4131
4588
  },
4132
4589
  });
package/index.js CHANGED
@@ -937,6 +937,29 @@ function publishCanvas(scope, sessionId, canvas) {
937
937
  }
938
938
  }
939
939
 
940
+ /**
941
+ * Publish live run-state telemetry (condition decisions, pruned nodes, blocked edges,
942
+ * waitingLead) to `.dsh/canvas/<sessionId>.run.json` so the sidebar canvas can
943
+ * visualize branch routing and verdict reasons without touching the canvas definition file.
944
+ */
945
+ function publishRunState(scope, sessionId, runState) {
946
+ try {
947
+ if (!sessionId) return false;
948
+ const live = scope && scope.sessions && scope.sessions.get(sessionId);
949
+ const root = live && live.header && live.header.cwd;
950
+ if (!root) return false;
951
+ const dir = join(root, '.dsh', 'canvas');
952
+ mkdirSync(dir, { recursive: true });
953
+ writeFileSync(join(dir, sessionId + '.run.json'), JSON.stringify({
954
+ ...(runState || {}),
955
+ at: Date.now(),
956
+ }), 'utf8');
957
+ return true;
958
+ } catch (_e) {
959
+ return false;
960
+ }
961
+ }
962
+
940
963
  async function runPlan(scope, args, exec) {
941
964
  const agent = exec && exec.agent;
942
965
  const sid = agent && agent.id !== undefined ? String(agent.id) : '';
@@ -1225,6 +1248,18 @@ async function executePlan(scope, plan, args, exec) {
1225
1248
  if (!state.decisions) state.decisions = {};
1226
1249
  if (!state.fallbackLinks) state.fallbackLinks = [];
1227
1250
 
1251
+ const emitRunState = (status, waitingLead) => {
1252
+ if (!sid) return;
1253
+ publishRunState(scope, sid, {
1254
+ status,
1255
+ decisions: { ...state.decisions },
1256
+ pruned: Array.from(state.pruned || []),
1257
+ blockedEdges: Array.from(state.blockedEdges || []),
1258
+ waitingLead: waitingLead ? { id: waitingLead.id, label: waitingLead.label } : null,
1259
+ });
1260
+ };
1261
+ emitRunState('running', null);
1262
+
1228
1263
  const snapshotLastRun = (haltedFlag) => {
1229
1264
  if (!sid) return;
1230
1265
  lastRunBySession.set(sid, {
@@ -1412,6 +1447,7 @@ async function executePlan(scope, plan, args, exec) {
1412
1447
 
1413
1448
  for (;;) {
1414
1449
  if (isAborted()) {
1450
+ emitRunState('halted', null);
1415
1451
  if (sid) runBySession.delete(sid);
1416
1452
  return { error: '工作流执行已取消。' };
1417
1453
  }
@@ -1420,6 +1456,7 @@ async function executePlan(scope, plan, args, exec) {
1420
1456
  // results are dropped before returning the halted report.
1421
1457
  if (haltedReason && inFlight.size === 0) {
1422
1458
  snapshotLastRun(true);
1459
+ emitRunState('halted', null);
1423
1460
  if (sid) runBySession.delete(sid);
1424
1461
  saveStore();
1425
1462
  return {
@@ -1438,6 +1475,7 @@ async function executePlan(scope, plan, args, exec) {
1438
1475
  const remaining = runnable.filter((n) => !state.done.has(n.id));
1439
1476
  if (!remaining.length) {
1440
1477
  snapshotLastRun(false);
1478
+ emitRunState('done', null);
1441
1479
  runBySession.delete(sid);
1442
1480
  saveStore();
1443
1481
  return {
@@ -1459,6 +1497,7 @@ async function executePlan(scope, plan, args, exec) {
1459
1497
  const { node, outcome } = await Promise.race(inFlight.values());
1460
1498
  inFlight.delete(node.id);
1461
1499
  if (isAborted()) {
1500
+ emitRunState('halted', null);
1462
1501
  if (sid) runBySession.delete(sid);
1463
1502
  return { error: '工作流执行已取消。' };
1464
1503
  }
@@ -1491,8 +1530,10 @@ async function executePlan(scope, plan, args, exec) {
1491
1530
  state.decisions[node.id].fallbackLead = fallbackLead.label;
1492
1531
  state.results[node.id] += '(未擅自选择分支,已直接转交至最近 Lead「' + fallbackLead.label + '」)';
1493
1532
  recomputeBranchPrune();
1533
+ emitRunState('running', null);
1494
1534
  } else {
1495
1535
  recomputeBranchPrune();
1536
+ emitRunState('running', null);
1496
1537
  haltedReason = '条件节点「' + node.label + '」自身执行失败(' + failReason
1497
1538
  + '),为避免误走分支已停止下游执行。';
1498
1539
  }
@@ -1545,6 +1586,7 @@ async function executePlan(scope, plan, args, exec) {
1545
1586
  }
1546
1587
  }
1547
1588
  recomputeBranchPrune();
1589
+ emitRunState('running', null);
1548
1590
  continue;
1549
1591
  }
1550
1592
  state.results[node.id] = outcome.text;
@@ -1598,6 +1640,7 @@ async function executePlan(scope, plan, args, exec) {
1598
1640
  // Terminal Lead: zero downstream nodes remain, so complete the run directly
1599
1641
  // and hand off final review/delivery to the Lead without a redundant extra turn.
1600
1642
  snapshotLastRun(false);
1643
+ emitRunState('done', null);
1601
1644
  if (sid) runBySession.delete(sid);
1602
1645
  saveStore();
1603
1646
  return {
@@ -1626,6 +1669,7 @@ async function executePlan(scope, plan, args, exec) {
1626
1669
  label: leadNode.label,
1627
1670
  role: leadNode.role || leadNode.label,
1628
1671
  };
1672
+ emitRunState('need-lead', state.waitingLead);
1629
1673
  return {
1630
1674
  status: 'need-lead',
1631
1675
  node: {
@@ -1735,6 +1779,7 @@ export function apply(ctx) {
1735
1779
  if (!id) return { kind: 'error', text: 'no session' };
1736
1780
  canvasBySession.set(id, parsePayload(rawInput));
1737
1781
  runBySession.delete(id);
1782
+ publishRunState(ctx, id, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
1738
1783
  saveStore();
1739
1784
  return { kind: 'success', text: 'canvas synced' };
1740
1785
  } catch (error) {
@@ -1863,6 +1908,7 @@ export function apply(ctx) {
1863
1908
  });
1864
1909
  runBySession.delete(sid);
1865
1910
  lastRunBySession.delete(sid);
1911
+ publishRunState(scope, sid, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
1866
1912
  saveStore();
1867
1913
  }
1868
1914
  return { canvas, delivered, warnings };
@@ -1920,6 +1966,7 @@ export function apply(ctx) {
1920
1966
  const nextPlan = patched.plan;
1921
1967
  canvasBySession.set(sid, { enabled: payload.enabled, plan: nextPlan });
1922
1968
  runBySession.delete(sid);
1969
+ publishRunState(scope, sid, { status: 'idle', decisions: {}, pruned: [], blockedEdges: [], waitingLead: null });
1923
1970
  saveStore();
1924
1971
  const patchDoc = {
1925
1972
  mode: 'merge',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-workflow-canvas",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "A visual subagent-workflow canvas for DeepSeek Harness, docked in the sidebar.",
5
5
  "type": "module",
6
6
  "main": "index.js",