pi-web-ui 0.115.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 (161) hide show
  1. package/CHANGELOG.md +65 -2
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +159 -71
  4. package/dist/server/agent-service-daemon.js +136 -8
  5. package/dist/server/agent-service.js +594 -159
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +52 -8
  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 +77 -2
  11. package/dist/server/device-center/collab-service.js +61 -12
  12. package/dist/server/device-center/collab-tool.js +482 -21
  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 +17 -7
  18. package/dist/server/device-center/execution-instructions.js +2 -1
  19. package/dist/server/device-center/execution-settings.js +138 -25
  20. package/dist/server/device-center/executor.js +51 -6
  21. package/dist/server/device-center/file-sync.js +14 -13
  22. package/dist/server/device-center/group-context-message.js +3 -1
  23. package/dist/server/device-center/group-context.js +73 -3
  24. package/dist/server/device-center/hub-conversations.js +71 -6
  25. package/dist/server/device-center/hub-deliveries.js +120 -15
  26. package/dist/server/device-center/hub-integration.js +655 -334
  27. package/dist/server/device-center/hub-locks.js +320 -0
  28. package/dist/server/device-center/hub-page.js +16 -35
  29. package/dist/server/device-center/hub-setup.js +23 -1
  30. package/dist/server/device-center/hub-transaction-log.js +197 -0
  31. package/dist/server/device-center/hub-webhooks.js +165 -0
  32. package/dist/server/device-center/hub.js +1531 -305
  33. package/dist/server/device-center/integration-verification.js +113 -0
  34. package/dist/server/device-center/local-hub.js +8 -3
  35. package/dist/server/device-center/local-publication.js +423 -0
  36. package/dist/server/device-center/local-verification-job.js +97 -0
  37. package/dist/server/device-center/local-verification.js +274 -0
  38. package/dist/server/device-center/local.js +181 -13
  39. package/dist/server/device-center/main.js +4 -1
  40. package/dist/server/device-center/partition-log.js +330 -0
  41. package/dist/server/device-center/publication-journal.js +312 -0
  42. package/dist/server/device-center/publish-intent.js +379 -0
  43. package/dist/server/device-center/relay.js +134 -24
  44. package/dist/server/device-center/runtime.js +475 -42
  45. package/dist/server/device-center/store.js +366 -89
  46. package/dist/server/device-center/task-outcome.js +81 -0
  47. package/dist/server/device-center/task-recovery.js +603 -178
  48. package/dist/server/device-center/task-scheduler.js +48 -3
  49. package/dist/server/device-center/task-settlement.js +353 -0
  50. package/dist/server/device-center/task-workspace.js +443 -0
  51. package/dist/server/device-center/transfers.js +41 -15
  52. package/dist/server/device-center/verification-limits.js +10 -0
  53. package/dist/server/device-center/work-contract.js +995 -0
  54. package/dist/server/dispatch-domain-handlers.js +29 -3
  55. package/dist/server/dsh/dsh-agent-service.js +9 -2
  56. package/dist/server/engine-probe.js +112 -1
  57. package/dist/server/global-loader.js +119 -19
  58. package/dist/server/index.js +159 -17
  59. package/dist/server/managed.js +2 -0
  60. package/dist/server/model-admin.js +48 -6
  61. package/dist/server/model-enrich.js +10 -1
  62. package/dist/server/patch-node-pty.js +3 -2
  63. package/dist/server/patch-remote-catalog.js +3 -2
  64. package/dist/server/plugins.js +64 -7
  65. package/dist/server/preset-fields.js +17 -1
  66. package/dist/server/preset-share.js +1 -0
  67. package/dist/server/prompt-composer.js +39 -0
  68. package/dist/server/protocol-version.js +1 -1
  69. package/dist/server/quick-ask-settings.js +28 -0
  70. package/dist/server/quick-ask.js +164 -0
  71. package/dist/server/reasoning-registry.js +207 -0
  72. package/dist/server/resolve-global-sdk.js +61 -11
  73. package/dist/server/scheduler-tasks.js +35 -8
  74. package/dist/server/session-list-scan.js +223 -0
  75. package/dist/server/session-open.js +93 -0
  76. package/dist/server/session-parser.js +4 -0
  77. package/dist/server/session-scan.js +90 -38
  78. package/dist/server/settings-service.js +9 -1
  79. package/dist/server/soft-cap.js +5 -0
  80. package/dist/server/startup-banner.js +35 -0
  81. package/dist/server/subagents.js +2 -1
  82. package/dist/server/tool-manager.js +17 -9
  83. package/dist/server/transcript-prepare.js +73 -0
  84. package/dist/server/unauthorized-page.js +319 -0
  85. package/dist/server/universal/drivers/claude-code.js +98 -34
  86. package/dist/server/universal/universal-session.js +4 -0
  87. package/dist/server/workspace-handle.js +428 -0
  88. package/docs/architecture-plugins.md +959 -0
  89. package/docs/device-center.md +34 -20
  90. package/package.json +4 -4
  91. package/plugin-sdk/README.md +16 -8
  92. package/plugin-sdk/client.d.ts +27 -0
  93. package/plugin-sdk/client.mjs +82 -0
  94. package/plugin-sdk/index.d.ts +10 -0
  95. package/plugin-sdk/index.mjs +4 -683
  96. package/plugin-sdk/package.json +15 -4
  97. package/plugin-sdk/testing.d.ts +10 -0
  98. package/plugin-sdk/testing.mjs +566 -0
  99. package/themes/flow-cristallo.css +168 -0
  100. package/themes/flow-ink.css +169 -0
  101. package/themes/flow-obsidian.css +169 -0
  102. package/themes/flow-zurich.css +169 -0
  103. package/web/dist/.build-assets.json +1 -1
  104. package/web/dist/assets/{BgTasksModal-BYzPgmoq.js → BgTasksModal-BjNRIUIc.js} +1 -1
  105. package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0zuU8FE.js} +1 -1
  106. package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  107. package/web/dist/assets/{CanvasStudio-BCUeEf25.js → CanvasStudio-VQFjmTGq.js} +3 -3
  108. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  109. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  110. package/web/dist/assets/DeviceExecutionSettings-BLP1Su5G.js +1 -0
  111. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  112. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  113. package/web/dist/assets/{Dropdown-CGXD0DfT.js → Dropdown-CQtstPGv.js} +1 -1
  114. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  115. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  116. package/web/dist/assets/{GlobalSearchModal-mevF-ySi.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  117. package/web/dist/assets/{GlobalSearchModal-qL99FN_F.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  118. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  119. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  120. package/web/dist/assets/{HintTip-LHwkS2jV.js → HintTip-ChTW8o1m.js} +1 -1
  121. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  122. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  123. package/web/dist/assets/{PiSetupModal-DE5-gEtI.js → PiSetupModal-BX5rUuoI.js} +1 -1
  124. package/web/dist/assets/{ProviderOAuthControls-6UMARucA.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  125. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  126. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  127. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  128. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  129. package/web/dist/assets/{TerminalPanel-CTp_BZ4S.js → TerminalPanel-D4By_RVc.js} +2 -2
  130. package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-lZw8-i3j.js} +2 -2
  131. package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  132. package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  133. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  134. package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-BY6ojmle.js} +1 -1
  135. package/web/dist/assets/{desktop-kjBoE3Nu.js → desktop-CV6KKp9R.js} +1 -1
  136. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  137. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  138. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  139. package/web/dist/assets/{plugin-host-C8mNgghx.js → plugin-host-Dn8Dd6SC.js} +1 -1
  140. package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  141. package/web/dist/assets/{theme-BXGpyTMh.js → theme-D_bihpdN.js} +1 -1
  142. package/web/dist/index.html +11 -11
  143. package/web/dist/sw.js +1 -1
  144. package/dist/server/patch-turn-end-boundary.js +0 -77
  145. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +0 -3
  146. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +0 -3
  147. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +0 -1
  148. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +0 -1
  149. package/web/dist/assets/FilePreview-B8iqnBjy.js +0 -2
  150. package/web/dist/assets/FilePreview-BqviZKCN.js +0 -2
  151. package/web/dist/assets/GroupConversation-B88Yy-lt.js +0 -3
  152. package/web/dist/assets/GroupConversation-BwP5NVOE.js +0 -3
  153. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +0 -2
  154. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +0 -2
  155. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +0 -2
  156. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +0 -20
  157. package/web/dist/assets/SettingsModal-CF-7MwqS.js +0 -20
  158. package/web/dist/assets/app-globals-DZNa9v8u.js +0 -325
  159. package/web/dist/assets/index-CsFs_HMb.css +0 -1
  160. package/web/dist/assets/index-DHeeHS_l.js +0 -85
  161. package/web/dist/assets/index-DTZch8uz.js +0 -85
@@ -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";
@@ -32,10 +31,13 @@ import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
32
31
  import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
33
32
  import { collectInstalledEngineTargets } from "./engine-probe.js";
34
33
  import { checkPluginUpdates } from "./plugin-updater.js";
35
- import { getAppVersion } from "./pkg-info.js";
34
+ 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;
@@ -885,6 +918,8 @@ export class ClientSession {
885
918
  owner.scheduleSubagentCompletionNotice(conv);
886
919
  owner.emitConversations();
887
920
  });
921
+ // spawn 成功派发后解除与父工具信号的绑定;后续父对话停止不连带中止已派出的子代理(issue #833)
922
+ signal?.removeEventListener("abort", onSpawnAbort);
888
923
  if (persist) {
889
924
  holder.pushProjects().catch(() => { });
890
925
  }
@@ -1474,6 +1509,26 @@ export class ClientSession {
1474
1509
  return;
1475
1510
  }
1476
1511
  }
1512
+ // 若父对话正在 wait_all 等待中,完成通知暂不投递进 steering 队列,避免与 wait_all 返回重复(issue #828)
1513
+ if (consultWaitingParents.has(targetConv)) {
1514
+ if (retryCount < 60) {
1515
+ const retryTimer = setTimeout(() => {
1516
+ const current = toNotify.filter(isCurrent);
1517
+ if (current.length === 0)
1518
+ return;
1519
+ const pending = this.pendingSubagentNotices.get(parentId);
1520
+ if (pending?.timer)
1521
+ clearTimeout(pending.timer);
1522
+ this.pendingSubagentNotices.set(parentId, {
1523
+ timer: retryTimer,
1524
+ subagents: new Set([...(pending?.subagents ?? []), ...current]),
1525
+ });
1526
+ void this.flushSubagentCompletionNotice(parentId, retryCount + 1);
1527
+ }, 400);
1528
+ this.pendingSubagentNotices.set(parentId, { timer: retryTimer, subagents: new Set(toNotify) });
1529
+ return;
1530
+ }
1531
+ }
1477
1532
  for (const c of toNotify) {
1478
1533
  c.subagentDoneNotified = true;
1479
1534
  }
@@ -2024,6 +2079,9 @@ export class ClientSession {
2024
2079
  piReadme: PI_DOC_PATHS.readme,
2025
2080
  piDocs: PI_DOC_PATHS.docs,
2026
2081
  piExamples: PI_DOC_PATHS.examples,
2082
+ pluginDocs: join(getPkgRoot(), "docs", "architecture-plugins.md"),
2083
+ pluginSdk: join(getPkgRoot(), "plugin-sdk"),
2084
+ pluginsDir: join(this.stateStore.dataDir, "plugins"),
2027
2085
  appendFiles: [...promptBase.append],
2028
2086
  windowsPersona: isRemote
2029
2087
  ? buildRemoteWorkspacePersona(realCwd)
@@ -2262,6 +2320,11 @@ export class ClientSession {
2262
2320
  consultWaitingParents.delete(parent);
2263
2321
  }
2264
2322
  },
2323
+ isRequestSteering: (parentId, requestId) => {
2324
+ const owner = this.subagentOwnerOf(parentId);
2325
+ const parent = owner.convs.get(this.subagentCurrentId(parentId));
2326
+ return !!parent?.queuedSteeringRequestIds?.has(requestId);
2327
+ },
2265
2328
  spawnSubagent: (prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, isolation, extra, signal) => {
2266
2329
  // B20:过户后 parentId 的主对话可能已搬去另一个 ClientSession ——
2267
2330
  // 委托给真正持有父对话的会话 spawn(模板/上限/注册/左栏全随它),
@@ -2897,8 +2960,10 @@ export class ClientSession {
2897
2960
  static async create(clientId, cwd, stateStore, opts) {
2898
2961
  const botExecution = getBotExecution(clientId);
2899
2962
  botExecution?.assertActive();
2900
- if (botExecution)
2901
- cwd = botExecution.bot.cwd;
2963
+ if (botExecution) {
2964
+ cwd = botExecution.executionCwd;
2965
+ await botExecution.assertWorkspace(cwd);
2966
+ }
2902
2967
  const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
2903
2968
  const cs = new ClientSession(clientId, cwd, agentDir, stateStore);
2904
2969
  cs.botExecution = botExecution;
@@ -3005,7 +3070,7 @@ export class ClientSession {
3005
3070
  const targetPath = resolve(p);
3006
3071
  if (!existsSync(targetPath))
3007
3072
  continue;
3008
- cs.repairTranscriptFileBeforeOpen(targetPath);
3073
+ await cs.repairTranscriptFileBeforeOpen(targetPath);
3009
3074
  const sm = SessionManager.open(targetPath);
3010
3075
  const convId = cs.nextConversationId();
3011
3076
  const terms = cs.makeTerminalManager(convId, cwd);
@@ -3055,7 +3120,8 @@ export class ClientSession {
3055
3120
  */
3056
3121
  makeRuntimeFactory(terminals, apply, ownerId, initialModel, targetPreset, noSpawnTools) {
3057
3122
  return async ({ cwd: effectiveCwd, sessionManager }) => {
3058
- this.botExecution?.assertActive();
3123
+ if (this.botExecution)
3124
+ await this.botExecution.assertWorkspace(effectiveCwd);
3059
3125
  const botEntry = sessionManager
3060
3126
  .getEntries()
3061
3127
  .find((entry) => entry.type === "custom" && entry.customType === "device-bot-execution");
@@ -3071,7 +3137,8 @@ export class ClientSession {
3071
3137
  botId: this.botExecution.bot.id,
3072
3138
  revision: this.botExecution.bot.revision,
3073
3139
  });
3074
- 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))
3075
3142
  throw new Error("Bot cwd is fixed");
3076
3143
  const sandboxIdentity = this.sandboxes.getExecutionIdentity(effectiveCwd);
3077
3144
  const releaseMcp = sandboxIdentity || this.botExecution ? undefined : ClientSession.mcpProjects?.retain(effectiveCwd);
@@ -3084,6 +3151,7 @@ export class ClientSession {
3084
3151
  allowedServers: this.botExecution.bot.mcpServers,
3085
3152
  });
3086
3153
  await this.botMcpBridge.load();
3154
+ await this.botExecution.assertWorkspace(effectiveCwd);
3087
3155
  }
3088
3156
  }
3089
3157
  else if (!sandboxIdentity)
@@ -3235,9 +3303,10 @@ export class ClientSession {
3235
3303
  name: "pi-webui-sandbox-final-gate",
3236
3304
  hidden: true,
3237
3305
  factory: (pi) => {
3238
- pi.on("tool_call", (event) => {
3306
+ pi.on("tool_call", async (event) => {
3239
3307
  if (this.botExecution) {
3240
3308
  try {
3309
+ await this.botExecution.assertWorkspace(effectiveCwd);
3241
3310
  const auth = this.botToolAuthorization(event.toolName, effectiveCwd, event.input);
3242
3311
  if (!auth.allowed)
3243
3312
  return { block: true, reason: auth.reason ?? "Tool is not authorized for this Bot" };
@@ -3424,6 +3493,7 @@ export class ClientSession {
3424
3493
  }
3425
3494
  }
3426
3495
  }
3496
+ await this.botExecution?.assertWorkspace(effectiveCwd);
3427
3497
  const created = await createAgentSessionFromServices({
3428
3498
  services,
3429
3499
  sessionManager,
@@ -3681,7 +3751,8 @@ export class ClientSession {
3681
3751
  askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category),
3682
3752
  getConversationId: () => ownerId,
3683
3753
  }, () => this.getLang()),
3684
- makeDeviceCollabTool(),
3754
+ // 设备中心群任务协作工具(仅在群任务 Bot 执行上下文注入;普通单聊完全不挂载)。
3755
+ ...(this.botExecution ? [makeDeviceCollabTool()] : []),
3685
3756
  // Git 工作树管理工具(worktree:list/create/switch/remove)。
3686
3757
  makeWorktreeTool({
3687
3758
  getCwd: () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? effectiveCwd,
@@ -3700,6 +3771,13 @@ export class ClientSession {
3700
3771
  });
3701
3772
  // 桥接工具归属锚点:SDK 会话对象在本 runtime 生命周期内稳定,过户只搬对话
3702
3773
  // 不改它(见 ClientSession.findConversationHome)。
3774
+ try {
3775
+ await this.botExecution?.assertWorkspace(effectiveCwd);
3776
+ }
3777
+ catch (error) {
3778
+ created.session.dispose();
3779
+ throw error;
3780
+ }
3703
3781
  bridgeAnchor.session = created.session;
3704
3782
  this.appliedPluginToolNames.set(created.session, new Set((this.pluginToolsProvider?.(effectiveCwd) ?? []).map((tool) => tool.name)));
3705
3783
  const evidenceHooksReady = installEvidenceToolHooks(created.session);
@@ -3878,10 +3956,17 @@ export class ClientSession {
3878
3956
  if (this.convs.get(conv.id) !== conv)
3879
3957
  return;
3880
3958
  conv.goalGeneration++;
3959
+ try {
3960
+ conv.session.clearQueue?.();
3961
+ }
3962
+ catch (err) {
3963
+ console.error("[agent-service] clearQueue failed during abortConversation:", err);
3964
+ }
3881
3965
  conv.queueSteering = [];
3882
3966
  conv.queueFollowUp = [];
3883
3967
  conv.queuedSteeringEntries = [];
3884
3968
  conv.queuedFollowUpEntries = [];
3969
+ conv.queuedSteeringRequestIds?.clear();
3885
3970
  await this.interruptRun(conv, "已停止");
3886
3971
  for (const push of this.conversationViewers?.get(conv) ?? [])
3887
3972
  push();
@@ -4180,6 +4265,8 @@ export class ClientSession {
4180
4265
  makeExtensionErrorReporter(prefix) {
4181
4266
  const seen = new Set();
4182
4267
  return (err) => {
4268
+ if (isAbortedTurnBoundaryError(err))
4269
+ return;
4183
4270
  const message = err?.error ?? String(err);
4184
4271
  const where = [err?.extensionPath, err?.event].filter(Boolean).join(" · ");
4185
4272
  console.error(`[extension] ${prefix?.text ?? "当前对话"}${where ? ` (${where})` : ""}: ${message}${err?.stack ? `\n${err.stack}` : ""}`);
@@ -4480,7 +4567,7 @@ export class ClientSession {
4480
4567
  * 复用 refreshSessions/searchSessions 共用的 loadSessionInfos 缓存(3s TTL,不扫两遍盘)。 */
4481
4568
  async listHistoryForPlugins(limit = 50) {
4482
4569
  try {
4483
- const infos = await this.loadSessionInfos();
4570
+ const infos = await this.loadSessionInfos(undefined, { listOnly: limit <= 200 });
4484
4571
  return infos.slice(0, Math.max(0, limit)).map((s) => ({
4485
4572
  id: s.path,
4486
4573
  title: (s.name?.trim() || s.firstMessage.trim() || basename(s.path)).slice(0, 60),
@@ -5468,40 +5555,7 @@ export class ClientSession {
5468
5555
  // 一次扫描同时收齐「当前转写里的全部缓存键」(live 集合,供
5469
5556
  // pruneMessageCache 精确回收死条目)与各自的序列化结果。
5470
5557
  const live = new Set();
5471
- let agentMessages = conv.session.agent.state.messages;
5472
- // issue #448: 多次压缩后 SDK state.messages 只保留最后一次压缩卡片。
5473
- // 从当前分支祖先链中提取前序未展示的历史 compaction 并正序置前,
5474
- // 使前端能逐段回溯展开历史折叠内容。
5475
- if (conv.session.sessionManager?.getBranch) {
5476
- try {
5477
- const branch = conv.session.sessionManager.getBranch();
5478
- const compEntries = branch.filter((e) => e.type === "compaction");
5479
- if (compEntries.length > 1) {
5480
- const existingCompKeys = new Set(agentMessages
5481
- .filter((m) => m.role === "compactionSummary")
5482
- .map((m) => `${m.timestamp}:${m.summary ?? ""}`));
5483
- const missingComps = [];
5484
- for (const ce of compEntries) {
5485
- const ts = ce.timestamp ? new Date(ce.timestamp).getTime() : 0;
5486
- const key = `${ts}:${ce.summary ?? ""}`;
5487
- if (!existingCompKeys.has(key)) {
5488
- missingComps.push({
5489
- role: "compactionSummary",
5490
- summary: ce.summary ?? "",
5491
- tokensBefore: ce.tokensBefore,
5492
- timestamp: ts,
5493
- });
5494
- }
5495
- }
5496
- if (missingComps.length > 0) {
5497
- agentMessages = [...missingComps, ...agentMessages];
5498
- }
5499
- }
5500
- }
5501
- catch {
5502
- // 获取分支异常不影响当前渲染
5503
- }
5504
- }
5558
+ const agentMessages = this.withHistoricalCompactions(conv.session.agent.state.messages, conv.session.sessionManager);
5505
5559
  let rawMessages = agentMessages
5506
5560
  .map((m) => {
5507
5561
  const k = this.uiMessageKey(conv, m);
@@ -5523,6 +5577,44 @@ export class ClientSession {
5523
5577
  conv.lastMessagesArray = rawMessages;
5524
5578
  return messages;
5525
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
+ }
5526
5618
  /** 序列化缓存上界:**先按「还在转写里」淘汰,绝不为省内存淘汰仍在转写里的条目**。
5527
5619
  *
5528
5620
  * 为什么不能 FIFO 淘汰(issue #259 实测的机理):缓存上限一旦低于转写长度,
@@ -5807,7 +5899,7 @@ export class ClientSession {
5807
5899
  this.pendingQuestions.set(request.id, request);
5808
5900
  request.onSettled = () => {
5809
5901
  this.pendingQuestions.delete(request.id);
5810
- this.emit({ type: "question_retracted", id: request.id });
5902
+ this.emit({ type: "question_retracted", id: request.id, owner: this.clientId });
5811
5903
  this.questionsChanged();
5812
5904
  const source = this.convs.get(request.conversationId);
5813
5905
  if (source?.notifyOnDone === "manual")
@@ -6009,8 +6101,6 @@ export class ClientSession {
6009
6101
  const seen = new Set();
6010
6102
  while (!seen.has(conv)) {
6011
6103
  seen.add(conv);
6012
- if (conv.subagentWorktree && isSameOrSubpath(conv.cwd, conv.subagentWorktree.worktreePath))
6013
- return normalizePathKey(conv.subagentWorktree.mainRepoPath);
6014
6104
  if (!conv.parentId)
6015
6105
  break;
6016
6106
  const parent = this.parentExecution(conv)?.conv;
@@ -6018,6 +6108,8 @@ export class ClientSession {
6018
6108
  break;
6019
6109
  conv = parent;
6020
6110
  }
6111
+ if (conv.subagentWorktree && isSameOrSubpath(conv.cwd, conv.subagentWorktree.worktreePath))
6112
+ return normalizePathKey(conv.subagentWorktree.mainRepoPath);
6021
6113
  // A child may execute in an independent checkout. Its registered ancestry,
6022
6114
  // rather than that checkout's path, determines the collaboration project.
6023
6115
  return normalizePathKey(conv.cwd);
@@ -6146,8 +6238,16 @@ export class ClientSession {
6146
6238
  conv.wakeReason = "other";
6147
6239
  conv.wakeTurnHadAction = false;
6148
6240
  }
6241
+ if (busy && envelope.requestId) {
6242
+ conv.queuedSteeringRequestIds = conv.queuedSteeringRequestIds ?? new Set();
6243
+ conv.queuedSteeringRequestIds.add(envelope.requestId);
6244
+ }
6149
6245
  // SDK queue acceptance is delivery to this conversation, not proof that the model read it.
6150
6246
  const delivery = conv.session.sendUserMessage(text, busy ? { deliverAs: "steer" } : undefined);
6247
+ void delivery.finally(() => {
6248
+ if (envelope.requestId)
6249
+ conv.queuedSteeringRequestIds?.delete(envelope.requestId);
6250
+ });
6151
6251
  void delivery.catch((error) => {
6152
6252
  owner.sendNotice({
6153
6253
  type: "notice",
@@ -8044,7 +8144,11 @@ export class ClientSession {
8044
8144
  const currentTokens = this.getEffectiveContextTokens(conv);
8045
8145
  if (currentTokens < cap)
8046
8146
  return false;
8047
- 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);
8048
8152
  return true;
8049
8153
  }
8050
8154
  catch (err) {
@@ -9390,6 +9494,7 @@ export class ClientSession {
9390
9494
  def = {
9391
9495
  ...def,
9392
9496
  execute: async (...args) => {
9497
+ await this.botExecution?.assertWorkspace(cwdOverride ?? this.cwd);
9393
9498
  if (!this.botToolAllowed(def.name, cwdOverride, args[1]))
9394
9499
  throw new Error("Tool is not authorized for this Bot");
9395
9500
  return execute(...args);
@@ -9455,6 +9560,7 @@ export class ClientSession {
9455
9560
  return {
9456
9561
  ...def,
9457
9562
  execute: async (...args) => {
9563
+ await this.botExecution?.assertWorkspace(cwd ?? this.cwd);
9458
9564
  const current = this.executionMcpBridge(cwd ?? this.cwd)?.getTools() ?? [];
9459
9565
  if (!current.includes(tool) || !this.botToolAllowed(tool.name, cwd, args[1]))
9460
9566
  throw new Error("Bot MCP tool authorization expired");
@@ -9843,6 +9949,8 @@ export class ClientSession {
9843
9949
  if (this.botExecution && text.trimStart().startsWith("/"))
9844
9950
  throw new Error("Bot slash commands are disabled");
9845
9951
  const conv = targetConversation ?? this.conv;
9952
+ if (this.botExecution)
9953
+ await this.botExecution.assertWorkspace(conv.cwd);
9846
9954
  this.assertSubagentWorktreeAdmission(conv);
9847
9955
  if (!this.botExecution &&
9848
9956
  conv.session.sessionManager
@@ -10249,6 +10357,8 @@ export class ClientSession {
10249
10357
  // 立即切换会话,若提前置位会被 displaceActive 误判为有消息投递而报错通知。
10250
10358
  startTurnTiming(conv);
10251
10359
  conv.promptInFlight = true;
10360
+ // 用户开始在这条对话里发言:不再是「只是查看」的历史对话,达上限时不得自动移出。
10361
+ conv.viewOnly = false;
10252
10362
  this.flushSnapshot();
10253
10363
  // Attach files as independent nextTurn context messages (asides) so the
10254
10364
  // user message stays clean; they render as separate attachment cards.
@@ -10427,6 +10537,7 @@ export class ClientSession {
10427
10537
  // switches away. (Also bumps the per-project "most recently active"
10428
10538
  // order used by set_cwd.)
10429
10539
  conv.promptedSinceActive = true;
10540
+ conv.viewOnly = false;
10430
10541
  conv.lastActiveAt = Date.now();
10431
10542
  // Fresh run — restart the stall watchdog window.
10432
10543
  conv.lastSdkEventAt = Date.now();
@@ -10459,6 +10570,18 @@ export class ClientSession {
10459
10570
  if (Array.isArray(this.conv.session?._pendingNextTurnMessages)) {
10460
10571
  this.conv.session._pendingNextTurnMessages = [];
10461
10572
  }
10573
+ // 停止时先清空 SDK 队列与本地排队镜像,防止 agent-loop 工具结束后消费排队消息导致写入对话却被中止丢消息(issue #834)
10574
+ try {
10575
+ this.conv.session.clearQueue?.();
10576
+ }
10577
+ catch (err) {
10578
+ console.error("[agent-service] clearQueue failed during abort:", err);
10579
+ }
10580
+ this.conv.queueSteering = [];
10581
+ this.conv.queueFollowUp = [];
10582
+ this.conv.queuedSteeringEntries = [];
10583
+ this.conv.queuedFollowUpEntries = [];
10584
+ this.conv.queuedSteeringRequestIds?.clear();
10462
10585
  const isRunning = this.conversationStreaming(this.conv) || !this.conv.session.isIdle;
10463
10586
  if (!isRunning) {
10464
10587
  this.flushSnapshot();
@@ -10542,6 +10665,7 @@ export class ClientSession {
10542
10665
  if (!current())
10543
10666
  return;
10544
10667
  conv.promptedSinceActive = true;
10668
+ conv.viewOnly = false;
10545
10669
  conv.lastActiveAt = Date.now();
10546
10670
  conv.lastSdkEventAt = Date.now();
10547
10671
  conv.stallNoticed = false;
@@ -11122,6 +11246,8 @@ export class ClientSession {
11122
11246
  // lists and don't consume this project's slots. Subagents don't count
11123
11247
  // (inMemory 后台任务,不占位)。临时会话也不占名额。
11124
11248
  if (!ephemeral) {
11249
+ // 达上限时先按 LRU 收起只查看过的历史对话(不计当前对话的释放:沿用原口径,保守)。
11250
+ this.makeRoomForConversation(this.cwd, 1);
11125
11251
  const openInProject = [...this.convs.values()].filter((c) => c.cwd === this.cwd && !c.isSubagent && !c.isEphemeral).length;
11126
11252
  const maxOpenConversations = getMaxOpenConversations();
11127
11253
  if (openInProject >= maxOpenConversations) {
@@ -11397,25 +11523,21 @@ export class ClientSession {
11397
11523
  * 返回 null = 文件健康或无需处理;返回 repair = 修过,调用方弹提示。
11398
11524
  * #280:顺带修悬空 toolCall(强制重置/崩溃残留的有调用无结果),修过同样弹提示。
11399
11525
  */
11400
- repairTranscriptFileBeforeOpen(filePath) {
11401
- let repair = null;
11526
+ async repairTranscriptFileBeforeOpen(filePath) {
11527
+ let prepared;
11402
11528
  try {
11403
- repair = repairSessionFile(filePath);
11529
+ // 链修复与悬空调用修复共用一次异步读盘;两项健康指纹都命中时不读盘(transcript-prepare.ts)。
11530
+ prepared = await prepareTranscriptForOpen(filePath, this.danglingCauseFor(filePath));
11404
11531
  }
11405
11532
  catch {
11406
11533
  return null;
11407
11534
  }
11408
- if (!repair?.changed) {
11535
+ const repair = prepared.repair;
11536
+ if (!repair)
11537
+ return null;
11538
+ if (!repair.changed) {
11409
11539
  // #280:压缩链健康时仍要查悬空 toolCall(崩溃/强制重置残留)。
11410
- let healed = 0;
11411
- try {
11412
- const n = healDanglingToolCallFile(filePath, this.danglingCauseFor(filePath));
11413
- if (n > 0)
11414
- healed = n;
11415
- }
11416
- catch {
11417
- // best-effort
11418
- }
11540
+ const healed = prepared.healed > 0 ? prepared.healed : 0;
11419
11541
  if (healed <= 0)
11420
11542
  return null;
11421
11543
  this.emit({
@@ -11448,6 +11570,9 @@ export class ClientSession {
11448
11570
  }
11449
11571
  }
11450
11572
  const totalMessages = msgEntries.length;
11573
+ const seeded = this.previewWithSnapshotIds(manager, maxPreview);
11574
+ if (seeded)
11575
+ return { totalMessages, previewMessages: seeded.previewMessages, idSeed: seeded.idSeed };
11451
11576
  const tail = msgEntries.slice(-maxPreview);
11452
11577
  const startOffset = totalMessages - tail.length;
11453
11578
  const previewMessages = [];
@@ -11462,6 +11587,60 @@ export class ClientSession {
11462
11587
  return { totalMessages: 0, previewMessages: [] };
11463
11588
  }
11464
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
+ }
11465
11644
  /**
11466
11645
  * #235:manager+runtime 一起建,链损坏报错则修最近文件后重试一次。
11467
11646
  * SessionManager.open 本身不走 parent 链(真正死循环的是 runtime 初始化里的
@@ -11506,6 +11685,26 @@ export class ClientSession {
11506
11685
  return false;
11507
11686
  }
11508
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
+ }
11509
11708
  maxOpenConversationsNotice(limit) {
11510
11709
  const retain = Boolean(this.settingsSvc?.current.retainFinishedConversations);
11511
11710
  if (retain) {
@@ -11551,12 +11750,33 @@ export class ClientSession {
11551
11750
  // Also retain a parent while any live first-party subagent conversation
11552
11751
  // points at it: dropping an idle in-memory parent orphans the child row
11553
11752
  // (the child vanishes from Running Chats with no result available).
11554
- 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);
11555
11775
  // Ephemeral transcripts have no history fallback: once started, only an
11556
11776
  // explicit close may discard them, even after revisiting without a prompt.
11557
11777
  const retainFinished = (Boolean(conv.isEphemeral) || Boolean(this.settingsSvc?.current.retainFinishedConversations)) &&
11558
11778
  this.isConversationStarted(conv);
11559
- const retained = hasLiveChild ||
11779
+ return (hasLiveChild ||
11560
11780
  retainFinished ||
11561
11781
  shouldRetainActive({
11562
11782
  reviewing: conv.goal.reviewing,
@@ -11574,20 +11794,99 @@ export class ClientSession {
11574
11794
  hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: conv.session.sessionFile }),
11575
11795
  hasPendingWake: () => hasPendingWaitSubscription({ sessionId: conv.session.sessionFile }),
11576
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.`,
11577
11886
  });
11578
- if (retained) {
11579
- conv.listed = true;
11580
- if (conv.promptInFlight && !conv.session.isStreaming) {
11581
- this.emit({
11582
- type: "notice",
11583
- level: "info",
11584
- text: `「${conv.title}」的消息正在投递,已为你保留该对话`,
11585
- textEn: `"${conv.title}" is still sending your message — kept in the running list`,
11586
- });
11587
- }
11588
- return null;
11887
+ this.emitConversations();
11589
11888
  }
11590
- return conv;
11889
+ return !over();
11591
11890
  }
11592
11891
  /** Remove a conversation from the running list and free its runtime. The
11593
11892
  * session stays persisted on disk, so it remains recoverable from the
@@ -11984,6 +12283,7 @@ export class ClientSession {
11984
12283
  }
11985
12284
  // Remember the new workspace (restore target + recent-project entry).
11986
12285
  this.stateStore.remember(this.clientId, abs);
12286
+ this.invalidateProjectsCache();
11987
12287
  void this.pushProjects();
11988
12288
  this.refreshSessionsOnSwitch();
11989
12289
  void this.listFiles(undefined);
@@ -12118,6 +12418,29 @@ export class ClientSession {
12118
12418
  * workspace stays visible; clicking one switches both the conversation and
12119
12419
  * its project (see switchConversation). The client groups the list by cwd.
12120
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
+ }
12121
12444
  emitConversations() {
12122
12445
  const conversations = [];
12123
12446
  // Active parents are normally absent from Running. Keep them visible while
@@ -12153,9 +12476,11 @@ export class ClientSession {
12153
12476
  try {
12154
12477
  const sid = conv.session.sessionId;
12155
12478
  const f = conv.session.sessionFile;
12479
+ const modified = f ? ClientSession.conversationFileMtime(f) : undefined;
12156
12480
  return {
12157
12481
  ...(sid ? { sessionId: sid } : {}),
12158
12482
  ...(f ? { sessionFile: f } : {}),
12483
+ ...(modified ? { modified } : {}),
12159
12484
  };
12160
12485
  }
12161
12486
  catch {
@@ -12241,7 +12566,8 @@ export class ClientSession {
12241
12566
  * 一致),变化的条目由调用方重新解析后经 store 覆盖(也落到最新端)。
12242
12567
  */
12243
12568
  static sessionFileCache = new Map();
12244
- static SESSION_FILE_CACHE_MAX = 512;
12569
+ // 2048:列表模式每项目约 260 个热条目,512 只够两三个项目,来回展开多个项目时会互相挤出、反复全文重解析。
12570
+ static SESSION_FILE_CACHE_MAX = 2048;
12245
12571
  /** sessionFileCache LRU 读取:命中即重插到最新端(续期),未命中返回 undefined。 */
12246
12572
  static sessionFileCacheLookup(key) {
12247
12573
  const entry = ClientSession.sessionFileCache.get(key);
@@ -12263,18 +12589,44 @@ export class ClientSession {
12263
12589
  }
12264
12590
  }
12265
12591
  /** 会话列表缓存(按 cwdKey 隔离,30s TTL)。 */
12592
+ /** complete=false:列表模式只解析了 mtime 最新的一部分文件(见 SESSION_LIST_PARSE_LIMIT),
12593
+ * 搜索 / 按 id 定位等需要全集的调用不能复用它。 */
12266
12594
  static sessionInfosCache = new Map();
12267
12595
  static sessionInfosInFlight = new Map();
12268
12596
  static SESSION_INFO_CACHE_TTL = 30_000;
12269
- 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) {
12270
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;
12271
12617
  const now = Date.now();
12272
12618
  const cwdKey = normalizePathKey(targetCwd);
12273
12619
  const c = ClientSession.sessionInfosCache.get(cwdKey);
12274
- 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))) {
12275
12623
  return c.infos;
12276
12624
  }
12277
- 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);
12278
12630
  if (inFlight)
12279
12631
  return inFlight;
12280
12632
  const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
@@ -12328,25 +12680,41 @@ export class ClientSession {
12328
12680
  }));
12329
12681
  const validStats = stats.filter((s) => s !== null);
12330
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;
12331
12688
  const results = await mapSessionsConcurrent(validStats, async (file) => {
12332
12689
  const cached = ClientSession.sessionFileCacheLookup(file.path);
12333
12690
  if (cached && cached.mtime === file.mtime && cached.size === file.size) {
12691
+ if (isOwn(cached.info))
12692
+ ownCount++;
12334
12693
  return cached.info;
12335
12694
  }
12336
- // 列表路径不收集转录全文(issue #440)——全文只在搜索时按需加载
12337
- const info = await parseSessionInfoFast(file.path, file.mtime);
12338
- 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) {
12339
12705
  ClientSession.sessionFileCacheStore(file.path, {
12340
12706
  mtime: file.mtime,
12341
12707
  size: file.size,
12342
12708
  info,
12709
+ scan: scanned.state,
12343
12710
  });
12711
+ if (isOwn(info))
12712
+ ownCount++;
12344
12713
  }
12345
12714
  return info;
12346
12715
  });
12347
12716
  const validInfos = results.filter((info) => info !== null);
12348
- const baseDirKey = normalizePathKey(sessionBaseDir);
12349
- const ownInfos = validInfos.filter((info) => info.cwd !== "" && (normalizePathKey(info.cwd) === cwdKey || normalizePathKey(info.cwd) === baseDirKey));
12717
+ const ownInfos = validInfos.filter(isOwn);
12350
12718
  const seenIds = new Set();
12351
12719
  const dedupedOwnInfos = [];
12352
12720
  for (const info of ownInfos) {
@@ -12359,7 +12727,19 @@ export class ClientSession {
12359
12727
  }
12360
12728
  const candidates = dedupedOwnInfos;
12361
12729
  candidates.sort((a, b) => b.modified.getTime() - a.modified.getTime());
12362
- 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
+ }
12363
12743
  return candidates;
12364
12744
  }
12365
12745
  catch {
@@ -12385,7 +12765,7 @@ export class ClientSession {
12385
12765
  combined.push({ ...s, allMessagesText: "" });
12386
12766
  }
12387
12767
  combined.sort((a, b) => b.modified.getTime() - a.modified.getTime());
12388
- ClientSession.sessionInfosCache.set(cwdKey, { infos: combined, at: Date.now() });
12768
+ ClientSession.sessionInfosCache.set(cwdKey, { infos: combined, at: Date.now(), complete: true });
12389
12769
  return combined;
12390
12770
  }
12391
12771
  catch {
@@ -12393,10 +12773,10 @@ export class ClientSession {
12393
12773
  }
12394
12774
  }
12395
12775
  finally {
12396
- ClientSession.sessionInfosInFlight.delete(cwdKey);
12776
+ ClientSession.sessionInfosInFlight.delete(flightKey);
12397
12777
  }
12398
12778
  })();
12399
- ClientSession.sessionInfosInFlight.set(cwdKey, run);
12779
+ ClientSession.sessionInfosInFlight.set(flightKey, run);
12400
12780
  return run;
12401
12781
  }
12402
12782
  /** Session files on disk changed (delete / new-transcript) — drop the brief
@@ -12426,40 +12806,79 @@ export class ClientSession {
12426
12806
  if (this.sessionsRequested)
12427
12807
  void this.refreshSessions();
12428
12808
  }
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) {
12832
+ const showForkedParents = this.settingsSvc.current.showForkedParentSessions === true;
12833
+ const visibleInfos = filterForkedParentSessions(infos, showForkedParents);
12834
+ const sessions = new Map();
12835
+ for (const s of visibleInfos) {
12836
+ const isPinned = this.stateStore?.isSessionPinned(targetCwd, s.path);
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);
12842
+ sessions.set(s.path, {
12843
+ path: s.path,
12844
+ ...(s.id ? { sessionId: s.id } : {}),
12845
+ cwd: targetCwd,
12846
+ name: s.name,
12847
+ displayName,
12848
+ firstMessage,
12849
+ messageCount: s.messageCount,
12850
+ modified: s.modified.getTime(),
12851
+ source: "web",
12852
+ ...(isPinned ? { pinned: true } : {}),
12853
+ ...(s.parentSessionPath ? { parentSessionPath: s.parentSessionPath } : {}),
12854
+ });
12855
+ }
12856
+ const sorted = [...sessions.values()].sort((a, b) => b.modified - a.modified);
12857
+ return Number.isFinite(limit) ? sorted.slice(0, limit) : sorted;
12858
+ }
12429
12859
  async pushSessions() {
12430
12860
  if (!this.sessionsRequested)
12431
12861
  return;
12862
+ const cwd = this.cwd;
12432
12863
  try {
12433
12864
  // Sessions live in the SDK default per-project dir
12434
12865
  // (<agentDir>/sessions/--<cwd>--/), the same files the pi CLI/TUI
12435
12866
  // use — one listing covers every conversation of the current folder.
12436
- const infos = await this.loadSessionInfos();
12437
- // 默认隐藏「被 fork 掉的父会话」(仅保留每条 fork 链最新的链尾会话);
12438
- // 开启 showForkedParentSessions 时保留全部会话(全文搜索 searchSessions 始终保留全部)。
12439
- const showForkedParents = this.settingsSvc.current.showForkedParentSessions === true;
12440
- const visibleInfos = filterForkedParentSessions(infos, showForkedParents);
12441
- const sessions = new Map();
12442
- for (const s of visibleInfos) {
12443
- const isPinned = this.stateStore?.isSessionPinned(this.cwd, s.path);
12444
- const displayName = s.name?.trim() || (s.firstMessage ? s.firstMessage.trim().replace(/\s+/g, " ") : undefined);
12445
- sessions.set(s.path, {
12446
- path: s.path,
12447
- ...(s.id ? { sessionId: s.id } : {}),
12448
- name: s.name,
12449
- displayName,
12450
- firstMessage: s.firstMessage,
12451
- messageCount: s.messageCount,
12452
- modified: s.modified.getTime(),
12453
- source: "web",
12454
- ...(isPinned ? { pinned: true } : {}),
12455
- ...(s.parentSessionPath ? { parentSessionPath: s.parentSessionPath } : {}),
12456
- });
12457
- }
12458
- const sorted = [...sessions.values()].sort((a, b) => b.modified - a.modified).slice(0, 200); // newest first — the panel shows recent history
12459
- this.emit({ type: "sessions", sessions: sorted });
12867
+ const { sessions, hasMore } = await this.sessionListPayload(cwd);
12868
+ this.emit({ type: "sessions", sessions, cwd, ...(hasMore ? { hasMore: true } : {}) });
12460
12869
  }
12461
12870
  catch {
12462
- this.emit({ type: "sessions", sessions: [] });
12871
+ this.emit({ type: "sessions", sessions: [], cwd });
12872
+ }
12873
+ }
12874
+ /** Push the persisted session list for a specific project directory (on demand, e.g. expanding an unopened project). */
12875
+ async pushSessionsForCwd(targetCwd) {
12876
+ try {
12877
+ const { sessions, hasMore } = await this.sessionListPayload(targetCwd);
12878
+ this.emit({ type: "sessions", sessions, cwd: targetCwd, ...(hasMore ? { hasMore: true } : {}) });
12879
+ }
12880
+ catch {
12881
+ this.emit({ type: "sessions", sessions: [], cwd: targetCwd });
12463
12882
  }
12464
12883
  }
12465
12884
  /** Remove an entry from the client's recent-project list (UI state only, or destroy if sandbox). */
@@ -12516,7 +12935,7 @@ export class ClientSession {
12516
12935
  }
12517
12936
  if (holder) {
12518
12937
  // Same source the history panel uses (refreshSessions): newest first.
12519
- const infos = await this.loadSessionInfos();
12938
+ const infos = await this.loadSessionInfos(undefined, { listOnly: true });
12520
12939
  const next = infos
12521
12940
  .filter((s) => resolve(s.path) !== abs)
12522
12941
  .sort((a, b) => b.modified.getTime() - a.modified.getTime())[0];
@@ -13362,8 +13781,19 @@ export class ClientSession {
13362
13781
  /* ignore */
13363
13782
  }
13364
13783
  if (sid === wantSid || conv.id === wantSid) {
13784
+ if (independent !== undefined)
13785
+ this.setConversationIndependent(conv.id, independent);
13365
13786
  await this.switchConversation(conv.id);
13366
13787
  outcome = "reused";
13788
+ this.emit({
13789
+ type: "transition_progress",
13790
+ kind: "session",
13791
+ target: wantSid,
13792
+ phase: "done",
13793
+ progress: 100,
13794
+ text: "会话加载完成",
13795
+ textEn: "Session loaded",
13796
+ });
13367
13797
  return;
13368
13798
  }
13369
13799
  }
@@ -13468,14 +13898,20 @@ export class ClientSession {
13468
13898
  });
13469
13899
  await new Promise((r) => setImmediate(r));
13470
13900
  timing.mark("resolve-and-ownership");
13471
- this.repairTranscriptFileBeforeOpen(targetPath);
13901
+ await this.repairTranscriptFileBeforeOpen(targetPath);
13472
13902
  timing.mark("repair");
13473
- const sessionManager = SessionManager.open(targetPath);
13903
+ // 异步读盘 + 分时片解析,不再同步阻塞事件循环(session-open.ts,失败回退 SessionManager.open)
13904
+ const sessionManager = await openSessionManagerAsync(targetPath);
13474
13905
  timing.mark("sdk-open");
13475
13906
  calibrateSessionLeaf(sessionManager);
13476
13907
  timing.mark("branch-calibration");
13908
+ // 预先分配对话 id 并随预览下发:浏览器用它 + 会话文件组成与首个快照相同的会话键,
13909
+ // 预览→快照只替换数据、不重挂载消息列表(C4)。打开失败时 id 作废,无副作用。
13910
+ const conversationId = this.nextConversationId();
13911
+ let previewIdSeed;
13477
13912
  {
13478
- const { totalMessages, previewMessages } = this.extractTranscriptPreview(sessionManager, 16);
13913
+ const { totalMessages, previewMessages, idSeed } = this.extractTranscriptPreview(sessionManager, 16);
13914
+ previewIdSeed = idSeed;
13479
13915
  this.emit({
13480
13916
  type: "transition_progress",
13481
13917
  kind: "session",
@@ -13490,6 +13926,8 @@ export class ClientSession {
13490
13926
  : "Transcript ready, mounting agent runtime…",
13491
13927
  totalMessages,
13492
13928
  ...(previewMessages.length > 0 ? { previewMessages } : {}),
13929
+ // 仅当预览 id 与快照一致时才下发:浏览器据此决定是否沿用同一个消息列表实例
13930
+ ...(idSeed ? { conversationId, sessionFile: targetPath } : {}),
13493
13931
  });
13494
13932
  await new Promise((r) => setImmediate(r));
13495
13933
  }
@@ -13497,7 +13935,13 @@ export class ClientSession {
13497
13935
  const rawSessionCwd = sessionManager.getCwd();
13498
13936
  const targetCwd = restoreWorkspaceUriFromSessionDir(rawSessionCwd);
13499
13937
  const runtimeCwd = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
13500
- 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
+ }
13501
13945
  openedTerminals = this.makeTerminalManager(conversationId, targetCwd);
13502
13946
  openedRuntime = await createAgentSessionRuntime(this.makeRuntimeFactory(openedTerminals, undefined, conversationId), {
13503
13947
  cwd: runtimeCwd,
@@ -13514,7 +13958,10 @@ export class ClientSession {
13514
13958
  1 -
13515
13959
  (displaced?.cwd === targetCwd && !displaced?.isSubagent && !displaced?.isEphemeral ? 1 : 0);
13516
13960
  const maxOpenConversations = getMaxOpenConversations();
13517
- if (openInProject > maxOpenConversations) {
13961
+ // 兜底复检:runtime 构建期间(await)别处可能新开了对话。仍超额时先尝试 LRU 收起,
13962
+ // 依然不行才放弃。displaced 此刻仍是 active(尚未移除),不会被收起。
13963
+ if (openInProject > maxOpenConversations &&
13964
+ !this.makeRoomForConversation(targetCwd, 1, displaced?.cwd === targetCwd && !displaced?.isSubagent)) {
13518
13965
  // displaceActive() may have promoted a streaming conversation into the
13519
13966
  // running list. Roll that presentation-only mutation back because no
13520
13967
  // switch will take place.
@@ -13523,25 +13970,11 @@ export class ClientSession {
13523
13970
  await openedRuntime.dispose();
13524
13971
  openedRuntime = null;
13525
13972
  openedTerminals = null;
13526
- this.emit({
13527
- type: "transition_progress",
13528
- kind: "session",
13529
- target: targetPath,
13530
- phase: "error",
13531
- progress: 100,
13532
- text: `当前项目运行的对话已达上限(${maxOpenConversations} 个)`,
13533
- textEn: `Max open conversations (${maxOpenConversations}) reached`,
13534
- });
13535
- const notice = this.maxOpenConversationsNotice(maxOpenConversations);
13536
- this.emit({
13537
- type: "notice",
13538
- level: "warning",
13539
- text: notice.text,
13540
- textEn: notice.textEn,
13541
- });
13973
+ this.emitMaxOpenConversationsReached(targetPath);
13542
13974
  return;
13543
13975
  }
13544
13976
  const conv = this.makeConversation(openedRuntime, conversationId, openedTerminals);
13977
+ this.seedConversationIds(conv, previewIdSeed);
13545
13978
  if (independent !== undefined) {
13546
13979
  conv.session.sessionManager.appendCustomEntry("webui/independent", { independent });
13547
13980
  conv.independent = independent;
@@ -13550,9 +13983,12 @@ export class ClientSession {
13550
13983
  // switches away without sending a new message.
13551
13984
  conv.listed = true;
13552
13985
  conv.promptedSinceActive = true;
13986
+ // 只是打开查看:达上限时可按 LRU 自动收起(发言即清除,见 prompt 路径)。
13987
+ conv.viewOnly = true;
13553
13988
  if (this.stateStore?.isSessionPinned(targetCwd, targetPath)) {
13554
13989
  conv.pinned = true;
13555
13990
  conv.listed = true;
13991
+ conv.viewOnly = false;
13556
13992
  }
13557
13993
  this.noticeInterruptedCompaction(conv);
13558
13994
  this.convs.set(conv.id, conv);
@@ -14197,20 +14633,22 @@ export class ClientSession {
14197
14633
  */
14198
14634
  async pushProjects() {
14199
14635
  const now = Date.now();
14200
- const cached = ClientSession.projectsCache;
14201
- // TTL 命中(或已建立过项目缓存):直接把当前 cwd 合并重排并续期,
14202
- // 避免切换工作区时因为刚好跨过 60s TTL 而触发全盘 30 个会话子目录重扫。
14203
- // 已建立过缓存:emit 本客户端的派生视图即可,**绝不把派生结果写回静态缓存**
14204
- // ——withCurrentCwd 注入了本客户端的 cwd/lastUsed/removedKeys 过滤与沙盒
14205
- // 元数据,写回会把 A 客户端的视图固化给 B(静态缓存跨客户端共享);
14206
- // 底层超过 TTL 后后台重扫一次,磁盘上新工作区不会被永久挡在列表外。
14207
- if (cached) {
14208
- this.emit({ type: "projects", projects: this.withCurrentCwd(cached.projects, now) });
14209
- if (now - cached.at >= ClientSession.PROJECTS_CACHE_TTL)
14210
- void this.ensureProjectsCache(false);
14211
- 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) });
14212
14651
  }
14213
- await this.ensureProjectsCache(true);
14214
14652
  }
14215
14653
  /**
14216
14654
  * 确保静态缓存有基底(单飞:已有扫描在跑则搭车,不并发扫两遍盘)。
@@ -14278,12 +14716,10 @@ export class ClientSession {
14278
14716
  list = validProjects;
14279
14717
  }
14280
14718
  else if (validProjects.some((p) => normalizePathKey(p.path) === currentKey)) {
14281
- list = validProjects
14282
- .map((p) => (normalizePathKey(p.path) === currentKey && p.lastUsed < now ? { ...p, lastUsed: now } : p))
14283
- .sort((a, b) => b.lastUsed - a.lastUsed);
14719
+ list = validProjects.map((p) => normalizePathKey(p.path) === currentKey ? { ...p, lastUsed: Math.max(p.lastUsed, now) } : p);
14284
14720
  }
14285
14721
  else {
14286
- list = [{ path: this.cwd, lastUsed: now }, ...validProjects].slice(0, 20);
14722
+ list = [{ path: this.cwd, lastUsed: now }, ...validProjects].slice(0, RECENT_PROJECTS_MAX);
14287
14723
  }
14288
14724
  // 确保所有仍存活的注册沙盒也出现在列表里,并附带 sandbox 元数据
14289
14725
  const existingKeys = new Set(list.map((p) => normalizePathKey(p.path)));
@@ -14294,13 +14730,13 @@ export class ClientSession {
14294
14730
  existingKeys.add(k);
14295
14731
  }
14296
14732
  }
14297
- return list
14733
+ return (list
14298
14734
  .map((p) => {
14299
14735
  const sbx = this.sandboxes.getByCwd(p.path);
14300
14736
  return sbx ? { ...p, sandbox: sbx } : p;
14301
14737
  })
14302
- .sort((a, b) => b.lastUsed - a.lastUsed)
14303
- .slice(0, 25);
14738
+ // 额外 5 个名额留给注册沙盒(原 30 + 5 口径)
14739
+ .slice(0, RECENT_PROJECTS_MAX + 5));
14304
14740
  }
14305
14741
  /** 最近项目缓存失效(用户显式移除项目后,下一次推送必须重扫)。 */
14306
14742
  invalidateProjectsCache() {
@@ -14573,7 +15009,7 @@ export class ClientSession {
14573
15009
  }
14574
15010
  else {
14575
15011
  // 冷切换的 runtime 创建要 1~2s(扫技能/扩展)—— 先回一条 ack +
14576
- // 流式进度 + 快照,点击立即呈现阶段进度与转录预览;落地后再推完整全量。
15012
+ // 流式进度,点击立即呈现阶段进度与转录预览;落地后再推完整全量。
14577
15013
  this.emit({
14578
15014
  type: "transition_progress",
14579
15015
  kind: "cwd",
@@ -14583,13 +15019,12 @@ export class ClientSession {
14583
15019
  text: openRecent ? `正在同步目录与检查最近会话:${abs}` : `正在切换工作目录:${abs}`,
14584
15020
  textEn: openRecent ? `Validating workspace & checking recent session: ${abs}` : `Switching workspace: ${abs}`,
14585
15021
  });
14586
- this.flushSnapshot();
14587
15022
  // 让出事件循环,确保首帧进度在同步磁盘扫描前真正发往浏览器
14588
15023
  await new Promise((r) => setImmediate(r));
14589
15024
  // 在耗时的 runtime 初始化期间,并行预热目标项目的会话列表缓存
14590
15025
  if (this.sessionsRequested) {
14591
15026
  ClientSession.sessionInfosCache.delete(normalizePathKey(abs));
14592
- void this.loadSessionInfos(abs).catch(() => { });
15027
+ void this.loadSessionInfos(abs, { listOnly: true }).catch(() => { });
14593
15028
  }
14594
15029
  // First visit to this project: resume its most recent session —
14595
15030
  // unless that transcript is still held on another client (#145):