pi-web-ui 0.113.0 → 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 (228) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/README.md +117 -252
  3. package/README.zh-CN.md +145 -223
  4. package/README.zh-TW.md +145 -223
  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 +145 -20
  8. package/dist/gh-comment-781.md +5 -0
  9. package/dist/server/agent-service-daemon.js +102 -24
  10. package/dist/server/agent-service.js +2296 -1121
  11. package/dist/server/approval-rules.js +29 -3
  12. package/dist/server/ask-user-question-tool.js +8 -8
  13. package/dist/server/atomic-file.js +35 -14
  14. package/dist/server/attachment-store.js +71 -35
  15. package/dist/server/attachments.js +18 -8
  16. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  17. package/dist/server/canvas/canvas-dispatch.js +61 -20
  18. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  19. package/dist/server/canvas/canvas-scheduler.js +99 -0
  20. package/dist/server/canvas/canvas-store.js +107 -54
  21. package/dist/server/canvas/canvas-validation.js +131 -0
  22. package/dist/server/canvas/canvas-workspace.js +284 -0
  23. package/dist/server/client-id-utils.js +8 -0
  24. package/dist/server/client-state.js +104 -22
  25. package/dist/server/communicate-tool.js +76 -0
  26. package/dist/server/compact-context-tool.js +2 -3
  27. package/dist/server/compaction-instructions.js +75 -0
  28. package/dist/server/compaction-markers.js +7 -2
  29. package/dist/server/compaction-state.js +84 -0
  30. package/dist/server/composer-drafts.js +43 -40
  31. package/dist/server/context-evidence.js +346 -0
  32. package/dist/server/control-socket.js +6 -2
  33. package/dist/server/conversation-communication.js +368 -0
  34. package/dist/server/conversation-read-tool.js +3 -4
  35. package/dist/server/conversation-tool-names.js +14 -0
  36. package/dist/server/conversation-tool.js +57 -0
  37. package/dist/server/delegate-mode.js +17 -4
  38. package/dist/server/device-center/bot-catalog.js +88 -0
  39. package/dist/server/device-center/bot-execution.js +106 -0
  40. package/dist/server/device-center/bots.js +170 -0
  41. package/dist/server/device-center/collab-service.js +153 -0
  42. package/dist/server/device-center/collab-tool.js +184 -0
  43. package/dist/server/device-center/connector.js +332 -0
  44. package/dist/server/device-center/desktop-linux.js +372 -0
  45. package/dist/server/device-center/desktop-native.js +413 -0
  46. package/dist/server/device-center/desktop-page.js +232 -0
  47. package/dist/server/device-center/desktop-setup.js +30 -0
  48. package/dist/server/device-center/desktop.js +387 -0
  49. package/dist/server/device-center/device-portals.js +241 -0
  50. package/dist/server/device-center/execution-failure.js +70 -0
  51. package/dist/server/device-center/executor.js +371 -0
  52. package/dist/server/device-center/file-sync.js +493 -0
  53. package/dist/server/device-center/hub-auth.js +69 -0
  54. package/dist/server/device-center/hub-page.js +68 -0
  55. package/dist/server/device-center/hub-setup.js +214 -0
  56. package/dist/server/device-center/hub.js +829 -0
  57. package/dist/server/device-center/local-page.js +17 -0
  58. package/dist/server/device-center/local.js +476 -0
  59. package/dist/server/device-center/main.js +118 -0
  60. package/dist/server/device-center/native-desktop/macos.js +192 -0
  61. package/dist/server/device-center/native-desktop/windows.js +118 -0
  62. package/dist/server/device-center/path-portal.js +120 -0
  63. package/dist/server/device-center/relay.js +959 -0
  64. package/dist/server/device-center/runtime.js +253 -0
  65. package/dist/server/device-center/smoke-preview.js +3 -0
  66. package/dist/server/device-center/store.js +122 -0
  67. package/dist/server/device-center/task-error.js +14 -0
  68. package/dist/server/device-center/transfers.js +293 -0
  69. package/dist/server/device-center/workspaces.js +45 -0
  70. package/dist/server/dispatch-domain-handlers.js +83 -27
  71. package/dist/server/dsh/dsh-agent-service.js +277 -158
  72. package/dist/server/dsh/dsh-client.js +12 -2
  73. package/dist/server/durable/durable-agent-service.js +1 -1
  74. package/dist/server/evidence-tool-hooks.js +49 -0
  75. package/dist/server/file-save.js +95 -0
  76. package/dist/server/file-transfer-routes.js +97 -47
  77. package/dist/server/files-service.js +110 -34
  78. package/dist/server/goal-review-gate.js +16 -6
  79. package/dist/server/goal-service.js +54 -30
  80. package/dist/server/http-proxy.js +120 -0
  81. package/dist/server/index.js +236 -232
  82. package/dist/server/load-timing.js +31 -0
  83. package/dist/server/mcp-bridge.js +219 -94
  84. package/dist/server/mcp-hot-reload.js +31 -5
  85. package/dist/server/mcp-manager.js +192 -93
  86. package/dist/server/mcp-oauth-login.js +169 -0
  87. package/dist/server/mcp-oauth-ui.js +137 -0
  88. package/dist/server/mcp-oauth.js +395 -0
  89. package/dist/server/mcp-project-runtime.js +207 -0
  90. package/dist/server/message-window.js +74 -21
  91. package/dist/server/net-guard.js +122 -20
  92. package/dist/server/payload-limits.js +17 -0
  93. package/dist/server/pending-question.js +82 -0
  94. package/dist/server/plan-mode.js +338 -137
  95. package/dist/server/plugin-assets.js +8 -4
  96. package/dist/server/plugin-chat-attachments.js +48 -0
  97. package/dist/server/plugin-facilities.js +67 -220
  98. package/dist/server/plugin-installer.js +2 -1
  99. package/dist/server/plugin-removal.js +49 -0
  100. package/dist/server/plugin-secrets.js +179 -0
  101. package/dist/server/plugins.js +262 -92
  102. package/dist/server/preset-fields.js +49 -0
  103. package/dist/server/preset-plugin-dependencies.js +57 -0
  104. package/dist/server/preset-share.js +112 -72
  105. package/dist/server/protocol-version.js +1 -1
  106. package/dist/server/queue-modes.js +10 -0
  107. package/dist/server/remote-ssh-service.js +160 -67
  108. package/dist/server/request-context.js +164 -0
  109. package/dist/server/sandbox-data.js +655 -0
  110. package/dist/server/sandbox-engines.js +7 -0
  111. package/dist/server/sandbox-runtime-gate.js +41 -0
  112. package/dist/server/sandbox-service.js +139 -698
  113. package/dist/server/sandbox-tool.js +21 -4
  114. package/dist/server/scheduler-tasks.js +63 -48
  115. package/dist/server/serialize.js +48 -19
  116. package/dist/server/session-branch.js +25 -3
  117. package/dist/server/session-parser.js +28 -18
  118. package/dist/server/session-scan.js +130 -0
  119. package/dist/server/session-search.js +51 -37
  120. package/dist/server/settings-service.js +267 -111
  121. package/dist/server/setup-config.js +58 -0
  122. package/dist/server/skill-maintenance.js +112 -24
  123. package/dist/server/subagent-helpers.js +4 -1
  124. package/dist/server/subagent-notify.js +4 -1
  125. package/dist/server/subagent-security-gate.js +52 -11
  126. package/dist/server/subagent-task.js +27 -0
  127. package/dist/server/subagents.js +217 -46
  128. package/dist/server/tabs.js +9 -1
  129. package/dist/server/terminals.js +467 -363
  130. package/dist/server/tool-guards.js +42 -6
  131. package/dist/server/tool-manager.js +47 -20
  132. package/dist/server/tool-overrides.js +13 -11
  133. package/dist/server/tool-prompt-overrides.js +32 -2
  134. package/dist/server/tool-prompts.js +1 -1
  135. package/dist/server/turn-timing.js +11 -0
  136. package/dist/server/universal/session-store.js +48 -6
  137. package/dist/server/universal/universal-service.js +1 -1
  138. package/dist/server/universal/universal-session.js +334 -231
  139. package/dist/server/uploads.js +64 -5
  140. package/dist/server/webui-context.js +6 -6
  141. package/dist/server/worktree-service.js +32 -24
  142. package/dist/server/ws-pending-queue.js +73 -27
  143. package/dist/test-artifact.md +9 -0
  144. package/dist/test-preview-modal.md +11 -0
  145. package/dist/test-report.html +20 -0
  146. package/docs/device-center.md +142 -0
  147. package/docs/device-desktop.md +48 -0
  148. package/package.json +4 -1
  149. package/plugin-sdk/index.d.ts +45 -9
  150. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  151. package/plugins/catalog.json +1 -1
  152. package/themes/aetheris.css +1 -107
  153. package/themes/ayu-light.css +5 -29
  154. package/themes/bases/flow-base.css +0 -6
  155. package/themes/bases/statusbar-flat-base.css +112 -0
  156. package/themes/bases/zhujian-base.css +1 -0
  157. package/themes/bases/zhupi-base.css +1 -0
  158. package/themes/catppuccin-latte.css +4 -27
  159. package/themes/catppuccin.css +4 -35
  160. package/themes/claude-code-dark.css +1 -0
  161. package/themes/codex.css +4 -28
  162. package/themes/cyberpunk.css +3 -61
  163. package/themes/dark-teal.css +0 -1
  164. package/themes/dazzle.css +3 -73
  165. package/themes/everforest-light.css +4 -27
  166. package/themes/geist.css +4 -28
  167. package/themes/gruvbox-light.css +4 -27
  168. package/themes/kanagawa-lotus.css +4 -27
  169. package/themes/md-preview.css +3 -213
  170. package/themes/mist.css +4 -24
  171. package/themes/nord.css +4 -35
  172. package/themes/one-dark.css +4 -37
  173. package/themes/paper.css +4 -16
  174. package/themes/rose-pine-dawn.css +4 -28
  175. package/themes/sakura.css +4 -24
  176. package/themes/solarized-light.css +4 -27
  177. package/themes/tokyo-night.css +3 -34
  178. package/themes/white.css +4 -26
  179. package/themes/zhujian-dark.css +1 -0
  180. package/themes/zhupi-dark.css +1 -0
  181. package/web/dist/.build-assets.json +1 -0
  182. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  183. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  184. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  185. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  186. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  187. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  188. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  189. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  190. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  191. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  192. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  193. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  194. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  195. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  196. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  197. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  198. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  199. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  200. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  201. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  202. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  203. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  204. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  205. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  206. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  207. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  208. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  209. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  210. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  211. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  212. package/web/dist/assets/index-Cje8iugL.js +83 -0
  213. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  214. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  215. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  216. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  217. package/web/dist/assets/math-BorAY7qD.css +1 -0
  218. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  219. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  220. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  221. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  222. package/web/dist/index.html +15 -9
  223. package/web/dist/sw.js +1 -1
  224. package/web/dist/assets/TerminalPanel-3wojLfLk.js +0 -3
  225. package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
  226. package/web/dist/assets/index-BwL7qBh6.css +0 -1
  227. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  228. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -7,11 +7,13 @@
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";
@@ -19,10 +21,12 @@ import { ModelAdminService } from "../model-admin.js";
19
21
  import { WebUIContext } from "../webui-context.js";
20
22
  import { ClaudeCodeDriver, probeClaudeCode } from "./drivers/claude-code.js";
21
23
  import { normalizeUiLayout, settingsPresetToUi } from "../client-state.js";
24
+ import { messageTextWithQuotes } from "../text-quote.js";
22
25
  import { readModelsJson, getModelThinkingLevelFromSettings, saveModelThinkingLevelToSettings, } from "../model-resolver.js";
23
26
  import { DEFAULT_UNIVERSAL_CAPABILITIES } from "../engine-capabilities.js";
24
27
  import { unsupportedToolInfo } from "../tool-info.js";
25
28
  import { SandboxManager } from "../sandbox-service.js";
29
+ import { assertEngineWorkspaceSupported } from "../sandbox-engines.js";
26
30
  import { getWorktreeContext, removeWorktree } from "../worktree-service.js";
27
31
  import { MarkerService } from "../marker-service.js";
28
32
  import { SlashCommandsService, parseSlash } from "../slash-commands.js";
@@ -37,7 +41,7 @@ import { subagentTitle, isSubagentTerminal, computeWaitCapMs, makeSubagentTools,
37
41
  import { recordSubagentHandoff, formatSubagentHandoffMessage, } from "../subagent-handoff.js";
38
42
  import { pick } from "../i18n.js";
39
43
  import { fetchRemoteSkillMarket, fetchRemoteSkillContent, fetchRemoteMcpMarket } from "../market-service.js";
40
- import { exportPresetVia, importPresetVia, importPresetFromUrlVia, pushPresetCatalogVia, sharePresetVia, } from "../preset-share.js";
44
+ import { exportPresetVia, importPresetVia, importPresetFromUrlVia, pushPresetCatalogVia, sharePresetVia, sanitizePresetSettings, } from "../preset-share.js";
41
45
  const SNAPSHOT_INTERVAL_MS = 60;
42
46
  function clampThinkingLevelToSupported(supported, current) {
43
47
  if (supported.includes(current))
@@ -86,6 +90,11 @@ export class UniversalSession {
86
90
  /** 在途回合归属的会话 id(#700/#701):prompt 开始时锚定,finalizeTurn 收尾时消费并清空。
87
91
  * 会话切换/回滚不再让流式回写与回合收尾锚错会话,避免跨对话内容污染落盘。 */
88
92
  turnConvId = null;
93
+ turn = null;
94
+ projectGeneration = 0;
95
+ switchingProject = false;
96
+ abortPromise = null;
97
+ markerOrigins = new Map();
89
98
  streamingMessage = null;
90
99
  streamingThinking = "";
91
100
  streamingText = "";
@@ -119,6 +128,7 @@ export class UniversalSession {
119
128
  this.pluginCommandsProvider = opts.pluginCommandsProvider;
120
129
  this.onQuit = opts.onQuit;
121
130
  this.sandboxes = new SandboxManager(this.dataDir);
131
+ assertEngineWorkspaceSupported(this.sandboxes, this.cwd, this.engine);
122
132
  void this.refreshWorktreeInfo();
123
133
  this.lang = opts.lang ?? "zh";
124
134
  this.webUi = new WebUIContext((msg) => this.send(msg));
@@ -248,7 +258,15 @@ export class UniversalSession {
248
258
  getActiveConversationId: () => this.activeConvId,
249
259
  getSessionManager: () => undefined,
250
260
  renameConversation: (convId, title) => {
251
- void this.renameConversation(convId, title);
261
+ const origin = this.markerOrigins.get(convId);
262
+ if (!origin || this.disposed)
263
+ return;
264
+ origin.conv.title = title;
265
+ origin.conv.updatedAt = Date.now();
266
+ if (!origin.conv.isEphemeral)
267
+ this.store.saveConversation(origin.cwd, origin.conv);
268
+ if (this.cwd === origin.cwd)
269
+ this.flushSnapshot();
252
270
  },
253
271
  refreshMarkers: () => this.flushSnapshot(),
254
272
  onActionsChange: (convId) => {
@@ -301,8 +319,9 @@ export class UniversalSession {
301
319
  isDisposed: () => this.disposed,
302
320
  getCwd: () => this.cwd,
303
321
  getActiveCwd: () => this.cwd,
322
+ getUploadMaxBytes: () => uploadLimitBytes(this.stateStore?.getSettings(this.clientId) ?? {}, "workspace"),
304
323
  });
305
- this.terminals = new TerminalManager((msg) => this.send(msg), this.cwd, () => this.getLang());
324
+ this.terminals = new TerminalManager((msg) => this.send(msg), () => this.cwd, () => this.getLang(), "client");
306
325
  this.bg = new BgServerTracker({
307
326
  emit: (msg) => this.send(msg),
308
327
  flushSnapshot: () => this.flushSnapshot(),
@@ -442,8 +461,16 @@ export class UniversalSession {
442
461
  send({ type: "default_model", modelId: defModel });
443
462
  }
444
463
  const terminals = this.terminals.list();
445
- if (terminals.length > 0) {
446
- this.send({ type: "terminal_list", conversationId: this.activeConvId, terminals });
464
+ this.send({ type: "terminal_list", conversationId: this.activeConvId, terminals });
465
+ for (const output of this.terminals.replay()) {
466
+ this.send({
467
+ type: "terminal_output",
468
+ conversationId: this.activeConvId,
469
+ ownerKind: "client",
470
+ terminalId: output.terminalId,
471
+ data: output.data,
472
+ reset: true,
473
+ });
447
474
  }
448
475
  this.bg.push();
449
476
  void this.refreshSessions();
@@ -497,6 +524,7 @@ export class UniversalSession {
497
524
  // 回合归属会话才携带流式态:切走后的前台会话快照不再混入后台回合内容(#701)
498
525
  streamingMessage: !this.turnConvId || this.turnConvId === conv.id ? this.streamingMessage : null,
499
526
  isStreaming: !this.turnConvId || this.turnConvId === conv.id ? this.isStreaming : false,
527
+ turnTiming: conv.turnTiming ?? null,
500
528
  isEphemeral: Boolean(conv.isEphemeral),
501
529
  draft: this.sessionDrafts.get(conv.id) ?? null,
502
530
  model: {
@@ -554,7 +582,14 @@ export class UniversalSession {
554
582
  const t = (title ?? "").trim();
555
583
  return !t || t === "新对话" || t === "New chat" || t === "New Chat" || t === "对话" || t === "Chat";
556
584
  }
557
- async prompt(text, attachments, _queue) {
585
+ activeConversationId() {
586
+ return this.activeConvId;
587
+ }
588
+ async prompt(text, attachments, _queue, targetConv = this.activeConv, rebuiltContext = "") {
589
+ assertEngineWorkspaceSupported(this.sandboxes, this.cwd, this.engine);
590
+ if (this.switchingProject || this.disposed || this.abortPromise)
591
+ return;
592
+ const generation = this.projectGeneration;
558
593
  if (this.isStreaming) {
559
594
  if (_queue === true) {
560
595
  const entry = createQueuedEntry(text, { attachments });
@@ -597,148 +632,178 @@ export class UniversalSession {
597
632
  const skillPrompt = instruction
598
633
  ? `[Skill: ${found.name}]\n${instruction}\n\n[User Prompt]\n${slash.args || "执行此技能"}`
599
634
  : slash.args || text;
600
- return this.prompt(skillPrompt, attachments, _queue);
635
+ return this.prompt(skillPrompt, attachments, _queue, targetConv, rebuiltContext);
601
636
  }
602
637
  }
603
638
  const handled = await this.slash.exec(slash.name, slash.args);
604
639
  if (handled)
605
640
  return;
606
641
  }
642
+ if (this.switchingProject || this.disposed || this.abortPromise || generation !== this.projectGeneration)
643
+ return;
644
+ if (this.activeConv !== targetConv)
645
+ return;
607
646
  this.isStreaming = true;
608
- const conv = this.activeConv;
647
+ const conv = targetConv;
648
+ startTurnTiming(conv);
649
+ const turn = { conv, cwd: this.cwd };
650
+ this.turn = turn;
651
+ const isCurrent = () => this.turn === turn && !this.disposed;
609
652
  this.turnConvId = conv.id;
610
653
  const now = Date.now();
611
654
  // 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);
655
+ try {
656
+ const availableSkills = await this.collectUniversalSkills();
657
+ if (!isCurrent())
658
+ return;
659
+ const scanResult = scanAtMentions(text, turn.cwd, availableSkills, attachments ?? []);
660
+ const effectiveAttachments = [...(attachments ?? []), ...scanResult.detectedAttachments];
661
+ const finalPrompt = formatPromptWithSkills(text, scanResult.detectedSkills);
662
+ // 3. 自动根据首条提问为新会话命名(首条提问立即刷新左侧栏运行与历史列表)
663
+ const hasNoUserMessages = !conv.messages.some((m) => m.role === "user");
664
+ if (UniversalSession.isDefaultTitle(conv.title) && hasNoUserMessages && text.trim()) {
665
+ const trimmed = text.trim().replace(/\s+/g, " ");
666
+ const cleanTitle = trimmed.length > 30 ? `${trimmed.slice(0, 30)}…` : trimmed;
667
+ conv.title = cleanTitle;
668
+ if (this.stateStore) {
669
+ this.stateStore.saveSessionTitle(this.cwd, conv.id, cleanTitle);
670
+ }
671
+ if (!conv.isEphemeral) {
672
+ this.store.saveConversation(this.cwd, conv);
673
+ }
674
+ void this.refreshSessions();
627
675
  }
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);
676
+ // 4. 插入用户消息以及附件卡片(保证 Web UI 附件卡片折叠呈现与历史复原)
677
+ const userMsg = {
678
+ id: `u-${now}-${randomUUID().slice(0, 6)}`,
679
+ role: "user",
680
+ content: [{ type: "text", text }],
681
+ timestamp: now,
682
+ };
683
+ conv.messages.push(userMsg);
684
+ if (effectiveAttachments.length > 0) {
685
+ const attCards = createAttachmentUiMessages(effectiveAttachments, now);
686
+ for (const card of attCards) {
687
+ conv.messages.push(card);
688
+ }
642
689
  }
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;
690
+ conv.updatedAt = now;
657
691
  if (!conv.isEphemeral) {
658
692
  this.store.saveConversation(this.cwd, conv);
659
693
  }
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)
694
+ // 用户发送了提示词,消费并清除当前会话的草稿
695
+ this.sessionDrafts.delete(conv.id);
696
+ // 确保底层驱动与当前对话的 driverSessionId 上下文同步(保证多轮对话连续且新建对话隔离)
697
+ if (conv.driverSessionId) {
698
+ await this.driver.resumeSession(conv.driverSessionId);
699
+ if (!isCurrent())
678
700
  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)
701
+ }
702
+ else {
703
+ const sid = await this.driver.createSession();
704
+ if (!isCurrent())
691
705
  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 });
706
+ conv.driverSessionId = sid;
707
+ if (!conv.isEphemeral) {
708
+ this.store.saveConversation(turn.cwd, conv);
698
709
  }
699
- this.emitDelta({ type: "text_delta", delta });
700
- this.scheduleThrottledSnapshot();
701
- },
702
- onToolStart: (callId, toolName, args) => {
703
- if (!this.streamingMessage)
710
+ }
711
+ // 3. 准备助手流式消息
712
+ const assistantMsgId = `a-${now}-${randomUUID().slice(0, 6)}`;
713
+ this.streamingThinking = "";
714
+ this.streamingText = "";
715
+ this.streamingMessage = {
716
+ id: assistantMsgId,
717
+ role: "assistant",
718
+ content: [],
719
+ timestamp: now,
720
+ model: this.currentModel,
721
+ };
722
+ this.flushSnapshot();
723
+ // 4. 构建 AgentEventSink(时序保真:思考 -> 前置正文 -> 工具调用 -> 总结正文)
724
+ const sink = {
725
+ onThinkingDelta: (delta) => {
726
+ this.streamingThinking += delta;
727
+ if (!this.streamingMessage)
728
+ return;
729
+ let thinkBlock = this.streamingMessage.content.find((b) => b.type === "thinking");
730
+ if (!thinkBlock) {
731
+ thinkBlock = { type: "thinking", thinking: "" };
732
+ this.streamingMessage.content.unshift(thinkBlock);
733
+ }
734
+ thinkBlock.thinking = this.streamingThinking;
735
+ this.emitDelta({ type: "thinking_delta", delta });
736
+ this.scheduleThrottledSnapshot();
737
+ },
738
+ onTextDelta: (delta) => {
739
+ this.streamingText += delta;
740
+ if (!this.streamingMessage)
741
+ return;
742
+ const lastBlock = this.streamingMessage.content[this.streamingMessage.content.length - 1];
743
+ if (lastBlock && lastBlock.type === "text" && !lastBlock.truncated) {
744
+ lastBlock.text += delta;
745
+ }
746
+ else {
747
+ this.streamingMessage.content.push({ type: "text", text: delta });
748
+ }
749
+ this.emitDelta({ type: "text_delta", delta });
750
+ this.scheduleThrottledSnapshot();
751
+ },
752
+ onToolStart: (callId, toolName, args) => {
753
+ if (!this.streamingMessage)
754
+ return;
755
+ const toolBlock = {
756
+ type: "toolCall",
757
+ id: callId,
758
+ name: toolName,
759
+ argumentsText: JSON.stringify(args, null, 2),
760
+ };
761
+ this.streamingMessage.content.push(toolBlock);
762
+ this.scheduleThrottledSnapshot();
763
+ },
764
+ onToolEnd: (callId, result) => {
765
+ const toolMsg = {
766
+ id: `t-${callId}`,
767
+ role: "toolResult",
768
+ toolCallId: callId,
769
+ content: [{ type: "text", text: result.output ?? result.error ?? "" }],
770
+ isError: Boolean(result.error),
771
+ timestamp: Date.now(),
772
+ };
773
+ this.pendingToolResults.push(toolMsg);
774
+ this.scheduleThrottledSnapshot();
775
+ },
776
+ onTurnComplete: (meta) => {
777
+ this.finalizeTurn(meta);
778
+ },
779
+ onError: (err) => {
780
+ const errText = typeof err === "string" ? err : err.message;
781
+ this.emitNotice("error", `执行出错: ${errText}`, `Execution error: ${errText}`);
782
+ this.finalizeTurn();
783
+ },
784
+ };
785
+ try {
786
+ const guardedSink = new Proxy(sink, {
787
+ get: (target, key) => (...args) => {
788
+ if (isCurrent())
789
+ target[key]?.(...args);
790
+ },
791
+ });
792
+ await this.driver.sendPrompt(rebuiltContext ? `${rebuiltContext}\n\n${finalPrompt}` : finalPrompt, effectiveAttachments, guardedSink);
793
+ }
794
+ catch (err) {
795
+ if (!isCurrent())
704
796
  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}`);
797
+ const msg = err instanceof Error ? err.message : String(err);
798
+ this.emitNotice("error", `驱动执行异常: ${msg}`, `Driver execution error: ${msg}`);
732
799
  this.finalizeTurn();
733
- },
734
- };
735
- try {
736
- await this.driver.sendPrompt(finalPrompt, effectiveAttachments, sink);
800
+ }
737
801
  }
738
802
  catch (err) {
739
- const msg = err instanceof Error ? err.message : String(err);
740
- this.emitNotice("error", `驱动执行异常: ${msg}`, `Driver execution error: ${msg}`);
803
+ if (!isCurrent())
804
+ return;
741
805
  this.finalizeTurn();
806
+ this.emitNotice("error", String(err), String(err));
742
807
  }
743
808
  }
744
809
  updateStreamingContent() {
@@ -776,10 +841,12 @@ export class UniversalSession {
776
841
  clearTimeout(this.snapshotTimer);
777
842
  this.snapshotTimer = null;
778
843
  }
779
- // 回合收尾锚定回合归属会话:中途切走/回滚不再把本轮内容写进别的会话(#700/#701)
780
- const turnId = this.turnConvId;
844
+ const turn = this.turn;
845
+ if (!turn)
846
+ return;
847
+ this.turn = null;
781
848
  this.turnConvId = null;
782
- const conv = (turnId && this.conversations.get(turnId)) || this.activeConv;
849
+ const conv = turn.conv;
783
850
  if (this.streamingMessage) {
784
851
  conv.messages.push(this.streamingMessage);
785
852
  this.streamingMessage = null;
@@ -822,6 +889,7 @@ export class UniversalSession {
822
889
  conv.driverSessionId = activeSid;
823
890
  }
824
891
  }
892
+ finishTurnTiming(conv);
825
893
  this.isStreaming = false;
826
894
  this.streamingThinking = "";
827
895
  // 先取本轮全文再清空:内联标记解析在清空之后读 streamingText,
@@ -831,26 +899,38 @@ export class UniversalSession {
831
899
  this.streamingText = "";
832
900
  conv.updatedAt = Date.now();
833
901
  if (!conv.isEphemeral) {
834
- this.store.saveConversation(this.cwd, conv);
902
+ this.store.saveConversation(turn.cwd, conv);
835
903
  }
836
904
  // 解析本轮生成的内联标记(如 [[conv:rename:...]] / [[action:suggest:...]])
837
905
  if (finalText && finalText.includes("[[")) {
906
+ this.markerOrigins.set(conv.id, turn);
838
907
  void this.markerSvc.handleAssistantText(conv.id, finalText);
839
908
  }
840
909
  this.flushSnapshot();
841
910
  void this.refreshSessions();
842
911
  // 检查排队消息并自动处理
843
- if (this.followUpQueue.length > 0) {
912
+ if (!this.switchingProject && !this.disposed && this.followUpQueue.length > 0) {
844
913
  const next = this.followUpQueue.shift();
845
914
  this.flushSnapshot(true);
846
915
  void this.prompt(next.text, next.attachments);
847
916
  }
848
917
  }
849
918
  async abort() {
850
- if (this.isStreaming) {
851
- await this.driver.abort();
919
+ if (this.abortPromise)
920
+ return this.abortPromise;
921
+ if (!this.isStreaming)
922
+ return;
923
+ // Install the gate before finalizeTurn can dispatch a queued prompt.
924
+ this.abortPromise = Promise.resolve().then(async () => {
852
925
  this.finalizeTurn();
926
+ await this.driver.abort();
853
927
  this.emitNotice("info", "已停止生成", "Generation stopped");
928
+ });
929
+ try {
930
+ await this.abortPromise;
931
+ }
932
+ finally {
933
+ this.abortPromise = null;
854
934
  }
855
935
  }
856
936
  async abortBash() {
@@ -882,7 +962,7 @@ export class UniversalSession {
882
962
  // ---------------------------------------------------------------------------
883
963
  // 对话生命周期
884
964
  // ---------------------------------------------------------------------------
885
- async newChat(_preset, ephemeral = false) {
965
+ async newChat(_preset, ephemeral = false, onReady) {
886
966
  const newConv = this.createEmptyConversation("新对话", Boolean(ephemeral));
887
967
  this.conversations.set(newConv.id, newConv);
888
968
  this.activeConvId = newConv.id;
@@ -891,9 +971,11 @@ export class UniversalSession {
891
971
  }
892
972
  this.flushSnapshot(true);
893
973
  void this.refreshSessions();
974
+ onReady?.(newConv.id);
894
975
  return true;
895
976
  }
896
977
  async switchConversation(id) {
978
+ assertEngineWorkspaceSupported(this.sandboxes, this.cwd, this.engine);
897
979
  let conv = this.conversations.get(id);
898
980
  if (!conv) {
899
981
  conv = this.store.loadConversation(this.cwd, id) ?? undefined;
@@ -1152,41 +1234,27 @@ export class UniversalSession {
1152
1234
  this.flushSnapshot();
1153
1235
  return;
1154
1236
  }
1155
- // 截断到编辑点之前的所有历史消息(跳过属于本轮提问的前置附件卡片,避免 prompt 重新注入后附件重复),
1156
- // fork 一个新的 UniversalConversation
1237
+ // Remove the question, its file asides and the abandoned suffix in place.
1157
1238
  let cutIdx = idx;
1158
1239
  while (cutIdx > 0 &&
1159
1240
  conv.messages[cutIdx - 1]?.role === "custom" &&
1160
1241
  conv.messages[cutIdx - 1]?.customType === "file") {
1161
1242
  cutIdx--;
1162
1243
  }
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);
1244
+ conv.messages.splice(cutIdx);
1245
+ // Drivers expose no in-place history replacement. A fresh backend handle
1246
+ // prevents resume from restoring the discarded suffix; the UI identity stays.
1247
+ conv.driverSessionId = undefined;
1248
+ const context = conv.messages.map((m) => `[${m.role}] ${messageTextWithQuotes(m)}`).join("\n");
1249
+ conv.updatedAt = Date.now();
1250
+ this.followUpQueue.length = 0;
1251
+ if (!conv.isEphemeral) {
1252
+ this.store.saveConversation(this.cwd, conv);
1184
1253
  }
1185
- this.activeConvId = forkedConv.id;
1186
1254
  this.flushSnapshot(true);
1187
1255
  void this.refreshSessions();
1188
- // 将编辑后的内容作为新 prompt 投递执行,实现无缝编辑重试
1189
- await this.prompt(text, attachments);
1256
+ // Capture the destination before any asynchronous slash/skill lookup.
1257
+ await this.prompt(text, attachments, undefined, conv, context ? `Previous conversation context:\n${context}` : "");
1190
1258
  }
1191
1259
  async refreshSessions() {
1192
1260
  const memoryConvs = Array.from(this.conversations.values());
@@ -1357,8 +1425,8 @@ export class UniversalSession {
1357
1425
  async writeFile(path, text) {
1358
1426
  await this.files.writeFile(path, text);
1359
1427
  }
1360
- async uploadFile(dirPath, name, data) {
1361
- await this.files.uploadFile(dirPath, name, data);
1428
+ async uploadFile(dirPath, name, data, uploadId) {
1429
+ await this.files.uploadFile(dirPath, name, data, uploadId);
1362
1430
  }
1363
1431
  async createEntry(dir, name, kind) {
1364
1432
  await this.files.createEntry(dir, name, kind);
@@ -1387,8 +1455,10 @@ export class UniversalSession {
1387
1455
  getUserTerminalManager() {
1388
1456
  return this.terminals;
1389
1457
  }
1390
- findTerminalManager() {
1391
- return this.terminals;
1458
+ findTerminalManager(terminalId, _conversationId, ownerKind) {
1459
+ if (ownerKind === "conversation")
1460
+ return undefined;
1461
+ return this.terminals.has(terminalId) ? this.terminals : undefined;
1392
1462
  }
1393
1463
  getTerminalCwd() {
1394
1464
  return this.cwd;
@@ -1510,37 +1580,52 @@ export class UniversalSession {
1510
1580
  this.flushSnapshot();
1511
1581
  }
1512
1582
  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);
1583
+ assertEngineWorkspaceSupported(this.sandboxes, path, this.engine);
1584
+ if (this.switchingProject)
1585
+ throw new Error("Workspace switch already in progress");
1586
+ this.switchingProject = true;
1587
+ try {
1588
+ // Finish the captured old turn before replacing the driver's workspace.
1589
+ this.followUpQueue = [];
1590
+ await this.abort();
1591
+ for (const id of this.subagentDrivers.keys())
1592
+ await this.stopSubagent(id);
1593
+ this.projectGeneration++;
1594
+ this.cwd = path;
1595
+ this.driver.setCwd(path);
1596
+ // 切换工作区 CWD:清空旧目录会话缓存与草稿,并加载属于新目录的会话
1597
+ this.conversations.clear();
1598
+ this.sessionDrafts.clear();
1599
+ const existing = this.store.listConversations(this.cwd);
1600
+ if (existing.length > 0) {
1601
+ for (const conv of existing) {
1602
+ this.conversations.set(conv.id, conv);
1603
+ }
1604
+ this.activeConvId = existing[0].id;
1522
1605
  }
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);
1606
+ else {
1607
+ const initialConv = this.createEmptyConversation("新对话");
1608
+ this.activeConvId = initialConv.id;
1609
+ this.conversations.set(initialConv.id, initialConv);
1610
+ this.store.saveConversation(this.cwd, initialConv);
1611
+ }
1612
+ await this.refreshSessions();
1613
+ await this.refreshWorktreeInfo();
1614
+ if (typeof this.stateStore?.remember === "function") {
1615
+ this.stateStore.remember(this.clientId, path);
1616
+ }
1617
+ void this.pushProjects();
1618
+ // 切换目录后恢复该目录按引擎隔离的项目记忆模型
1619
+ const savedModel = this.stateStore?.getProjectModel(this.clientId, path, this.engine) ??
1620
+ this.stateStore?.getDefaultModel(this.engine);
1621
+ if (savedModel && savedModel !== this.currentModel) {
1622
+ void this.setModel(savedModel).catch(() => { });
1623
+ }
1624
+ this.flushSnapshot(true);
1535
1625
  }
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(() => { });
1626
+ finally {
1627
+ this.switchingProject = false;
1542
1628
  }
1543
- this.flushSnapshot(true);
1544
1629
  }
1545
1630
  async setWorkspaceRoots(roots) {
1546
1631
  if (this.stateStore) {
@@ -1549,12 +1634,12 @@ export class UniversalSession {
1549
1634
  this.flushSnapshot();
1550
1635
  }
1551
1636
  async refreshWorktreeInfo() {
1552
- try {
1553
- this.worktreeInfo = await getWorktreeContext(this.cwd);
1554
- }
1555
- catch {
1556
- this.worktreeInfo = null;
1557
- }
1637
+ const cwd = this.cwd;
1638
+ const info = await getWorktreeContext(cwd);
1639
+ if (this.cwd !== cwd)
1640
+ return;
1641
+ this.worktreeInfo = info;
1642
+ this.flushSnapshot();
1558
1643
  }
1559
1644
  /** 获取通用底座持有的持久终端交互工具集 */
1560
1645
  getTerminalTools() {
@@ -1645,13 +1730,9 @@ export class UniversalSession {
1645
1730
  messages: compacted,
1646
1731
  });
1647
1732
  }
1648
- async createSandbox(opts) {
1733
+ async createSandbox(_opts) {
1649
1734
  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)`);
1735
+ throw new Error(`引擎 ${this.engine} 不支持受管沙盒执行,请使用 pi。 Engine "${this.engine}" does not support managed sandbox execution; use pi.`);
1655
1736
  }
1656
1737
  catch (err) {
1657
1738
  this.emitNotice("error", `创建沙盒失败:${err.message}`, `Failed to create sandbox: ${err.message}`);
@@ -1660,7 +1741,7 @@ export class UniversalSession {
1660
1741
  async resetSandbox(path) {
1661
1742
  const target = path?.trim() || this.cwd;
1662
1743
  try {
1663
- const { sandbox, copiedFiles } = await this.sandboxes.reset(target);
1744
+ const { sandbox, copiedFiles } = await this.sandboxes.withLifecycle(target, async (_info, lifecycle) => lifecycle.reset());
1664
1745
  this.flushSnapshot();
1665
1746
  this.emitNotice("info", sandbox.sourcePath
1666
1747
  ? `🔄 已重置沙盒「${sandbox.name}」(重新从源项目同步 ${copiedFiles} 个文件)`
@@ -1696,19 +1777,21 @@ export class UniversalSession {
1696
1777
  this.emitNotice("error", `导出沙盒失败:${err.message}`, `Failed to export sandbox: ${err.message}`);
1697
1778
  }
1698
1779
  }
1699
- async diffSandbox(path) {
1780
+ async diffSandbox(path, requestId) {
1700
1781
  const target = path?.trim() || this.cwd;
1701
1782
  try {
1702
1783
  const res = await this.sandboxes.diffWithSource(target);
1703
1784
  this.send({
1704
1785
  type: "sandbox_diff",
1705
1786
  diff: {
1787
+ requestId,
1788
+ expectedRevision: res.expectedRevision,
1706
1789
  sandboxId: res.sandbox.id,
1707
1790
  path: res.sandbox.path,
1708
1791
  sourcePath: res.sourcePath,
1709
- added: res.added.slice(0, 200),
1710
- modified: res.modified.slice(0, 200),
1711
- deleted: res.deleted.slice(0, 200),
1792
+ added: res.added,
1793
+ modified: res.modified,
1794
+ deleted: res.deleted,
1712
1795
  unchangedCount: res.unchangedCount,
1713
1796
  },
1714
1797
  });
@@ -1717,6 +1800,7 @@ export class UniversalSession {
1717
1800
  this.send({
1718
1801
  type: "sandbox_diff",
1719
1802
  diff: {
1803
+ requestId,
1720
1804
  sandboxId: "",
1721
1805
  path: target,
1722
1806
  added: [],
@@ -1728,10 +1812,10 @@ export class UniversalSession {
1728
1812
  });
1729
1813
  }
1730
1814
  }
1731
- async applySandboxToSource(path) {
1815
+ async applySandboxToSource(path, expectedRevision) {
1732
1816
  const target = path?.trim() || this.cwd;
1733
1817
  try {
1734
- const { sandbox, sourcePath, copiedFiles, deletedFiles } = await this.sandboxes.applyToSource(target);
1818
+ const { sandbox, sourcePath, copiedFiles, deletedFiles } = await this.sandboxes.withLifecycle(target, async (_info, lifecycle) => lifecycle.applyToSource(expectedRevision));
1735
1819
  const delSuffixZh = deletedFiles ? `,清理 ${deletedFiles} 个已删除文件` : "";
1736
1820
  const delSuffixEn = deletedFiles ? `, pruned ${deletedFiles} deleted files` : "";
1737
1821
  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 +1826,15 @@ export class UniversalSession {
1742
1826
  }
1743
1827
  async destroySandbox(path) {
1744
1828
  const target = path?.trim() || this.cwd;
1745
- const sbx = this.sandboxes.get(target) ?? this.sandboxes.getByCwd(target);
1746
- if (!sbx)
1747
- return;
1748
1829
  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);
1830
+ const sbx = await this.sandboxes.withLifecycle(target, async (sbx, lifecycle) => {
1831
+ if (this.cwd === sbx.path || this.cwd.startsWith(sbx.path + "/")) {
1832
+ const fallback = sbx.sourcePath && existsSync(sbx.sourcePath) ? sbx.sourcePath : homedir();
1833
+ await this.setCwd(fallback);
1834
+ }
1835
+ await lifecycle.destroy();
1836
+ return sbx;
1837
+ });
1754
1838
  this.emitNotice("info", `🗑️ 已销毁沙盒「${sbx.name}」`, `🗑️ Destroyed sandbox "${sbx.name}"`);
1755
1839
  }
1756
1840
  catch (err) {
@@ -1885,6 +1969,8 @@ export class UniversalSession {
1885
1969
  pushSettings() {
1886
1970
  const s = this.stateStore?.getSettings(this.clientId);
1887
1971
  const settings = {
1972
+ steeringMode: s?.steeringMode ?? "all",
1973
+ followUpMode: s?.followUpMode ?? "all",
1888
1974
  promptMode: s?.promptMode ?? "append",
1889
1975
  customSystemPrompt: s?.customSystemPrompt ?? "",
1890
1976
  disabledSkills: s?.disabledSkills ?? [],
@@ -1923,6 +2009,9 @@ export class UniversalSession {
1923
2009
  skillsCatalogMaxDesc: 250,
1924
2010
  skillsCatalogShowLocation: false,
1925
2011
  skillsCatalogBudget: 20000,
2012
+ chatUploadMaxMb: s?.chatUploadMaxMb ?? 20,
2013
+ workspaceUploadMaxMb: s?.workspaceUploadMaxMb ?? 100,
2014
+ folderUploadMaxMb: s?.folderUploadMaxMb ?? 32,
1926
2015
  visionBridgeEnabled: false,
1927
2016
  visionBridgeModel: null,
1928
2017
  visionBridgePromptMode: "append",
@@ -2122,18 +2211,9 @@ export class UniversalSession {
2122
2211
  this.emitNotice("error", `未找到名为「${name}」的设置预设`, `Settings preset "${name}" not found`);
2123
2212
  return;
2124
2213
  }
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
- });
2214
+ // Missing settings retain their current values; metadata never enters settings.
2215
+ const { settings } = sanitizePresetSettings(found);
2216
+ this.stateStore.saveSettings(this.clientId, settings);
2137
2217
  this.pushSettings();
2138
2218
  this.emitNotice("info", `已应用设置预设「${name}」`, `Settings preset "${name}" applied`);
2139
2219
  }
@@ -2346,6 +2426,13 @@ export class UniversalSession {
2346
2426
  }
2347
2427
  /** 创建并启动一个子代理会话 */
2348
2428
  async spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist = false, title, _thinking, _notifyOnDone) {
2429
+ if (_notifyOnDone === "manual") {
2430
+ throw new Error("notifyOnDone=manual is only supported by the pi engine.");
2431
+ }
2432
+ assertEngineWorkspaceSupported(this.sandboxes, cwd, this.engine);
2433
+ if (this.switchingProject || this.disposed)
2434
+ throw new Error("Workspace is switching");
2435
+ const generation = this.projectGeneration;
2349
2436
  const maxSubagents = Number(process.env.PI_WEB_MAX_SUBAGENTS) || 8;
2350
2437
  const liveCount = this.getLiveSubagentsCount();
2351
2438
  if (liveCount >= maxSubagents) {
@@ -2434,6 +2521,8 @@ export class UniversalSession {
2434
2521
  // 驱动不支持或模型设置失败时平滑降级
2435
2522
  }
2436
2523
  }
2524
+ if (this.disposed || generation !== this.projectGeneration || this.subagentDrivers.get(convId) !== subDriver)
2525
+ return { convId };
2437
2526
  // 异步启动子代理执行流程
2438
2527
  void this.runSubagent(convId, subDriver, effectivePrompt, targetCwd);
2439
2528
  return { convId };
@@ -2443,6 +2532,8 @@ export class UniversalSession {
2443
2532
  const conv = this.conversations.get(convId);
2444
2533
  if (!conv)
2445
2534
  return;
2535
+ const generation = this.projectGeneration;
2536
+ const isCurrent = () => !this.disposed && generation === this.projectGeneration && this.subagentDrivers.get(convId) === subDriver;
2446
2537
  const now = Date.now();
2447
2538
  const assistantMsgId = `a-${now}-${randomUUID().slice(0, 6)}`;
2448
2539
  let thinkingText = "";
@@ -2564,9 +2655,19 @@ export class UniversalSession {
2564
2655
  const sid = await subDriver.createSession();
2565
2656
  conv.driverSessionId = sid;
2566
2657
  }
2567
- await subDriver.sendPrompt(prompt, undefined, sink);
2658
+ if (!isCurrent())
2659
+ return;
2660
+ const guardedSink = new Proxy(sink, {
2661
+ get: (target, key) => (...args) => {
2662
+ if (isCurrent())
2663
+ target[key]?.(...args);
2664
+ },
2665
+ });
2666
+ await subDriver.sendPrompt(prompt, undefined, guardedSink);
2568
2667
  }
2569
2668
  catch (err) {
2669
+ if (!isCurrent())
2670
+ return;
2570
2671
  const msg = err instanceof Error ? err.message : String(err);
2571
2672
  sink.onError(msg);
2572
2673
  }
@@ -2762,6 +2863,8 @@ export class UniversalSession {
2762
2863
  }
2763
2864
  dispose() {
2764
2865
  this.disposed = true;
2866
+ this.finalizeTurn();
2867
+ this.projectGeneration++;
2765
2868
  if (this.snapshotTimer) {
2766
2869
  clearTimeout(this.snapshotTimer);
2767
2870
  this.snapshotTimer = null;