pi-web-ui 0.113.1 → 0.114.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +187 -316
  3. package/README.zh-CN.md +227 -299
  4. package/README.zh-TW.md +227 -299
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -0
  8. package/bin/pi-web-ui.mjs +4081 -4041
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service-daemon.js +102 -24
  12. package/dist/server/agent-service.js +2419 -1174
  13. package/dist/server/approval-rules.js +29 -3
  14. package/dist/server/ask-user-question-tool.js +8 -8
  15. package/dist/server/atomic-file.js +35 -14
  16. package/dist/server/attachment-store.js +71 -35
  17. package/dist/server/attachments.js +69 -13
  18. package/dist/server/canvas/canvas-agent-tool.js +68 -18
  19. package/dist/server/canvas/canvas-cards.js +1 -1
  20. package/dist/server/canvas/canvas-dispatch.js +61 -20
  21. package/dist/server/canvas/canvas-orchestrator.js +519 -202
  22. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  23. package/dist/server/canvas/canvas-scheduler.js +99 -0
  24. package/dist/server/canvas/canvas-store.js +107 -54
  25. package/dist/server/canvas/canvas-validation.js +131 -0
  26. package/dist/server/canvas/canvas-workspace.js +284 -0
  27. package/dist/server/client-id-utils.js +8 -0
  28. package/dist/server/client-state.js +110 -24
  29. package/dist/server/communicate-tool.js +76 -0
  30. package/dist/server/compact-context-tool.js +2 -3
  31. package/dist/server/compaction-instructions.js +75 -0
  32. package/dist/server/compaction-markers.js +7 -2
  33. package/dist/server/compaction-state.js +84 -0
  34. package/dist/server/composer-drafts.js +43 -40
  35. package/dist/server/context-evidence.js +346 -0
  36. package/dist/server/conversation-communication.js +368 -0
  37. package/dist/server/conversation-read-tool.js +3 -4
  38. package/dist/server/conversation-tool-names.js +14 -0
  39. package/dist/server/conversation-tool.js +57 -0
  40. package/dist/server/delegate-mode.js +17 -4
  41. package/dist/server/device-center/bot-catalog.js +88 -0
  42. package/dist/server/device-center/bot-execution.js +106 -0
  43. package/dist/server/device-center/bots.js +170 -0
  44. package/dist/server/device-center/collab-service.js +153 -0
  45. package/dist/server/device-center/collab-tool.js +184 -0
  46. package/dist/server/device-center/connector.js +351 -0
  47. package/dist/server/device-center/desktop-linux.js +372 -0
  48. package/dist/server/device-center/desktop-native.js +413 -0
  49. package/dist/server/device-center/desktop-page.js +232 -0
  50. package/dist/server/device-center/desktop-setup.js +30 -0
  51. package/dist/server/device-center/desktop.js +387 -0
  52. package/dist/server/device-center/device-portals.js +241 -0
  53. package/dist/server/device-center/execution-failure.js +70 -0
  54. package/dist/server/device-center/executor.js +371 -0
  55. package/dist/server/device-center/file-sync.js +493 -0
  56. package/dist/server/device-center/hub-auth.js +69 -0
  57. package/dist/server/device-center/hub-page.js +68 -0
  58. package/dist/server/device-center/hub-setup.js +214 -0
  59. package/dist/server/device-center/hub.js +830 -0
  60. package/dist/server/device-center/local-hub.js +92 -0
  61. package/dist/server/device-center/local.js +529 -0
  62. package/dist/server/device-center/main.js +118 -0
  63. package/dist/server/device-center/native-desktop/macos.js +192 -0
  64. package/dist/server/device-center/native-desktop/windows.js +118 -0
  65. package/dist/server/device-center/path-portal.js +120 -0
  66. package/dist/server/device-center/relay.js +996 -0
  67. package/dist/server/device-center/runtime.js +253 -0
  68. package/dist/server/device-center/store.js +122 -0
  69. package/dist/server/device-center/task-error.js +14 -0
  70. package/dist/server/device-center/transfers.js +293 -0
  71. package/dist/server/device-center/workspaces.js +45 -0
  72. package/dist/server/dispatch-domain-handlers.js +84 -27
  73. package/dist/server/dsh/dsh-agent-service.js +282 -159
  74. package/dist/server/dsh/dsh-client.js +12 -2
  75. package/dist/server/dsh/runtime/cordis.yml +1 -1
  76. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  77. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  78. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  79. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  80. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  81. package/dist/server/durable/durable-agent-service.js +1 -1
  82. package/dist/server/engine-probe.js +36 -6
  83. package/dist/server/eval-tool.js +135 -135
  84. package/dist/server/evidence-tool-hooks.js +49 -0
  85. package/dist/server/file-save.js +95 -0
  86. package/dist/server/file-transfer-routes.js +97 -47
  87. package/dist/server/files-service.js +38 -26
  88. package/dist/server/global-loader.js +40 -2
  89. package/dist/server/goal-review-gate.js +16 -6
  90. package/dist/server/goal-service.js +54 -30
  91. package/dist/server/http-proxy.js +120 -0
  92. package/dist/server/index.js +285 -255
  93. package/dist/server/load-timing.js +31 -0
  94. package/dist/server/mcp-bridge.js +219 -94
  95. package/dist/server/mcp-hot-reload.js +31 -5
  96. package/dist/server/mcp-manager.js +192 -93
  97. package/dist/server/mcp-oauth-login.js +169 -0
  98. package/dist/server/mcp-oauth-ui.js +137 -0
  99. package/dist/server/mcp-oauth.js +395 -0
  100. package/dist/server/mcp-project-runtime.js +207 -0
  101. package/dist/server/message-window.js +74 -21
  102. package/dist/server/net-guard.js +122 -20
  103. package/dist/server/patch-bash-process.js +125 -0
  104. package/dist/server/patch-tool.js +9 -9
  105. package/dist/server/patch-turn-end-boundary.js +3 -3
  106. package/dist/server/payload-limits.js +17 -0
  107. package/dist/server/pending-question.js +82 -0
  108. package/dist/server/persona-chain.js +8 -8
  109. package/dist/server/plan-mode.js +338 -137
  110. package/dist/server/plugin-assets.js +8 -4
  111. package/dist/server/plugin-chat-attachments.js +48 -0
  112. package/dist/server/plugin-facilities.js +67 -220
  113. package/dist/server/plugin-installer.js +2 -1
  114. package/dist/server/plugin-removal.js +49 -0
  115. package/dist/server/plugin-secrets.js +179 -0
  116. package/dist/server/plugins.js +288 -94
  117. package/dist/server/preset-fields.js +56 -0
  118. package/dist/server/preset-plugin-dependencies.js +57 -0
  119. package/dist/server/preset-share.js +113 -72
  120. package/dist/server/prompt-templates.js +106 -0
  121. package/dist/server/protocol-version.js +1 -1
  122. package/dist/server/queue-modes.js +10 -0
  123. package/dist/server/remote-ssh-service.js +199 -106
  124. package/dist/server/request-context.js +164 -0
  125. package/dist/server/resolve-global-sdk.js +2 -0
  126. package/dist/server/sandbox-data.js +655 -0
  127. package/dist/server/sandbox-engines.js +7 -0
  128. package/dist/server/sandbox-runtime-gate.js +41 -0
  129. package/dist/server/sandbox-service.js +139 -698
  130. package/dist/server/sandbox-tool.js +21 -4
  131. package/dist/server/schedule-agent-tool.js +39 -21
  132. package/dist/server/scheduler-tasks.js +106 -55
  133. package/dist/server/scm-commitmsg.js +10 -10
  134. package/dist/server/serialize.js +48 -19
  135. package/dist/server/session-branch.js +25 -3
  136. package/dist/server/session-parser.js +28 -18
  137. package/dist/server/session-scan.js +130 -0
  138. package/dist/server/session-search.js +51 -37
  139. package/dist/server/settings-service.js +273 -111
  140. package/dist/server/setup-config.js +58 -0
  141. package/dist/server/setup-page.js +620 -620
  142. package/dist/server/skill-maintenance.js +112 -24
  143. package/dist/server/subagent-helpers.js +4 -1
  144. package/dist/server/subagent-notify.js +4 -1
  145. package/dist/server/subagent-security-gate.js +52 -11
  146. package/dist/server/subagent-task.js +27 -0
  147. package/dist/server/subagents.js +217 -46
  148. package/dist/server/tabs.js +9 -1
  149. package/dist/server/terminals.js +467 -363
  150. package/dist/server/text-quote.js +9 -0
  151. package/dist/server/tool-guards.js +42 -6
  152. package/dist/server/tool-manager.js +48 -20
  153. package/dist/server/tool-overrides.js +13 -11
  154. package/dist/server/tool-prompt-overrides.js +32 -2
  155. package/dist/server/tool-prompts.js +1 -1
  156. package/dist/server/turn-timing.js +11 -0
  157. package/dist/server/universal/drivers/claude-code.js +5 -0
  158. package/dist/server/universal/drivers/codex.js +336 -0
  159. package/dist/server/universal/index.js +1 -0
  160. package/dist/server/universal/session-store.js +48 -6
  161. package/dist/server/universal/universal-attachments.js +24 -1
  162. package/dist/server/universal/universal-service.js +1 -1
  163. package/dist/server/universal/universal-session.js +357 -231
  164. package/dist/server/uploads.js +64 -5
  165. package/dist/server/vision-bridge.js +18 -18
  166. package/dist/server/worktree-service.js +32 -24
  167. package/dist/server/ws-pending-queue.js +73 -27
  168. package/docs/device-center.md +148 -0
  169. package/docs/device-desktop.md +48 -0
  170. package/docs/dsh-engine.md +493 -493
  171. package/extensions/webui.ts +335 -335
  172. package/package.json +5 -2
  173. package/plugin-sdk/README.md +174 -174
  174. package/plugin-sdk/client-utils.mjs +279 -279
  175. package/plugin-sdk/import-check.mjs +210 -210
  176. package/plugin-sdk/index.d.ts +698 -676
  177. package/plugin-sdk/index.mjs +696 -696
  178. package/plugin-sdk/package.json +13 -13
  179. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  180. package/plugins/catalog.json +11 -1
  181. package/themes/aetheris.css +501 -607
  182. package/themes/ayu-light.css +116 -140
  183. package/themes/bases/flow-base.css +1357 -1363
  184. package/themes/bases/obsidian-base.css +895 -895
  185. package/themes/bases/statusbar-flat-base.css +112 -0
  186. package/themes/bases/zhujian-base.css +688 -687
  187. package/themes/bases/zhupi-base.css +660 -659
  188. package/themes/catppuccin-latte.css +119 -142
  189. package/themes/catppuccin.css +116 -147
  190. package/themes/claude-code-dark.css +147 -146
  191. package/themes/codex.css +114 -138
  192. package/themes/cyberpunk.css +50 -108
  193. package/themes/dark-teal.css +264 -265
  194. package/themes/dazzle.css +38 -108
  195. package/themes/everforest-light.css +115 -138
  196. package/themes/flow-light.css +164 -164
  197. package/themes/flow.css +161 -161
  198. package/themes/geist.css +114 -138
  199. package/themes/gruvbox-light.css +115 -138
  200. package/themes/kanagawa-lotus.css +115 -138
  201. package/themes/md-preview.css +24 -234
  202. package/themes/mist.css +166 -186
  203. package/themes/nord.css +107 -138
  204. package/themes/one-dark.css +106 -139
  205. package/themes/paper.css +174 -186
  206. package/themes/rose-pine-dawn.css +114 -138
  207. package/themes/sakura.css +166 -186
  208. package/themes/solarized-light.css +114 -137
  209. package/themes/tokyo-night.css +115 -146
  210. package/themes/translucent.css +85 -85
  211. package/themes/transparent.css +116 -116
  212. package/themes/vs-code-dark.css +147 -147
  213. package/themes/wallpaper-flow.css +382 -382
  214. package/themes/wallpaper-obsidian.css +74 -74
  215. package/themes/white.css +164 -186
  216. package/themes/zhujian-dark.css +115 -114
  217. package/themes/zhujian.css +114 -114
  218. package/themes/zhupi-dark.css +115 -114
  219. package/themes/zhupi.css +114 -114
  220. package/web/dist/.build-assets.json +1 -0
  221. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  222. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  223. package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
  224. package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
  225. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  226. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  227. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  228. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  229. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  230. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  231. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  232. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  233. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  234. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  235. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  236. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  237. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  238. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  239. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  240. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  241. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  242. package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
  243. package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
  244. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  245. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  246. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  247. package/web/dist/assets/desktop-YguLbrX1.js +1 -0
  248. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  249. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  250. package/web/dist/assets/index-BPvpea8t.js +85 -0
  251. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  252. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  253. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  254. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  255. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  256. package/web/dist/assets/math-BorAY7qD.css +1 -0
  257. package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
  258. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  259. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  260. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  261. package/web/dist/index.html +42 -35
  262. package/web/dist/sw.js +179 -179
  263. package/web/public/sw.js +179 -179
  264. package/dist/gh-comment-781.md +0 -5
  265. package/dist/server/durable/durable-capabilities.js +0 -11
  266. package/dist/server/markers/builtins/services.js +0 -123
  267. package/dist/server/markers/builtins/todo.js +0 -189
  268. package/dist/server/markers-list-tool.js +0 -34
  269. package/dist/server/orchestrator.js +0 -109
  270. package/dist/server/system-prompt-soul.js +0 -41
  271. package/dist/server/univer-service.js +0 -448
  272. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  273. package/dist/test-artifact.md +0 -9
  274. package/dist/test-preview-modal.md +0 -11
  275. package/dist/test-report.html +0 -20
  276. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  277. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  278. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  279. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  280. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -7,22 +7,27 @@
7
7
  * 3. 60ms 节流下发 snapshot / message_delta,实现高帧率低开销的前端流式渲染;
8
8
  * 4. 无缝复用宿主 FilesService(文件树/预览/SCM/上传)、TerminalManager(终端)与 BgServerTracker(后台服务)。
9
9
  */
10
+ import { startTurnTiming, finishTurnTiming } from "../turn-timing.js";
10
11
  import { randomUUID } from "node:crypto";
11
12
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
12
13
  import { homedir } from "node:os";
13
14
  import { join } from "node:path";
14
15
  import { FilesService } from "../files-service.js";
16
+ import { uploadLimitBytes } from "../payload-limits.js";
15
17
  import { TerminalManager, makePersistentTerminalTools } from "../terminals.js";
16
18
  import { TERMINAL_TOOL_NAMES } from "../tool-manager.js";
17
19
  import { BgServerTracker } from "../bg-servers.js";
18
20
  import { ModelAdminService } from "../model-admin.js";
19
21
  import { WebUIContext } from "../webui-context.js";
20
22
  import { ClaudeCodeDriver, probeClaudeCode } from "./drivers/claude-code.js";
23
+ import { CodexDriver, probeCodex } from "./drivers/codex.js";
21
24
  import { normalizeUiLayout, settingsPresetToUi } from "../client-state.js";
25
+ import { messageTextWithQuotes } from "../text-quote.js";
22
26
  import { readModelsJson, getModelThinkingLevelFromSettings, saveModelThinkingLevelToSettings, } from "../model-resolver.js";
23
27
  import { DEFAULT_UNIVERSAL_CAPABILITIES } from "../engine-capabilities.js";
24
28
  import { unsupportedToolInfo } from "../tool-info.js";
25
29
  import { SandboxManager } from "../sandbox-service.js";
30
+ import { assertEngineWorkspaceSupported } from "../sandbox-engines.js";
26
31
  import { getWorktreeContext, removeWorktree } from "../worktree-service.js";
27
32
  import { MarkerService } from "../marker-service.js";
28
33
  import { SlashCommandsService, parseSlash } from "../slash-commands.js";
@@ -37,7 +42,7 @@ import { subagentTitle, isSubagentTerminal, computeWaitCapMs, makeSubagentTools,
37
42
  import { recordSubagentHandoff, formatSubagentHandoffMessage, } from "../subagent-handoff.js";
38
43
  import { pick } from "../i18n.js";
39
44
  import { fetchRemoteSkillMarket, fetchRemoteSkillContent, fetchRemoteMcpMarket } from "../market-service.js";
40
- import { exportPresetVia, importPresetVia, importPresetFromUrlVia, pushPresetCatalogVia, sharePresetVia, } from "../preset-share.js";
45
+ import { exportPresetVia, importPresetVia, importPresetFromUrlVia, pushPresetCatalogVia, sharePresetVia, sanitizePresetSettings, } from "../preset-share.js";
41
46
  const SNAPSHOT_INTERVAL_MS = 60;
42
47
  function clampThinkingLevelToSupported(supported, current) {
43
48
  if (supported.includes(current))
@@ -86,6 +91,11 @@ export class UniversalSession {
86
91
  /** 在途回合归属的会话 id(#700/#701):prompt 开始时锚定,finalizeTurn 收尾时消费并清空。
87
92
  * 会话切换/回滚不再让流式回写与回合收尾锚错会话,避免跨对话内容污染落盘。 */
88
93
  turnConvId = null;
94
+ turn = null;
95
+ projectGeneration = 0;
96
+ switchingProject = false;
97
+ abortPromise = null;
98
+ markerOrigins = new Map();
89
99
  streamingMessage = null;
90
100
  streamingThinking = "";
91
101
  streamingText = "";
@@ -119,6 +129,7 @@ export class UniversalSession {
119
129
  this.pluginCommandsProvider = opts.pluginCommandsProvider;
120
130
  this.onQuit = opts.onQuit;
121
131
  this.sandboxes = new SandboxManager(this.dataDir);
132
+ assertEngineWorkspaceSupported(this.sandboxes, this.cwd, this.engine);
122
133
  void this.refreshWorktreeInfo();
123
134
  this.lang = opts.lang ?? "zh";
124
135
  this.webUi = new WebUIContext((msg) => this.send(msg));
@@ -248,7 +259,15 @@ export class UniversalSession {
248
259
  getActiveConversationId: () => this.activeConvId,
249
260
  getSessionManager: () => undefined,
250
261
  renameConversation: (convId, title) => {
251
- void this.renameConversation(convId, title);
262
+ const origin = this.markerOrigins.get(convId);
263
+ if (!origin || this.disposed)
264
+ return;
265
+ origin.conv.title = title;
266
+ origin.conv.updatedAt = Date.now();
267
+ if (!origin.conv.isEphemeral)
268
+ this.store.saveConversation(origin.cwd, origin.conv);
269
+ if (this.cwd === origin.cwd)
270
+ this.flushSnapshot();
252
271
  },
253
272
  refreshMarkers: () => this.flushSnapshot(),
254
273
  onActionsChange: (convId) => {
@@ -261,6 +280,10 @@ export class UniversalSession {
261
280
  this.currentModel = "claude-3-7-sonnet-20250219";
262
281
  this.seedDefaultClaudeModels();
263
282
  }
283
+ else if (opts.driver.id === "codex") {
284
+ this.currentModel = "default";
285
+ this.thinkingLevel = "medium";
286
+ }
264
287
  else if (opts.driver.id === "dsh") {
265
288
  this.currentModel = "deepseek/deepseek-v4-flash";
266
289
  this.thinkingLevel = "high";
@@ -301,8 +324,9 @@ export class UniversalSession {
301
324
  isDisposed: () => this.disposed,
302
325
  getCwd: () => this.cwd,
303
326
  getActiveCwd: () => this.cwd,
327
+ getUploadMaxBytes: () => uploadLimitBytes(this.stateStore?.getSettings(this.clientId) ?? {}, "workspace"),
304
328
  });
305
- this.terminals = new TerminalManager((msg) => this.send(msg), this.cwd, () => this.getLang());
329
+ this.terminals = new TerminalManager((msg) => this.send(msg), () => this.cwd, () => this.getLang(), "client");
306
330
  this.bg = new BgServerTracker({
307
331
  emit: (msg) => this.send(msg),
308
332
  flushSnapshot: () => this.flushSnapshot(),
@@ -329,6 +353,14 @@ export class UniversalSession {
329
353
  if (typeof this.stateStore?.remember === "function" && this.cwd) {
330
354
  this.stateStore.remember(this.clientId, this.cwd);
331
355
  }
356
+ if (this.driver instanceof CodexDriver) {
357
+ void probeCodex()
358
+ .then((probe) => {
359
+ if (!probe.available && !this.disposed)
360
+ this.emitNotice("warning", "Codex CLI 未安装,请运行 npm i -g @openai/codex 并完成 codex login。", "Codex CLI not found; run npm i -g @openai/codex and codex login.");
361
+ })
362
+ .catch(() => { });
363
+ }
332
364
  // 若驱动为 Claude Code,异步探测环境并下发安装指引
333
365
  if (this.driver instanceof ClaudeCodeDriver) {
334
366
  void probeClaudeCode().then((probe) => {
@@ -442,8 +474,16 @@ export class UniversalSession {
442
474
  send({ type: "default_model", modelId: defModel });
443
475
  }
444
476
  const terminals = this.terminals.list();
445
- if (terminals.length > 0) {
446
- this.send({ type: "terminal_list", conversationId: this.activeConvId, terminals });
477
+ this.send({ type: "terminal_list", conversationId: this.activeConvId, terminals });
478
+ for (const output of this.terminals.replay()) {
479
+ this.send({
480
+ type: "terminal_output",
481
+ conversationId: this.activeConvId,
482
+ ownerKind: "client",
483
+ terminalId: output.terminalId,
484
+ data: output.data,
485
+ reset: true,
486
+ });
447
487
  }
448
488
  this.bg.push();
449
489
  void this.refreshSessions();
@@ -497,6 +537,7 @@ export class UniversalSession {
497
537
  // 回合归属会话才携带流式态:切走后的前台会话快照不再混入后台回合内容(#701)
498
538
  streamingMessage: !this.turnConvId || this.turnConvId === conv.id ? this.streamingMessage : null,
499
539
  isStreaming: !this.turnConvId || this.turnConvId === conv.id ? this.isStreaming : false,
540
+ turnTiming: conv.turnTiming ?? null,
500
541
  isEphemeral: Boolean(conv.isEphemeral),
501
542
  draft: this.sessionDrafts.get(conv.id) ?? null,
502
543
  model: {
@@ -554,7 +595,14 @@ export class UniversalSession {
554
595
  const t = (title ?? "").trim();
555
596
  return !t || t === "新对话" || t === "New chat" || t === "New Chat" || t === "对话" || t === "Chat";
556
597
  }
557
- async prompt(text, attachments, _queue) {
598
+ activeConversationId() {
599
+ return this.activeConvId;
600
+ }
601
+ async prompt(text, attachments, _queue, targetConv = this.activeConv, rebuiltContext = "") {
602
+ assertEngineWorkspaceSupported(this.sandboxes, this.cwd, this.engine);
603
+ if (this.switchingProject || this.disposed || this.abortPromise)
604
+ return;
605
+ const generation = this.projectGeneration;
558
606
  if (this.isStreaming) {
559
607
  if (_queue === true) {
560
608
  const entry = createQueuedEntry(text, { attachments });
@@ -597,148 +645,183 @@ export class UniversalSession {
597
645
  const skillPrompt = instruction
598
646
  ? `[Skill: ${found.name}]\n${instruction}\n\n[User Prompt]\n${slash.args || "执行此技能"}`
599
647
  : slash.args || text;
600
- return this.prompt(skillPrompt, attachments, _queue);
648
+ return this.prompt(skillPrompt, attachments, _queue, targetConv, rebuiltContext);
601
649
  }
602
650
  }
603
651
  const handled = await this.slash.exec(slash.name, slash.args);
604
652
  if (handled)
605
653
  return;
606
654
  }
655
+ if (this.switchingProject || this.disposed || this.abortPromise || generation !== this.projectGeneration)
656
+ return;
657
+ if (this.activeConv !== targetConv)
658
+ return;
607
659
  this.isStreaming = true;
608
- const conv = this.activeConv;
660
+ const conv = targetConv;
661
+ startTurnTiming(conv);
662
+ const turn = { conv, cwd: this.cwd };
663
+ this.turn = turn;
664
+ const isCurrent = () => this.turn === turn && !this.disposed;
609
665
  this.turnConvId = conv.id;
610
666
  const now = Date.now();
611
667
  // 2. 扫描用户文本中的 @ 提及(文件路径与技能指令)
612
- const availableSkills = await this.collectUniversalSkills();
613
- const scanResult = scanAtMentions(text, this.cwd, availableSkills, attachments ?? []);
614
- const effectiveAttachments = [...(attachments ?? []), ...scanResult.detectedAttachments];
615
- const finalPrompt = formatPromptWithSkills(text, scanResult.detectedSkills);
616
- // 3. 自动根据首条提问为新会话命名(首条提问立即刷新左侧栏运行与历史列表)
617
- const hasNoUserMessages = !conv.messages.some((m) => m.role === "user");
618
- if (UniversalSession.isDefaultTitle(conv.title) && hasNoUserMessages && text.trim()) {
619
- const trimmed = text.trim().replace(/\s+/g, " ");
620
- const cleanTitle = trimmed.length > 30 ? `${trimmed.slice(0, 30)}…` : trimmed;
621
- conv.title = cleanTitle;
622
- if (this.stateStore) {
623
- this.stateStore.saveSessionTitle(this.cwd, conv.id, cleanTitle);
624
- }
625
- if (!conv.isEphemeral) {
626
- this.store.saveConversation(this.cwd, conv);
668
+ try {
669
+ const availableSkills = await this.collectUniversalSkills();
670
+ if (!isCurrent())
671
+ return;
672
+ const scanResult = scanAtMentions(text, turn.cwd, availableSkills, attachments ?? []);
673
+ const effectiveAttachments = [...(attachments ?? []), ...scanResult.detectedAttachments];
674
+ const finalPrompt = formatPromptWithSkills(text, scanResult.detectedSkills);
675
+ // 3. 自动根据首条提问为新会话命名(首条提问立即刷新左侧栏运行与历史列表)
676
+ const hasNoUserMessages = !conv.messages.some((m) => m.role === "user");
677
+ if (UniversalSession.isDefaultTitle(conv.title) && hasNoUserMessages && text.trim()) {
678
+ const trimmed = text.trim().replace(/\s+/g, " ");
679
+ const cleanTitle = trimmed.length > 30 ? `${trimmed.slice(0, 30)}…` : trimmed;
680
+ conv.title = cleanTitle;
681
+ if (this.stateStore) {
682
+ this.stateStore.saveSessionTitle(this.cwd, conv.id, cleanTitle);
683
+ }
684
+ if (!conv.isEphemeral) {
685
+ this.store.saveConversation(this.cwd, conv);
686
+ }
687
+ void this.refreshSessions();
627
688
  }
628
- void this.refreshSessions();
629
- }
630
- // 4. 插入用户消息以及附件卡片(保证 Web UI 附件卡片折叠呈现与历史复原)
631
- const userMsg = {
632
- id: `u-${now}-${randomUUID().slice(0, 6)}`,
633
- role: "user",
634
- content: [{ type: "text", text }],
635
- timestamp: now,
636
- };
637
- conv.messages.push(userMsg);
638
- if (effectiveAttachments.length > 0) {
639
- const attCards = createAttachmentUiMessages(effectiveAttachments, now);
640
- for (const card of attCards) {
641
- conv.messages.push(card);
689
+ // 4. 插入用户消息以及附件卡片(保证 Web UI 附件卡片折叠呈现与历史复原)
690
+ const userMsg = {
691
+ id: `u-${now}-${randomUUID().slice(0, 6)}`,
692
+ role: "user",
693
+ content: [{ type: "text", text }],
694
+ timestamp: now,
695
+ };
696
+ conv.messages.push(userMsg);
697
+ if (effectiveAttachments.length > 0) {
698
+ const attCards = createAttachmentUiMessages(effectiveAttachments, now);
699
+ for (const card of attCards) {
700
+ conv.messages.push(card);
701
+ }
642
702
  }
643
- }
644
- conv.updatedAt = now;
645
- if (!conv.isEphemeral) {
646
- this.store.saveConversation(this.cwd, conv);
647
- }
648
- // 用户发送了提示词,消费并清除当前会话的草稿
649
- this.sessionDrafts.delete(conv.id);
650
- // 确保底层驱动与当前对话的 driverSessionId 上下文同步(保证多轮对话连续且新建对话隔离)
651
- if (conv.driverSessionId) {
652
- await this.driver.resumeSession(conv.driverSessionId);
653
- }
654
- else {
655
- const sid = await this.driver.createSession();
656
- conv.driverSessionId = sid;
703
+ conv.updatedAt = now;
657
704
  if (!conv.isEphemeral) {
658
705
  this.store.saveConversation(this.cwd, conv);
659
706
  }
660
- }
661
- // 3. 准备助手流式消息
662
- const assistantMsgId = `a-${now}-${randomUUID().slice(0, 6)}`;
663
- this.streamingThinking = "";
664
- this.streamingText = "";
665
- this.streamingMessage = {
666
- id: assistantMsgId,
667
- role: "assistant",
668
- content: [],
669
- timestamp: now,
670
- model: this.currentModel,
671
- };
672
- this.flushSnapshot();
673
- // 4. 构建 AgentEventSink(时序保真:思考 -> 前置正文 -> 工具调用 -> 总结正文)
674
- const sink = {
675
- onThinkingDelta: (delta) => {
676
- this.streamingThinking += delta;
677
- if (!this.streamingMessage)
707
+ // 用户发送了提示词,消费并清除当前会话的草稿
708
+ this.sessionDrafts.delete(conv.id);
709
+ // 确保底层驱动与当前对话的 driverSessionId 上下文同步(保证多轮对话连续且新建对话隔离)
710
+ if (conv.driverSessionId) {
711
+ await this.driver.resumeSession(conv.driverSessionId);
712
+ if (!isCurrent())
678
713
  return;
679
- let thinkBlock = this.streamingMessage.content.find((b) => b.type === "thinking");
680
- if (!thinkBlock) {
681
- thinkBlock = { type: "thinking", thinking: "" };
682
- this.streamingMessage.content.unshift(thinkBlock);
683
- }
684
- thinkBlock.thinking = this.streamingThinking;
685
- this.emitDelta({ type: "thinking_delta", delta });
686
- this.scheduleThrottledSnapshot();
687
- },
688
- onTextDelta: (delta) => {
689
- this.streamingText += delta;
690
- if (!this.streamingMessage)
714
+ }
715
+ else {
716
+ const sid = await this.driver.createSession();
717
+ if (!isCurrent())
691
718
  return;
692
- const lastBlock = this.streamingMessage.content[this.streamingMessage.content.length - 1];
693
- if (lastBlock && lastBlock.type === "text" && !lastBlock.truncated) {
694
- lastBlock.text += delta;
695
- }
696
- else {
697
- this.streamingMessage.content.push({ type: "text", text: delta });
719
+ conv.driverSessionId = sid;
720
+ if (!conv.isEphemeral) {
721
+ this.store.saveConversation(turn.cwd, conv);
698
722
  }
699
- this.emitDelta({ type: "text_delta", delta });
700
- this.scheduleThrottledSnapshot();
701
- },
702
- onToolStart: (callId, toolName, args) => {
703
- if (!this.streamingMessage)
723
+ }
724
+ // 3. 准备助手流式消息
725
+ const assistantMsgId = `a-${now}-${randomUUID().slice(0, 6)}`;
726
+ this.streamingThinking = "";
727
+ this.streamingText = "";
728
+ this.streamingMessage = {
729
+ id: assistantMsgId,
730
+ role: "assistant",
731
+ content: [],
732
+ timestamp: now,
733
+ model: this.currentModel,
734
+ };
735
+ this.flushSnapshot();
736
+ // 4. 构建 AgentEventSink(时序保真:思考 -> 前置正文 -> 工具调用 -> 总结正文)
737
+ const sink = {
738
+ onSessionStarted: (sessionId) => {
739
+ conv.driverSessionId = sessionId;
740
+ if (!conv.isEphemeral)
741
+ this.store.saveConversation(turn.cwd, conv);
742
+ },
743
+ onThinkingDelta: (delta) => {
744
+ this.streamingThinking += delta;
745
+ if (!this.streamingMessage)
746
+ return;
747
+ let thinkBlock = this.streamingMessage.content.find((b) => b.type === "thinking");
748
+ if (!thinkBlock) {
749
+ thinkBlock = { type: "thinking", thinking: "" };
750
+ this.streamingMessage.content.unshift(thinkBlock);
751
+ }
752
+ thinkBlock.thinking = this.streamingThinking;
753
+ this.emitDelta({ type: "thinking_delta", delta });
754
+ this.scheduleThrottledSnapshot();
755
+ },
756
+ onTextDelta: (delta) => {
757
+ this.streamingText += delta;
758
+ if (!this.streamingMessage)
759
+ return;
760
+ const lastBlock = this.streamingMessage.content[this.streamingMessage.content.length - 1];
761
+ if (lastBlock && lastBlock.type === "text" && !lastBlock.truncated) {
762
+ lastBlock.text += delta;
763
+ }
764
+ else {
765
+ this.streamingMessage.content.push({ type: "text", text: delta });
766
+ }
767
+ this.emitDelta({ type: "text_delta", delta });
768
+ this.scheduleThrottledSnapshot();
769
+ },
770
+ onToolStart: (callId, toolName, args) => {
771
+ if (!this.streamingMessage)
772
+ return;
773
+ const toolBlock = {
774
+ type: "toolCall",
775
+ id: callId,
776
+ name: toolName,
777
+ argumentsText: JSON.stringify(args, null, 2),
778
+ };
779
+ this.streamingMessage.content.push(toolBlock);
780
+ this.scheduleThrottledSnapshot();
781
+ },
782
+ onToolEnd: (callId, result) => {
783
+ const toolMsg = {
784
+ id: `t-${callId}`,
785
+ role: "toolResult",
786
+ toolCallId: callId,
787
+ content: [{ type: "text", text: result.output ?? result.error ?? "" }],
788
+ isError: Boolean(result.error),
789
+ timestamp: Date.now(),
790
+ };
791
+ this.pendingToolResults.push(toolMsg);
792
+ this.scheduleThrottledSnapshot();
793
+ },
794
+ onTurnComplete: (meta) => {
795
+ this.finalizeTurn(meta);
796
+ },
797
+ onError: (err) => {
798
+ const errText = typeof err === "string" ? err : err.message;
799
+ this.emitNotice("error", `执行出错: ${errText}`, `Execution error: ${errText}`);
800
+ this.finalizeTurn();
801
+ },
802
+ };
803
+ try {
804
+ const guardedSink = new Proxy(sink, {
805
+ get: (target, key) => (...args) => {
806
+ if (isCurrent())
807
+ target[key]?.(...args);
808
+ },
809
+ });
810
+ await this.driver.sendPrompt(rebuiltContext ? `${rebuiltContext}\n\n${finalPrompt}` : finalPrompt, effectiveAttachments, guardedSink);
811
+ }
812
+ catch (err) {
813
+ if (!isCurrent())
704
814
  return;
705
- const toolBlock = {
706
- type: "toolCall",
707
- id: callId,
708
- name: toolName,
709
- argumentsText: JSON.stringify(args, null, 2),
710
- };
711
- this.streamingMessage.content.push(toolBlock);
712
- this.scheduleThrottledSnapshot();
713
- },
714
- onToolEnd: (callId, result) => {
715
- const toolMsg = {
716
- id: `t-${callId}`,
717
- role: "toolResult",
718
- toolCallId: callId,
719
- content: [{ type: "text", text: result.output ?? result.error ?? "" }],
720
- isError: Boolean(result.error),
721
- timestamp: Date.now(),
722
- };
723
- this.pendingToolResults.push(toolMsg);
724
- this.scheduleThrottledSnapshot();
725
- },
726
- onTurnComplete: (meta) => {
727
- this.finalizeTurn(meta);
728
- },
729
- onError: (err) => {
730
- const errText = typeof err === "string" ? err : err.message;
731
- this.emitNotice("error", `执行出错: ${errText}`, `Execution error: ${errText}`);
815
+ const msg = err instanceof Error ? err.message : String(err);
816
+ this.emitNotice("error", `驱动执行异常: ${msg}`, `Driver execution error: ${msg}`);
732
817
  this.finalizeTurn();
733
- },
734
- };
735
- try {
736
- await this.driver.sendPrompt(finalPrompt, effectiveAttachments, sink);
818
+ }
737
819
  }
738
820
  catch (err) {
739
- const msg = err instanceof Error ? err.message : String(err);
740
- this.emitNotice("error", `驱动执行异常: ${msg}`, `Driver execution error: ${msg}`);
821
+ if (!isCurrent())
822
+ return;
741
823
  this.finalizeTurn();
824
+ this.emitNotice("error", String(err), String(err));
742
825
  }
743
826
  }
744
827
  updateStreamingContent() {
@@ -776,10 +859,12 @@ export class UniversalSession {
776
859
  clearTimeout(this.snapshotTimer);
777
860
  this.snapshotTimer = null;
778
861
  }
779
- // 回合收尾锚定回合归属会话:中途切走/回滚不再把本轮内容写进别的会话(#700/#701)
780
- const turnId = this.turnConvId;
862
+ const turn = this.turn;
863
+ if (!turn)
864
+ return;
865
+ this.turn = null;
781
866
  this.turnConvId = null;
782
- const conv = (turnId && this.conversations.get(turnId)) || this.activeConv;
867
+ const conv = turn.conv;
783
868
  if (this.streamingMessage) {
784
869
  conv.messages.push(this.streamingMessage);
785
870
  this.streamingMessage = null;
@@ -822,6 +907,7 @@ export class UniversalSession {
822
907
  conv.driverSessionId = activeSid;
823
908
  }
824
909
  }
910
+ finishTurnTiming(conv);
825
911
  this.isStreaming = false;
826
912
  this.streamingThinking = "";
827
913
  // 先取本轮全文再清空:内联标记解析在清空之后读 streamingText,
@@ -831,26 +917,38 @@ export class UniversalSession {
831
917
  this.streamingText = "";
832
918
  conv.updatedAt = Date.now();
833
919
  if (!conv.isEphemeral) {
834
- this.store.saveConversation(this.cwd, conv);
920
+ this.store.saveConversation(turn.cwd, conv);
835
921
  }
836
922
  // 解析本轮生成的内联标记(如 [[conv:rename:...]] / [[action:suggest:...]])
837
923
  if (finalText && finalText.includes("[[")) {
924
+ this.markerOrigins.set(conv.id, turn);
838
925
  void this.markerSvc.handleAssistantText(conv.id, finalText);
839
926
  }
840
927
  this.flushSnapshot();
841
928
  void this.refreshSessions();
842
929
  // 检查排队消息并自动处理
843
- if (this.followUpQueue.length > 0) {
930
+ if (!this.switchingProject && !this.disposed && this.followUpQueue.length > 0) {
844
931
  const next = this.followUpQueue.shift();
845
932
  this.flushSnapshot(true);
846
933
  void this.prompt(next.text, next.attachments);
847
934
  }
848
935
  }
849
936
  async abort() {
850
- if (this.isStreaming) {
851
- await this.driver.abort();
937
+ if (this.abortPromise)
938
+ return this.abortPromise;
939
+ if (!this.isStreaming)
940
+ return;
941
+ // Install the gate before finalizeTurn can dispatch a queued prompt.
942
+ this.abortPromise = Promise.resolve().then(async () => {
852
943
  this.finalizeTurn();
944
+ await this.driver.abort();
853
945
  this.emitNotice("info", "已停止生成", "Generation stopped");
946
+ });
947
+ try {
948
+ await this.abortPromise;
949
+ }
950
+ finally {
951
+ this.abortPromise = null;
854
952
  }
855
953
  }
856
954
  async abortBash() {
@@ -882,7 +980,7 @@ export class UniversalSession {
882
980
  // ---------------------------------------------------------------------------
883
981
  // 对话生命周期
884
982
  // ---------------------------------------------------------------------------
885
- async newChat(_preset, ephemeral = false) {
983
+ async newChat(_preset, ephemeral = false, onReady) {
886
984
  const newConv = this.createEmptyConversation("新对话", Boolean(ephemeral));
887
985
  this.conversations.set(newConv.id, newConv);
888
986
  this.activeConvId = newConv.id;
@@ -891,9 +989,11 @@ export class UniversalSession {
891
989
  }
892
990
  this.flushSnapshot(true);
893
991
  void this.refreshSessions();
992
+ onReady?.(newConv.id);
894
993
  return true;
895
994
  }
896
995
  async switchConversation(id) {
996
+ assertEngineWorkspaceSupported(this.sandboxes, this.cwd, this.engine);
897
997
  let conv = this.conversations.get(id);
898
998
  if (!conv) {
899
999
  conv = this.store.loadConversation(this.cwd, id) ?? undefined;
@@ -1152,41 +1252,27 @@ export class UniversalSession {
1152
1252
  this.flushSnapshot();
1153
1253
  return;
1154
1254
  }
1155
- // 截断到编辑点之前的所有历史消息(跳过属于本轮提问的前置附件卡片,避免 prompt 重新注入后附件重复),
1156
- // fork 一个新的 UniversalConversation
1255
+ // Remove the question, its file asides and the abandoned suffix in place.
1157
1256
  let cutIdx = idx;
1158
1257
  while (cutIdx > 0 &&
1159
1258
  conv.messages[cutIdx - 1]?.role === "custom" &&
1160
1259
  conv.messages[cutIdx - 1]?.customType === "file") {
1161
1260
  cutIdx--;
1162
1261
  }
1163
- const headMessages = structuredClone(conv.messages.slice(0, cutIdx));
1164
- const forkedConv = this.createEmptyConversation(conv.title, Boolean(conv.isEphemeral));
1165
- forkedConv.messages = headMessages;
1166
- if (headMessages.length > 0) {
1167
- forkedConv.updatedAt = Date.now();
1168
- }
1169
- // 若底层驱动支持原生会话分叉(如 Durable 引擎),继承前序不可变记录
1170
- if (conv.driverSessionId && typeof this.driver.forkSession === "function") {
1171
- try {
1172
- const forkedSid = await this.driver.forkSession(conv.driverSessionId);
1173
- if (forkedSid) {
1174
- forkedConv.driverSessionId = forkedSid;
1175
- }
1176
- }
1177
- catch {
1178
- /* fallback */
1179
- }
1180
- }
1181
- this.conversations.set(forkedConv.id, forkedConv);
1182
- if (!forkedConv.isEphemeral) {
1183
- this.store.saveConversation(this.cwd, forkedConv);
1262
+ conv.messages.splice(cutIdx);
1263
+ // Drivers expose no in-place history replacement. A fresh backend handle
1264
+ // prevents resume from restoring the discarded suffix; the UI identity stays.
1265
+ conv.driverSessionId = undefined;
1266
+ const context = conv.messages.map((m) => `[${m.role}] ${messageTextWithQuotes(m)}`).join("\n");
1267
+ conv.updatedAt = Date.now();
1268
+ this.followUpQueue.length = 0;
1269
+ if (!conv.isEphemeral) {
1270
+ this.store.saveConversation(this.cwd, conv);
1184
1271
  }
1185
- this.activeConvId = forkedConv.id;
1186
1272
  this.flushSnapshot(true);
1187
1273
  void this.refreshSessions();
1188
- // 将编辑后的内容作为新 prompt 投递执行,实现无缝编辑重试
1189
- await this.prompt(text, attachments);
1274
+ // Capture the destination before any asynchronous slash/skill lookup.
1275
+ await this.prompt(text, attachments, undefined, conv, context ? `Previous conversation context:\n${context}` : "");
1190
1276
  }
1191
1277
  async refreshSessions() {
1192
1278
  const memoryConvs = Array.from(this.conversations.values());
@@ -1357,8 +1443,8 @@ export class UniversalSession {
1357
1443
  async writeFile(path, text) {
1358
1444
  await this.files.writeFile(path, text);
1359
1445
  }
1360
- async uploadFile(dirPath, name, data) {
1361
- await this.files.uploadFile(dirPath, name, data);
1446
+ async uploadFile(dirPath, name, data, uploadId) {
1447
+ await this.files.uploadFile(dirPath, name, data, uploadId);
1362
1448
  }
1363
1449
  async createEntry(dir, name, kind) {
1364
1450
  await this.files.createEntry(dir, name, kind);
@@ -1387,8 +1473,10 @@ export class UniversalSession {
1387
1473
  getUserTerminalManager() {
1388
1474
  return this.terminals;
1389
1475
  }
1390
- findTerminalManager() {
1391
- return this.terminals;
1476
+ findTerminalManager(terminalId, _conversationId, ownerKind) {
1477
+ if (ownerKind === "conversation")
1478
+ return undefined;
1479
+ return this.terminals.has(terminalId) ? this.terminals : undefined;
1392
1480
  }
1393
1481
  getTerminalCwd() {
1394
1482
  return this.cwd;
@@ -1510,37 +1598,52 @@ export class UniversalSession {
1510
1598
  this.flushSnapshot();
1511
1599
  }
1512
1600
  async setCwd(path) {
1513
- this.cwd = path;
1514
- this.driver.setCwd(path);
1515
- // 切换工作区 CWD:清空旧目录会话缓存与草稿,并加载属于新目录的会话
1516
- this.conversations.clear();
1517
- this.sessionDrafts.clear();
1518
- const existing = this.store.listConversations(this.cwd);
1519
- if (existing.length > 0) {
1520
- for (const conv of existing) {
1521
- this.conversations.set(conv.id, conv);
1601
+ assertEngineWorkspaceSupported(this.sandboxes, path, this.engine);
1602
+ if (this.switchingProject)
1603
+ throw new Error("Workspace switch already in progress");
1604
+ this.switchingProject = true;
1605
+ try {
1606
+ // Finish the captured old turn before replacing the driver's workspace.
1607
+ this.followUpQueue = [];
1608
+ await this.abort();
1609
+ for (const id of this.subagentDrivers.keys())
1610
+ await this.stopSubagent(id);
1611
+ this.projectGeneration++;
1612
+ this.cwd = path;
1613
+ this.driver.setCwd(path);
1614
+ // 切换工作区 CWD:清空旧目录会话缓存与草稿,并加载属于新目录的会话
1615
+ this.conversations.clear();
1616
+ this.sessionDrafts.clear();
1617
+ const existing = this.store.listConversations(this.cwd);
1618
+ if (existing.length > 0) {
1619
+ for (const conv of existing) {
1620
+ this.conversations.set(conv.id, conv);
1621
+ }
1622
+ this.activeConvId = existing[0].id;
1522
1623
  }
1523
- this.activeConvId = existing[0].id;
1524
- }
1525
- else {
1526
- const initialConv = this.createEmptyConversation("新对话");
1527
- this.activeConvId = initialConv.id;
1528
- this.conversations.set(initialConv.id, initialConv);
1529
- this.store.saveConversation(this.cwd, initialConv);
1530
- }
1531
- await this.refreshSessions();
1532
- await this.refreshWorktreeInfo();
1533
- if (typeof this.stateStore?.remember === "function") {
1534
- this.stateStore.remember(this.clientId, path);
1624
+ else {
1625
+ const initialConv = this.createEmptyConversation("新对话");
1626
+ this.activeConvId = initialConv.id;
1627
+ this.conversations.set(initialConv.id, initialConv);
1628
+ this.store.saveConversation(this.cwd, initialConv);
1629
+ }
1630
+ await this.refreshSessions();
1631
+ await this.refreshWorktreeInfo();
1632
+ if (typeof this.stateStore?.remember === "function") {
1633
+ this.stateStore.remember(this.clientId, path);
1634
+ }
1635
+ void this.pushProjects();
1636
+ // 切换目录后恢复该目录按引擎隔离的项目记忆模型
1637
+ const savedModel = this.stateStore?.getProjectModel(this.clientId, path, this.engine) ??
1638
+ this.stateStore?.getDefaultModel(this.engine);
1639
+ if (savedModel && savedModel !== this.currentModel) {
1640
+ void this.setModel(savedModel).catch(() => { });
1641
+ }
1642
+ this.flushSnapshot(true);
1535
1643
  }
1536
- void this.pushProjects();
1537
- // 切换目录后恢复该目录按引擎隔离的项目记忆模型
1538
- const savedModel = this.stateStore?.getProjectModel(this.clientId, path, this.engine) ??
1539
- this.stateStore?.getDefaultModel(this.engine);
1540
- if (savedModel && savedModel !== this.currentModel) {
1541
- void this.setModel(savedModel).catch(() => { });
1644
+ finally {
1645
+ this.switchingProject = false;
1542
1646
  }
1543
- this.flushSnapshot(true);
1544
1647
  }
1545
1648
  async setWorkspaceRoots(roots) {
1546
1649
  if (this.stateStore) {
@@ -1549,12 +1652,12 @@ export class UniversalSession {
1549
1652
  this.flushSnapshot();
1550
1653
  }
1551
1654
  async refreshWorktreeInfo() {
1552
- try {
1553
- this.worktreeInfo = await getWorktreeContext(this.cwd);
1554
- }
1555
- catch {
1556
- this.worktreeInfo = null;
1557
- }
1655
+ const cwd = this.cwd;
1656
+ const info = await getWorktreeContext(cwd);
1657
+ if (this.cwd !== cwd)
1658
+ return;
1659
+ this.worktreeInfo = info;
1660
+ this.flushSnapshot();
1558
1661
  }
1559
1662
  /** 获取通用底座持有的持久终端交互工具集 */
1560
1663
  getTerminalTools() {
@@ -1645,13 +1748,9 @@ export class UniversalSession {
1645
1748
  messages: compacted,
1646
1749
  });
1647
1750
  }
1648
- async createSandbox(opts) {
1751
+ async createSandbox(_opts) {
1649
1752
  try {
1650
- const { sandbox, copiedFiles } = await this.sandboxes.create(opts);
1651
- await this.setCwd(sandbox.path);
1652
- const modeZh = sandbox.sourcePath ? `已从源项目导入 ${copiedFiles} 个文件` : "空白隔离环境";
1653
- const modeEn = sandbox.sourcePath ? `imported ${copiedFiles} files from source` : "blank isolated workspace";
1654
- this.emitNotice("info", `🧪 沙盒「${sandbox.name}」已启动(${modeZh},一切修改与原项目完全隔离)`, `🧪 Sandbox "${sandbox.name}" started (${modeEn}; all changes are strictly isolated)`);
1753
+ throw new Error(`引擎 ${this.engine} 不支持受管沙盒执行,请使用 pi。 Engine "${this.engine}" does not support managed sandbox execution; use pi.`);
1655
1754
  }
1656
1755
  catch (err) {
1657
1756
  this.emitNotice("error", `创建沙盒失败:${err.message}`, `Failed to create sandbox: ${err.message}`);
@@ -1660,7 +1759,7 @@ export class UniversalSession {
1660
1759
  async resetSandbox(path) {
1661
1760
  const target = path?.trim() || this.cwd;
1662
1761
  try {
1663
- const { sandbox, copiedFiles } = await this.sandboxes.reset(target);
1762
+ const { sandbox, copiedFiles } = await this.sandboxes.withLifecycle(target, async (_info, lifecycle) => lifecycle.reset());
1664
1763
  this.flushSnapshot();
1665
1764
  this.emitNotice("info", sandbox.sourcePath
1666
1765
  ? `🔄 已重置沙盒「${sandbox.name}」(重新从源项目同步 ${copiedFiles} 个文件)`
@@ -1696,19 +1795,21 @@ export class UniversalSession {
1696
1795
  this.emitNotice("error", `导出沙盒失败:${err.message}`, `Failed to export sandbox: ${err.message}`);
1697
1796
  }
1698
1797
  }
1699
- async diffSandbox(path) {
1798
+ async diffSandbox(path, requestId) {
1700
1799
  const target = path?.trim() || this.cwd;
1701
1800
  try {
1702
1801
  const res = await this.sandboxes.diffWithSource(target);
1703
1802
  this.send({
1704
1803
  type: "sandbox_diff",
1705
1804
  diff: {
1805
+ requestId,
1806
+ expectedRevision: res.expectedRevision,
1706
1807
  sandboxId: res.sandbox.id,
1707
1808
  path: res.sandbox.path,
1708
1809
  sourcePath: res.sourcePath,
1709
- added: res.added.slice(0, 200),
1710
- modified: res.modified.slice(0, 200),
1711
- deleted: res.deleted.slice(0, 200),
1810
+ added: res.added,
1811
+ modified: res.modified,
1812
+ deleted: res.deleted,
1712
1813
  unchangedCount: res.unchangedCount,
1713
1814
  },
1714
1815
  });
@@ -1717,6 +1818,7 @@ export class UniversalSession {
1717
1818
  this.send({
1718
1819
  type: "sandbox_diff",
1719
1820
  diff: {
1821
+ requestId,
1720
1822
  sandboxId: "",
1721
1823
  path: target,
1722
1824
  added: [],
@@ -1728,10 +1830,10 @@ export class UniversalSession {
1728
1830
  });
1729
1831
  }
1730
1832
  }
1731
- async applySandboxToSource(path) {
1833
+ async applySandboxToSource(path, expectedRevision) {
1732
1834
  const target = path?.trim() || this.cwd;
1733
1835
  try {
1734
- const { sandbox, sourcePath, copiedFiles, deletedFiles } = await this.sandboxes.applyToSource(target);
1836
+ const { sandbox, sourcePath, copiedFiles, deletedFiles } = await this.sandboxes.withLifecycle(target, async (_info, lifecycle) => lifecycle.applyToSource(expectedRevision));
1735
1837
  const delSuffixZh = deletedFiles ? `,清理 ${deletedFiles} 个已删除文件` : "";
1736
1838
  const delSuffixEn = deletedFiles ? `, pruned ${deletedFiles} deleted files` : "";
1737
1839
  this.emitNotice("info", `✅ 已将沙盒「${sandbox.name}」中的改动同步回源项目:${sourcePath}(同步 ${copiedFiles} 个文件${delSuffixZh})`, `✅ Applied changes from sandbox "${sandbox.name}" back to source project: ${sourcePath} (${copiedFiles} files synced${delSuffixEn})`);
@@ -1742,15 +1844,15 @@ export class UniversalSession {
1742
1844
  }
1743
1845
  async destroySandbox(path) {
1744
1846
  const target = path?.trim() || this.cwd;
1745
- const sbx = this.sandboxes.get(target) ?? this.sandboxes.getByCwd(target);
1746
- if (!sbx)
1747
- return;
1748
1847
  try {
1749
- if (this.cwd === sbx.path || this.cwd.startsWith(sbx.path + "/")) {
1750
- const fallback = sbx.sourcePath && existsSync(sbx.sourcePath) ? sbx.sourcePath : homedir();
1751
- await this.setCwd(fallback);
1752
- }
1753
- await this.sandboxes.destroy(sbx.path);
1848
+ const sbx = await this.sandboxes.withLifecycle(target, async (sbx, lifecycle) => {
1849
+ if (this.cwd === sbx.path || this.cwd.startsWith(sbx.path + "/")) {
1850
+ const fallback = sbx.sourcePath && existsSync(sbx.sourcePath) ? sbx.sourcePath : homedir();
1851
+ await this.setCwd(fallback);
1852
+ }
1853
+ await lifecycle.destroy();
1854
+ return sbx;
1855
+ });
1754
1856
  this.emitNotice("info", `🗑️ 已销毁沙盒「${sbx.name}」`, `🗑️ Destroyed sandbox "${sbx.name}"`);
1755
1857
  }
1756
1858
  catch (err) {
@@ -1885,6 +1987,8 @@ export class UniversalSession {
1885
1987
  pushSettings() {
1886
1988
  const s = this.stateStore?.getSettings(this.clientId);
1887
1989
  const settings = {
1990
+ steeringMode: s?.steeringMode ?? "all",
1991
+ followUpMode: s?.followUpMode ?? "all",
1888
1992
  promptMode: s?.promptMode ?? "append",
1889
1993
  customSystemPrompt: s?.customSystemPrompt ?? "",
1890
1994
  disabledSkills: s?.disabledSkills ?? [],
@@ -1923,6 +2027,9 @@ export class UniversalSession {
1923
2027
  skillsCatalogMaxDesc: 250,
1924
2028
  skillsCatalogShowLocation: false,
1925
2029
  skillsCatalogBudget: 20000,
2030
+ chatUploadMaxMb: s?.chatUploadMaxMb ?? 20,
2031
+ workspaceUploadMaxMb: s?.workspaceUploadMaxMb ?? 100,
2032
+ folderUploadMaxMb: s?.folderUploadMaxMb ?? 32,
1926
2033
  visionBridgeEnabled: false,
1927
2034
  visionBridgeModel: null,
1928
2035
  visionBridgePromptMode: "append",
@@ -2122,18 +2229,9 @@ export class UniversalSession {
2122
2229
  this.emitNotice("error", `未找到名为「${name}」的设置预设`, `Settings preset "${name}" not found`);
2123
2230
  return;
2124
2231
  }
2125
- this.stateStore.saveSettings(this.clientId, {
2126
- promptMode: found.promptMode,
2127
- customSystemPrompt: found.customSystemPrompt,
2128
- promptDisabled: [...(found.promptDisabled ?? [])],
2129
- disabledSkills: [...(found.disabledSkills ?? [])],
2130
- disabledExtensions: [...(found.disabledExtensions ?? [])],
2131
- reviewPrompt: found.reviewPrompt ?? "",
2132
- reviewDisabledSkills: [...(found.reviewDisabledSkills ?? [])],
2133
- retryMaxAttempts: found.retryMaxAttempts,
2134
- softCapTokens: found.softCapTokens,
2135
- softCapByModel: found.softCapByModel,
2136
- });
2232
+ // Missing settings retain their current values; metadata never enters settings.
2233
+ const { settings } = sanitizePresetSettings(found);
2234
+ this.stateStore.saveSettings(this.clientId, settings);
2137
2235
  this.pushSettings();
2138
2236
  this.emitNotice("info", `已应用设置预设「${name}」`, `Settings preset "${name}" applied`);
2139
2237
  }
@@ -2346,6 +2444,13 @@ export class UniversalSession {
2346
2444
  }
2347
2445
  /** 创建并启动一个子代理会话 */
2348
2446
  async spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist = false, title, _thinking, _notifyOnDone) {
2447
+ if (_notifyOnDone === "manual") {
2448
+ throw new Error("notifyOnDone=manual is only supported by the pi engine.");
2449
+ }
2450
+ assertEngineWorkspaceSupported(this.sandboxes, cwd, this.engine);
2451
+ if (this.switchingProject || this.disposed)
2452
+ throw new Error("Workspace is switching");
2453
+ const generation = this.projectGeneration;
2349
2454
  const maxSubagents = Number(process.env.PI_WEB_MAX_SUBAGENTS) || 8;
2350
2455
  const liveCount = this.getLiveSubagentsCount();
2351
2456
  if (liveCount >= maxSubagents) {
@@ -2434,6 +2539,8 @@ export class UniversalSession {
2434
2539
  // 驱动不支持或模型设置失败时平滑降级
2435
2540
  }
2436
2541
  }
2542
+ if (this.disposed || generation !== this.projectGeneration || this.subagentDrivers.get(convId) !== subDriver)
2543
+ return { convId };
2437
2544
  // 异步启动子代理执行流程
2438
2545
  void this.runSubagent(convId, subDriver, effectivePrompt, targetCwd);
2439
2546
  return { convId };
@@ -2443,6 +2550,8 @@ export class UniversalSession {
2443
2550
  const conv = this.conversations.get(convId);
2444
2551
  if (!conv)
2445
2552
  return;
2553
+ const generation = this.projectGeneration;
2554
+ const isCurrent = () => !this.disposed && generation === this.projectGeneration && this.subagentDrivers.get(convId) === subDriver;
2446
2555
  const now = Date.now();
2447
2556
  const assistantMsgId = `a-${now}-${randomUUID().slice(0, 6)}`;
2448
2557
  let thinkingText = "";
@@ -2456,6 +2565,11 @@ export class UniversalSession {
2456
2565
  };
2457
2566
  conv.messages.push(assistantMsg);
2458
2567
  const sink = {
2568
+ onSessionStarted: (sessionId) => {
2569
+ conv.driverSessionId = sessionId;
2570
+ if (!conv.isEphemeral)
2571
+ this.store.saveConversation(cwd, conv);
2572
+ },
2459
2573
  onThinkingDelta: (delta) => {
2460
2574
  thinkingText += delta;
2461
2575
  let thinkBlock = assistantMsg.content.find((b) => b.type === "thinking");
@@ -2564,9 +2678,19 @@ export class UniversalSession {
2564
2678
  const sid = await subDriver.createSession();
2565
2679
  conv.driverSessionId = sid;
2566
2680
  }
2567
- await subDriver.sendPrompt(prompt, undefined, sink);
2681
+ if (!isCurrent())
2682
+ return;
2683
+ const guardedSink = new Proxy(sink, {
2684
+ get: (target, key) => (...args) => {
2685
+ if (isCurrent())
2686
+ target[key]?.(...args);
2687
+ },
2688
+ });
2689
+ await subDriver.sendPrompt(prompt, undefined, guardedSink);
2568
2690
  }
2569
2691
  catch (err) {
2692
+ if (!isCurrent())
2693
+ return;
2570
2694
  const msg = err instanceof Error ? err.message : String(err);
2571
2695
  sink.onError(msg);
2572
2696
  }
@@ -2762,6 +2886,8 @@ export class UniversalSession {
2762
2886
  }
2763
2887
  dispose() {
2764
2888
  this.disposed = true;
2889
+ this.finalizeTurn();
2890
+ this.projectGeneration++;
2765
2891
  if (this.snapshotTimer) {
2766
2892
  clearTimeout(this.snapshotTimer);
2767
2893
  this.snapshotTimer = null;