pi-web-ui 0.113.1 → 0.114.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/README.md +117 -246
  3. package/README.zh-CN.md +145 -217
  4. package/README.zh-TW.md +145 -217
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/pi-device-hub.mjs +9 -0
  7. package/bin/pi-web-ui.mjs +47 -15
  8. package/dist/server/agent-service-daemon.js +102 -24
  9. package/dist/server/agent-service.js +2289 -1120
  10. package/dist/server/approval-rules.js +29 -3
  11. package/dist/server/ask-user-question-tool.js +8 -8
  12. package/dist/server/atomic-file.js +35 -14
  13. package/dist/server/attachment-store.js +71 -35
  14. package/dist/server/attachments.js +18 -8
  15. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  16. package/dist/server/canvas/canvas-dispatch.js +61 -20
  17. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  18. package/dist/server/canvas/canvas-scheduler.js +99 -0
  19. package/dist/server/canvas/canvas-store.js +107 -54
  20. package/dist/server/canvas/canvas-validation.js +131 -0
  21. package/dist/server/canvas/canvas-workspace.js +284 -0
  22. package/dist/server/client-id-utils.js +8 -0
  23. package/dist/server/client-state.js +104 -22
  24. package/dist/server/communicate-tool.js +76 -0
  25. package/dist/server/compact-context-tool.js +2 -3
  26. package/dist/server/compaction-instructions.js +75 -0
  27. package/dist/server/compaction-markers.js +7 -2
  28. package/dist/server/compaction-state.js +84 -0
  29. package/dist/server/composer-drafts.js +43 -40
  30. package/dist/server/context-evidence.js +346 -0
  31. package/dist/server/conversation-communication.js +368 -0
  32. package/dist/server/conversation-read-tool.js +3 -4
  33. package/dist/server/conversation-tool-names.js +14 -0
  34. package/dist/server/conversation-tool.js +57 -0
  35. package/dist/server/delegate-mode.js +17 -4
  36. package/dist/server/device-center/bot-catalog.js +88 -0
  37. package/dist/server/device-center/bot-execution.js +106 -0
  38. package/dist/server/device-center/bots.js +170 -0
  39. package/dist/server/device-center/collab-service.js +153 -0
  40. package/dist/server/device-center/collab-tool.js +184 -0
  41. package/dist/server/device-center/connector.js +332 -0
  42. package/dist/server/device-center/desktop-linux.js +372 -0
  43. package/dist/server/device-center/desktop-native.js +413 -0
  44. package/dist/server/device-center/desktop-page.js +232 -0
  45. package/dist/server/device-center/desktop-setup.js +30 -0
  46. package/dist/server/device-center/desktop.js +387 -0
  47. package/dist/server/device-center/device-portals.js +241 -0
  48. package/dist/server/device-center/execution-failure.js +70 -0
  49. package/dist/server/device-center/executor.js +371 -0
  50. package/dist/server/device-center/file-sync.js +493 -0
  51. package/dist/server/device-center/hub-auth.js +69 -0
  52. package/dist/server/device-center/hub-page.js +68 -0
  53. package/dist/server/device-center/hub-setup.js +214 -0
  54. package/dist/server/device-center/hub.js +829 -0
  55. package/dist/server/device-center/local-page.js +17 -0
  56. package/dist/server/device-center/local.js +476 -0
  57. package/dist/server/device-center/main.js +118 -0
  58. package/dist/server/device-center/native-desktop/macos.js +192 -0
  59. package/dist/server/device-center/native-desktop/windows.js +118 -0
  60. package/dist/server/device-center/path-portal.js +120 -0
  61. package/dist/server/device-center/relay.js +959 -0
  62. package/dist/server/device-center/runtime.js +253 -0
  63. package/dist/server/device-center/smoke-preview.js +3 -0
  64. package/dist/server/device-center/store.js +122 -0
  65. package/dist/server/device-center/task-error.js +14 -0
  66. package/dist/server/device-center/transfers.js +293 -0
  67. package/dist/server/device-center/workspaces.js +45 -0
  68. package/dist/server/dispatch-domain-handlers.js +83 -27
  69. package/dist/server/dsh/dsh-agent-service.js +277 -158
  70. package/dist/server/dsh/dsh-client.js +12 -2
  71. package/dist/server/durable/durable-agent-service.js +1 -1
  72. package/dist/server/evidence-tool-hooks.js +49 -0
  73. package/dist/server/file-save.js +95 -0
  74. package/dist/server/file-transfer-routes.js +97 -47
  75. package/dist/server/files-service.js +38 -26
  76. package/dist/server/goal-review-gate.js +16 -6
  77. package/dist/server/goal-service.js +54 -30
  78. package/dist/server/http-proxy.js +120 -0
  79. package/dist/server/index.js +229 -223
  80. package/dist/server/load-timing.js +31 -0
  81. package/dist/server/mcp-bridge.js +219 -94
  82. package/dist/server/mcp-hot-reload.js +31 -5
  83. package/dist/server/mcp-manager.js +192 -93
  84. package/dist/server/mcp-oauth-login.js +169 -0
  85. package/dist/server/mcp-oauth-ui.js +137 -0
  86. package/dist/server/mcp-oauth.js +395 -0
  87. package/dist/server/mcp-project-runtime.js +207 -0
  88. package/dist/server/message-window.js +74 -21
  89. package/dist/server/net-guard.js +122 -20
  90. package/dist/server/payload-limits.js +17 -0
  91. package/dist/server/pending-question.js +82 -0
  92. package/dist/server/plan-mode.js +338 -137
  93. package/dist/server/plugin-assets.js +8 -4
  94. package/dist/server/plugin-chat-attachments.js +48 -0
  95. package/dist/server/plugin-facilities.js +67 -220
  96. package/dist/server/plugin-installer.js +2 -1
  97. package/dist/server/plugin-removal.js +49 -0
  98. package/dist/server/plugin-secrets.js +179 -0
  99. package/dist/server/plugins.js +262 -92
  100. package/dist/server/preset-fields.js +49 -0
  101. package/dist/server/preset-plugin-dependencies.js +57 -0
  102. package/dist/server/preset-share.js +112 -72
  103. package/dist/server/protocol-version.js +1 -1
  104. package/dist/server/queue-modes.js +10 -0
  105. package/dist/server/remote-ssh-service.js +160 -67
  106. package/dist/server/request-context.js +164 -0
  107. package/dist/server/sandbox-data.js +655 -0
  108. package/dist/server/sandbox-engines.js +7 -0
  109. package/dist/server/sandbox-runtime-gate.js +41 -0
  110. package/dist/server/sandbox-service.js +139 -698
  111. package/dist/server/sandbox-tool.js +21 -4
  112. package/dist/server/scheduler-tasks.js +63 -48
  113. package/dist/server/serialize.js +48 -19
  114. package/dist/server/session-branch.js +25 -3
  115. package/dist/server/session-parser.js +28 -18
  116. package/dist/server/session-scan.js +130 -0
  117. package/dist/server/session-search.js +51 -37
  118. package/dist/server/settings-service.js +267 -111
  119. package/dist/server/setup-config.js +58 -0
  120. package/dist/server/skill-maintenance.js +112 -24
  121. package/dist/server/subagent-helpers.js +4 -1
  122. package/dist/server/subagent-notify.js +4 -1
  123. package/dist/server/subagent-security-gate.js +52 -11
  124. package/dist/server/subagent-task.js +27 -0
  125. package/dist/server/subagents.js +217 -46
  126. package/dist/server/tabs.js +9 -1
  127. package/dist/server/terminals.js +467 -363
  128. package/dist/server/tool-guards.js +42 -6
  129. package/dist/server/tool-manager.js +47 -20
  130. package/dist/server/tool-overrides.js +13 -11
  131. package/dist/server/tool-prompt-overrides.js +32 -2
  132. package/dist/server/tool-prompts.js +1 -1
  133. package/dist/server/turn-timing.js +11 -0
  134. package/dist/server/universal/session-store.js +48 -6
  135. package/dist/server/universal/universal-service.js +1 -1
  136. package/dist/server/universal/universal-session.js +334 -231
  137. package/dist/server/uploads.js +64 -5
  138. package/dist/server/worktree-service.js +32 -24
  139. package/dist/server/ws-pending-queue.js +73 -27
  140. package/docs/device-center.md +142 -0
  141. package/docs/device-desktop.md +48 -0
  142. package/package.json +4 -1
  143. package/plugin-sdk/index.d.ts +28 -6
  144. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  145. package/plugins/catalog.json +1 -1
  146. package/themes/aetheris.css +1 -107
  147. package/themes/ayu-light.css +5 -29
  148. package/themes/bases/flow-base.css +0 -6
  149. package/themes/bases/statusbar-flat-base.css +112 -0
  150. package/themes/bases/zhujian-base.css +1 -0
  151. package/themes/bases/zhupi-base.css +1 -0
  152. package/themes/catppuccin-latte.css +4 -27
  153. package/themes/catppuccin.css +4 -35
  154. package/themes/claude-code-dark.css +1 -0
  155. package/themes/codex.css +4 -28
  156. package/themes/cyberpunk.css +3 -61
  157. package/themes/dark-teal.css +0 -1
  158. package/themes/dazzle.css +3 -73
  159. package/themes/everforest-light.css +4 -27
  160. package/themes/geist.css +4 -28
  161. package/themes/gruvbox-light.css +4 -27
  162. package/themes/kanagawa-lotus.css +4 -27
  163. package/themes/md-preview.css +3 -213
  164. package/themes/mist.css +4 -24
  165. package/themes/nord.css +4 -35
  166. package/themes/one-dark.css +4 -37
  167. package/themes/paper.css +4 -16
  168. package/themes/rose-pine-dawn.css +4 -28
  169. package/themes/sakura.css +4 -24
  170. package/themes/solarized-light.css +4 -27
  171. package/themes/tokyo-night.css +3 -34
  172. package/themes/white.css +4 -26
  173. package/themes/zhujian-dark.css +1 -0
  174. package/themes/zhupi-dark.css +1 -0
  175. package/web/dist/.build-assets.json +1 -0
  176. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  177. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  178. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  179. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  180. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  181. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  182. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  183. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  184. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  185. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  186. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  187. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  188. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  189. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  190. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  191. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  192. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  193. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  194. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  195. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  196. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  197. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  198. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  199. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  200. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  201. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  202. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  203. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  204. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  205. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  206. package/web/dist/assets/index-Cje8iugL.js +83 -0
  207. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  208. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  209. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  210. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  211. package/web/dist/assets/math-BorAY7qD.css +1 -0
  212. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  213. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  214. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  215. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  216. package/web/dist/index.html +15 -9
  217. package/web/dist/sw.js +1 -1
  218. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  219. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  220. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  221. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  222. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -9,16 +9,18 @@
9
9
  * 5. 审查回路与防死循环熔断保护(Review Loop Breaker)。
10
10
  */
11
11
  import { existsSync, mkdirSync } from "node:fs";
12
- import { isAbsolute, resolve, sep } from "node:path";
12
+ import { isAbsolute, resolve } from "node:path";
13
13
  import { isRemoteWorkspaceUri } from "../remote-ssh-service.js";
14
14
  import { existsSync as fsExistsSync, mkdirSync as fsMkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
15
15
  import { join as pathJoin } from "node:path";
16
- import { saveCanvasRuntimeState, loadCanvasGraph, saveCanvasGraph, isSafeGraphId } from "./canvas-store.js";
17
- import { isInsideGitRepo, normalizeWirePath } from "../worktree-service.js";
16
+ import { saveCanvasRuntimeState, loadCanvasGraph, saveCanvasGraph, isSafeGraphId, deleteCanvasGraph, markInterruptedCanvasRuns, } from "./canvas-store.js";
17
+ import { prepareCanvasWorkspace, captureCanvasWorkspaceArtifact } from "./canvas-workspace.js";
18
18
  import { execFile } from "node:child_process";
19
19
  import { promisify } from "node:util";
20
20
  import { PSTACK_SKILLS_MAP } from "./pstack-skills-data.js";
21
21
  import { discoverDiskSkills, readSkillInstruction } from "../skill-discovery.js";
22
+ import { randomUUID } from "node:crypto";
23
+ import { CanvasExecutionQueue, canvasCondition, canvasReadiness, isCanvasBackedge, validateCanvasTopology, } from "./canvas-scheduler.js";
22
24
  const exec = promisify(execFile);
23
25
  export class CanvasOrchestrator {
24
26
  dataDir;
@@ -35,10 +37,18 @@ export class CanvasOrchestrator {
35
37
  broadcaster = null;
36
38
  activeExecutions = new Map();
37
39
  runningGraphs = new Map();
40
+ graphGenerations = new Map();
41
+ nodeGenerations = new Map();
42
+ executionQueue = new CanvasExecutionQueue(4);
43
+ static sharedWorkspaceQueue = new CanvasExecutionQueue(1);
44
+ /** Immutable rejection inputs survive resetting the producer and its forward region. */
45
+ feedbackArtifacts = new Map();
46
+ runDeadlines = new Map();
38
47
  constructor(baseCwd, dataDir, engineGetter) {
39
48
  this.baseCwd = baseCwd;
40
49
  this.dataDir = dataDir;
41
50
  this.engineGetter = engineGetter;
51
+ markInterruptedCanvasRuns(dataDir);
42
52
  }
43
53
  setBroadcaster(broadcaster) {
44
54
  this.broadcaster = broadcaster;
@@ -51,6 +61,15 @@ export class CanvasOrchestrator {
51
61
  // 背压/断连导致广播失败不得污染调度主路径(故障注入 S3 命中)
52
62
  }
53
63
  }
64
+ /** Reload after the store merges runtime fields so stale execution topology never reaches clients. */
65
+ broadcastCanvasRuntime(graph) {
66
+ try {
67
+ this.broadcast({ type: "canvas_graph_state", graph: loadCanvasGraph(this.dataDir, graph.id) });
68
+ }
69
+ catch {
70
+ // Deletion wins over late runtime publication.
71
+ }
72
+ }
54
73
  logKey(graphId, nodeId) {
55
74
  return `${graphId}:${nodeId}`;
56
75
  }
@@ -113,7 +132,10 @@ export class CanvasOrchestrator {
113
132
  while (list.length > 300)
114
133
  list.shift();
115
134
  this.nodeLogs.set(key, list);
135
+ const generation = this.graphGenerations.get(graphId) ?? 0;
116
136
  this.broadcast({ type: "canvas_node_log", graphId, nodeId, entry });
137
+ if ((this.graphGenerations.get(graphId) ?? 0) !== generation)
138
+ return;
117
139
  // 每 10 条落盘一次,避免高频 IO
118
140
  if (list.length % 10 === 0 || kind === "error" || kind === "done") {
119
141
  try {
@@ -161,74 +183,143 @@ export class CanvasOrchestrator {
161
183
  return resolve(this.baseCwd);
162
184
  }
163
185
  async resolveNodeCwd(node, runBase) {
164
- // node.id 用于 worktree 目录名与 git 分支名;node.cwd 允许工作区外任意绝对路径。
165
186
  if (!isSafeGraphId(node.id))
166
- throw new Error(`Invalid canvas node id: ${JSON.stringify(node.id)}`);
187
+ throw new Error(`Invalid canvas node id: ${node.id}`);
188
+ if (node.useWorktree)
189
+ return (await prepareCanvasWorkspace({
190
+ baseCwd: this.pickRunBase(runBase),
191
+ dataDir: this.dataDir,
192
+ graphId: "standalone",
193
+ runId: randomUUID(),
194
+ nodeId: node.id,
195
+ cwd: node.cwd,
196
+ useWorktree: true,
197
+ })).cwd;
167
198
  const raw = (node.cwd ?? "").trim();
168
- // 远程 SSH 工作区路径(如 ssh://user@host:22/path)原生透传给引擎,不走本地目录与 worktree
169
- if (isRemoteWorkspaceUri(raw)) {
199
+ if (isRemoteWorkspaceUri(raw))
170
200
  return raw;
171
- }
172
201
  const base = this.pickRunBase(runBase);
173
- if (isRemoteWorkspaceUri(base)) {
202
+ if (isRemoteWorkspaceUri(base))
174
203
  return !raw || raw === "." ? base : `${base.replace(/\/+$/, "")}/${raw.replace(/^\/+/, "")}`;
204
+ const cwd = !raw ? base : isAbsolute(raw) ? resolve(raw) : resolve(base, raw);
205
+ if (!existsSync(cwd))
206
+ mkdirSync(cwd, { recursive: true });
207
+ return cwd;
208
+ }
209
+ armRunDeadline(graph) {
210
+ const previous = this.runDeadlines.get(graph.id);
211
+ if (previous)
212
+ clearTimeout(previous);
213
+ const runId = graph.run.id;
214
+ const timer = setTimeout(() => {
215
+ this.runDeadlines.delete(graph.id);
216
+ if (graph.run?.id !== runId ||
217
+ !graph.nodes.some((n) => n.status === "running" || n.status === "waiting_approval"))
218
+ return;
219
+ this.stopAll(graph.id);
220
+ graph.status = "error";
221
+ graph.run.error = "Canvas run exceeded 30 minute deadline";
222
+ saveCanvasRuntimeState(this.dataDir, graph);
223
+ this.broadcastCanvasRuntime(graph);
224
+ }, 30 * 60 * 1000);
225
+ timer.unref();
226
+ this.runDeadlines.set(graph.id, timer);
227
+ }
228
+ /** Invalidate executions before deleting persistence. */
229
+ deleteGraph(graphId) {
230
+ if (!isSafeGraphId(graphId))
231
+ return false;
232
+ this.graphGenerations.set(graphId, (this.graphGenerations.get(graphId) ?? 0) + 1);
233
+ for (const [key, execution] of this.activeExecutions) {
234
+ if (execution.graphId !== graphId)
235
+ continue;
236
+ this.activeExecutions.delete(key);
237
+ execution.abortController?.abort();
175
238
  }
176
- // 空 = 运行基准;相对路径 = 相对运行基准(默认服务工作区,运行时可被当前项目覆盖);绝对路径 = 原样使用(不再拦截越出工作区)。
177
- const targetDir = !raw ? base : isAbsolute(raw) ? resolve(raw) : resolve(base, raw);
178
- if (!node.useWorktree) {
179
- if (!existsSync(targetDir)) {
180
- mkdirSync(targetDir, { recursive: true });
181
- }
182
- return targetDir;
183
- }
184
- // 启用 Git Worktree 隔离机制(仅工作区内目录才做 worktree;工作区外绝对路径直接使用目标目录)
185
- const basePrefix = base.endsWith(sep) ? base : base + sep;
186
- const insideBase = targetDir === base || targetDir.startsWith(basePrefix);
187
- if (!insideBase) {
188
- return targetDir;
189
- }
190
- const isGit = await isInsideGitRepo(base);
191
- if (!isGit) {
192
- // 如果不是 git 仓库,回落到普通子目录
193
- return targetDir;
194
- }
195
- const worktreeDir = resolve(base, ".worktrees", `canvas-${node.id}`);
196
- if (!existsSync(worktreeDir)) {
197
- mkdirSync(resolve(base, ".worktrees"), { recursive: true });
198
- try {
199
- await exec("git", ["worktree", "add", "-B", `canvas/${node.id}`, normalizeWirePath(worktreeDir), "HEAD"], {
200
- cwd: base,
201
- windowsHide: true,
202
- });
203
- }
204
- catch {
205
- // 若创建 worktree 失败(例如已存在锁),回退普通目录
206
- return targetDir;
207
- }
208
- }
209
- return worktreeDir;
239
+ clearTimeout(this.runDeadlines.get(graphId));
240
+ this.runDeadlines.delete(graphId);
241
+ for (const key of this.feedbackArtifacts.keys())
242
+ if (key.startsWith(`${graphId}:`))
243
+ this.feedbackArtifacts.delete(key);
244
+ this.runningGraphs.delete(graphId);
245
+ this.runBaseByGraph.delete(graphId);
246
+ for (const key of this.nodeLogs.keys())
247
+ if (key.startsWith(`${graphId}:`))
248
+ this.nodeLogs.delete(key);
249
+ for (const key of this.nodeMessages.keys())
250
+ if (key.startsWith(`${graphId}:`))
251
+ this.nodeMessages.delete(key);
252
+ return deleteCanvasGraph(this.dataDir, graphId);
210
253
  }
211
254
  /** 启动单个节点 */
212
- async runNode(graph, nodeId, initialPrompt, runBase) {
255
+ async runNode(graph, nodeId, initialPrompt, runBase, scheduled = false) {
256
+ if (!fsExistsSync(pathJoin(this.dataDir, "canvas", `${graph.id}.json`)))
257
+ return;
258
+ const execKey = `${graph.id}:${nodeId}`;
259
+ if (this.activeExecutions.has(execKey))
260
+ throw new Error(`Canvas node already running: ${nodeId}`);
261
+ if (!scheduled && ["running", "waiting_approval"].includes(this.runningGraphs.get(graph.id)?.status ?? ""))
262
+ throw new Error("Canvas graph already running");
263
+ // A separately loaded run_node must not replace an active graph object.
264
+ if ([...this.activeExecutions.values()].some((execution) => execution.graphId === graph.id)) {
265
+ graph = this.runningGraphs.get(graph.id) ?? graph;
266
+ }
213
267
  const node = graph.nodes.find((n) => n.id === nodeId);
214
268
  if (!node)
215
269
  return;
216
270
  this.runningGraphs.set(graph.id, graph);
217
- const execKey = `${graph.id}:${nodeId}`;
218
- if (this.activeExecutions.has(execKey)) {
219
- // 已在运行中
220
- return;
221
- }
271
+ const generation = this.graphGenerations.get(graph.id) ?? 0;
272
+ const nodeGeneration = (this.nodeGenerations.get(execKey) ?? 0) + 1;
273
+ this.nodeGenerations.set(execKey, nodeGeneration);
274
+ const lifecycleCurrent = () => (this.graphGenerations.get(graph.id) ?? 0) === generation && this.nodeGenerations.get(execKey) === nodeGeneration;
222
275
  const controller = new AbortController();
223
- this.activeExecutions.set(execKey, {
276
+ const execution = {
224
277
  graphId: graph.id,
225
278
  nodeId,
226
279
  abortController: controller,
227
- });
280
+ };
281
+ this.activeExecutions.set(execKey, execution);
282
+ const isCurrent = () => lifecycleCurrent() && !controller.signal.aborted && this.activeExecutions.get(execKey) === execution;
283
+ if (!scheduled || !graph.run) {
284
+ for (const key of this.feedbackArtifacts.keys())
285
+ if (key.startsWith(`${graph.id}:`))
286
+ this.feedbackArtifacts.delete(key);
287
+ graph.run = { id: randomUUID(), graphRev: graph.rev ?? 0, startedAt: Date.now(), scope: "node", nodeId };
288
+ }
289
+ graph.status = "running";
290
+ if (!scheduled)
291
+ this.armRunDeadline(graph);
292
+ node.runId = graph.run.id;
293
+ node.attempt = (node.attempt ?? 0) + 1;
294
+ node.artifact = undefined;
295
+ node.lastOutputSummary = undefined;
296
+ if (!scheduled) {
297
+ const scope = new Set(this.runNodes(graph).map((n) => n.id));
298
+ for (const target of this.runNodes(graph))
299
+ if (target !== node) {
300
+ target.status = "idle";
301
+ target.error = undefined;
302
+ target.artifact = undefined;
303
+ target.lastOutputSummary = undefined;
304
+ target.aiVerdict = undefined;
305
+ target.runId = graph.run.id;
306
+ target.attempt = 0;
307
+ }
308
+ for (const edge of graph.edges) {
309
+ edge.active = scope.has(edge.sourceNodeId) ? undefined : false;
310
+ edge.runId = graph.run.id;
311
+ edge.lastHandoffSummary = undefined;
312
+ edge.currentLoopCount = 0;
313
+ }
314
+ }
315
+ node.aiVerdict = undefined;
316
+ node.actualEngine = undefined;
317
+ node.actualModel = undefined;
228
318
  node.status = "running";
229
319
  node.error = undefined;
230
320
  node.currentAction = `[${node.engine.toUpperCase()}] 正在分配独立环境与工作目录...`;
231
321
  saveCanvasRuntimeState(this.dataDir, graph);
322
+ this.broadcastCanvasRuntime(graph);
232
323
  this.appendLog(graph.id, nodeId, "system", `启动节点「${node.title}」(${node.engine}/${node.model}),工作目录: ${node.cwd || "."}(基准: ${this.pickRunBase(runBase ?? this.runBaseByGraph.get(graph.id))})`);
233
324
  this.broadcast({
234
325
  type: "canvas_node_event",
@@ -237,14 +328,62 @@ export class CanvasOrchestrator {
237
328
  event: "started",
238
329
  currentAction: node.currentAction,
239
330
  });
331
+ let releaseSlot = () => { };
332
+ let releaseCwd = () => { };
333
+ const releaseCapacity = () => {
334
+ releaseSlot();
335
+ releaseCwd();
336
+ };
240
337
  try {
338
+ releaseSlot = await this.executionQueue.acquire(controller.signal);
339
+ if (["cron", "webhook", "memory", "loop"].includes(node.role))
340
+ throw new Error(`Unsupported canvas executor: ${node.role}`);
241
341
  if ((runBase ?? "").trim())
242
342
  this.runBaseByGraph.set(graph.id, runBase);
243
- const resolvedCwd = await this.resolveNodeCwd(node, runBase ?? this.runBaseByGraph.get(graph.id));
244
- if (controller.signal.aborted) {
245
- this.activeExecutions.delete(execKey);
246
- return;
343
+ const upstreamArtifacts = graph.edges
344
+ .filter((e) => e.targetNodeId === node.id && e.active === true)
345
+ .flatMap((e) => {
346
+ const artifact = graph.nodes.find((n) => n.id === e.sourceNodeId)?.artifact;
347
+ const feedback = this.feedbackArtifacts.get(`${graph.id}:${graph.run?.id}:${e.id}`);
348
+ return feedback
349
+ ? [feedback]
350
+ : artifact && artifact.runId === graph.run?.id && artifact.workspace
351
+ ? [artifact.workspace]
352
+ : [];
353
+ });
354
+ if (!node.useWorktree && upstreamArtifacts.length === 0) {
355
+ releaseCwd = await CanvasOrchestrator.sharedWorkspaceQueue.acquire(controller.signal);
247
356
  }
357
+ const workspace = await prepareCanvasWorkspace({
358
+ baseCwd: this.pickRunBase(runBase ?? this.runBaseByGraph.get(graph.id)),
359
+ dataDir: this.dataDir,
360
+ graphId: graph.id,
361
+ runId: graph.run.id,
362
+ nodeId: node.id + "-" + node.attempt,
363
+ cwd: node.cwd,
364
+ useWorktree: node.useWorktree,
365
+ upstreamArtifacts,
366
+ signal: controller.signal,
367
+ });
368
+ const resolvedCwd = workspace.cwd;
369
+ if (!isCurrent())
370
+ return;
371
+ const captureControlArtifact = async () => {
372
+ const workspaceArtifact = workspace.isolated
373
+ ? await captureCanvasWorkspaceArtifact(workspace, { signal: controller.signal })
374
+ : undefined;
375
+ if (!isCurrent())
376
+ return;
377
+ node.artifact = {
378
+ runId: graph.run.id,
379
+ attempt: node.attempt,
380
+ summary: node.lastOutputSummary ?? "",
381
+ text: node.lastOutputSummary,
382
+ cwd: resolvedCwd,
383
+ createdAt: Date.now(),
384
+ workspace: workspaceArtifact,
385
+ };
386
+ };
248
387
  const roleDetail = node.role === "pstack"
249
388
  ? `pstack: ${String(node.config?.skill || "poteto-mode")}`
250
389
  : node.role === "skill"
@@ -259,7 +398,7 @@ export class CanvasOrchestrator {
259
398
  currentAction: node.currentAction,
260
399
  });
261
400
  // 组装前置契约提示词(若上游边有 handoff 产物)
262
- const incomingEdges = graph.edges.filter((e) => e.targetNodeId === nodeId);
401
+ const incomingEdges = graph.edges.filter((e) => e.targetNodeId === nodeId && e.active !== false);
263
402
  let contractContext = "";
264
403
  for (const edge of incomingEdges) {
265
404
  if (edge.lastHandoffSummary) {
@@ -336,8 +475,7 @@ export class CanvasOrchestrator {
336
475
  // AI 条件裁决(config.aiJudge=true):条件节点走一次轻量问答做语义判定,
337
476
  // 只能回“结论:通过/不通过”,下游按它分流;失败回落关键词。未开启还是零 token 透传。
338
477
  const wantAiJudge = (node.role === "ai_judge" || (node.role === "condition" && node.config?.aiJudge === true)) &&
339
- graph.executionMode !== "simulate" &&
340
- !!this.engineGetter;
478
+ graph.executionMode !== "simulate";
341
479
  let judgeModel = node.model;
342
480
  if (wantAiJudge) {
343
481
  const condRef = String(node.config?.condition ?? "").trim() || "上游产物符合预期";
@@ -368,9 +506,16 @@ export class CanvasOrchestrator {
368
506
  node.status = "done";
369
507
  node.currentAction = "格式转换完成(本地执行)";
370
508
  node.lastOutputSummary = transformed;
509
+ await captureControlArtifact();
510
+ if (!isCurrent())
511
+ return;
371
512
  this.appendLog(graph.id, nodeId, "done", transformed.slice(0, 2000));
513
+ if (!isCurrent())
514
+ return;
515
+ releaseCapacity();
372
516
  this.activeExecutions.delete(execKey);
373
517
  saveCanvasRuntimeState(this.dataDir, graph);
518
+ this.broadcastCanvasRuntime(graph);
374
519
  this.broadcast({
375
520
  type: "canvas_node_event",
376
521
  graphId: graph.id,
@@ -379,7 +524,7 @@ export class CanvasOrchestrator {
379
524
  currentAction: node.currentAction,
380
525
  summary: node.lastOutputSummary,
381
526
  });
382
- await this.handleDownstreamEdges(graph, node);
527
+ await this.handleDownstreamEdges(graph, node, undefined, () => lifecycleCurrent() && !controller.signal.aborted);
383
528
  return;
384
529
  }
385
530
  if (!wantAiJudge && isCanvasPassthroughRole(node.role)) {
@@ -389,9 +534,17 @@ export class CanvasOrchestrator {
389
534
  node.currentAction =
390
535
  (node.config?.approvalHint ? String(node.config.approvalHint) + " —— " : "") + "等待人工在抽屉中批准/驳回";
391
536
  node.lastOutputSummary = passthroughSummary;
537
+ await captureControlArtifact();
538
+ if (!isCurrent())
539
+ return;
392
540
  this.appendLog(graph.id, nodeId, "system", "人工审批节点已就绪,等待批准");
541
+ if (!isCurrent())
542
+ return;
543
+ releaseCapacity();
393
544
  this.activeExecutions.delete(execKey);
545
+ this.settleGraph(graph);
394
546
  saveCanvasRuntimeState(this.dataDir, graph);
547
+ this.broadcastCanvasRuntime(graph);
395
548
  this.broadcast({
396
549
  type: "canvas_node_event",
397
550
  graphId: graph.id,
@@ -405,9 +558,16 @@ export class CanvasOrchestrator {
405
558
  node.status = "done";
406
559
  node.currentAction = `控制节点直通 (${node.role})`;
407
560
  node.lastOutputSummary = passthroughSummary;
561
+ await captureControlArtifact();
562
+ if (!isCurrent())
563
+ return;
408
564
  this.appendLog(graph.id, nodeId, "done", passthroughSummary.slice(0, 2000));
565
+ if (!isCurrent())
566
+ return;
567
+ releaseCapacity();
409
568
  this.activeExecutions.delete(execKey);
410
569
  saveCanvasRuntimeState(this.dataDir, graph);
570
+ this.broadcastCanvasRuntime(graph);
411
571
  this.broadcast({
412
572
  type: "canvas_node_event",
413
573
  graphId: graph.id,
@@ -416,12 +576,14 @@ export class CanvasOrchestrator {
416
576
  currentAction: node.currentAction,
417
577
  summary: node.lastOutputSummary,
418
578
  });
419
- await this.handleDownstreamEdges(graph, node);
579
+ await this.handleDownstreamEdges(graph, node, undefined, () => lifecycleCurrent() && !controller.signal.aborted);
420
580
  return;
421
581
  }
422
582
  // 双模调度:真实引擎执行 (Real Engine) vs 拓扑演练演示 (Simulation)
423
- if (graph.executionMode === "simulate" || !this.engineGetter) {
583
+ if (graph.executionMode === "simulate") {
424
584
  await this.simulateNodeExecution(node, resolvedCwd, prompt, controller.signal, (action) => {
585
+ if (!isCurrent())
586
+ return;
425
587
  node.currentAction = action;
426
588
  this.broadcast({
427
589
  type: "canvas_node_event",
@@ -439,6 +601,8 @@ export class CanvasOrchestrator {
439
601
  node.model = judgeModel;
440
602
  try {
441
603
  outputSummary = await this.executeRealEngineNode(graph, node, resolvedCwd, prompt, controller.signal, (action) => {
604
+ if (!isCurrent())
605
+ return;
442
606
  node.currentAction = action;
443
607
  this.broadcast({
444
608
  type: "canvas_node_event",
@@ -453,10 +617,22 @@ export class CanvasOrchestrator {
453
617
  node.model = savedModel;
454
618
  }
455
619
  }
456
- if (controller.signal.aborted) {
457
- this.activeExecutions.delete(execKey);
620
+ if (!isCurrent())
458
621
  return;
459
- }
622
+ const workspaceArtifact = workspace.isolated
623
+ ? await captureCanvasWorkspaceArtifact(workspace, { signal: controller.signal })
624
+ : undefined;
625
+ if (!isCurrent())
626
+ return;
627
+ node.artifact = {
628
+ runId: graph.run.id,
629
+ attempt: node.attempt,
630
+ summary: outputSummary,
631
+ text: outputSummary,
632
+ cwd: workspace.cwd,
633
+ createdAt: Date.now(),
634
+ workspace: workspaceArtifact,
635
+ };
460
636
  // 节点完成
461
637
  node.status = "done";
462
638
  node.currentAction = `已完成 (${node.engine.toUpperCase()})`;
@@ -467,13 +643,19 @@ export class CanvasOrchestrator {
467
643
  ];
468
644
  const last = hits.length > 0 ? String(hits[hits.length - 1][1]).toLowerCase() : "";
469
645
  node.aiVerdict = last ? ["通过", "成立", "是", "真", "true", "yes"].includes(last) : undefined;
646
+ if (node.aiVerdict === undefined)
647
+ throw new Error("AI judge returned no explicit decision");
470
648
  this.appendLog(graph.id, nodeId, "system", node.aiVerdict === undefined
471
649
  ? "AI 裁决未给出有效结论(默认走不成立边)。"
472
650
  : `AI 裁决结论:${node.aiVerdict ? "通过" : "不通过"}(独立判定,未混入关键词)。`);
473
651
  }
474
652
  this.appendLog(graph.id, nodeId, "done", outputSummary.slice(0, 2000));
653
+ if (!isCurrent())
654
+ return;
655
+ releaseCapacity();
475
656
  this.activeExecutions.delete(execKey);
476
657
  saveCanvasRuntimeState(this.dataDir, graph);
658
+ this.broadcastCanvasRuntime(graph);
477
659
  this.broadcast({
478
660
  type: "canvas_node_event",
479
661
  graphId: graph.id,
@@ -483,20 +665,23 @@ export class CanvasOrchestrator {
483
665
  summary: node.lastOutputSummary,
484
666
  });
485
667
  // 触发下游交接或审查
486
- await this.handleDownstreamEdges(graph, node);
668
+ await this.handleDownstreamEdges(graph, node, undefined, () => lifecycleCurrent() && !controller.signal.aborted);
487
669
  }
488
670
  catch (err) {
489
- if (controller.signal.aborted) {
490
- this.activeExecutions.delete(execKey);
671
+ if (!lifecycleCurrent() || controller.signal.aborted)
491
672
  return;
492
- }
493
673
  const msg = err.message || String(err);
494
674
  node.status = "error";
495
675
  node.error = msg;
496
676
  node.currentAction = `执行出错: ${msg}`;
497
677
  this.appendLog(graph.id, node.id, "error", msg.slice(0, 2000));
678
+ if (!lifecycleCurrent() || controller.signal.aborted)
679
+ return;
680
+ releaseCapacity();
498
681
  this.activeExecutions.delete(execKey);
682
+ this.settleGraph(graph);
499
683
  saveCanvasRuntimeState(this.dataDir, graph);
684
+ this.broadcastCanvasRuntime(graph);
500
685
  this.broadcast({
501
686
  type: "canvas_node_event",
502
687
  graphId: graph.id,
@@ -506,115 +691,218 @@ export class CanvasOrchestrator {
506
691
  error: msg,
507
692
  });
508
693
  }
694
+ finally {
695
+ releaseCapacity();
696
+ }
509
697
  }
510
- /** 运行全图(从所有入度为 0 的根节点,或者未完成节点并发拉起) */
698
+ /** Start a fresh run; active and approval-paused runs must be resolved first. */
511
699
  async runAll(graph, initialPrompt, runBase) {
512
- this.runningGraphs.set(graph.id, graph);
700
+ if (!fsExistsSync(pathJoin(this.dataDir, "canvas", `${graph.id}.json`)))
701
+ return;
702
+ const current = this.runningGraphs.get(graph.id);
703
+ if (current && ["running", "waiting_approval"].includes(current.status))
704
+ throw new Error("Canvas graph already running");
705
+ if ([...this.activeExecutions.values()].some((e) => e.graphId === graph.id))
706
+ throw new Error("Canvas graph already running");
707
+ validateCanvasTopology(graph);
708
+ for (const key of this.feedbackArtifacts.keys())
709
+ if (key.startsWith(`${graph.id}:`))
710
+ this.feedbackArtifacts.delete(key);
711
+ this.graphGenerations.set(graph.id, (this.graphGenerations.get(graph.id) ?? 0) + 1);
712
+ graph.run = { id: randomUUID(), graphRev: graph.rev ?? 0, startedAt: Date.now(), scope: "all" };
513
713
  graph.status = "running";
514
- saveCanvasRuntimeState(this.dataDir, graph);
515
- // 找到没有入边或当前状态为 idle/error 的起点节点
516
- const targetNodes = new Set(graph.nodes.map((n) => n.id));
517
- for (const edge of graph.edges) {
518
- targetNodes.delete(edge.targetNodeId);
519
- }
520
- let startNodes = graph.nodes.filter((n) => targetNodes.has(n.id));
521
- if (startNodes.length === 0) {
522
- startNodes = graph.nodes.filter((n) => n.status === "idle" || n.status === "error");
714
+ for (const node of graph.nodes) {
715
+ node.status = "idle";
716
+ node.error = undefined;
717
+ node.currentAction = undefined;
718
+ node.lastOutputSummary = undefined;
719
+ node.artifact = undefined;
720
+ node.aiVerdict = undefined;
721
+ node.runId = graph.run.id;
722
+ node.attempt = 0;
723
+ node.actualEngine = undefined;
724
+ node.actualModel = undefined;
523
725
  }
524
- if (startNodes.length === 0 && graph.nodes.length > 0) {
525
- startNodes = [graph.nodes[0]];
726
+ for (const edge of graph.edges) {
727
+ edge.active = undefined;
728
+ edge.runId = graph.run.id;
729
+ edge.lastHandoffSummary = undefined;
730
+ edge.currentLoopCount = 0;
526
731
  }
732
+ this.runningGraphs.set(graph.id, graph);
733
+ this.armRunDeadline(graph);
527
734
  if ((runBase ?? "").trim())
528
735
  this.runBaseByGraph.set(graph.id, runBase);
529
- await Promise.all(startNodes.map((n) => this.runNode(graph, n.id, initialPrompt, runBase)));
736
+ saveCanvasRuntimeState(this.dataDir, graph);
737
+ this.broadcastCanvasRuntime(graph);
738
+ const roots = graph.nodes.filter((n) => !graph.edges.some((e) => e.targetNodeId === n.id && !isCanvasBackedge(e)));
739
+ const generation = this.graphGenerations.get(graph.id);
740
+ await Promise.all(roots.map((n) => this.runNode(graph, n.id, initialPrompt, runBase, true)));
741
+ if (this.graphGenerations.get(graph.id) !== generation || this.runningGraphs.get(graph.id) !== graph)
742
+ return;
743
+ this.settleGraph(graph);
744
+ saveCanvasRuntimeState(this.dataDir, graph);
745
+ this.broadcastCanvasRuntime(graph);
530
746
  }
531
- /** 处理节点完成后的下游连线流转 */
532
- async handleDownstreamEdges(graph, completedNode, via) {
533
- let outEdges = graph.edges.filter((e) => e.sourceNodeId === completedNode.id);
534
- if (via === "approve") {
535
- // 人工批准只走批准/主线边,不触发驳回回路边(reject / loop_back / review)
536
- outEdges = outEdges.filter((e) => e.type !== "reject" && e.type !== "loop_back" && e.type !== "review");
747
+ /** A node run owns the reachable subgraph, including explicitly requested rework. */
748
+ runNodes(graph) {
749
+ if (graph.run?.scope !== "node" || !graph.run.nodeId)
750
+ return graph.nodes;
751
+ const ids = new Set();
752
+ const visit = (id) => {
753
+ if (ids.has(id))
754
+ return;
755
+ ids.add(id);
756
+ for (const edge of graph.edges)
757
+ if (edge.sourceNodeId === id)
758
+ visit(edge.targetNodeId);
759
+ };
760
+ visit(graph.run.nodeId);
761
+ return graph.nodes.filter((n) => ids.has(n.id));
762
+ }
763
+ settleGraph(graph) {
764
+ const scoped = this.runNodes(graph);
765
+ if (scoped.some((n) => n.status === "error"))
766
+ graph.status = "error";
767
+ else if (scoped.some((n) => n.status === "waiting_approval"))
768
+ graph.status = "waiting_approval";
769
+ else if (scoped.some((n) => n.status === "running"))
770
+ graph.status = "running";
771
+ else if (scoped.every((n) => n.status === "done" || n.status === "skipped"))
772
+ graph.status = "completed";
773
+ else
774
+ graph.status = "blocked";
775
+ if (graph.run &&
776
+ ["completed", "error", "blocked"].includes(graph.status) &&
777
+ !scoped.some((n) => n.status === "running" || n.status === "waiting_approval")) {
778
+ clearTimeout(this.runDeadlines.get(graph.id));
779
+ this.runDeadlines.delete(graph.id);
780
+ graph.run.finishedAt = Date.now();
781
+ graph.run.error = scoped.find((n) => n.error)?.error;
537
782
  }
538
- if (completedNode.role === "condition" || completedNode.role === "ai_judge") {
539
- const aiMode = completedNode.role === "ai_judge" || completedNode.config?.aiJudge === true;
540
- const condText = String(completedNode.config?.condition ?? "");
541
- const upstreamText = graph.edges
542
- .filter((e) => e.targetNodeId === completedNode.id)
543
- .map((e) => e.lastHandoffSummary ?? "")
544
- .join("\n") ||
545
- completedNode.lastOutputSummary ||
546
- "";
547
- const summary = upstreamText;
548
- const tokens = condText
549
- .split(/[\s,\uFF0C\u3001/()\u2014\u2014]+/)
550
- .map((t) => t.trim())
551
- .filter((t) => t.length >= 2);
552
- const hit = aiMode
553
- ? completedNode.aiVerdict === true
554
- : tokens.length === 0
555
- ? true
556
- : tokens.some((t) => summary.includes(t));
557
- if (aiMode) {
558
- this.appendLog(graph.id, completedNode.id, "system", `分支:${hit ? "成立边" : "不成立边"}(AI 独立裁决${completedNode.aiVerdict === undefined ? ",无结论默认不成立" : ""})。`);
783
+ }
784
+ async handleDownstreamEdges(graph, completedNode, via, lifecycleCurrent = () => true) {
785
+ const generation = this.graphGenerations.get(graph.id) ?? 0;
786
+ const isCurrent = () => lifecycleCurrent() &&
787
+ (this.graphGenerations.get(graph.id) ?? 0) === generation &&
788
+ this.runningGraphs.get(graph.id) === graph &&
789
+ fsExistsSync(pathJoin(this.dataDir, "canvas", `${graph.id}.json`));
790
+ if (!isCurrent())
791
+ return;
792
+ completedNode.artifact = {
793
+ ...completedNode.artifact,
794
+ runId: graph.run?.id ?? "",
795
+ attempt: completedNode.attempt ?? 1,
796
+ summary: completedNode.lastOutputSummary ?? "",
797
+ text: completedNode.lastOutputSummary,
798
+ cwd: completedNode.artifact?.cwd ?? completedNode.cwd,
799
+ createdAt: completedNode.artifact?.createdAt ?? Date.now(),
800
+ };
801
+ const conditional = completedNode.role === "condition" || completedNode.role === "ai_judge";
802
+ const hit = conditional ? canvasCondition(completedNode, graph) : undefined;
803
+ const decision = via ?? (conditional ? (hit ? "approve" : "reject") : undefined);
804
+ const rework = [];
805
+ for (const edge of graph.edges.filter((e) => e.sourceNodeId === completedNode.id)) {
806
+ const back = isCanvasBackedge(edge);
807
+ const selected = back
808
+ ? decision === "reject"
809
+ : via !== "reject" &&
810
+ (edge.type === "approve"
811
+ ? via === "approve" || (conditional && hit === true)
812
+ : edge.type === "condition_true"
813
+ ? hit === true
814
+ : edge.type === "condition_false"
815
+ ? hit === false
816
+ : true);
817
+ edge.runId = graph.run?.id;
818
+ edge.active = selected;
819
+ edge.lastHandoffSummary = selected ? completedNode.artifact.text : undefined;
820
+ if (selected)
821
+ this.appendLog(graph.id, edge.targetNodeId, "handoff", `收到来自「${completedNode.title}」的交接:${edge.lastHandoffSummary ?? ""}`);
822
+ if (!selected || !back)
823
+ continue;
824
+ if ((edge.currentLoopCount ?? 0) >= (edge.maxLoopRetries ?? 3)) {
825
+ completedNode.status = "waiting_approval";
826
+ completedNode.currentAction = "已达审查重试上限,等待人工仲裁";
827
+ continue;
559
828
  }
560
- outEdges = outEdges.filter((e) => {
561
- if (e.type === "condition_true")
562
- return hit;
563
- if (e.type === "condition_false")
564
- return !hit;
565
- return true;
566
- });
567
- this.appendLog(graph.id, completedNode.id, "system", "条件分支判定:" + (hit ? "成立,走 true 边" : "不成立,走 false 边"));
829
+ const feedbackKey = `${graph.id}:${graph.run?.id}:${edge.id}`;
830
+ if (completedNode.artifact.workspace)
831
+ this.feedbackArtifacts.set(feedbackKey, completedNode.artifact.workspace);
832
+ else
833
+ this.feedbackArtifacts.delete(feedbackKey);
834
+ edge.currentLoopCount = (edge.currentLoopCount ?? 0) + 1;
835
+ const target = graph.nodes.find((n) => n.id === edge.targetNodeId);
836
+ if (target && !rework.includes(target))
837
+ rework.push(target);
568
838
  }
569
- for (const edge of outEdges) {
570
- edge.lastHandoffSummary = completedNode.lastOutputSummary;
571
- if (edge.type === "review" || edge.type === "loop_back" || edge.type === "reject") {
572
- // 审查回路:检查是否超出最大驳回重试次数
573
- const maxRetries = edge.maxLoopRetries ?? 3;
574
- const current = edge.currentLoopCount ?? 0;
575
- if (current >= maxRetries) {
576
- // 达到熔断上限,暂停并等待人工介入
577
- completedNode.status = "waiting_approval";
578
- completedNode.currentAction = `已达审查重试上限 (${maxRetries} 次),暂停等待人工仲裁确认`;
579
- saveCanvasRuntimeState(this.dataDir, graph);
580
- this.broadcast({
581
- type: "canvas_node_event",
582
- graphId: graph.id,
583
- nodeId: completedNode.id,
584
- event: "paused",
585
- currentAction: completedNode.currentAction,
586
- });
587
- continue;
588
- }
589
- edge.currentLoopCount = current + 1;
590
- }
591
- // 触发下游目标节点
592
- const targetNode = graph.nodes.find((n) => n.id === edge.targetNodeId);
593
- if (targetNode) {
594
- this.appendLog(graph.id, targetNode.id, "handoff", `收到来自「${completedNode.title}」的交接${edge.label ? `(${edge.label})` : ""}:${(edge.lastHandoffSummary || "").slice(0, 1500)}`);
595
- }
596
- if (targetNode) {
597
- const execKey = graph.id + ":" + targetNode.id;
598
- if (targetNode.status === "running" || this.activeExecutions.has(execKey))
599
- continue;
600
- const upstreamIds = graph.edges.filter((e) => e.targetNodeId === targetNode.id).map((e) => e.sourceNodeId);
601
- const allUpstreamDone = upstreamIds.every((uid) => graph.nodes.find((n) => n.id === uid)?.status === "done");
602
- if (!via && !allUpstreamDone)
603
- continue; // 人工批准直放(via=approve)不受合流门限制
604
- targetNode.status = "running";
605
- void this.runNode(graph, targetNode.id, undefined, this.runBaseByGraph.get(graph.id));
839
+ if (via === "reject" && rework.length === 0 && completedNode.status !== "waiting_approval") {
840
+ completedNode.status = "waiting_approval";
841
+ completedNode.currentAction = "Rejection requires a configured rework edge";
842
+ }
843
+ // Reset the forward rework region, retaining the feedback contract and retry counts.
844
+ const reset = (id, seen = new Set()) => {
845
+ if (seen.has(id))
846
+ return;
847
+ seen.add(id);
848
+ const node = graph.nodes.find((n) => n.id === id);
849
+ if (this.activeExecutions.has(graph.id + ":" + id))
850
+ this.stopNode(graph.id, id);
851
+ node.status = "idle";
852
+ node.error = undefined;
853
+ node.artifact = undefined;
854
+ node.lastOutputSummary = undefined;
855
+ node.aiVerdict = undefined;
856
+ for (const edge of graph.edges.filter((e) => e.sourceNodeId === id && !isCanvasBackedge(e))) {
857
+ edge.active = undefined;
858
+ edge.lastHandoffSummary = undefined;
859
+ reset(edge.targetNodeId, seen);
606
860
  }
861
+ };
862
+ for (const target of rework)
863
+ reset(target.id);
864
+ const scheduled = [];
865
+ for (const target of rework) {
866
+ if (!isCurrent())
867
+ return;
868
+ scheduled.push(this.runNode(graph, target.id, undefined, this.runBaseByGraph.get(graph.id), true));
607
869
  }
608
- // 检查图上所有节点是否都已经到达完成状态
609
- const allDone = graph.nodes.every((n) => n.status === "done");
610
- if (allDone) {
611
- graph.status = "completed";
612
- saveCanvasRuntimeState(this.dataDir, graph);
870
+ // Resolve skipped branches to a fixed point before scheduling joins.
871
+ let changed = true;
872
+ while (changed) {
873
+ changed = false;
874
+ for (const node of this.runNodes(graph))
875
+ if (node.status === "idle" && canvasReadiness(graph, node) === "skip") {
876
+ node.status = "skipped";
877
+ changed = true;
878
+ for (const edge of graph.edges.filter((e) => e.sourceNodeId === node.id && !isCanvasBackedge(e))) {
879
+ edge.active = false;
880
+ edge.lastHandoffSummary = undefined;
881
+ }
882
+ }
613
883
  }
884
+ for (const node of this.runNodes(graph)) {
885
+ if (!isCurrent())
886
+ return;
887
+ if (node.status === "idle" &&
888
+ graph.edges.some((e) => e.targetNodeId === node.id && !isCanvasBackedge(e) && e.active === true) &&
889
+ canvasReadiness(graph, node) === "ready")
890
+ scheduled.push(this.runNode(graph, node.id, undefined, this.runBaseByGraph.get(graph.id), true));
891
+ }
892
+ this.settleGraph(graph);
893
+ saveCanvasRuntimeState(this.dataDir, graph);
894
+ this.broadcastCanvasRuntime(graph);
895
+ await Promise.all(scheduled);
896
+ if (!isCurrent())
897
+ return;
898
+ this.settleGraph(graph);
899
+ saveCanvasRuntimeState(this.dataDir, graph);
900
+ this.broadcastCanvasRuntime(graph);
614
901
  }
615
902
  /** 停止单个节点 */
616
903
  stopNode(graphId, nodeId) {
617
904
  const execKey = `${graphId}:${nodeId}`;
905
+ this.nodeGenerations.set(execKey, (this.nodeGenerations.get(execKey) ?? 0) + 1);
618
906
  const execution = this.activeExecutions.get(execKey);
619
907
  if (execution) {
620
908
  execution.abortController?.abort();
@@ -624,10 +912,12 @@ export class CanvasOrchestrator {
624
912
  if (graph) {
625
913
  const node = graph.nodes.find((n) => n.id === nodeId);
626
914
  if (node) {
627
- node.status = "idle";
915
+ node.status = "cancelled";
628
916
  node.currentAction = "已手动中止";
917
+ this.settleGraph(graph);
629
918
  this.appendLog(graphId, nodeId, "system", "已手动中止当前任务");
630
919
  saveCanvasRuntimeState(this.dataDir, graph);
920
+ this.broadcastCanvasRuntime(graph);
631
921
  this.broadcast({
632
922
  type: "canvas_node_event",
633
923
  graphId,
@@ -640,6 +930,9 @@ export class CanvasOrchestrator {
640
930
  }
641
931
  /** 停止全图所有正在运行的节点 */
642
932
  stopAll(graphId) {
933
+ clearTimeout(this.runDeadlines.get(graphId));
934
+ this.runDeadlines.delete(graphId);
935
+ this.graphGenerations.set(graphId, (this.graphGenerations.get(graphId) ?? 0) + 1);
643
936
  this.runBaseByGraph.delete(graphId);
644
937
  for (const [key, execution] of this.activeExecutions.entries()) {
645
938
  if (execution.graphId === graphId) {
@@ -649,14 +942,17 @@ export class CanvasOrchestrator {
649
942
  }
650
943
  const graph = this.runningGraphs.get(graphId);
651
944
  if (graph) {
652
- graph.status = "idle";
945
+ graph.status = "paused";
946
+ if (graph.run)
947
+ graph.run.finishedAt = Date.now();
653
948
  for (const node of graph.nodes) {
654
- if (node.status === "running") {
655
- node.status = "idle";
949
+ if (["running", "idle", "waiting_approval"].includes(node.status)) {
950
+ node.status = "cancelled";
656
951
  node.currentAction = "已手动中止";
657
952
  }
658
953
  }
659
954
  saveCanvasRuntimeState(this.dataDir, graph);
955
+ this.broadcastCanvasRuntime(graph);
660
956
  }
661
957
  }
662
958
  /** 审查门禁裁决(#707):批准/驳回落盘持久化并广播;执行中的节点同步收到审查意见 */
@@ -675,17 +971,22 @@ export class CanvasOrchestrator {
675
971
  const node = graph.nodes.find((n) => n.id === nodeId);
676
972
  if (!node)
677
973
  return null;
678
- const cleanComment = (comment ?? "").slice(0, 500);
974
+ if (node.status !== "waiting_approval")
975
+ return null;
976
+ const cleanComment = (comment ?? "").trim();
977
+ node.lastOutputSummary = `${node.lastOutputSummary ?? ""}\n${decision === "reject" ? "Rework requested" : "Approved"}: ${cleanComment}`;
978
+ graph.status = "running";
679
979
  if (decision === "approve") {
680
980
  node.status = "done";
681
981
  node.currentAction = cleanComment ? `人工审查批准合流:${cleanComment}` : "人工审查批准合流";
682
982
  }
683
983
  else {
684
- node.status = "waiting_approval";
984
+ node.status = "done";
685
985
  node.currentAction = cleanComment ? `人工驳回:${cleanComment}` : "人工驳回:需补充完善测试与注释";
686
986
  }
687
987
  graph.updatedAt = Date.now();
688
988
  saveCanvasRuntimeState(this.dataDir, graph);
989
+ this.broadcastCanvasRuntime(graph);
689
990
  this.runningGraphs.set(graphId, graph);
690
991
  this.appendLog(graphId, nodeId, "review", `${decision === "approve" ? "人工审查批准合流" : "人工驳回"}${cleanComment ? `:${cleanComment}` : ""}`);
691
992
  // 执行中的节点同步收到审查意见(复用节点事件通道,currentAction 即裁决正文)
@@ -699,9 +1000,13 @@ export class CanvasOrchestrator {
699
1000
  summary: node.lastOutputSummary,
700
1001
  });
701
1002
  }
702
- if (decision === "approve") {
703
- void this.handleDownstreamEdges(graph, node, "approve");
704
- }
1003
+ void this.handleDownstreamEdges(graph, node, decision).catch((error) => {
1004
+ node.status = "error";
1005
+ node.error = String(error);
1006
+ this.settleGraph(graph);
1007
+ saveCanvasRuntimeState(this.dataDir, graph);
1008
+ this.broadcastCanvasRuntime(graph);
1009
+ });
705
1010
  return graph;
706
1011
  }
707
1012
  /** 向节点插话干预 (Steer) */
@@ -721,6 +1026,7 @@ export class CanvasOrchestrator {
721
1026
  return;
722
1027
  node.currentAction = `[收到人工插话指导]: ${message.slice(0, 40)}`;
723
1028
  saveCanvasRuntimeState(this.dataDir, graph);
1029
+ this.broadcastCanvasRuntime(graph);
724
1030
  this.appendLog(graphId, nodeId, "steer", message.slice(0, 2000));
725
1031
  this.broadcast({
726
1032
  type: "canvas_node_event",
@@ -735,9 +1041,13 @@ export class CanvasOrchestrator {
735
1041
  if (execution?.session && typeof execution.session.prompt === "function") {
736
1042
  try {
737
1043
  await execution.session.prompt(message);
1044
+ if (execution.abortController?.signal.aborted || this.activeExecutions.get(execKey) !== execution)
1045
+ return;
738
1046
  this.appendLog(graphId, nodeId, "system", "已将插话实时投递进正在运行的智能体会话。");
739
1047
  }
740
1048
  catch (err) {
1049
+ if (execution.abortController?.signal.aborted || this.activeExecutions.get(execKey) !== execution)
1050
+ return;
741
1051
  const errMsg = err instanceof Error ? err.message : String(err);
742
1052
  this.appendLog(graphId, nodeId, "error", `插话投递底层会话失败: ${errMsg}`);
743
1053
  }
@@ -767,6 +1077,7 @@ export class CanvasOrchestrator {
767
1077
  edge.lastHandoffSummary = undefined;
768
1078
  }
769
1079
  saveCanvasRuntimeState(this.dataDir, graph);
1080
+ this.broadcastCanvasRuntime(graph);
770
1081
  }
771
1082
  /** 节点执行过程模拟与调度心跳(具备取消信号响应) */
772
1083
  async simulateNodeExecution(node, _cwd, _prompt, signal, onAction) {
@@ -795,11 +1106,7 @@ export class CanvasOrchestrator {
795
1106
  if (!this.engineGetter) {
796
1107
  throw new Error("引擎服务提供者未注入");
797
1108
  }
798
- let engineSvc = this.engineGetter(node.engine);
799
- if (!engineSvc && node.engine !== "pi") {
800
- engineSvc = this.engineGetter("pi");
801
- this.appendLog(graph.id, node.id, "system", `引擎 ${node.engine} 不可用,已自动切换为 Pi 原生引擎。`);
802
- }
1109
+ const engineSvc = this.engineGetter(node.engine);
803
1110
  if (!engineSvc) {
804
1111
  throw new Error(`找不到智能体引擎:${node.engine}`);
805
1112
  }
@@ -831,6 +1138,8 @@ export class CanvasOrchestrator {
831
1138
  if (messages.length > 0)
832
1139
  this.pushNodeMessages(graph.id, node.id, messages);
833
1140
  for (const m of messages) {
1141
+ if (signal.aborted)
1142
+ return;
834
1143
  if (m.toolName) {
835
1144
  const tid = m.toolCallId || `${m.toolName}:${m.id}`;
836
1145
  if (!seenToolIds.has(tid)) {
@@ -851,38 +1160,32 @@ export class CanvasOrchestrator {
851
1160
  }
852
1161
  }
853
1162
  };
854
- const cs = await engineSvc.attach(clientId, sink);
855
1163
  const execKey = `${graph.id}:${node.id}`;
856
1164
  const execution = this.activeExecutions.get(execKey);
857
- if (execution) {
1165
+ const cs = await engineSvc.attach(clientId, sink);
1166
+ const checkCurrent = () => {
1167
+ if (signal.aborted || this.activeExecutions.get(execKey) !== execution)
1168
+ throw new Error("任务已被手动中止");
1169
+ };
1170
+ if (!signal.aborted && this.activeExecutions.get(execKey) === execution && execution) {
858
1171
  execution.session = cs;
859
1172
  }
860
1173
  try {
1174
+ checkCurrent();
861
1175
  if (cs.cwd !== resolvedCwd) {
862
1176
  await cs.setCwd(resolvedCwd);
863
1177
  }
1178
+ checkCurrent();
864
1179
  // 真实应用模型切换(若模型不存在或 Key 无效,真实报错)
865
1180
  // 归一化双前缀:历史存量可能是 opencode-go/opencode-go/xxx,压成 opencode-go/xxx 再切换。
866
- if (node.model && typeof cs.switchModelOrThrow === "function") {
867
- try {
868
- await cs.switchModelOrThrow(normalizeCanvasModelId(node.model));
869
- }
870
- catch (err) {
871
- // 尝试安全回退到当前引擎默认可用模型,避免特定模型未配置导致整张画布崩溃
872
- let fallbackOk = false;
873
- if (typeof cs.switchModel === "function") {
874
- try {
875
- await cs.switchModel("");
876
- fallbackOk = true;
877
- this.appendLog(graph.id, node.id, "system", `指定模型 [${node.model}] 不可用,已自动回落至引擎默认模型。`);
878
- }
879
- catch { }
880
- }
881
- if (!fallbackOk) {
882
- throw new Error(`模型未配置或不可用 [${node.model}]: ${err.message}`);
883
- }
884
- }
1181
+ if (node.model) {
1182
+ if (typeof cs.switchModelOrThrow !== "function")
1183
+ throw new Error(`Engine cannot select model: ${node.model}`);
1184
+ await cs.switchModelOrThrow(normalizeCanvasModelId(node.model));
885
1185
  }
1186
+ node.actualEngine = node.engine;
1187
+ node.actualModel = node.model;
1188
+ checkCurrent();
886
1189
  // 真实应用思考强度
887
1190
  if (node.thinkingLevel && typeof cs.setThinking === "function") {
888
1191
  try {
@@ -898,7 +1201,20 @@ export class CanvasOrchestrator {
898
1201
  baselineMsgIds.add(m.id);
899
1202
  const baselineMsgCount = preRunMsgs.length;
900
1203
  captureErrors = true;
901
- await cs.prompt(prompt);
1204
+ const abortSession = () => {
1205
+ void Promise.resolve()
1206
+ .then(() => cs.abort())
1207
+ .catch(() => { });
1208
+ };
1209
+ signal.addEventListener("abort", abortSession, { once: true });
1210
+ try {
1211
+ checkCurrent();
1212
+ await cs.prompt(prompt);
1213
+ }
1214
+ finally {
1215
+ signal.removeEventListener("abort", abortSession);
1216
+ }
1217
+ checkCurrent();
902
1218
  // 等待执行完成(带超时和取消监听)
903
1219
  const startTime = Date.now();
904
1220
  const maxWaitMs = 15 * 60 * 1000;
@@ -932,6 +1248,7 @@ export class CanvasOrchestrator {
932
1248
  throw new Error("任务执行超时 (15分钟)");
933
1249
  }
934
1250
  }
1251
+ checkCurrent();
935
1252
  // 真实检测代码变更统计(仅本地项目支持本地 git diff)
936
1253
  let diffSummary = "";
937
1254
  try {
@@ -952,7 +1269,7 @@ export class CanvasOrchestrator {
952
1269
  // 旧逻辑于是把下游交接内容写成「交付完成(未产生文件修改)」的占位文案)
953
1270
  const replyText = (collectedText.trim() || extractRunReplyText(canvasSnapshotMessages(cs).slice(baselineMsgCount))).trim();
954
1271
  if (replyText)
955
- return `${replyText.slice(-300)}${diffSummary}`;
1272
+ return `${replyText}${diffSummary}`;
956
1273
  return `[${node.title}] 交付完成${diffSummary || "(未产生文件修改)"}`;
957
1274
  }
958
1275
  finally {
@@ -1092,7 +1409,7 @@ function buildPassthroughSummary(node, contractContext, initialPrompt) {
1092
1409
  .map(([k, v]) => `${k}=${String(v)}`)
1093
1410
  .slice(0, 8)
1094
1411
  .join(";");
1095
- const contract = contractContext ? contractContext.slice(0, 1500) : "(无上游输入,直接透传)";
1412
+ const contract = contractContext ? contractContext : "(无上游输入,直接透传)";
1096
1413
  switch (node.role) {
1097
1414
  case "condition":
1098
1415
  return `【条件分支 ${node.title}】判定配置:${cfgText || "未配置表达式,默认走 true 边"}\n透传上游产物:\n${contract}`;
@@ -1103,12 +1420,12 @@ function buildPassthroughSummary(node, contractContext, initialPrompt) {
1103
1420
  case "trigger": {
1104
1421
  const popup = (initialPrompt ?? "").trim();
1105
1422
  const payload = popup || String(cfg["payload"] ?? "").trim() || String(node.instruction ?? "").trim();
1106
- const extra = contractContext ? contractContext.slice(0, 1000) : "";
1423
+ const extra = contractContext || "";
1107
1424
  if (payload)
1108
1425
  return ("【手动触发 · 业务需求输入 " +
1109
1426
  node.title +
1110
1427
  "】任务内容:\n" +
1111
- payload.slice(0, 1500) +
1428
+ payload +
1112
1429
  (extra ? "\n上游输入:\n" + extra : ""));
1113
1430
  return ("【手动触发 · 业务需求输入 " + node.title + "】" + (extra ? "上游输入:\n" + extra : "(无载荷,直接启动)"));
1114
1431
  }