dsh-workflow-canvas 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -1,2192 +1,2192 @@
1
- window.__ModuleLoader__.load({
2
- id: '@local/dsh-workflow-canvas',
3
- factory(require) {
4
- const React = require('react');
5
- const h = React.createElement;
6
- const useState = React.useState;
7
- const useRef = React.useRef;
8
- const useEffect = React.useEffect;
9
- const Component = React.Component;
10
-
11
- /** Resolved lazily so a missing namespace can never fail plugin load. */
12
- let workspaceFilesService = null;
13
- function resolveWorkspaceFiles(ctx) {
14
- if (workspaceFilesService) return workspaceFilesService;
15
- try {
16
- if (ctx && typeof ctx.get === 'function') {
17
- workspaceFilesService = ctx.get('remote.workspaceFiles') || null;
18
- }
19
- } catch (_e) { /* service absent */ }
20
- if (!workspaceFilesService) {
21
- try {
22
- workspaceFilesService = (ctx && ctx.remote && ctx.remote.workspaceFiles) || null;
23
- } catch (_e) { /* proxy refuses unknown namespaces */ }
24
- }
25
- return workspaceFilesService;
26
- }
27
-
28
- const TAB_ID = '@local/dsh-workflow-canvas';
29
- const KIND = 'workflow';
30
- const STORAGE_PREFIX = 'dsh-workflow-canvas:v1:';
31
- const PRESET_KEY = STORAGE_PREFIX + 'presets';
32
-
33
- const NODE_W = 216;
34
- const NODE_H = 224;
35
- const PORT = 12;
36
- const SOCKET_BAND_TOP = 168;
37
- const ROW_H = 18;
38
- const CONTENT_W = 2400;
39
- const CONTENT_H = 1600;
40
- /** World origin offset: keeps negative node coordinates inside the scroll area. */
41
- const WORLD_PAD = 2000;
42
-
43
- // One socket per channel type: a link can only join the same type.
44
- const SOCKET_TYPES = [
45
- { id: 'prompt', label: 'prompt', color: '#8a8f98' },
46
- { id: 'structured', label: 'structured', color: '#2f81f7' },
47
- { id: 'session-ref', label: 'session', color: '#a371f7' },
48
- ];
49
-
50
- /** Fallback effort ids when the model catalog carries no reasoning metadata. */
51
- const REASONING_FALLBACK = ['low', 'medium', 'high'];
52
-
53
- const LANG_KEY = STORAGE_PREFIX + 'lang';
54
- const I18N = {
55
- zh: {
56
- addAgent: '+ 子代理', addLead: '+ Lead', undo: '↶ 撤销', sync: '↥ 同步',
57
- enabled: '● 已启用', disabled: '○ 已禁用', presetName: '预设名', save: '☆ 保存',
58
- presets: '☰ 预设', unsaved: '有未同步改动', synced: '已同步',
59
- pickModel: '选择模型', defaultEffort: '默认',
60
- leadThis: 'Lead(本对话)',
61
- tipSocketOut: '拖出可断开 / 拖入可连接',
62
- tipSocketIn: '从这里拖出连线 / 也可以把输入口拖到这里',
63
- delNodeTip: '删除节点(可用 ↶ 撤销 找回)',
64
- deletedNode: '节点已删除,可点「撤销」找回',
65
- orphanTip: '未连线:运行时会被跳过',
66
- syncOff: '自动同步不可用',
67
- syncNoSession: '无会话 id',
68
- syncReadFail: '读取失败: ',
69
- syncApplied: '已应用生成结果',
70
- syncBadFile: '文件内容无效',
71
- generated: '已从对话生成画布',
72
- dupName: '已存在,请换一个名字',
73
- guideDesc: '画一张子代理流程图',
74
- model: '模型', reason: '推理', role: '分工', task: '任务', taskPh: '本次任务:例如把这批反馈归类并给出建议',
75
- rolePhLead: '我自己这一步做什么', rolePhAgent: '这个子代理做什么',
76
- memory: '记忆', scope: '能力', retry: '重试', jsonOut: 'JSON 输出',
77
- sep: ': ', on: '开', off: '关', allTools: '默认(全部工具)', none: '无',
78
- scopeMinimal: 'minimal(只读思考)', scopeStandard: 'standard(全部工具)',
79
- fallbackModel: '备用',
80
- stPending: '未执行', stRunning: '进行中', stDone: '已完成', stFailed: '失败',
81
- stOrphan: '未连线', stLead: '由对话执行',
82
- presetEmpty: '还没有保存过预设', del: '删除这个预设',
83
- needName: '请先给预设起个名字', duplicate: '已存在,请换一个名字',
84
- savedPreset: '已保存预设', saveFailed: '保存失败(存储不可用)',
85
- loadedPreset: '已载入预设', invalidPreset: '预设内容无效', deletedPreset: '已删除预设',
86
- syncFailed: '同步失败', upToDate: '已是最新', syncedToHost: '已同步到 Host',
87
- cannotOpen: '无法打开会话', undoDone: '已撤销', undoNone: '没有可撤销的操作',
88
- leadLocked: '入口 Lead 不能删除', modelsMissing: '模型列表未加载',
89
- tipLead: 'Lead 步骤在对话里执行,画布不追踪其状态',
90
- tipOrphan: '未连线:运行时会被跳过', tipStatus: '子代理节点的运行状态',
91
- tipZoom: '滚轮缩放(以光标为中心)',
92
- tipResetZoom: '回到 100% 并把画面中心拉到 Lead 节点',
93
- tipLocate: '把画面中心拉到 Lead(本对话)节点',
94
- locate: '◎ 定位',
95
- importBtn: '⇩ 导入',
96
- tipImport: '从剪贴板导入模型生成的画布(先复制聊天里的画布 JSON)',
97
- importOk: '已导入画布,共 ',
98
- tipMore: '更多',
99
- help: '使用说明',
100
- helpTitle: '怎么用这个画布',
101
- close: '关闭',
102
- cutLinks: '右键划断连线',
103
- linkCut: '已断开一条连线',
104
- tipToggle: '启用/禁用此画布(启用后我才能执行它)',
105
- helpBody: [
106
- '1. 在入口 Lead 里写「本次任务」,这是整张图的总目标。',
107
- '2. 点「+ 子代理」加节点,从右侧输出口拖到另一个节点左侧输入口即可连线。',
108
- '3. 连线有三种:prompt 传文本,structured 传 JSON,session 让下游接着上游的会话跑。',
109
- '4. 端口颜色即类型,只能同色相连;拖已连接的左口可以断开。',
110
- '5. 每个节点可设模型、推理强度、能力范围、备用模型、是否记忆。',
111
- '6. 连好后点「● 已启用」,然后对对话说「跑一次」,由我调用执行。',
112
- '7. 遇到 Lead 节点会暂停,我做完再把结果交回去继续。',
113
- '8. 没连线的节点显示为虚线,运行时会被跳过。',
114
- '9. 右键按住划过一条连线可以切断;可在「⋯」里关掉这个手势。',
115
- '10. 预设名 + ☆ 保存 可以把整张图存下来,新对话里从「☰ 预设」载入。',
116
- '11. 你可以直接让我改画布:说「把那三个节点的分工改成…」,我会就地修改,不动你摆的位置。',
117
- '12. session 线连到 Lead 时,我会在暂停那步拿到那个子代理的会话,可以继续追问它。',
118
- ].join('\n'),
119
- importNone: '剪贴板里没有可识别的画布数据',
120
- importBad: '画布数据格式不对',
121
- tipSync: '把当前画布同步给 Host(会在对话里留一条同步记录)',
122
- tipUndo: '撤销上一步结构改动', tipSave: '把当前画布保存为预设',
123
- tipPresets: '载入已保存的预设', tipModel: '推理等级(默认 = 该模型声明的 defaultEffort)',
124
- tipMemory: '记忆:复用这个节点上一次的会话(仅同一进程内有效)',
125
- tipPreset: '能力范围(点一下切换):standard = 全部工具(读写文件、跑命令、子代理、工作流、网页、办公);minimal = 只读思考(文件读写关闭,没有子代理/工作流/网页)',
126
- tipFallback: '失败重试:该节点出错时自动换一个模型再跑一次',
127
- tipStructured: 'JSON 输出:要求该节点返回 JSON 对象,structured 连线会把结果作为 JSON 传给下游',
128
- lang: 'ZH',
129
- },
130
- en: {
131
- addAgent: '+ Subagent', addLead: '+ Lead', undo: '↶ Undo', sync: '↥ Sync',
132
- enabled: '● ON', disabled: '○ OFF', presetName: 'Preset name', save: '☆ Save',
133
- presets: '☰ Presets', unsaved: 'Unsaved changes', synced: 'Synced',
134
- pickModel: 'Pick a model', defaultEffort: 'default',
135
- leadThis: 'Lead (this chat)',
136
- tipSocketOut: 'Drag to detach / drop to connect',
137
- tipSocketIn: 'Drag out to link, or drop an input here',
138
- delNodeTip: 'Delete this node (undo with ↶)',
139
- deletedNode: 'Node deleted, use Undo to restore it',
140
- orphanTip: 'Unlinked: skipped when the canvas runs',
141
- syncOff: 'Auto-sync unavailable',
142
- syncNoSession: 'No session id',
143
- syncReadFail: 'Read failed: ',
144
- syncApplied: 'Generated canvas applied',
145
- syncBadFile: 'File content is invalid',
146
- generated: 'Canvas generated from chat',
147
- dupName: 'already exists, pick another name',
148
- guideDesc: 'Sketch a subagent workflow',
149
- model: 'Model', reason: 'Reasoning', role: 'Role', task: 'Task', taskPh: 'Task, e.g. classify these reports and suggest actions',
150
- rolePhLead: 'What I do in this step', rolePhAgent: 'What this subagent does',
151
- memory: 'Memory', scope: 'Scope', retry: 'Retry', jsonOut: 'JSON out',
152
- sep: ': ', on: 'on', off: 'off', allTools: 'default (all tools)', none: 'none',
153
- scopeMinimal: 'minimal (read-only thinking)', scopeStandard: 'standard (all tools)',
154
- fallbackModel: 'Fallback',
155
- stPending: 'Pending', stRunning: 'Running', stDone: 'Done', stFailed: 'Failed',
156
- stOrphan: 'Unlinked', stLead: 'Runs in chat',
157
- presetEmpty: 'No presets saved yet', del: 'Delete this preset',
158
- needName: 'Name the preset first', duplicate: 'already exists, pick another name',
159
- savedPreset: 'Saved preset', saveFailed: 'Save failed (storage unavailable)',
160
- loadedPreset: 'Loaded preset', invalidPreset: 'Preset content is invalid', deletedPreset: 'Deleted preset',
161
- syncFailed: 'Sync failed', upToDate: 'Already up to date', syncedToHost: 'Synced to host',
162
- cannotOpen: 'Cannot open the session', undoDone: 'Undone', undoNone: 'Nothing to undo',
163
- leadLocked: 'The entry Lead cannot be deleted', modelsMissing: 'Model list is not loaded',
164
- tipLead: 'Lead steps run in the chat; the canvas does not track them',
165
- tipOrphan: 'Unlinked: skipped when the canvas runs', tipStatus: 'Subagent run status',
166
- tipZoom: 'Wheel zooms around the cursor',
167
- tipResetZoom: 'Reset to 100% and centre the view on the Lead node',
168
- tipLocate: 'Centre the view on the Lead (this conversation) node',
169
- locate: '◎ Locate',
170
- importBtn: '⇩ Import',
171
- tipImport: 'Import a model-generated canvas from the clipboard (copy the canvas JSON from chat first)',
172
- importOk: 'Canvas imported, ',
173
- tipMore: 'More',
174
- help: 'How to use',
175
- helpTitle: 'Using this canvas',
176
- close: 'Close',
177
- cutLinks: 'Right-drag to cut links',
178
- linkCut: 'Link cut',
179
- tipToggle: 'Enable or disable this canvas (I can only run it while enabled)',
180
- helpBody: [
181
- '1. Write the overall task in the entry Lead node.',
182
- '2. Add nodes with the + buttons, then drag from a right socket to a left socket.',
183
- '3. Links carry text (prompt), JSON (structured), or continue the upstream session (session).',
184
- '4. Socket colour is the type; only matching types connect. Drag a connected input to detach.',
185
- '5. Each node sets model, reasoning, capability scope, fallback model and memory.',
186
- '6. Press ● ON, then ask in chat to run the canvas.',
187
- '7. The run pauses at every Lead node so the conversation can do that step.',
188
- '8. Unlinked nodes are dashed and skipped at run time.',
189
- '9. Hold the right button and sweep across a link to cut it; turn the gesture off under ⋯.',
190
- '10. Name a preset and press ☆ Save to keep the canvas for other sessions.',
191
- '11. You can ask me to edit the canvas; I patch it in place and keep your layout.',
192
- '12. A session link into a Lead step hands me that child agent, so I can follow up with it.',
193
- ].join('\n'),
194
- importNone: 'No canvas data found in the clipboard',
195
- importBad: 'Canvas data is malformed',
196
- tipSync: 'Publish this canvas to the host (leaves one sync record in the chat)',
197
- tipUndo: 'Undo the last structural change', tipSave: 'Save this canvas as a preset',
198
- tipPresets: 'Load a saved preset', tipModel: 'Reasoning effort (default = the model\'s defaultEffort)',
199
- tipMemory: 'Memory: reuse this node\'s previous session (same process only)',
200
- tipPreset: 'Capability (click to toggle): standard = all tools (files, shells, subagents, workflow, web, office); minimal = read-only thinking (no file writes, no subagents/workflow/web)',
201
- tipFallback: 'Retry: when this node fails, rerun it once on another model',
202
- tipStructured: 'JSON output: require an object result; structured links pass it downstream as JSON',
203
- lang: 'EN',
204
- },
205
- };
206
-
207
- /** Bilingual string for text read outside the component (tab titles, guide). */
208
- function pick(zh, en) {
209
- return loadLang() === 'en' ? en : zh;
210
- }
211
-
212
- function loadLang() {
213
- try {
214
- const v = window.localStorage.getItem(LANG_KEY);
215
- return v === 'en' ? 'en' : 'zh';
216
- } catch (_e) {
217
- return 'zh';
218
- }
219
- }
220
-
221
- const C = {
222
- text: 'var(--dsw-alias-label-primary, inherit)',
223
- dim: 'var(--dsw-alias-label-tertiary, rgba(140,140,140,0.95))',
224
- border: 'var(--dsw-alias-border-l2, rgba(128,128,128,0.4))',
225
- raised: 'var(--dsw-alias-bg-layer-1, rgba(128,128,128,0.10))',
226
- elevated: 'var(--dsw-alias-bg-elevated, #2a2b2f)',
227
- base: 'var(--dsw-alias-bg-base, transparent)',
228
- hover: 'var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,0.18))',
229
- accent: 'var(--dsw-alias-brand-primary, #2f81f7)',
230
- };
231
-
232
- const S = {
233
- root: {
234
- boxSizing: 'border-box', height: '100%', width: '100%',
235
- display: 'flex', flexDirection: 'column',
236
- background: C.base, color: C.text, fontSize: '13px',
237
- },
238
- toolbar: {
239
- display: 'flex', alignItems: 'center', gap: '6px',
240
- padding: '8px 10px', borderBottom: '1px solid ' + C.border, flex: '0 0 auto',
241
- },
242
- btn: {
243
- padding: '5px 10px', borderRadius: '6px', border: '1px solid ' + C.border,
244
- background: C.raised, color: C.text, fontSize: '12px', cursor: 'pointer', whiteSpace: 'nowrap',
245
- },
246
- toggleOn: {
247
- padding: '5px 12px', borderRadius: '6px', border: '1px solid ' + C.accent,
248
- background: 'transparent', color: C.accent, fontSize: '12px', fontWeight: 600,
249
- cursor: 'pointer', whiteSpace: 'nowrap',
250
- },
251
- toggleOff: {
252
- padding: '5px 12px', borderRadius: '6px', border: '1px solid ' + C.border,
253
- background: 'transparent', color: C.dim, fontSize: '12px',
254
- cursor: 'pointer', whiteSpace: 'nowrap',
255
- },
256
- status: {
257
- fontSize: '11px', color: C.dim,
258
- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%',
259
- },
260
- floatOn: {
261
- position: 'absolute', top: '52px', left: '10px', zIndex: 30,
262
- padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.accent,
263
- background: C.elevated, color: C.accent, fontSize: '11px', fontWeight: 600,
264
- cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
265
- },
266
- floatOff: {
267
- position: 'absolute', top: '52px', left: '10px', zIndex: 30,
268
- padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.border,
269
- background: C.elevated, color: C.dim, fontSize: '11px', fontWeight: 600,
270
- cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
271
- },
272
- moreBar: { position: 'relative', flex: '0 0 auto' },
273
- moreMenu: {
274
- position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '190px',
275
- background: C.elevated, border: '1px solid ' + C.border, borderRadius: '6px',
276
- zIndex: 80, padding: '4px', boxShadow: '0 10px 26px rgba(0,0,0,0.45)',
277
- },
278
- moreRow: {
279
- padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
280
- whiteSpace: 'nowrap', color: C.text,
281
- },
282
- helpOverlay: {
283
- position: 'absolute', inset: '0', background: 'rgba(0,0,0,0.45)', zIndex: 90,
284
- display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '12px',
285
- },
286
- helpCard: {
287
- width: '100%', maxWidth: '420px', maxHeight: '100%', overflow: 'auto',
288
- background: C.elevated, border: '1px solid ' + C.border, borderRadius: '8px',
289
- boxShadow: '0 16px 40px rgba(0,0,0,0.5)', padding: '12px',
290
- },
291
- helpHead: { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' },
292
- helpTitle: { flex: '1 1 auto', fontSize: '13px', fontWeight: 600, color: C.text },
293
- helpBody: { fontSize: '11px', lineHeight: '17px', color: C.dim },
294
- helpLine: { whiteSpace: 'pre-wrap' },
295
- presetBar: {
296
- marginLeft: 'auto', display: 'flex', flexDirection: 'column', alignItems: 'flex-end',
297
- gap: '3px', position: 'relative', flex: '0 0 auto',
298
- },
299
- presetRowTop: { display: 'flex', alignItems: 'center', gap: '5px' },
300
- presetMenu: {
301
- position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '190px',
302
- maxHeight: '260px', overflowY: 'auto', background: C.elevated,
303
- border: '1px solid ' + C.border, borderRadius: '6px', zIndex: 60, padding: '4px',
304
- boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
305
- },
306
- presetRow: {
307
- display: 'flex', alignItems: 'center', gap: '6px', padding: '5px 6px',
308
- borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
309
- },
310
- presetRowText: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
311
- presetDel: {
312
- flex: '0 0 auto', padding: '0 4px', borderRadius: '3px', border: 'none',
313
- background: 'transparent', color: '#e5534b', fontSize: '11px', cursor: 'pointer',
314
- },
315
- presetInput: {
316
- width: '92px', padding: '3px 6px', borderRadius: '5px', border: '1px solid ' + C.border,
317
- background: C.base, color: C.text, fontSize: '11px', outline: 'none', userSelect: 'text',
318
- },
319
- presetEmpty: { padding: '6px', fontSize: '10px', color: C.dim },
320
- syncNote: { fontSize: '10px', color: C.dim, maxWidth: '140px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
321
- canvas: { position: 'relative', flex: '1 1 auto', overflow: 'auto', minHeight: '0', userSelect: 'none' },
322
- content: { position: 'relative', width: CONTENT_W, height: CONTENT_H },
323
-
324
- node: {
325
- position: 'absolute', width: NODE_W, height: NODE_H, boxSizing: 'border-box',
326
- borderRadius: '10px', border: '1px solid ' + C.border,
327
- background: C.raised, color: C.text, cursor: 'grab',
328
- boxShadow: '0 1px 4px rgba(0,0,0,0.3)',
329
- },
330
- nodeSel: { border: '2px solid ' + C.accent },
331
- leadNode: {},
332
- orphanNode: { border: '1px dashed ' + C.dim, opacity: 0.65 },
333
-
334
- title: {
335
- position: 'absolute', left: '10px', right: '10px', top: '10px', height: '18px',
336
- fontWeight: 600, fontSize: '13px', lineHeight: '18px',
337
- border: 'none', background: 'transparent', color: C.text, padding: 0, margin: 0,
338
- outline: 'none', boxSizing: 'border-box', userSelect: 'text',
339
- },
340
- titleReadonly: {
341
- position: 'absolute', left: '10px', right: '10px', top: '10px', height: '18px',
342
- fontWeight: 600, fontSize: '13px', lineHeight: '18px',
343
- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
344
- },
345
- topBar: {
346
- position: 'absolute', left: 0, right: 0, top: 0, height: '4px',
347
- borderRadius: '10px 10px 0 0', zIndex: 2, pointerEvents: 'none',
348
- },
349
- statusChip: {
350
- position: 'absolute', right: '10px', bottom: '3px', fontSize: '9px', lineHeight: '14px',
351
- color: C.dim, pointerEvents: 'none', zIndex: 3, whiteSpace: 'nowrap',
352
- },
353
-
354
- fieldModel: { position: 'absolute', left: '10px', right: '10px', top: '28px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
355
- fieldReason: { position: 'absolute', left: '10px', right: '10px', top: '50px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
356
- fieldScope: { position: 'absolute', left: '10px', right: '10px', top: '72px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
357
- fieldFallback: { position: 'absolute', left: '10px', right: '10px', top: '94px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
358
- fieldMemory: { position: 'absolute', left: '10px', right: '10px', top: '116px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
359
- fieldRole: { position: 'absolute', left: '10px', right: '10px', top: '138px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
360
- fieldRoleTop: { position: 'absolute', left: '10px', right: '10px', top: '34px', height: '24px', display: 'flex', alignItems: 'center', gap: '6px' },
361
- optRow: {
362
- position: 'absolute', left: '10px', right: '10px', top: '114px', height: '18px',
363
- display: 'flex', alignItems: 'center', gap: '5px', fontSize: '9px', color: C.dim,
364
- overflow: 'hidden',
365
- },
366
-
367
- toggleSwitch: {
368
- flex: '1 1 auto', width: '100%', height: '18px', boxSizing: 'border-box', padding: '0 5px', borderRadius: '4px',
369
- border: '1px solid ' + C.border, background: C.base, color: C.text,
370
- fontSize: '10px', cursor: 'pointer', outline: 'none', textAlign: 'center', lineHeight: '14px',
371
- },
372
- toggleSwitchOn: {
373
- flex: '1 1 auto', width: '100%', height: '18px', boxSizing: 'border-box', padding: '0 5px', borderRadius: '4px',
374
- border: '1px solid ' + C.accent, background: C.base, color: C.accent,
375
- fontSize: '10px', cursor: 'pointer', outline: 'none', textAlign: 'center', lineHeight: '14px',
376
- },
377
- optChip: {
378
- flex: '0 0 auto', padding: '2px 6px', borderRadius: '4px',
379
- border: '1px solid ' + C.border, background: 'transparent', color: C.dim,
380
- fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '12px',
381
- outline: 'none',
382
- },
383
- optChipOn: {
384
- flex: '0 0 auto', padding: '2px 6px', borderRadius: '4px',
385
- border: '1px solid ' + C.accent, background: C.hover, color: C.accent,
386
- fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '12px',
387
- outline: 'none',
388
- },
389
- fieldLabel: { flex: '0 0 30px', width: '30px', fontSize: '9px', color: C.dim },
390
-
391
- input: {
392
- flex: '1 1 auto', minWidth: '0', padding: '3px 6px', borderRadius: '5px',
393
- border: '1px solid ' + C.border, background: C.base, color: C.text, fontSize: '12px',
394
- outline: 'none', userSelect: 'text',
395
- },
396
- rolePopover: {
397
- position: 'absolute', left: '100%', top: '0', marginLeft: '8px', width: '230px',
398
- background: C.elevated, border: '1px solid ' + C.border, borderRadius: '8px',
399
- boxShadow: '0 10px 26px rgba(0,0,0,0.45)', padding: '8px', zIndex: 70,
400
- },
401
- roleArea: {
402
- width: '100%', height: '96px', boxSizing: 'border-box', resize: 'none',
403
- background: C.base, color: C.text, fontSize: '11px', lineHeight: '15px',
404
- border: '1px solid ' + C.border, borderRadius: '5px', padding: '5px 6px',
405
- outline: 'none', userSelect: 'text',
406
- },
407
- leadLabel: { position: 'absolute', left: '10px', right: '10px', top: '26px', height: '16px', display: 'flex', alignItems: 'center' },
408
- task: {
409
- position: 'absolute', left: '10px', right: '10px', top: '44px', height: '118px',
410
- padding: '4px 6px', borderRadius: '5px', border: '1px solid ' + C.border,
411
- background: C.base, color: C.text, fontSize: '11px', resize: 'none', outline: 'none',
412
- lineHeight: '14px', boxSizing: 'border-box', userSelect: 'text',
413
- },
414
-
415
- selectBtn: {
416
- flex: '1 1 auto', minWidth: '0', width: '100%', height: '18px', boxSizing: 'border-box',
417
- display: 'flex', alignItems: 'center', gap: '4px',
418
- padding: '0 5px', borderRadius: '4px', border: '1px solid ' + C.border,
419
- background: C.base, color: C.text, fontSize: '10px', cursor: 'pointer', textAlign: 'left',
420
- lineHeight: '14px',
421
- },
422
- reasonChip: {
423
- flex: '0 0 auto', maxWidth: '44px', padding: '3px 4px', borderRadius: '5px',
424
- border: '1px solid ' + C.border, background: 'transparent', color: C.dim,
425
- fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap',
426
- overflow: 'hidden', textOverflow: 'ellipsis',
427
- },
428
- selectText: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
429
- caret: { flex: '0 0 auto', color: C.dim, fontSize: '9px' },
430
- menu: {
431
- position: 'absolute', left: 0, right: 0, top: '100%', marginTop: '4px',
432
- maxHeight: '220px', overflowY: 'auto', background: C.elevated,
433
- border: '1px solid ' + C.border, borderRadius: '6px',
434
- boxShadow: '0 8px 24px rgba(0,0,0,0.4)', zIndex: 50, padding: '4px',
435
- },
436
- menuRow: {
437
- padding: '3px 7px', borderRadius: '4px', fontSize: '10px', cursor: 'pointer',
438
- overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
439
- },
440
- menuHead: { padding: '6px 8px 2px', fontSize: '10px', color: C.dim, textTransform: 'uppercase', letterSpacing: '0.04em' },
441
-
442
- band: { position: 'absolute', left: 0, right: 0, top: SOCKET_BAND_TOP + 'px' },
443
- row: { position: 'relative', height: ROW_H + 'px', display: 'flex', alignItems: 'center', justifyContent: 'center' },
444
- rowLabel: { fontSize: '9px', color: C.dim, letterSpacing: '0.02em' },
445
- socket: {
446
- position: 'absolute', top: (ROW_H - PORT) / 2, width: PORT, height: PORT,
447
- borderRadius: '50%', background: C.raised, border: '2px solid ' + C.border,
448
- boxSizing: 'border-box', cursor: 'crosshair', zIndex: 6,
449
- /* a little extra grab area without changing the drawn dot */
450
- padding: 0, margin: -3, boxShadow: '0 0 0 3px transparent',
451
- },
452
- nodeDelete: {
453
- position: 'absolute', right: '-8px', top: '-8px', width: '18px', height: '18px',
454
- borderRadius: '50%', background: C.elevated, border: '1px solid ' + C.border,
455
- color: '#e5534b', fontSize: '12px', lineHeight: '16px', textAlign: 'center',
456
- cursor: 'pointer', zIndex: 8, userSelect: 'none',
457
- },
458
- runsBadge: {
459
- position: 'absolute', right: '10px', bottom: '2px', fontSize: '9px',
460
- color: C.accent, cursor: 'pointer', userSelect: 'none', zIndex: 4,
461
- },
462
- statusBar: {
463
- position: 'absolute', left: '2px', top: '10px', bottom: '10px', width: '3px',
464
- borderRadius: '2px', zIndex: 3,
465
- },
466
- };
467
-
468
- let hostCtx = null;
469
-
470
- function socketCenterY(i) {
471
- return SOCKET_BAND_TOP + i * ROW_H + ROW_H / 2;
472
- }
473
-
474
- function defaultNodes() {
475
- return [
476
- { id: 'lead', kind: 'lead', x: 30, y: 30, label: 'Lead', task: '', provider: '', model: '', role: '' },
477
- { id: 'n1', kind: 'agent', x: 40, y: 230, label: 'Classifier', provider: '', model: 'deepseek-v4-flash', role: '把请求分类' },
478
- { id: 'n2', kind: 'agent', x: 340, y: 420, label: 'Executor', provider: '', model: 'deepseek-v4-pro', role: '执行方案' },
479
- ];
480
- }
481
-
482
- function defaultEdges() {
483
- return [
484
- { id: 'e-lead-n1', from: 'lead', to: 'n1', type: 'prompt' },
485
- { id: 'e-n1-n2', from: 'n1', to: 'n2', type: 'prompt' },
486
- ];
487
- }
488
-
489
- /**
490
- * Older docs used an `output` node as the exit. Its meaning is now "another
491
- * lead step", so migrate the kind instead of dropping the user's graph.
492
- */
493
- function ensureEntry(doc) {
494
- if (!doc || !Array.isArray(doc.nodes)) return doc;
495
- for (const n of doc.nodes) {
496
- if (!n) continue;
497
- if (n.kind === 'output') {
498
- n.kind = 'lead';
499
- if (!n.label || n.label === '输出') n.label = 'Lead';
500
- } else if (!n.kind) {
501
- n.kind = n.id === 'lead' ? 'lead' : 'agent';
502
- }
503
- }
504
- if (!doc.nodes.some((n) => n && n.id === 'lead')) {
505
- doc.nodes.unshift({ id: 'lead', kind: 'lead', x: 30, y: 30, label: 'Lead', task: '', provider: '', model: '', role: '' });
506
- }
507
- for (const n of doc.nodes) {
508
- if (n && n.id === 'lead') n.kind = 'lead';
509
- }
510
- return doc;
511
- }
512
-
513
- /** Control points of one link, in canvas coordinates. */
514
- function edgeCurve(from, to, type) {
515
- const idx = Math.max(0, SOCKET_TYPES.findIndex((t) => t.id === type));
516
- const y = socketCenterY(idx);
517
- const x1 = from.x + WORLD_PAD + NODE_W, y1 = from.y + WORLD_PAD + y;
518
- const x2 = to.x + WORLD_PAD, y2 = to.y + WORLD_PAD + y;
519
- const dx = Math.max(40, Math.abs(x2 - x1) * 0.5);
520
- return { x1, y1, c1x: x1 + dx, c1y: y1, c2x: x2 - dx, c2y: y2, x2, y2 };
521
- }
522
-
523
- function edgePath(from, to, type) {
524
- const c = edgeCurve(from, to, type);
525
- return 'M ' + c.x1 + ' ' + c.y1 + ' C ' + c.c1x + ' ' + c.c1y + ', ' + c.c2x + ' ' + c.c2y + ', ' + c.x2 + ' ' + c.y2;
526
- }
527
-
528
- /** Shortest distance between a point and one link, sampled along the curve. */
529
- function distanceToEdge(point, from, to, type) {
530
- const c = edgeCurve(from, to, type);
531
- let best = Infinity;
532
- let prevX = c.x1;
533
- let prevY = c.y1;
534
- for (let i = 1; i <= 18; i += 1) {
535
- const t = i / 18;
536
- const u = 1 - t;
537
- const bx = u * u * u * c.x1 + 3 * u * u * t * c.c1x + 3 * u * t * t * c.c2x + t * t * t * c.x2;
538
- const by = u * u * u * c.y1 + 3 * u * u * t * c.c1y + 3 * u * t * t * c.c2y + t * t * t * c.y2;
539
- best = Math.min(best, distanceToSegment(point, prevX, prevY, bx, by));
540
- prevX = bx;
541
- prevY = by;
542
- }
543
- return best;
544
- }
545
-
546
- function distanceToSegment(p, ax, ay, bx, by) {
547
- const vx = bx - ax;
548
- const vy = by - ay;
549
- const len = vx * vx + vy * vy;
550
- const t = len === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - ax) * vx + (p.y - ay) * vy) / len));
551
- const dx = p.x - (ax + t * vx);
552
- const dy = p.y - (ay + t * vy);
553
- return Math.hypot(dx, dy);
554
- }
555
-
556
- function topoOrder(nodes, edges) {
557
- const indeg = new Map(nodes.map((n) => [n.id, 0]));
558
- const adj = new Map(nodes.map((n) => [n.id, []]));
559
- for (const e of edges) {
560
- if (!indeg.has(e.from) || !indeg.has(e.to)) continue;
561
- indeg.set(e.to, indeg.get(e.to) + 1);
562
- adj.get(e.from).push(e.to);
563
- }
564
- const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
565
- const out = [];
566
- while (queue.length) {
567
- const id = queue.shift();
568
- out.push(id);
569
- for (const next of adj.get(id)) {
570
- indeg.set(next, indeg.get(next) - 1);
571
- if (indeg.get(next) === 0) queue.push(next);
572
- }
573
- }
574
- return out.length === nodes.length ? out : null;
575
- }
576
-
577
- function varOf(id) {
578
- return 'n_' + String(id).replace(/[^a-zA-Z0-9_]/g, '_');
579
- }
580
-
581
- function buildWorkflowScript(nodes, edges) {
582
- const entry = nodes.find((n) => n.id === 'lead');
583
- if (!entry) return { error: '缺少入口 Lead 节点' };
584
- const rest = nodes.filter((n) => n.id !== 'lead');
585
- if (!rest.length) return { error: '画布上还没有可执行的节点' };
586
- const task = String(entry.task || '').trim();
587
- if (!task) return { error: '请先在 Lead 节点填写「本次任务」' };
588
-
589
- const byIdAll = new Map(rest.map((n) => [n.id, n]));
590
-
591
- const reachable = new Set([entry.id]);
592
- let grew = true;
593
- while (grew) {
594
- grew = false;
595
- for (const e of edges) {
596
- if (reachable.has(e.from) && !reachable.has(e.to)) { reachable.add(e.to); grew = true; }
597
- }
598
- }
599
- const orphan = rest.filter((n) => !reachable.has(n.id));
600
- if (orphan.length) {
601
- return { error: '这些节点没有从入口 Lead 连过来:' + orphan.map((n) => n.label).join('、') };
602
- }
603
-
604
- const dataEdgesAll = edges.filter((e) => e.from !== entry.id && byIdAll.has(e.from) && byIdAll.has(e.to));
605
-
606
- // Lead-kind nodes are executed by the conversation itself, which can only
607
- // happen after the script returns — so they must be terminal.
608
- const leadNodes = rest.filter((n) => n.kind === 'lead');
609
- for (const ln of leadNodes) {
610
- if (dataEdgesAll.some((e) => e.from === ln.id)) {
611
- return {
612
- error: '中间 Lead 节点暂不支持(「' + ln.label + '」后面还有步骤)。'
613
- + '把中间这一步换成子代理,或把它移到流程末尾。',
614
- };
615
- }
616
- }
617
-
618
- const agentNodes = rest.filter((n) => n.kind !== 'lead');
619
- if (!agentNodes.length) return { error: '需要至少一个子代理节点来执行' };
620
-
621
- const byId = new Map(agentNodes.map((n) => [n.id, n]));
622
- const dataEdges = dataEdgesAll.filter((e) => byId.has(e.from) && byId.has(e.to));
623
- const order = topoOrder(agentNodes, dataEdges);
624
- if (!order) return { error: '存在环,无法生成有向无环图的脚本' };
625
-
626
- const upstream = new Map(agentNodes.map((n) => [n.id, []]));
627
- for (const e of dataEdges) upstream.get(e.to).push(e);
628
- const hasDownstream = new Set(dataEdges.map((e) => e.from));
629
-
630
- // Hand back everything a lead step consumes, plus every terminal agent.
631
- const delivered = [];
632
- const deliver = (id) => { if (byId.has(id) && !delivered.includes(id)) delivered.push(id); };
633
- for (const ln of leadNodes) {
634
- for (const e of dataEdgesAll) if (e.to === ln.id) deliver(e.from);
635
- }
636
- for (const n of agentNodes) if (!hasDownstream.has(n.id)) deliver(n.id);
637
-
638
- const lines = [];
639
- lines.push('// meta: ' + JSON.stringify({ name: 'workflow-canvas', description: 'Canvas-generated agent DAG', phases: [{ title: 'run' }] }));
640
- for (const id of order) {
641
- const node = byId.get(id);
642
- const ups = upstream.get(id);
643
- const isRoot = ups.length === 0;
644
- const upsLabels = ups.map((e) => (byId.get(e.from) || {}).label).filter(Boolean);
645
- const downs = dataEdgesAll.filter((e) => e.from === id).map((e) => (byIdAll.get(e.to) || {}).label).filter(Boolean);
646
- const head = [];
647
- head.push('【工作流节点】你在一个多步工作流里负责「' + node.label + '」这一步(子代理)。');
648
- if (isRoot) head.push('【总任务】' + task);
649
- head.push('【职责】' + (node.role || node.label || id));
650
- if (upsLabels.length) head.push('【上游】' + upsLabels.join('、') + ' 已交付结果给你(见下文)。');
651
- head.push('【下游】' + (downs.length ? downs.join('、') + ' 会使用你的输出。' : '你是终点,结果会直接交付给用户。'));
652
- head.push('【要求】只完成你这一步;输出要能被下游直接使用,不要重复上游已完成的工作。');
653
- const pieces = [JSON.stringify(head.join('\n') + '\n')];
654
- for (const e of ups) {
655
- const from = byId.get(e.from);
656
- pieces.push(JSON.stringify('\n## 来自【' + from.label + '】(' + (e.type || 'prompt') + ')\n'));
657
- pieces.push(varOf(e.from));
658
- }
659
- // The label carries the canvas node id so the client can match the
660
- // spawned subagent session back to its node through the catalog.
661
- const opts = ["label: " + JSON.stringify((node.label || id) + '#' + id), "phase: 'run'"];
662
- if (node.provider) opts.push('provider: ' + JSON.stringify(node.provider));
663
- if (node.model) opts.push('model: ' + JSON.stringify(node.model));
664
- lines.push('const ' + varOf(id) + ' = await agent(' + pieces.join(' + ') + ', { ' + opts.join(', ') + ' });');
665
- }
666
- lines.push('// 交付给 Lead:' + delivered.map((id) => byId.get(id).label).join('、'));
667
- const rets = delivered.map((id) => JSON.stringify(byId.get(id).label) + ': ' + varOf(id));
668
- lines.push('return { ' + rets.join(', ') + ' };');
669
-
670
- // These run in the conversation after the script returns.
671
- const leadSteps = leadNodes.map((ln) => ({
672
- label: ln.label,
673
- role: ln.role || ln.label,
674
- needs: dataEdgesAll.filter((e) => e.to === ln.id).map((e) => (byIdAll.get(e.from) || {}).label).filter(Boolean),
675
- }));
676
-
677
- return { script: lines.join('\n'), leadSteps };
678
- }
679
-
680
- /** Ids reachable from the entry Lead; every other node is skipped at run time. */
681
- function reachableFrom(nodes, edges) {
682
- const set = new Set(['lead']);
683
- let grew = true;
684
- while (grew) {
685
- grew = false;
686
- for (const e of edges) {
687
- if (set.has(e.from) && !set.has(e.to)) { set.add(e.to); grew = true; }
688
- }
689
- }
690
- return set;
691
- }
692
-
693
- /** Everything the Host executor needs; no prompts are pre-rendered here. */
694
- function buildPlan(nodes, edges) {
695
- const entry = nodes.find((n) => n.id === 'lead');
696
- if (!entry) return { error: '缺少入口 Lead 节点' };
697
- const task = String(entry.task || '').trim();
698
- if (!task) return { error: '请先在 Lead 节点填写「本次任务」' };
699
- const rest = nodes.filter((n) => n.id !== 'lead');
700
- if (!rest.length) return { error: '画布上还没有可执行的节点' };
701
- // Nodes the entry Lead cannot reach are skipped rather than refused; the
702
- // canvas marks them so the user can see what will not run.
703
- const reachableIds = reachableFrom(nodes, edges);
704
-
705
- const ids = new Set(rest.map((n) => n.id));
706
- const planEdges = edges
707
- .filter((e) => (e.from === 'lead' || ids.has(e.from)) && ids.has(e.to))
708
- .map((e) => ({ from: e.from, to: e.to, type: e.type || 'prompt' }));
709
-
710
- // Unconnected nodes are left out of the plan instead of blocking the run.
711
- const skipped = rest.filter((n) => !reachableIds.has(n.id));
712
- const active = rest.filter((n) => reachableIds.has(n.id));
713
- if (!active.length) {
714
- return { error: '没有从入口 Lead 连通的节点,无法执行' };
715
- }
716
-
717
- return {
718
- plan: {
719
- task,
720
- skipped: skipped.map((n) => n.label || n.id),
721
- nodes: active.map((n) => ({
722
- id: n.id,
723
- kind: n.kind === 'lead' ? 'lead' : 'agent',
724
- label: n.label || n.id,
725
- role: n.role || '',
726
- provider: n.provider || '',
727
- model: n.model || '',
728
- reasoning: n.reasoning || '',
729
- preset: n.preset === 'minimal' ? 'minimal' : 'standard',
730
- keepSession: Boolean(n.keepSession),
731
- // A structured link is the only thing that decides this: no separate switch.
732
- structured: planEdges.some((e) => e.from === n.id && e.type === 'structured'),
733
- fallbackModel: n.fallbackModel || '',
734
- fallbackProvider: n.fallbackProvider || '',
735
- })),
736
- edges: planEdges,
737
- },
738
- };
739
- }
740
-
741
- function loadCutMode() {
742
- try {
743
- return window.localStorage.getItem(STORAGE_PREFIX + 'cut') !== 'off';
744
- } catch (_e) {
745
- return true;
746
- }
747
- }
748
-
749
- function saveCutMode(on) {
750
- try {
751
- window.localStorage.setItem(STORAGE_PREFIX + 'cut', on ? 'on' : 'off');
752
- } catch (_e) { /* ignore */ }
753
- }
754
-
755
- function loadPresets() {
756
- try {
757
- const raw = window.localStorage.getItem(PRESET_KEY);
758
- if (!raw) return {};
759
- const doc = JSON.parse(raw);
760
- return doc && typeof doc === 'object' && !Array.isArray(doc) ? doc : {};
761
- } catch (_e) {
762
- return {};
763
- }
764
- }
765
-
766
- function savePresets(presets) {
767
- try {
768
- window.localStorage.setItem(PRESET_KEY, JSON.stringify(presets));
769
- return true;
770
- } catch (_e) {
771
- return false;
772
- }
773
- }
774
-
775
- function storageKey(sessionId) { return STORAGE_PREFIX + (sessionId || '__global__');
776
- }
777
-
778
- function loadDoc(sessionId) {
779
- try {
780
- const raw = window.localStorage.getItem(storageKey(sessionId));
781
- if (!raw) return null;
782
- const doc = JSON.parse(raw);
783
- if (!doc || !Array.isArray(doc.nodes) || !Array.isArray(doc.edges)) return null;
784
- return ensureEntry(doc);
785
- } catch (_e) {
786
- return null;
787
- }
788
- }
789
-
790
- function saveDoc(sessionId, doc, stamp) {
791
- try {
792
- /** Stamp every local edit so a stale generated canvas cannot overwrite it. */
793
- const stamped = { ...doc, at: typeof stamp === 'number' ? stamp : Date.now() };
794
- window.localStorage.setItem(storageKey(sessionId), JSON.stringify(stamped));
795
- } catch (_e) {
796
- /* storage unavailable */
797
- }
798
- }
799
-
800
- function sessionFace(sessionId) {
801
- try {
802
- const sessions = hostCtx && hostCtx.sessions;
803
- if (!sessions || typeof sessions.binding !== 'function' || !sessionId) return undefined;
804
- const binding = sessions.binding(sessionId);
805
- return binding && binding.session;
806
- } catch (_e) {
807
- return undefined;
808
- }
809
- }
810
-
811
- /**
812
- * Keeps a rendering failure visible: without this the whole tab renders as
813
- * an empty box and the reason is lost.
814
- */
815
- class CanvasBoundary extends Component {
816
- constructor(props) {
817
- super(props);
818
- this.state = { error: null };
819
- }
820
-
821
- static getDerivedStateFromError(error) {
822
- return { error };
823
- }
824
-
825
- componentDidCatch(error, info) {
826
- try {
827
- console.error('[workflow-canvas] render failed', error, info);
828
- } catch (_e) { /* ignore */ }
829
- }
830
-
831
- render() {
832
- const error = this.state.error;
833
- if (!error) return this.props.children;
834
- const message = String((error && error.message) || error);
835
- const stack = String((error && error.stack) || '').slice(0, 900);
836
- return h('div', {
837
- style: {
838
- padding: '12px', fontFamily: 'ui-monospace, monospace', fontSize: '11px',
839
- color: '#e5534b', whiteSpace: 'pre-wrap', overflow: 'auto', height: '100%',
840
- },
841
- }, '画布渲染出错:\n' + message + '\n\n' + stack);
842
- }
843
- }
844
-
845
- function WorkflowCanvas(props) {
846
- const sessionId = props && props.sessionId;
847
- const stored = useRef(loadDoc(sessionId));
848
- const initial = stored.current;
849
-
850
- const [nodes, setNodes] = useState(() => (initial ? initial.nodes : defaultNodes()));
851
- const [edges, setEdges] = useState(() => (initial ? initial.edges : defaultEdges()));
852
- const [selectedIds, setSelectedIds] = useState([]);
853
- const [marquee, setMarquee] = useState(null);
854
- const [dragging, setDragging] = useState(false);
855
- const [syncNote, setSyncNote] = useState('');
856
- const [roleEditFor, setRoleEditFor] = useState(null);
857
- const [menuOpen, setMenuOpen] = useState(false);
858
- const [helpOpen, setHelpOpen] = useState(false);
859
- const [cutMode, setCutMode] = useState(loadCutMode);
860
- const cutRef = useRef(null);
861
- /** Timestamp of the remote document being applied, so saving it does not bump the clock. */
862
- const applyStamp = useRef(null);
863
- const [cutPath, setCutPath] = useState([]);
864
- const [cutVictims, setCutVictims] = useState([]);
865
- const cutHits = useRef(new Set());
866
- const [pending, setPending] = useState(null);
867
- const [status, setStatus] = useState('');
868
- const [models, setModels] = useState([]);
869
- const [openModelFor, setOpenModelFor] = useState(null);
870
- const [enabled, setEnabled] = useState(() => Boolean(initial && initial.enabled));
871
-
872
- const contentRef = useRef(null);
873
- const canvasElRef = useRef(null);
874
- const nodeDrag = useRef(null); const statusTimer = useRef(null);
875
- const dropdownRef = useRef(null);
876
- const syncTimer = useRef(null);
877
- const lastSync = useRef('');
878
- const historyRef = useRef([]);
879
- const [dirty, setDirty] = useState(() => Boolean(initial && initial.enabled));
880
- const [view, setView] = useState({ k: 1, x: 0, y: 0 });
881
- const viewRef = useRef(view);
882
- viewRef.current = view;
883
- const [statusById, setStatusById] = useState({});
884
- const [presets, setPresets] = useState(loadPresets);
885
- const [presetOpen, setPresetOpen] = useState(null);
886
- const [presetName, setPresetName] = useState('');
887
- const [lang, setLang] = useState(loadLang);
888
- const t = (key) => (I18N[lang] && I18N[lang][key]) || I18N.zh[key] || key;
889
- const toggleLang = () => {
890
- const next = lang === 'zh' ? 'en' : 'zh';
891
- setLang(next);
892
- try { window.localStorage.setItem(LANG_KEY, next); } catch (_e) { /* ignore */ }
893
- };
894
- const nodesRef = useRef(nodes);
895
- nodesRef.current = nodes;
896
-
897
- useEffect(() => {
898
- const stamp = applyStamp.current;
899
- applyStamp.current = null;
900
- saveDoc(sessionId, { nodes, edges, enabled }, stamp === null ? undefined : stamp);
901
- }, [sessionId, nodes, edges, enabled]);
902
-
903
- // Any structural edit after enabling leaves the Host copy stale.
904
- useEffect(() => {
905
- if (enabled) setDirty(true);
906
- }, [nodes, edges]);
907
-
908
- // A disabled canvas shows no run status at all.
909
- useEffect(() => {
910
- if (!enabled) setStatusById({});
911
- }, [enabled]);
912
-
913
- useEffect(() => {
914
- let alive = true;
915
- const remote = hostCtx && hostCtx.remote && hostCtx.remote.session;
916
- if (!remote || typeof remote.modelCatalog !== 'function') return undefined;
917
- remote.modelCatalog().then((res) => {
918
- if (!alive || !res || !res.ok) return;
919
- const flat = [];
920
- for (const group of (res.value && res.value.groups) || []) {
921
- for (const model of group.models || []) {
922
- flat.push({
923
- provider: group.id,
924
- providerName: group.name,
925
- model: model.id,
926
- modelName: model.name,
927
- efforts: (model.reasoning && model.reasoning.efforts) || [],
928
- defaultEffort: model.reasoning && model.reasoning.defaultEffort,
929
- });
930
- }
931
- }
932
- setModels(flat);
933
- }).catch(() => {});
934
- return () => { alive = false; };
935
- }, []);
936
-
937
- useEffect(() => {
938
- if (!openModelFor) return undefined;
939
- const onDown = (ev) => {
940
- if (dropdownRef.current && !dropdownRef.current.contains(ev.target)) setOpenModelFor(null);
941
- };
942
- document.addEventListener('mousedown', onDown);
943
- return () => document.removeEventListener('mousedown', onDown);
944
- }, [openModelFor]);
945
-
946
- // Publishing costs one visible command row in the conversation, so it only
947
- // happens when the user enables the canvas or asks for it explicitly.
948
- const pushPlan = (nextEnabled) => {
949
- try {
950
- const face = sessionFace(sessionId);
951
- if (!face || typeof face.command !== 'function') { flash(t('syncFailed')); return; }
952
- const res = buildPlan(nodes, edges);
953
- const payload = res.error
954
- ? { enabled: nextEnabled, error: res.error }
955
- : { enabled: nextEnabled, plan: res.plan };
956
- const sig = JSON.stringify(payload);
957
- if (sig === lastSync.current) { flash(t('upToDate')); return; }
958
- const line = '/canvas-sync ' + encodeURIComponent(sig);
959
- face.command(line).then((ack) => {
960
- if (ack && ack.ok) {
961
- lastSync.current = sig;
962
- setDirty(false);
963
- setStatusById({});
964
- flash(t('syncedToHost'));
965
- } else {
966
- flash(t('syncFailed'));
967
- }
968
- }, () => flash(t('syncFailed')));
969
- } catch (_e) {
970
- flash(t('syncFailed'));
971
- }
972
- };
973
-
974
- // Sync the moment a user message starts a turn, so this turn's tool call
975
- // already sees the latest canvas. Falls back to the turn end if the start
976
- // edge was missed; `dirty` clears on success so only one fires.
977
- const liveRef = useRef({ enabled, dirty, pushPlan });
978
- liveRef.current = { enabled, dirty, pushPlan };
979
-
980
- useEffect(() => {
981
- const face = sessionFace(sessionId);
982
- if (!face || typeof face.subscribe !== 'function' || typeof face.getSnapshot !== 'function') return undefined;
983
- let wasRunning = false;
984
- try { wasRunning = Boolean(face.getSnapshot().running); } catch (_e) { wasRunning = false; }
985
- const onSnapshot = () => {
986
- let running = false;
987
- try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
988
- if (running !== wasRunning) {
989
- const live = liveRef.current;
990
- if (live.enabled && live.dirty) live.pushPlan(true);
991
- }
992
- wasRunning = running;
993
- };
994
- let unsub;
995
- try { unsub = face.subscribe(onSnapshot); } catch (_e) { unsub = undefined; }
996
- return () => {
997
- if (typeof unsub === 'function') { try { unsub(); } catch (_e) { /* ignore */ } }
998
- };
999
- }, [sessionId]);
1000
-
1001
- const flash = (msg) => {
1002
- setStatus(msg);
1003
- if (statusTimer.current) clearTimeout(statusTimer.current);
1004
- statusTimer.current = setTimeout(() => setStatus(''), 3200);
1005
- };
1006
-
1007
- // Live node status for subagent nodes only: the catalog lists children by
1008
- // `label#nodeId`. Lead steps run inside the conversation, so the canvas
1009
- // cannot observe them and must not pretend to.
1010
- useEffect(() => {
1011
- const sessions = hostCtx && hostCtx.sessions;
1012
- const face = sessionFace(sessionId);
1013
- if (!sessions || !sessionId || !face || typeof face.subscribe !== 'function') return undefined;
1014
- let timer = null;
1015
- const read = () => {
1016
- try {
1017
- const state = sessions.list.getSnapshot();
1018
- const proj = state && state.projectionsBySession && state.projectionsBySession[sessionId];
1019
- const catalog = proj && proj.values && proj.values.subagentCatalog;
1020
- if (!Array.isArray(catalog)) return;
1021
- const known = new Set(nodesRef.current.map((n) => n.id));
1022
- const next = {};
1023
- for (const entry of catalog) {
1024
- const m = NODE_MARK.exec(String(entry.label || ''));
1025
- if (!m || !known.has(m[1])) continue;
1026
- const child = state.byId && state.byId[entry.id];
1027
- const timingProj = state.projectionsBySession && state.projectionsBySession[entry.id];
1028
- const timing = timingProj && timingProj.values && timingProj.values.subagentTiming;
1029
- if (child && child.running) next[m[1]] = 'running';
1030
- else if (timing && timing.lastTurnCompleted === false) next[m[1]] = 'failed';
1031
- else next[m[1]] = 'done';
1032
- }
1033
- setStatusById(next);
1034
- } catch (_e) { /* ignore */ }
1035
- };
1036
- const stop = () => { if (timer) { clearInterval(timer); timer = null; } };
1037
- let wasRunning = false;
1038
- try { wasRunning = Boolean(face.getSnapshot().running); } catch (_e) { wasRunning = false; }
1039
- if (wasRunning) { read(); timer = setInterval(read, 700); }
1040
- const onSnapshot = () => {
1041
- let running = false;
1042
- try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
1043
- // A new turn means a new run: drop the previous run's statuses first.
1044
- if (running && !wasRunning) setStatusById({});
1045
- wasRunning = running;
1046
- if (running && !timer) { read(); timer = setInterval(read, 700); }
1047
- if (!running && timer) { stop(); read(); }
1048
- };
1049
- let unsub;
1050
- try { unsub = face.subscribe(onSnapshot); } catch (_e) { unsub = undefined; }
1051
- return () => {
1052
- stop();
1053
- if (typeof unsub === 'function') { try { unsub(); } catch (_e) { /* ignore */ } }
1054
- };
1055
- }, [sessionId]);
1056
-
1057
- // Zoom with the wheel, anchored on the cursor: the content point under the
1058
- // pointer stays under it while the scale changes.
1059
- useEffect(() => {
1060
- const el = canvasElRef.current;
1061
- if (!el) return undefined;
1062
- const onWheel = (e) => {
1063
- e.preventDefault();
1064
- const rect = el.getBoundingClientRect();
1065
- const mx = e.clientX - rect.left;
1066
- const my = e.clientY - rect.top;
1067
- const cur = viewRef.current;
1068
- const factor = e.deltaY < 0 ? 1.12 : 1 / 1.12;
1069
- const k = Math.min(3, Math.max(0.2, cur.k * factor));
1070
- if (k === cur.k) return;
1071
- const lx = (mx - cur.x) / cur.k;
1072
- const ly = (my - cur.y) / cur.k;
1073
- setView({ k, x: mx - lx * k, y: my - ly * k });
1074
- };
1075
- el.addEventListener('wheel', onWheel, { passive: false });
1076
- return () => el.removeEventListener('wheel', onWheel);
1077
- }, []);
1078
-
1079
- const pointTo = (e) => {
1080
- const rect = contentRef.current.getBoundingClientRect();
1081
- const k = viewRef.current.k || 1;
1082
- return {
1083
- x: (e.clientX - rect.left) / k - WORLD_PAD,
1084
- y: (e.clientY - rect.top) / k - WORLD_PAD,
1085
- };
1086
- };
1087
-
1088
- /** Put a world point at the middle of the visible canvas. */
1089
- const centerOn = (wx, wy, nextK) => {
1090
- const el = canvasElRef.current;
1091
- if (!el) return;
1092
- const k = nextK || viewRef.current.k || 1;
1093
- const cw = el.clientWidth || 1;
1094
- const chh = el.clientHeight || 1;
1095
- setView({
1096
- k,
1097
- x: cw / 2 - (wx + WORLD_PAD) * k,
1098
- y: chh / 2 - (wy + WORLD_PAD) * k,
1099
- });
1100
- el.scrollLeft = 0;
1101
- el.scrollTop = 0;
1102
- };
1103
-
1104
- /** World coordinate currently sitting in the middle of the viewport. */
1105
- const viewportCenterWorld = () => {
1106
- const el = canvasElRef.current;
1107
- const k = viewRef.current.k || 1;
1108
- const cw = (el && el.clientWidth) || 800;
1109
- const chh = (el && el.clientHeight) || 600;
1110
- return {
1111
- x: (cw / 2 - viewRef.current.x) / k - WORLD_PAD,
1112
- y: (chh / 2 - viewRef.current.y) / k - WORLD_PAD,
1113
- };
1114
- };
1115
-
1116
- const focusLead = () => {
1117
- const lead = nodes.find((n) => n.id === 'lead');
1118
- if (!lead) return;
1119
- centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2);
1120
- };
1121
-
1122
- // The world origin is padded, so the initial viewport would otherwise show
1123
- // empty space. Centre on the entry Lead the first time the pane mounts.
1124
- const didCenter = useRef(false);
1125
- useEffect(() => {
1126
- if (didCenter.current) return;
1127
- const lead = nodesRef.current.find((n) => n.id === 'lead');
1128
- if (!lead) return;
1129
- didCenter.current = true;
1130
- const raf = typeof requestAnimationFrame === 'function'
1131
- ? requestAnimationFrame(() => centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2))
1132
- : setTimeout(() => centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2), 0);
1133
- return () => {
1134
- if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(raf);
1135
- else clearTimeout(raf);
1136
- };
1137
- }, []);
1138
-
1139
- // Snapshot before every structural change so a mis-click can be undone.
1140
- const pushSnapshot = () => {
1141
- historyRef.current.push({ nodes, edges });
1142
- if (historyRef.current.length > 50) historyRef.current.shift();
1143
- };
1144
-
1145
- const undo = () => {
1146
- const prev = historyRef.current.pop();
1147
- if (!prev) { flash(t('undoNone')); return; }
1148
- setNodes(prev.nodes);
1149
- setEdges(prev.edges);
1150
- setSelectedIds([]);
1151
- flash(t('undoDone'));
1152
- };
1153
-
1154
- const NODE_MARK = /#([A-Za-z0-9_]+)/;
1155
-
1156
- /** Match this canvas's spawned subagent sessions back to their nodes. */
1157
- const refreshRuns = async () => {
1158
- try {
1159
- const sessions = hostCtx && hostCtx.sessions;
1160
- if (!sessions || !sessionId) { flash('没有会话上下文'); return; }
1161
- try { await sessions.refreshProjections(sessionId); } catch (_e) { /* ignore */ }
1162
- const state = sessions.list.getSnapshot();
1163
- const proj = state && state.projectionsBySession && state.projectionsBySession[sessionId];
1164
- const values = proj && (proj.values || (proj.state === 'ready' ? proj.values : undefined));
1165
- const catalog = values && values.subagentCatalog;
1166
- if (!Array.isArray(catalog)) {
1167
- flash('读不到子代理目录(' + (proj ? '没有 subagentCatalog' : '没有该会话投影') + ')');
1168
- return;
1169
- }
1170
- if (!catalog.length) { flash('子代理目录是空的(这次运行可能没产生子会话)'); return; }
1171
- const known = new Set(nodes.map((n) => n.id));
1172
- const byNode = new Map();
1173
- const samples = [];
1174
- for (const entry of catalog) {
1175
- const label = String(entry.label || entry.name || entry.description || '');
1176
- if (samples.length < 2) samples.push(label || '(无 label)');
1177
- const m = NODE_MARK.exec(label);
1178
- if (!m) continue;
1179
- const nodeId = m[1];
1180
- if (!known.has(nodeId)) continue;
1181
- if (!byNode.has(nodeId)) byNode.set(nodeId, []);
1182
- byNode.get(nodeId).push({ childId: entry.id, label, mode: entry.mode || 'continuable' });
1183
- }
1184
- if (!byNode.size) {
1185
- flash('目录 ' + catalog.length + ' 项但没有带 #节点id 的,示例:' + samples.join(' / '));
1186
- return;
1187
- }
1188
- setNodes((ns) => ns.map((n) => (byNode.has(n.id) ? { ...n, runs: byNode.get(n.id) } : n)));
1189
- flash('已同步 ' + byNode.size + ' 个节点的运行记录');
1190
- } catch (_e) {
1191
- flash('同步运行记录失败:' + String((_e && _e.message) || _e));
1192
- }
1193
- };
1194
-
1195
- const openRun = (node, run) => {
1196
- try {
1197
- const sr = hostCtx && hostCtx.sidebarRight;
1198
- if (!sr || typeof sr.openResource !== 'function') { flash('无法打开会话'); return; }
1199
- const addr = 'dsh-resource://subagentchat/session/' + encodeURIComponent(run.childId)
1200
- + '?parent=' + encodeURIComponent(sessionId)
1201
- + '&mode=' + encodeURIComponent(run.mode || 'continuable');
1202
- sr.openResource(addr, { kind: 'subagentchat', preferNewPane: true });
1203
- } catch (_e) {
1204
- flash('打开会话失败');
1205
- }
1206
- };
1207
-
1208
- const addNode = (kind) => {
1209
- pushSnapshot();
1210
- setNodes((ns) => {
1211
- const i = ns.length;
1212
- const center = viewportCenterWorld();
1213
- return [...ns, {
1214
- id: 'n' + Date.now().toString(36),
1215
- kind: kind === 'lead' ? 'lead' : 'agent',
1216
- // New nodes land near the middle of the viewport, nudged right.
1217
- x: center.x + 40 + (ns.length % 3) * 30,
1218
- y: center.y - NODE_H / 2 + (ns.length % 3) * 40,
1219
- label: kind === 'lead' ? 'Lead 步骤 ' + i : 'Node ' + i,
1220
- provider: '',
1221
- model: '',
1222
- role: '',
1223
- }];
1224
- });
1225
- };
1226
-
1227
- const updateNode = (id, patch) => {
1228
- setNodes((ns) => ns.map((n) => (n.id === id ? { ...n, ...patch } : n)));
1229
- };
1230
-
1231
- const deleteNode = (id) => {
1232
- if (id === 'lead') { flash(t('leadLocked')); return; }
1233
- pushSnapshot();
1234
- setNodes((ns) => ns.filter((n) => n.id !== id));
1235
- setEdges((es) => es.filter((e) => e.from !== id && e.to !== id));
1236
- setSelectedIds([]);
1237
- flash(t('deletedNode'));
1238
- };
1239
-
1240
- /** Dragging any selected node moves the whole selection together. */
1241
- const onNodeDown = (e, id) => {
1242
- if (!contentRef.current) return;
1243
- const node = nodes.find((n) => n.id === id);
1244
- if (!node) return;
1245
- const p = pointTo(e);
1246
- const group = selectedIds.includes(id) ? selectedIds : [id];
1247
- if (!selectedIds.includes(id)) setSelectedIds([id]);
1248
- const origins = group
1249
- .map((nid) => nodes.find((n) => n.id === nid))
1250
- .filter(Boolean)
1251
- .map((n) => ({ id: n.id, x: n.x, y: n.y }));
1252
- nodeDrag.current = { origins, startX: p.x, startY: p.y, moved: false };
1253
- setDragging(true);
1254
- setOpenModelFor(null);
1255
- e.preventDefault();
1256
- e.stopPropagation();
1257
- };
1258
-
1259
- const onOutputDown = (e, id, type) => {
1260
- const node = nodes.find((n) => n.id === id);
1261
- if (!node) return;
1262
- const idx = SOCKET_TYPES.findIndex((t) => t.id === type);
1263
- const sx = node.x + NODE_W;
1264
- const sy = node.y + socketCenterY(idx);
1265
- setPending({ dir: 'out', fromId: id, type, sx, sy, x: sx, y: sy });
1266
- setDragging(true);
1267
- e.preventDefault();
1268
- e.stopPropagation();
1269
- };
1270
-
1271
- /** Release over an output socket: completes a drag that started at an input. */
1272
- const onOutputUp = (e, id, type) => {
1273
- if (!pending || pending.dir !== 'in' || pending.type !== type) return;
1274
- e.preventDefault();
1275
- e.stopPropagation();
1276
- const toId = pending.toId;
1277
- if (toId && toId !== id) {
1278
- pushSnapshot();
1279
- setEdges((es) => {
1280
- if (es.some((x) => x.from === id && x.to === toId && x.type === type)) return es;
1281
- return [...es, { id: 'e' + Date.now().toString(36), from: id, to: toId, type }];
1282
- });
1283
- }
1284
- setPending(null);
1285
- setDragging(false);
1286
- };
1287
-
1288
- // Dragging a connected input detaches it; dragging a free input starts a
1289
- // link that finishes on an output socket of the same type.
1290
- const onInputDown = (e, id, type) => {
1291
- e.preventDefault();
1292
- e.stopPropagation();
1293
- const link = edges.find((x) => x.to === id && x.type === type);
1294
- const idx = SOCKET_TYPES.findIndex((t) => t.id === type);
1295
- if (!link) {
1296
- const node = nodes.find((n) => n.id === id);
1297
- if (!node) return;
1298
- const sx = node.x;
1299
- const sy = node.y + socketCenterY(idx);
1300
- setPending({ dir: 'in', toId: id, type, sx, sy, x: sx, y: sy });
1301
- setDragging(true);
1302
- return;
1303
- }
1304
- pushSnapshot();
1305
- setEdges((es) => es.filter((x) => !(x.to === id && x.type === type)));
1306
- const from = nodes.find((n) => n.id === link.from);
1307
- if (!from) return;
1308
- const sx = from.x + NODE_W;
1309
- const sy = from.y + socketCenterY(idx);
1310
- setPending({ dir: 'out', fromId: link.from, type, sx, sy, x: sx, y: sy });
1311
- setDragging(true);
1312
- };
1313
-
1314
- const onInputUp = (e, id, type) => {
1315
- if (!pending || pending.dir !== 'out' || pending.type !== type) return;
1316
- e.preventDefault();
1317
- e.stopPropagation();
1318
- if (pending.fromId !== id) {
1319
- const fromId = pending.fromId;
1320
- pushSnapshot();
1321
- setEdges((es) => {
1322
- if (es.some((x) => x.from === fromId && x.to === id && x.type === type)) return es;
1323
- return [...es, { id: 'e' + Date.now().toString(36), from: fromId, to: id, type }];
1324
- });
1325
- }
1326
- setPending(null);
1327
- setDragging(false);
1328
- };
1329
-
1330
- // Suppress the host context menu over the canvas while cutting is on.
1331
- useEffect(() => {
1332
- if (!cutMode) return undefined;
1333
- const inside = (ev) => {
1334
- const el = canvasElRef.current;
1335
- return Boolean(el) && ev.target instanceof Node && el.contains(ev.target);
1336
- };
1337
- const onCtx = (ev) => { if (inside(ev)) ev.preventDefault(); };
1338
- const onDown = (ev) => {
1339
- if (ev.button !== 2 || !inside(ev) || ev.target.closest('[data-node]')) return;
1340
- ev.preventDefault();
1341
- const start = pointTo(ev);
1342
- cutRef.current = start;
1343
- setCutPath([start]);
1344
- setDragging(true);
1345
- };
1346
- window.addEventListener('contextmenu', onCtx, true);
1347
- window.addEventListener('mousedown', onDown, true);
1348
- return () => {
1349
- window.removeEventListener('contextmenu', onCtx, true);
1350
- window.removeEventListener('mousedown', onDown, true);
1351
- };
1352
- }, [cutMode, sessionId]);
1353
-
1354
- useEffect(() => {
1355
- if (!dragging) return undefined;
1356
- const move = (ev) => onCanvasMove(ev);
1357
- const up = () => onCanvasUp();
1358
- window.addEventListener('mousemove', move);
1359
- window.addEventListener('mouseup', up);
1360
- return () => {
1361
- window.removeEventListener('mousemove', move);
1362
- window.removeEventListener('mouseup', up);
1363
- };
1364
- }, [dragging, marquee, pending]);
1365
-
1366
- const onCanvasDown = (e) => {
1367
- if (e.button === 2) {
1368
- if (!cutMode) return;
1369
- e.preventDefault();
1370
- try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
1371
- const start = pointTo(e);
1372
- cutRef.current = start;
1373
- cutHits.current = new Set();
1374
- setCutPath([start]);
1375
- setCutVictims([]);
1376
- setDragging(true);
1377
- return;
1378
- }
1379
- if (e.button !== 0) return;
1380
- if (roleEditFor) setRoleEditFor(null);
1381
- if (menuOpen) setMenuOpen(false);
1382
- e.preventDefault();
1383
- try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
1384
- const p = pointTo(e);
1385
- setMarquee({ x1: p.x, y1: p.y, x2: p.x, y2: p.y });
1386
- setDragging(true);
1387
- if (selectedIds.length) setSelectedIds([]);
1388
- setOpenModelFor(null);
1389
- };
1390
-
1391
- const onCanvasMove = (e) => {
1392
- if (nodeDrag.current) {
1393
- const p = pointTo(e);
1394
- const drag = nodeDrag.current;
1395
- const dx = p.x - drag.startX;
1396
- const dy = p.y - drag.startY;
1397
- if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) drag.moved = true;
1398
- const byId = new Map(drag.origins.map((o) => [o.id, o]));
1399
- setNodes((ns) => ns.map((n) => {
1400
- const origin = byId.get(n.id);
1401
- return origin ? { ...n, x: origin.x + dx, y: origin.y + dy } : n;
1402
- }));
1403
- } else if (cutRef.current) {
1404
- const p = pointTo(e);
1405
- const threshold = 12 / (viewRef.current.k || 1);
1406
- const from = cutRef.current;
1407
- const steps = Math.max(1, Math.ceil(Math.hypot(p.x - from.x, p.y - from.y) / 6));
1408
- for (let step = 1; step <= steps; step += 1) {
1409
- const t = step / steps;
1410
- const canvasSpot = {
1411
- x: from.x + (p.x - from.x) * t + WORLD_PAD,
1412
- y: from.y + (p.y - from.y) * t + WORLD_PAD,
1413
- };
1414
- for (const edge of edges) {
1415
- if (cutHits.current.has(edge.id)) continue;
1416
- const source = nodes.find((n) => n.id === edge.from);
1417
- const target = nodes.find((n) => n.id === edge.to);
1418
- if (!source || !target) continue;
1419
- if (distanceToEdge(canvasSpot, source, target, edge.type) <= threshold) {
1420
- cutHits.current.add(edge.id);
1421
- }
1422
- }
1423
- }
1424
- setCutPath((path) => path.concat([{ x: p.x, y: p.y }]).slice(-60));
1425
- setCutVictims(Array.from(cutHits.current));
1426
- cutRef.current = p;
1427
- } else if (marquee) {
1428
- const p = pointTo(e);
1429
- const next = { x1: marquee.x1, y1: marquee.y1, x2: p.x, y2: p.y };
1430
- setMarquee(next);
1431
- // Live preview: highlight what the band currently covers.
1432
- setSelectedIds(hitTest(next));
1433
- } else if (pending) {
1434
- const p = pointTo(e);
1435
- setPending((prev) => (prev ? { ...prev, x: p.x, y: p.y } : prev));
1436
- }
1437
- };
1438
-
1439
- const onCanvasUp = () => {
1440
- if (cutRef.current) {
1441
- cutRef.current = null;
1442
- setDragging(false);
1443
- const victims = Array.from(cutHits.current);
1444
- const victimIds = new Set(victims);
1445
- cutHits.current = new Set();
1446
- if (victims.length) {
1447
- pushSnapshot();
1448
- setEdges((es) => es.filter((x) => !victimIds.has(x.id)));
1449
- flash(t('linkCut') + ' ×' + victims.length);
1450
- }
1451
- }
1452
- if (cutPath.length) { setCutPath([]); setCutVictims([]); }
1453
- if (marquee) {
1454
- setSelectedIds(hitTest(marquee));
1455
- setMarquee(null);
1456
- }
1457
- nodeDrag.current = null;
1458
- setPending(null);
1459
- setDragging(false);
1460
- };
1461
-
1462
- const savePresetNow = () => {
1463
- const name = presetName.trim();
1464
- if (!name) { flash(t('needName')); return; }
1465
- if (Object.prototype.hasOwnProperty.call(presets, name)) {
1466
- flash('"' + name + '" ' + t('dupName'));
1467
- return;
1468
- }
1469
- const next = { ...presets, [name]: { nodes, edges } };
1470
- if (!savePresets(next)) { flash(t('saveFailed')); return; }
1471
- setPresets(next);
1472
- setPresetName('');
1473
- setPresetOpen(null);
1474
- flash(t('savedPreset') + ': ' + name);
1475
- };
1476
-
1477
- /** Load a canvas document produced by the model. */
1478
- const applyCanvasDoc = (doc) => {
1479
- if (!doc || !Array.isArray(doc.nodes)) return false;
1480
- const merge = doc.mode === 'merge';
1481
- if (!merge && !doc.nodes.length) return false;
1482
- pushSnapshot();
1483
- applyStamp.current = typeof doc.at === 'number' ? doc.at : null;
1484
- setNodes((existing) => {
1485
- const byId = new Map(existing.map((n) => [n.id, n]));
1486
- const incoming = doc.nodes.map((n, i) => {
1487
- const prev = byId.get(n.id) || {};
1488
- return {
1489
- ...prev,
1490
- ...n,
1491
- // keep the position the user placed, unless the document sets one
1492
- x: typeof n.x === 'number' ? n.x : (typeof prev.x === 'number' ? prev.x : 60 + i * 300),
1493
- y: typeof n.y === 'number' ? n.y : (typeof prev.y === 'number' ? prev.y : 80),
1494
- };
1495
- });
1496
- if (!merge) return incoming;
1497
- const touched = new Set(incoming.map((n) => n.id));
1498
- const removed = new Set(doc.removeNodes || []);
1499
- const kept = existing.filter((n) => !touched.has(n.id) && !removed.has(n.id));
1500
- return kept.concat(incoming);
1501
- });
1502
- setEdges((existing) => {
1503
- const incoming = (Array.isArray(doc.edges) ? doc.edges : []).map((e, i) => ({
1504
- id: e.id || 'e' + i + '-' + Math.random().toString(36).slice(2, 6),
1505
- from: e.from,
1506
- to: e.to,
1507
- type: e.type || 'prompt',
1508
- }));
1509
- if (!merge) return incoming;
1510
- const drop = new Set((doc.removeEdges || []).map((e) => String(e.from) + '>' + String(e.to)));
1511
- const kept = existing.filter((e) => !drop.has(e.from + '>' + e.to));
1512
- const seen = new Set(kept.map((e) => e.from + '>' + e.to + '|' + e.type));
1513
- const added = incoming.filter((e) => !seen.has(e.from + '>' + e.to + '|' + e.type));
1514
- return kept.concat(added);
1515
- });
1516
- setSelectedIds([]);
1517
- setStatusById({});
1518
- // Remember what the remote document claimed, so re-reading it on the next
1519
- // start does not resurrect nodes the user has deleted since.
1520
- if (typeof doc.at === 'number') {
1521
- try {
1522
- const key = storageKey(sessionId);
1523
- const raw = window.localStorage.getItem(key);
1524
- const local = raw ? JSON.parse(raw) : {};
1525
- if (!local || typeof local.at !== 'number' || local.at <= doc.at) {
1526
- window.localStorage.setItem(key, JSON.stringify({
1527
- nodes: doc.nodes,
1528
- edges: Array.isArray(doc.edges) ? doc.edges : [],
1529
- enabled: Boolean(local && local.enabled),
1530
- at: doc.at,
1531
- }));
1532
- }
1533
- } catch (_e) { /* storage unavailable */ }
1534
- }
1535
- const lead = doc.nodes.find((n) => n.id === 'lead') || doc.nodes[0];
1536
- if (lead) {
1537
- const lx = typeof lead.x === 'number' ? lead.x : 60;
1538
- const ly = typeof lead.y === 'number' ? lead.y : 80;
1539
- setTimeout(() => centerOn(lx + NODE_W / 2, ly + NODE_H / 2), 0);
1540
- }
1541
- return true;
1542
- };
1543
-
1544
- // The Host writes generated canvases where the workspace Remote can read
1545
- // them; polling that file is the only Host -> canvas channel available.
1546
- const AUTO_CANVAS = true;
1547
- useEffect(() => {
1548
- if (!AUTO_CANVAS) return undefined;
1549
- let remote;
1550
- try { remote = hostCtx && hostCtx.remote; } catch (_e) { remote = undefined; }
1551
- let wf = resolveWorkspaceFiles(hostCtx);
1552
- if (!wf) {
1553
- try { wf = remote && remote.workspaceFiles; } catch (_e) { wf = undefined; }
1554
- }
1555
- if (!wf || typeof wf.read !== 'function') { setSyncNote(t('syncOff')); return undefined; }
1556
- if (!sessionId) { setSyncNote(t('syncNoSession')); return undefined; }
1557
- // The Host names the file after the agent id (session-<uuid>); the
1558
- // pane prop may carry either form, so try both.
1559
- const bare = String(sessionId).replace(/^session-/, '');
1560
- const paths = [
1561
- '.dsh/canvas/' + String(sessionId) + '.json',
1562
- '.dsh/canvas/session-' + bare + '.json',
1563
- '.dsh/canvas/' + bare + '.json',
1564
- ].filter((v, i, all) => all.indexOf(v) === i);
1565
- let alive = true;
1566
- let lastText = '';
1567
- const tick = async () => {
1568
- try {
1569
- let text = '';
1570
- for (const path of paths) {
1571
- try {
1572
- const res = await wf.read(sessionId, path, {}, new AbortController().signal);
1573
- if (!alive) return;
1574
- const payload = res && res.ok === false ? null : (res && res.value !== undefined ? res.value : res);
1575
- const read = payload && (typeof payload.text === 'string' ? payload.text : '');
1576
- if (read) { text = read; break; }
1577
- } catch (err) {
1578
- setSyncNote(t('syncReadFail') + String((err && err.message) || err).slice(0, 80));
1579
- }
1580
- }
1581
- if (!text) return;
1582
- if (text === lastText) return;
1583
- lastText = text;
1584
- const doc = JSON.parse(text);
1585
- const canvas = doc && doc.canvas;
1586
- // A canvas the user has edited more recently wins over an old file.
1587
- try {
1588
- const raw = window.localStorage.getItem(storageKey(sessionId));
1589
- const local = raw ? JSON.parse(raw) : null;
1590
- if (local && typeof local.at === 'number' && typeof doc.at === 'number' && local.at > doc.at) {
1591
- lastText = text;
1592
- return;
1593
- }
1594
- } catch (_e) { /* ignore */ }
1595
- const valid = canvas && Array.isArray(canvas.nodes) && canvas.nodes.length
1596
- && canvas.nodes.every((n) => n && typeof n.id === 'string');
1597
- if (valid && applyCanvasDoc(canvas)) {
1598
- flash(t('generated'));
1599
- setSyncNote(t('syncApplied'));
1600
- setTimeout(() => setSyncNote(''), 4000);
1601
- }
1602
- else setSyncNote(t('syncBadFile'));
1603
- } catch (_e) { /* file absent or not readable yet */ }
1604
- };
1605
- const timer = setInterval(tick, 1500);
1606
- tick();
1607
- return () => { alive = false; clearInterval(timer); };
1608
- }, [sessionId]);
1609
-
1610
- const importFromClipboard = () => {
1611
- const finish = (text) => {
1612
- if (!text) { flash(t('importNone')); return; }
1613
- let doc;
1614
- try {
1615
- const start = text.indexOf('{');
1616
- const end = text.lastIndexOf('}');
1617
- doc = JSON.parse(text.slice(start, end + 1));
1618
- } catch (_e) { flash(t('importBad')); return; }
1619
- if (!applyCanvasDoc(doc.canvas || doc)) { flash(t('importBad')); return; }
1620
- flash(t('importOk') + (doc.canvas || doc).nodes.length);
1621
- };
1622
- try {
1623
- if (navigator.clipboard && navigator.clipboard.readText) {
1624
- navigator.clipboard.readText().then(finish, () => flash(t('importNone')));
1625
- return;
1626
- }
1627
- } catch (_e) { /* fall through */ }
1628
- flash(t('importNone'));
1629
- };
1630
-
1631
- const applyPreset = (name) => {
1632
- const preset = presets[name];
1633
- if (!preset || !Array.isArray(preset.nodes) || !Array.isArray(preset.edges)) { flash(t('invalidPreset')); return; }
1634
- pushSnapshot();
1635
- setNodes(preset.nodes);
1636
- setEdges(preset.edges);
1637
- setSelectedIds([]);
1638
- setStatusById({});
1639
- setPresetOpen(null);
1640
- flash(t('loadedPreset') + ': ' + name);
1641
- };
1642
-
1643
- const deletePreset = (name) => {
1644
- const next = { ...presets };
1645
- delete next[name];
1646
- savePresets(next);
1647
- setPresets(next);
1648
- flash(t('deletedPreset') + ': ' + name);
1649
- };
1650
-
1651
- const toggleEnabled = () => {
1652
- const next = !enabled;
1653
- setEnabled(next);
1654
- setDirty(false);
1655
- pushPlan(next);
1656
- };
1657
-
1658
- const modelValue = (node) => (node.provider ? node.provider + '::' : '') + (node.model || '');
1659
- const modelEntry = (node) => models.find((m) => m.provider + '::' + m.model === modelValue(node));
1660
- const modelLabel = (node) => {
1661
- const hit = modelEntry(node);
1662
- return hit ? hit.modelName : (node.model || t('pickModel'));
1663
- };
1664
- // Reasoning ids are adapter-declared per model; '' means "use the model default".
1665
- const reasoningOptions = (node) => {
1666
- const hit = modelEntry(node);
1667
- const ids = ((hit && hit.efforts) || []).map((e) => e.id);
1668
- return ['', ...(ids.length ? ids : REASONING_FALLBACK)];
1669
- };
1670
- const reasoningLabel = (node) => {
1671
- if (!node.reasoning) return t('defaultEffort');
1672
- const hit = modelEntry(node);
1673
- const found = hit && hit.efforts ? hit.efforts.find((e) => e.id === node.reasoning) : undefined;
1674
- return (found && (found.name || found.id)) || node.reasoning;
1675
- };
1676
-
1677
- const scopeToggle = (node) => {
1678
- const wide = (node.preset || 'standard') !== 'minimal';
1679
- return h('button', {
1680
- style: wide ? S.toggleSwitchOn : S.toggleSwitch,
1681
- type: 'button',
1682
- title: t('tipPreset'),
1683
- onMouseDown: (e) => e.stopPropagation(),
1684
- onClick: () => updateNode(node.id, { preset: wide ? 'minimal' : 'standard' }),
1685
- }, wide ? t('scopeStandard') : t('scopeMinimal'));
1686
- };
1687
- const fallbackControl = (node) => {
1688
- const key = 'f:' + node.id;
1689
- const isOpen = openModelFor === key;
1690
- const current = node.fallbackModel;
1691
- const shown = models.find((m) => m.model === current);
1692
- const rows = [];
1693
- rows.push(h('div', {
1694
- key: 'none',
1695
- style: current ? S.menuRow : { ...S.menuRow, background: C.hover, color: C.accent },
1696
- onClick: () => { updateNode(node.id, { fallbackModel: '', fallbackProvider: '' }); setOpenModelFor(null); },
1697
- }, t('none')));
1698
- let lastProvider = null;
1699
- for (const m of models) {
1700
- if (m.provider !== lastProvider) {
1701
- rows.push(h('div', { key: 'h-' + m.provider, style: S.menuHead }, m.providerName || m.provider));
1702
- lastProvider = m.provider;
1703
- }
1704
- const picked = m.model === current;
1705
- rows.push(h('div', {
1706
- key: m.provider + '::' + m.model,
1707
- style: picked ? { ...S.menuRow, background: C.hover, color: C.accent } : S.menuRow,
1708
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1709
- onMouseLeave: (e) => { e.currentTarget.style.background = picked ? C.hover : 'transparent'; },
1710
- onClick: () => { updateNode(node.id, { fallbackModel: m.model, fallbackProvider: m.provider }); setOpenModelFor(null); },
1711
- }, m.modelName || m.model));
1712
- }
1713
- return h('div', { ref: isOpen ? dropdownRef : undefined, style: { position: 'relative', flex: '1 1 auto', minWidth: 0 } },
1714
- h('button', {
1715
- style: S.selectBtn,
1716
- type: 'button',
1717
- title: t('tipFallback'),
1718
- onMouseDown: (e) => e.stopPropagation(),
1719
- onClick: () => setOpenModelFor(isOpen ? null : key),
1720
- },
1721
- h('span', { style: S.selectText }, shown ? (shown.modelName || shown.model) : t('none')),
1722
- h('span', { style: S.caret }, '▾'),
1723
- ),
1724
- isOpen && h('div', { style: S.menu, onMouseDown: (e) => e.stopPropagation() }, rows),
1725
- );
1726
- };
1727
- const memoryToggle = (node) => h('button', {
1728
- style: node.keepSession ? S.toggleSwitchOn : S.toggleSwitch,
1729
- type: 'button',
1730
- title: t('tipMemory'),
1731
- onMouseDown: (e) => e.stopPropagation(),
1732
- onClick: () => updateNode(node.id, { keepSession: !node.keepSession }),
1733
- }, node.keepSession ? t('on') : t('off'));
1734
-
1735
- const reasoningControl = (node) => {
1736
- const key = 'r:' + node.id;
1737
- const isOpen = openModelFor === key;
1738
- const entry = modelEntry(node);
1739
- const labelOf = (id) => {
1740
- if (!id) return t('defaultEffort');
1741
- const found = entry && entry.efforts ? entry.efforts.find((e) => e.id === id) : undefined;
1742
- return (found && (found.name || found.id)) || id;
1743
- };
1744
- const rows = reasoningOptions(node).map((id, i) => h('div', {
1745
- key: 'r' + i,
1746
- style: node.reasoning === id ? { ...S.menuRow, background: C.hover, color: C.accent } : S.menuRow,
1747
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1748
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1749
- onClick: () => { updateNode(node.id, { reasoning: id }); setOpenModelFor(null); },
1750
- }, labelOf(id)));
1751
- return h('div', { ref: isOpen ? dropdownRef : undefined, style: { position: 'relative', flex: '1 1 auto', minWidth: 0 } },
1752
- h('button', {
1753
- style: S.selectBtn,
1754
- type: 'button',
1755
- title: t('tipModel'),
1756
- onMouseDown: (e) => e.stopPropagation(),
1757
- onClick: () => setOpenModelFor(isOpen ? null : key),
1758
- },
1759
- h('span', { style: S.selectText }, labelOf(node.reasoning)),
1760
- h('span', { style: S.caret }, '▾'),
1761
- ),
1762
- isOpen && h('div', { style: S.menu, onMouseDown: (e) => e.stopPropagation() }, rows),
1763
- );
1764
- };
1765
-
1766
- const modelControl = (node) => {
1767
- if (!models.length) {
1768
- return h('input', {
1769
- style: S.input,
1770
- value: node.model || '',
1771
- placeholder: 'model id',
1772
- onMouseDown: (e) => e.stopPropagation(),
1773
- onChange: (e) => updateNode(node.id, { model: e.target.value }),
1774
- });
1775
- }
1776
- const current = modelValue(node);
1777
- const isOpen = openModelFor === node.id;
1778
- const rows = [];
1779
- let lastProvider = null;
1780
- for (const m of models) {
1781
- if (m.provider !== lastProvider) {
1782
- rows.push(h('div', { key: 'h-' + m.provider, style: S.menuHead }, m.providerName || m.provider));
1783
- lastProvider = m.provider;
1784
- }
1785
- const selectedRow = m.provider + '::' + m.model === current;
1786
- rows.push(h('div', {
1787
- key: m.provider + '::' + m.model,
1788
- style: selectedRow ? { ...S.menuRow, background: C.hover, color: C.accent } : S.menuRow,
1789
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1790
- onMouseLeave: (e) => { e.currentTarget.style.background = selectedRow ? C.hover : 'transparent'; },
1791
- onClick: () => { updateNode(node.id, { provider: m.provider, model: m.model }); setOpenModelFor(null); },
1792
- }, m.modelName || m.model));
1793
- }
1794
- return h('div', { ref: isOpen ? dropdownRef : undefined, style: { position: 'relative', flex: '1 1 auto', minWidth: 0 } },
1795
- h('button', {
1796
- style: S.selectBtn,
1797
- type: 'button',
1798
- onMouseDown: (e) => e.stopPropagation(),
1799
- onClick: () => setOpenModelFor(isOpen ? null : node.id),
1800
- },
1801
- h('span', { style: S.selectText }, modelLabel(node)),
1802
- h('span', { style: S.caret }, '▾'),
1803
- ),
1804
- isOpen && h('div', {
1805
- style: S.menu,
1806
- onMouseDown: (e) => e.stopPropagation(),
1807
- }, rows),
1808
- );
1809
- };
1810
-
1811
- const edgeEls = edges.map((edge) => {
1812
- const from = nodes.find((n) => n.id === edge.from);
1813
- const to = nodes.find((n) => n.id === edge.to);
1814
- if (!from || !to) return null;
1815
- const color = (SOCKET_TYPES.find((t) => t.id === edge.type) || SOCKET_TYPES[0]).color;
1816
- const d = edgePath(from, to, edge.type);
1817
- const highlighted = cutVictims.includes(edge.id);
1818
- return h('path', {
1819
- key: edge.id,
1820
- d,
1821
- stroke: highlighted ? '#e5534b' : color,
1822
- strokeWidth: highlighted ? 3 : 2,
1823
- fill: 'none',
1824
- style: { pointerEvents: 'none' },
1825
- });
1826
- });
1827
-
1828
- const renderBand = (node) => {
1829
- const isEntry = node.id === 'lead';
1830
- return h('div', { style: S.band },
1831
- SOCKET_TYPES.map((sock) => h('div', { key: sock.id, style: S.row },
1832
- h('span', { style: S.rowLabel }, sock.label),
1833
- !isEntry && h('div', {
1834
- style: { ...S.socket, left: -PORT / 2, borderColor: sock.color },
1835
- title: t('tipSocketOut'),
1836
- onMouseDown: (e) => onInputDown(e, node.id, sock.id),
1837
- onMouseUp: (e) => onInputUp(e, node.id, sock.id),
1838
- }),
1839
- h('div', {
1840
- style: { ...S.socket, right: -PORT / 2, borderColor: sock.color },
1841
- title: t('tipSocketIn'),
1842
- onMouseDown: (e) => onOutputDown(e, node.id, sock.id),
1843
- onMouseUp: (e) => onOutputUp(e, node.id, sock.id),
1844
- }),
1845
- )),
1846
- );
1847
- };
1848
-
1849
- const reachableIds = reachableFrom(nodes, edges);
1850
-
1851
- // The canvas grows with its nodes so links past the original size are
1852
- // still painted instead of being clipped by the SVG viewport.
1853
- const contentW = Math.max(CONTENT_W, WORLD_PAD + Math.max(0, ...nodes.map((n) => n.x + NODE_W)) + 400);
1854
- const contentH = Math.max(CONTENT_H, WORLD_PAD + Math.max(0, ...nodes.map((n) => n.y + NODE_H)) + 400);
1855
-
1856
- const hitTest = (m) => {
1857
- const left = Math.min(m.x1, m.x2);
1858
- const right = Math.max(m.x1, m.x2);
1859
- const top = Math.min(m.y1, m.y2);
1860
- const bottom = Math.max(m.y1, m.y2);
1861
- return nodes
1862
- .filter((n) => n.x + NODE_W >= left && n.x <= right && n.y + NODE_H >= top && n.y <= bottom)
1863
- .map((n) => n.id);
1864
- };
1865
-
1866
- return h('div', { style: S.root },
1867
- h('div', { style: S.toolbar },
1868
- h('button', { style: S.btn, onClick: () => addNode('agent'), type: 'button' }, t('addAgent')),
1869
- h('button', { style: S.btn, onClick: () => addNode('lead'), type: 'button' }, t('addLead')),
1870
- h('button', { style: S.btn, onClick: undo, type: 'button', title: t('tipUndo') }, t('undo')),
1871
- h('button', {
1872
- style: S.btn,
1873
- onClick: () => pushPlan(enabled),
1874
- type: 'button',
1875
- title: t('tipSync'),
1876
- }, t('sync')),
1877
-
1878
- h('button', {
1879
- style: S.btn,
1880
- onClick: focusLead,
1881
- type: 'button',
1882
- title: t('tipLocate'),
1883
- }, t('locate')),
1884
- h('button', {
1885
- style: S.btn,
1886
- onClick: () => focusLead(),
1887
- type: 'button',
1888
- title: t('tipResetZoom'),
1889
- }, Math.round(view.k * 100) + '%'),
1890
- syncNote ? h('span', { style: S.syncNote, title: syncNote }, syncNote) : null,
1891
- h('button', {
1892
- style: S.btn,
1893
- onClick: toggleLang,
1894
- type: 'button',
1895
- title: 'Switch language / 切换语言',
1896
- }, t('lang')),
1897
- h('div', { style: S.moreBar },
1898
- h('button', {
1899
- style: S.btn,
1900
- type: 'button',
1901
- title: t('tipMore'),
1902
- onMouseDown: (e) => e.stopPropagation(),
1903
- onClick: () => setMenuOpen(!menuOpen),
1904
- }, '⋯'),
1905
- menuOpen && h('div', { style: S.moreMenu, onMouseDown: (e) => e.stopPropagation() },
1906
- h('div', {
1907
- style: S.moreRow,
1908
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1909
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1910
- onClick: () => { setMenuOpen(false); importFromClipboard(); },
1911
- }, t('importBtn')),
1912
- h('div', {
1913
- style: S.moreRow,
1914
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1915
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1916
- onClick: () => { setMenuOpen(false); setHelpOpen(true); },
1917
- }, t('help')),
1918
- h('div', {
1919
- style: S.moreRow,
1920
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1921
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1922
- onClick: () => {
1923
- const next = !cutMode;
1924
- setCutMode(next);
1925
- saveCutMode(next);
1926
- },
1927
- }, t('cutLinks') + t('sep') + (cutMode ? t('on') : t('off'))),
1928
- ),
1929
- ),
1930
- h('div', { style: S.presetBar },
1931
- h('div', { style: S.presetRowTop },
1932
- h('input', {
1933
- style: S.presetInput,
1934
- value: presetName,
1935
- placeholder: t('presetName'),
1936
- onMouseDown: (e) => e.stopPropagation(),
1937
- onChange: (e) => setPresetName(e.target.value),
1938
- onKeyDown: (e) => { if (e.key === 'Enter') savePresetNow(); },
1939
- }),
1940
- h('button', { style: S.btn, onClick: savePresetNow, type: 'button', title: t('tipSave') }, t('save')),
1941
- (() => {
1942
- const names = Object.keys(presets);
1943
- return h('button', {
1944
- style: S.btn,
1945
- onClick: () => setPresetOpen(presetOpen === 'menu' ? null : 'menu'),
1946
- type: 'button',
1947
- title: t('tipPresets'),
1948
- }, t('presets') + (names.length ? ' (' + names.length + ')' : ''));
1949
- })(),
1950
- ),
1951
- // Feedback for saving / loading / syncing sits right under the name field.
1952
- h('span', { style: S.status },
1953
- status || (enabled ? (dirty ? t('unsaved') : t('synced')) : '')),
1954
- presetOpen === 'menu' && (() => {
1955
- const names = Object.keys(presets);
1956
- return h('div', { style: S.presetMenu, onMouseDown: (e) => e.stopPropagation() },
1957
- names.length
1958
- ? names.map((name) => h('div', {
1959
- key: name,
1960
- style: S.presetRow,
1961
- onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1962
- onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1963
- },
1964
- h('span', { style: S.presetRowText, onClick: () => applyPreset(name) }, name),
1965
- h('button', { style: S.presetDel, type: 'button', title: t('del'), onClick: () => deletePreset(name) }, '×'),
1966
- ))
1967
- : h('div', { style: S.presetEmpty }, t('presetEmpty')),
1968
- );
1969
- })(),
1970
- ),
1971
- ),
1972
- helpOpen && h('div', { style: S.helpOverlay, onMouseDown: (e) => e.stopPropagation() },
1973
- h('div', { style: S.helpCard },
1974
- h('div', { style: S.helpHead },
1975
- h('span', { style: S.helpTitle }, t('helpTitle')),
1976
- h('button', { style: S.btn, type: 'button', onClick: () => setHelpOpen(false) }, t('close')),
1977
- ),
1978
- h('div', { style: S.helpBody }, t('helpBody').split('\n').map((line, i) => h('div', { key: i, style: S.helpLine }, line))),
1979
- ),
1980
- ),
1981
- h('button', {
1982
- style: enabled ? S.floatOn : S.floatOff,
1983
- type: 'button',
1984
- onMouseDown: (e) => e.stopPropagation(),
1985
- onClick: toggleEnabled,
1986
- title: t('tipToggle'),
1987
- }, enabled ? t('enabled') : t('disabled')),
1988
- h('div', { ref: canvasElRef, style: S.canvas, onMouseDown: onCanvasDown },
1989
- h('div', {
1990
- ref: contentRef,
1991
- style: {
1992
- ...S.content, width: contentW, height: contentH, overflow: 'visible',
1993
- transform: 'translate(' + view.x + 'px,' + view.y + 'px) scale(' + view.k + ')',
1994
- transformOrigin: '0 0',
1995
- },
1996
- },
1997
- h('svg', { width: contentW, height: contentH, style: { position: 'absolute', left: 0, top: 0, pointerEvents: 'none', overflow: 'visible' } },
1998
- h('g', null, edgeEls),
1999
- cutPath.length > 1 && h('polyline', {
2000
- points: cutPath.map((pt) => (pt.x + WORLD_PAD) + ',' + (pt.y + WORLD_PAD)).join(' '),
2001
- fill: 'none',
2002
- stroke: '#e5534b',
2003
- strokeWidth: 1.5,
2004
- strokeDasharray: '5 4',
2005
- }),
2006
- marquee && h('rect', {
2007
- x: Math.min(marquee.x1, marquee.x2) + WORLD_PAD,
2008
- y: Math.min(marquee.y1, marquee.y2) + WORLD_PAD,
2009
- width: Math.abs(marquee.x2 - marquee.x1),
2010
- height: Math.abs(marquee.y2 - marquee.y1),
2011
- fill: 'rgba(47,129,247,0.12)',
2012
- stroke: C.accent,
2013
- strokeWidth: 1,
2014
- strokeDasharray: '4 3',
2015
- }),
2016
- pending && (() => {
2017
- const color = (SOCKET_TYPES.find((t) => t.id === pending.type) || SOCKET_TYPES[0]).color;
2018
- const d = 'M ' + (pending.sx + WORLD_PAD) + ' ' + (pending.sy + WORLD_PAD) + ' L ' + (pending.x + WORLD_PAD) + ' ' + (pending.y + WORLD_PAD);
2019
- return h('path', { d, stroke: color, strokeWidth: 2, strokeDasharray: '4 4', fill: 'none' });
2020
- })(),
2021
- ),
2022
- nodes.map((node) => {
2023
- const isEntry = node.id === 'lead';
2024
- const isLeadKind = node.kind === 'lead';
2025
- const roleInput = (style) => h('div', { style },
2026
- h('span', { style: S.fieldLabel }, t('role')),
2027
- h('input', {
2028
- style: S.input,
2029
- value: node.role || '',
2030
- placeholder: isLeadKind ? t('rolePhLead') : t('rolePhAgent'),
2031
- onMouseDown: (e) => e.stopPropagation(),
2032
- onFocus: () => setSelectedIds([node.id]),
2033
- onChange: (e) => updateNode(node.id, { role: e.target.value }),
2034
- }),
2035
- );
2036
- const isOrphan = node.id !== 'lead' && !reachableIds.has(node.id);
2037
- return h('div', {
2038
- key: node.id,
2039
- 'data-node': node.id,
2040
- style: selectedIds.includes(node.id)
2041
- ? { ...S.node, left: node.x + WORLD_PAD, top: node.y + WORLD_PAD, ...(isLeadKind ? S.leadNode : null), ...(isOrphan ? S.orphanNode : null), ...S.nodeSel }
2042
- : { ...S.node, left: node.x + WORLD_PAD, top: node.y + WORLD_PAD, ...(isLeadKind ? S.leadNode : null), ...(isOrphan ? S.orphanNode : null) },
2043
- title: isOrphan ? t('orphanTip') : undefined,
2044
- onMouseDown: (e) => onNodeDown(e, node.id),
2045
- },
2046
- h('div', {
2047
- style: {
2048
- ...S.topBar,
2049
- background: isLeadKind ? '#2f81f7' : '#3fb950',
2050
- },
2051
- }),
2052
- enabled && h('div', {
2053
- style: {
2054
- ...S.statusChip,
2055
- color: isLeadKind ? C.dim
2056
- : statusById[node.id] === 'running' ? '#2f81f7'
2057
- : statusById[node.id] === 'failed' ? '#e5534b'
2058
- : statusById[node.id] === 'done' ? '#3fb950' : C.dim,
2059
- },
2060
- title: isLeadKind ? t('tipLead') : (isOrphan ? t('tipOrphan') : t('tipStatus')),
2061
- }, isOrphan ? t('stOrphan')
2062
- : isLeadKind ? t('stLead')
2063
- : statusById[node.id] === 'running' ? t('stRunning')
2064
- : statusById[node.id] === 'failed' ? t('stFailed')
2065
- : statusById[node.id] === 'done' ? t('stDone') : t('stPending')),
2066
- isEntry
2067
- ? h('div', { style: S.titleReadonly }, t('leadThis'))
2068
- : h('input', {
2069
- style: S.title,
2070
- value: node.label,
2071
- onMouseDown: (e) => e.stopPropagation(),
2072
- onFocus: () => setSelectedIds([node.id]),
2073
- onChange: (e) => updateNode(node.id, { label: e.target.value }),
2074
- }),
2075
- isEntry
2076
- ? h(React.Fragment, null,
2077
- h('div', { style: S.leadLabel }, h('span', { style: S.fieldLabel }, t('task'))),
2078
- h('textarea', {
2079
- style: S.task,
2080
- value: node.task || '',
2081
- placeholder: t('taskPh'),
2082
- onMouseDown: (e) => e.stopPropagation(),
2083
- onFocus: () => setSelectedIds([node.id]),
2084
- onChange: (e) => updateNode(node.id, { task: e.target.value }),
2085
- }),
2086
- )
2087
- : isLeadKind
2088
- ? h(React.Fragment, null,
2089
- h('div', { style: S.leadLabel }, h('span', { style: S.fieldLabel }, t('role'))),
2090
- h('textarea', {
2091
- style: S.task,
2092
- value: node.role || '',
2093
- placeholder: t('rolePhLead'),
2094
- onMouseDown: (e) => e.stopPropagation(),
2095
- onFocus: () => setSelectedIds([node.id]),
2096
- onChange: (e) => updateNode(node.id, { role: e.target.value }),
2097
- }),
2098
- )
2099
- : h(React.Fragment, null,
2100
- h('div', { style: S.fieldModel },
2101
- h('span', { style: S.fieldLabel }, t('model')),
2102
- modelControl(node),
2103
- ),
2104
- h('div', { style: S.fieldReason },
2105
- h('span', { style: S.fieldLabel }, t('reason')),
2106
- reasoningControl(node),
2107
- ),
2108
- h('div', { style: S.fieldScope },
2109
- h('span', { style: S.fieldLabel }, t('scope')),
2110
- scopeToggle(node),
2111
- ),
2112
- h('div', { style: S.fieldFallback },
2113
- h('span', { style: S.fieldLabel }, t('fallbackModel')),
2114
- fallbackControl(node),
2115
- ),
2116
- h('div', { style: S.fieldMemory },
2117
- h('span', { style: S.fieldLabel }, t('memory')),
2118
- memoryToggle(node),
2119
- ),
2120
- h('div', { style: S.fieldRole },
2121
- h('span', { style: S.fieldLabel }, t('role')),
2122
- h('button', {
2123
- style: S.selectBtn,
2124
- type: 'button',
2125
- title: t('rolePhAgent'),
2126
- onMouseDown: (e) => e.stopPropagation(),
2127
- onClick: () => setRoleEditFor(roleEditFor === node.id ? null : node.id),
2128
- },
2129
- h('span', { style: S.selectText }, node.role || t('rolePhAgent')),
2130
- h('span', { style: S.caret }, '✎'),
2131
- ),
2132
- ),
2133
- roleEditFor === node.id && h('div', {
2134
- style: S.rolePopover,
2135
- onMouseDown: (e) => e.stopPropagation(),
2136
- },
2137
- h('textarea', {
2138
- style: S.roleArea,
2139
- value: node.role || '',
2140
- placeholder: t('rolePhAgent'),
2141
- autoFocus: true,
2142
- onChange: (e) => updateNode(node.id, { role: e.target.value }),
2143
- }),
2144
- ),
2145
- ),
2146
- selectedIds.includes(node.id) && node.id !== 'lead' && h('div', {
2147
- style: S.nodeDelete,
2148
- title: t('delNodeTip'),
2149
- onMouseDown: (e) => e.stopPropagation(),
2150
- onClick: () => deleteNode(node.id),
2151
- }, '×'),
2152
- renderBand(node),
2153
- );
2154
- }),
2155
- ),
2156
- ),
2157
- );
2158
- }
2159
-
2160
- return {
2161
- inject: ['slots', 'sessions', 'remote', 'remote.session', 'sidebarRight'],
2162
- apply(ctx) {
2163
- try {
2164
- hostCtx = ctx;
2165
- ctx.inject(['sidebarRightTabs'], (scope) => {
2166
- scope.effect(() => scope.sidebarRightTabs.register({
2167
- id: TAB_ID,
2168
- kind: KIND,
2169
- // Keep the tab (and its canvas state) alive while the pane is closed.
2170
- keepMounted: true,
2171
- title: () => 'Workflow',
2172
- guide: [{
2173
- id: 'workflow-canvas',
2174
- order: 100,
2175
- title: () => 'Workflow canvas',
2176
- description: () => pick('画一张子代理流程图', 'Sketch a subagent workflow'),
2177
- }],
2178
- }), 'workflow-canvas: tab type');
2179
-
2180
- scope.effect(() => scope.slots.inject('sidebar.right.pane.tab', () => scope.slots.register({
2181
- name: 'sidebar.right.pane.tab',
2182
- key: TAB_ID,
2183
- }, (props) => h(CanvasBoundary, null, h(WorkflowCanvas, props)))), 'workflow-canvas: tab body');
2184
- });
2185
- } catch (error) {
2186
- try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
2187
- }
2188
- },
2189
- __test: { topoOrder, buildWorkflowScript, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, distanceToEdge, edgeCurve },
2190
- };
2191
- },
2192
- });
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-workflow-canvas',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+ const useState = React.useState;
7
+ const useRef = React.useRef;
8
+ const useEffect = React.useEffect;
9
+ const Component = React.Component;
10
+
11
+ /** Resolved lazily so a missing namespace can never fail plugin load. */
12
+ let workspaceFilesService = null;
13
+ function resolveWorkspaceFiles(ctx) {
14
+ if (workspaceFilesService) return workspaceFilesService;
15
+ try {
16
+ if (ctx && typeof ctx.get === 'function') {
17
+ workspaceFilesService = ctx.get('remote.workspaceFiles') || null;
18
+ }
19
+ } catch (_e) { /* service absent */ }
20
+ if (!workspaceFilesService) {
21
+ try {
22
+ workspaceFilesService = (ctx && ctx.remote && ctx.remote.workspaceFiles) || null;
23
+ } catch (_e) { /* proxy refuses unknown namespaces */ }
24
+ }
25
+ return workspaceFilesService;
26
+ }
27
+
28
+ const TAB_ID = '@local/dsh-workflow-canvas';
29
+ const KIND = 'workflow';
30
+ const STORAGE_PREFIX = 'dsh-workflow-canvas:v1:';
31
+ const PRESET_KEY = STORAGE_PREFIX + 'presets';
32
+
33
+ const NODE_W = 216;
34
+ const NODE_H = 224;
35
+ const PORT = 12;
36
+ const SOCKET_BAND_TOP = 168;
37
+ const ROW_H = 18;
38
+ const CONTENT_W = 2400;
39
+ const CONTENT_H = 1600;
40
+ /** World origin offset: keeps negative node coordinates inside the scroll area. */
41
+ const WORLD_PAD = 2000;
42
+
43
+ // One socket per channel type: a link can only join the same type.
44
+ const SOCKET_TYPES = [
45
+ { id: 'prompt', label: 'prompt', color: '#8a8f98' },
46
+ { id: 'structured', label: 'structured', color: '#2f81f7' },
47
+ { id: 'session-ref', label: 'session', color: '#a371f7' },
48
+ ];
49
+
50
+ /** Fallback effort ids when the model catalog carries no reasoning metadata. */
51
+ const REASONING_FALLBACK = ['low', 'medium', 'high'];
52
+
53
+ const LANG_KEY = STORAGE_PREFIX + 'lang';
54
+ const I18N = {
55
+ zh: {
56
+ addAgent: '+ 子代理', addLead: '+ Lead', undo: '↶ 撤销', sync: '↥ 同步',
57
+ enabled: '● 已启用', disabled: '○ 已禁用', presetName: '预设名', save: '☆ 保存',
58
+ presets: '☰ 预设', unsaved: '有未同步改动', synced: '已同步',
59
+ pickModel: '选择模型', defaultEffort: '默认',
60
+ leadThis: 'Lead(本对话)',
61
+ tipSocketOut: '拖出可断开 / 拖入可连接',
62
+ tipSocketIn: '从这里拖出连线 / 也可以把输入口拖到这里',
63
+ delNodeTip: '删除节点(可用 ↶ 撤销 找回)',
64
+ deletedNode: '节点已删除,可点「撤销」找回',
65
+ orphanTip: '未连线:运行时会被跳过',
66
+ syncOff: '自动同步不可用',
67
+ syncNoSession: '无会话 id',
68
+ syncReadFail: '读取失败: ',
69
+ syncApplied: '已应用生成结果',
70
+ syncBadFile: '文件内容无效',
71
+ generated: '已从对话生成画布',
72
+ dupName: '已存在,请换一个名字',
73
+ guideDesc: '画一张子代理流程图',
74
+ model: '模型', reason: '推理', role: '分工', task: '任务', taskPh: '本次任务:例如把这批反馈归类并给出建议',
75
+ rolePhLead: '我自己这一步做什么', rolePhAgent: '这个子代理做什么',
76
+ memory: '记忆', scope: '能力', retry: '重试', jsonOut: 'JSON 输出',
77
+ sep: ': ', on: '开', off: '关', allTools: '默认(全部工具)', none: '无',
78
+ scopeMinimal: 'minimal(只读思考)', scopeStandard: 'standard(全部工具)',
79
+ fallbackModel: '备用',
80
+ stPending: '未执行', stRunning: '进行中', stDone: '已完成', stFailed: '失败',
81
+ stOrphan: '未连线', stLead: '由对话执行',
82
+ presetEmpty: '还没有保存过预设', del: '删除这个预设',
83
+ needName: '请先给预设起个名字', duplicate: '已存在,请换一个名字',
84
+ savedPreset: '已保存预设', saveFailed: '保存失败(存储不可用)',
85
+ loadedPreset: '已载入预设', invalidPreset: '预设内容无效', deletedPreset: '已删除预设',
86
+ syncFailed: '同步失败', upToDate: '已是最新', syncedToHost: '已同步到 Host',
87
+ cannotOpen: '无法打开会话', undoDone: '已撤销', undoNone: '没有可撤销的操作',
88
+ leadLocked: '入口 Lead 不能删除', modelsMissing: '模型列表未加载',
89
+ tipLead: 'Lead 步骤在对话里执行,画布不追踪其状态',
90
+ tipOrphan: '未连线:运行时会被跳过', tipStatus: '子代理节点的运行状态',
91
+ tipZoom: '滚轮缩放(以光标为中心)',
92
+ tipResetZoom: '回到 100% 并把画面中心拉到 Lead 节点',
93
+ tipLocate: '把画面中心拉到 Lead(本对话)节点',
94
+ locate: '◎ 定位',
95
+ importBtn: '⇩ 导入',
96
+ tipImport: '从剪贴板导入模型生成的画布(先复制聊天里的画布 JSON)',
97
+ importOk: '已导入画布,共 ',
98
+ tipMore: '更多',
99
+ help: '使用说明',
100
+ helpTitle: '怎么用这个画布',
101
+ close: '关闭',
102
+ cutLinks: '右键划断连线',
103
+ linkCut: '已断开一条连线',
104
+ tipToggle: '启用/禁用此画布(启用后我才能执行它)',
105
+ helpBody: [
106
+ '1. 在入口 Lead 里写「本次任务」,这是整张图的总目标。',
107
+ '2. 点「+ 子代理」加节点,从右侧输出口拖到另一个节点左侧输入口即可连线。',
108
+ '3. 连线有三种:prompt 传文本,structured 传 JSON,session 让下游接着上游的会话跑。',
109
+ '4. 端口颜色即类型,只能同色相连;拖已连接的左口可以断开。',
110
+ '5. 每个节点可设模型、推理强度、能力范围、备用模型、是否记忆。',
111
+ '6. 连好后点「● 已启用」,然后对对话说「跑一次」,由我调用执行。',
112
+ '7. 遇到 Lead 节点会暂停,我做完再把结果交回去继续。',
113
+ '8. 没连线的节点显示为虚线,运行时会被跳过。',
114
+ '9. 右键按住划过一条连线可以切断;可在「⋯」里关掉这个手势。',
115
+ '10. 预设名 + ☆ 保存 可以把整张图存下来,新对话里从「☰ 预设」载入。',
116
+ '11. 你可以直接让我改画布:说「把那三个节点的分工改成…」,我会就地修改,不动你摆的位置。',
117
+ '12. session 线连到 Lead 时,我会在暂停那步拿到那个子代理的会话,可以继续追问它。',
118
+ ].join('\n'),
119
+ importNone: '剪贴板里没有可识别的画布数据',
120
+ importBad: '画布数据格式不对',
121
+ tipSync: '把当前画布同步给 Host(会在对话里留一条同步记录)',
122
+ tipUndo: '撤销上一步结构改动', tipSave: '把当前画布保存为预设',
123
+ tipPresets: '载入已保存的预设', tipModel: '推理等级(默认 = 该模型声明的 defaultEffort)',
124
+ tipMemory: '记忆:复用这个节点上一次的会话(仅同一进程内有效)',
125
+ tipPreset: '能力范围(点一下切换):standard = 全部工具(读写文件、跑命令、子代理、工作流、网页、办公);minimal = 只读思考(文件读写关闭,没有子代理/工作流/网页)',
126
+ tipFallback: '失败重试:该节点出错时自动换一个模型再跑一次',
127
+ tipStructured: 'JSON 输出:要求该节点返回 JSON 对象,structured 连线会把结果作为 JSON 传给下游',
128
+ lang: 'ZH',
129
+ },
130
+ en: {
131
+ addAgent: '+ Subagent', addLead: '+ Lead', undo: '↶ Undo', sync: '↥ Sync',
132
+ enabled: '● ON', disabled: '○ OFF', presetName: 'Preset name', save: '☆ Save',
133
+ presets: '☰ Presets', unsaved: 'Unsaved changes', synced: 'Synced',
134
+ pickModel: 'Pick a model', defaultEffort: 'default',
135
+ leadThis: 'Lead (this chat)',
136
+ tipSocketOut: 'Drag to detach / drop to connect',
137
+ tipSocketIn: 'Drag out to link, or drop an input here',
138
+ delNodeTip: 'Delete this node (undo with ↶)',
139
+ deletedNode: 'Node deleted, use Undo to restore it',
140
+ orphanTip: 'Unlinked: skipped when the canvas runs',
141
+ syncOff: 'Auto-sync unavailable',
142
+ syncNoSession: 'No session id',
143
+ syncReadFail: 'Read failed: ',
144
+ syncApplied: 'Generated canvas applied',
145
+ syncBadFile: 'File content is invalid',
146
+ generated: 'Canvas generated from chat',
147
+ dupName: 'already exists, pick another name',
148
+ guideDesc: 'Sketch a subagent workflow',
149
+ model: 'Model', reason: 'Reasoning', role: 'Role', task: 'Task', taskPh: 'Task, e.g. classify these reports and suggest actions',
150
+ rolePhLead: 'What I do in this step', rolePhAgent: 'What this subagent does',
151
+ memory: 'Memory', scope: 'Scope', retry: 'Retry', jsonOut: 'JSON out',
152
+ sep: ': ', on: 'on', off: 'off', allTools: 'default (all tools)', none: 'none',
153
+ scopeMinimal: 'minimal (read-only thinking)', scopeStandard: 'standard (all tools)',
154
+ fallbackModel: 'Fallback',
155
+ stPending: 'Pending', stRunning: 'Running', stDone: 'Done', stFailed: 'Failed',
156
+ stOrphan: 'Unlinked', stLead: 'Runs in chat',
157
+ presetEmpty: 'No presets saved yet', del: 'Delete this preset',
158
+ needName: 'Name the preset first', duplicate: 'already exists, pick another name',
159
+ savedPreset: 'Saved preset', saveFailed: 'Save failed (storage unavailable)',
160
+ loadedPreset: 'Loaded preset', invalidPreset: 'Preset content is invalid', deletedPreset: 'Deleted preset',
161
+ syncFailed: 'Sync failed', upToDate: 'Already up to date', syncedToHost: 'Synced to host',
162
+ cannotOpen: 'Cannot open the session', undoDone: 'Undone', undoNone: 'Nothing to undo',
163
+ leadLocked: 'The entry Lead cannot be deleted', modelsMissing: 'Model list is not loaded',
164
+ tipLead: 'Lead steps run in the chat; the canvas does not track them',
165
+ tipOrphan: 'Unlinked: skipped when the canvas runs', tipStatus: 'Subagent run status',
166
+ tipZoom: 'Wheel zooms around the cursor',
167
+ tipResetZoom: 'Reset to 100% and centre the view on the Lead node',
168
+ tipLocate: 'Centre the view on the Lead (this conversation) node',
169
+ locate: '◎ Locate',
170
+ importBtn: '⇩ Import',
171
+ tipImport: 'Import a model-generated canvas from the clipboard (copy the canvas JSON from chat first)',
172
+ importOk: 'Canvas imported, ',
173
+ tipMore: 'More',
174
+ help: 'How to use',
175
+ helpTitle: 'Using this canvas',
176
+ close: 'Close',
177
+ cutLinks: 'Right-drag to cut links',
178
+ linkCut: 'Link cut',
179
+ tipToggle: 'Enable or disable this canvas (I can only run it while enabled)',
180
+ helpBody: [
181
+ '1. Write the overall task in the entry Lead node.',
182
+ '2. Add nodes with the + buttons, then drag from a right socket to a left socket.',
183
+ '3. Links carry text (prompt), JSON (structured), or continue the upstream session (session).',
184
+ '4. Socket colour is the type; only matching types connect. Drag a connected input to detach.',
185
+ '5. Each node sets model, reasoning, capability scope, fallback model and memory.',
186
+ '6. Press ● ON, then ask in chat to run the canvas.',
187
+ '7. The run pauses at every Lead node so the conversation can do that step.',
188
+ '8. Unlinked nodes are dashed and skipped at run time.',
189
+ '9. Hold the right button and sweep across a link to cut it; turn the gesture off under ⋯.',
190
+ '10. Name a preset and press ☆ Save to keep the canvas for other sessions.',
191
+ '11. You can ask me to edit the canvas; I patch it in place and keep your layout.',
192
+ '12. A session link into a Lead step hands me that child agent, so I can follow up with it.',
193
+ ].join('\n'),
194
+ importNone: 'No canvas data found in the clipboard',
195
+ importBad: 'Canvas data is malformed',
196
+ tipSync: 'Publish this canvas to the host (leaves one sync record in the chat)',
197
+ tipUndo: 'Undo the last structural change', tipSave: 'Save this canvas as a preset',
198
+ tipPresets: 'Load a saved preset', tipModel: 'Reasoning effort (default = the model\'s defaultEffort)',
199
+ tipMemory: 'Memory: reuse this node\'s previous session (same process only)',
200
+ tipPreset: 'Capability (click to toggle): standard = all tools (files, shells, subagents, workflow, web, office); minimal = read-only thinking (no file writes, no subagents/workflow/web)',
201
+ tipFallback: 'Retry: when this node fails, rerun it once on another model',
202
+ tipStructured: 'JSON output: require an object result; structured links pass it downstream as JSON',
203
+ lang: 'EN',
204
+ },
205
+ };
206
+
207
+ /** Bilingual string for text read outside the component (tab titles, guide). */
208
+ function pick(zh, en) {
209
+ return loadLang() === 'en' ? en : zh;
210
+ }
211
+
212
+ function loadLang() {
213
+ try {
214
+ const v = window.localStorage.getItem(LANG_KEY);
215
+ return v === 'en' ? 'en' : 'zh';
216
+ } catch (_e) {
217
+ return 'zh';
218
+ }
219
+ }
220
+
221
+ const C = {
222
+ text: 'var(--dsw-alias-label-primary, inherit)',
223
+ dim: 'var(--dsw-alias-label-tertiary, rgba(140,140,140,0.95))',
224
+ border: 'var(--dsw-alias-border-l2, rgba(128,128,128,0.4))',
225
+ raised: 'var(--dsw-alias-bg-layer-1, rgba(128,128,128,0.10))',
226
+ elevated: 'var(--dsw-alias-bg-elevated, #2a2b2f)',
227
+ base: 'var(--dsw-alias-bg-base, transparent)',
228
+ hover: 'var(--dsw-alias-interactive-bg-hover, rgba(128,128,128,0.18))',
229
+ accent: 'var(--dsw-alias-brand-primary, #2f81f7)',
230
+ };
231
+
232
+ const S = {
233
+ root: {
234
+ boxSizing: 'border-box', height: '100%', width: '100%',
235
+ display: 'flex', flexDirection: 'column',
236
+ background: C.base, color: C.text, fontSize: '13px',
237
+ },
238
+ toolbar: {
239
+ display: 'flex', alignItems: 'center', gap: '6px',
240
+ padding: '8px 10px', borderBottom: '1px solid ' + C.border, flex: '0 0 auto',
241
+ },
242
+ btn: {
243
+ padding: '5px 10px', borderRadius: '6px', border: '1px solid ' + C.border,
244
+ background: C.raised, color: C.text, fontSize: '12px', cursor: 'pointer', whiteSpace: 'nowrap',
245
+ },
246
+ toggleOn: {
247
+ padding: '5px 12px', borderRadius: '6px', border: '1px solid ' + C.accent,
248
+ background: 'transparent', color: C.accent, fontSize: '12px', fontWeight: 600,
249
+ cursor: 'pointer', whiteSpace: 'nowrap',
250
+ },
251
+ toggleOff: {
252
+ padding: '5px 12px', borderRadius: '6px', border: '1px solid ' + C.border,
253
+ background: 'transparent', color: C.dim, fontSize: '12px',
254
+ cursor: 'pointer', whiteSpace: 'nowrap',
255
+ },
256
+ status: {
257
+ fontSize: '11px', color: C.dim,
258
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%',
259
+ },
260
+ floatOn: {
261
+ position: 'absolute', top: '52px', left: '10px', zIndex: 30,
262
+ padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.accent,
263
+ background: C.elevated, color: C.accent, fontSize: '11px', fontWeight: 600,
264
+ cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
265
+ },
266
+ floatOff: {
267
+ position: 'absolute', top: '52px', left: '10px', zIndex: 30,
268
+ padding: '5px 10px', borderRadius: '999px', border: '1px solid ' + C.border,
269
+ background: C.elevated, color: C.dim, fontSize: '11px', fontWeight: 600,
270
+ cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,0.35)',
271
+ },
272
+ moreBar: { position: 'relative', flex: '0 0 auto' },
273
+ moreMenu: {
274
+ position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '190px',
275
+ background: C.elevated, border: '1px solid ' + C.border, borderRadius: '6px',
276
+ zIndex: 80, padding: '4px', boxShadow: '0 10px 26px rgba(0,0,0,0.45)',
277
+ },
278
+ moreRow: {
279
+ padding: '5px 8px', borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
280
+ whiteSpace: 'nowrap', color: C.text,
281
+ },
282
+ helpOverlay: {
283
+ position: 'absolute', inset: '0', background: 'rgba(0,0,0,0.45)', zIndex: 90,
284
+ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '12px',
285
+ },
286
+ helpCard: {
287
+ width: '100%', maxWidth: '420px', maxHeight: '100%', overflow: 'auto',
288
+ background: C.elevated, border: '1px solid ' + C.border, borderRadius: '8px',
289
+ boxShadow: '0 16px 40px rgba(0,0,0,0.5)', padding: '12px',
290
+ },
291
+ helpHead: { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' },
292
+ helpTitle: { flex: '1 1 auto', fontSize: '13px', fontWeight: 600, color: C.text },
293
+ helpBody: { fontSize: '11px', lineHeight: '17px', color: C.dim },
294
+ helpLine: { whiteSpace: 'pre-wrap' },
295
+ presetBar: {
296
+ marginLeft: 'auto', display: 'flex', flexDirection: 'column', alignItems: 'flex-end',
297
+ gap: '3px', position: 'relative', flex: '0 0 auto',
298
+ },
299
+ presetRowTop: { display: 'flex', alignItems: 'center', gap: '5px' },
300
+ presetMenu: {
301
+ position: 'absolute', right: 0, top: '100%', marginTop: '4px', minWidth: '190px',
302
+ maxHeight: '260px', overflowY: 'auto', background: C.elevated,
303
+ border: '1px solid ' + C.border, borderRadius: '6px', zIndex: 60, padding: '4px',
304
+ boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
305
+ },
306
+ presetRow: {
307
+ display: 'flex', alignItems: 'center', gap: '6px', padding: '5px 6px',
308
+ borderRadius: '4px', fontSize: '11px', cursor: 'pointer',
309
+ },
310
+ presetRowText: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
311
+ presetDel: {
312
+ flex: '0 0 auto', padding: '0 4px', borderRadius: '3px', border: 'none',
313
+ background: 'transparent', color: '#e5534b', fontSize: '11px', cursor: 'pointer',
314
+ },
315
+ presetInput: {
316
+ width: '92px', padding: '3px 6px', borderRadius: '5px', border: '1px solid ' + C.border,
317
+ background: C.base, color: C.text, fontSize: '11px', outline: 'none', userSelect: 'text',
318
+ },
319
+ presetEmpty: { padding: '6px', fontSize: '10px', color: C.dim },
320
+ syncNote: { fontSize: '10px', color: C.dim, maxWidth: '140px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
321
+ canvas: { position: 'relative', flex: '1 1 auto', overflow: 'auto', minHeight: '0', userSelect: 'none' },
322
+ content: { position: 'relative', width: CONTENT_W, height: CONTENT_H },
323
+
324
+ node: {
325
+ position: 'absolute', width: NODE_W, height: NODE_H, boxSizing: 'border-box',
326
+ borderRadius: '10px', border: '1px solid ' + C.border,
327
+ background: C.raised, color: C.text, cursor: 'grab',
328
+ boxShadow: '0 1px 4px rgba(0,0,0,0.3)',
329
+ },
330
+ nodeSel: { border: '2px solid ' + C.accent },
331
+ leadNode: {},
332
+ orphanNode: { border: '1px dashed ' + C.dim, opacity: 0.65 },
333
+
334
+ title: {
335
+ position: 'absolute', left: '10px', right: '10px', top: '10px', height: '18px',
336
+ fontWeight: 600, fontSize: '13px', lineHeight: '18px',
337
+ border: 'none', background: 'transparent', color: C.text, padding: 0, margin: 0,
338
+ outline: 'none', boxSizing: 'border-box', userSelect: 'text',
339
+ },
340
+ titleReadonly: {
341
+ position: 'absolute', left: '10px', right: '10px', top: '10px', height: '18px',
342
+ fontWeight: 600, fontSize: '13px', lineHeight: '18px',
343
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
344
+ },
345
+ topBar: {
346
+ position: 'absolute', left: 0, right: 0, top: 0, height: '4px',
347
+ borderRadius: '10px 10px 0 0', zIndex: 2, pointerEvents: 'none',
348
+ },
349
+ statusChip: {
350
+ position: 'absolute', right: '10px', bottom: '3px', fontSize: '9px', lineHeight: '14px',
351
+ color: C.dim, pointerEvents: 'none', zIndex: 3, whiteSpace: 'nowrap',
352
+ },
353
+
354
+ fieldModel: { position: 'absolute', left: '10px', right: '10px', top: '28px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
355
+ fieldReason: { position: 'absolute', left: '10px', right: '10px', top: '50px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
356
+ fieldScope: { position: 'absolute', left: '10px', right: '10px', top: '72px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
357
+ fieldFallback: { position: 'absolute', left: '10px', right: '10px', top: '94px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
358
+ fieldMemory: { position: 'absolute', left: '10px', right: '10px', top: '116px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
359
+ fieldRole: { position: 'absolute', left: '10px', right: '10px', top: '138px', height: '22px', display: 'flex', alignItems: 'center', gap: '6px' },
360
+ fieldRoleTop: { position: 'absolute', left: '10px', right: '10px', top: '34px', height: '24px', display: 'flex', alignItems: 'center', gap: '6px' },
361
+ optRow: {
362
+ position: 'absolute', left: '10px', right: '10px', top: '114px', height: '18px',
363
+ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '9px', color: C.dim,
364
+ overflow: 'hidden',
365
+ },
366
+
367
+ toggleSwitch: {
368
+ flex: '1 1 auto', width: '100%', height: '18px', boxSizing: 'border-box', padding: '0 5px', borderRadius: '4px',
369
+ border: '1px solid ' + C.border, background: C.base, color: C.text,
370
+ fontSize: '10px', cursor: 'pointer', outline: 'none', textAlign: 'center', lineHeight: '14px',
371
+ },
372
+ toggleSwitchOn: {
373
+ flex: '1 1 auto', width: '100%', height: '18px', boxSizing: 'border-box', padding: '0 5px', borderRadius: '4px',
374
+ border: '1px solid ' + C.accent, background: C.base, color: C.accent,
375
+ fontSize: '10px', cursor: 'pointer', outline: 'none', textAlign: 'center', lineHeight: '14px',
376
+ },
377
+ optChip: {
378
+ flex: '0 0 auto', padding: '2px 6px', borderRadius: '4px',
379
+ border: '1px solid ' + C.border, background: 'transparent', color: C.dim,
380
+ fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '12px',
381
+ outline: 'none',
382
+ },
383
+ optChipOn: {
384
+ flex: '0 0 auto', padding: '2px 6px', borderRadius: '4px',
385
+ border: '1px solid ' + C.accent, background: C.hover, color: C.accent,
386
+ fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap', lineHeight: '12px',
387
+ outline: 'none',
388
+ },
389
+ fieldLabel: { flex: '0 0 30px', width: '30px', fontSize: '9px', color: C.dim },
390
+
391
+ input: {
392
+ flex: '1 1 auto', minWidth: '0', padding: '3px 6px', borderRadius: '5px',
393
+ border: '1px solid ' + C.border, background: C.base, color: C.text, fontSize: '12px',
394
+ outline: 'none', userSelect: 'text',
395
+ },
396
+ rolePopover: {
397
+ position: 'absolute', left: '100%', top: '0', marginLeft: '8px', width: '230px',
398
+ background: C.elevated, border: '1px solid ' + C.border, borderRadius: '8px',
399
+ boxShadow: '0 10px 26px rgba(0,0,0,0.45)', padding: '8px', zIndex: 70,
400
+ },
401
+ roleArea: {
402
+ width: '100%', height: '96px', boxSizing: 'border-box', resize: 'none',
403
+ background: C.base, color: C.text, fontSize: '11px', lineHeight: '15px',
404
+ border: '1px solid ' + C.border, borderRadius: '5px', padding: '5px 6px',
405
+ outline: 'none', userSelect: 'text',
406
+ },
407
+ leadLabel: { position: 'absolute', left: '10px', right: '10px', top: '26px', height: '16px', display: 'flex', alignItems: 'center' },
408
+ task: {
409
+ position: 'absolute', left: '10px', right: '10px', top: '44px', height: '118px',
410
+ padding: '4px 6px', borderRadius: '5px', border: '1px solid ' + C.border,
411
+ background: C.base, color: C.text, fontSize: '11px', resize: 'none', outline: 'none',
412
+ lineHeight: '14px', boxSizing: 'border-box', userSelect: 'text',
413
+ },
414
+
415
+ selectBtn: {
416
+ flex: '1 1 auto', minWidth: '0', width: '100%', height: '18px', boxSizing: 'border-box',
417
+ display: 'flex', alignItems: 'center', gap: '4px',
418
+ padding: '0 5px', borderRadius: '4px', border: '1px solid ' + C.border,
419
+ background: C.base, color: C.text, fontSize: '10px', cursor: 'pointer', textAlign: 'left',
420
+ lineHeight: '14px',
421
+ },
422
+ reasonChip: {
423
+ flex: '0 0 auto', maxWidth: '44px', padding: '3px 4px', borderRadius: '5px',
424
+ border: '1px solid ' + C.border, background: 'transparent', color: C.dim,
425
+ fontSize: '9px', cursor: 'pointer', whiteSpace: 'nowrap',
426
+ overflow: 'hidden', textOverflow: 'ellipsis',
427
+ },
428
+ selectText: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
429
+ caret: { flex: '0 0 auto', color: C.dim, fontSize: '9px' },
430
+ menu: {
431
+ position: 'absolute', left: 0, right: 0, top: '100%', marginTop: '4px',
432
+ maxHeight: '220px', overflowY: 'auto', background: C.elevated,
433
+ border: '1px solid ' + C.border, borderRadius: '6px',
434
+ boxShadow: '0 8px 24px rgba(0,0,0,0.4)', zIndex: 50, padding: '4px',
435
+ },
436
+ menuRow: {
437
+ padding: '3px 7px', borderRadius: '4px', fontSize: '10px', cursor: 'pointer',
438
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
439
+ },
440
+ menuHead: { padding: '6px 8px 2px', fontSize: '10px', color: C.dim, textTransform: 'uppercase', letterSpacing: '0.04em' },
441
+
442
+ band: { position: 'absolute', left: 0, right: 0, top: SOCKET_BAND_TOP + 'px' },
443
+ row: { position: 'relative', height: ROW_H + 'px', display: 'flex', alignItems: 'center', justifyContent: 'center' },
444
+ rowLabel: { fontSize: '9px', color: C.dim, letterSpacing: '0.02em' },
445
+ socket: {
446
+ position: 'absolute', top: (ROW_H - PORT) / 2, width: PORT, height: PORT,
447
+ borderRadius: '50%', background: C.raised, border: '2px solid ' + C.border,
448
+ boxSizing: 'border-box', cursor: 'crosshair', zIndex: 6,
449
+ /* a little extra grab area without changing the drawn dot */
450
+ padding: 0, margin: -3, boxShadow: '0 0 0 3px transparent',
451
+ },
452
+ nodeDelete: {
453
+ position: 'absolute', right: '-8px', top: '-8px', width: '18px', height: '18px',
454
+ borderRadius: '50%', background: C.elevated, border: '1px solid ' + C.border,
455
+ color: '#e5534b', fontSize: '12px', lineHeight: '16px', textAlign: 'center',
456
+ cursor: 'pointer', zIndex: 8, userSelect: 'none',
457
+ },
458
+ runsBadge: {
459
+ position: 'absolute', right: '10px', bottom: '2px', fontSize: '9px',
460
+ color: C.accent, cursor: 'pointer', userSelect: 'none', zIndex: 4,
461
+ },
462
+ statusBar: {
463
+ position: 'absolute', left: '2px', top: '10px', bottom: '10px', width: '3px',
464
+ borderRadius: '2px', zIndex: 3,
465
+ },
466
+ };
467
+
468
+ let hostCtx = null;
469
+
470
+ function socketCenterY(i) {
471
+ return SOCKET_BAND_TOP + i * ROW_H + ROW_H / 2;
472
+ }
473
+
474
+ function defaultNodes() {
475
+ return [
476
+ { id: 'lead', kind: 'lead', x: 30, y: 30, label: 'Lead', task: '', provider: '', model: '', role: '' },
477
+ { id: 'n1', kind: 'agent', x: 40, y: 230, label: 'Classifier', provider: '', model: 'deepseek-v4-flash', role: '把请求分类' },
478
+ { id: 'n2', kind: 'agent', x: 340, y: 420, label: 'Executor', provider: '', model: 'deepseek-v4-pro', role: '执行方案' },
479
+ ];
480
+ }
481
+
482
+ function defaultEdges() {
483
+ return [
484
+ { id: 'e-lead-n1', from: 'lead', to: 'n1', type: 'prompt' },
485
+ { id: 'e-n1-n2', from: 'n1', to: 'n2', type: 'prompt' },
486
+ ];
487
+ }
488
+
489
+ /**
490
+ * Older docs used an `output` node as the exit. Its meaning is now "another
491
+ * lead step", so migrate the kind instead of dropping the user's graph.
492
+ */
493
+ function ensureEntry(doc) {
494
+ if (!doc || !Array.isArray(doc.nodes)) return doc;
495
+ for (const n of doc.nodes) {
496
+ if (!n) continue;
497
+ if (n.kind === 'output') {
498
+ n.kind = 'lead';
499
+ if (!n.label || n.label === '输出') n.label = 'Lead';
500
+ } else if (!n.kind) {
501
+ n.kind = n.id === 'lead' ? 'lead' : 'agent';
502
+ }
503
+ }
504
+ if (!doc.nodes.some((n) => n && n.id === 'lead')) {
505
+ doc.nodes.unshift({ id: 'lead', kind: 'lead', x: 30, y: 30, label: 'Lead', task: '', provider: '', model: '', role: '' });
506
+ }
507
+ for (const n of doc.nodes) {
508
+ if (n && n.id === 'lead') n.kind = 'lead';
509
+ }
510
+ return doc;
511
+ }
512
+
513
+ /** Control points of one link, in canvas coordinates. */
514
+ function edgeCurve(from, to, type) {
515
+ const idx = Math.max(0, SOCKET_TYPES.findIndex((t) => t.id === type));
516
+ const y = socketCenterY(idx);
517
+ const x1 = from.x + WORLD_PAD + NODE_W, y1 = from.y + WORLD_PAD + y;
518
+ const x2 = to.x + WORLD_PAD, y2 = to.y + WORLD_PAD + y;
519
+ const dx = Math.max(40, Math.abs(x2 - x1) * 0.5);
520
+ return { x1, y1, c1x: x1 + dx, c1y: y1, c2x: x2 - dx, c2y: y2, x2, y2 };
521
+ }
522
+
523
+ function edgePath(from, to, type) {
524
+ const c = edgeCurve(from, to, type);
525
+ return 'M ' + c.x1 + ' ' + c.y1 + ' C ' + c.c1x + ' ' + c.c1y + ', ' + c.c2x + ' ' + c.c2y + ', ' + c.x2 + ' ' + c.y2;
526
+ }
527
+
528
+ /** Shortest distance between a point and one link, sampled along the curve. */
529
+ function distanceToEdge(point, from, to, type) {
530
+ const c = edgeCurve(from, to, type);
531
+ let best = Infinity;
532
+ let prevX = c.x1;
533
+ let prevY = c.y1;
534
+ for (let i = 1; i <= 18; i += 1) {
535
+ const t = i / 18;
536
+ const u = 1 - t;
537
+ const bx = u * u * u * c.x1 + 3 * u * u * t * c.c1x + 3 * u * t * t * c.c2x + t * t * t * c.x2;
538
+ const by = u * u * u * c.y1 + 3 * u * u * t * c.c1y + 3 * u * t * t * c.c2y + t * t * t * c.y2;
539
+ best = Math.min(best, distanceToSegment(point, prevX, prevY, bx, by));
540
+ prevX = bx;
541
+ prevY = by;
542
+ }
543
+ return best;
544
+ }
545
+
546
+ function distanceToSegment(p, ax, ay, bx, by) {
547
+ const vx = bx - ax;
548
+ const vy = by - ay;
549
+ const len = vx * vx + vy * vy;
550
+ const t = len === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - ax) * vx + (p.y - ay) * vy) / len));
551
+ const dx = p.x - (ax + t * vx);
552
+ const dy = p.y - (ay + t * vy);
553
+ return Math.hypot(dx, dy);
554
+ }
555
+
556
+ function topoOrder(nodes, edges) {
557
+ const indeg = new Map(nodes.map((n) => [n.id, 0]));
558
+ const adj = new Map(nodes.map((n) => [n.id, []]));
559
+ for (const e of edges) {
560
+ if (!indeg.has(e.from) || !indeg.has(e.to)) continue;
561
+ indeg.set(e.to, indeg.get(e.to) + 1);
562
+ adj.get(e.from).push(e.to);
563
+ }
564
+ const queue = nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id);
565
+ const out = [];
566
+ while (queue.length) {
567
+ const id = queue.shift();
568
+ out.push(id);
569
+ for (const next of adj.get(id)) {
570
+ indeg.set(next, indeg.get(next) - 1);
571
+ if (indeg.get(next) === 0) queue.push(next);
572
+ }
573
+ }
574
+ return out.length === nodes.length ? out : null;
575
+ }
576
+
577
+ function varOf(id) {
578
+ return 'n_' + String(id).replace(/[^a-zA-Z0-9_]/g, '_');
579
+ }
580
+
581
+ function buildWorkflowScript(nodes, edges) {
582
+ const entry = nodes.find((n) => n.id === 'lead');
583
+ if (!entry) return { error: '缺少入口 Lead 节点' };
584
+ const rest = nodes.filter((n) => n.id !== 'lead');
585
+ if (!rest.length) return { error: '画布上还没有可执行的节点' };
586
+ const task = String(entry.task || '').trim();
587
+ if (!task) return { error: '请先在 Lead 节点填写「本次任务」' };
588
+
589
+ const byIdAll = new Map(rest.map((n) => [n.id, n]));
590
+
591
+ const reachable = new Set([entry.id]);
592
+ let grew = true;
593
+ while (grew) {
594
+ grew = false;
595
+ for (const e of edges) {
596
+ if (reachable.has(e.from) && !reachable.has(e.to)) { reachable.add(e.to); grew = true; }
597
+ }
598
+ }
599
+ const orphan = rest.filter((n) => !reachable.has(n.id));
600
+ if (orphan.length) {
601
+ return { error: '这些节点没有从入口 Lead 连过来:' + orphan.map((n) => n.label).join('、') };
602
+ }
603
+
604
+ const dataEdgesAll = edges.filter((e) => e.from !== entry.id && byIdAll.has(e.from) && byIdAll.has(e.to));
605
+
606
+ // Lead-kind nodes are executed by the conversation itself, which can only
607
+ // happen after the script returns — so they must be terminal.
608
+ const leadNodes = rest.filter((n) => n.kind === 'lead');
609
+ for (const ln of leadNodes) {
610
+ if (dataEdgesAll.some((e) => e.from === ln.id)) {
611
+ return {
612
+ error: '中间 Lead 节点暂不支持(「' + ln.label + '」后面还有步骤)。'
613
+ + '把中间这一步换成子代理,或把它移到流程末尾。',
614
+ };
615
+ }
616
+ }
617
+
618
+ const agentNodes = rest.filter((n) => n.kind !== 'lead');
619
+ if (!agentNodes.length) return { error: '需要至少一个子代理节点来执行' };
620
+
621
+ const byId = new Map(agentNodes.map((n) => [n.id, n]));
622
+ const dataEdges = dataEdgesAll.filter((e) => byId.has(e.from) && byId.has(e.to));
623
+ const order = topoOrder(agentNodes, dataEdges);
624
+ if (!order) return { error: '存在环,无法生成有向无环图的脚本' };
625
+
626
+ const upstream = new Map(agentNodes.map((n) => [n.id, []]));
627
+ for (const e of dataEdges) upstream.get(e.to).push(e);
628
+ const hasDownstream = new Set(dataEdges.map((e) => e.from));
629
+
630
+ // Hand back everything a lead step consumes, plus every terminal agent.
631
+ const delivered = [];
632
+ const deliver = (id) => { if (byId.has(id) && !delivered.includes(id)) delivered.push(id); };
633
+ for (const ln of leadNodes) {
634
+ for (const e of dataEdgesAll) if (e.to === ln.id) deliver(e.from);
635
+ }
636
+ for (const n of agentNodes) if (!hasDownstream.has(n.id)) deliver(n.id);
637
+
638
+ const lines = [];
639
+ lines.push('// meta: ' + JSON.stringify({ name: 'workflow-canvas', description: 'Canvas-generated agent DAG', phases: [{ title: 'run' }] }));
640
+ for (const id of order) {
641
+ const node = byId.get(id);
642
+ const ups = upstream.get(id);
643
+ const isRoot = ups.length === 0;
644
+ const upsLabels = ups.map((e) => (byId.get(e.from) || {}).label).filter(Boolean);
645
+ const downs = dataEdgesAll.filter((e) => e.from === id).map((e) => (byIdAll.get(e.to) || {}).label).filter(Boolean);
646
+ const head = [];
647
+ head.push('【工作流节点】你在一个多步工作流里负责「' + node.label + '」这一步(子代理)。');
648
+ if (isRoot) head.push('【总任务】' + task);
649
+ head.push('【职责】' + (node.role || node.label || id));
650
+ if (upsLabels.length) head.push('【上游】' + upsLabels.join('、') + ' 已交付结果给你(见下文)。');
651
+ head.push('【下游】' + (downs.length ? downs.join('、') + ' 会使用你的输出。' : '你是终点,结果会直接交付给用户。'));
652
+ head.push('【要求】只完成你这一步;输出要能被下游直接使用,不要重复上游已完成的工作。');
653
+ const pieces = [JSON.stringify(head.join('\n') + '\n')];
654
+ for (const e of ups) {
655
+ const from = byId.get(e.from);
656
+ pieces.push(JSON.stringify('\n## 来自【' + from.label + '】(' + (e.type || 'prompt') + ')\n'));
657
+ pieces.push(varOf(e.from));
658
+ }
659
+ // The label carries the canvas node id so the client can match the
660
+ // spawned subagent session back to its node through the catalog.
661
+ const opts = ["label: " + JSON.stringify((node.label || id) + '#' + id), "phase: 'run'"];
662
+ if (node.provider) opts.push('provider: ' + JSON.stringify(node.provider));
663
+ if (node.model) opts.push('model: ' + JSON.stringify(node.model));
664
+ lines.push('const ' + varOf(id) + ' = await agent(' + pieces.join(' + ') + ', { ' + opts.join(', ') + ' });');
665
+ }
666
+ lines.push('// 交付给 Lead:' + delivered.map((id) => byId.get(id).label).join('、'));
667
+ const rets = delivered.map((id) => JSON.stringify(byId.get(id).label) + ': ' + varOf(id));
668
+ lines.push('return { ' + rets.join(', ') + ' };');
669
+
670
+ // These run in the conversation after the script returns.
671
+ const leadSteps = leadNodes.map((ln) => ({
672
+ label: ln.label,
673
+ role: ln.role || ln.label,
674
+ needs: dataEdgesAll.filter((e) => e.to === ln.id).map((e) => (byIdAll.get(e.from) || {}).label).filter(Boolean),
675
+ }));
676
+
677
+ return { script: lines.join('\n'), leadSteps };
678
+ }
679
+
680
+ /** Ids reachable from the entry Lead; every other node is skipped at run time. */
681
+ function reachableFrom(nodes, edges) {
682
+ const set = new Set(['lead']);
683
+ let grew = true;
684
+ while (grew) {
685
+ grew = false;
686
+ for (const e of edges) {
687
+ if (set.has(e.from) && !set.has(e.to)) { set.add(e.to); grew = true; }
688
+ }
689
+ }
690
+ return set;
691
+ }
692
+
693
+ /** Everything the Host executor needs; no prompts are pre-rendered here. */
694
+ function buildPlan(nodes, edges) {
695
+ const entry = nodes.find((n) => n.id === 'lead');
696
+ if (!entry) return { error: '缺少入口 Lead 节点' };
697
+ const task = String(entry.task || '').trim();
698
+ if (!task) return { error: '请先在 Lead 节点填写「本次任务」' };
699
+ const rest = nodes.filter((n) => n.id !== 'lead');
700
+ if (!rest.length) return { error: '画布上还没有可执行的节点' };
701
+ // Nodes the entry Lead cannot reach are skipped rather than refused; the
702
+ // canvas marks them so the user can see what will not run.
703
+ const reachableIds = reachableFrom(nodes, edges);
704
+
705
+ const ids = new Set(rest.map((n) => n.id));
706
+ const planEdges = edges
707
+ .filter((e) => (e.from === 'lead' || ids.has(e.from)) && ids.has(e.to))
708
+ .map((e) => ({ from: e.from, to: e.to, type: e.type || 'prompt' }));
709
+
710
+ // Unconnected nodes are left out of the plan instead of blocking the run.
711
+ const skipped = rest.filter((n) => !reachableIds.has(n.id));
712
+ const active = rest.filter((n) => reachableIds.has(n.id));
713
+ if (!active.length) {
714
+ return { error: '没有从入口 Lead 连通的节点,无法执行' };
715
+ }
716
+
717
+ return {
718
+ plan: {
719
+ task,
720
+ skipped: skipped.map((n) => n.label || n.id),
721
+ nodes: active.map((n) => ({
722
+ id: n.id,
723
+ kind: n.kind === 'lead' ? 'lead' : 'agent',
724
+ label: n.label || n.id,
725
+ role: n.role || '',
726
+ provider: n.provider || '',
727
+ model: n.model || '',
728
+ reasoning: n.reasoning || '',
729
+ preset: n.preset === 'minimal' ? 'minimal' : 'standard',
730
+ keepSession: Boolean(n.keepSession),
731
+ // A structured link is the only thing that decides this: no separate switch.
732
+ structured: planEdges.some((e) => e.from === n.id && e.type === 'structured'),
733
+ fallbackModel: n.fallbackModel || '',
734
+ fallbackProvider: n.fallbackProvider || '',
735
+ })),
736
+ edges: planEdges,
737
+ },
738
+ };
739
+ }
740
+
741
+ function loadCutMode() {
742
+ try {
743
+ return window.localStorage.getItem(STORAGE_PREFIX + 'cut') !== 'off';
744
+ } catch (_e) {
745
+ return true;
746
+ }
747
+ }
748
+
749
+ function saveCutMode(on) {
750
+ try {
751
+ window.localStorage.setItem(STORAGE_PREFIX + 'cut', on ? 'on' : 'off');
752
+ } catch (_e) { /* ignore */ }
753
+ }
754
+
755
+ function loadPresets() {
756
+ try {
757
+ const raw = window.localStorage.getItem(PRESET_KEY);
758
+ if (!raw) return {};
759
+ const doc = JSON.parse(raw);
760
+ return doc && typeof doc === 'object' && !Array.isArray(doc) ? doc : {};
761
+ } catch (_e) {
762
+ return {};
763
+ }
764
+ }
765
+
766
+ function savePresets(presets) {
767
+ try {
768
+ window.localStorage.setItem(PRESET_KEY, JSON.stringify(presets));
769
+ return true;
770
+ } catch (_e) {
771
+ return false;
772
+ }
773
+ }
774
+
775
+ function storageKey(sessionId) { return STORAGE_PREFIX + (sessionId || '__global__');
776
+ }
777
+
778
+ function loadDoc(sessionId) {
779
+ try {
780
+ const raw = window.localStorage.getItem(storageKey(sessionId));
781
+ if (!raw) return null;
782
+ const doc = JSON.parse(raw);
783
+ if (!doc || !Array.isArray(doc.nodes) || !Array.isArray(doc.edges)) return null;
784
+ return ensureEntry(doc);
785
+ } catch (_e) {
786
+ return null;
787
+ }
788
+ }
789
+
790
+ function saveDoc(sessionId, doc, stamp) {
791
+ try {
792
+ /** Stamp every local edit so a stale generated canvas cannot overwrite it. */
793
+ const stamped = { ...doc, at: typeof stamp === 'number' ? stamp : Date.now() };
794
+ window.localStorage.setItem(storageKey(sessionId), JSON.stringify(stamped));
795
+ } catch (_e) {
796
+ /* storage unavailable */
797
+ }
798
+ }
799
+
800
+ function sessionFace(sessionId) {
801
+ try {
802
+ const sessions = hostCtx && hostCtx.sessions;
803
+ if (!sessions || typeof sessions.binding !== 'function' || !sessionId) return undefined;
804
+ const binding = sessions.binding(sessionId);
805
+ return binding && binding.session;
806
+ } catch (_e) {
807
+ return undefined;
808
+ }
809
+ }
810
+
811
+ /**
812
+ * Keeps a rendering failure visible: without this the whole tab renders as
813
+ * an empty box and the reason is lost.
814
+ */
815
+ class CanvasBoundary extends Component {
816
+ constructor(props) {
817
+ super(props);
818
+ this.state = { error: null };
819
+ }
820
+
821
+ static getDerivedStateFromError(error) {
822
+ return { error };
823
+ }
824
+
825
+ componentDidCatch(error, info) {
826
+ try {
827
+ console.error('[workflow-canvas] render failed', error, info);
828
+ } catch (_e) { /* ignore */ }
829
+ }
830
+
831
+ render() {
832
+ const error = this.state.error;
833
+ if (!error) return this.props.children;
834
+ const message = String((error && error.message) || error);
835
+ const stack = String((error && error.stack) || '').slice(0, 900);
836
+ return h('div', {
837
+ style: {
838
+ padding: '12px', fontFamily: 'ui-monospace, monospace', fontSize: '11px',
839
+ color: '#e5534b', whiteSpace: 'pre-wrap', overflow: 'auto', height: '100%',
840
+ },
841
+ }, '画布渲染出错:\n' + message + '\n\n' + stack);
842
+ }
843
+ }
844
+
845
+ function WorkflowCanvas(props) {
846
+ const sessionId = props && props.sessionId;
847
+ const stored = useRef(loadDoc(sessionId));
848
+ const initial = stored.current;
849
+
850
+ const [nodes, setNodes] = useState(() => (initial ? initial.nodes : defaultNodes()));
851
+ const [edges, setEdges] = useState(() => (initial ? initial.edges : defaultEdges()));
852
+ const [selectedIds, setSelectedIds] = useState([]);
853
+ const [marquee, setMarquee] = useState(null);
854
+ const [dragging, setDragging] = useState(false);
855
+ const [syncNote, setSyncNote] = useState('');
856
+ const [roleEditFor, setRoleEditFor] = useState(null);
857
+ const [menuOpen, setMenuOpen] = useState(false);
858
+ const [helpOpen, setHelpOpen] = useState(false);
859
+ const [cutMode, setCutMode] = useState(loadCutMode);
860
+ const cutRef = useRef(null);
861
+ /** Timestamp of the remote document being applied, so saving it does not bump the clock. */
862
+ const applyStamp = useRef(null);
863
+ const [cutPath, setCutPath] = useState([]);
864
+ const [cutVictims, setCutVictims] = useState([]);
865
+ const cutHits = useRef(new Set());
866
+ const [pending, setPending] = useState(null);
867
+ const [status, setStatus] = useState('');
868
+ const [models, setModels] = useState([]);
869
+ const [openModelFor, setOpenModelFor] = useState(null);
870
+ const [enabled, setEnabled] = useState(() => Boolean(initial && initial.enabled));
871
+
872
+ const contentRef = useRef(null);
873
+ const canvasElRef = useRef(null);
874
+ const nodeDrag = useRef(null); const statusTimer = useRef(null);
875
+ const dropdownRef = useRef(null);
876
+ const syncTimer = useRef(null);
877
+ const lastSync = useRef('');
878
+ const historyRef = useRef([]);
879
+ const [dirty, setDirty] = useState(() => Boolean(initial && initial.enabled));
880
+ const [view, setView] = useState({ k: 1, x: 0, y: 0 });
881
+ const viewRef = useRef(view);
882
+ viewRef.current = view;
883
+ const [statusById, setStatusById] = useState({});
884
+ const [presets, setPresets] = useState(loadPresets);
885
+ const [presetOpen, setPresetOpen] = useState(null);
886
+ const [presetName, setPresetName] = useState('');
887
+ const [lang, setLang] = useState(loadLang);
888
+ const t = (key) => (I18N[lang] && I18N[lang][key]) || I18N.zh[key] || key;
889
+ const toggleLang = () => {
890
+ const next = lang === 'zh' ? 'en' : 'zh';
891
+ setLang(next);
892
+ try { window.localStorage.setItem(LANG_KEY, next); } catch (_e) { /* ignore */ }
893
+ };
894
+ const nodesRef = useRef(nodes);
895
+ nodesRef.current = nodes;
896
+
897
+ useEffect(() => {
898
+ const stamp = applyStamp.current;
899
+ applyStamp.current = null;
900
+ saveDoc(sessionId, { nodes, edges, enabled }, stamp === null ? undefined : stamp);
901
+ }, [sessionId, nodes, edges, enabled]);
902
+
903
+ // Any structural edit after enabling leaves the Host copy stale.
904
+ useEffect(() => {
905
+ if (enabled) setDirty(true);
906
+ }, [nodes, edges]);
907
+
908
+ // A disabled canvas shows no run status at all.
909
+ useEffect(() => {
910
+ if (!enabled) setStatusById({});
911
+ }, [enabled]);
912
+
913
+ useEffect(() => {
914
+ let alive = true;
915
+ const remote = hostCtx && hostCtx.remote && hostCtx.remote.session;
916
+ if (!remote || typeof remote.modelCatalog !== 'function') return undefined;
917
+ remote.modelCatalog().then((res) => {
918
+ if (!alive || !res || !res.ok) return;
919
+ const flat = [];
920
+ for (const group of (res.value && res.value.groups) || []) {
921
+ for (const model of group.models || []) {
922
+ flat.push({
923
+ provider: group.id,
924
+ providerName: group.name,
925
+ model: model.id,
926
+ modelName: model.name,
927
+ efforts: (model.reasoning && model.reasoning.efforts) || [],
928
+ defaultEffort: model.reasoning && model.reasoning.defaultEffort,
929
+ });
930
+ }
931
+ }
932
+ setModels(flat);
933
+ }).catch(() => {});
934
+ return () => { alive = false; };
935
+ }, []);
936
+
937
+ useEffect(() => {
938
+ if (!openModelFor) return undefined;
939
+ const onDown = (ev) => {
940
+ if (dropdownRef.current && !dropdownRef.current.contains(ev.target)) setOpenModelFor(null);
941
+ };
942
+ document.addEventListener('mousedown', onDown);
943
+ return () => document.removeEventListener('mousedown', onDown);
944
+ }, [openModelFor]);
945
+
946
+ // Publishing costs one visible command row in the conversation, so it only
947
+ // happens when the user enables the canvas or asks for it explicitly.
948
+ const pushPlan = (nextEnabled) => {
949
+ try {
950
+ const face = sessionFace(sessionId);
951
+ if (!face || typeof face.command !== 'function') { flash(t('syncFailed')); return; }
952
+ const res = buildPlan(nodes, edges);
953
+ const payload = res.error
954
+ ? { enabled: nextEnabled, error: res.error }
955
+ : { enabled: nextEnabled, plan: res.plan };
956
+ const sig = JSON.stringify(payload);
957
+ if (sig === lastSync.current) { flash(t('upToDate')); return; }
958
+ const line = '/canvas-sync ' + encodeURIComponent(sig);
959
+ face.command(line).then((ack) => {
960
+ if (ack && ack.ok) {
961
+ lastSync.current = sig;
962
+ setDirty(false);
963
+ setStatusById({});
964
+ flash(t('syncedToHost'));
965
+ } else {
966
+ flash(t('syncFailed'));
967
+ }
968
+ }, () => flash(t('syncFailed')));
969
+ } catch (_e) {
970
+ flash(t('syncFailed'));
971
+ }
972
+ };
973
+
974
+ // Sync the moment a user message starts a turn, so this turn's tool call
975
+ // already sees the latest canvas. Falls back to the turn end if the start
976
+ // edge was missed; `dirty` clears on success so only one fires.
977
+ const liveRef = useRef({ enabled, dirty, pushPlan });
978
+ liveRef.current = { enabled, dirty, pushPlan };
979
+
980
+ useEffect(() => {
981
+ const face = sessionFace(sessionId);
982
+ if (!face || typeof face.subscribe !== 'function' || typeof face.getSnapshot !== 'function') return undefined;
983
+ let wasRunning = false;
984
+ try { wasRunning = Boolean(face.getSnapshot().running); } catch (_e) { wasRunning = false; }
985
+ const onSnapshot = () => {
986
+ let running = false;
987
+ try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
988
+ if (running !== wasRunning) {
989
+ const live = liveRef.current;
990
+ if (live.enabled && live.dirty) live.pushPlan(true);
991
+ }
992
+ wasRunning = running;
993
+ };
994
+ let unsub;
995
+ try { unsub = face.subscribe(onSnapshot); } catch (_e) { unsub = undefined; }
996
+ return () => {
997
+ if (typeof unsub === 'function') { try { unsub(); } catch (_e) { /* ignore */ } }
998
+ };
999
+ }, [sessionId]);
1000
+
1001
+ const flash = (msg) => {
1002
+ setStatus(msg);
1003
+ if (statusTimer.current) clearTimeout(statusTimer.current);
1004
+ statusTimer.current = setTimeout(() => setStatus(''), 3200);
1005
+ };
1006
+
1007
+ // Live node status for subagent nodes only: the catalog lists children by
1008
+ // `label#nodeId`. Lead steps run inside the conversation, so the canvas
1009
+ // cannot observe them and must not pretend to.
1010
+ useEffect(() => {
1011
+ const sessions = hostCtx && hostCtx.sessions;
1012
+ const face = sessionFace(sessionId);
1013
+ if (!sessions || !sessionId || !face || typeof face.subscribe !== 'function') return undefined;
1014
+ let timer = null;
1015
+ const read = () => {
1016
+ try {
1017
+ const state = sessions.list.getSnapshot();
1018
+ const proj = state && state.projectionsBySession && state.projectionsBySession[sessionId];
1019
+ const catalog = proj && proj.values && proj.values.subagentCatalog;
1020
+ if (!Array.isArray(catalog)) return;
1021
+ const known = new Set(nodesRef.current.map((n) => n.id));
1022
+ const next = {};
1023
+ for (const entry of catalog) {
1024
+ const m = NODE_MARK.exec(String(entry.label || ''));
1025
+ if (!m || !known.has(m[1])) continue;
1026
+ const child = state.byId && state.byId[entry.id];
1027
+ const timingProj = state.projectionsBySession && state.projectionsBySession[entry.id];
1028
+ const timing = timingProj && timingProj.values && timingProj.values.subagentTiming;
1029
+ if (child && child.running) next[m[1]] = 'running';
1030
+ else if (timing && timing.lastTurnCompleted === false) next[m[1]] = 'failed';
1031
+ else next[m[1]] = 'done';
1032
+ }
1033
+ setStatusById(next);
1034
+ } catch (_e) { /* ignore */ }
1035
+ };
1036
+ const stop = () => { if (timer) { clearInterval(timer); timer = null; } };
1037
+ let wasRunning = false;
1038
+ try { wasRunning = Boolean(face.getSnapshot().running); } catch (_e) { wasRunning = false; }
1039
+ if (wasRunning) { read(); timer = setInterval(read, 700); }
1040
+ const onSnapshot = () => {
1041
+ let running = false;
1042
+ try { running = Boolean(face.getSnapshot().running); } catch (_e) { running = false; }
1043
+ // A new turn means a new run: drop the previous run's statuses first.
1044
+ if (running && !wasRunning) setStatusById({});
1045
+ wasRunning = running;
1046
+ if (running && !timer) { read(); timer = setInterval(read, 700); }
1047
+ if (!running && timer) { stop(); read(); }
1048
+ };
1049
+ let unsub;
1050
+ try { unsub = face.subscribe(onSnapshot); } catch (_e) { unsub = undefined; }
1051
+ return () => {
1052
+ stop();
1053
+ if (typeof unsub === 'function') { try { unsub(); } catch (_e) { /* ignore */ } }
1054
+ };
1055
+ }, [sessionId]);
1056
+
1057
+ // Zoom with the wheel, anchored on the cursor: the content point under the
1058
+ // pointer stays under it while the scale changes.
1059
+ useEffect(() => {
1060
+ const el = canvasElRef.current;
1061
+ if (!el) return undefined;
1062
+ const onWheel = (e) => {
1063
+ e.preventDefault();
1064
+ const rect = el.getBoundingClientRect();
1065
+ const mx = e.clientX - rect.left;
1066
+ const my = e.clientY - rect.top;
1067
+ const cur = viewRef.current;
1068
+ const factor = e.deltaY < 0 ? 1.12 : 1 / 1.12;
1069
+ const k = Math.min(3, Math.max(0.2, cur.k * factor));
1070
+ if (k === cur.k) return;
1071
+ const lx = (mx - cur.x) / cur.k;
1072
+ const ly = (my - cur.y) / cur.k;
1073
+ setView({ k, x: mx - lx * k, y: my - ly * k });
1074
+ };
1075
+ el.addEventListener('wheel', onWheel, { passive: false });
1076
+ return () => el.removeEventListener('wheel', onWheel);
1077
+ }, []);
1078
+
1079
+ const pointTo = (e) => {
1080
+ const rect = contentRef.current.getBoundingClientRect();
1081
+ const k = viewRef.current.k || 1;
1082
+ return {
1083
+ x: (e.clientX - rect.left) / k - WORLD_PAD,
1084
+ y: (e.clientY - rect.top) / k - WORLD_PAD,
1085
+ };
1086
+ };
1087
+
1088
+ /** Put a world point at the middle of the visible canvas. */
1089
+ const centerOn = (wx, wy, nextK) => {
1090
+ const el = canvasElRef.current;
1091
+ if (!el) return;
1092
+ const k = nextK || viewRef.current.k || 1;
1093
+ const cw = el.clientWidth || 1;
1094
+ const chh = el.clientHeight || 1;
1095
+ setView({
1096
+ k,
1097
+ x: cw / 2 - (wx + WORLD_PAD) * k,
1098
+ y: chh / 2 - (wy + WORLD_PAD) * k,
1099
+ });
1100
+ el.scrollLeft = 0;
1101
+ el.scrollTop = 0;
1102
+ };
1103
+
1104
+ /** World coordinate currently sitting in the middle of the viewport. */
1105
+ const viewportCenterWorld = () => {
1106
+ const el = canvasElRef.current;
1107
+ const k = viewRef.current.k || 1;
1108
+ const cw = (el && el.clientWidth) || 800;
1109
+ const chh = (el && el.clientHeight) || 600;
1110
+ return {
1111
+ x: (cw / 2 - viewRef.current.x) / k - WORLD_PAD,
1112
+ y: (chh / 2 - viewRef.current.y) / k - WORLD_PAD,
1113
+ };
1114
+ };
1115
+
1116
+ const focusLead = () => {
1117
+ const lead = nodes.find((n) => n.id === 'lead');
1118
+ if (!lead) return;
1119
+ centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2);
1120
+ };
1121
+
1122
+ // The world origin is padded, so the initial viewport would otherwise show
1123
+ // empty space. Centre on the entry Lead the first time the pane mounts.
1124
+ const didCenter = useRef(false);
1125
+ useEffect(() => {
1126
+ if (didCenter.current) return;
1127
+ const lead = nodesRef.current.find((n) => n.id === 'lead');
1128
+ if (!lead) return;
1129
+ didCenter.current = true;
1130
+ const raf = typeof requestAnimationFrame === 'function'
1131
+ ? requestAnimationFrame(() => centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2))
1132
+ : setTimeout(() => centerOn(lead.x + NODE_W / 2, lead.y + NODE_H / 2), 0);
1133
+ return () => {
1134
+ if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(raf);
1135
+ else clearTimeout(raf);
1136
+ };
1137
+ }, []);
1138
+
1139
+ // Snapshot before every structural change so a mis-click can be undone.
1140
+ const pushSnapshot = () => {
1141
+ historyRef.current.push({ nodes, edges });
1142
+ if (historyRef.current.length > 50) historyRef.current.shift();
1143
+ };
1144
+
1145
+ const undo = () => {
1146
+ const prev = historyRef.current.pop();
1147
+ if (!prev) { flash(t('undoNone')); return; }
1148
+ setNodes(prev.nodes);
1149
+ setEdges(prev.edges);
1150
+ setSelectedIds([]);
1151
+ flash(t('undoDone'));
1152
+ };
1153
+
1154
+ const NODE_MARK = /#([A-Za-z0-9_]+)/;
1155
+
1156
+ /** Match this canvas's spawned subagent sessions back to their nodes. */
1157
+ const refreshRuns = async () => {
1158
+ try {
1159
+ const sessions = hostCtx && hostCtx.sessions;
1160
+ if (!sessions || !sessionId) { flash('没有会话上下文'); return; }
1161
+ try { await sessions.refreshProjections(sessionId); } catch (_e) { /* ignore */ }
1162
+ const state = sessions.list.getSnapshot();
1163
+ const proj = state && state.projectionsBySession && state.projectionsBySession[sessionId];
1164
+ const values = proj && (proj.values || (proj.state === 'ready' ? proj.values : undefined));
1165
+ const catalog = values && values.subagentCatalog;
1166
+ if (!Array.isArray(catalog)) {
1167
+ flash('读不到子代理目录(' + (proj ? '没有 subagentCatalog' : '没有该会话投影') + ')');
1168
+ return;
1169
+ }
1170
+ if (!catalog.length) { flash('子代理目录是空的(这次运行可能没产生子会话)'); return; }
1171
+ const known = new Set(nodes.map((n) => n.id));
1172
+ const byNode = new Map();
1173
+ const samples = [];
1174
+ for (const entry of catalog) {
1175
+ const label = String(entry.label || entry.name || entry.description || '');
1176
+ if (samples.length < 2) samples.push(label || '(无 label)');
1177
+ const m = NODE_MARK.exec(label);
1178
+ if (!m) continue;
1179
+ const nodeId = m[1];
1180
+ if (!known.has(nodeId)) continue;
1181
+ if (!byNode.has(nodeId)) byNode.set(nodeId, []);
1182
+ byNode.get(nodeId).push({ childId: entry.id, label, mode: entry.mode || 'continuable' });
1183
+ }
1184
+ if (!byNode.size) {
1185
+ flash('目录 ' + catalog.length + ' 项但没有带 #节点id 的,示例:' + samples.join(' / '));
1186
+ return;
1187
+ }
1188
+ setNodes((ns) => ns.map((n) => (byNode.has(n.id) ? { ...n, runs: byNode.get(n.id) } : n)));
1189
+ flash('已同步 ' + byNode.size + ' 个节点的运行记录');
1190
+ } catch (_e) {
1191
+ flash('同步运行记录失败:' + String((_e && _e.message) || _e));
1192
+ }
1193
+ };
1194
+
1195
+ const openRun = (node, run) => {
1196
+ try {
1197
+ const sr = hostCtx && hostCtx.sidebarRight;
1198
+ if (!sr || typeof sr.openResource !== 'function') { flash('无法打开会话'); return; }
1199
+ const addr = 'dsh-resource://subagentchat/session/' + encodeURIComponent(run.childId)
1200
+ + '?parent=' + encodeURIComponent(sessionId)
1201
+ + '&mode=' + encodeURIComponent(run.mode || 'continuable');
1202
+ sr.openResource(addr, { kind: 'subagentchat', preferNewPane: true });
1203
+ } catch (_e) {
1204
+ flash('打开会话失败');
1205
+ }
1206
+ };
1207
+
1208
+ const addNode = (kind) => {
1209
+ pushSnapshot();
1210
+ setNodes((ns) => {
1211
+ const i = ns.length;
1212
+ const center = viewportCenterWorld();
1213
+ return [...ns, {
1214
+ id: 'n' + Date.now().toString(36),
1215
+ kind: kind === 'lead' ? 'lead' : 'agent',
1216
+ // New nodes land near the middle of the viewport, nudged right.
1217
+ x: center.x + 40 + (ns.length % 3) * 30,
1218
+ y: center.y - NODE_H / 2 + (ns.length % 3) * 40,
1219
+ label: kind === 'lead' ? 'Lead 步骤 ' + i : 'Node ' + i,
1220
+ provider: '',
1221
+ model: '',
1222
+ role: '',
1223
+ }];
1224
+ });
1225
+ };
1226
+
1227
+ const updateNode = (id, patch) => {
1228
+ setNodes((ns) => ns.map((n) => (n.id === id ? { ...n, ...patch } : n)));
1229
+ };
1230
+
1231
+ const deleteNode = (id) => {
1232
+ if (id === 'lead') { flash(t('leadLocked')); return; }
1233
+ pushSnapshot();
1234
+ setNodes((ns) => ns.filter((n) => n.id !== id));
1235
+ setEdges((es) => es.filter((e) => e.from !== id && e.to !== id));
1236
+ setSelectedIds([]);
1237
+ flash(t('deletedNode'));
1238
+ };
1239
+
1240
+ /** Dragging any selected node moves the whole selection together. */
1241
+ const onNodeDown = (e, id) => {
1242
+ if (!contentRef.current) return;
1243
+ const node = nodes.find((n) => n.id === id);
1244
+ if (!node) return;
1245
+ const p = pointTo(e);
1246
+ const group = selectedIds.includes(id) ? selectedIds : [id];
1247
+ if (!selectedIds.includes(id)) setSelectedIds([id]);
1248
+ const origins = group
1249
+ .map((nid) => nodes.find((n) => n.id === nid))
1250
+ .filter(Boolean)
1251
+ .map((n) => ({ id: n.id, x: n.x, y: n.y }));
1252
+ nodeDrag.current = { origins, startX: p.x, startY: p.y, moved: false };
1253
+ setDragging(true);
1254
+ setOpenModelFor(null);
1255
+ e.preventDefault();
1256
+ e.stopPropagation();
1257
+ };
1258
+
1259
+ const onOutputDown = (e, id, type) => {
1260
+ const node = nodes.find((n) => n.id === id);
1261
+ if (!node) return;
1262
+ const idx = SOCKET_TYPES.findIndex((t) => t.id === type);
1263
+ const sx = node.x + NODE_W;
1264
+ const sy = node.y + socketCenterY(idx);
1265
+ setPending({ dir: 'out', fromId: id, type, sx, sy, x: sx, y: sy });
1266
+ setDragging(true);
1267
+ e.preventDefault();
1268
+ e.stopPropagation();
1269
+ };
1270
+
1271
+ /** Release over an output socket: completes a drag that started at an input. */
1272
+ const onOutputUp = (e, id, type) => {
1273
+ if (!pending || pending.dir !== 'in' || pending.type !== type) return;
1274
+ e.preventDefault();
1275
+ e.stopPropagation();
1276
+ const toId = pending.toId;
1277
+ if (toId && toId !== id) {
1278
+ pushSnapshot();
1279
+ setEdges((es) => {
1280
+ if (es.some((x) => x.from === id && x.to === toId && x.type === type)) return es;
1281
+ return [...es, { id: 'e' + Date.now().toString(36), from: id, to: toId, type }];
1282
+ });
1283
+ }
1284
+ setPending(null);
1285
+ setDragging(false);
1286
+ };
1287
+
1288
+ // Dragging a connected input detaches it; dragging a free input starts a
1289
+ // link that finishes on an output socket of the same type.
1290
+ const onInputDown = (e, id, type) => {
1291
+ e.preventDefault();
1292
+ e.stopPropagation();
1293
+ const link = edges.find((x) => x.to === id && x.type === type);
1294
+ const idx = SOCKET_TYPES.findIndex((t) => t.id === type);
1295
+ if (!link) {
1296
+ const node = nodes.find((n) => n.id === id);
1297
+ if (!node) return;
1298
+ const sx = node.x;
1299
+ const sy = node.y + socketCenterY(idx);
1300
+ setPending({ dir: 'in', toId: id, type, sx, sy, x: sx, y: sy });
1301
+ setDragging(true);
1302
+ return;
1303
+ }
1304
+ pushSnapshot();
1305
+ setEdges((es) => es.filter((x) => !(x.to === id && x.type === type)));
1306
+ const from = nodes.find((n) => n.id === link.from);
1307
+ if (!from) return;
1308
+ const sx = from.x + NODE_W;
1309
+ const sy = from.y + socketCenterY(idx);
1310
+ setPending({ dir: 'out', fromId: link.from, type, sx, sy, x: sx, y: sy });
1311
+ setDragging(true);
1312
+ };
1313
+
1314
+ const onInputUp = (e, id, type) => {
1315
+ if (!pending || pending.dir !== 'out' || pending.type !== type) return;
1316
+ e.preventDefault();
1317
+ e.stopPropagation();
1318
+ if (pending.fromId !== id) {
1319
+ const fromId = pending.fromId;
1320
+ pushSnapshot();
1321
+ setEdges((es) => {
1322
+ if (es.some((x) => x.from === fromId && x.to === id && x.type === type)) return es;
1323
+ return [...es, { id: 'e' + Date.now().toString(36), from: fromId, to: id, type }];
1324
+ });
1325
+ }
1326
+ setPending(null);
1327
+ setDragging(false);
1328
+ };
1329
+
1330
+ // Suppress the host context menu over the canvas while cutting is on.
1331
+ useEffect(() => {
1332
+ if (!cutMode) return undefined;
1333
+ const inside = (ev) => {
1334
+ const el = canvasElRef.current;
1335
+ return Boolean(el) && ev.target instanceof Node && el.contains(ev.target);
1336
+ };
1337
+ const onCtx = (ev) => { if (inside(ev)) ev.preventDefault(); };
1338
+ const onDown = (ev) => {
1339
+ if (ev.button !== 2 || !inside(ev) || ev.target.closest('[data-node]')) return;
1340
+ ev.preventDefault();
1341
+ const start = pointTo(ev);
1342
+ cutRef.current = start;
1343
+ setCutPath([start]);
1344
+ setDragging(true);
1345
+ };
1346
+ window.addEventListener('contextmenu', onCtx, true);
1347
+ window.addEventListener('mousedown', onDown, true);
1348
+ return () => {
1349
+ window.removeEventListener('contextmenu', onCtx, true);
1350
+ window.removeEventListener('mousedown', onDown, true);
1351
+ };
1352
+ }, [cutMode, sessionId]);
1353
+
1354
+ useEffect(() => {
1355
+ if (!dragging) return undefined;
1356
+ const move = (ev) => onCanvasMove(ev);
1357
+ const up = () => onCanvasUp();
1358
+ window.addEventListener('mousemove', move);
1359
+ window.addEventListener('mouseup', up);
1360
+ return () => {
1361
+ window.removeEventListener('mousemove', move);
1362
+ window.removeEventListener('mouseup', up);
1363
+ };
1364
+ }, [dragging, marquee, pending]);
1365
+
1366
+ const onCanvasDown = (e) => {
1367
+ if (e.button === 2) {
1368
+ if (!cutMode) return;
1369
+ e.preventDefault();
1370
+ try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
1371
+ const start = pointTo(e);
1372
+ cutRef.current = start;
1373
+ cutHits.current = new Set();
1374
+ setCutPath([start]);
1375
+ setCutVictims([]);
1376
+ setDragging(true);
1377
+ return;
1378
+ }
1379
+ if (e.button !== 0) return;
1380
+ if (roleEditFor) setRoleEditFor(null);
1381
+ if (menuOpen) setMenuOpen(false);
1382
+ e.preventDefault();
1383
+ try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
1384
+ const p = pointTo(e);
1385
+ setMarquee({ x1: p.x, y1: p.y, x2: p.x, y2: p.y });
1386
+ setDragging(true);
1387
+ if (selectedIds.length) setSelectedIds([]);
1388
+ setOpenModelFor(null);
1389
+ };
1390
+
1391
+ const onCanvasMove = (e) => {
1392
+ if (nodeDrag.current) {
1393
+ const p = pointTo(e);
1394
+ const drag = nodeDrag.current;
1395
+ const dx = p.x - drag.startX;
1396
+ const dy = p.y - drag.startY;
1397
+ if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) drag.moved = true;
1398
+ const byId = new Map(drag.origins.map((o) => [o.id, o]));
1399
+ setNodes((ns) => ns.map((n) => {
1400
+ const origin = byId.get(n.id);
1401
+ return origin ? { ...n, x: origin.x + dx, y: origin.y + dy } : n;
1402
+ }));
1403
+ } else if (cutRef.current) {
1404
+ const p = pointTo(e);
1405
+ const threshold = 12 / (viewRef.current.k || 1);
1406
+ const from = cutRef.current;
1407
+ const steps = Math.max(1, Math.ceil(Math.hypot(p.x - from.x, p.y - from.y) / 6));
1408
+ for (let step = 1; step <= steps; step += 1) {
1409
+ const t = step / steps;
1410
+ const canvasSpot = {
1411
+ x: from.x + (p.x - from.x) * t + WORLD_PAD,
1412
+ y: from.y + (p.y - from.y) * t + WORLD_PAD,
1413
+ };
1414
+ for (const edge of edges) {
1415
+ if (cutHits.current.has(edge.id)) continue;
1416
+ const source = nodes.find((n) => n.id === edge.from);
1417
+ const target = nodes.find((n) => n.id === edge.to);
1418
+ if (!source || !target) continue;
1419
+ if (distanceToEdge(canvasSpot, source, target, edge.type) <= threshold) {
1420
+ cutHits.current.add(edge.id);
1421
+ }
1422
+ }
1423
+ }
1424
+ setCutPath((path) => path.concat([{ x: p.x, y: p.y }]).slice(-60));
1425
+ setCutVictims(Array.from(cutHits.current));
1426
+ cutRef.current = p;
1427
+ } else if (marquee) {
1428
+ const p = pointTo(e);
1429
+ const next = { x1: marquee.x1, y1: marquee.y1, x2: p.x, y2: p.y };
1430
+ setMarquee(next);
1431
+ // Live preview: highlight what the band currently covers.
1432
+ setSelectedIds(hitTest(next));
1433
+ } else if (pending) {
1434
+ const p = pointTo(e);
1435
+ setPending((prev) => (prev ? { ...prev, x: p.x, y: p.y } : prev));
1436
+ }
1437
+ };
1438
+
1439
+ const onCanvasUp = () => {
1440
+ if (cutRef.current) {
1441
+ cutRef.current = null;
1442
+ setDragging(false);
1443
+ const victims = Array.from(cutHits.current);
1444
+ const victimIds = new Set(victims);
1445
+ cutHits.current = new Set();
1446
+ if (victims.length) {
1447
+ pushSnapshot();
1448
+ setEdges((es) => es.filter((x) => !victimIds.has(x.id)));
1449
+ flash(t('linkCut') + ' ×' + victims.length);
1450
+ }
1451
+ }
1452
+ if (cutPath.length) { setCutPath([]); setCutVictims([]); }
1453
+ if (marquee) {
1454
+ setSelectedIds(hitTest(marquee));
1455
+ setMarquee(null);
1456
+ }
1457
+ nodeDrag.current = null;
1458
+ setPending(null);
1459
+ setDragging(false);
1460
+ };
1461
+
1462
+ const savePresetNow = () => {
1463
+ const name = presetName.trim();
1464
+ if (!name) { flash(t('needName')); return; }
1465
+ if (Object.prototype.hasOwnProperty.call(presets, name)) {
1466
+ flash('"' + name + '" ' + t('dupName'));
1467
+ return;
1468
+ }
1469
+ const next = { ...presets, [name]: { nodes, edges } };
1470
+ if (!savePresets(next)) { flash(t('saveFailed')); return; }
1471
+ setPresets(next);
1472
+ setPresetName('');
1473
+ setPresetOpen(null);
1474
+ flash(t('savedPreset') + ': ' + name);
1475
+ };
1476
+
1477
+ /** Load a canvas document produced by the model. */
1478
+ const applyCanvasDoc = (doc) => {
1479
+ if (!doc || !Array.isArray(doc.nodes)) return false;
1480
+ const merge = doc.mode === 'merge';
1481
+ if (!merge && !doc.nodes.length) return false;
1482
+ pushSnapshot();
1483
+ applyStamp.current = typeof doc.at === 'number' ? doc.at : null;
1484
+ setNodes((existing) => {
1485
+ const byId = new Map(existing.map((n) => [n.id, n]));
1486
+ const incoming = doc.nodes.map((n, i) => {
1487
+ const prev = byId.get(n.id) || {};
1488
+ return {
1489
+ ...prev,
1490
+ ...n,
1491
+ // keep the position the user placed, unless the document sets one
1492
+ x: typeof n.x === 'number' ? n.x : (typeof prev.x === 'number' ? prev.x : 60 + i * 300),
1493
+ y: typeof n.y === 'number' ? n.y : (typeof prev.y === 'number' ? prev.y : 80),
1494
+ };
1495
+ });
1496
+ if (!merge) return incoming;
1497
+ const touched = new Set(incoming.map((n) => n.id));
1498
+ const removed = new Set(doc.removeNodes || []);
1499
+ const kept = existing.filter((n) => !touched.has(n.id) && !removed.has(n.id));
1500
+ return kept.concat(incoming);
1501
+ });
1502
+ setEdges((existing) => {
1503
+ const incoming = (Array.isArray(doc.edges) ? doc.edges : []).map((e, i) => ({
1504
+ id: e.id || 'e' + i + '-' + Math.random().toString(36).slice(2, 6),
1505
+ from: e.from,
1506
+ to: e.to,
1507
+ type: e.type || 'prompt',
1508
+ }));
1509
+ if (!merge) return incoming;
1510
+ const drop = new Set((doc.removeEdges || []).map((e) => String(e.from) + '>' + String(e.to)));
1511
+ const kept = existing.filter((e) => !drop.has(e.from + '>' + e.to));
1512
+ const seen = new Set(kept.map((e) => e.from + '>' + e.to + '|' + e.type));
1513
+ const added = incoming.filter((e) => !seen.has(e.from + '>' + e.to + '|' + e.type));
1514
+ return kept.concat(added);
1515
+ });
1516
+ setSelectedIds([]);
1517
+ setStatusById({});
1518
+ // Remember what the remote document claimed, so re-reading it on the next
1519
+ // start does not resurrect nodes the user has deleted since.
1520
+ if (typeof doc.at === 'number') {
1521
+ try {
1522
+ const key = storageKey(sessionId);
1523
+ const raw = window.localStorage.getItem(key);
1524
+ const local = raw ? JSON.parse(raw) : {};
1525
+ if (!local || typeof local.at !== 'number' || local.at <= doc.at) {
1526
+ window.localStorage.setItem(key, JSON.stringify({
1527
+ nodes: doc.nodes,
1528
+ edges: Array.isArray(doc.edges) ? doc.edges : [],
1529
+ enabled: Boolean(local && local.enabled),
1530
+ at: doc.at,
1531
+ }));
1532
+ }
1533
+ } catch (_e) { /* storage unavailable */ }
1534
+ }
1535
+ const lead = doc.nodes.find((n) => n.id === 'lead') || doc.nodes[0];
1536
+ if (lead) {
1537
+ const lx = typeof lead.x === 'number' ? lead.x : 60;
1538
+ const ly = typeof lead.y === 'number' ? lead.y : 80;
1539
+ setTimeout(() => centerOn(lx + NODE_W / 2, ly + NODE_H / 2), 0);
1540
+ }
1541
+ return true;
1542
+ };
1543
+
1544
+ // The Host writes generated canvases where the workspace Remote can read
1545
+ // them; polling that file is the only Host -> canvas channel available.
1546
+ const AUTO_CANVAS = true;
1547
+ useEffect(() => {
1548
+ if (!AUTO_CANVAS) return undefined;
1549
+ let remote;
1550
+ try { remote = hostCtx && hostCtx.remote; } catch (_e) { remote = undefined; }
1551
+ let wf = resolveWorkspaceFiles(hostCtx);
1552
+ if (!wf) {
1553
+ try { wf = remote && remote.workspaceFiles; } catch (_e) { wf = undefined; }
1554
+ }
1555
+ if (!wf || typeof wf.read !== 'function') { setSyncNote(t('syncOff')); return undefined; }
1556
+ if (!sessionId) { setSyncNote(t('syncNoSession')); return undefined; }
1557
+ // The Host names the file after the agent id (session-<uuid>); the
1558
+ // pane prop may carry either form, so try both.
1559
+ const bare = String(sessionId).replace(/^session-/, '');
1560
+ const paths = [
1561
+ '.dsh/canvas/' + String(sessionId) + '.json',
1562
+ '.dsh/canvas/session-' + bare + '.json',
1563
+ '.dsh/canvas/' + bare + '.json',
1564
+ ].filter((v, i, all) => all.indexOf(v) === i);
1565
+ let alive = true;
1566
+ let lastText = '';
1567
+ const tick = async () => {
1568
+ try {
1569
+ let text = '';
1570
+ for (const path of paths) {
1571
+ try {
1572
+ const res = await wf.read(sessionId, path, {}, new AbortController().signal);
1573
+ if (!alive) return;
1574
+ const payload = res && res.ok === false ? null : (res && res.value !== undefined ? res.value : res);
1575
+ const read = payload && (typeof payload.text === 'string' ? payload.text : '');
1576
+ if (read) { text = read; break; }
1577
+ } catch (err) {
1578
+ setSyncNote(t('syncReadFail') + String((err && err.message) || err).slice(0, 80));
1579
+ }
1580
+ }
1581
+ if (!text) return;
1582
+ if (text === lastText) return;
1583
+ lastText = text;
1584
+ const doc = JSON.parse(text);
1585
+ const canvas = doc && doc.canvas;
1586
+ // A canvas the user has edited more recently wins over an old file.
1587
+ try {
1588
+ const raw = window.localStorage.getItem(storageKey(sessionId));
1589
+ const local = raw ? JSON.parse(raw) : null;
1590
+ if (local && typeof local.at === 'number' && typeof doc.at === 'number' && local.at > doc.at) {
1591
+ lastText = text;
1592
+ return;
1593
+ }
1594
+ } catch (_e) { /* ignore */ }
1595
+ const valid = canvas && Array.isArray(canvas.nodes) && canvas.nodes.length
1596
+ && canvas.nodes.every((n) => n && typeof n.id === 'string');
1597
+ if (valid && applyCanvasDoc(canvas)) {
1598
+ flash(t('generated'));
1599
+ setSyncNote(t('syncApplied'));
1600
+ setTimeout(() => setSyncNote(''), 4000);
1601
+ }
1602
+ else setSyncNote(t('syncBadFile'));
1603
+ } catch (_e) { /* file absent or not readable yet */ }
1604
+ };
1605
+ const timer = setInterval(tick, 1500);
1606
+ tick();
1607
+ return () => { alive = false; clearInterval(timer); };
1608
+ }, [sessionId]);
1609
+
1610
+ const importFromClipboard = () => {
1611
+ const finish = (text) => {
1612
+ if (!text) { flash(t('importNone')); return; }
1613
+ let doc;
1614
+ try {
1615
+ const start = text.indexOf('{');
1616
+ const end = text.lastIndexOf('}');
1617
+ doc = JSON.parse(text.slice(start, end + 1));
1618
+ } catch (_e) { flash(t('importBad')); return; }
1619
+ if (!applyCanvasDoc(doc.canvas || doc)) { flash(t('importBad')); return; }
1620
+ flash(t('importOk') + (doc.canvas || doc).nodes.length);
1621
+ };
1622
+ try {
1623
+ if (navigator.clipboard && navigator.clipboard.readText) {
1624
+ navigator.clipboard.readText().then(finish, () => flash(t('importNone')));
1625
+ return;
1626
+ }
1627
+ } catch (_e) { /* fall through */ }
1628
+ flash(t('importNone'));
1629
+ };
1630
+
1631
+ const applyPreset = (name) => {
1632
+ const preset = presets[name];
1633
+ if (!preset || !Array.isArray(preset.nodes) || !Array.isArray(preset.edges)) { flash(t('invalidPreset')); return; }
1634
+ pushSnapshot();
1635
+ setNodes(preset.nodes);
1636
+ setEdges(preset.edges);
1637
+ setSelectedIds([]);
1638
+ setStatusById({});
1639
+ setPresetOpen(null);
1640
+ flash(t('loadedPreset') + ': ' + name);
1641
+ };
1642
+
1643
+ const deletePreset = (name) => {
1644
+ const next = { ...presets };
1645
+ delete next[name];
1646
+ savePresets(next);
1647
+ setPresets(next);
1648
+ flash(t('deletedPreset') + ': ' + name);
1649
+ };
1650
+
1651
+ const toggleEnabled = () => {
1652
+ const next = !enabled;
1653
+ setEnabled(next);
1654
+ setDirty(false);
1655
+ pushPlan(next);
1656
+ };
1657
+
1658
+ const modelValue = (node) => (node.provider ? node.provider + '::' : '') + (node.model || '');
1659
+ const modelEntry = (node) => models.find((m) => m.provider + '::' + m.model === modelValue(node));
1660
+ const modelLabel = (node) => {
1661
+ const hit = modelEntry(node);
1662
+ return hit ? hit.modelName : (node.model || t('pickModel'));
1663
+ };
1664
+ // Reasoning ids are adapter-declared per model; '' means "use the model default".
1665
+ const reasoningOptions = (node) => {
1666
+ const hit = modelEntry(node);
1667
+ const ids = ((hit && hit.efforts) || []).map((e) => e.id);
1668
+ return ['', ...(ids.length ? ids : REASONING_FALLBACK)];
1669
+ };
1670
+ const reasoningLabel = (node) => {
1671
+ if (!node.reasoning) return t('defaultEffort');
1672
+ const hit = modelEntry(node);
1673
+ const found = hit && hit.efforts ? hit.efforts.find((e) => e.id === node.reasoning) : undefined;
1674
+ return (found && (found.name || found.id)) || node.reasoning;
1675
+ };
1676
+
1677
+ const scopeToggle = (node) => {
1678
+ const wide = (node.preset || 'standard') !== 'minimal';
1679
+ return h('button', {
1680
+ style: wide ? S.toggleSwitchOn : S.toggleSwitch,
1681
+ type: 'button',
1682
+ title: t('tipPreset'),
1683
+ onMouseDown: (e) => e.stopPropagation(),
1684
+ onClick: () => updateNode(node.id, { preset: wide ? 'minimal' : 'standard' }),
1685
+ }, wide ? t('scopeStandard') : t('scopeMinimal'));
1686
+ };
1687
+ const fallbackControl = (node) => {
1688
+ const key = 'f:' + node.id;
1689
+ const isOpen = openModelFor === key;
1690
+ const current = node.fallbackModel;
1691
+ const shown = models.find((m) => m.model === current);
1692
+ const rows = [];
1693
+ rows.push(h('div', {
1694
+ key: 'none',
1695
+ style: current ? S.menuRow : { ...S.menuRow, background: C.hover, color: C.accent },
1696
+ onClick: () => { updateNode(node.id, { fallbackModel: '', fallbackProvider: '' }); setOpenModelFor(null); },
1697
+ }, t('none')));
1698
+ let lastProvider = null;
1699
+ for (const m of models) {
1700
+ if (m.provider !== lastProvider) {
1701
+ rows.push(h('div', { key: 'h-' + m.provider, style: S.menuHead }, m.providerName || m.provider));
1702
+ lastProvider = m.provider;
1703
+ }
1704
+ const picked = m.model === current;
1705
+ rows.push(h('div', {
1706
+ key: m.provider + '::' + m.model,
1707
+ style: picked ? { ...S.menuRow, background: C.hover, color: C.accent } : S.menuRow,
1708
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1709
+ onMouseLeave: (e) => { e.currentTarget.style.background = picked ? C.hover : 'transparent'; },
1710
+ onClick: () => { updateNode(node.id, { fallbackModel: m.model, fallbackProvider: m.provider }); setOpenModelFor(null); },
1711
+ }, m.modelName || m.model));
1712
+ }
1713
+ return h('div', { ref: isOpen ? dropdownRef : undefined, style: { position: 'relative', flex: '1 1 auto', minWidth: 0 } },
1714
+ h('button', {
1715
+ style: S.selectBtn,
1716
+ type: 'button',
1717
+ title: t('tipFallback'),
1718
+ onMouseDown: (e) => e.stopPropagation(),
1719
+ onClick: () => setOpenModelFor(isOpen ? null : key),
1720
+ },
1721
+ h('span', { style: S.selectText }, shown ? (shown.modelName || shown.model) : t('none')),
1722
+ h('span', { style: S.caret }, '▾'),
1723
+ ),
1724
+ isOpen && h('div', { style: S.menu, onMouseDown: (e) => e.stopPropagation() }, rows),
1725
+ );
1726
+ };
1727
+ const memoryToggle = (node) => h('button', {
1728
+ style: node.keepSession ? S.toggleSwitchOn : S.toggleSwitch,
1729
+ type: 'button',
1730
+ title: t('tipMemory'),
1731
+ onMouseDown: (e) => e.stopPropagation(),
1732
+ onClick: () => updateNode(node.id, { keepSession: !node.keepSession }),
1733
+ }, node.keepSession ? t('on') : t('off'));
1734
+
1735
+ const reasoningControl = (node) => {
1736
+ const key = 'r:' + node.id;
1737
+ const isOpen = openModelFor === key;
1738
+ const entry = modelEntry(node);
1739
+ const labelOf = (id) => {
1740
+ if (!id) return t('defaultEffort');
1741
+ const found = entry && entry.efforts ? entry.efforts.find((e) => e.id === id) : undefined;
1742
+ return (found && (found.name || found.id)) || id;
1743
+ };
1744
+ const rows = reasoningOptions(node).map((id, i) => h('div', {
1745
+ key: 'r' + i,
1746
+ style: node.reasoning === id ? { ...S.menuRow, background: C.hover, color: C.accent } : S.menuRow,
1747
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1748
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1749
+ onClick: () => { updateNode(node.id, { reasoning: id }); setOpenModelFor(null); },
1750
+ }, labelOf(id)));
1751
+ return h('div', { ref: isOpen ? dropdownRef : undefined, style: { position: 'relative', flex: '1 1 auto', minWidth: 0 } },
1752
+ h('button', {
1753
+ style: S.selectBtn,
1754
+ type: 'button',
1755
+ title: t('tipModel'),
1756
+ onMouseDown: (e) => e.stopPropagation(),
1757
+ onClick: () => setOpenModelFor(isOpen ? null : key),
1758
+ },
1759
+ h('span', { style: S.selectText }, labelOf(node.reasoning)),
1760
+ h('span', { style: S.caret }, '▾'),
1761
+ ),
1762
+ isOpen && h('div', { style: S.menu, onMouseDown: (e) => e.stopPropagation() }, rows),
1763
+ );
1764
+ };
1765
+
1766
+ const modelControl = (node) => {
1767
+ if (!models.length) {
1768
+ return h('input', {
1769
+ style: S.input,
1770
+ value: node.model || '',
1771
+ placeholder: 'model id',
1772
+ onMouseDown: (e) => e.stopPropagation(),
1773
+ onChange: (e) => updateNode(node.id, { model: e.target.value }),
1774
+ });
1775
+ }
1776
+ const current = modelValue(node);
1777
+ const isOpen = openModelFor === node.id;
1778
+ const rows = [];
1779
+ let lastProvider = null;
1780
+ for (const m of models) {
1781
+ if (m.provider !== lastProvider) {
1782
+ rows.push(h('div', { key: 'h-' + m.provider, style: S.menuHead }, m.providerName || m.provider));
1783
+ lastProvider = m.provider;
1784
+ }
1785
+ const selectedRow = m.provider + '::' + m.model === current;
1786
+ rows.push(h('div', {
1787
+ key: m.provider + '::' + m.model,
1788
+ style: selectedRow ? { ...S.menuRow, background: C.hover, color: C.accent } : S.menuRow,
1789
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1790
+ onMouseLeave: (e) => { e.currentTarget.style.background = selectedRow ? C.hover : 'transparent'; },
1791
+ onClick: () => { updateNode(node.id, { provider: m.provider, model: m.model }); setOpenModelFor(null); },
1792
+ }, m.modelName || m.model));
1793
+ }
1794
+ return h('div', { ref: isOpen ? dropdownRef : undefined, style: { position: 'relative', flex: '1 1 auto', minWidth: 0 } },
1795
+ h('button', {
1796
+ style: S.selectBtn,
1797
+ type: 'button',
1798
+ onMouseDown: (e) => e.stopPropagation(),
1799
+ onClick: () => setOpenModelFor(isOpen ? null : node.id),
1800
+ },
1801
+ h('span', { style: S.selectText }, modelLabel(node)),
1802
+ h('span', { style: S.caret }, '▾'),
1803
+ ),
1804
+ isOpen && h('div', {
1805
+ style: S.menu,
1806
+ onMouseDown: (e) => e.stopPropagation(),
1807
+ }, rows),
1808
+ );
1809
+ };
1810
+
1811
+ const edgeEls = edges.map((edge) => {
1812
+ const from = nodes.find((n) => n.id === edge.from);
1813
+ const to = nodes.find((n) => n.id === edge.to);
1814
+ if (!from || !to) return null;
1815
+ const color = (SOCKET_TYPES.find((t) => t.id === edge.type) || SOCKET_TYPES[0]).color;
1816
+ const d = edgePath(from, to, edge.type);
1817
+ const highlighted = cutVictims.includes(edge.id);
1818
+ return h('path', {
1819
+ key: edge.id,
1820
+ d,
1821
+ stroke: highlighted ? '#e5534b' : color,
1822
+ strokeWidth: highlighted ? 3 : 2,
1823
+ fill: 'none',
1824
+ style: { pointerEvents: 'none' },
1825
+ });
1826
+ });
1827
+
1828
+ const renderBand = (node) => {
1829
+ const isEntry = node.id === 'lead';
1830
+ return h('div', { style: S.band },
1831
+ SOCKET_TYPES.map((sock) => h('div', { key: sock.id, style: S.row },
1832
+ h('span', { style: S.rowLabel }, sock.label),
1833
+ !isEntry && h('div', {
1834
+ style: { ...S.socket, left: -PORT / 2, borderColor: sock.color },
1835
+ title: t('tipSocketOut'),
1836
+ onMouseDown: (e) => onInputDown(e, node.id, sock.id),
1837
+ onMouseUp: (e) => onInputUp(e, node.id, sock.id),
1838
+ }),
1839
+ h('div', {
1840
+ style: { ...S.socket, right: -PORT / 2, borderColor: sock.color },
1841
+ title: t('tipSocketIn'),
1842
+ onMouseDown: (e) => onOutputDown(e, node.id, sock.id),
1843
+ onMouseUp: (e) => onOutputUp(e, node.id, sock.id),
1844
+ }),
1845
+ )),
1846
+ );
1847
+ };
1848
+
1849
+ const reachableIds = reachableFrom(nodes, edges);
1850
+
1851
+ // The canvas grows with its nodes so links past the original size are
1852
+ // still painted instead of being clipped by the SVG viewport.
1853
+ const contentW = Math.max(CONTENT_W, WORLD_PAD + Math.max(0, ...nodes.map((n) => n.x + NODE_W)) + 400);
1854
+ const contentH = Math.max(CONTENT_H, WORLD_PAD + Math.max(0, ...nodes.map((n) => n.y + NODE_H)) + 400);
1855
+
1856
+ const hitTest = (m) => {
1857
+ const left = Math.min(m.x1, m.x2);
1858
+ const right = Math.max(m.x1, m.x2);
1859
+ const top = Math.min(m.y1, m.y2);
1860
+ const bottom = Math.max(m.y1, m.y2);
1861
+ return nodes
1862
+ .filter((n) => n.x + NODE_W >= left && n.x <= right && n.y + NODE_H >= top && n.y <= bottom)
1863
+ .map((n) => n.id);
1864
+ };
1865
+
1866
+ return h('div', { style: S.root },
1867
+ h('div', { style: S.toolbar },
1868
+ h('button', { style: S.btn, onClick: () => addNode('agent'), type: 'button' }, t('addAgent')),
1869
+ h('button', { style: S.btn, onClick: () => addNode('lead'), type: 'button' }, t('addLead')),
1870
+ h('button', { style: S.btn, onClick: undo, type: 'button', title: t('tipUndo') }, t('undo')),
1871
+ h('button', {
1872
+ style: S.btn,
1873
+ onClick: () => pushPlan(enabled),
1874
+ type: 'button',
1875
+ title: t('tipSync'),
1876
+ }, t('sync')),
1877
+
1878
+ h('button', {
1879
+ style: S.btn,
1880
+ onClick: focusLead,
1881
+ type: 'button',
1882
+ title: t('tipLocate'),
1883
+ }, t('locate')),
1884
+ h('button', {
1885
+ style: S.btn,
1886
+ onClick: () => focusLead(),
1887
+ type: 'button',
1888
+ title: t('tipResetZoom'),
1889
+ }, Math.round(view.k * 100) + '%'),
1890
+ syncNote ? h('span', { style: S.syncNote, title: syncNote }, syncNote) : null,
1891
+ h('button', {
1892
+ style: S.btn,
1893
+ onClick: toggleLang,
1894
+ type: 'button',
1895
+ title: 'Switch language / 切换语言',
1896
+ }, t('lang')),
1897
+ h('div', { style: S.moreBar },
1898
+ h('button', {
1899
+ style: S.btn,
1900
+ type: 'button',
1901
+ title: t('tipMore'),
1902
+ onMouseDown: (e) => e.stopPropagation(),
1903
+ onClick: () => setMenuOpen(!menuOpen),
1904
+ }, '⋯'),
1905
+ menuOpen && h('div', { style: S.moreMenu, onMouseDown: (e) => e.stopPropagation() },
1906
+ h('div', {
1907
+ style: S.moreRow,
1908
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1909
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1910
+ onClick: () => { setMenuOpen(false); importFromClipboard(); },
1911
+ }, t('importBtn')),
1912
+ h('div', {
1913
+ style: S.moreRow,
1914
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1915
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1916
+ onClick: () => { setMenuOpen(false); setHelpOpen(true); },
1917
+ }, t('help')),
1918
+ h('div', {
1919
+ style: S.moreRow,
1920
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1921
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1922
+ onClick: () => {
1923
+ const next = !cutMode;
1924
+ setCutMode(next);
1925
+ saveCutMode(next);
1926
+ },
1927
+ }, t('cutLinks') + t('sep') + (cutMode ? t('on') : t('off'))),
1928
+ ),
1929
+ ),
1930
+ h('div', { style: S.presetBar },
1931
+ h('div', { style: S.presetRowTop },
1932
+ h('input', {
1933
+ style: S.presetInput,
1934
+ value: presetName,
1935
+ placeholder: t('presetName'),
1936
+ onMouseDown: (e) => e.stopPropagation(),
1937
+ onChange: (e) => setPresetName(e.target.value),
1938
+ onKeyDown: (e) => { if (e.key === 'Enter') savePresetNow(); },
1939
+ }),
1940
+ h('button', { style: S.btn, onClick: savePresetNow, type: 'button', title: t('tipSave') }, t('save')),
1941
+ (() => {
1942
+ const names = Object.keys(presets);
1943
+ return h('button', {
1944
+ style: S.btn,
1945
+ onClick: () => setPresetOpen(presetOpen === 'menu' ? null : 'menu'),
1946
+ type: 'button',
1947
+ title: t('tipPresets'),
1948
+ }, t('presets') + (names.length ? ' (' + names.length + ')' : ''));
1949
+ })(),
1950
+ ),
1951
+ // Feedback for saving / loading / syncing sits right under the name field.
1952
+ h('span', { style: S.status },
1953
+ status || (enabled ? (dirty ? t('unsaved') : t('synced')) : '')),
1954
+ presetOpen === 'menu' && (() => {
1955
+ const names = Object.keys(presets);
1956
+ return h('div', { style: S.presetMenu, onMouseDown: (e) => e.stopPropagation() },
1957
+ names.length
1958
+ ? names.map((name) => h('div', {
1959
+ key: name,
1960
+ style: S.presetRow,
1961
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
1962
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
1963
+ },
1964
+ h('span', { style: S.presetRowText, onClick: () => applyPreset(name) }, name),
1965
+ h('button', { style: S.presetDel, type: 'button', title: t('del'), onClick: () => deletePreset(name) }, '×'),
1966
+ ))
1967
+ : h('div', { style: S.presetEmpty }, t('presetEmpty')),
1968
+ );
1969
+ })(),
1970
+ ),
1971
+ ),
1972
+ helpOpen && h('div', { style: S.helpOverlay, onMouseDown: (e) => e.stopPropagation() },
1973
+ h('div', { style: S.helpCard },
1974
+ h('div', { style: S.helpHead },
1975
+ h('span', { style: S.helpTitle }, t('helpTitle')),
1976
+ h('button', { style: S.btn, type: 'button', onClick: () => setHelpOpen(false) }, t('close')),
1977
+ ),
1978
+ h('div', { style: S.helpBody }, t('helpBody').split('\n').map((line, i) => h('div', { key: i, style: S.helpLine }, line))),
1979
+ ),
1980
+ ),
1981
+ h('button', {
1982
+ style: enabled ? S.floatOn : S.floatOff,
1983
+ type: 'button',
1984
+ onMouseDown: (e) => e.stopPropagation(),
1985
+ onClick: toggleEnabled,
1986
+ title: t('tipToggle'),
1987
+ }, enabled ? t('enabled') : t('disabled')),
1988
+ h('div', { ref: canvasElRef, style: S.canvas, onMouseDown: onCanvasDown },
1989
+ h('div', {
1990
+ ref: contentRef,
1991
+ style: {
1992
+ ...S.content, width: contentW, height: contentH, overflow: 'visible',
1993
+ transform: 'translate(' + view.x + 'px,' + view.y + 'px) scale(' + view.k + ')',
1994
+ transformOrigin: '0 0',
1995
+ },
1996
+ },
1997
+ h('svg', { width: contentW, height: contentH, style: { position: 'absolute', left: 0, top: 0, pointerEvents: 'none', overflow: 'visible' } },
1998
+ h('g', null, edgeEls),
1999
+ cutPath.length > 1 && h('polyline', {
2000
+ points: cutPath.map((pt) => (pt.x + WORLD_PAD) + ',' + (pt.y + WORLD_PAD)).join(' '),
2001
+ fill: 'none',
2002
+ stroke: '#e5534b',
2003
+ strokeWidth: 1.5,
2004
+ strokeDasharray: '5 4',
2005
+ }),
2006
+ marquee && h('rect', {
2007
+ x: Math.min(marquee.x1, marquee.x2) + WORLD_PAD,
2008
+ y: Math.min(marquee.y1, marquee.y2) + WORLD_PAD,
2009
+ width: Math.abs(marquee.x2 - marquee.x1),
2010
+ height: Math.abs(marquee.y2 - marquee.y1),
2011
+ fill: 'rgba(47,129,247,0.12)',
2012
+ stroke: C.accent,
2013
+ strokeWidth: 1,
2014
+ strokeDasharray: '4 3',
2015
+ }),
2016
+ pending && (() => {
2017
+ const color = (SOCKET_TYPES.find((t) => t.id === pending.type) || SOCKET_TYPES[0]).color;
2018
+ const d = 'M ' + (pending.sx + WORLD_PAD) + ' ' + (pending.sy + WORLD_PAD) + ' L ' + (pending.x + WORLD_PAD) + ' ' + (pending.y + WORLD_PAD);
2019
+ return h('path', { d, stroke: color, strokeWidth: 2, strokeDasharray: '4 4', fill: 'none' });
2020
+ })(),
2021
+ ),
2022
+ nodes.map((node) => {
2023
+ const isEntry = node.id === 'lead';
2024
+ const isLeadKind = node.kind === 'lead';
2025
+ const roleInput = (style) => h('div', { style },
2026
+ h('span', { style: S.fieldLabel }, t('role')),
2027
+ h('input', {
2028
+ style: S.input,
2029
+ value: node.role || '',
2030
+ placeholder: isLeadKind ? t('rolePhLead') : t('rolePhAgent'),
2031
+ onMouseDown: (e) => e.stopPropagation(),
2032
+ onFocus: () => setSelectedIds([node.id]),
2033
+ onChange: (e) => updateNode(node.id, { role: e.target.value }),
2034
+ }),
2035
+ );
2036
+ const isOrphan = node.id !== 'lead' && !reachableIds.has(node.id);
2037
+ return h('div', {
2038
+ key: node.id,
2039
+ 'data-node': node.id,
2040
+ style: selectedIds.includes(node.id)
2041
+ ? { ...S.node, left: node.x + WORLD_PAD, top: node.y + WORLD_PAD, ...(isLeadKind ? S.leadNode : null), ...(isOrphan ? S.orphanNode : null), ...S.nodeSel }
2042
+ : { ...S.node, left: node.x + WORLD_PAD, top: node.y + WORLD_PAD, ...(isLeadKind ? S.leadNode : null), ...(isOrphan ? S.orphanNode : null) },
2043
+ title: isOrphan ? t('orphanTip') : undefined,
2044
+ onMouseDown: (e) => onNodeDown(e, node.id),
2045
+ },
2046
+ h('div', {
2047
+ style: {
2048
+ ...S.topBar,
2049
+ background: isLeadKind ? '#2f81f7' : '#3fb950',
2050
+ },
2051
+ }),
2052
+ enabled && h('div', {
2053
+ style: {
2054
+ ...S.statusChip,
2055
+ color: isLeadKind ? C.dim
2056
+ : statusById[node.id] === 'running' ? '#2f81f7'
2057
+ : statusById[node.id] === 'failed' ? '#e5534b'
2058
+ : statusById[node.id] === 'done' ? '#3fb950' : C.dim,
2059
+ },
2060
+ title: isLeadKind ? t('tipLead') : (isOrphan ? t('tipOrphan') : t('tipStatus')),
2061
+ }, isOrphan ? t('stOrphan')
2062
+ : isLeadKind ? t('stLead')
2063
+ : statusById[node.id] === 'running' ? t('stRunning')
2064
+ : statusById[node.id] === 'failed' ? t('stFailed')
2065
+ : statusById[node.id] === 'done' ? t('stDone') : t('stPending')),
2066
+ isEntry
2067
+ ? h('div', { style: S.titleReadonly }, t('leadThis'))
2068
+ : h('input', {
2069
+ style: S.title,
2070
+ value: node.label,
2071
+ onMouseDown: (e) => e.stopPropagation(),
2072
+ onFocus: () => setSelectedIds([node.id]),
2073
+ onChange: (e) => updateNode(node.id, { label: e.target.value }),
2074
+ }),
2075
+ isEntry
2076
+ ? h(React.Fragment, null,
2077
+ h('div', { style: S.leadLabel }, h('span', { style: S.fieldLabel }, t('task'))),
2078
+ h('textarea', {
2079
+ style: S.task,
2080
+ value: node.task || '',
2081
+ placeholder: t('taskPh'),
2082
+ onMouseDown: (e) => e.stopPropagation(),
2083
+ onFocus: () => setSelectedIds([node.id]),
2084
+ onChange: (e) => updateNode(node.id, { task: e.target.value }),
2085
+ }),
2086
+ )
2087
+ : isLeadKind
2088
+ ? h(React.Fragment, null,
2089
+ h('div', { style: S.leadLabel }, h('span', { style: S.fieldLabel }, t('role'))),
2090
+ h('textarea', {
2091
+ style: S.task,
2092
+ value: node.role || '',
2093
+ placeholder: t('rolePhLead'),
2094
+ onMouseDown: (e) => e.stopPropagation(),
2095
+ onFocus: () => setSelectedIds([node.id]),
2096
+ onChange: (e) => updateNode(node.id, { role: e.target.value }),
2097
+ }),
2098
+ )
2099
+ : h(React.Fragment, null,
2100
+ h('div', { style: S.fieldModel },
2101
+ h('span', { style: S.fieldLabel }, t('model')),
2102
+ modelControl(node),
2103
+ ),
2104
+ h('div', { style: S.fieldReason },
2105
+ h('span', { style: S.fieldLabel }, t('reason')),
2106
+ reasoningControl(node),
2107
+ ),
2108
+ h('div', { style: S.fieldScope },
2109
+ h('span', { style: S.fieldLabel }, t('scope')),
2110
+ scopeToggle(node),
2111
+ ),
2112
+ h('div', { style: S.fieldFallback },
2113
+ h('span', { style: S.fieldLabel }, t('fallbackModel')),
2114
+ fallbackControl(node),
2115
+ ),
2116
+ h('div', { style: S.fieldMemory },
2117
+ h('span', { style: S.fieldLabel }, t('memory')),
2118
+ memoryToggle(node),
2119
+ ),
2120
+ h('div', { style: S.fieldRole },
2121
+ h('span', { style: S.fieldLabel }, t('role')),
2122
+ h('button', {
2123
+ style: S.selectBtn,
2124
+ type: 'button',
2125
+ title: t('rolePhAgent'),
2126
+ onMouseDown: (e) => e.stopPropagation(),
2127
+ onClick: () => setRoleEditFor(roleEditFor === node.id ? null : node.id),
2128
+ },
2129
+ h('span', { style: S.selectText }, node.role || t('rolePhAgent')),
2130
+ h('span', { style: S.caret }, '✎'),
2131
+ ),
2132
+ ),
2133
+ roleEditFor === node.id && h('div', {
2134
+ style: S.rolePopover,
2135
+ onMouseDown: (e) => e.stopPropagation(),
2136
+ },
2137
+ h('textarea', {
2138
+ style: S.roleArea,
2139
+ value: node.role || '',
2140
+ placeholder: t('rolePhAgent'),
2141
+ autoFocus: true,
2142
+ onChange: (e) => updateNode(node.id, { role: e.target.value }),
2143
+ }),
2144
+ ),
2145
+ ),
2146
+ selectedIds.includes(node.id) && node.id !== 'lead' && h('div', {
2147
+ style: S.nodeDelete,
2148
+ title: t('delNodeTip'),
2149
+ onMouseDown: (e) => e.stopPropagation(),
2150
+ onClick: () => deleteNode(node.id),
2151
+ }, '×'),
2152
+ renderBand(node),
2153
+ );
2154
+ }),
2155
+ ),
2156
+ ),
2157
+ );
2158
+ }
2159
+
2160
+ return {
2161
+ inject: ['slots', 'sessions', 'remote', 'remote.session', 'sidebarRight'],
2162
+ apply(ctx) {
2163
+ try {
2164
+ hostCtx = ctx;
2165
+ ctx.inject(['sidebarRightTabs'], (scope) => {
2166
+ scope.effect(() => scope.sidebarRightTabs.register({
2167
+ id: TAB_ID,
2168
+ kind: KIND,
2169
+ // Keep the tab (and its canvas state) alive while the pane is closed.
2170
+ keepMounted: true,
2171
+ title: () => 'Workflow',
2172
+ guide: [{
2173
+ id: 'workflow-canvas',
2174
+ order: 100,
2175
+ title: () => 'Workflow canvas',
2176
+ description: () => pick('画一张子代理流程图', 'Sketch a subagent workflow'),
2177
+ }],
2178
+ }), 'workflow-canvas: tab type');
2179
+
2180
+ scope.effect(() => scope.slots.inject('sidebar.right.pane.tab', () => scope.slots.register({
2181
+ name: 'sidebar.right.pane.tab',
2182
+ key: TAB_ID,
2183
+ }, (props) => h(CanvasBoundary, null, h(WorkflowCanvas, props)))), 'workflow-canvas: tab body');
2184
+ });
2185
+ } catch (error) {
2186
+ try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
2187
+ }
2188
+ },
2189
+ __test: { topoOrder, buildWorkflowScript, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, distanceToEdge, edgeCurve },
2190
+ };
2191
+ },
2192
+ });