pi-web-ui 0.103.3 → 0.104.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/dist/server/agent-formatters.js +9 -1
  3. package/dist/server/agent-service-daemon.js +4 -3
  4. package/dist/server/agent-service.js +586 -44
  5. package/dist/server/compaction-markers.js +111 -3
  6. package/dist/server/delegate-mode.js +2 -0
  7. package/dist/server/dispatch-domain-handlers.js +25 -0
  8. package/dist/server/dsh/dsh-agent-service.js +265 -11
  9. package/dist/server/goal-review-gate.js +2 -0
  10. package/dist/server/index.js +1 -0
  11. package/dist/server/market-service.js +36 -9
  12. package/dist/server/mcp-agent-tool.js +164 -0
  13. package/dist/server/mcp-manager.js +182 -0
  14. package/dist/server/net-guard.js +277 -0
  15. package/dist/server/plan-mode.js +3 -0
  16. package/dist/server/plugin-api-catalog.js +24 -0
  17. package/dist/server/plugins.js +113 -0
  18. package/dist/server/preset-share.js +90 -42
  19. package/dist/server/remote-ssh-service.js +90 -25
  20. package/dist/server/sandbox-service.js +705 -0
  21. package/dist/server/sandbox-tool.js +365 -0
  22. package/dist/server/session-branch.js +32 -11
  23. package/dist/server/session-parser.js +48 -21
  24. package/dist/server/terminals.js +210 -10
  25. package/dist/server/tool-manager.js +24 -0
  26. package/dist/server/webui-context.js +6 -0
  27. package/dist/server/workspace-snapshot.js +51 -13
  28. package/package.json +1 -1
  29. package/plugin-sdk/index.d.ts +39 -0
  30. package/plugin-sdk/index.mjs +14 -0
  31. package/plugins/catalog.json +101 -2
  32. package/themes/zhujian-dark.css +711 -0
  33. package/themes/zhujian.css +760 -0
  34. package/web/dist/assets/{TerminalPanel-CAqMqC49.js → TerminalPanel-CpfPFx32.js} +1 -1
  35. package/web/dist/assets/index-D85H75iu.js +680 -0
  36. package/web/dist/assets/index-RqIdFOsh.css +1 -0
  37. package/web/dist/index.html +2 -2
  38. package/web/dist/sw.js +1 -1
  39. package/web/dist/assets/index-CYQdZEbx.css +0 -1
  40. package/web/dist/assets/index-Dt7CQ_Z6.js +0 -680
@@ -52,6 +52,7 @@ import { pick, resolveServerLang } from "./i18n.js";
52
52
  import { SubagentTemplatesStore, pickTemplatePrompt } from "./subagent-templates.js";
53
53
  import { ApprovalRulesStore, extractTargetPath } from "./approval-rules.js";
54
54
  import { ComposerDraftsStore } from "./composer-drafts.js";
55
+ import { SandboxManager, evaluateSandboxJail, isSameOrSubpath, withSandboxJailGate } from "./sandbox-service.js";
55
56
  import { readPermissionFromSession } from "./permission-preset.js";
56
57
  import { createWorkspaceSnapshot, restoreWorkspaceSnapshot, findMatchingWorkspaceSnapshot, } from "./workspace-snapshot.js";
57
58
  import { createScheduleToolHost, createConversationReadHost, createClaimToolHost, createCompactContextHost, createSkillToolHost, } from "./tool-host-factories.js";
@@ -103,13 +104,15 @@ import { getCompactedMessages } from "./compacted-history.js";
103
104
  import { makeScheduleTool } from "./schedule-agent-tool.js";
104
105
  import { makePatchTool } from "./patch-tool.js";
105
106
  import { makeLspTool } from "./lsp-tool.js";
107
+ import { makeMcpManageTool } from "./mcp-agent-tool.js";
108
+ import { makeSandboxTool } from "./sandbox-tool.js";
106
109
  import { sameSessionFile } from "./scheduler-tasks.js";
107
110
  import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
108
111
  import { formatQuotedPrompt, readTextQuote } from "./text-quote.js";
109
112
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
110
113
  import { generateScmCommitMessage } from "./scm-commitmsg.js";
111
114
  import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, estimatePromptTokens, renderPromptTemplate, resolveSectionTexts, splitExtensionWrap, } from "./prompt-composer.js";
112
- import { listAllMcpServers, saveMcpServer as saveMcpServerFile, deleteMcpServer as deleteMcpServerFile, toggleMcpServer as toggleMcpServerFile, } from "./mcp-manager.js";
115
+ import { listAllMcpServers, checkMcpServer, installMcpServer, saveMcpServer as saveMcpServerFile, deleteMcpServer as deleteMcpServerFile, toggleMcpServer as toggleMcpServerFile, } from "./mcp-manager.js";
113
116
  import { fetchRemoteMcpMarket, fetchRemoteSkillMarket, fetchRemoteSkillContent } from "./market-service.js";
114
117
  import { launchOrigin, toServiceInfo } from "./launch-origin.js";
115
118
  import { findEntryByUiId, serializeMessage, serializeStreamingMessage, stripTransientRetryErrors, } from "./serialize.js";
@@ -204,7 +207,7 @@ import { makeMarkersListTool } from "./markers-list-tool.js";
204
207
  import { makeAskUserQuestionTool, shouldPopQuestion } from "./ask-user-question-tool.js";
205
208
  import { normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, } from "./browser-page-tool.js";
206
209
  export { makeAskUserQuestionTool, shouldPopQuestion, normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, };
207
- import { RUN_TASK_CAP, RUN_ARGS_CAP, RUN_RESULT_CAP, MAX_OPEN_CONVERSATIONS, getMaxSubagents, SUBAGENT_PROMPT_SNAPSHOT_CAP, DEFAULT_CONV_TITLE, truncRun, previewToolResult, atomicWriteFileSync, conversationTitle, pluginToolToDefinition, contentFingerprint, extractPartialText, extractAssistantTextFromContent, firstSentence, modelKeyOf, contextWindowOf, } from "./agent-formatters.js";
210
+ import { RUN_TASK_CAP, RUN_ARGS_CAP, RUN_RESULT_CAP, getMaxOpenConversations, getMaxSubagents, SUBAGENT_PROMPT_SNAPSHOT_CAP, DEFAULT_CONV_TITLE, truncRun, previewToolResult, atomicWriteFileSync, conversationTitle, pluginToolToDefinition, contentFingerprint, extractPartialText, extractAssistantTextFromContent, firstSentence, modelKeyOf, contextWindowOf, } from "./agent-formatters.js";
208
211
  export { workspacePath };
209
212
  import { MAX_TRANSCRIPT_SCAN_BYTES, MAX_SEARCH_TEXT_CHARS, sessionMatchesMetadata, messageSearchText, collectSessionAnchors, piSessionsRoot, isInsideSessionsDir, readCwdFromSessionHeader, } from "./session-search.js";
210
213
  export { piSessionsRoot, isInsideSessionsDir };
@@ -440,8 +443,9 @@ export class ClientSession {
440
443
  const baseCwdForLimit = parentId ? (this.convs.get(parentId)?.cwd ?? this.cwd) : this.cwd;
441
444
  const resolvedCwdForLimit = cwd ? resolve(baseCwdForLimit, cwd) : baseCwdForLimit;
442
445
  const openInProject = [...this.convs.values()].filter((c) => c.cwd === resolvedCwdForLimit && !c.isSubagent && !c.isEphemeral).length;
443
- if (openInProject >= MAX_OPEN_CONVERSATIONS) {
444
- throw new Error(pick(this.getLang(), `目标项目运行的普通对话已达上限(${MAX_OPEN_CONVERSATIONS} 个),无法创建持久化对话。请先关闭不需要的对话,或以轻量子代理(persist=false)方式运行`, `The project already has max open regular conversations (${MAX_OPEN_CONVERSATIONS}). Please close some or run as a lightweight subagent (persist=false)`, "agent.conv.limit.reached", { limit: MAX_OPEN_CONVERSATIONS }));
446
+ const maxOpenConversations = getMaxOpenConversations();
447
+ if (openInProject >= maxOpenConversations) {
448
+ throw new Error(pick(this.getLang(), `目标项目运行的普通对话已达上限(${maxOpenConversations} 个),无法创建持久化对话。请先关闭不需要的对话,或以轻量子代理(persist=false)方式运行`, `The project already has max open regular conversations (${maxOpenConversations}). Please close some or run as a lightweight subagent (persist=false)`, "agent.conv.limit.reached", { limit: maxOpenConversations }));
445
449
  }
446
450
  }
447
451
  else {
@@ -1522,6 +1526,8 @@ export class ClientSession {
1522
1526
  approvalRules;
1523
1527
  /** 未发送输入框草稿(全局共享,<dataDir>/composer-drafts.json,按 sessionId 键入,见 server/composer-drafts.ts)。 */
1524
1528
  drafts;
1529
+ /** 隔离沙盒项目管理器(全局共享,<dataDir>/sandboxes/registry.json)。 */
1530
+ sandboxes;
1525
1531
  /** 内置标记服务(todo/notify/svc/rename 等,可全局/分组开关)。 */
1526
1532
  markerSvc;
1527
1533
  // -----------------------------------------------------------------------
@@ -1562,6 +1568,7 @@ export class ClientSession {
1562
1568
  this.subagentTemplates = new SubagentTemplatesStore(join(stateStore.dataDir, "subagent-templates.json"));
1563
1569
  this.approvalRules = new ApprovalRulesStore(join(stateStore.dataDir, "approval-rules.json"));
1564
1570
  this.drafts = new ComposerDraftsStore(join(stateStore.dataDir, "composer-drafts.json"));
1571
+ this.sandboxes = new SandboxManager(stateStore.dataDir);
1565
1572
  this.planManager = new PlanManager(join(stateStore.dataDir, "plans.json"));
1566
1573
  this.markerSvc = new MarkerService({
1567
1574
  clientId,
@@ -1895,8 +1902,9 @@ export class ClientSession {
1895
1902
  }
1896
1903
  // 恢复本项目其他已被钉住的会话(重启后常驻运行列表,issue #433)
1897
1904
  const pinnedPaths = cs.stateStore?.getPinnedSessions(cwd) ?? [];
1905
+ const maxOpenConversations = getMaxOpenConversations();
1898
1906
  for (const p of pinnedPaths) {
1899
- if (cs.convs.size >= MAX_OPEN_CONVERSATIONS)
1907
+ if (cs.convs.size >= maxOpenConversations)
1900
1908
  break;
1901
1909
  const normP = normalizePathKey(p);
1902
1910
  const alreadyOpen = [...cs.convs.values()].some((c) => c.session.sessionFile && normalizePathKey(c.session.sessionFile) === normP);
@@ -2004,6 +2012,13 @@ export class ClientSession {
2004
2012
  if (this.delegateModeOf(ownerId) && !this.planModeOf(ownerId)) {
2005
2013
  out.push(DELEGATION_SYSTEM_PROMPT);
2006
2014
  }
2015
+ const activeSandbox = this.sandboxes.getByCwd(effectiveCwd);
2016
+ if (activeSandbox) {
2017
+ out.push(`[Sandbox Isolation Mode] You are operating inside an isolated sandbox workspace "${activeSandbox.name}" at "${activeSandbox.path}".` +
2018
+ (activeSandbox.sourcePath
2019
+ ? ` This sandbox is an isolated copy of "${activeSandbox.sourcePath}". NEVER read from or modify "${activeSandbox.sourcePath}" directly; make all changes exclusively within the current sandbox directory "${activeSandbox.path}".`
2020
+ : ` Keep all file writes, edits, and command side effects strictly inside "${activeSandbox.path}".`));
2021
+ }
2007
2022
  const realCwd = restoreWorkspaceUriFromSessionDir(effectiveCwd);
2008
2023
  if (isRemoteWorkspaceUri(realCwd)) {
2009
2024
  // 远程 SSH 工作区:明确告知 AI 当前处于远程主机以及所有工具已透明桥接至远端,
@@ -2175,7 +2190,9 @@ export class ClientSession {
2175
2190
  // 避免 SDK findInitialModel 在无 model 时回退到内置硬编码默认(如 deepseek-v4-pro):
2176
2191
  let sessionModel = initialModel;
2177
2192
  if (!sessionModel) {
2178
- const isBlank = sessionManager.buildSessionContext().messages.length === 0;
2193
+ const isBlank = typeof sessionManager.getEntries === "function"
2194
+ ? !sessionManager.getEntries().some((e) => e.type === "message")
2195
+ : sessionManager.buildSessionContext().messages.length === 0;
2179
2196
  if (isBlank) {
2180
2197
  const savedModelId = this.stateStore.getProjectModel(this.clientId, effectiveCwd) ?? this.stateStore.getDefaultModel();
2181
2198
  if (savedModelId) {
@@ -2240,6 +2257,13 @@ export class ClientSession {
2240
2257
  "workspace-write-never", () => this.getLang()),
2241
2258
  ...makePersistentTerminalTools(terminals, effectiveCwd, () => this.getLang(), {
2242
2259
  checkSafety: (cmd) => {
2260
+ // 沙盒硬围栏:禁止引用源项目路径或跳出沙盒根。
2261
+ const activeSbx = this.sandboxes.getByCwd(effectiveCwd);
2262
+ if (activeSbx) {
2263
+ const sbxDenied = evaluateSandboxJail(activeSbx, "bash", { command: cmd }, effectiveCwd);
2264
+ if (sbxDenied)
2265
+ return { blocked: true, reason: sbxDenied.reason };
2266
+ }
2243
2267
  // 计划模式:终端只放行只读命令(常驻终端也走这条,与 bash 覆盖同口径)。
2244
2268
  if (this.planModeOf(ownerId)) {
2245
2269
  const denied = planModeDenial("bash", { command: cmd });
@@ -2273,9 +2297,9 @@ export class ClientSession {
2273
2297
  // tool-overrides.ts);它们改在会话建好后由 installToolOverrides 注入。
2274
2298
  // 不覆盖内置 edit 的独立宽松编辑工具(缩进不敏感匹配;开关看设置;带权限沙箱拦截与人机协同)。
2275
2299
  // 目标审查闸门包在最外层:审查回合的理由最贴合此刻(跟模型说「这是审查回合」)。
2276
- withGoalReviewGate(withDelegationGate(withPlanModeGate(wrapEditSoftToolWithPermission(makeEditSoftTool(effectiveCwd, () => this.getLang()), effectiveCwd, () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
2300
+ withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(wrapEditSoftToolWithPermission(makeEditSoftTool(effectiveCwd, () => this.getLang()), effectiveCwd, () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
2277
2301
  this.settingsSvc.current.defaultPermissionPreset ??
2278
- "workspace-write-never", () => this.roots, () => this.getLang(), (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category), () => ownerId, () => this.approvalRules.list()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()),
2302
+ "workspace-write-never", () => this.roots, () => this.getLang(), (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category), () => ownerId, () => this.approvalRules.list()), () => this.sandboxes.getByCwd(effectiveCwd), () => effectiveCwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()),
2279
2303
  // 插件注册的 AI 工具(创建时刻的实时快照,已按 disabledPluginTools 过滤;
2280
2304
  // 后续注册经 refreshPluginTools 动态补入已有会话)。
2281
2305
  // 子代理模板带非空扩展白名单时不注入:插件/MCP 工具没有 SDK extensionKey
@@ -2373,11 +2397,26 @@ export class ClientSession {
2373
2397
  makePatchTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }),
2374
2398
  // 原生语言服务器工具(lsp,定义跳转/引用/悬停/诊断)。
2375
2399
  makeLspTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }),
2400
+ // MCP 服务器检测与安装管理工具(mcp_manage:list/check/install/remove/reload)。
2401
+ makeMcpManageTool(this.mcpManageToolHost(effectiveCwd), () => this.getLang()),
2402
+ // 隔离沙盒项目管理工具(sandbox:list/create/diff/reset/persist/promote/apply_to_source/destroy)。
2403
+ makeSandboxTool({
2404
+ sandboxes: this.sandboxes,
2405
+ getCwd: () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? effectiveCwd,
2406
+ setCwd: (newCwd) => this.setCwd(newCwd),
2407
+ onSandboxesChanged: async () => {
2408
+ this.invalidateProjectsCache();
2409
+ await this.pushProjects();
2410
+ this.flushSnapshot();
2411
+ },
2412
+ askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category),
2413
+ getConversationId: () => ownerId,
2414
+ }, () => this.getLang()),
2376
2415
  ].map((t) =>
2377
2416
  // 目标审查闸门在最外层(理由最贴合此刻);插件工具也在这个数组里,
2378
2417
  // 创建时注册的同样被闸门覆盖(后续动态补入的走 syncPluginTools,与
2379
2418
  // 计划/审查者闸门同口径不在覆盖面,见 goal-review-gate.ts 头注)。
2380
- withGoalReviewGate(withDelegationGate(withPlanModeGate(t, () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang())),
2419
+ withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(t, () => this.sandboxes.getByCwd(effectiveCwd), () => effectiveCwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang())),
2381
2420
  });
2382
2421
  // 桥接工具归属锚点:SDK 会话对象在本 runtime 生命周期内稳定,过户只搬对话
2383
2422
  // 不改它(见 ClientSession.findConversationHome)。
@@ -3973,6 +4012,7 @@ export class ClientSession {
3973
4012
  // 必须**恒存在**(不能只在 true 时展开):转正后它由 true→false,而增量快照是
3974
4013
  // `{...ui, ...d.state}` 浅合并,缺字段会把 true 残留下来。
3975
4014
  isEphemeral: !!this.conv?.isEphemeral,
4015
+ sandbox: this.sandboxes?.getByCwd(this.cwd) ?? null,
3976
4016
  rev,
3977
4017
  streamingMessage,
3978
4018
  isStreaming: this.session.isStreaming,
@@ -5932,6 +5972,80 @@ export class ClientSession {
5932
5972
  projectConfigPath: data.projectPath,
5933
5973
  });
5934
5974
  }
5975
+ /** 构造 mcp_manage 工具宿主:安装/删除/重载后同步本客户端会话工具表与设置面板。 */
5976
+ mcpManageToolHost(cwd) {
5977
+ return {
5978
+ listServers: () => listAllMcpServers({
5979
+ agentDir: this.agentDir,
5980
+ cwd,
5981
+ dataDir: this.stateStore.dataDir,
5982
+ bridge: ClientSession.mcpBridge ?? undefined,
5983
+ }),
5984
+ checkServer: (query) => checkMcpServer({
5985
+ agentDir: this.agentDir,
5986
+ cwd,
5987
+ dataDir: this.stateStore.dataDir,
5988
+ bridge: ClientSession.mcpBridge ?? undefined,
5989
+ query,
5990
+ }),
5991
+ installServer: async (spec) => {
5992
+ const res = await installMcpServer({
5993
+ agentDir: this.agentDir,
5994
+ cwd,
5995
+ dataDir: this.stateStore.dataDir,
5996
+ bridge: ClientSession.mcpBridge ?? undefined,
5997
+ spec,
5998
+ });
5999
+ if (res.ok) {
6000
+ this.refreshPluginTools();
6001
+ this.broadcastMcpServers();
6002
+ this.pushSettings();
6003
+ }
6004
+ return res;
6005
+ },
6006
+ removeServer: async (name, scope) => {
6007
+ const targetScope = scope ??
6008
+ (checkMcpServer({
6009
+ agentDir: this.agentDir,
6010
+ cwd,
6011
+ dataDir: this.stateStore.dataDir,
6012
+ bridge: ClientSession.mcpBridge ?? undefined,
6013
+ query: name,
6014
+ }).server?.scope ||
6015
+ "project");
6016
+ const res = deleteMcpServerFile({
6017
+ agentDir: this.agentDir,
6018
+ cwd,
6019
+ dataDir: this.stateStore.dataDir,
6020
+ name,
6021
+ scope: targetScope,
6022
+ });
6023
+ if (res.ok) {
6024
+ if (ClientSession.mcpBridge) {
6025
+ await ClientSession.mcpBridge.reload();
6026
+ }
6027
+ this.refreshPluginTools();
6028
+ this.broadcastMcpServers();
6029
+ this.pushSettings();
6030
+ }
6031
+ return res;
6032
+ },
6033
+ reloadServers: async () => {
6034
+ if (ClientSession.mcpBridge) {
6035
+ await ClientSession.mcpBridge.reload();
6036
+ }
6037
+ this.refreshPluginTools();
6038
+ this.broadcastMcpServers();
6039
+ this.pushSettings();
6040
+ return listAllMcpServers({
6041
+ agentDir: this.agentDir,
6042
+ cwd,
6043
+ dataDir: this.stateStore.dataDir,
6044
+ bridge: ClientSession.mcpBridge ?? undefined,
6045
+ });
6046
+ },
6047
+ };
6048
+ }
5935
6049
  /** 从技能市场安装技能到全局 (~/.pi/agent/skills) 或当前项目 (.pi/skills) */
5936
6050
  async installSkill(name, scope, content) {
5937
6051
  const cleanName = name.trim();
@@ -6120,7 +6234,7 @@ export class ClientSession {
6120
6234
  };
6121
6235
  // 写/编的权限沙箱包装:同一个函数,有扩展同名工具时把它的定义当基底(末参)。
6122
6236
  // 目标审查闸门包在**最外层**(权限沙箱之前):审查回合只读核实,写类直接拒。
6123
- const planGate = (def) => withGoalReviewGate(withDelegationGate(withPlanModeGate(def, () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang());
6237
+ const planGate = (def) => withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(def, () => this.sandboxes.getByCwd(cwd), () => cwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang());
6124
6238
  const composeWrite = (base) => planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
6125
6239
  const composeEdit = (base) => planGate(wrapEditToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
6126
6240
  const remoteOps = createRemoteSdkOperations(cwd);
@@ -7910,12 +8024,13 @@ export class ClientSession {
7910
8024
  // (inMemory 后台任务,不占位)。临时会话也不占名额。
7911
8025
  if (!ephemeral) {
7912
8026
  const openInProject = [...this.convs.values()].filter((c) => c.cwd === this.cwd && !c.isSubagent && !c.isEphemeral).length;
7913
- if (openInProject >= MAX_OPEN_CONVERSATIONS) {
8027
+ const maxOpenConversations = getMaxOpenConversations();
8028
+ if (openInProject >= maxOpenConversations) {
7914
8029
  this.emit({
7915
8030
  type: "notice",
7916
8031
  level: "warning",
7917
- text: `当前项目运行的对话已达上限(${MAX_OPEN_CONVERSATIONS} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
7918
- textEn: `This project already has the max open conversations (${MAX_OPEN_CONVERSATIONS}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
8032
+ text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
8033
+ textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
7919
8034
  });
7920
8035
  return false;
7921
8036
  }
@@ -7933,6 +8048,16 @@ export class ClientSession {
7933
8048
  const conversationId = this.nextConversationId();
7934
8049
  const terminals = this.makeTerminalManager(conversationId, this.cwd);
7935
8050
  const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, this.cwd);
8051
+ this.emit({
8052
+ type: "transition_progress",
8053
+ kind: "new_chat",
8054
+ target: this.cwd,
8055
+ phase: "runtime",
8056
+ progress: 45,
8057
+ text: "正在初始化新对话环境…",
8058
+ textEn: "Initializing new chat runtime…",
8059
+ });
8060
+ await new Promise((r) => setImmediate(r));
7936
8061
  let sessionManager;
7937
8062
  if (ephemeral) {
7938
8063
  sessionManager = SessionManager.inMemory(sessionBaseDir);
@@ -8026,9 +8151,27 @@ export class ClientSession {
8026
8151
  // 新对话即当前打开 → 插件重拉(轨迹视图跟随)。
8027
8152
  this.notifyConversationChanged();
8028
8153
  this.pushSettings();
8154
+ this.emit({
8155
+ type: "transition_progress",
8156
+ kind: "new_chat",
8157
+ target: this.cwd,
8158
+ phase: "done",
8159
+ progress: 100,
8160
+ text: "新对话已就绪",
8161
+ textEn: "New chat ready",
8162
+ });
8029
8163
  ready = true;
8030
8164
  }
8031
8165
  catch (err) {
8166
+ this.emit({
8167
+ type: "transition_progress",
8168
+ kind: "new_chat",
8169
+ target: this.cwd,
8170
+ phase: "error",
8171
+ progress: 100,
8172
+ text: `新建对话失败:${err.message}`,
8173
+ textEn: `Failed to create chat: ${err.message}`,
8174
+ });
8032
8175
  this.emit({
8033
8176
  type: "notice",
8034
8177
  level: "error",
@@ -8235,15 +8378,49 @@ export class ClientSession {
8235
8378
  this.emit(n);
8236
8379
  return repair;
8237
8380
  }
8381
+ /**
8382
+ * 从已打开并校准叶子节点的 SessionManager 中提取尾部预览消息与总条数。
8383
+ * 在耗时的 createAgentSessionRuntime(扫扩展/技能)开始前先行流式推给浏览器,
8384
+ * 让切换目录/历史会话在几十毫秒内就能在屏幕上流式呈现对话内容。
8385
+ */
8386
+ extractTranscriptPreview(manager, maxPreview = 16) {
8387
+ try {
8388
+ const branch = manager.getBranch();
8389
+ const msgEntries = [];
8390
+ for (const e of branch) {
8391
+ if (e.type === "message") {
8392
+ const m = e.message;
8393
+ if (m && m.role !== "system") {
8394
+ msgEntries.push(m);
8395
+ }
8396
+ }
8397
+ }
8398
+ const totalMessages = msgEntries.length;
8399
+ const tail = msgEntries.slice(-maxPreview);
8400
+ const startOffset = totalMessages - tail.length;
8401
+ const previewMessages = [];
8402
+ for (let i = 0; i < tail.length; i++) {
8403
+ const ui = serializeMessage(tail[i], startOffset + i + 1);
8404
+ if (ui)
8405
+ previewMessages.push(ui);
8406
+ }
8407
+ return { totalMessages, previewMessages };
8408
+ }
8409
+ catch {
8410
+ return { totalMessages: 0, previewMessages: [] };
8411
+ }
8412
+ }
8238
8413
  /**
8239
8414
  * #235:manager+runtime 一起建,链损坏报错则修最近文件后重试一次。
8240
8415
  * SessionManager.open 本身不走 parent 链(真正死循环的是 runtime 初始化里的
8241
8416
  * getBranch),所以重试必须把两步都包进来;修完用全新 manager 重读。
8242
8417
  */
8243
- async openManagerAndRuntime(makeManager, makeRuntime, locateFile) {
8418
+ async openManagerAndRuntime(makeManager, makeRuntime, locateFile, onTranscriptLoaded) {
8244
8419
  try {
8245
8420
  const manager = makeManager();
8246
8421
  calibrateSessionLeaf(manager);
8422
+ if (onTranscriptLoaded)
8423
+ await onTranscriptLoaded(manager);
8247
8424
  const runtime = await makeRuntime(manager);
8248
8425
  return { manager, runtime, repair: null };
8249
8426
  }
@@ -8256,6 +8433,8 @@ export class ClientSession {
8256
8433
  throw err;
8257
8434
  const manager = makeManager();
8258
8435
  calibrateSessionLeaf(manager);
8436
+ if (onTranscriptLoaded)
8437
+ await onTranscriptLoaded(manager);
8259
8438
  const runtime = await makeRuntime(manager);
8260
8439
  return { manager, runtime, repair };
8261
8440
  }
@@ -9001,9 +9180,10 @@ export class ClientSession {
9001
9180
  static sessionInfosCache = new Map();
9002
9181
  static sessionInfosInFlight = new Map();
9003
9182
  static SESSION_INFO_CACHE_TTL = 30_000;
9004
- async loadSessionInfos() {
9183
+ async loadSessionInfos(forCwd) {
9184
+ const targetCwd = forCwd ?? this.cwd;
9005
9185
  const now = Date.now();
9006
- const cwdKey = normalizePathKey(this.cwd);
9186
+ const cwdKey = normalizePathKey(targetCwd);
9007
9187
  const c = ClientSession.sessionInfosCache.get(cwdKey);
9008
9188
  if (c && now - c.at < ClientSession.SESSION_INFO_CACHE_TTL) {
9009
9189
  return c.infos;
@@ -9011,7 +9191,7 @@ export class ClientSession {
9011
9191
  const inFlight = ClientSession.sessionInfosInFlight.get(cwdKey);
9012
9192
  if (inFlight)
9013
9193
  return inFlight;
9014
- const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, this.cwd);
9194
+ const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
9015
9195
  const run = (async () => {
9016
9196
  try {
9017
9197
  const sessionDir = piSessionsRoot()
@@ -9097,10 +9277,14 @@ export class ClientSession {
9097
9277
  this.sessionsRequested = true;
9098
9278
  await this.pushSessions();
9099
9279
  }
9100
- /** 切项目时的会话列表刷新:历史面板没打开过就不扫盘(只清缓存),打开过
9101
- * 才重推 —— 首访切项目的转录解析不在关键路径上。 */
9280
+ /** 切项目时的会话列表刷新:sessionInfosCache 已按 cwdKey 隔离(30s TTL),
9281
+ * 若刚刚在 setCwd 并行预热过(<2s 内)则直接复用预热结果推送,不再清空重扫。 */
9102
9282
  refreshSessionsOnSwitch() {
9103
- this.invalidateSessionInfos();
9283
+ const cwdKey = normalizePathKey(this.cwd);
9284
+ const cached = ClientSession.sessionInfosCache.get(cwdKey);
9285
+ if (!cached || Date.now() - cached.at > 2_000) {
9286
+ ClientSession.sessionInfosCache.delete(cwdKey);
9287
+ }
9104
9288
  if (this.sessionsRequested)
9105
9289
  void this.refreshSessions();
9106
9290
  }
@@ -9148,8 +9332,13 @@ export class ClientSession {
9148
9332
  this.emit({ type: "sessions", sessions: [] });
9149
9333
  }
9150
9334
  }
9151
- /** Remove an entry from the client's recent-project list (UI state only). */
9335
+ /** Remove an entry from the client's recent-project list (UI state only, or destroy if sandbox). */
9152
9336
  async removeProject(path) {
9337
+ const sbx = this.sandboxes.get(path) ?? this.sandboxes.getByCwd(path);
9338
+ if (sbx) {
9339
+ await this.destroySandbox(sbx.path);
9340
+ return;
9341
+ }
9153
9342
  this.stateStore.removeProject(this.clientId, path);
9154
9343
  this.invalidateProjectsCache();
9155
9344
  await this.pushProjects();
@@ -10091,9 +10280,38 @@ export class ClientSession {
10091
10280
  }
10092
10281
  // #235:先修后开——坏转录到 open 后的 getBranch 会死循环,修完再读。
10093
10282
  // 单文件预扫描,健康文件只多一次小读;修过即弹提示(含压缩被打断与分支拓扑纠偏)。
10283
+ this.emit({
10284
+ type: "transition_progress",
10285
+ kind: "session",
10286
+ target: targetPath,
10287
+ phase: "fs",
10288
+ progress: 28,
10289
+ text: "正在读取历史会话记录…",
10290
+ textEn: "Reading session transcript…",
10291
+ });
10292
+ await new Promise((r) => setImmediate(r));
10094
10293
  this.repairTranscriptFileBeforeOpen(targetPath);
10095
10294
  const sessionManager = SessionManager.open(targetPath);
10096
10295
  calibrateSessionLeaf(sessionManager);
10296
+ {
10297
+ const { totalMessages, previewMessages } = this.extractTranscriptPreview(sessionManager, 16);
10298
+ this.emit({
10299
+ type: "transition_progress",
10300
+ kind: "session",
10301
+ target: targetPath,
10302
+ phase: "transcript",
10303
+ progress: 62,
10304
+ text: totalMessages > 0
10305
+ ? `已流式载入会话记录(${totalMessages} 条消息),正在挂载智能体环境…`
10306
+ : "会话记录已就绪,正在挂载智能体环境…",
10307
+ textEn: totalMessages > 0
10308
+ ? `Streamed session transcript (${totalMessages} messages), mounting agent runtime…`
10309
+ : "Transcript ready, mounting agent runtime…",
10310
+ totalMessages,
10311
+ ...(previewMessages.length > 0 ? { previewMessages } : {}),
10312
+ });
10313
+ await new Promise((r) => setImmediate(r));
10314
+ }
10097
10315
  const rawSessionCwd = sessionManager.getCwd();
10098
10316
  const targetCwd = restoreWorkspaceUriFromSessionDir(rawSessionCwd);
10099
10317
  const runtimeCwd = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
@@ -10111,7 +10329,8 @@ export class ClientSession {
10111
10329
  const openInProject = [...this.convs.values()].filter((c) => c.cwd === targetCwd && !c.isSubagent && !c.isEphemeral).length +
10112
10330
  1 -
10113
10331
  (displaced?.cwd === targetCwd && !displaced?.isSubagent && !displaced?.isEphemeral ? 1 : 0);
10114
- if (openInProject > MAX_OPEN_CONVERSATIONS) {
10332
+ const maxOpenConversations = getMaxOpenConversations();
10333
+ if (openInProject > maxOpenConversations) {
10115
10334
  // displaceActive() may have promoted a streaming conversation into the
10116
10335
  // running list. Roll that presentation-only mutation back because no
10117
10336
  // switch will take place.
@@ -10120,11 +10339,20 @@ export class ClientSession {
10120
10339
  await openedRuntime.dispose();
10121
10340
  openedRuntime = null;
10122
10341
  openedTerminals = null;
10342
+ this.emit({
10343
+ type: "transition_progress",
10344
+ kind: "session",
10345
+ target: targetPath,
10346
+ phase: "error",
10347
+ progress: 100,
10348
+ text: `当前项目运行的对话已达上限(${maxOpenConversations} 个)`,
10349
+ textEn: `Max open conversations (${maxOpenConversations}) reached`,
10350
+ });
10123
10351
  this.emit({
10124
10352
  type: "notice",
10125
10353
  level: "warning",
10126
- text: `当前项目运行的对话已达上限(${MAX_OPEN_CONVERSATIONS} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
10127
- textEn: `This project already has the max open conversations (${MAX_OPEN_CONVERSATIONS}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
10354
+ text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
10355
+ textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
10128
10356
  });
10129
10357
  return;
10130
10358
  }
@@ -10152,8 +10380,24 @@ export class ClientSession {
10152
10380
  // 打开的历史会话可能属于另一个项目 —— 工作区跟随面(roots/文件树/
10153
10381
  // 历史列表/命令目录/最近项目)必须跟着切,否则 UI 停在旧项目。
10154
10382
  this.applyCwdSideEffects(targetCwd);
10155
- await this.restoreProjectProviderKeysForCwd(targetCwd);
10156
- await this.restoreProjectModelForCwd(targetCwd);
10383
+ // 模型与 key 恢复走后台异步(带代际守卫),不阻塞历史会话快照首帧送达
10384
+ {
10385
+ const convId = this.activeId;
10386
+ void (async () => {
10387
+ try {
10388
+ await this.restoreProjectProviderKeysForCwd(targetCwd);
10389
+ if (this.disposed || this.activeId !== convId || this.cwd !== targetCwd)
10390
+ return;
10391
+ await this.restoreProjectModelForCwd(targetCwd);
10392
+ if (this.disposed || this.activeId !== convId || this.cwd !== targetCwd)
10393
+ return;
10394
+ this.flushSnapshot();
10395
+ }
10396
+ catch {
10397
+ /* 静默:恢复失败保持会话默认 */
10398
+ }
10399
+ })();
10400
+ }
10157
10401
  this.conv.lastActiveAt = Date.now();
10158
10402
  this.webUi.refresh();
10159
10403
  this.emitConversations();
@@ -10164,11 +10408,29 @@ export class ClientSession {
10164
10408
  // 切历史会话成功 → 插件重拉(轨迹视图立即显示该会话时间线)。
10165
10409
  this.notifyConversationChanged();
10166
10410
  this.pushSettings();
10411
+ this.emit({
10412
+ type: "transition_progress",
10413
+ kind: "session",
10414
+ target: targetPath,
10415
+ phase: "done",
10416
+ progress: 100,
10417
+ text: "会话加载完成",
10418
+ textEn: "Session loaded",
10419
+ });
10167
10420
  }
10168
10421
  catch (err) {
10169
10422
  openedTerminals?.killAll();
10170
10423
  if (openedRuntime)
10171
10424
  await openedRuntime.dispose().catch(() => { });
10425
+ this.emit({
10426
+ type: "transition_progress",
10427
+ kind: "session",
10428
+ target: path || sessionId || "",
10429
+ phase: "error",
10430
+ progress: 100,
10431
+ text: `切换会话失败:${err.message}`,
10432
+ textEn: `Failed to switch session: ${err.message}`,
10433
+ });
10172
10434
  this.emit({
10173
10435
  type: "notice",
10174
10436
  level: "error",
@@ -10296,7 +10558,8 @@ export class ClientSession {
10296
10558
  const openInProject = [...this.convs.values()].filter((c) => c.cwd === targetConv.cwd && !c.isSubagent && !c.isEphemeral).length +
10297
10559
  1 -
10298
10560
  (displaced?.cwd === targetConv.cwd && !displaced?.isSubagent && !displaced?.isEphemeral ? 1 : 0);
10299
- if (openInProject > MAX_OPEN_CONVERSATIONS) {
10561
+ const maxOpenConversations = getMaxOpenConversations();
10562
+ if (openInProject > maxOpenConversations) {
10300
10563
  // displaceActive() 可能只是把旧对话标成后台展示(presentation-only);
10301
10564
  // 没有切换发生时回滚该标记,新 fork 的 runtime/终端直接释放。
10302
10565
  this.conv.listed = oldListed;
@@ -10305,8 +10568,8 @@ export class ClientSession {
10305
10568
  this.emit({
10306
10569
  type: "notice",
10307
10570
  level: "warning",
10308
- text: `当前项目运行的对话已达上限(${MAX_OPEN_CONVERSATIONS} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
10309
- textEn: `This project already has the max open conversations (${MAX_OPEN_CONVERSATIONS}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
10571
+ text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
10572
+ textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
10310
10573
  });
10311
10574
  return;
10312
10575
  }
@@ -10574,9 +10837,12 @@ export class ClientSession {
10574
10837
  async pushProjects() {
10575
10838
  const now = Date.now();
10576
10839
  const cached = ClientSession.projectsCache;
10577
- // TTL 命中:直接复用(把当前 cwd 合并进去,刚 remember 的新项目也可见)。
10578
- if (cached && now - cached.at < ClientSession.PROJECTS_CACHE_TTL) {
10579
- this.emit({ type: "projects", projects: this.withCurrentCwd(cached.projects, now) });
10840
+ // TTL 命中(或已建立过项目缓存):直接把当前 cwd 合并重排并续期,
10841
+ // 避免切换工作区时因为刚好跨过 60s TTL 而触发全盘 30 个会话子目录重扫。
10842
+ if (cached) {
10843
+ const updated = this.withCurrentCwd(cached.projects, now);
10844
+ ClientSession.projectsCache = { at: now, projects: updated };
10845
+ this.emit({ type: "projects", projects: updated });
10580
10846
  return;
10581
10847
  }
10582
10848
  // 已有扫描在跑:搭车等它,不要并发扫两遍盘。
@@ -10624,15 +10890,41 @@ export class ClientSession {
10624
10890
  withCurrentCwd(projects, now) {
10625
10891
  const currentKey = normalizePathKey(this.cwd);
10626
10892
  const removedKeys = new Set(this.stateStore.getRemovedProjects(this.clientId).map(normalizePathKey));
10893
+ // 过滤掉已销毁(不在沙盒注册表且目录位于 sandboxesRoot 下)的残留沙盒条目
10894
+ const validProjects = projects.filter((p) => {
10895
+ if (isSameOrSubpath(p.path, this.sandboxes.sandboxesRoot)) {
10896
+ return Boolean(this.sandboxes.getByCwd(p.path));
10897
+ }
10898
+ return true;
10899
+ });
10900
+ let list;
10627
10901
  if (removedKeys.has(currentKey)) {
10628
- return projects;
10902
+ list = validProjects;
10629
10903
  }
10630
- if (projects.some((p) => normalizePathKey(p.path) === currentKey)) {
10631
- return projects
10904
+ else if (validProjects.some((p) => normalizePathKey(p.path) === currentKey)) {
10905
+ list = validProjects
10632
10906
  .map((p) => (normalizePathKey(p.path) === currentKey && p.lastUsed < now ? { ...p, lastUsed: now } : p))
10633
10907
  .sort((a, b) => b.lastUsed - a.lastUsed);
10634
10908
  }
10635
- return [{ path: this.cwd, lastUsed: now }, ...projects].slice(0, 20);
10909
+ else {
10910
+ list = [{ path: this.cwd, lastUsed: now }, ...validProjects].slice(0, 20);
10911
+ }
10912
+ // 确保所有仍存活的注册沙盒也出现在列表里,并附带 sandbox 元数据
10913
+ const existingKeys = new Set(list.map((p) => normalizePathKey(p.path)));
10914
+ for (const sbx of this.sandboxes.list()) {
10915
+ const k = normalizePathKey(sbx.path);
10916
+ if (!existingKeys.has(k) && !removedKeys.has(k)) {
10917
+ list.push({ path: sbx.path, lastUsed: sbx.createdAt, sandbox: sbx });
10918
+ existingKeys.add(k);
10919
+ }
10920
+ }
10921
+ return list
10922
+ .map((p) => {
10923
+ const sbx = this.sandboxes.getByCwd(p.path);
10924
+ return sbx ? { ...p, sandbox: sbx } : p;
10925
+ })
10926
+ .sort((a, b) => b.lastUsed - a.lastUsed)
10927
+ .slice(0, 25);
10636
10928
  }
10637
10929
  /** 最近项目缓存失效(用户显式移除项目后,下一次推送必须重扫)。 */
10638
10930
  invalidateProjectsCache() {
@@ -10874,14 +11166,24 @@ export class ClientSession {
10874
11166
  }
10875
11167
  else {
10876
11168
  // 冷切换的 runtime 创建要 1~2s(扫技能/扩展)—— 先回一条 ack +
10877
- // 快照,点击看起来不再 frozen;落地后再推第二次全量。
11169
+ // 流式进度 + 快照,点击立即呈现阶段进度与转录预览;落地后再推完整全量。
10878
11170
  this.emit({
10879
- type: "notice",
10880
- level: "info",
10881
- text: `正在切换到工作目录:${abs}`,
10882
- textEn: `Switching to directory: ${abs}`,
11171
+ type: "transition_progress",
11172
+ kind: "cwd",
11173
+ target: abs,
11174
+ phase: "fs",
11175
+ progress: 28,
11176
+ text: `正在同步目录与检查最近会话:${abs}`,
11177
+ textEn: `Validating workspace & checking recent session: ${abs}`,
10883
11178
  });
10884
11179
  this.flushSnapshot();
11180
+ // 让出事件循环,确保首帧进度在同步磁盘扫描前真正发往浏览器
11181
+ await new Promise((r) => setImmediate(r));
11182
+ // 在耗时的 runtime 初始化期间,并行预热目标项目的会话列表缓存
11183
+ if (this.sessionsRequested) {
11184
+ ClientSession.sessionInfosCache.delete(normalizePathKey(abs));
11185
+ void this.loadSessionInfos(abs).catch(() => { });
11186
+ }
10885
11187
  // First visit to this project: resume its most recent session —
10886
11188
  // unless that transcript is still held on another client (#145):
10887
11189
  // default-opening it would strand the tab on a conversation it
@@ -10912,7 +11214,25 @@ export class ClientSession {
10912
11214
  cwd: sessionBaseDir,
10913
11215
  agentDir: this.agentDir,
10914
11216
  sessionManager: m,
10915
- }), async () => (await SessionManager.list(sessionBaseDir))[0]?.path);
11217
+ }), async () => (await SessionManager.list(sessionBaseDir))[0]?.path, async (m) => {
11218
+ const { totalMessages, previewMessages } = this.extractTranscriptPreview(m, 16);
11219
+ this.emit({
11220
+ type: "transition_progress",
11221
+ kind: "cwd",
11222
+ target: abs,
11223
+ phase: "transcript",
11224
+ progress: 64,
11225
+ text: totalMessages > 0
11226
+ ? `已流式载入最近会话(${totalMessages} 条消息),正在挂载智能体与工具…`
11227
+ : `工作区会话已就绪,正在挂载智能体与工具…`,
11228
+ textEn: totalMessages > 0
11229
+ ? `Streamed recent session (${totalMessages} messages), mounting agent & tools…`
11230
+ : `Workspace session ready, mounting agent & tools…`,
11231
+ totalMessages,
11232
+ ...(previewMessages.length > 0 ? { previewMessages } : {}),
11233
+ });
11234
+ await new Promise((r) => setImmediate(r));
11235
+ });
10916
11236
  const newRuntime = opened.runtime;
10917
11237
  if (opened.repair) {
10918
11238
  for (const n of this.transcriptRepairNotices(opened.repair))
@@ -10979,8 +11299,11 @@ export class ClientSession {
10979
11299
  // Skills / prompt templates are project-bound — refresh the catalog.
10980
11300
  void this.pushSlashCommands();
10981
11301
  this.emit({
10982
- type: "notice",
10983
- level: "info",
11302
+ type: "transition_progress",
11303
+ kind: "cwd",
11304
+ target: abs,
11305
+ phase: "done",
11306
+ progress: 100,
10984
11307
  text: `已切换到工作目录:${abs}`,
10985
11308
  textEn: `Switched to directory: ${abs}`,
10986
11309
  });
@@ -10989,6 +11312,15 @@ export class ClientSession {
10989
11312
  this.pushSettings();
10990
11313
  }
10991
11314
  catch (err) {
11315
+ this.emit({
11316
+ type: "transition_progress",
11317
+ kind: "cwd",
11318
+ target: newCwd.trim(),
11319
+ phase: "error",
11320
+ progress: 100,
11321
+ text: `切换工作目录失败:${err.message}`,
11322
+ textEn: `Failed to switch directory: ${err.message}`,
11323
+ });
10992
11324
  this.emit({
10993
11325
  type: "notice",
10994
11326
  level: "error",
@@ -10998,6 +11330,216 @@ export class ClientSession {
10998
11330
  }
10999
11331
  this.flushSnapshot();
11000
11332
  }
11333
+ /** 创建隔离沙盒项目(空白或从 sourcePath 导入)并自动切换到该沙盒。 */
11334
+ async createSandbox(opts) {
11335
+ try {
11336
+ const { sandbox, copiedFiles } = await this.sandboxes.create(opts);
11337
+ this.invalidateProjectsCache();
11338
+ await this.setCwd(sandbox.path);
11339
+ await this.pushProjects();
11340
+ const modeZh = sandbox.sourcePath ? `已从源项目导入 ${copiedFiles} 个文件` : "空白隔离环境";
11341
+ const modeEn = sandbox.sourcePath ? `imported ${copiedFiles} files from source` : "blank isolated workspace";
11342
+ this.emit({
11343
+ type: "notice",
11344
+ level: "info",
11345
+ text: `🧪 沙盒「${sandbox.name}」已启动(${modeZh},一切修改与原项目完全隔离)`,
11346
+ textEn: `🧪 Sandbox "${sandbox.name}" started (${modeEn}; all changes are strictly isolated)`,
11347
+ });
11348
+ }
11349
+ catch (err) {
11350
+ this.emit({
11351
+ type: "notice",
11352
+ level: "error",
11353
+ text: `创建沙盒失败:${err.message}`,
11354
+ textEn: `Failed to create sandbox: ${err.message}`,
11355
+ });
11356
+ }
11357
+ }
11358
+ /** 重置沙盒工作区到初始状态(空白或重新从源项目复制)。 */
11359
+ async resetSandbox(path) {
11360
+ const target = path?.trim() || this.cwd;
11361
+ try {
11362
+ const { sandbox, copiedFiles } = await this.sandboxes.reset(target);
11363
+ await this.listFiles();
11364
+ this.flushSnapshot();
11365
+ this.emit({
11366
+ type: "notice",
11367
+ level: "info",
11368
+ text: sandbox.sourcePath
11369
+ ? `🔄 已重置沙盒「${sandbox.name}」(重新从源项目同步 ${copiedFiles} 个文件)`
11370
+ : `🔄 已清空并重置沙盒「${sandbox.name}」`,
11371
+ textEn: sandbox.sourcePath
11372
+ ? `🔄 Reset sandbox "${sandbox.name}" (re-synced ${copiedFiles} files from source)`
11373
+ : `🔄 Cleared and reset sandbox "${sandbox.name}"`,
11374
+ });
11375
+ }
11376
+ catch (err) {
11377
+ this.emit({
11378
+ type: "notice",
11379
+ level: "error",
11380
+ text: `重置沙盒失败:${err.message}`,
11381
+ textEn: `Failed to reset sandbox: ${err.message}`,
11382
+ });
11383
+ }
11384
+ }
11385
+ /** 将临时沙盒转为永久保留的沙盒项目。 */
11386
+ async persistSandbox(path) {
11387
+ const target = path?.trim() || this.cwd;
11388
+ try {
11389
+ const sandbox = this.sandboxes.persist(target);
11390
+ this.invalidateProjectsCache();
11391
+ await this.pushProjects();
11392
+ this.flushSnapshot();
11393
+ this.emit({
11394
+ type: "notice",
11395
+ level: "info",
11396
+ text: `📌 沙盒「${sandbox.name}」已转为永久保留`,
11397
+ textEn: `📌 Sandbox "${sandbox.name}" is now saved permanently`,
11398
+ });
11399
+ }
11400
+ catch (err) {
11401
+ this.emit({
11402
+ type: "notice",
11403
+ level: "error",
11404
+ text: `转换永久沙盒失败:${err.message}`,
11405
+ textEn: `Failed to persist sandbox: ${err.message}`,
11406
+ });
11407
+ }
11408
+ }
11409
+ /** 将沙盒导出/另存为正式项目目录,可选立即切换过去。 */
11410
+ async promoteSandbox(targetPath, path, switchToTarget = true) {
11411
+ const sbxTarget = path?.trim() || this.cwd;
11412
+ try {
11413
+ const { sandbox, targetPath: resolvedTarget, copiedFiles } = await this.sandboxes.promote(sbxTarget, targetPath);
11414
+ this.invalidateProjectsCache();
11415
+ if (switchToTarget) {
11416
+ await this.setCwd(resolvedTarget);
11417
+ }
11418
+ else {
11419
+ await this.pushProjects();
11420
+ }
11421
+ this.emit({
11422
+ type: "notice",
11423
+ level: "info",
11424
+ text: `📤 已将沙盒「${sandbox.name}」导出为正式项目:${resolvedTarget}(共 ${copiedFiles} 个文件)`,
11425
+ textEn: `📤 Exported sandbox "${sandbox.name}" to formal project: ${resolvedTarget} (${copiedFiles} files)`,
11426
+ });
11427
+ }
11428
+ catch (err) {
11429
+ this.emit({
11430
+ type: "notice",
11431
+ level: "error",
11432
+ text: `导出沙盒失败:${err.message}`,
11433
+ textEn: `Failed to export sandbox: ${err.message}`,
11434
+ });
11435
+ }
11436
+ }
11437
+ /** 对比沙盒与源项目之间的新增/修改/删除文件清单并推送给前端。 */
11438
+ async diffSandbox(path) {
11439
+ const target = path?.trim() || this.cwd;
11440
+ try {
11441
+ const res = await this.sandboxes.diffWithSource(target);
11442
+ this.emit({
11443
+ type: "sandbox_diff",
11444
+ diff: {
11445
+ sandboxId: res.sandbox.id,
11446
+ path: res.sandbox.path,
11447
+ sourcePath: res.sourcePath,
11448
+ added: res.added.slice(0, 200),
11449
+ modified: res.modified.slice(0, 200),
11450
+ deleted: res.deleted.slice(0, 200),
11451
+ unchangedCount: res.unchangedCount,
11452
+ },
11453
+ });
11454
+ }
11455
+ catch (err) {
11456
+ this.emit({
11457
+ type: "sandbox_diff",
11458
+ diff: {
11459
+ sandboxId: "",
11460
+ path: target,
11461
+ added: [],
11462
+ modified: [],
11463
+ deleted: [],
11464
+ unchangedCount: 0,
11465
+ error: err.message,
11466
+ },
11467
+ });
11468
+ }
11469
+ }
11470
+ /** 将导入型沙盒的改动写回源项目(保留源项目 .git 与依赖缓存)。 */
11471
+ async applySandboxToSource(path) {
11472
+ const target = path?.trim() || this.cwd;
11473
+ try {
11474
+ const { sandbox, sourcePath, copiedFiles } = await this.sandboxes.applyToSource(target);
11475
+ this.emit({
11476
+ type: "notice",
11477
+ level: "info",
11478
+ text: `✅ 已将沙盒「${sandbox.name}」中的 ${copiedFiles} 个文件同步回源项目:${sourcePath}`,
11479
+ textEn: `✅ Applied ${copiedFiles} files from sandbox "${sandbox.name}" back to source project: ${sourcePath}`,
11480
+ });
11481
+ }
11482
+ catch (err) {
11483
+ this.emit({
11484
+ type: "notice",
11485
+ level: "error",
11486
+ text: `写回源项目失败:${err.message}`,
11487
+ textEn: `Failed to apply sandbox changes to source: ${err.message}`,
11488
+ });
11489
+ }
11490
+ }
11491
+ /** 彻底销毁沙盒目录:若当前正在该沙盒内,先自动切回源项目或其它最近项目。 */
11492
+ async destroySandbox(path) {
11493
+ const target = path?.trim() || this.cwd;
11494
+ const sbx = this.sandboxes.get(target) ?? this.sandboxes.getByCwd(target);
11495
+ if (!sbx) {
11496
+ this.stateStore.removeProject(this.clientId, target);
11497
+ this.invalidateProjectsCache();
11498
+ await this.pushProjects();
11499
+ return;
11500
+ }
11501
+ try {
11502
+ const activeInSbx = isSameOrSubpath(this.cwd, sbx.path);
11503
+ if (activeInSbx) {
11504
+ // 挑选回退目录:优先源项目 → 最近非当前沙盒项目 → homedir
11505
+ let fallbackCwd = sbx.sourcePath && existsSync(sbx.sourcePath) ? sbx.sourcePath : "";
11506
+ if (!fallbackCwd) {
11507
+ const recent = await this.stateStore.getRecentProjects(this.clientId);
11508
+ const other = recent.find((p) => {
11509
+ const pk = normalizePathKey(p.path);
11510
+ return pk !== normalizePathKey(sbx.path) && existsSync(p.path);
11511
+ });
11512
+ fallbackCwd = other?.path || homedir();
11513
+ }
11514
+ await this.setCwd(fallbackCwd);
11515
+ }
11516
+ // 清理仍挂在该沙盒下的后台会话
11517
+ for (const [cid, c] of this.convs) {
11518
+ if (cid !== this.activeId && normalizePathKey(c.cwd) === normalizePathKey(sbx.path)) {
11519
+ this.removeConversation(cid);
11520
+ }
11521
+ }
11522
+ await this.sandboxes.destroy(sbx.id);
11523
+ this.stateStore.removeProject(this.clientId, sbx.path);
11524
+ this.invalidateProjectsCache();
11525
+ await this.pushProjects();
11526
+ this.flushSnapshot();
11527
+ this.emit({
11528
+ type: "notice",
11529
+ level: "info",
11530
+ text: `🗑️ 已销毁沙盒项目「${sbx.name}」并清理隔离目录`,
11531
+ textEn: `🗑️ Destroyed sandbox project "${sbx.name}" and cleaned up isolated directory`,
11532
+ });
11533
+ }
11534
+ catch (err) {
11535
+ this.emit({
11536
+ type: "notice",
11537
+ level: "error",
11538
+ text: `销毁沙盒失败:${err.message}`,
11539
+ textEn: `Failed to destroy sandbox: ${err.message}`,
11540
+ });
11541
+ }
11542
+ }
11001
11543
  /** Strip the "(New)" freshness marker some catalogs append to display names
11002
11544
  * (pi.dev data, e.g. "DeepSeek V4 Pro (New)") — display-only; the model id
11003
11545
  * is untouched so switching still uses the exact official id. */