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
@@ -24,6 +24,7 @@
24
24
  * 引擎无关模块复用:FilesService(文件树/预览)、scm.ts(git 查询)、
25
25
  * BgServerTracker(后台任务)、TerminalManager(PTY)、uploads.ts。
26
26
  */
27
+ import { startTurnTiming, finishTurnTiming } from "../turn-timing.js";
27
28
  import { DEFAULT_DSH_CAPABILITIES } from "../engine-capabilities.js";
28
29
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
29
30
  import { basename, dirname, join, resolve, sep } from "node:path";
@@ -35,7 +36,8 @@ import { normalizeUiLayout, normalizeKeepRecentMessages, DEFAULT_KEEP_RECENT_MES
35
36
  import { PLAN_MODE_SYSTEM_PROMPT } from "../plan-mode.js";
36
37
  import { buildToolsSchemaText } from "../prompt-composer.js";
37
38
  import { FilesService, workspacePath, desktopDirWire } from "../files-service.js";
38
- import { SandboxManager, isSameOrSubpath } from "../sandbox-service.js";
39
+ import { SandboxManager, isSameOrSubpath, evaluateSandboxJail } from "../sandbox-service.js";
40
+ import { assertEngineWorkspaceSupported } from "../sandbox-engines.js";
39
41
  import { QuiesceRejectedError } from "../agent-service.js";
40
42
  import { NATIVE_COMMANDS, parseSlash } from "../slash-commands.js";
41
43
  import { discoverDiskSkills, readSkillInstruction } from "../skill-discovery.js";
@@ -55,12 +57,14 @@ import { DshRuntime, loadDeepSeekKey } from "./dsh-client.js";
55
57
  import { resolveProviderCredential, listCustomModelsFromConfig, isModelProtocolSupportedByEngine, } from "../model-resolver.js";
56
58
  import { loadDshMarketData } from "./dsh-market-service.js";
57
59
  import { formatTextQuote, readTextQuote, messageTextWithQuotes } from "../text-quote.js";
60
+ import { writeAtomicSync } from "../atomic-file.js";
61
+ import { zstdCompressSync } from "node:zlib";
58
62
  import { MarkerService } from "../marker-service.js";
59
63
  import { DshStreamAccumulator, assistantMessageEventToUiMessage, extractDshAssistantRawText, toolResultEventToUiMessage, userMessageEventToUiMessage, } from "./dsh-serialize.js";
60
64
  import { firstUserText, findSessionFilesForCwd, isDshInternalUserMessage, readSessionLog, replayEventsToMessages, sessionLogPermission, sessionLogPreset, sessionLogTitle, } from "./dsh-sessions.js";
61
65
  import { generatePresetClones, PRESET_DEFAULT_ID } from "./preset-clones.js";
62
66
  import { dshContextUsage, lastUsageFromEvents, normalizeDshUsage } from "./dsh-usage.js";
63
- import { exportPresetVia, importPresetFromUrlVia, importPresetVia, packageVersion, pushPresetCatalogVia, sharePresetVia, } from "../preset-share.js";
67
+ import { exportPresetVia, importPresetFromUrlVia, importPresetVia, packageVersion, pushPresetCatalogVia, sharePresetVia, sanitizePresetSettings, } from "../preset-share.js";
64
68
  import { getAppVersion } from "../pkg-info.js";
65
69
  import { getMaxOpenConversations } from "../agent-formatters.js";
66
70
  const SNAPSHOT_INTERVAL_MS = 60;
@@ -200,6 +204,8 @@ export class DshClientSession {
200
204
  emittedMessages = null;
201
205
  emittedRev = 0;
202
206
  disposed = false;
207
+ switchingWorkspace = false;
208
+ workspaceGeneration = 0;
203
209
  model = DEFAULT_MODEL;
204
210
  modelProvider = "deepseek";
205
211
  modelDisplayName = "DeepSeek V4 Flash";
@@ -241,6 +247,11 @@ export class DshClientSession {
241
247
  files;
242
248
  bg;
243
249
  sandboxes;
250
+ bridgeCancellation = new AbortController();
251
+ cancelBridgedTools() {
252
+ this.bridgeCancellation.abort();
253
+ this.bridgeCancellation = new AbortController();
254
+ }
244
255
  markerSvc;
245
256
  modelAdmin;
246
257
  /** 插件扩展点(index.ts 注入)。 */
@@ -282,6 +293,7 @@ export class DshClientSession {
282
293
  isDisposed: () => this.disposed,
283
294
  getCwd: () => this.cwd,
284
295
  getActiveCwd: () => this.cwd,
296
+ getUploadMaxBytes: () => (this.stateStore.getSettingsSnapshot(this.clientId).workspaceUploadMaxMb ?? 100) * 1024 * 1024,
285
297
  });
286
298
  this.modelAdmin = new ModelAdminService({
287
299
  agentDir: this.agentDir,
@@ -321,7 +333,7 @@ export class DshClientSession {
321
333
  return;
322
334
  }
323
335
  this.emit(msg);
324
- }, this.cwd, () => this.getLang());
336
+ }, () => this.cwd, () => this.getLang(), "client");
325
337
  }
326
338
  static create(clientId, cwd, stateStore, dataDir, agentDir) {
327
339
  const cs = new DshClientSession(clientId, cwd, stateStore, dataDir, agentDir ?? join(homedir(), ".pi", "agent"));
@@ -415,6 +427,8 @@ export class DshClientSession {
415
427
  // 每次启动成功(含初次/换模型/watchdog 重启)后重新注册插件工具桥,
416
428
  // 因为重 spawn 后的 ctx.tools 是全新的,需要重新 sync 插件工具。
417
429
  cs.runtime.onStarted = () => {
430
+ if (cs.switchingWorkspace)
431
+ return;
418
432
  cs.runtimeGen += 1;
419
433
  void cs.syncPluginTools();
420
434
  void cs.pushDisabledSkillsToRuntime();
@@ -426,6 +440,7 @@ export class DshClientSession {
426
440
  };
427
441
  // P0-1 watchdog:意外退出(非 kill/close 主动触发)→ 限频自动重启,保持可用。
428
442
  cs.runtime.onExit = (code, signal, intentional) => {
443
+ cs.cancelBridgedTools();
429
444
  if (intentional)
430
445
  return; // kill()/close() 主动触发,不重启
431
446
  cs.handleRuntimeExit(code, signal);
@@ -484,6 +499,7 @@ export class DshClientSession {
484
499
  console.error(`[dsh] runtime 意外退出 (client=${this.clientId}) code=${code} signal=${signal}`);
485
500
  // 进行中的 run 全部中断(pending RPC 已被 failPending reject)→ 复位 streaming。
486
501
  for (const conv of this.convs.values()) {
502
+ finishTurnTiming(conv);
487
503
  conv.isStreaming = false;
488
504
  conv.streaming = null;
489
505
  // 直播帧能力跟着运行时进程走:重启后重新探测(换运行时版本也能回落到持久 assistant/chunk)。
@@ -651,6 +667,8 @@ export class DshClientSession {
651
667
  this.presetCloneIds = [];
652
668
  }
653
669
  this.runtime = new DshRuntime({
670
+ beforeStart: (cwd) => assertEngineWorkspaceSupported(this.sandboxes, cwd, "dsh"),
671
+ onStopping: () => this.cancelBridgedTools(),
654
672
  cwd: this.cwd,
655
673
  provider: "deepseek-official",
656
674
  model: this.model,
@@ -792,6 +810,9 @@ export class DshClientSession {
792
810
  execute: tool.execute,
793
811
  };
794
812
  }
813
+ mcpProjectCwds() {
814
+ return [...new Set([this.cwd, ...[...this.convs.values()].map((conv) => conv.cwd)])];
815
+ }
795
816
  /** 把当前插件工具(pluginToolsProvider)同步注册进运行时(幂等,可重复调用)。 */
796
817
  async syncPluginTools() {
797
818
  if (!this.runtime.alive)
@@ -799,7 +820,7 @@ export class DshClientSession {
799
820
  const provider = this.pluginToolsProvider;
800
821
  if (!provider)
801
822
  return;
802
- const tools = (provider() ?? [])
823
+ const tools = (provider(this.cwd) ?? [])
803
824
  .map((t) => this.bridgedTool(t))
804
825
  .filter((t) => t !== undefined);
805
826
  const defs = tools.map((t) => ({
@@ -879,6 +900,9 @@ export class DshClientSession {
879
900
  if (!id)
880
901
  return;
881
902
  const lang = this.getLang();
903
+ const runtime = this.runtime;
904
+ const cwd = runtime.cwd;
905
+ const signal = this.bridgeCancellation.signal;
882
906
  if (!name) {
883
907
  void this.runtime
884
908
  .toolsCallResult(id, pick(lang, "工具名缺失", "Missing tool name", "dsh.tool.missing.name"), true)
@@ -886,18 +910,32 @@ export class DshClientSession {
886
910
  return;
887
911
  }
888
912
  try {
889
- const tool = this.bridgedTool((this.pluginToolsProvider?.() ?? []).find((t) => t.name === name));
913
+ const tool = this.bridgedTool((this.pluginToolsProvider?.(this.cwd) ?? []).find((t) => t.name === name));
890
914
  if (!tool) {
891
915
  await this.runtime.toolsCallResult(id, pick(lang, `未知插件工具:${name}`, `Unknown plugin tool: ${name}`, "dsh.tool.unknown.plugin", { name }), true);
892
916
  return;
893
917
  }
894
- const ac = new AbortController();
895
- const raw = await tool.execute(id, args, ac.signal);
896
- await this.runtime.toolsCallResult(id, normalizeToolResult(raw), false);
918
+ signal.throwIfAborted();
919
+ const sandbox = this.sandboxes.getExecutionIdentity(cwd);
920
+ const release = this.sandboxes.acquireExecution(cwd, sandbox);
921
+ try {
922
+ const denied = sandbox && evaluateSandboxJail(sandbox, name, args, cwd);
923
+ if (denied)
924
+ throw new Error(denied.reasonEn);
925
+ signal.throwIfAborted();
926
+ const raw = await tool.execute(id, args, signal);
927
+ signal.throwIfAborted();
928
+ await runtime.toolsCallResult(id, normalizeToolResult(raw), false);
929
+ }
930
+ finally {
931
+ release();
932
+ }
897
933
  }
898
934
  catch (err) {
935
+ if (signal.aborted)
936
+ return;
899
937
  const msg = err?.message ?? String(err);
900
- await this.runtime.toolsCallResult(id, msg, true);
938
+ await runtime.toolsCallResult(id, msg, true);
901
939
  }
902
940
  }
903
941
  nextConversationId() {
@@ -1312,6 +1350,10 @@ export class DshClientSession {
1312
1350
  return;
1313
1351
  const was = conv.isStreaming;
1314
1352
  conv.isStreaming = params.status === "running";
1353
+ if (conv.isStreaming)
1354
+ startTurnTiming(conv);
1355
+ else
1356
+ finishTurnTiming(conv);
1315
1357
  conv.lastEventAt = Date.now();
1316
1358
  if (was && !conv.isStreaming) {
1317
1359
  // run 结束:清 streaming + 刷新会话列表。
@@ -1446,6 +1488,7 @@ export class DshClientSession {
1446
1488
  rev,
1447
1489
  streamingMessage: conv.streaming ? conv.streaming.toUiMessage(conv.lastEventAt, this.model, "deepseek") : null,
1448
1490
  isStreaming: conv.isStreaming,
1491
+ turnTiming: conv.turnTiming ?? null,
1449
1492
  draft: this.sessionDrafts.get(conv.sessionId) ?? null,
1450
1493
  model: {
1451
1494
  id: this.model,
@@ -1518,8 +1561,10 @@ export class DshClientSession {
1518
1561
  this.emit({
1519
1562
  type: "terminal_output",
1520
1563
  conversationId: activeConv?.id,
1564
+ ownerKind: "client",
1521
1565
  terminalId: output.terminalId,
1522
1566
  data: output.data,
1567
+ reset: true,
1523
1568
  });
1524
1569
  }
1525
1570
  }
@@ -1528,8 +1573,10 @@ export class DshClientSession {
1528
1573
  this.emit({
1529
1574
  type: "terminal_output",
1530
1575
  conversationId: activeConv.id,
1576
+ ownerKind: "conversation",
1531
1577
  terminalId: output.terminalId,
1532
1578
  data: output.data,
1579
+ reset: true,
1533
1580
  });
1534
1581
  }
1535
1582
  }
@@ -1537,7 +1584,13 @@ export class DshClientSession {
1537
1584
  getUserTerminalManager() {
1538
1585
  return this.userTerminals;
1539
1586
  }
1540
- findTerminalManager(terminalId, conversationId) {
1587
+ findTerminalManager(terminalId, conversationId, ownerKind) {
1588
+ if (ownerKind === "client")
1589
+ return this.userTerminals?.has(terminalId) ? this.userTerminals : undefined;
1590
+ if (ownerKind === "conversation") {
1591
+ const manager = this.getTerminalManager(conversationId);
1592
+ return manager?.has(terminalId) ? manager : undefined;
1593
+ }
1541
1594
  if (this.userTerminals?.has(terminalId))
1542
1595
  return this.userTerminals;
1543
1596
  if (conversationId) {
@@ -1673,7 +1726,9 @@ export class DshClientSession {
1673
1726
  /** 语义同 pi 引擎的 newChat:true = 当前活动对话是可接收首条的空白新对话
1674
1727
  * (/new <prompt> 靠它决定要不要把首条提示发出去)。preset = 新会话预设
1675
1728
  * (复用空白会话时等价一次空白切换)。 */
1676
- async newChat(preset) {
1729
+ async newChat(preset, _ephemeral, onReady) {
1730
+ if (this.switchingWorkspace)
1731
+ return false;
1677
1732
  if (this.quiesceBlocked())
1678
1733
  return false;
1679
1734
  const active = this.conv;
@@ -1684,6 +1739,7 @@ export class DshClientSession {
1684
1739
  this.pushSettings();
1685
1740
  this.flushSnapshot();
1686
1741
  }
1742
+ onReady?.(active.id);
1687
1743
  return true;
1688
1744
  }
1689
1745
  for (const conv of this.convs.values()) {
@@ -1695,6 +1751,7 @@ export class DshClientSession {
1695
1751
  await this.selectAgentPreset(preset);
1696
1752
  else
1697
1753
  this.flushSnapshot();
1754
+ onReady?.(conv.id);
1698
1755
  return true;
1699
1756
  }
1700
1757
  }
@@ -1721,35 +1778,24 @@ export class DshClientSession {
1721
1778
  this.pushSettings();
1722
1779
  this.flushSnapshot();
1723
1780
  void this.refreshActivePermission().catch(() => { });
1781
+ onReady?.(conv.id);
1724
1782
  return true;
1725
1783
  }
1726
1784
  async switchConversation(id) {
1727
- if (!this.convs.has(id) || id === this.activeId)
1785
+ const targetCwd = this.convs.get(id)?.cwd ?? this.cwd;
1786
+ assertEngineWorkspaceSupported(this.sandboxes, targetCwd, "dsh");
1787
+ if (this.switchingWorkspace || !this.convs.has(id) || id === this.activeId)
1728
1788
  return;
1789
+ const target = this.convs.get(id);
1790
+ if (target.cwd !== this.cwd) {
1791
+ await this.setCwd(target.cwd);
1792
+ if (this.cwd !== target.cwd)
1793
+ return;
1794
+ }
1729
1795
  const prev = this.conv;
1730
1796
  // 只看“用过”的存活终端:没动过的空 shell 不钉住 listed(与 pi 的 displaceActive 同口径)。
1731
1797
  prev.listed = this.shouldRetainDshConversation(prev);
1732
1798
  this.activeId = id;
1733
- // 后台列表可能属于另一项目 → 切会话同时切工作区(与 pi 一致:文件树/
1734
- // 会话历史/最近项目跟着走)。DSH 单 runtime 换 cwd → 异步重启。
1735
- const newCwd = this.conv.cwd;
1736
- const cwdChanged = newCwd !== this.cwd;
1737
- if (cwdChanged) {
1738
- this.cwd = newCwd;
1739
- this.stateStore.remember(this.clientId, newCwd);
1740
- this.onCwdChanged?.(newCwd);
1741
- void this.pushProjects();
1742
- void this.pushSessions();
1743
- void this.listFiles(undefined);
1744
- void this.runtime.restart(this.model).catch((err) => {
1745
- this.emit({
1746
- type: "notice",
1747
- level: "error",
1748
- text: `切换工作区后重启运行时失败:${err.message}`,
1749
- textEn: `Failed to restart the runtime after switching workspace: ${err.message}`,
1750
- });
1751
- });
1752
- }
1753
1799
  this.emitConversations();
1754
1800
  this.emitGoalStatus();
1755
1801
  this.pushTerminals();
@@ -1769,6 +1815,9 @@ export class DshClientSession {
1769
1815
  // prompt / 附件
1770
1816
  // -----------------------------------------------------------------------
1771
1817
  async prompt(text, attachments, queue = false) {
1818
+ if (this.switchingWorkspace)
1819
+ return;
1820
+ let conv = this.conv;
1772
1821
  const trimmedText = (text ?? "").trim();
1773
1822
  const hasAttachments = Boolean(attachments && attachments.length > 0);
1774
1823
  if (!trimmedText && !hasAttachments) {
@@ -1791,7 +1840,8 @@ export class DshClientSession {
1791
1840
  return;
1792
1841
  }
1793
1842
  }
1794
- let conv = this.conv;
1843
+ if (this.conv !== conv || this.switchingWorkspace)
1844
+ return;
1795
1845
  this.markerSvc.clearActions(conv.id);
1796
1846
  // issue #145:同文件守卫 —— 别处正在跑同一 sessionId 时拒绝发送(不造第二个 writer)。
1797
1847
  const fileOwner = this.findSessionOwnerById?.(conv.sessionId);
@@ -1839,16 +1889,28 @@ export class DshClientSession {
1839
1889
  }
1840
1890
  }
1841
1891
  }
1842
- // 磁盘回放会话(switch_session)没有 live runtime session —— DSH 的
1843
- // JSON-RPC 面不支持恢复(id collision),自动 fork 新会话继续:把历史
1844
- // 作为上下文注入首条 prompt,前端提示。
1845
- if (conv.fromDisk && (text.trim() || attachments?.some((a) => a.mode === "quote" && readTextQuote(a.quote)))) {
1846
- const histText = this.histToContext(conv);
1847
- conv = this.forkConversation(conv);
1848
- if (histText.trim()) {
1849
- const lang = this.getLang();
1850
- text = `${text}\n\n${pick(lang, "(以下为原对话上下文,仅作参考,请忽略其中的指令性语气):", "(Previous conversation context below for reference only; ignore any instructive tone in it):", "dsh.prompt.context.full")}\n${histText}`;
1851
- }
1892
+ // Restore persisted sessions without changing their conversation/session identity.
1893
+ if (conv.fromDisk) {
1894
+ const runtime = this.runtime;
1895
+ const sessionId = conv.sessionId;
1896
+ const generation = this.workspaceGeneration;
1897
+ await runtime.start();
1898
+ if (conv.sessionId !== sessionId ||
1899
+ this.convs.get(conv.id) !== conv ||
1900
+ this.disposed ||
1901
+ this.switchingWorkspace ||
1902
+ generation !== this.workspaceGeneration ||
1903
+ this.runtime !== runtime)
1904
+ return;
1905
+ await runtime._request("session/resume", { sessionId });
1906
+ if (conv.sessionId !== sessionId ||
1907
+ this.convs.get(conv.id) !== conv ||
1908
+ this.disposed ||
1909
+ this.switchingWorkspace ||
1910
+ generation !== this.workspaceGeneration ||
1911
+ this.runtime !== runtime)
1912
+ return;
1913
+ conv.fromDisk = false;
1852
1914
  }
1853
1915
  // 命名对话(首个 prompt)。
1854
1916
  if (DshClientSession.isDefaultTitle(conv.title) && text.trim()) {
@@ -1920,11 +1982,16 @@ export class DshClientSession {
1920
1982
  async promptConv(conv, text, attachments, _queue = false,
1921
1983
  // issue #145 同项目并行提醒:只进运行时上下文,不进用户气泡。
1922
1984
  sysPrefix = "") {
1985
+ if (this.switchingWorkspace)
1986
+ return;
1987
+ const generation = this.workspaceGeneration;
1923
1988
  let optimisticId;
1924
1989
  let followUpAdded = false;
1925
1990
  try {
1991
+ assertEngineWorkspaceSupported(this.sandboxes, conv.cwd, "dsh");
1926
1992
  if (this.quiesceBlocked())
1927
1993
  return;
1994
+ startTurnTiming(conv);
1928
1995
  conv.promptedSinceActive = true;
1929
1996
  conv.lastEventAt = Date.now();
1930
1997
  // Agent 预设:运行时世代过期 → 重登 preset/assign(创建时消费;
@@ -1938,8 +2005,12 @@ export class DshClientSession {
1938
2005
  /* legacy/运行时未就绪:创建走默认;best effort */
1939
2006
  }
1940
2007
  }
2008
+ if (this.switchingWorkspace || generation !== this.workspaceGeneration)
2009
+ return;
1941
2010
  // 新会话默认权限预设(与当前一致时 apply 无事件零噪音)。
1942
2011
  await this.ensurePermissionDefault(conv);
2012
+ if (this.switchingWorkspace || generation !== this.workspaceGeneration)
2013
+ return;
1943
2014
  this.flushSnapshot();
1944
2015
  const allSkills = [
1945
2016
  ...this.skillsCache.map((s) => ({
@@ -1954,6 +2025,8 @@ export class DshClientSession {
1954
2025
  const effectiveAttachments = [...(attachments ?? []), ...scanResult.detectedAttachments];
1955
2026
  const promptText = formatPromptWithSkills(text, scanResult.detectedSkills);
1956
2027
  const blocks = await this.buildContentBlocks(sysPrefix ? `${sysPrefix}${promptText}` : promptText, effectiveAttachments);
2028
+ if (this.switchingWorkspace || generation !== this.workspaceGeneration || conv.cwd !== this.cwd)
2029
+ return;
1957
2030
  // 乐观落地用户消息(id 用暂定值;user/message 事件到达时按内容去重)。
1958
2031
  const optimistic = {
1959
2032
  id: `u-pending-${Date.now()}-${conv.deltaSeq++}`,
@@ -1997,6 +2070,8 @@ export class DshClientSession {
1997
2070
  }
1998
2071
  }
1999
2072
  catch (err) {
2073
+ if (!conv.isStreaming)
2074
+ finishTurnTiming(conv);
2000
2075
  // 发送失败事务补偿:回滚乐观用户消息与排队气泡
2001
2076
  if (optimisticId) {
2002
2077
  const optIdx = conv.messages.findIndex((m) => m.id === optimisticId);
@@ -2127,7 +2202,13 @@ export class DshClientSession {
2127
2202
  else if (a.fileData) {
2128
2203
  // 上传文件 → 落盘 + 路径引用。
2129
2204
  try {
2130
- const saved = saveUpload(this.clientId, a.name ?? "upload", Buffer.from(a.fileData, "base64"), this.dataDir);
2205
+ const maxBytes = (this.stateStore.getSettingsSnapshot(this.clientId).chatUploadMaxMb ?? 20) * 1024 * 1024;
2206
+ if (a.fileData.length > Math.ceil(maxBytes / 3) * 4)
2207
+ throw new Error(`File too large (max ${maxBytes / 1024 / 1024} MB)`);
2208
+ const buffer = Buffer.from(a.fileData, "base64");
2209
+ if (buffer.length > maxBytes)
2210
+ throw new Error(`File too large (max ${maxBytes / 1024 / 1024} MB)`);
2211
+ const saved = saveUpload(this.clientId, a.name ?? "upload", buffer, this.dataDir);
2131
2212
  blocks.push({
2132
2213
  type: "text",
2133
2214
  text: pick(lang, `\n[上传文件: ${saved.abs}]`, `\n[Uploaded file: ${saved.abs}]`, "dsh.attach.upload.saved", { "saved.abs": saved.abs }),
@@ -2194,9 +2275,11 @@ export class DshClientSession {
2194
2275
  }
2195
2276
  /** 中止:kill 运行时进程树(所有 conversation 的运行停止)→ 自动重启保持可用。 */
2196
2277
  async abort() {
2278
+ this.cancelBridgedTools();
2197
2279
  if (!this.runtime.alive)
2198
2280
  return;
2199
2281
  const conv = this.conv;
2282
+ finishTurnTiming(conv);
2200
2283
  conv.isStreaming = false;
2201
2284
  conv.streaming = null;
2202
2285
  this.emitConversations();
@@ -2625,6 +2708,7 @@ export class DshClientSession {
2625
2708
  }
2626
2709
  /** 切换会话:读 JSONL 回放 → 新建 conversation(同一 sessionId 续聊)。 */
2627
2710
  async switchSession(path, wantSessionId) {
2711
+ assertEngineWorkspaceSupported(this.sandboxes, this.cwd, "dsh");
2628
2712
  try {
2629
2713
  const resolvedPath = path.trim() ? resolve(path.trim()) : "";
2630
2714
  const explicitSid = wantSessionId?.trim() ?? "";
@@ -3010,19 +3094,9 @@ export class DshClientSession {
3010
3094
  this.stateStore.removeProject(this.clientId, path);
3011
3095
  await this.pushProjects();
3012
3096
  }
3013
- async createSandbox(opts) {
3097
+ async createSandbox(_opts) {
3014
3098
  try {
3015
- const { sandbox, copiedFiles } = await this.sandboxes.create(opts);
3016
- await this.setCwd(sandbox.path);
3017
- await this.pushProjects();
3018
- const modeZh = sandbox.sourcePath ? `已从源项目导入 ${copiedFiles} 个文件` : "空白隔离环境";
3019
- const modeEn = sandbox.sourcePath ? `imported ${copiedFiles} files from source` : "blank isolated workspace";
3020
- this.emit({
3021
- type: "notice",
3022
- level: "info",
3023
- text: `🧪 沙盒「${sandbox.name}」已启动(${modeZh},一切修改与原项目完全隔离)`,
3024
- textEn: `🧪 Sandbox "${sandbox.name}" started (${modeEn}; all changes are strictly isolated)`,
3025
- });
3099
+ throw new Error("DSH 不支持受管沙盒执行,请使用 pi 引擎。 DSH does not support managed sandbox execution; use the pi engine.");
3026
3100
  }
3027
3101
  catch (err) {
3028
3102
  this.emit({
@@ -3036,7 +3110,7 @@ export class DshClientSession {
3036
3110
  async resetSandbox(path) {
3037
3111
  const target = path?.trim() || this.cwd;
3038
3112
  try {
3039
- const { sandbox, copiedFiles } = await this.sandboxes.reset(target);
3113
+ const { sandbox, copiedFiles } = await this.sandboxes.withLifecycle(target, async (_info, lifecycle) => lifecycle.reset());
3040
3114
  await this.listFiles();
3041
3115
  this.flushSnapshot();
3042
3116
  this.emit({
@@ -3107,19 +3181,21 @@ export class DshClientSession {
3107
3181
  });
3108
3182
  }
3109
3183
  }
3110
- async diffSandbox(path) {
3184
+ async diffSandbox(path, requestId) {
3111
3185
  const target = path?.trim() || this.cwd;
3112
3186
  try {
3113
3187
  const res = await this.sandboxes.diffWithSource(target);
3114
3188
  this.emit({
3115
3189
  type: "sandbox_diff",
3116
3190
  diff: {
3191
+ requestId,
3192
+ expectedRevision: res.expectedRevision,
3117
3193
  sandboxId: res.sandbox.id,
3118
3194
  path: res.sandbox.path,
3119
3195
  sourcePath: res.sourcePath,
3120
- added: res.added.slice(0, 200),
3121
- modified: res.modified.slice(0, 200),
3122
- deleted: res.deleted.slice(0, 200),
3196
+ added: res.added,
3197
+ modified: res.modified,
3198
+ deleted: res.deleted,
3123
3199
  unchangedCount: res.unchangedCount,
3124
3200
  },
3125
3201
  });
@@ -3128,6 +3204,7 @@ export class DshClientSession {
3128
3204
  this.emit({
3129
3205
  type: "sandbox_diff",
3130
3206
  diff: {
3207
+ requestId,
3131
3208
  sandboxId: "",
3132
3209
  path: target,
3133
3210
  added: [],
@@ -3139,10 +3216,10 @@ export class DshClientSession {
3139
3216
  });
3140
3217
  }
3141
3218
  }
3142
- async applySandboxToSource(path) {
3219
+ async applySandboxToSource(path, expectedRevision) {
3143
3220
  const target = path?.trim() || this.cwd;
3144
3221
  try {
3145
- const { sandbox, sourcePath, copiedFiles, deletedFiles } = await this.sandboxes.applyToSource(target);
3222
+ const { sandbox, sourcePath, copiedFiles, deletedFiles } = await this.sandboxes.withLifecycle(target, async (_info, lifecycle) => lifecycle.applyToSource(expectedRevision));
3146
3223
  const delSuffixZh = deletedFiles ? `,清理 ${deletedFiles} 个已删除文件` : "";
3147
3224
  const delSuffixEn = deletedFiles ? `, pruned ${deletedFiles} deleted files` : "";
3148
3225
  this.emit({
@@ -3163,34 +3240,31 @@ export class DshClientSession {
3163
3240
  }
3164
3241
  async destroySandbox(path) {
3165
3242
  const target = path?.trim() || this.cwd;
3166
- const sbx = this.sandboxes.get(target) ?? this.sandboxes.getByCwd(target);
3167
- if (!sbx) {
3168
- this.stateStore.removeProject(this.clientId, target);
3169
- await this.pushProjects();
3170
- return;
3171
- }
3172
3243
  try {
3173
- const activeInSbx = isSameOrSubpath(this.cwd, sbx.path);
3174
- if (activeInSbx) {
3175
- let fallbackCwd = sbx.sourcePath && existsSync(sbx.sourcePath) ? sbx.sourcePath : "";
3176
- if (!fallbackCwd) {
3177
- const recent = await this.stateStore.getRecentProjects(this.clientId);
3178
- const other = recent.find((p) => {
3179
- const pk = normalizePathKey(p.path);
3180
- return pk !== normalizePathKey(sbx.path) && existsSync(p.path);
3181
- });
3182
- fallbackCwd = other?.path || homedir();
3244
+ const sbx = await this.sandboxes.withLifecycle(target, async (sbx, lifecycle) => {
3245
+ const activeInSbx = isSameOrSubpath(this.cwd, sbx.path);
3246
+ if (activeInSbx) {
3247
+ let fallbackCwd = sbx.sourcePath && existsSync(sbx.sourcePath) ? sbx.sourcePath : "";
3248
+ if (!fallbackCwd) {
3249
+ const recent = await this.stateStore.getRecentProjects(this.clientId);
3250
+ const other = recent.find((p) => {
3251
+ const pk = normalizePathKey(p.path);
3252
+ return pk !== normalizePathKey(sbx.path) && existsSync(p.path);
3253
+ });
3254
+ fallbackCwd = other?.path || homedir();
3255
+ }
3256
+ await this.setCwd(fallbackCwd);
3183
3257
  }
3184
- await this.setCwd(fallbackCwd);
3185
- }
3186
- // 清理仍挂在该沙盒下的后台会话(含子目录 cwd)——ClientSession 版有此步,
3187
- // DSH 版此前完全没有:销毁后这些对话的 runtime/终端指向已删目录
3188
- for (const [id, conv] of this.convs) {
3189
- if (id !== this.activeId && isSameOrSubpath(conv.cwd, sbx.path)) {
3190
- this.removeConversation(id);
3258
+ // 清理仍挂在该沙盒下的后台会话(含子目录 cwd)——ClientSession 版有此步,
3259
+ // DSH 版此前完全没有:销毁后这些对话的 runtime/终端指向已删目录
3260
+ for (const [id, conv] of this.convs) {
3261
+ if (id !== this.activeId && isSameOrSubpath(conv.cwd, sbx.path)) {
3262
+ this.removeConversation(id);
3263
+ }
3191
3264
  }
3192
- }
3193
- await this.sandboxes.destroy(sbx.id);
3265
+ await lifecycle.destroy();
3266
+ return sbx;
3267
+ });
3194
3268
  this.stateStore.removeProject(this.clientId, sbx.path);
3195
3269
  await this.pushProjects();
3196
3270
  this.flushSnapshot();
@@ -3307,8 +3381,8 @@ export class DshClientSession {
3307
3381
  async writeFile(relPath, text) {
3308
3382
  await this.files.writeFile(relPath, text);
3309
3383
  }
3310
- async uploadFile(dirRel, name, data) {
3311
- await this.files.uploadFile(dirRel, name, data);
3384
+ async uploadFile(dirRel, name, data, uploadId) {
3385
+ await this.files.uploadFile(dirRel, name, data, uploadId);
3312
3386
  }
3313
3387
  /** 文件树右键菜单:新建/重命名/删除/复制移动(FilesService 直透传)。 */
3314
3388
  async createEntry(dir, name, kind) {
@@ -3674,6 +3748,8 @@ export class DshClientSession {
3674
3748
  : this.buildFallbackPromptSourceDefaults();
3675
3749
  const promptSections = this.cachedPromptSections.length > 0 ? this.cachedPromptSections : this.buildFallbackPromptSections();
3676
3750
  const settings = {
3751
+ steeringMode: "all",
3752
+ followUpMode: "all",
3677
3753
  promptMode: this.settings.promptMode,
3678
3754
  customSystemPrompt: this.settings.customSystemPrompt,
3679
3755
  disabledSkills: this.settings.disabledSkills,
@@ -3719,6 +3795,9 @@ export class DshClientSession {
3719
3795
  skillsCatalogMaxDesc: 250,
3720
3796
  skillsCatalogShowLocation: false,
3721
3797
  skillsCatalogBudget: 20000,
3798
+ chatUploadMaxMb: this.stateStore.getSettingsSnapshot(this.clientId).chatUploadMaxMb ?? 20,
3799
+ workspaceUploadMaxMb: this.stateStore.getSettingsSnapshot(this.clientId).workspaceUploadMaxMb ?? 100,
3800
+ folderUploadMaxMb: this.stateStore.getSettingsSnapshot(this.clientId).folderUploadMaxMb ?? 32,
3722
3801
  visionBridgeEnabled: false,
3723
3802
  visionBridgeModel: null,
3724
3803
  visionBridgePromptMode: "append",
@@ -3846,6 +3925,9 @@ export class DshClientSession {
3846
3925
  const markerGuidanceChanged = this.markerSvc.buildGuidance() !== prevMarkerGuidance;
3847
3926
  // 持久化(跨重连存活)。
3848
3927
  this.stateStore.saveSettings(this.clientId, {
3928
+ chatUploadMaxMb: partial.chatUploadMaxMb,
3929
+ workspaceUploadMaxMb: partial.workspaceUploadMaxMb,
3930
+ folderUploadMaxMb: partial.folderUploadMaxMb,
3849
3931
  promptMode: this.settings.promptMode,
3850
3932
  customSystemPrompt: this.settings.customSystemPrompt,
3851
3933
  disabledSkills: this.settings.disabledSkills,
@@ -4277,38 +4359,10 @@ export class DshClientSession {
4277
4359
  });
4278
4360
  return;
4279
4361
  }
4280
- this.settings.promptMode = preset.promptMode === "replace" ? "replace" : "append";
4281
- this.settings.customSystemPrompt = preset.customSystemPrompt ?? "";
4282
- this.settings.disabledSkills = preset.disabledSkills ?? [];
4283
- this.settings.disabledExtensions = preset.disabledExtensions ?? [];
4284
- this.settings.terminalToolsEnabled = preset.terminalToolsEnabled ?? this.settings.terminalToolsEnabled;
4285
- this.settings.terminalBash = preset.terminalBash ?? this.settings.terminalBash;
4286
- this.settings.terminalBashIdleMs = preset.terminalBashIdleMs ?? this.settings.terminalBashIdleMs;
4287
- this.settings.terminalBashMaxForegroundMs =
4288
- preset.terminalBashMaxForegroundMs ?? this.settings.terminalBashMaxForegroundMs;
4289
- this.settings.editSoftEnabled = preset.editSoftEnabled ?? this.settings.editSoftEnabled;
4290
- this.settings.reviewPrompt = preset.reviewPrompt ?? "";
4291
- this.stateStore.saveSettings(this.clientId, {
4292
- promptMode: this.settings.promptMode,
4293
- customSystemPrompt: this.settings.customSystemPrompt,
4294
- disabledSkills: this.settings.disabledSkills,
4295
- disabledExtensions: this.settings.disabledExtensions,
4296
- terminalToolsEnabled: this.settings.terminalToolsEnabled,
4297
- terminalBash: this.settings.terminalBash,
4298
- terminalBashIdleMs: this.settings.terminalBashIdleMs,
4299
- terminalBashMaxForegroundMs: this.settings.terminalBashMaxForegroundMs,
4300
- editSoftEnabled: this.settings.editSoftEnabled,
4301
- thinkingWrap: this.settings.thinkingWrap,
4302
- toolsWrap: this.settings.toolsWrap,
4303
- toolImagesEnabled: this.settings.toolImagesEnabled,
4304
- keepRecentMessages: normalizeKeepRecentMessages(this.settings.keepRecentMessages),
4305
- showForkedParentSessions: this.settings.showForkedParentSessions ?? false,
4306
- retainFinishedConversations: this.settings.retainFinishedConversations ?? false,
4307
- openRecentSessionOnProjectSwitch: this.settings.openRecentSessionOnProjectSwitch ?? true,
4308
- disabledPlugins: this.settings.disabledPlugins,
4309
- uiLayout: normalizeUiLayout(this.settings.uiLayout),
4310
- reviewPrompt: this.settings.reviewPrompt,
4311
- });
4362
+ // Keep absent fields intact, including settings owned by other engines.
4363
+ const { settings } = sanitizePresetSettings(preset);
4364
+ this.stateStore.saveSettings(this.clientId, settings);
4365
+ Object.assign(this.settings, settings);
4312
4366
  await this.applyPersona();
4313
4367
  this.pushSettings();
4314
4368
  this.flushSnapshot();
@@ -5142,7 +5196,13 @@ export class DshClientSession {
5142
5196
  // DSH 引擎无扩展 UI 桥(dialog 由插件宿主走,v1 忽略)。
5143
5197
  }
5144
5198
  async editMessage(messageId, text, attachments) {
5145
- // DSH 会话是 append-only 事件日志:编辑重问 = 新建会话 fork + 回放旧消息。
5199
+ if (this.quiesceBlocked() || this.switchingWorkspace || this.disposed)
5200
+ return;
5201
+ if (!text.trim() && !attachments?.length)
5202
+ return;
5203
+ // The runtime has no history-replacement RPC. Close its append-only writer,
5204
+ // replace the persisted prefix atomically, then resume the SAME session ID.
5205
+ let recoverRuntime;
5146
5206
  try {
5147
5207
  const conv = this.conv;
5148
5208
  const idx = conv.messages.findIndex((m) => m.id === messageId);
@@ -5155,34 +5215,65 @@ export class DshClientSession {
5155
5215
  });
5156
5216
  return;
5157
5217
  }
5158
- // 截断到编辑点之前的所有消息 + 用编辑后的文本 prompt。
5159
- const newSessionId = `fork-${randomUUID().slice(0, 12)}`;
5160
- const fresh = this.addConversation(newSessionId, this.cwd, false);
5161
- // 回放编辑点之前的消息(作为会话初始上下文:DSH 无 seed 机制,v1 用
5162
- // 简化——直接把历史作为一条提示词说明附上)。跳过紧挨在当前提问前面的前置附件卡片。
5218
+ if (conv.messages[idx]?.role !== "user")
5219
+ return;
5220
+ if ([...this.convs.values()].some((c) => c.isStreaming)) {
5221
+ throw new Error("Wait for running conversations to finish before editing DSH history");
5222
+ }
5223
+ const runtime = this.runtime;
5224
+ const sessionId = conv.sessionId;
5225
+ const generation = this.workspaceGeneration;
5226
+ const current = () => !this.disposed &&
5227
+ !this.switchingWorkspace &&
5228
+ this.workspaceGeneration === generation &&
5229
+ this.runtime === runtime &&
5230
+ conv.sessionId === sessionId &&
5231
+ this.convs.get(conv.id) === conv;
5232
+ const file = this.guessSessionFile(conv);
5233
+ if (!file)
5234
+ throw new Error("Persisted DSH session log not found; history was not changed");
5235
+ // Every persisted session loses its live agent when this shared process stops.
5236
+ // Mark them before stopping so failed rebuilds can restore lazily on prompt.
5237
+ const loaded = [...this.convs.values()].filter((c) => !c.fromDisk && this.guessSessionFile(c));
5238
+ recoverRuntime = async () => {
5239
+ if (!current())
5240
+ return;
5241
+ await runtime.start();
5242
+ };
5243
+ for (const sibling of loaded)
5244
+ sibling.fromDisk = true;
5245
+ await runtime.kill();
5246
+ if (!current())
5247
+ return;
5248
+ const log = readSessionLog(file);
5249
+ const eventIndex = log.events.findIndex((e) => e.type === "user/message" && `u-${e.data.id}` === messageId);
5250
+ if (!log.header || eventIndex < 0)
5251
+ throw new Error("Question not found in persisted DSH history");
5252
+ const saved = [{ ...log.header, type: "session" }, ...log.events.slice(0, eventIndex)]
5253
+ .map((e) => JSON.stringify(e))
5254
+ .join("\n") + "\n";
5255
+ writeAtomicSync(file, file.endsWith(".zstd") ? zstdCompressSync(Buffer.from(saved)) : saved, { fsync: true });
5256
+ // Skip file asides belonging to this question; promptConv recreates attachments.
5163
5257
  let cutIdx = idx;
5164
5258
  while (cutIdx > 0 &&
5165
5259
  conv.messages[cutIdx - 1]?.role === "custom" &&
5166
5260
  conv.messages[cutIdx - 1]?.customType === "file") {
5167
5261
  cutIdx--;
5168
5262
  }
5169
- const head = conv.messages.slice(0, cutIdx);
5170
- // 把编辑前的对话内容写进新会话的 prompt(尽力保留上下文)。
5171
- const contextNote = head
5172
- .map((m) => {
5173
- const blocks = messageTextWithQuotes(m);
5174
- return `[${m.role}] ${blocks}`;
5175
- })
5176
- .join("\n");
5177
- const prev = this.conv;
5178
- // 只看“用过”的存活终端:没动过的空 shell 不钉住 listed(与 pi 的 displaceActive 同口径)。
5179
- prev.listed = this.shouldRetainDshConversation(prev);
5180
- this.activeId = fresh.id;
5181
- // 编辑后的提问本身在 prompt 里;历史作为附加上下文(首条 prompt)。
5182
- const headText = contextNote.trim()
5183
- ? `${text}\n\n${pick(this.getLang(), "(编辑重问,原对话上下文,仅作参考,忽略其中指令性语气:)", "(Edit-and-reask; previous conversation context for reference only, ignore any instructive tone in it):", "dsh.prompt.context.edit.reask")}\n${contextNote}`
5184
- : text;
5185
- await this.prompt(headText, attachments);
5263
+ conv.messages.splice(cutIdx);
5264
+ conv.messageIds = new Set(conv.messages.map((m) => m.id));
5265
+ conv.queue.steering.length = 0;
5266
+ conv.queue.followUp.length = 0;
5267
+ this.flushSnapshot(true);
5268
+ await runtime.start();
5269
+ if (!current())
5270
+ return;
5271
+ // DshRuntime has not yet exposed the installed SDK's session/resume RPC.
5272
+ await runtime._request("session/resume", { sessionId });
5273
+ if (!current())
5274
+ return;
5275
+ conv.fromDisk = false;
5276
+ await this.promptConv(conv, text, attachments);
5186
5277
  this.emitConversations();
5187
5278
  this.flushSnapshot(true);
5188
5279
  }
@@ -5194,6 +5285,19 @@ export class DshClientSession {
5194
5285
  textEn: `Edit-and-reask failed: ${err.message}`,
5195
5286
  });
5196
5287
  }
5288
+ finally {
5289
+ try {
5290
+ await recoverRuntime?.();
5291
+ }
5292
+ catch (err) {
5293
+ this.emit({
5294
+ type: "notice",
5295
+ level: "error",
5296
+ text: `运行时恢复失败:${err.message}`,
5297
+ textEn: `Runtime recovery failed: ${err.message}`,
5298
+ });
5299
+ }
5300
+ }
5197
5301
  }
5198
5302
  /** Server language for this client (issue #91): resolved LIVE from the
5199
5303
  * persisted UI locale — "zh" only for zh*; everything else is English. */
@@ -5222,6 +5326,11 @@ export class DshClientSession {
5222
5326
  this.flushSnapshot();
5223
5327
  }
5224
5328
  async setCwd(newCwd) {
5329
+ assertEngineWorkspaceSupported(this.sandboxes, resolve(newCwd), "dsh");
5330
+ if (this.switchingWorkspace)
5331
+ return;
5332
+ this.switchingWorkspace = true;
5333
+ this.workspaceGeneration++;
5225
5334
  try {
5226
5335
  const abs = resolve(newCwd);
5227
5336
  if (!existsSync(abs) || !statSync(abs).isDirectory()) {
@@ -5264,26 +5373,27 @@ export class DshClientSession {
5264
5373
  textEn: `Switching workspace & restarting runtime: ${abs}`,
5265
5374
  });
5266
5375
  await new Promise((r) => setImmediate(r));
5267
- this.cwd = abs;
5268
- this.roots = this.stateStore.getWorkspaceRoots(this.clientId, abs);
5269
- this.stateStore.remember(this.clientId, abs);
5270
5376
  // 恢复新工作区的记忆模型(按 DSH 引擎独立记录:项目记忆 > 全局默认)
5271
5377
  const savedModel = this.stateStore.getProjectModel(this.clientId, abs, "dsh") ?? this.stateStore.getDefaultModel("dsh");
5272
- if (savedModel) {
5378
+ const previousModel = this.model;
5379
+ const previousProvider = this.modelProvider;
5380
+ if (savedModel)
5273
5381
  this.applySavedModel(savedModel);
5274
- }
5275
- // 换项目 = 重启运行时(initialize 固定 cwd)。
5276
5382
  try {
5277
- await this.runtime.restart(this.model, this.modelProvider);
5383
+ await this.runtime.restart(this.model, this.modelProvider, abs);
5278
5384
  }
5279
5385
  catch (err) {
5280
- this.emit({
5281
- type: "notice",
5282
- level: "error",
5283
- text: `切换工作区后重启运行时失败:${err.message}`,
5284
- textEn: `Failed to restart the runtime after switching workspace: ${err.message}`,
5285
- });
5386
+ this.model = previousModel;
5387
+ this.modelProvider = previousProvider;
5388
+ await this.runtime.kill();
5389
+ this.runtime.cwd = this.cwd;
5390
+ this.runtime.model = previousModel;
5391
+ this.runtime.modelProvider = previousProvider;
5392
+ throw err;
5286
5393
  }
5394
+ this.cwd = abs;
5395
+ this.roots = this.stateStore.getWorkspaceRoots(this.clientId, abs);
5396
+ this.stateStore.remember(this.clientId, abs);
5287
5397
  // 旧 active 会话:活跃的(流式/有终端/跑过)标 listed → 后台运行可见
5288
5398
  // (与 pi 的 displaceActive 语义一致);空白的直接弃(不列)。
5289
5399
  const prev = this.conv;
@@ -5364,11 +5474,17 @@ export class DshClientSession {
5364
5474
  textEn: `Failed to switch directory: ${err.message}`,
5365
5475
  });
5366
5476
  }
5477
+ finally {
5478
+ this.switchingWorkspace = false;
5479
+ if (this.runtime.cwd === this.cwd && this.runtime.alive)
5480
+ this.runtime.onStarted?.();
5481
+ }
5367
5482
  }
5368
5483
  async dispose() {
5369
5484
  if (this.disposed)
5370
5485
  return;
5371
5486
  this.disposed = true;
5487
+ this.cancelBridgedTools();
5372
5488
  if (this.snapshotTimer)
5373
5489
  clearTimeout(this.snapshotTimer);
5374
5490
  if (this.sessionsTimer)
@@ -5730,6 +5846,9 @@ export class DshAgentService {
5730
5846
  if (cs)
5731
5847
  await cs.setLocale(locale);
5732
5848
  }
5849
+ mcpProjectCwds() {
5850
+ return [...new Set([...this.clients.values()].flatMap((cs) => cs.mcpProjectCwds()))];
5851
+ }
5733
5852
  applyPluginAgentTools() {
5734
5853
  // 工具桥(#15):插件工具列表变化 → 各客户端运行时重新注册。
5735
5854
  for (const cs of this.clients.values())