pi-web-ui 0.116.0 → 0.117.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 (155) hide show
  1. package/CHANGELOG.md +38 -4
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +138 -70
  4. package/dist/server/agent-service-daemon.js +52 -6
  5. package/dist/server/agent-service.js +495 -141
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +35 -6
  8. package/dist/server/compaction-markers.js +43 -24
  9. package/dist/server/dangling-tools.js +172 -16
  10. package/dist/server/device-center/bot-execution.js +48 -1
  11. package/dist/server/device-center/collab-service.js +26 -8
  12. package/dist/server/device-center/collab-tool.js +394 -18
  13. package/dist/server/device-center/connector.js +107 -37
  14. package/dist/server/device-center/delivery-authority.js +98 -0
  15. package/dist/server/device-center/delivery-subject.js +30 -0
  16. package/dist/server/device-center/device-integration.js +453 -183
  17. package/dist/server/device-center/execution-guides.js +15 -5
  18. package/dist/server/device-center/executor.js +47 -5
  19. package/dist/server/device-center/hub-conversations.js +14 -4
  20. package/dist/server/device-center/hub-deliveries.js +120 -15
  21. package/dist/server/device-center/hub-integration.js +655 -334
  22. package/dist/server/device-center/hub-page.js +5 -4
  23. package/dist/server/device-center/hub-setup.js +23 -1
  24. package/dist/server/device-center/hub-transaction-log.js +197 -0
  25. package/dist/server/device-center/hub.js +772 -354
  26. package/dist/server/device-center/integration-verification.js +113 -0
  27. package/dist/server/device-center/local-hub.js +6 -2
  28. package/dist/server/device-center/local-publication.js +423 -0
  29. package/dist/server/device-center/local-verification-job.js +97 -0
  30. package/dist/server/device-center/local-verification.js +274 -0
  31. package/dist/server/device-center/local.js +107 -12
  32. package/dist/server/device-center/main.js +4 -1
  33. package/dist/server/device-center/partition-log.js +62 -25
  34. package/dist/server/device-center/publication-journal.js +312 -0
  35. package/dist/server/device-center/publish-intent.js +379 -0
  36. package/dist/server/device-center/relay.js +134 -24
  37. package/dist/server/device-center/runtime.js +426 -42
  38. package/dist/server/device-center/store.js +225 -47
  39. package/dist/server/device-center/task-outcome.js +81 -0
  40. package/dist/server/device-center/task-recovery.js +603 -178
  41. package/dist/server/device-center/task-settlement.js +353 -0
  42. package/dist/server/device-center/task-workspace.js +443 -0
  43. package/dist/server/device-center/verification-limits.js +10 -0
  44. package/dist/server/device-center/work-contract.js +995 -0
  45. package/dist/server/dispatch-domain-handlers.js +15 -0
  46. package/dist/server/dsh/dsh-agent-service.js +9 -2
  47. package/dist/server/index.js +26 -1
  48. package/dist/server/patch-node-pty.js +3 -2
  49. package/dist/server/patch-remote-catalog.js +3 -2
  50. package/dist/server/preset-fields.js +17 -1
  51. package/dist/server/preset-share.js +1 -0
  52. package/dist/server/protocol-version.js +1 -1
  53. package/dist/server/quick-ask-settings.js +28 -0
  54. package/dist/server/quick-ask.js +164 -0
  55. package/dist/server/resolve-global-sdk.js +61 -11
  56. package/dist/server/scheduler-tasks.js +35 -8
  57. package/dist/server/session-list-scan.js +223 -0
  58. package/dist/server/session-open.js +93 -0
  59. package/dist/server/session-parser.js +4 -0
  60. package/dist/server/session-scan.js +90 -38
  61. package/dist/server/settings-service.js +9 -1
  62. package/dist/server/soft-cap.js +5 -0
  63. package/dist/server/transcript-prepare.js +73 -0
  64. package/dist/server/universal/drivers/claude-code.js +98 -34
  65. package/dist/server/universal/universal-session.js +4 -0
  66. package/dist/server/workspace-handle.js +428 -0
  67. package/docs/architecture-plugins.md +18 -5
  68. package/docs/device-center.md +30 -22
  69. package/package.json +3 -4
  70. package/plugin-sdk/README.md +16 -8
  71. package/plugin-sdk/client.d.ts +27 -0
  72. package/plugin-sdk/client.mjs +82 -0
  73. package/plugin-sdk/index.d.ts +10 -0
  74. package/plugin-sdk/index.mjs +4 -683
  75. package/plugin-sdk/package.json +15 -4
  76. package/plugin-sdk/testing.d.ts +10 -0
  77. package/plugin-sdk/testing.mjs +566 -0
  78. package/themes/flow-cristallo.css +168 -0
  79. package/themes/flow-ink.css +169 -0
  80. package/themes/flow-obsidian.css +169 -0
  81. package/themes/flow-zurich.css +169 -0
  82. package/web/dist/.build-assets.json +1 -1
  83. package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-BjNRIUIc.js} +1 -1
  84. package/web/dist/assets/{BgTasksModal-C0i3O1FT.js → BgTasksModal-C0zuU8FE.js} +1 -1
  85. package/web/dist/assets/{CanvasStudio-B8thymBN.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  86. package/web/dist/assets/{CanvasStudio-zSxyIx1R.js → CanvasStudio-VQFjmTGq.js} +3 -3
  87. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  88. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  89. package/web/dist/assets/{DeviceExecutionSettings-q5Ik8oXg.js → DeviceExecutionSettings-BLP1Su5G.js} +1 -1
  90. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  91. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  92. package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CQtstPGv.js} +1 -1
  93. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  94. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  95. package/web/dist/assets/{GlobalSearchModal-BWgU8yPd.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  96. package/web/dist/assets/{GlobalSearchModal-F7fNimKk.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  97. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  98. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  99. package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-ChTW8o1m.js} +1 -1
  100. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  101. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  102. package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-BX5rUuoI.js} +1 -1
  103. package/web/dist/assets/{ProviderOAuthControls-BGSBIKD7.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  104. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  105. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  106. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  107. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  108. package/web/dist/assets/{TerminalPanel-DDavKvFr.js → TerminalPanel-D4By_RVc.js} +2 -2
  109. package/web/dist/assets/{TerminalPanel-0CYvD72B.js → TerminalPanel-lZw8-i3j.js} +2 -2
  110. package/web/dist/assets/{TuiOverlayModal-BsA-QTvN.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  111. package/web/dist/assets/{TuiOverlayModal-DzoVQBuG.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  112. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  113. package/web/dist/assets/{canvas-client-CUnXlQYX.js → canvas-client-BY6ojmle.js} +1 -1
  114. package/web/dist/assets/{desktop-aAKpvKJV.js → desktop-CV6KKp9R.js} +1 -1
  115. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  116. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  117. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  118. package/web/dist/assets/{plugin-host-BRWib9DF.js → plugin-host-Dn8Dd6SC.js} +1 -1
  119. package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  120. package/web/dist/assets/{theme-D2l_mLNo.js → theme-D_bihpdN.js} +1 -1
  121. package/web/dist/index.html +11 -11
  122. package/web/dist/sw.js +1 -1
  123. package/dist/gh-comment-781.md +0 -5
  124. package/dist/server/device-center/local-page.js +0 -17
  125. package/dist/server/device-center/smoke-preview.js +0 -3
  126. package/dist/server/durable/durable-capabilities.js +0 -11
  127. package/dist/server/markers/builtins/services.js +0 -123
  128. package/dist/server/markers/builtins/todo.js +0 -189
  129. package/dist/server/markers-list-tool.js +0 -34
  130. package/dist/server/orchestrator.js +0 -109
  131. package/dist/server/patch-turn-end-boundary.js +0 -77
  132. package/dist/server/system-prompt-soul.js +0 -41
  133. package/dist/server/univer-service.js +0 -448
  134. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  135. package/dist/test-artifact.md +0 -9
  136. package/dist/test-preview-modal.md +0 -11
  137. package/dist/test-report.html +0 -20
  138. package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
  139. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
  140. package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
  141. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
  142. package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
  143. package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
  144. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
  145. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
  146. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
  147. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
  148. package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
  149. package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
  150. package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
  151. package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
  152. package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
  153. package/web/dist/assets/index-C6DwztqE.css +0 -1
  154. package/web/dist/assets/index-CuN802Sj.js +0 -93
  155. package/web/dist/assets/index-EH5Fw9fa.js +0 -93
@@ -15,7 +15,6 @@
15
15
  // wholesale (no union merge / no stale built-in leftovers).
16
16
  import "./patch-remote-catalog.js";
17
17
  import { applyQueueModesToSession } from "./queue-modes.js";
18
- import "./patch-turn-end-boundary.js";
19
18
  import { startTurnTiming, finishTurnTiming } from "./turn-timing.js";
20
19
  import { PendingQuestion } from "./pending-question.js";
21
20
  import { formatSubagentsCompletionNotice } from "./subagent-notify.js";
@@ -36,6 +35,9 @@ import { getAppVersion, getPkgRoot } from "./pkg-info.js";
36
35
  import { isBundledInUse, sdkCopies } from "./sdk-origin.js";
37
36
  import { hasActiveSubagentRun, hasPendingWaitSubscription, hasRunningBackgroundTask, shouldRetainActive, } from "./wait-subscription-scan.js";
38
37
  import { looksLikeChainCorruption, repairSessionFile } from "./compaction-markers.js";
38
+ import { prepareTranscriptForOpen } from "./transcript-prepare.js";
39
+ import { scanSessionListInfo } from "./session-list-scan.js";
40
+ import { openSessionManagerAsync } from "./session-open.js";
39
41
  import { calibrateSessionLeaf } from "./session-branch.js";
40
42
  import { startLoadTiming } from "./load-timing.js";
41
43
  import { mark as markCompactionState, finish as finishCompactionState, consumeInterrupted as consumeInterruptedCompaction, } from "./compaction-state.js";
@@ -52,7 +54,7 @@ import { SlashCommandsService, parseSlash } from "./slash-commands.js";
52
54
  import { ModelAdminService } from "./model-admin.js";
53
55
  import { FilesService, MACHINE_ROOT, desktopDirWire, workspacePath } from "./files-service.js";
54
56
  import { buildRemoteWorkspacePersona, createRemoteSdkOperations, formatCwdForPrompt, getGlobalRemoteSshService, isRemoteWorkspaceUri, RemoteSshService, resolveWorkspaceSessionDir, restoreWorkspaceUriFromSessionDir, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
55
- import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, defaultSubagentAutoWakeMaxTurns, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, isInternalExtension, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
57
+ import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, defaultSubagentAutoWakeMaxTurns, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, isInternalExtension, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, RECENT_PROJECTS_MAX, } from "./client-state.js";
56
58
  import { isTraditionalLocale, pick, resolveServerLang } from "./i18n.js";
57
59
  import { SubagentTemplatesStore, localizeTemplate, pickTemplatePrompt, } from "./subagent-templates.js";
58
60
  import { ApprovalRulesStore } from "./approval-rules.js";
@@ -281,10 +283,41 @@ export function cleanupOrphanedSessionDirs(agentDir, maxAgeMs = 24 * 3600_000) {
281
283
  }
282
284
  }
283
285
  let ephemeralCleanupScheduled = false;
286
+ /**
287
+ * 识别 SDK 在中止回合(未持久化助理消息)时误报的 turn_end 扩展伪错误(issue #411;earendil-works/pi#10149)。
288
+ * 纯函数,应用层静默丢弃,无需改写底层 SDK 源码或拦截文件系统。
289
+ */
290
+ export function isAbortedTurnBoundaryError(err) {
291
+ if (!err || typeof err !== "object")
292
+ return false;
293
+ const e = err;
294
+ if (e.extensionPath === "<boundary>" && e.event === "turn_end")
295
+ return true;
296
+ if (typeof e.error === "string" && e.error.includes("turn_end could not resolve the persisted assistant entry ID")) {
297
+ return true;
298
+ }
299
+ return false;
300
+ }
284
301
  export { processTreeKillPlan, resolveCwdTarget };
302
+ /** 会话列表展示字段上限(字符):左栏标题单行省略号显示,搜索弹窗副标题两行即止。 */
303
+ const LIST_TEXT_MAX = 300;
304
+ export function clipListText(text) {
305
+ if (text.length <= LIST_TEXT_MAX)
306
+ return text;
307
+ // 避免截在 UTF-16 代理对中间留下孤立高位代理
308
+ let end = LIST_TEXT_MAX;
309
+ const code = text.charCodeAt(end - 1);
310
+ if (code >= 0xd800 && code <= 0xdbff)
311
+ end -= 1;
312
+ return `${text.slice(0, end)}…`;
313
+ }
285
314
  export class ClientSession {
286
315
  static mcpProjects = null;
287
316
  clientId;
317
+ /** 残骸被新连接认领时更新 clientId,保持与 Daemon 映射和所有队列推送一致 */
318
+ updateClientId(newClientId) {
319
+ this.clientId = newClientId;
320
+ }
288
321
  /** Set by AgentService.attach: reflects the SERVICE-wide quiesce flag
289
322
  * (server draining — new work rejected). Default false for direct use. */
290
323
  isQuiesced = () => false;
@@ -2927,8 +2960,10 @@ export class ClientSession {
2927
2960
  static async create(clientId, cwd, stateStore, opts) {
2928
2961
  const botExecution = getBotExecution(clientId);
2929
2962
  botExecution?.assertActive();
2930
- if (botExecution)
2931
- cwd = botExecution.bot.cwd;
2963
+ if (botExecution) {
2964
+ cwd = botExecution.executionCwd;
2965
+ await botExecution.assertWorkspace(cwd);
2966
+ }
2932
2967
  const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
2933
2968
  const cs = new ClientSession(clientId, cwd, agentDir, stateStore);
2934
2969
  cs.botExecution = botExecution;
@@ -3035,7 +3070,7 @@ export class ClientSession {
3035
3070
  const targetPath = resolve(p);
3036
3071
  if (!existsSync(targetPath))
3037
3072
  continue;
3038
- cs.repairTranscriptFileBeforeOpen(targetPath);
3073
+ await cs.repairTranscriptFileBeforeOpen(targetPath);
3039
3074
  const sm = SessionManager.open(targetPath);
3040
3075
  const convId = cs.nextConversationId();
3041
3076
  const terms = cs.makeTerminalManager(convId, cwd);
@@ -3085,7 +3120,8 @@ export class ClientSession {
3085
3120
  */
3086
3121
  makeRuntimeFactory(terminals, apply, ownerId, initialModel, targetPreset, noSpawnTools) {
3087
3122
  return async ({ cwd: effectiveCwd, sessionManager }) => {
3088
- this.botExecution?.assertActive();
3123
+ if (this.botExecution)
3124
+ await this.botExecution.assertWorkspace(effectiveCwd);
3089
3125
  const botEntry = sessionManager
3090
3126
  .getEntries()
3091
3127
  .find((entry) => entry.type === "custom" && entry.customType === "device-bot-execution");
@@ -3101,7 +3137,8 @@ export class ClientSession {
3101
3137
  botId: this.botExecution.bot.id,
3102
3138
  revision: this.botExecution.bot.revision,
3103
3139
  });
3104
- if (this.botExecution && resolve(effectiveCwd) !== resolve(this.botExecution.bot.cwd))
3140
+ const expectedBotCwd = this.botExecution?.executionCwd ?? this.botExecution?.bot.cwd;
3141
+ if (this.botExecution && expectedBotCwd && resolve(effectiveCwd) !== resolve(expectedBotCwd))
3105
3142
  throw new Error("Bot cwd is fixed");
3106
3143
  const sandboxIdentity = this.sandboxes.getExecutionIdentity(effectiveCwd);
3107
3144
  const releaseMcp = sandboxIdentity || this.botExecution ? undefined : ClientSession.mcpProjects?.retain(effectiveCwd);
@@ -3114,6 +3151,7 @@ export class ClientSession {
3114
3151
  allowedServers: this.botExecution.bot.mcpServers,
3115
3152
  });
3116
3153
  await this.botMcpBridge.load();
3154
+ await this.botExecution.assertWorkspace(effectiveCwd);
3117
3155
  }
3118
3156
  }
3119
3157
  else if (!sandboxIdentity)
@@ -3265,9 +3303,10 @@ export class ClientSession {
3265
3303
  name: "pi-webui-sandbox-final-gate",
3266
3304
  hidden: true,
3267
3305
  factory: (pi) => {
3268
- pi.on("tool_call", (event) => {
3306
+ pi.on("tool_call", async (event) => {
3269
3307
  if (this.botExecution) {
3270
3308
  try {
3309
+ await this.botExecution.assertWorkspace(effectiveCwd);
3271
3310
  const auth = this.botToolAuthorization(event.toolName, effectiveCwd, event.input);
3272
3311
  if (!auth.allowed)
3273
3312
  return { block: true, reason: auth.reason ?? "Tool is not authorized for this Bot" };
@@ -3454,6 +3493,7 @@ export class ClientSession {
3454
3493
  }
3455
3494
  }
3456
3495
  }
3496
+ await this.botExecution?.assertWorkspace(effectiveCwd);
3457
3497
  const created = await createAgentSessionFromServices({
3458
3498
  services,
3459
3499
  sessionManager,
@@ -3731,6 +3771,13 @@ export class ClientSession {
3731
3771
  });
3732
3772
  // 桥接工具归属锚点:SDK 会话对象在本 runtime 生命周期内稳定,过户只搬对话
3733
3773
  // 不改它(见 ClientSession.findConversationHome)。
3774
+ try {
3775
+ await this.botExecution?.assertWorkspace(effectiveCwd);
3776
+ }
3777
+ catch (error) {
3778
+ created.session.dispose();
3779
+ throw error;
3780
+ }
3734
3781
  bridgeAnchor.session = created.session;
3735
3782
  this.appliedPluginToolNames.set(created.session, new Set((this.pluginToolsProvider?.(effectiveCwd) ?? []).map((tool) => tool.name)));
3736
3783
  const evidenceHooksReady = installEvidenceToolHooks(created.session);
@@ -4218,6 +4265,8 @@ export class ClientSession {
4218
4265
  makeExtensionErrorReporter(prefix) {
4219
4266
  const seen = new Set();
4220
4267
  return (err) => {
4268
+ if (isAbortedTurnBoundaryError(err))
4269
+ return;
4221
4270
  const message = err?.error ?? String(err);
4222
4271
  const where = [err?.extensionPath, err?.event].filter(Boolean).join(" · ");
4223
4272
  console.error(`[extension] ${prefix?.text ?? "当前对话"}${where ? ` (${where})` : ""}: ${message}${err?.stack ? `\n${err.stack}` : ""}`);
@@ -4518,7 +4567,7 @@ export class ClientSession {
4518
4567
  * 复用 refreshSessions/searchSessions 共用的 loadSessionInfos 缓存(3s TTL,不扫两遍盘)。 */
4519
4568
  async listHistoryForPlugins(limit = 50) {
4520
4569
  try {
4521
- const infos = await this.loadSessionInfos();
4570
+ const infos = await this.loadSessionInfos(undefined, { listOnly: limit <= 200 });
4522
4571
  return infos.slice(0, Math.max(0, limit)).map((s) => ({
4523
4572
  id: s.path,
4524
4573
  title: (s.name?.trim() || s.firstMessage.trim() || basename(s.path)).slice(0, 60),
@@ -5506,40 +5555,7 @@ export class ClientSession {
5506
5555
  // 一次扫描同时收齐「当前转写里的全部缓存键」(live 集合,供
5507
5556
  // pruneMessageCache 精确回收死条目)与各自的序列化结果。
5508
5557
  const live = new Set();
5509
- let agentMessages = conv.session.agent.state.messages;
5510
- // issue #448: 多次压缩后 SDK state.messages 只保留最后一次压缩卡片。
5511
- // 从当前分支祖先链中提取前序未展示的历史 compaction 并正序置前,
5512
- // 使前端能逐段回溯展开历史折叠内容。
5513
- if (conv.session.sessionManager?.getBranch) {
5514
- try {
5515
- const branch = conv.session.sessionManager.getBranch();
5516
- const compEntries = branch.filter((e) => e.type === "compaction");
5517
- if (compEntries.length > 1) {
5518
- const existingCompKeys = new Set(agentMessages
5519
- .filter((m) => m.role === "compactionSummary")
5520
- .map((m) => `${m.timestamp}:${m.summary ?? ""}`));
5521
- const missingComps = [];
5522
- for (const ce of compEntries) {
5523
- const ts = ce.timestamp ? new Date(ce.timestamp).getTime() : 0;
5524
- const key = `${ts}:${ce.summary ?? ""}`;
5525
- if (!existingCompKeys.has(key)) {
5526
- missingComps.push({
5527
- role: "compactionSummary",
5528
- summary: ce.summary ?? "",
5529
- tokensBefore: ce.tokensBefore,
5530
- timestamp: ts,
5531
- });
5532
- }
5533
- }
5534
- if (missingComps.length > 0) {
5535
- agentMessages = [...missingComps, ...agentMessages];
5536
- }
5537
- }
5538
- }
5539
- catch {
5540
- // 获取分支异常不影响当前渲染
5541
- }
5542
- }
5558
+ const agentMessages = this.withHistoricalCompactions(conv.session.agent.state.messages, conv.session.sessionManager);
5543
5559
  let rawMessages = agentMessages
5544
5560
  .map((m) => {
5545
5561
  const k = this.uiMessageKey(conv, m);
@@ -5561,6 +5577,44 @@ export class ClientSession {
5561
5577
  conv.lastMessagesArray = rawMessages;
5562
5578
  return messages;
5563
5579
  }
5580
+ /**
5581
+ * issue #448: 多次压缩后 SDK state.messages 只保留最后一次压缩卡片。
5582
+ * 从当前分支祖先链中提取前序未展示的历史 compaction 并正序置前,
5583
+ * 使前端能逐段回溯展开历史折叠内容。(messagesOf 与打开历史时的预览共用,
5584
+ * 两边得到同一份消息序列,预览消息 id 才能与首个快照一致。)
5585
+ */
5586
+ withHistoricalCompactions(agentMessages, sessionManager) {
5587
+ if (!sessionManager?.getBranch)
5588
+ return agentMessages;
5589
+ try {
5590
+ const branch = sessionManager.getBranch();
5591
+ const compEntries = branch.filter((e) => e.type === "compaction");
5592
+ if (compEntries.length > 1) {
5593
+ const existingCompKeys = new Set(agentMessages
5594
+ .filter((m) => m.role === "compactionSummary")
5595
+ .map((m) => `${m.timestamp}:${m.summary ?? ""}`));
5596
+ const missingComps = [];
5597
+ for (const ce of compEntries) {
5598
+ const ts = ce.timestamp ? new Date(ce.timestamp).getTime() : 0;
5599
+ const key = `${ts}:${ce.summary ?? ""}`;
5600
+ if (!existingCompKeys.has(key)) {
5601
+ missingComps.push({
5602
+ role: "compactionSummary",
5603
+ summary: ce.summary ?? "",
5604
+ tokensBefore: ce.tokensBefore,
5605
+ timestamp: ts,
5606
+ });
5607
+ }
5608
+ }
5609
+ if (missingComps.length > 0)
5610
+ return [...missingComps, ...agentMessages];
5611
+ }
5612
+ }
5613
+ catch {
5614
+ // 获取分支异常不影响当前渲染
5615
+ }
5616
+ return agentMessages;
5617
+ }
5564
5618
  /** 序列化缓存上界:**先按「还在转写里」淘汰,绝不为省内存淘汰仍在转写里的条目**。
5565
5619
  *
5566
5620
  * 为什么不能 FIFO 淘汰(issue #259 实测的机理):缓存上限一旦低于转写长度,
@@ -5845,7 +5899,7 @@ export class ClientSession {
5845
5899
  this.pendingQuestions.set(request.id, request);
5846
5900
  request.onSettled = () => {
5847
5901
  this.pendingQuestions.delete(request.id);
5848
- this.emit({ type: "question_retracted", id: request.id });
5902
+ this.emit({ type: "question_retracted", id: request.id, owner: this.clientId });
5849
5903
  this.questionsChanged();
5850
5904
  const source = this.convs.get(request.conversationId);
5851
5905
  if (source?.notifyOnDone === "manual")
@@ -8090,7 +8144,11 @@ export class ClientSession {
8090
8144
  const currentTokens = this.getEffectiveContextTokens(conv);
8091
8145
  if (currentTokens < cap)
8092
8146
  return false;
8093
- await session.compact();
8147
+ // 自动压缩也可携带自定义指令:扩展可用它接管摘要生成方式
8148
+ // (例如传暗号让 session_before_compact 钩子返回自建摘要)。
8149
+ // 手动 /compact 与 AI 的 compact_context 各自传自己的指令,不受影响。
8150
+ const instructions = this.settingsSvc.current.autoCompactionInstructions?.trim() || undefined;
8151
+ await session.compact(instructions);
8094
8152
  return true;
8095
8153
  }
8096
8154
  catch (err) {
@@ -9436,6 +9494,7 @@ export class ClientSession {
9436
9494
  def = {
9437
9495
  ...def,
9438
9496
  execute: async (...args) => {
9497
+ await this.botExecution?.assertWorkspace(cwdOverride ?? this.cwd);
9439
9498
  if (!this.botToolAllowed(def.name, cwdOverride, args[1]))
9440
9499
  throw new Error("Tool is not authorized for this Bot");
9441
9500
  return execute(...args);
@@ -9501,6 +9560,7 @@ export class ClientSession {
9501
9560
  return {
9502
9561
  ...def,
9503
9562
  execute: async (...args) => {
9563
+ await this.botExecution?.assertWorkspace(cwd ?? this.cwd);
9504
9564
  const current = this.executionMcpBridge(cwd ?? this.cwd)?.getTools() ?? [];
9505
9565
  if (!current.includes(tool) || !this.botToolAllowed(tool.name, cwd, args[1]))
9506
9566
  throw new Error("Bot MCP tool authorization expired");
@@ -9889,6 +9949,8 @@ export class ClientSession {
9889
9949
  if (this.botExecution && text.trimStart().startsWith("/"))
9890
9950
  throw new Error("Bot slash commands are disabled");
9891
9951
  const conv = targetConversation ?? this.conv;
9952
+ if (this.botExecution)
9953
+ await this.botExecution.assertWorkspace(conv.cwd);
9892
9954
  this.assertSubagentWorktreeAdmission(conv);
9893
9955
  if (!this.botExecution &&
9894
9956
  conv.session.sessionManager
@@ -10295,6 +10357,8 @@ export class ClientSession {
10295
10357
  // 立即切换会话,若提前置位会被 displaceActive 误判为有消息投递而报错通知。
10296
10358
  startTurnTiming(conv);
10297
10359
  conv.promptInFlight = true;
10360
+ // 用户开始在这条对话里发言:不再是「只是查看」的历史对话,达上限时不得自动移出。
10361
+ conv.viewOnly = false;
10298
10362
  this.flushSnapshot();
10299
10363
  // Attach files as independent nextTurn context messages (asides) so the
10300
10364
  // user message stays clean; they render as separate attachment cards.
@@ -10473,6 +10537,7 @@ export class ClientSession {
10473
10537
  // switches away. (Also bumps the per-project "most recently active"
10474
10538
  // order used by set_cwd.)
10475
10539
  conv.promptedSinceActive = true;
10540
+ conv.viewOnly = false;
10476
10541
  conv.lastActiveAt = Date.now();
10477
10542
  // Fresh run — restart the stall watchdog window.
10478
10543
  conv.lastSdkEventAt = Date.now();
@@ -10600,6 +10665,7 @@ export class ClientSession {
10600
10665
  if (!current())
10601
10666
  return;
10602
10667
  conv.promptedSinceActive = true;
10668
+ conv.viewOnly = false;
10603
10669
  conv.lastActiveAt = Date.now();
10604
10670
  conv.lastSdkEventAt = Date.now();
10605
10671
  conv.stallNoticed = false;
@@ -11180,6 +11246,8 @@ export class ClientSession {
11180
11246
  // lists and don't consume this project's slots. Subagents don't count
11181
11247
  // (inMemory 后台任务,不占位)。临时会话也不占名额。
11182
11248
  if (!ephemeral) {
11249
+ // 达上限时先按 LRU 收起只查看过的历史对话(不计当前对话的释放:沿用原口径,保守)。
11250
+ this.makeRoomForConversation(this.cwd, 1);
11183
11251
  const openInProject = [...this.convs.values()].filter((c) => c.cwd === this.cwd && !c.isSubagent && !c.isEphemeral).length;
11184
11252
  const maxOpenConversations = getMaxOpenConversations();
11185
11253
  if (openInProject >= maxOpenConversations) {
@@ -11455,25 +11523,21 @@ export class ClientSession {
11455
11523
  * 返回 null = 文件健康或无需处理;返回 repair = 修过,调用方弹提示。
11456
11524
  * #280:顺带修悬空 toolCall(强制重置/崩溃残留的有调用无结果),修过同样弹提示。
11457
11525
  */
11458
- repairTranscriptFileBeforeOpen(filePath) {
11459
- let repair = null;
11526
+ async repairTranscriptFileBeforeOpen(filePath) {
11527
+ let prepared;
11460
11528
  try {
11461
- repair = repairSessionFile(filePath);
11529
+ // 链修复与悬空调用修复共用一次异步读盘;两项健康指纹都命中时不读盘(transcript-prepare.ts)。
11530
+ prepared = await prepareTranscriptForOpen(filePath, this.danglingCauseFor(filePath));
11462
11531
  }
11463
11532
  catch {
11464
11533
  return null;
11465
11534
  }
11466
- if (!repair?.changed) {
11535
+ const repair = prepared.repair;
11536
+ if (!repair)
11537
+ return null;
11538
+ if (!repair.changed) {
11467
11539
  // #280:压缩链健康时仍要查悬空 toolCall(崩溃/强制重置残留)。
11468
- let healed = 0;
11469
- try {
11470
- const n = healDanglingToolCallFile(filePath, this.danglingCauseFor(filePath));
11471
- if (n > 0)
11472
- healed = n;
11473
- }
11474
- catch {
11475
- // best-effort
11476
- }
11540
+ const healed = prepared.healed > 0 ? prepared.healed : 0;
11477
11541
  if (healed <= 0)
11478
11542
  return null;
11479
11543
  this.emit({
@@ -11506,6 +11570,9 @@ export class ClientSession {
11506
11570
  }
11507
11571
  }
11508
11572
  const totalMessages = msgEntries.length;
11573
+ const seeded = this.previewWithSnapshotIds(manager, maxPreview);
11574
+ if (seeded)
11575
+ return { totalMessages, previewMessages: seeded.previewMessages, idSeed: seeded.idSeed };
11509
11576
  const tail = msgEntries.slice(-maxPreview);
11510
11577
  const startOffset = totalMessages - tail.length;
11511
11578
  const previewMessages = [];
@@ -11520,6 +11587,60 @@ export class ClientSession {
11520
11587
  return { totalMessages: 0, previewMessages: [] };
11521
11588
  }
11522
11589
  }
11590
+ /**
11591
+ * 用首个快照将会使用的同一套 id 规则生成预览(C4:预览→快照不再整列重挂载)。
11592
+ *
11593
+ * 新建对话的 agent.state.messages 由 SDK 以 `sessionManager.buildSessionContext().messages`
11594
+ * 初始化(sdk.js),messagesOf 再经 withHistoricalCompactions 补历史压缩卡;这里对同一序列
11595
+ * 走同一个 uiMessageKey(内容键 → 序号 n),只序列化尾部若干条。用户消息的 seq 是「同时间戳
11596
+ * 用户消息的 1-based 序」:首个快照里尾部条目命中缓存不再计数、更早条目按序 miss 计数,
11597
+ * 所以 userSeqByTs 种子留空、尾部按全序列精确计算,两者结果一致。
11598
+ * 种子随后交给 seedConversationIds 写入新对话:msgIds 按内容键映射,即便扩展在 bind 时
11599
+ * 追加消息,已有键的序号也不变。返回 null = 管理器不支持(回退旧预览,id 不保证一致)。
11600
+ */
11601
+ previewWithSnapshotIds(manager, maxPreview) {
11602
+ if (typeof manager.buildSessionContext !== "function")
11603
+ return null;
11604
+ const all = this.withHistoricalCompactions(manager.buildSessionContext().messages, manager);
11605
+ const ids = { msgIds: new Map(), nextMsgId: 1 };
11606
+ const keys = all.map((m) => this.uiMessageKey(ids, m));
11607
+ // 从尾部找出最后 maxPreview 条会渲染的(非 system)消息
11608
+ let start = all.length;
11609
+ for (let shown = 0; start > 0 && shown < maxPreview;) {
11610
+ start--;
11611
+ if (all[start].role !== "system")
11612
+ shown++;
11613
+ }
11614
+ const userSeen = new Map();
11615
+ const uiMessageCache = new Map();
11616
+ const previewMessages = [];
11617
+ for (let i = 0; i < all.length; i++) {
11618
+ const m = all[i];
11619
+ let seq = keys[i].n;
11620
+ if (m.role === "user") {
11621
+ const ts = m.timestamp ?? 0;
11622
+ seq = (userSeen.get(ts) ?? 0) + 1;
11623
+ userSeen.set(ts, seq);
11624
+ }
11625
+ if (i < start)
11626
+ continue;
11627
+ const ui = serializeMessage(m, seq);
11628
+ if (!ui)
11629
+ continue;
11630
+ uiMessageCache.set(keys[i].cacheKey, ui);
11631
+ previewMessages.push(ui);
11632
+ }
11633
+ return { previewMessages, idSeed: { msgIds: ids.msgIds, nextMsgId: ids.nextMsgId, uiMessageCache } };
11634
+ }
11635
+ /** 把预览阶段的 id 状态交给刚建好的对话(仅当对话尚未产生任何 id 时)。 */
11636
+ seedConversationIds(conv, seed) {
11637
+ if (!seed || conv.msgIds.size > 0 || conv.uiMessageCache.size > 0)
11638
+ return;
11639
+ conv.msgIds = seed.msgIds;
11640
+ conv.nextMsgId = seed.nextMsgId;
11641
+ for (const [k, v] of seed.uiMessageCache)
11642
+ conv.uiMessageCache.set(k, v);
11643
+ }
11523
11644
  /**
11524
11645
  * #235:manager+runtime 一起建,链损坏报错则修最近文件后重试一次。
11525
11646
  * SessionManager.open 本身不走 parent 链(真正死循环的是 runtime 初始化里的
@@ -11564,6 +11685,26 @@ export class ClientSession {
11564
11685
  return false;
11565
11686
  }
11566
11687
  }
11688
+ /** 打开历史会话因名额不足失败:结束切换进度条并给出移出指引。 */
11689
+ emitMaxOpenConversationsReached(targetPath) {
11690
+ const maxOpenConversations = getMaxOpenConversations();
11691
+ this.emit({
11692
+ type: "transition_progress",
11693
+ kind: "session",
11694
+ target: targetPath,
11695
+ phase: "error",
11696
+ progress: 100,
11697
+ text: `当前项目运行的对话已达上限(${maxOpenConversations} 个)`,
11698
+ textEn: `Max open conversations (${maxOpenConversations}) reached`,
11699
+ });
11700
+ const notice = this.maxOpenConversationsNotice(maxOpenConversations);
11701
+ this.emit({
11702
+ type: "notice",
11703
+ level: "warning",
11704
+ text: notice.text,
11705
+ textEn: notice.textEn,
11706
+ });
11707
+ }
11567
11708
  maxOpenConversationsNotice(limit) {
11568
11709
  const retain = Boolean(this.settingsSvc?.current.retainFinishedConversations);
11569
11710
  if (retain) {
@@ -11609,12 +11750,33 @@ export class ClientSession {
11609
11750
  // Also retain a parent while any live first-party subagent conversation
11610
11751
  // points at it: dropping an idle in-memory parent orphans the child row
11611
11752
  // (the child vanishes from Running Chats with no result available).
11612
- const hasLiveChild = [...new Set([this, ...(this.allSubagentSessions?.() ?? [])])].some((owner) => [...owner.convs.values()].some((child) => owner.parentExecution(child)?.conv === conv));
11753
+ const retained = this.isRetainedOnDisplace(conv);
11754
+ if (retained) {
11755
+ conv.listed = true;
11756
+ if (conv.promptInFlight && !conv.session.isStreaming) {
11757
+ this.emit({
11758
+ type: "notice",
11759
+ level: "info",
11760
+ text: `「${conv.title}」的消息正在投递,已为你保留该对话`,
11761
+ textEn: `"${conv.title}" is still sending your message — kept in the running list`,
11762
+ });
11763
+ }
11764
+ return null;
11765
+ }
11766
+ return conv;
11767
+ }
11768
+ /** 有存活的一方子代理对话指向它(丢掉父对话会让子代理行成为孤儿)。 */
11769
+ hasLiveSubagentChild(conv) {
11770
+ return [...new Set([this, ...(this.allSubagentSessions?.() ?? [])])].some((owner) => [...owner.convs.values()].some((child) => owner.parentExecution(child)?.conv === conv));
11771
+ }
11772
+ /** displaceActive 的保留判定(无副作用,可用于预测切走时是否会释放当前对话)。 */
11773
+ isRetainedOnDisplace(conv) {
11774
+ const hasLiveChild = this.hasLiveSubagentChild(conv);
11613
11775
  // Ephemeral transcripts have no history fallback: once started, only an
11614
11776
  // explicit close may discard them, even after revisiting without a prompt.
11615
11777
  const retainFinished = (Boolean(conv.isEphemeral) || Boolean(this.settingsSvc?.current.retainFinishedConversations)) &&
11616
11778
  this.isConversationStarted(conv);
11617
- const retained = hasLiveChild ||
11779
+ return (hasLiveChild ||
11618
11780
  retainFinished ||
11619
11781
  shouldRetainActive({
11620
11782
  reviewing: conv.goal.reviewing,
@@ -11632,20 +11794,99 @@ export class ClientSession {
11632
11794
  hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: conv.session.sessionFile }),
11633
11795
  hasPendingWake: () => hasPendingWaitSubscription({ sessionId: conv.session.sessionFile }),
11634
11796
  hasRunningBackgroundTask: () => hasRunningBackgroundTask({ cwd: conv.cwd, sessionFile: conv.session.sessionFile }),
11797
+ }));
11798
+ }
11799
+ /** 现在切走的话,当前对话会不会被 displaceActive 释放(无副作用的预测)。 */
11800
+ wouldDisplaceActive() {
11801
+ if (this.convs.size === 0)
11802
+ return false;
11803
+ const conv = this.conv;
11804
+ if (conv.transferring || conv.isSubagent)
11805
+ return false;
11806
+ return !this.isRetainedOnDisplace(conv);
11807
+ }
11808
+ /** 占项目运行对话名额的对话数(子代理、临时对话不占位;含创建中的预留)。 */
11809
+ countProjectSlots(cwd) {
11810
+ let open = 0;
11811
+ for (const c of this.convs.values())
11812
+ if (c.cwd === cwd && !c.isSubagent && !c.isEphemeral)
11813
+ open++;
11814
+ return open + (this.creatingConversations.get(cwd) ?? 0);
11815
+ }
11816
+ /**
11817
+ * 可自动移出的「只查看过」历史对话:从历史打开后从未发言、不是当前对话、未钉住、
11818
+ * 不在过户中、无流式/压缩/投递中、无用户终端、无审查/向导、无后台 run/唤醒订阅/后台任务、
11819
+ * 无存活子代理。移出只释放内存中的 runtime——转录早已在磁盘,可从历史列表重新打开。
11820
+ */
11821
+ isEvictableViewedConversation(c) {
11822
+ if (!c.viewOnly || c.id === this.activeId || c.pinned || c.transferring)
11823
+ return false;
11824
+ if (c.isSubagent || c.isEphemeral || c.promptInFlight)
11825
+ return false;
11826
+ try {
11827
+ if (c.session.isStreaming || c.session.isCompacting)
11828
+ return false;
11829
+ }
11830
+ catch {
11831
+ return false;
11832
+ }
11833
+ if (c.terminals.countBlockingLive() > 0)
11834
+ return false;
11835
+ if (this.hasLiveSubagentChild(c))
11836
+ return false;
11837
+ return !shouldRetainActive({
11838
+ reviewing: c.goal.reviewing,
11839
+ wizardRunning: c.wizardRunning,
11840
+ streaming: false,
11841
+ openTerminals: 0,
11842
+ listed: false,
11843
+ promptedSinceActive: false,
11844
+ promptInFlight: false,
11845
+ pinned: false,
11846
+ hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: c.session.sessionFile }),
11847
+ hasPendingWake: () => hasPendingWaitSubscription({ sessionId: c.session.sessionFile }),
11848
+ hasRunningBackgroundTask: () => hasRunningBackgroundTask({ cwd: c.cwd, sessionFile: c.session.sessionFile }),
11849
+ });
11850
+ }
11851
+ /**
11852
+ * 为 cwd 腾出名额,使「已占用 + needed」不超过上限:按 lastActiveAt 从旧到新移出只查看过的
11853
+ * 历史对话(LRU)。`activeWillBeFreed`:调用方随后的切换会释放当前对话(它也占本项目一个名额)。
11854
+ * 返回是否腾出成功;成功时发一条提示,告知哪些对话被收起。
11855
+ */
11856
+ makeRoomForConversation(cwd, needed, activeWillBeFreed = false) {
11857
+ const max = getMaxOpenConversations();
11858
+ if (this.countProjectSlots(cwd) + needed <= max)
11859
+ return true;
11860
+ // 只有确实超额时才评估(可能涉及磁盘探测的)当前对话释放预测
11861
+ const active = this.convs.size > 0 ? this.conv : null;
11862
+ const freed = typeof activeWillBeFreed === "function" ? activeWillBeFreed() : activeWillBeFreed;
11863
+ const activeCredit = freed && active && active.cwd === cwd && !active.isSubagent && !active.isEphemeral ? 1 : 0;
11864
+ const over = () => this.countProjectSlots(cwd) + needed - activeCredit > max;
11865
+ if (!over())
11866
+ return true;
11867
+ const candidates = [...this.convs.values()]
11868
+ .filter((c) => c.cwd === cwd)
11869
+ .sort((a, b) => a.lastActiveAt - b.lastActiveAt);
11870
+ const evicted = [];
11871
+ for (const c of candidates) {
11872
+ if (!over())
11873
+ break;
11874
+ if (!this.isEvictableViewedConversation(c))
11875
+ continue;
11876
+ evicted.push(c.title || basename(c.session.sessionFile ?? "") || c.id);
11877
+ this.removeConversation(c.id);
11878
+ }
11879
+ if (evicted.length > 0) {
11880
+ const names = evicted.map((t) => `「${t}」`).join("、");
11881
+ this.emit({
11882
+ type: "notice",
11883
+ level: "info",
11884
+ text: `运行的对话已达上限(${max} 个),已自动收起较早仅查看过的对话 ${names},可在历史对话中重新打开`,
11885
+ textEn: `Running chats reached the limit (${max}); closed ${evicted.length} earlier view-only chat(s) to make room. Reopen them from history anytime.`,
11635
11886
  });
11636
- if (retained) {
11637
- conv.listed = true;
11638
- if (conv.promptInFlight && !conv.session.isStreaming) {
11639
- this.emit({
11640
- type: "notice",
11641
- level: "info",
11642
- text: `「${conv.title}」的消息正在投递,已为你保留该对话`,
11643
- textEn: `"${conv.title}" is still sending your message — kept in the running list`,
11644
- });
11645
- }
11646
- return null;
11887
+ this.emitConversations();
11647
11888
  }
11648
- return conv;
11889
+ return !over();
11649
11890
  }
11650
11891
  /** Remove a conversation from the running list and free its runtime. The
11651
11892
  * session stays persisted on disk, so it remains recoverable from the
@@ -12042,6 +12283,7 @@ export class ClientSession {
12042
12283
  }
12043
12284
  // Remember the new workspace (restore target + recent-project entry).
12044
12285
  this.stateStore.remember(this.clientId, abs);
12286
+ this.invalidateProjectsCache();
12045
12287
  void this.pushProjects();
12046
12288
  this.refreshSessionsOnSwitch();
12047
12289
  void this.listFiles(undefined);
@@ -12176,6 +12418,29 @@ export class ClientSession {
12176
12418
  * workspace stays visible; clicking one switches both the conversation and
12177
12419
  * its project (see switchConversation). The client groups the list by cwd.
12178
12420
  * 推什么见 shownInRunningList(listed + 当前对话有内容时)。 */
12421
+ /** 运行列表行的会话文件 mtime 短时缓存:emitConversations 有约 40 个调用点、
12422
+ * 流式期间频繁触发,原先每次对每条对话做 existsSync + statSync 两次同步系统调用。 */
12423
+ static convFileMtimeCache = new Map();
12424
+ static CONV_FILE_MTIME_TTL = 2_000;
12425
+ /** 语义同原实现:文件不存在 → undefined;列表元信息缓存里有 → 用它的 mtime;否则 stat。 */
12426
+ static conversationFileMtime(f) {
12427
+ const now = Date.now();
12428
+ const hit = ClientSession.convFileMtimeCache.get(f);
12429
+ if (hit && now - hit.at < ClientSession.CONV_FILE_MTIME_TTL)
12430
+ return hit.mtime;
12431
+ let mtime;
12432
+ try {
12433
+ const statMtime = statSync(f).mtimeMs; // 一次 stat 同时完成存在性判断
12434
+ mtime = ClientSession.sessionFileCacheLookup(f)?.mtime ?? statMtime;
12435
+ }
12436
+ catch {
12437
+ mtime = undefined;
12438
+ }
12439
+ if (ClientSession.convFileMtimeCache.size >= 1024)
12440
+ ClientSession.convFileMtimeCache.clear();
12441
+ ClientSession.convFileMtimeCache.set(f, { at: now, mtime });
12442
+ return mtime;
12443
+ }
12179
12444
  emitConversations() {
12180
12445
  const conversations = [];
12181
12446
  // Active parents are normally absent from Running. Keep them visible while
@@ -12211,9 +12476,11 @@ export class ClientSession {
12211
12476
  try {
12212
12477
  const sid = conv.session.sessionId;
12213
12478
  const f = conv.session.sessionFile;
12479
+ const modified = f ? ClientSession.conversationFileMtime(f) : undefined;
12214
12480
  return {
12215
12481
  ...(sid ? { sessionId: sid } : {}),
12216
12482
  ...(f ? { sessionFile: f } : {}),
12483
+ ...(modified ? { modified } : {}),
12217
12484
  };
12218
12485
  }
12219
12486
  catch {
@@ -12299,7 +12566,8 @@ export class ClientSession {
12299
12566
  * 一致),变化的条目由调用方重新解析后经 store 覆盖(也落到最新端)。
12300
12567
  */
12301
12568
  static sessionFileCache = new Map();
12302
- static SESSION_FILE_CACHE_MAX = 512;
12569
+ // 2048:列表模式每项目约 260 个热条目,512 只够两三个项目,来回展开多个项目时会互相挤出、反复全文重解析。
12570
+ static SESSION_FILE_CACHE_MAX = 2048;
12303
12571
  /** sessionFileCache LRU 读取:命中即重插到最新端(续期),未命中返回 undefined。 */
12304
12572
  static sessionFileCacheLookup(key) {
12305
12573
  const entry = ClientSession.sessionFileCache.get(key);
@@ -12321,18 +12589,44 @@ export class ClientSession {
12321
12589
  }
12322
12590
  }
12323
12591
  /** 会话列表缓存(按 cwdKey 隔离,30s TTL)。 */
12592
+ /** complete=false:列表模式只解析了 mtime 最新的一部分文件(见 SESSION_LIST_PARSE_LIMIT),
12593
+ * 搜索 / 按 id 定位等需要全集的调用不能复用它。 */
12324
12594
  static sessionInfosCache = new Map();
12325
12595
  static sessionInfosInFlight = new Map();
12326
12596
  static SESSION_INFO_CACHE_TTL = 30_000;
12327
- async loadSessionInfos(forCwd) {
12597
+ /** 左栏列表展示的条数之外多解析一些,给 fork 父会话过滤留余量。 */
12598
+ static SESSION_LIST_PARSE_EXTRA = 60;
12599
+ /** 默认列表条数(buildSessionSummaries);B5 起客户端可按页请求更多。 */
12600
+ static SESSION_LIST_DEFAULT = 200;
12601
+ static SESSION_LIST_MAX = 5000;
12602
+ /** 兼容既有测试/调用:默认列表的解析上限(= 200 + 余量)。 */
12603
+ static SESSION_LIST_PARSE_LIMIT = ClientSession.SESSION_LIST_DEFAULT + ClientSession.SESSION_LIST_PARSE_EXTRA;
12604
+ /**
12605
+ * @param opts.listOnly 左栏列表用:按 mtime 从新到旧解析,凑够所需条数的本项目会话即停,
12606
+ * 不再对项目里成百上千个旧转录逐字节流式扫描(冷启动列表耗时从 O(项目全部字节) 降到 O(最新 N 个文件))。
12607
+ * 缓存命中的文件不计解析成本,照常纳入。
12608
+ * @param opts.listLimit 列表模式下需要的条数(缺省 200,左栏「显示更多」翻页时加大)。
12609
+ */
12610
+ async loadSessionInfos(forCwd, opts) {
12328
12611
  const targetCwd = forCwd ?? this.cwd;
12612
+ const listOnly = opts?.listOnly === true;
12613
+ const listLimit = Math.max(ClientSession.SESSION_LIST_DEFAULT, opts?.listLimit ?? ClientSession.SESSION_LIST_DEFAULT);
12614
+ const parseNeed = listOnly
12615
+ ? ClientSession.SESSION_LIST_PARSE_LIMIT + (listLimit - ClientSession.SESSION_LIST_DEFAULT)
12616
+ : Number.POSITIVE_INFINITY;
12329
12617
  const now = Date.now();
12330
12618
  const cwdKey = normalizePathKey(targetCwd);
12331
12619
  const c = ClientSession.sessionInfosCache.get(cwdKey);
12332
- if (c && now - c.at < ClientSession.SESSION_INFO_CACHE_TTL) {
12620
+ if (c &&
12621
+ now - c.at < ClientSession.SESSION_INFO_CACHE_TTL &&
12622
+ (c.complete || (listOnly && (c.parsedFor ?? ClientSession.SESSION_LIST_PARSE_LIMIT) >= parseNeed))) {
12333
12623
  return c.infos;
12334
12624
  }
12335
- const inFlight = ClientSession.sessionInfosInFlight.get(cwdKey);
12625
+ const fullFlightKey = `${cwdKey}\0full`;
12626
+ const flightKey = listOnly ? `${cwdKey}\0list:${parseNeed}` : fullFlightKey;
12627
+ // 全量扫描进行中时列表请求直接复用它(全集 ⊇ 列表)
12628
+ const inFlight = ClientSession.sessionInfosInFlight.get(flightKey) ??
12629
+ (listOnly ? ClientSession.sessionInfosInFlight.get(fullFlightKey) : undefined);
12336
12630
  if (inFlight)
12337
12631
  return inFlight;
12338
12632
  const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
@@ -12386,25 +12680,41 @@ export class ClientSession {
12386
12680
  }));
12387
12681
  const validStats = stats.filter((s) => s !== null);
12388
12682
  validStats.sort((a, b) => b.mtime - a.mtime);
12683
+ const baseDirKey = normalizePathKey(sessionBaseDir);
12684
+ const isOwn = (info) => info.cwd !== "" && (normalizePathKey(info.cwd) === cwdKey || normalizePathKey(info.cwd) === baseDirKey);
12685
+ const parseLimit = parseNeed;
12686
+ let ownCount = 0;
12687
+ let truncated = false;
12389
12688
  const results = await mapSessionsConcurrent(validStats, async (file) => {
12390
12689
  const cached = ClientSession.sessionFileCacheLookup(file.path);
12391
12690
  if (cached && cached.mtime === file.mtime && cached.size === file.size) {
12691
+ if (isOwn(cached.info))
12692
+ ownCount++;
12392
12693
  return cached.info;
12393
12694
  }
12394
- // 列表路径不收集转录全文(issue #440)——全文只在搜索时按需加载
12395
- const info = await parseSessionInfoFast(file.path, file.mtime);
12396
- if (info) {
12695
+ if (ownCount >= parseLimit) {
12696
+ // 已凑够列表所需条数:更旧的未缓存文件不再解析(工作者按 mtime 新→旧取任务)
12697
+ truncated = true;
12698
+ return null;
12699
+ }
12700
+ // 列表路径不收集转录全文(issue #440)——全文只在搜索时按需加载。
12701
+ // 文件只是被追加(活跃会话每轮都会):带上次的扫描状态,只解析新增字节。
12702
+ const scanned = await scanSessionListInfo(file.path, file.mtime, cached?.scan);
12703
+ const info = scanned?.info ?? null;
12704
+ if (info && scanned) {
12397
12705
  ClientSession.sessionFileCacheStore(file.path, {
12398
12706
  mtime: file.mtime,
12399
12707
  size: file.size,
12400
12708
  info,
12709
+ scan: scanned.state,
12401
12710
  });
12711
+ if (isOwn(info))
12712
+ ownCount++;
12402
12713
  }
12403
12714
  return info;
12404
12715
  });
12405
12716
  const validInfos = results.filter((info) => info !== null);
12406
- const baseDirKey = normalizePathKey(sessionBaseDir);
12407
- const ownInfos = validInfos.filter((info) => info.cwd !== "" && (normalizePathKey(info.cwd) === cwdKey || normalizePathKey(info.cwd) === baseDirKey));
12717
+ const ownInfos = validInfos.filter(isOwn);
12408
12718
  const seenIds = new Set();
12409
12719
  const dedupedOwnInfos = [];
12410
12720
  for (const info of ownInfos) {
@@ -12417,7 +12727,19 @@ export class ClientSession {
12417
12727
  }
12418
12728
  const candidates = dedupedOwnInfos;
12419
12729
  candidates.sort((a, b) => b.modified.getTime() - a.modified.getTime());
12420
- ClientSession.sessionInfosCache.set(cwdKey, { infos: candidates, at: Date.now() });
12730
+ // 列表模式提前停下时缓存标记为不完整;不覆盖仍新鲜的完整缓存
12731
+ const prev = ClientSession.sessionInfosCache.get(cwdKey);
12732
+ const prevFresh = prev && Date.now() - prev.at < ClientSession.SESSION_INFO_CACHE_TTL;
12733
+ // 不覆盖仍新鲜、且覆盖面更大的缓存(完整集,或按更大需求解析过的)
12734
+ const prevCovers = prevFresh && (prev.complete || (truncated && (prev.parsedFor ?? 0) >= parseNeed));
12735
+ if (!prevCovers) {
12736
+ ClientSession.sessionInfosCache.set(cwdKey, {
12737
+ infos: candidates,
12738
+ at: Date.now(),
12739
+ complete: !truncated,
12740
+ ...(truncated ? { parsedFor: parseNeed } : {}),
12741
+ });
12742
+ }
12421
12743
  return candidates;
12422
12744
  }
12423
12745
  catch {
@@ -12443,7 +12765,7 @@ export class ClientSession {
12443
12765
  combined.push({ ...s, allMessagesText: "" });
12444
12766
  }
12445
12767
  combined.sort((a, b) => b.modified.getTime() - a.modified.getTime());
12446
- ClientSession.sessionInfosCache.set(cwdKey, { infos: combined, at: Date.now() });
12768
+ ClientSession.sessionInfosCache.set(cwdKey, { infos: combined, at: Date.now(), complete: true });
12447
12769
  return combined;
12448
12770
  }
12449
12771
  catch {
@@ -12451,10 +12773,10 @@ export class ClientSession {
12451
12773
  }
12452
12774
  }
12453
12775
  finally {
12454
- ClientSession.sessionInfosInFlight.delete(cwdKey);
12776
+ ClientSession.sessionInfosInFlight.delete(flightKey);
12455
12777
  }
12456
12778
  })();
12457
- ClientSession.sessionInfosInFlight.set(cwdKey, run);
12779
+ ClientSession.sessionInfosInFlight.set(flightKey, run);
12458
12780
  return run;
12459
12781
  }
12460
12782
  /** Session files on disk changed (delete / new-transcript) — drop the brief
@@ -12484,19 +12806,46 @@ export class ClientSession {
12484
12806
  if (this.sessionsRequested)
12485
12807
  void this.refreshSessions();
12486
12808
  }
12487
- buildSessionSummaries(targetCwd, infos) {
12809
+ /** 左栏按项目请求的列表条数(B5「显示更多」翻页后,自动刷新沿用它,已展开的列表不被缩回)。 */
12810
+ sessionListLimits = new Map();
12811
+ /** 记录并返回某项目的列表条数;limit 缺省时沿用此前记录的值。 */
12812
+ setSessionListLimit(cwd, limit) {
12813
+ const key = normalizePathKey(cwd);
12814
+ if (typeof limit === "number" && Number.isFinite(limit)) {
12815
+ const clamped = Math.min(ClientSession.SESSION_LIST_MAX, Math.max(ClientSession.SESSION_LIST_DEFAULT, Math.floor(limit)));
12816
+ this.sessionListLimits.set(key, clamped);
12817
+ return clamped;
12818
+ }
12819
+ return this.sessionListLimits.get(key) ?? ClientSession.SESSION_LIST_DEFAULT;
12820
+ }
12821
+ /** 列表推送:取该项目记住的条数,返回摘要与「服务端还有更多」标记。 */
12822
+ async sessionListPayload(targetCwd) {
12823
+ const limit = this.setSessionListLimit(targetCwd);
12824
+ const infos = await this.loadSessionInfos(targetCwd, { listOnly: true, listLimit: limit });
12825
+ const all = this.buildSessionSummaries(targetCwd, infos, Number.POSITIVE_INFINITY);
12826
+ // 解析提前停下(还有未解析的更旧文件)或摘要超过条数,都说明还有更多
12827
+ const cached = ClientSession.sessionInfosCache.get(normalizePathKey(targetCwd));
12828
+ const hasMore = all.length > limit || (cached ? !cached.complete : false);
12829
+ return { sessions: all.slice(0, limit), hasMore };
12830
+ }
12831
+ buildSessionSummaries(targetCwd, infos, limit = ClientSession.SESSION_LIST_DEFAULT) {
12488
12832
  const showForkedParents = this.settingsSvc.current.showForkedParentSessions === true;
12489
12833
  const visibleInfos = filterForkedParentSessions(infos, showForkedParents);
12490
12834
  const sessions = new Map();
12491
12835
  for (const s of visibleInfos) {
12492
12836
  const isPinned = this.stateStore?.isSessionPinned(targetCwd, s.path);
12493
- const displayName = s.name?.trim() || (s.firstMessage ? s.firstMessage.trim().replace(/\s+/g, " ") : undefined);
12837
+ // 列表只用于标题与副标题展示:首条消息可能是整段粘贴的大文本(数十 KB),
12838
+ // 每次推送 ×200 行 ×2 份(firstMessage + displayName)会显著放大 WS 负载与客户端 localStorage 缓存。
12839
+ // 全文检索走 search_sessions,不依赖这里的字段。
12840
+ const firstMessage = s.firstMessage ? clipListText(s.firstMessage) : s.firstMessage;
12841
+ const displayName = s.name?.trim() || (firstMessage ? clipListText(firstMessage.trim().replace(/\s+/g, " ")) : undefined);
12494
12842
  sessions.set(s.path, {
12495
12843
  path: s.path,
12496
12844
  ...(s.id ? { sessionId: s.id } : {}),
12845
+ cwd: targetCwd,
12497
12846
  name: s.name,
12498
12847
  displayName,
12499
- firstMessage: s.firstMessage,
12848
+ firstMessage,
12500
12849
  messageCount: s.messageCount,
12501
12850
  modified: s.modified.getTime(),
12502
12851
  source: "web",
@@ -12504,29 +12853,29 @@ export class ClientSession {
12504
12853
  ...(s.parentSessionPath ? { parentSessionPath: s.parentSessionPath } : {}),
12505
12854
  });
12506
12855
  }
12507
- return [...sessions.values()].sort((a, b) => b.modified - a.modified).slice(0, 200);
12856
+ const sorted = [...sessions.values()].sort((a, b) => b.modified - a.modified);
12857
+ return Number.isFinite(limit) ? sorted.slice(0, limit) : sorted;
12508
12858
  }
12509
12859
  async pushSessions() {
12510
12860
  if (!this.sessionsRequested)
12511
12861
  return;
12862
+ const cwd = this.cwd;
12512
12863
  try {
12513
12864
  // Sessions live in the SDK default per-project dir
12514
12865
  // (<agentDir>/sessions/--<cwd>--/), the same files the pi CLI/TUI
12515
12866
  // use — one listing covers every conversation of the current folder.
12516
- const infos = await this.loadSessionInfos();
12517
- const sorted = this.buildSessionSummaries(this.cwd, infos);
12518
- this.emit({ type: "sessions", sessions: sorted });
12867
+ const { sessions, hasMore } = await this.sessionListPayload(cwd);
12868
+ this.emit({ type: "sessions", sessions, cwd, ...(hasMore ? { hasMore: true } : {}) });
12519
12869
  }
12520
12870
  catch {
12521
- this.emit({ type: "sessions", sessions: [] });
12871
+ this.emit({ type: "sessions", sessions: [], cwd });
12522
12872
  }
12523
12873
  }
12524
12874
  /** Push the persisted session list for a specific project directory (on demand, e.g. expanding an unopened project). */
12525
12875
  async pushSessionsForCwd(targetCwd) {
12526
12876
  try {
12527
- const infos = await this.loadSessionInfos(targetCwd);
12528
- const sorted = this.buildSessionSummaries(targetCwd, infos);
12529
- this.emit({ type: "sessions", sessions: sorted, cwd: targetCwd });
12877
+ const { sessions, hasMore } = await this.sessionListPayload(targetCwd);
12878
+ this.emit({ type: "sessions", sessions, cwd: targetCwd, ...(hasMore ? { hasMore: true } : {}) });
12530
12879
  }
12531
12880
  catch {
12532
12881
  this.emit({ type: "sessions", sessions: [], cwd: targetCwd });
@@ -12586,7 +12935,7 @@ export class ClientSession {
12586
12935
  }
12587
12936
  if (holder) {
12588
12937
  // Same source the history panel uses (refreshSessions): newest first.
12589
- const infos = await this.loadSessionInfos();
12938
+ const infos = await this.loadSessionInfos(undefined, { listOnly: true });
12590
12939
  const next = infos
12591
12940
  .filter((s) => resolve(s.path) !== abs)
12592
12941
  .sort((a, b) => b.modified.getTime() - a.modified.getTime())[0];
@@ -13549,14 +13898,20 @@ export class ClientSession {
13549
13898
  });
13550
13899
  await new Promise((r) => setImmediate(r));
13551
13900
  timing.mark("resolve-and-ownership");
13552
- this.repairTranscriptFileBeforeOpen(targetPath);
13901
+ await this.repairTranscriptFileBeforeOpen(targetPath);
13553
13902
  timing.mark("repair");
13554
- const sessionManager = SessionManager.open(targetPath);
13903
+ // 异步读盘 + 分时片解析,不再同步阻塞事件循环(session-open.ts,失败回退 SessionManager.open)
13904
+ const sessionManager = await openSessionManagerAsync(targetPath);
13555
13905
  timing.mark("sdk-open");
13556
13906
  calibrateSessionLeaf(sessionManager);
13557
13907
  timing.mark("branch-calibration");
13908
+ // 预先分配对话 id 并随预览下发:浏览器用它 + 会话文件组成与首个快照相同的会话键,
13909
+ // 预览→快照只替换数据、不重挂载消息列表(C4)。打开失败时 id 作废,无副作用。
13910
+ const conversationId = this.nextConversationId();
13911
+ let previewIdSeed;
13558
13912
  {
13559
- const { totalMessages, previewMessages } = this.extractTranscriptPreview(sessionManager, 16);
13913
+ const { totalMessages, previewMessages, idSeed } = this.extractTranscriptPreview(sessionManager, 16);
13914
+ previewIdSeed = idSeed;
13560
13915
  this.emit({
13561
13916
  type: "transition_progress",
13562
13917
  kind: "session",
@@ -13571,6 +13926,8 @@ export class ClientSession {
13571
13926
  : "Transcript ready, mounting agent runtime…",
13572
13927
  totalMessages,
13573
13928
  ...(previewMessages.length > 0 ? { previewMessages } : {}),
13929
+ // 仅当预览 id 与快照一致时才下发:浏览器据此决定是否沿用同一个消息列表实例
13930
+ ...(idSeed ? { conversationId, sessionFile: targetPath } : {}),
13574
13931
  });
13575
13932
  await new Promise((r) => setImmediate(r));
13576
13933
  }
@@ -13578,7 +13935,13 @@ export class ClientSession {
13578
13935
  const rawSessionCwd = sessionManager.getCwd();
13579
13936
  const targetCwd = restoreWorkspaceUriFromSessionDir(rawSessionCwd);
13580
13937
  const runtimeCwd = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
13581
- const conversationId = this.nextConversationId();
13938
+ // 名额预检放在构建 runtime 之前:原先达上限时要先完整构建 runtime(扩展/技能/MCP)
13939
+ // 再发现超额并 dispose,白白耗时;现在超额时先按 LRU 收起只查看过的历史对话,
13940
+ // 仍腾不出才拒绝。
13941
+ if (!this.makeRoomForConversation(targetCwd, 1, () => this.wouldDisplaceActive())) {
13942
+ this.emitMaxOpenConversationsReached(targetPath);
13943
+ return;
13944
+ }
13582
13945
  openedTerminals = this.makeTerminalManager(conversationId, targetCwd);
13583
13946
  openedRuntime = await createAgentSessionRuntime(this.makeRuntimeFactory(openedTerminals, undefined, conversationId), {
13584
13947
  cwd: runtimeCwd,
@@ -13595,7 +13958,10 @@ export class ClientSession {
13595
13958
  1 -
13596
13959
  (displaced?.cwd === targetCwd && !displaced?.isSubagent && !displaced?.isEphemeral ? 1 : 0);
13597
13960
  const maxOpenConversations = getMaxOpenConversations();
13598
- if (openInProject > maxOpenConversations) {
13961
+ // 兜底复检:runtime 构建期间(await)别处可能新开了对话。仍超额时先尝试 LRU 收起,
13962
+ // 依然不行才放弃。displaced 此刻仍是 active(尚未移除),不会被收起。
13963
+ if (openInProject > maxOpenConversations &&
13964
+ !this.makeRoomForConversation(targetCwd, 1, displaced?.cwd === targetCwd && !displaced?.isSubagent)) {
13599
13965
  // displaceActive() may have promoted a streaming conversation into the
13600
13966
  // running list. Roll that presentation-only mutation back because no
13601
13967
  // switch will take place.
@@ -13604,25 +13970,11 @@ export class ClientSession {
13604
13970
  await openedRuntime.dispose();
13605
13971
  openedRuntime = null;
13606
13972
  openedTerminals = null;
13607
- this.emit({
13608
- type: "transition_progress",
13609
- kind: "session",
13610
- target: targetPath,
13611
- phase: "error",
13612
- progress: 100,
13613
- text: `当前项目运行的对话已达上限(${maxOpenConversations} 个)`,
13614
- textEn: `Max open conversations (${maxOpenConversations}) reached`,
13615
- });
13616
- const notice = this.maxOpenConversationsNotice(maxOpenConversations);
13617
- this.emit({
13618
- type: "notice",
13619
- level: "warning",
13620
- text: notice.text,
13621
- textEn: notice.textEn,
13622
- });
13973
+ this.emitMaxOpenConversationsReached(targetPath);
13623
13974
  return;
13624
13975
  }
13625
13976
  const conv = this.makeConversation(openedRuntime, conversationId, openedTerminals);
13977
+ this.seedConversationIds(conv, previewIdSeed);
13626
13978
  if (independent !== undefined) {
13627
13979
  conv.session.sessionManager.appendCustomEntry("webui/independent", { independent });
13628
13980
  conv.independent = independent;
@@ -13631,9 +13983,12 @@ export class ClientSession {
13631
13983
  // switches away without sending a new message.
13632
13984
  conv.listed = true;
13633
13985
  conv.promptedSinceActive = true;
13986
+ // 只是打开查看:达上限时可按 LRU 自动收起(发言即清除,见 prompt 路径)。
13987
+ conv.viewOnly = true;
13634
13988
  if (this.stateStore?.isSessionPinned(targetCwd, targetPath)) {
13635
13989
  conv.pinned = true;
13636
13990
  conv.listed = true;
13991
+ conv.viewOnly = false;
13637
13992
  }
13638
13993
  this.noticeInterruptedCompaction(conv);
13639
13994
  this.convs.set(conv.id, conv);
@@ -14278,20 +14633,22 @@ export class ClientSession {
14278
14633
  */
14279
14634
  async pushProjects() {
14280
14635
  const now = Date.now();
14281
- const cached = ClientSession.projectsCache;
14282
- // TTL 命中(或已建立过项目缓存):直接把当前 cwd 合并重排并续期,
14283
- // 避免切换工作区时因为刚好跨过 60s TTL 而触发全盘 30 个会话子目录重扫。
14284
- // 已建立过缓存:emit 本客户端的派生视图即可,**绝不把派生结果写回静态缓存**
14285
- // ——withCurrentCwd 注入了本客户端的 cwd/lastUsed/removedKeys 过滤与沙盒
14286
- // 元数据,写回会把 A 客户端的视图固化给 B(静态缓存跨客户端共享);
14287
- // 底层超过 TTL 后后台重扫一次,磁盘上新工作区不会被永久挡在列表外。
14288
- if (cached) {
14289
- this.emit({ type: "projects", projects: this.withCurrentCwd(cached.projects, now) });
14290
- if (now - cached.at >= ClientSession.PROJECTS_CACHE_TTL)
14291
- void this.ensureProjectsCache(false);
14292
- return;
14636
+ try {
14637
+ const cache = ClientSession.projectsCache;
14638
+ if (!cache) {
14639
+ // Cold starts must discover workspaces known only through saved session headers.
14640
+ await this.ensureProjectsCache(false);
14641
+ }
14642
+ else if (now - cache.at >= ClientSession.PROJECTS_CACHE_TTL) {
14643
+ // Renew metadata in the background; warm requests still read current persisted state.
14644
+ void this.ensureProjectsCache(false).catch(() => { });
14645
+ }
14646
+ const recent = await this.stateStore.getRecentProjects(this.clientId);
14647
+ this.emit({ type: "projects", projects: this.withCurrentCwd(recent, now) });
14648
+ }
14649
+ catch {
14650
+ this.emit({ type: "projects", projects: this.withCurrentCwd([], now) });
14293
14651
  }
14294
- await this.ensureProjectsCache(true);
14295
14652
  }
14296
14653
  /**
14297
14654
  * 确保静态缓存有基底(单飞:已有扫描在跑则搭车,不并发扫两遍盘)。
@@ -14359,12 +14716,10 @@ export class ClientSession {
14359
14716
  list = validProjects;
14360
14717
  }
14361
14718
  else if (validProjects.some((p) => normalizePathKey(p.path) === currentKey)) {
14362
- list = validProjects
14363
- .map((p) => (normalizePathKey(p.path) === currentKey && p.lastUsed < now ? { ...p, lastUsed: now } : p))
14364
- .sort((a, b) => b.lastUsed - a.lastUsed);
14719
+ list = validProjects.map((p) => normalizePathKey(p.path) === currentKey ? { ...p, lastUsed: Math.max(p.lastUsed, now) } : p);
14365
14720
  }
14366
14721
  else {
14367
- list = [{ path: this.cwd, lastUsed: now }, ...validProjects].slice(0, 20);
14722
+ list = [{ path: this.cwd, lastUsed: now }, ...validProjects].slice(0, RECENT_PROJECTS_MAX);
14368
14723
  }
14369
14724
  // 确保所有仍存活的注册沙盒也出现在列表里,并附带 sandbox 元数据
14370
14725
  const existingKeys = new Set(list.map((p) => normalizePathKey(p.path)));
@@ -14375,13 +14730,13 @@ export class ClientSession {
14375
14730
  existingKeys.add(k);
14376
14731
  }
14377
14732
  }
14378
- return list
14733
+ return (list
14379
14734
  .map((p) => {
14380
14735
  const sbx = this.sandboxes.getByCwd(p.path);
14381
14736
  return sbx ? { ...p, sandbox: sbx } : p;
14382
14737
  })
14383
- .sort((a, b) => b.lastUsed - a.lastUsed)
14384
- .slice(0, 25);
14738
+ // 额外 5 个名额留给注册沙盒(原 30 + 5 口径)
14739
+ .slice(0, RECENT_PROJECTS_MAX + 5));
14385
14740
  }
14386
14741
  /** 最近项目缓存失效(用户显式移除项目后,下一次推送必须重扫)。 */
14387
14742
  invalidateProjectsCache() {
@@ -14654,7 +15009,7 @@ export class ClientSession {
14654
15009
  }
14655
15010
  else {
14656
15011
  // 冷切换的 runtime 创建要 1~2s(扫技能/扩展)—— 先回一条 ack +
14657
- // 流式进度 + 快照,点击立即呈现阶段进度与转录预览;落地后再推完整全量。
15012
+ // 流式进度,点击立即呈现阶段进度与转录预览;落地后再推完整全量。
14658
15013
  this.emit({
14659
15014
  type: "transition_progress",
14660
15015
  kind: "cwd",
@@ -14664,13 +15019,12 @@ export class ClientSession {
14664
15019
  text: openRecent ? `正在同步目录与检查最近会话:${abs}` : `正在切换工作目录:${abs}`,
14665
15020
  textEn: openRecent ? `Validating workspace & checking recent session: ${abs}` : `Switching workspace: ${abs}`,
14666
15021
  });
14667
- this.flushSnapshot();
14668
15022
  // 让出事件循环,确保首帧进度在同步磁盘扫描前真正发往浏览器
14669
15023
  await new Promise((r) => setImmediate(r));
14670
15024
  // 在耗时的 runtime 初始化期间,并行预热目标项目的会话列表缓存
14671
15025
  if (this.sessionsRequested) {
14672
15026
  ClientSession.sessionInfosCache.delete(normalizePathKey(abs));
14673
- void this.loadSessionInfos(abs).catch(() => { });
15027
+ void this.loadSessionInfos(abs, { listOnly: true }).catch(() => { });
14674
15028
  }
14675
15029
  // First visit to this project: resume its most recent session —
14676
15030
  // unless that transcript is still held on another client (#145):