dsh-workflow-canvas 1.1.0 → 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/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
@@ -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: '标准',
@@ -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',
@@ -466,6 +494,11 @@ window.__ModuleLoader__.load({
466
494
  padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
467
495
  color: C.text, whiteSpace: 'nowrap',
468
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
+ },
469
502
  addMenuHint: { fontSize: '10px', color: C.dim },
470
503
  helpOverlay: {
471
504
  position: 'absolute', inset: '0', background: 'rgba(0,0,0,0.45)', zIndex: 90,
@@ -733,6 +766,21 @@ window.__ModuleLoader__.load({
733
766
  position: 'absolute', left: '2px', top: '10px', bottom: '10px', width: '3px',
734
767
  borderRadius: '2px', zIndex: 3,
735
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
+ },
736
784
  };
737
785
 
738
786
  let hostCtx = null;
@@ -741,6 +789,103 @@ window.__ModuleLoader__.load({
741
789
  return SOCKET_BAND_TOP + i * ROW_H + ROW_H / 2;
742
790
  }
743
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
+
744
889
  function isCustomBranches(node) {
745
890
  return Boolean(node && node.kind === 'condition' && Array.isArray(node.branches) && node.branches.length >= 2);
746
891
  }
@@ -1569,7 +1714,13 @@ window.__ModuleLoader__.load({
1569
1714
  viewRef.current = view;
1570
1715
  const [statusById, setStatusById] = useState({});
1571
1716
  const [runsById, setRunsById] = useState({});
1717
+ const [runState, setRunState] = useState(null);
1718
+ const [decisionViewFor, setDecisionViewFor] = useState(null);
1572
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' });
1573
1724
  const [presets, setPresets] = useState(loadPresets);
1574
1725
  const [presetOpen, setPresetOpen] = useState(null);
1575
1726
  const [presetName, setPresetName] = useState('');
@@ -1667,25 +1818,89 @@ window.__ModuleLoader__.load({
1667
1818
  const pushPlan = (nextEnabled, overrideNodes, overrideEdges, overrideParallel) => {
1668
1819
  try {
1669
1820
  const face = sessionFace(sessionId);
1670
- if (!face || typeof face.command !== 'function') { flash(t('syncFailed')); return; }
1821
+ if (!face || typeof face.command !== 'function') { flash(t('syncFailed')); return Promise.resolve(false); }
1671
1822
  const curNodes = Array.isArray(overrideNodes) ? overrideNodes : nodesRef.current;
1672
1823
  const curEdges = Array.isArray(overrideEdges) ? overrideEdges : edgesRef.current;
1673
1824
  const sig = planSig(nextEnabled, curNodes, curEdges, overrideParallel);
1674
- if (sig === lastSync.current) { setDirty(false); flash(t('upToDate')); return; }
1825
+ if (sig === lastSync.current) { setDirty(false); flash(t('upToDate')); return Promise.resolve(true); }
1675
1826
  const line = '/canvas-sync ' + encodeURIComponent(sig);
1676
1827
  const hasStandardAgent = nextEnabled && curNodes.some((n) => n && n.kind !== 'lead' && (n.preset || 'standard') !== 'minimal');
1677
- face.command(line).then((ack) => {
1828
+ return face.command(line).then((ack) => {
1678
1829
  if (ack && ack.ok) {
1679
1830
  lastSync.current = sig;
1680
1831
  setDirty(false);
1832
+ setRunState(null);
1833
+ setDecisionViewFor(null);
1681
1834
  snapshotStaleCatalog();
1682
1835
  flash(hasStandardAgent ? t('syncedWithStdWarn') : t('syncedToHost'));
1683
- } else {
1684
- flash(t('syncFailed'));
1836
+ return true;
1685
1837
  }
1686
- }, () => flash(t('syncFailed')));
1838
+ flash(t('syncFailed'));
1839
+ return false;
1840
+ }, () => { flash(t('syncFailed')); return false; });
1687
1841
  } catch (_e) {
1688
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
+ }
1689
1904
  }
1690
1905
  };
1691
1906
 
@@ -2063,39 +2278,78 @@ window.__ModuleLoader__.load({
2063
2278
  openRun(node, run);
2064
2279
  };
2065
2280
 
2066
- 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
+ }
2067
2293
  pushSnapshot();
2068
2294
  const newId = 'n' + Date.now().toString(36) + Math.random().toString(36).slice(2, 4);
2295
+ const prefs = lastNodePrefsRef.current || {};
2069
2296
  setNodes((ns) => {
2070
2297
  const i = ns.length;
2071
2298
  const center = viewportCenterWorld();
2072
2299
  const x = atWorld && typeof atWorld.x === 'number'
2073
- ? Math.round(atWorld.x - NODE_W / 2)
2300
+ ? (linkFrom ? Math.round(atWorld.x) : Math.round(atWorld.x - NODE_W / 2))
2074
2301
  : center.x + 40 + (ns.length % 3) * 30;
2075
2302
  const y = atWorld && typeof atWorld.y === 'number'
2076
- ? Math.round(atWorld.y - NODE_H / 2)
2303
+ ? (linkFrom ? Math.round(atWorld.y - socketCenterY(0)) : Math.round(atWorld.y - NODE_H / 2))
2077
2304
  : center.y - NODE_H / 2 + (ns.length % 3) * 40;
2078
- const normKind = kind === 'lead' ? 'lead' : (kind === 'condition' ? 'condition' : 'agent');
2079
2305
  const defaultLabel = normKind === 'lead'
2080
2306
  ? 'Lead 步骤 ' + i
2081
2307
  : (normKind === 'condition' ? (lang === 'en' ? 'Condition ' + i : '条件判断 ' + i) : 'Node ' + i);
2082
- return [...ns, {
2308
+ const nextNode = {
2083
2309
  id: newId,
2084
2310
  kind: normKind,
2085
2311
  x,
2086
2312
  y,
2087
2313
  label: defaultLabel,
2088
- provider: '',
2089
- model: '',
2090
- preset: normKind === 'condition' ? 'minimal' : 'standard',
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'),
2091
2318
  role: '',
2092
- }];
2319
+ };
2320
+ return [...ns, nextNode];
2093
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
+ }
2094
2336
  setSelectedIds([newId]);
2095
2337
  setAddMenu(null);
2096
2338
  };
2097
2339
 
2098
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
+ }
2099
2353
  setNodes((ns) => ns.map((n) => (n.id === id ? { ...n, ...patch } : n)));
2100
2354
  };
2101
2355
 
@@ -2308,6 +2562,7 @@ window.__ModuleLoader__.load({
2308
2562
  /** Release over an output socket: completes a drag that started at the unified left input. */
2309
2563
  const onOutputUp = (e, id, type, branch) => {
2310
2564
  if (!pending || pending.dir !== 'in') return;
2565
+ pendingHandledRef.current = true;
2311
2566
  e.preventDefault();
2312
2567
  e.stopPropagation();
2313
2568
  const b = typeof branch === 'string' ? branch.trim() : '';
@@ -2360,6 +2615,7 @@ window.__ModuleLoader__.load({
2360
2615
 
2361
2616
  const onInputUp = (e, id) => {
2362
2617
  if (!pending || pending.dir !== 'out') return;
2618
+ pendingHandledRef.current = true;
2363
2619
  e.preventDefault();
2364
2620
  e.stopPropagation();
2365
2621
  if (pending.fromId !== id) {
@@ -2442,8 +2698,8 @@ window.__ModuleLoader__.load({
2442
2698
  const keyActionsRef = useRef(null);
2443
2699
  keyActionsRef.current = {
2444
2700
  undo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode,
2445
- addMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen,
2446
- setAddMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen,
2701
+ addMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, decisionViewFor,
2702
+ setAddMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setDecisionViewFor,
2447
2703
  };
2448
2704
  useEffect(() => {
2449
2705
  const isEditable = (target) => {
@@ -2455,7 +2711,7 @@ window.__ModuleLoader__.load({
2455
2711
  const act = keyActionsRef.current;
2456
2712
  if (!act) return;
2457
2713
  if (ev.key === 'Escape') {
2458
- 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) {
2459
2715
  ev.preventDefault();
2460
2716
  act.setAddMenu(null);
2461
2717
  act.setRoleEditFor(null);
@@ -2463,24 +2719,26 @@ window.__ModuleLoader__.load({
2463
2719
  act.setMenuOpen(false);
2464
2720
  act.setPresetOpen(null);
2465
2721
  act.setHelpOpen(false);
2722
+ act.setDecisionViewFor(null);
2466
2723
  }
2467
2724
  return;
2468
2725
  }
2469
2726
  if (isEditable(ev.target)) return;
2470
2727
  if (act.addMenu) {
2728
+ const lf = act.addMenu.linkFrom || null;
2471
2729
  if (ev.key === '1' || ev.key === 'Enter') {
2472
2730
  ev.preventDefault();
2473
- act.addNode('agent', { x: act.addMenu.wx, y: act.addMenu.wy });
2731
+ act.addNode('agent', { x: act.addMenu.wx, y: act.addMenu.wy }, lf);
2474
2732
  return;
2475
2733
  }
2476
2734
  if (ev.key === '2') {
2477
2735
  ev.preventDefault();
2478
- act.addNode('lead', { x: act.addMenu.wx, y: act.addMenu.wy });
2736
+ act.addNode('lead', { x: act.addMenu.wx, y: act.addMenu.wy }, lf);
2479
2737
  return;
2480
2738
  }
2481
2739
  if (ev.key === '3') {
2482
2740
  ev.preventDefault();
2483
- act.addNode('condition', { x: act.addMenu.wx, y: act.addMenu.wy });
2741
+ act.addNode('condition', { x: act.addMenu.wx, y: act.addMenu.wy }, lf);
2484
2742
  return;
2485
2743
  }
2486
2744
  }
@@ -2543,7 +2801,7 @@ window.__ModuleLoader__.load({
2543
2801
  useEffect(() => {
2544
2802
  if (!dragging) return undefined;
2545
2803
  const move = (ev) => onCanvasMove(ev);
2546
- const up = () => onCanvasUp();
2804
+ const up = (ev) => onCanvasUp(ev);
2547
2805
  window.addEventListener('mousemove', move);
2548
2806
  window.addEventListener('mouseup', up);
2549
2807
  return () => {
@@ -2567,6 +2825,7 @@ window.__ModuleLoader__.load({
2567
2825
  }
2568
2826
  if (e.button !== 0) return;
2569
2827
  if (roleEditFor) setRoleEditFor(null);
2828
+ if (decisionViewFor) setDecisionViewFor(null);
2570
2829
  if (menuOpen) setMenuOpen(false);
2571
2830
  if (addMenu) setAddMenu(null);
2572
2831
  if (presetOpen) setPresetOpen(null);
@@ -2635,7 +2894,7 @@ window.__ModuleLoader__.load({
2635
2894
  }
2636
2895
  };
2637
2896
 
2638
- const onCanvasUp = () => {
2897
+ const onCanvasUp = (ev) => {
2639
2898
  if (cutRef.current) {
2640
2899
  cutRef.current = null;
2641
2900
  setDragging(false);
@@ -2658,6 +2917,39 @@ window.__ModuleLoader__.load({
2658
2917
  setPanning(false);
2659
2918
  }
2660
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
+ }
2661
2953
  setPending(null);
2662
2954
  setDragging(false);
2663
2955
  };
@@ -2781,8 +3073,16 @@ window.__ModuleLoader__.load({
2781
3073
  '.dsh/canvas/session-' + bare + '.json',
2782
3074
  '.dsh/canvas/' + bare + '.json',
2783
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);
2784
3083
  let alive = true;
2785
3084
  let lastText = '';
3085
+ let lastRunText = '';
2786
3086
  const tick = async () => {
2787
3087
  try {
2788
3088
  let text = '';
@@ -2797,30 +3097,51 @@ window.__ModuleLoader__.load({
2797
3097
  setSyncNote(t('syncReadFail') + String((err && err.message) || err).slice(0, 80));
2798
3098
  }
2799
3099
  }
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;
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'));
2812
3123
  }
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
3124
  }
2822
- else setSyncNote(t('syncBadFile'));
2823
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 */ }
2824
3145
  };
2825
3146
  const timer = setInterval(tick, 1500);
2826
3147
  tick();
@@ -3187,6 +3508,13 @@ window.__ModuleLoader__.load({
3187
3508
  }
3188
3509
  }
3189
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
+
3190
3518
  const edgeEls = edges.map((edge) => {
3191
3519
  const from = nodeById.get(edge.from);
3192
3520
  const to = nodeById.get(edge.to);
@@ -3194,6 +3522,7 @@ window.__ModuleLoader__.load({
3194
3522
  const color = edgeColorFor(from, edge);
3195
3523
  const d = edgePath(from, to, edge);
3196
3524
  const highlighted = cutVictims.includes(edge.id);
3525
+ const isPrunedEdge = !highlighted && (blockedEdgeSet.has(edgeKeyForState(edge)) || prunedSet.has(edge.from) || prunedSet.has(edge.to));
3197
3526
  const hasSel = selectedSet.size > 0;
3198
3527
  const linkedToSel = hasSel && (selectedSet.has(edge.from) || selectedSet.has(edge.to));
3199
3528
  const toRunning = enabled && statusById[edge.to] === 'running';
@@ -3201,7 +3530,7 @@ window.__ModuleLoader__.load({
3201
3530
  || from.kind === 'lead'
3202
3531
  || statusById[edge.from] === 'done'
3203
3532
  || statusById[edge.from] === 'failed';
3204
- const isFlowing = enabled && !highlighted && (
3533
+ const isFlowing = enabled && !highlighted && !isPrunedEdge && (
3205
3534
  (toRunning && fromReady)
3206
3535
  || (leadReadyIds.has(edge.to) && (statusById[edge.from] === 'done' || statusById[edge.from] === 'failed'))
3207
3536
  );
@@ -3214,11 +3543,11 @@ window.__ModuleLoader__.load({
3214
3543
  || statusById[edge.to] === 'failed'
3215
3544
  || leadReadyIds.has(edge.to)
3216
3545
  || leadDoneIds.has(edge.to);
3217
- const isCompletedLink = enabled && !highlighted && fromSettled && toSettled;
3218
- const dimmed = hasSel && !linkedToSel && !highlighted && !isFlowing;
3546
+ const isCompletedLink = enabled && !highlighted && !isPrunedEdge && fromSettled && toSettled;
3547
+ const dimmed = isPrunedEdge || (hasSel && !linkedToSel && !highlighted && !isFlowing);
3219
3548
  const strokeColor = highlighted ? '#e5534b' : color;
3220
3549
  const baseWidth = highlighted ? 3 : (linkedToSel || isFlowing ? 2.6 : 2);
3221
- 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)));
3222
3551
  const useGlow = fxLevel === 'vivid' && !dimmed;
3223
3552
  const showDashFlow = isFlowing && fxLevel !== 'minimal';
3224
3553
  const showBead = isFlowing && fxLevel === 'vivid';
@@ -3247,6 +3576,7 @@ window.__ModuleLoader__.load({
3247
3576
  stroke: strokeColor,
3248
3577
  strokeWidth: baseWidth,
3249
3578
  strokeOpacity: showDashFlow ? 0.35 : baseOpacity,
3579
+ strokeDasharray: isPrunedEdge ? '4 4' : undefined,
3250
3580
  fill: 'none',
3251
3581
  }),
3252
3582
  showDashFlow && fxLevel === 'vivid' && h('path', {
@@ -3300,16 +3630,20 @@ window.__ModuleLoader__.load({
3300
3630
  });
3301
3631
  if (node.kind === 'condition') {
3302
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;
3303
3635
  return h('div', { style: S.band },
3304
3636
  unifiedInSocket,
3305
3637
  h('span', { style: { ...S.rowLabel, position: 'absolute', left: '12px', top: '3px', pointerEvents: 'none' } }, inText),
3306
3638
  branches.map((b) => {
3307
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));
3308
3642
  const outTip = !b.custom
3309
3643
  ? (b.id === 'true' ? t('tipCondTrue') : t('tipCondFalse'))
3310
3644
  : t('tipBranchOut');
3311
3645
  const editKey = 'branch:' + node.id + ':' + b.id;
3312
- return h('div', { key: b.id, style: S.condBranchRow },
3646
+ return h('div', { key: b.id, style: { ...S.condBranchRow, opacity: isUnmatchedBranch ? 0.48 : 1 } },
3313
3647
  h('div', {
3314
3648
  style: { display: 'flex', alignItems: 'center', marginRight: '10px' },
3315
3649
  onMouseDown: (e) => e.stopPropagation(),
@@ -3323,7 +3657,11 @@ window.__ModuleLoader__.load({
3323
3657
  onClick: () => setRoleEditFor(roleEditFor === editKey ? null : editKey),
3324
3658
  }, '⤢'),
3325
3659
  h('input', {
3326
- style: { ...S.condBranchInput, borderRight: '2px solid ' + b.color },
3660
+ style: {
3661
+ ...S.condBranchInput,
3662
+ borderRight: '2px solid ' + b.color,
3663
+ borderColor: isMatchedBranch ? b.color : C.border,
3664
+ },
3327
3665
  value: b.label,
3328
3666
  placeholder: t('branchPh'),
3329
3667
  onFocus: () => setSelectedIds([node.id]),
@@ -3685,30 +4023,36 @@ window.__ModuleLoader__.load({
3685
4023
  }),
3686
4024
  h('span', null, (enabled ? t('enabled') : t('disabled')).replace(/^[●○]\s*/, '')),
3687
4025
  ),
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
- ),
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
+ })(),
3712
4056
  h('div', {
3713
4057
  ref: canvasElRef,
3714
4058
  style: {
@@ -3744,9 +4088,10 @@ window.__ModuleLoader__.load({
3744
4088
  strokeWidth: 1,
3745
4089
  strokeDasharray: '4 3',
3746
4090
  }),
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);
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);
3750
4095
  return h('path', { d, stroke: color, strokeWidth: 2, strokeDasharray: '4 4', fill: 'none' });
3751
4096
  })(),
3752
4097
  ),
@@ -3797,6 +4142,9 @@ window.__ModuleLoader__.load({
3797
4142
  ? 'linear-gradient(90deg, #d29922 0%, #f2cc60 50%, #d29922 100%)'
3798
4143
  : 'linear-gradient(90deg, #2f81f7 0%, #58d580 50%, #2f81f7 100%)'))
3799
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;
3800
4148
  return h('div', {
3801
4149
  key: node.id,
3802
4150
  'data-node': node.id,
@@ -3807,10 +4155,11 @@ window.__ModuleLoader__.load({
3807
4155
  left: node.x + WORLD_PAD,
3808
4156
  top: node.y + WORLD_PAD,
3809
4157
  ...(isLeadKind ? S.leadNode : null),
3810
- ...(isInactive ? S.orphanNode : null),
4158
+ ...(isInactive || isPruned ? S.orphanNode : null),
3811
4159
  ...(stateStyle || null),
4160
+ ...(decisionViewFor === node.id ? { zIndex: 40 } : null),
3812
4161
  },
3813
- 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))),
3814
4163
  onMouseDown: (e) => onNodeDown(e, node.id),
3815
4164
  },
3816
4165
  h('div', {
@@ -3822,7 +4171,55 @@ window.__ModuleLoader__.load({
3822
4171
  }),
3823
4172
  h('div', { style: S.nodeHeader }),
3824
4173
  h('div', { style: S.bandDivider }),
3825
- isDeadEnd
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
4192
+ ? 'rgba(63,185,80,0.14)'
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
3826
4223
  ? h('div', {
3827
4224
  style: S.warnChip,
3828
4225
  title: t('tipDeadEnd'),
@@ -3843,14 +4240,15 @@ window.__ModuleLoader__.load({
3843
4240
  : isDone
3844
4241
  ? 'rgba(63,185,80,0.14)'
3845
4242
  : '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');
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');
3854
4252
  const glyph = nodeStatus === 'running'
3855
4253
  ? h('span', {
3856
4254
  className: fxLevel !== 'minimal' ? 'dsh-wc-dot-live' : undefined,
@@ -4088,6 +4486,44 @@ window.__ModuleLoader__.load({
4088
4486
  onMouseDown: (e) => e.stopPropagation(),
4089
4487
  onClick: () => deleteNode(node.id),
4090
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
+ ),
4091
4527
  renderBand(node),
4092
4528
  );
4093
4529
  }),
@@ -4126,7 +4562,7 @@ window.__ModuleLoader__.load({
4126
4562
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
4127
4563
  }
4128
4564
  },
4129
- __test: { topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, 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 },
4130
4566
  };
4131
4567
  },
4132
4568
  });
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.0",
4
4
  "description": "A visual subagent-workflow canvas for DeepSeek Harness, docked in the sidebar.",
5
5
  "type": "module",
6
6
  "main": "index.js",