pi-web-ui 0.104.4 → 0.105.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 (52) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +2 -2
  4. package/bin/pi-web-ui.mjs +9 -3
  5. package/dist/server/agent-service-daemon.js +7 -7
  6. package/dist/server/agent-service.js +497 -109
  7. package/dist/server/approval-default-rules.js +15 -0
  8. package/dist/server/client-state.js +29 -0
  9. package/dist/server/dispatch-domain-handlers.js +35 -7
  10. package/dist/server/dsh/dsh-agent-service.js +88 -33
  11. package/dist/server/dsh/dsh-serialize.js +16 -1
  12. package/dist/server/ensure-bash.js +7 -2
  13. package/dist/server/file-transfer-routes.js +114 -1
  14. package/dist/server/index.js +347 -68
  15. package/dist/server/load-tools-tool.js +2 -1
  16. package/dist/server/locales.js +5 -0
  17. package/dist/server/markers/marker.js +28 -0
  18. package/dist/server/mcp-bridge.js +20 -6
  19. package/dist/server/pkg-info.js +69 -0
  20. package/dist/server/plugin-facilities.js +18 -9
  21. package/dist/server/plugin-manifest-validate.js +3 -0
  22. package/dist/server/plugin-updater.js +11 -5
  23. package/dist/server/plugins.js +3 -12
  24. package/dist/server/present-files-tool.js +47 -1
  25. package/dist/server/preset-fields.js +14 -0
  26. package/dist/server/preset-share.js +5 -12
  27. package/dist/server/prompt-composer.js +1 -1
  28. package/dist/server/remote-ssh-service.js +158 -5
  29. package/dist/server/serialize.js +15 -4
  30. package/dist/server/session-parser.js +138 -2
  31. package/dist/server/settings-service.js +19 -0
  32. package/dist/server/terminals.js +7 -1
  33. package/dist/server/text-quote.js +64 -2
  34. package/dist/server/tool-manager.js +10 -0
  35. package/dist/server/tool-prompts.js +1 -0
  36. package/dist/server/update-check.js +98 -24
  37. package/dist/server/workspace-snapshot.js +251 -13
  38. package/dist/server/worktree-service.js +262 -0
  39. package/dist/server/worktree-tool.js +173 -0
  40. package/package.json +3 -1
  41. package/plugin-sdk/index.d.ts +14 -1
  42. package/themes/zhujian-dark.css +16 -4
  43. package/themes/zhujian.css +16 -4
  44. package/themes/zhupi-dark.css +16 -4
  45. package/themes/zhupi.css +16 -4
  46. package/web/dist/assets/{TerminalPanel-B7x99tkg.js → TerminalPanel-B9exeXrl.js} +1 -1
  47. package/web/dist/assets/index-BQC6lADz.css +1 -0
  48. package/web/dist/assets/index-D79IKG33.js +690 -0
  49. package/web/dist/index.html +21 -21
  50. package/web/dist/sw.js +1 -1
  51. package/web/dist/assets/index-DOrLcjLY.js +0 -680
  52. package/web/dist/assets/index-_H2BS7OX.css +0 -1
@@ -29,6 +29,7 @@ import { Type } from "typebox";
29
29
  import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
30
30
  import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
31
31
  import { checkPluginUpdates } from "./plugin-updater.js";
32
+ import { getAppVersion } from "./pkg-info.js";
32
33
  import { isBundledInUse, sdkCopies } from "./sdk-origin.js";
33
34
  import { hasActiveSubagentRun, hasPendingWaitSubscription, hasRunningBackgroundTask, shouldRetainActive, } from "./wait-subscription-scan.js";
34
35
  import { COMPACTION_PENDING_TYPE, looksLikeChainCorruption, makeCompactionMarkerId, repairSessionFile, } from "./compaction-markers.js";
@@ -54,7 +55,7 @@ import { ApprovalRulesStore, extractTargetPath } from "./approval-rules.js";
54
55
  import { ComposerDraftsStore } from "./composer-drafts.js";
55
56
  import { SandboxManager, evaluateSandboxJail, isSameOrSubpath, withSandboxJailGate } from "./sandbox-service.js";
56
57
  import { readPermissionFromSession } from "./permission-preset.js";
57
- import { createWorkspaceSnapshot, restoreWorkspaceSnapshot, findMatchingWorkspaceSnapshot, } from "./workspace-snapshot.js";
58
+ import { createWorkspaceSnapshot, restoreWorkspaceSnapshot, findMatchingWorkspaceSnapshot, readWorkspaceSnapshotsFromSession, appendWorkspaceSnapshotToSession, withWorkspaceSnapshotGate, } from "./workspace-snapshot.js";
58
59
  import { createScheduleToolHost, createConversationReadHost, createClaimToolHost, createCompactContextHost, createSkillToolHost, } from "./tool-host-factories.js";
59
60
  import { toSubagentSnapshot, listSubagentSnapshots, subagentRunOutcome, roleOutcomeOf, countActiveSubagents, } from "./subagent-helpers.js";
60
61
  import { resolveUserMessageEntryId, resolveConversationMessageEntry } from "./message-entry-resolver.js";
@@ -106,9 +107,11 @@ import { makePatchTool } from "./patch-tool.js";
106
107
  import { makeLspTool } from "./lsp-tool.js";
107
108
  import { makeMcpManageTool } from "./mcp-agent-tool.js";
108
109
  import { makeSandboxTool } from "./sandbox-tool.js";
110
+ import { makeWorktreeTool, WORKTREE_TOOL_NAME } from "./worktree-tool.js";
111
+ import { getWorktreeContext, removeWorktree, normalizeWirePath } from "./worktree-service.js";
109
112
  import { sameSessionFile } from "./scheduler-tasks.js";
110
113
  import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
111
- import { formatQuotedPrompt, readTextQuote } from "./text-quote.js";
114
+ import { formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt } from "./text-quote.js";
112
115
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
113
116
  import { generateScmCommitMessage } from "./scm-commitmsg.js";
114
117
  import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, estimatePromptTokens, renderPromptTemplate, resolveSectionTexts, splitExtensionWrap, } from "./prompt-composer.js";
@@ -211,7 +214,7 @@ import { RUN_TASK_CAP, RUN_ARGS_CAP, RUN_RESULT_CAP, getMaxOpenConversations, ge
211
214
  export { workspacePath };
212
215
  import { MAX_TRANSCRIPT_SCAN_BYTES, MAX_SEARCH_TEXT_CHARS, sessionMatchesMetadata, messageSearchText, collectSessionAnchors, piSessionsRoot, isInsideSessionsDir, readCwdFromSessionHeader, } from "./session-search.js";
213
216
  export { piSessionsRoot, isInsideSessionsDir };
214
- import { discoverRecentProjectsFromDisk, parseSessionInfoFast } from "./session-parser.js";
217
+ import { discoverRecentProjectsFromDisk, filterForkedParentSessions, findMostRecentSessionFileFast, parseSessionInfoFast, } from "./session-parser.js";
215
218
  import { pickAdoptableOrphan, sameCwd } from "./orphan-manager.js";
216
219
  export { pickAdoptableOrphan, sameCwd };
217
220
  import { processTreeKillPlan, resolveCwdTarget } from "./process-utils.js";
@@ -728,6 +731,9 @@ export class ClientSession {
728
731
  // Do not stream it into the active xterm; push the retained window on switch.
729
732
  if (msg.type === "terminal_output" && conversationId !== this.activeId)
730
733
  return;
734
+ if (msg.type === "terminal_exit") {
735
+ this.updatesAllCache = null;
736
+ }
731
737
  if (msg.type === "terminal_output" || msg.type === "terminal_exit" || msg.type === "terminal_list") {
732
738
  this.emit({ ...msg, conversationId });
733
739
  return;
@@ -979,8 +985,11 @@ export class ClientSession {
979
985
  });
980
986
  continue;
981
987
  }
982
- if (name === LOAD_TOOLS_TOOL_NAME) {
983
- rejected.push({ name, reason: pick(lang, "常驻工具,无需加载", "always available", "loadtools.always") });
988
+ if (name === LOAD_TOOLS_TOOL_NAME || LAZY_CORE_TOOL_NAMES.includes(name)) {
989
+ rejected.push({
990
+ name,
991
+ reason: pick(lang, "常驻核心工具,无需加载", "always available without loading", "loadtools.always"),
992
+ });
984
993
  continue;
985
994
  }
986
995
  if (set.has(name)) {
@@ -1024,8 +1033,12 @@ export class ClientSession {
1024
1033
  * automatically mark it as loaded so subsequent turns track it as fully active.
1025
1034
  */
1026
1035
  autoActivateToolIfLoadable(session, conv, name) {
1027
- if (!this.lazyLoadingOn() || !name || name === LOAD_TOOLS_TOOL_NAME)
1036
+ if (!this.lazyLoadingOn() ||
1037
+ !name ||
1038
+ name === LOAD_TOOLS_TOOL_NAME ||
1039
+ LAZY_CORE_TOOL_NAMES.includes(name)) {
1028
1040
  return;
1041
+ }
1029
1042
  const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
1030
1043
  if (loaded.has(name))
1031
1044
  return;
@@ -1528,6 +1541,8 @@ export class ClientSession {
1528
1541
  drafts;
1529
1542
  /** 隔离沙盒项目管理器(全局共享,<dataDir>/sandboxes/registry.json)。 */
1530
1543
  sandboxes;
1544
+ /** 当前工作区关联的 Git 工作树元数据(用于顶栏横幅与 AI 工具同步)。 */
1545
+ worktreeInfo = null;
1531
1546
  /** 内置标记服务(todo/notify/svc/rename 等,可全局/分组开关)。 */
1532
1547
  markerSvc;
1533
1548
  // -----------------------------------------------------------------------
@@ -1639,6 +1654,9 @@ export class ClientSession {
1639
1654
  onGoalModeDisabled: () => {
1640
1655
  void this.goalSvc.stopAllGoals();
1641
1656
  },
1657
+ onSessionsFilterChanged: () => {
1658
+ void this.pushSessions();
1659
+ },
1642
1660
  getMcpServers: () => this.listMcpServers(),
1643
1661
  }, this.subagentTemplates, this.approvalRules);
1644
1662
  this.goalSvc = new GoalService({
@@ -1836,7 +1854,7 @@ export class ClientSession {
1836
1854
  cwd: sessionBaseDir,
1837
1855
  agentDir,
1838
1856
  sessionManager: m,
1839
- }), async () => (await SessionManager.list(sessionBaseDir))[0]?.path);
1857
+ }), () => findMostRecentSessionFileFast(sessionBaseDir, cwd));
1840
1858
  const runtime = opened.runtime;
1841
1859
  if (opened.repair) {
1842
1860
  for (const n of cs.transcriptRepairNotices(opened.repair))
@@ -1948,6 +1966,7 @@ export class ClientSession {
1948
1966
  // best effort
1949
1967
  }
1950
1968
  }
1969
+ void cs.refreshWorktreeInfo();
1951
1970
  return cs;
1952
1971
  }
1953
1972
  /**
@@ -2239,7 +2258,7 @@ export class ClientSession {
2239
2258
  // P1-5:bash/read 包插件拦截(pre 拒/问即拦、post 脱敏补上下文;
2240
2259
  // 未注入 toolGuard 时 withToolGuard 原样返回,零开销)。
2241
2260
  // 权限沙箱拦截(只读模式拦截终端执行)。
2242
- wrapBashToolWithPermission(withToolGuard(makeAdaptiveBashTool(
2261
+ wrapBashToolWithPermission(withToolGuard(withWorkspaceSnapshotGate(makeAdaptiveBashTool(
2243
2262
  // issue #91:bash 返回按客户端 UI 语言出中英(英文默认)。
2244
2263
  makeKillableBashTool(effectiveCwd, this.bashKills, () => this.getLang()), makeTerminalBashTool(terminals, {
2245
2264
  cwd: effectiveCwd,
@@ -2253,7 +2272,7 @@ export class ClientSession {
2253
2272
  lang: () => this.getLang(),
2254
2273
  }),
2255
2274
  // 设置关 → 原生 bash;开 → 终端 bash。
2256
- () => this.settingsSvc.current.terminalBash), {
2275
+ () => this.settingsSvc.current.terminalBash), () => this.awaitPendingWorkspaceSnapshot(ownerId)), {
2257
2276
  toolName: "bash",
2258
2277
  guard: this.lateToolGuard,
2259
2278
  conversationId: () => ownerId,
@@ -2301,7 +2320,7 @@ export class ClientSession {
2301
2320
  }
2302
2321
  return {};
2303
2322
  },
2304
- }),
2323
+ }).map((tool) => withWorkspaceSnapshotGate(tool, () => this.awaitPendingWorkspaceSnapshot(ownerId))),
2305
2324
  // read / write / edit 三处覆盖**不在这里注册**:创建时的 customTools 恒胜、与
2306
2325
  // 扩展加载顺序无关,直接塞进来会静默顶掉第三方扩展注册的同名工具(见
2307
2326
  // tool-overrides.ts);它们改在会话建好后由 installToolOverrides 注入。
@@ -2422,6 +2441,14 @@ export class ClientSession {
2422
2441
  askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category),
2423
2442
  getConversationId: () => ownerId,
2424
2443
  }, () => this.getLang()),
2444
+ // Git 工作树管理工具(worktree:list/create/switch/remove)。
2445
+ makeWorktreeTool({
2446
+ getCwd: () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? effectiveCwd,
2447
+ setCwd: (newCwd) => this.setCwd(newCwd),
2448
+ onWorktreeChanged: async () => {
2449
+ await this.refreshWorktreeInfo();
2450
+ },
2451
+ }, () => this.getLang()),
2425
2452
  ].map((t) =>
2426
2453
  // 目标审查闸门在最外层(理由最贴合此刻);插件工具也在这个数组里,
2427
2454
  // 创建时注册的同样被闸门覆盖(后续动态补入的走 syncPluginTools,与
@@ -2494,11 +2521,12 @@ export class ClientSession {
2494
2521
  lastMessagesArray: [],
2495
2522
  queueSteering: [],
2496
2523
  queueFollowUp: [],
2524
+ queuedImages: new Map(),
2497
2525
  toolStartTimes: new Map(),
2498
2526
  toolPendingArgs: new Map(),
2499
2527
  activeToolCalls: new Map(),
2500
2528
  toolWatchdogs: new Map(),
2501
- workspaceSnapshots: [],
2529
+ workspaceSnapshots: readWorkspaceSnapshotsFromSession(runtime.session.sessionManager),
2502
2530
  };
2503
2531
  this.restorePlan(conv);
2504
2532
  return conv;
@@ -3415,6 +3443,14 @@ export class ClientSession {
3415
3443
  case "queue_update":
3416
3444
  conv.queueSteering = [...event.steering];
3417
3445
  conv.queueFollowUp = [...event.followUp];
3446
+ if (conv.queuedImages && conv.queuedImages.size > 0) {
3447
+ const allQueued = new Set([...event.steering, ...event.followUp]);
3448
+ for (const key of conv.queuedImages.keys()) {
3449
+ if (!allQueued.has(key)) {
3450
+ conv.queuedImages.delete(key);
3451
+ }
3452
+ }
3453
+ }
3418
3454
  break;
3419
3455
  // 手动 /compact 或阈值/溢出自动压缩开始——常驻进度条(快照 compaction
3420
3456
  // 字段),而不是一次性 toast(toast 几秒就消失,而摘要生成可能持续
@@ -3620,6 +3656,12 @@ export class ClientSession {
3620
3656
  }
3621
3657
  // 本轮真正结束且不再重试:立即向客户端广播最新会话状态(流式状态及时复位)
3622
3658
  if (!event.willRetry) {
3659
+ if (conv.queueSteering.length === 0 && conv.queueFollowUp.length === 0) {
3660
+ conv.queuedImages?.clear();
3661
+ if (Array.isArray(conv.session?._pendingNextTurnMessages)) {
3662
+ conv.session._pendingNextTurnMessages = [];
3663
+ }
3664
+ }
3623
3665
  this.emitConversations();
3624
3666
  }
3625
3667
  break;
@@ -3662,6 +3704,14 @@ export class ClientSession {
3662
3704
  // 每条 assistant 气泡流式结束 → 立即解析其中的内联标记:每个气泡各自
3663
3705
  // 生效(不再等整轮 agent_end),同一轮里先前消息的标记也不再丢。
3664
3706
  const mm = event.message;
3707
+ if (mm?.role === "user") {
3708
+ // 用户消息定稿(无论是空闲首轮提问,还是流式期间从 steer/followUp 队列出队落盘):
3709
+ // SDK 在 _emit(message_end) 返回后的同一同步 tick 内执行 sessionManager.appendMessage,
3710
+ // 因此在微任务里即可精确拿到本条用户消息的 entryId 并异步绑定工作区影子快照,
3711
+ // 既不阻塞流式入队与 UI 快照推送,又保证插队/排队轮次也有独立的写工具前快照。
3712
+ this.bindOrStartWorkspaceSnapshotForUserMessage(conv);
3713
+ break;
3714
+ }
3665
3715
  if (mm?.role !== "assistant")
3666
3716
  break;
3667
3717
  // 非 error 的 assistant 定稿 = 重试周期结束(与 SDK 重置
@@ -3750,11 +3800,16 @@ export class ClientSession {
3750
3800
  // 全量),它在左栏的运行态由 emitConversations 走另一条通道。
3751
3801
  if (conv.id !== this.conv.id)
3752
3802
  return;
3803
+ const eventMsgRole = event.type === "message_start" || event.type === "message_end"
3804
+ ? event.message?.role
3805
+ : undefined;
3753
3806
  if (event.type === "agent_end" ||
3754
3807
  event.type === "tool_execution_end" ||
3755
3808
  event.type === "compaction_end" ||
3756
3809
  event.type === "auto_retry_start" ||
3757
- event.type === "auto_retry_end") {
3810
+ event.type === "auto_retry_end" ||
3811
+ event.type === "queue_update" ||
3812
+ eventMsgRole === "user") {
3758
3813
  this.flushSnapshot();
3759
3814
  }
3760
3815
  else {
@@ -4023,6 +4078,7 @@ export class ClientSession {
4023
4078
  // `{...ui, ...d.state}` 浅合并,缺字段会把 true 残留下来。
4024
4079
  isEphemeral: !!this.conv?.isEphemeral,
4025
4080
  sandbox: this.sandboxes?.getByCwd(this.cwd) ?? null,
4081
+ worktree: this.worktreeInfo ?? null,
4026
4082
  rev,
4027
4083
  streamingMessage,
4028
4084
  isStreaming: this.session.isStreaming,
@@ -4805,7 +4861,36 @@ export class ClientSession {
4805
4861
  const cached = this.piCheckCache;
4806
4862
  if (cached && now - cached.at < 2000)
4807
4863
  return cached.configured;
4808
- const configured = (this.sharedModelRuntime?.getAvailableSnapshot().length ?? 0) > 0;
4864
+ let configured = (this.sharedModelRuntime?.getAvailableSnapshot().length ?? 0) > 0;
4865
+ if (!configured) {
4866
+ try {
4867
+ const authFile = join(this.agentDir, "auth.json");
4868
+ if (existsSync(authFile)) {
4869
+ const auth = JSON.parse(readFileSync(authFile, "utf8"));
4870
+ if (auth && typeof auth === "object" && Object.keys(auth).length > 0) {
4871
+ configured = true;
4872
+ }
4873
+ }
4874
+ }
4875
+ catch {
4876
+ /* ignore */
4877
+ }
4878
+ if (!configured) {
4879
+ try {
4880
+ const modelsFile = join(this.agentDir, "models.json");
4881
+ if (existsSync(modelsFile)) {
4882
+ const conf = JSON.parse(readFileSync(modelsFile, "utf8"));
4883
+ const provs = conf?.providers;
4884
+ if (provs && typeof provs === "object" && Object.keys(provs).length > 0) {
4885
+ configured = true;
4886
+ }
4887
+ }
4888
+ }
4889
+ catch {
4890
+ /* ignore */
4891
+ }
4892
+ }
4893
+ }
4809
4894
  this.piCheckCache = { at: now, configured };
4810
4895
  return configured;
4811
4896
  }
@@ -4827,6 +4912,10 @@ export class ClientSession {
4827
4912
  static piCliProbe = null;
4828
4913
  static PI_CLI_PROBE_TTL_MS = 10_000;
4829
4914
  isPiCliInstalled() {
4915
+ // 在便携模式或已加载智能体引擎(内置 SDK)时直接视为就绪,无需系统全局安装外部 pi CLI
4916
+ if (process.env.PI_PORTABLE === "1" || this.sharedModelRuntime != null) {
4917
+ return true;
4918
+ }
4830
4919
  const now = Date.now();
4831
4920
  const cached = ClientSession.piCliProbe;
4832
4921
  if (cached && now - cached.at < ClientSession.PI_CLI_PROBE_TTL_MS)
@@ -4838,8 +4927,14 @@ export class ClientSession {
4838
4927
  static piCliOnPath() {
4839
4928
  const dirs = (process.env.PATH ?? "").split(delimiter);
4840
4929
  for (const dir of dirs) {
4841
- if (dir && existsSync(join(dir, "pi")))
4930
+ if (!dir)
4931
+ continue;
4932
+ if (existsSync(join(dir, "pi")))
4842
4933
  return true;
4934
+ if (process.platform === "win32") {
4935
+ if (existsSync(join(dir, "pi.cmd")) || existsSync(join(dir, "pi.exe")))
4936
+ return true;
4937
+ }
4843
4938
  }
4844
4939
  return false;
4845
4940
  }
@@ -4918,15 +5013,7 @@ export class ClientSession {
4918
5013
  * resolved from this compiled module: <pkg>/dist/server → <pkg>).
4919
5014
  */
4920
5015
  static currentAppVersion() {
4921
- try {
4922
- const here = dirname(fileURLToPath(import.meta.url));
4923
- const pkgRoot = resolve(here, "..", "..");
4924
- const pkg = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
4925
- return pkg.version ?? "0.0.0";
4926
- }
4927
- catch {
4928
- return "0.0.0";
4929
- }
5016
+ return getAppVersion() || "0.0.0";
4930
5017
  }
4931
5018
  /** Simple numeric semver compare: >0 means a newer than b. */
4932
5019
  static compareVersions(a, b) {
@@ -6244,7 +6331,8 @@ export class ClientSession {
6244
6331
  };
6245
6332
  // 写/编的权限沙箱包装:同一个函数,有扩展同名工具时把它的定义当基底(末参)。
6246
6333
  // 目标审查闸门包在**最外层**(权限沙箱之前):审查回合只读核实,写类直接拒。
6247
- const planGate = (def) => withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(def, () => this.sandboxes.getByCwd(cwd), () => cwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang());
6334
+ // 快照并发门禁包裹在工具执行最前沿,确保写操作前快照必定已就绪。
6335
+ const planGate = (def) => withWorkspaceSnapshotGate(withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(def, () => this.sandboxes.getByCwd(cwd), () => cwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()), () => this.awaitPendingWorkspaceSnapshot(ownerId));
6248
6336
  const composeWrite = (base) => planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
6249
6337
  const composeEdit = (base) => planGate(wrapEditToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
6250
6338
  const remoteOps = createRemoteSdkOperations(cwd);
@@ -6489,6 +6577,98 @@ export class ClientSession {
6489
6577
  const id = ownerId ?? this.activeId;
6490
6578
  return this.convs.get(id)?.awaitingVerdict != null;
6491
6579
  }
6580
+ /** 等待该会话正在并发生成的影子快照完成,确保写操作发生在快照完成之后。 */
6581
+ async awaitPendingWorkspaceSnapshot(ownerId) {
6582
+ const id = ownerId ?? this.activeId;
6583
+ const conv = this.convs.get(id);
6584
+ if (conv?.pendingWorkspaceSnapshot) {
6585
+ try {
6586
+ await conv.pendingWorkspaceSnapshot;
6587
+ }
6588
+ catch {
6589
+ // best-effort
6590
+ }
6591
+ }
6592
+ }
6593
+ /** 启动一次工作区版本影子快照并挂到 conv.pendingWorkspaceSnapshot(供写工具门禁等待)。 */
6594
+ startWorkspaceSnapshot(conv) {
6595
+ const snapshotPromise = createWorkspaceSnapshot(conv.cwd).catch((err) => {
6596
+ console.warn(`[workspace-snapshot] 创建快照失败 (${conv.cwd}):`, err.message);
6597
+ return null;
6598
+ });
6599
+ conv.pendingWorkspaceSnapshot = snapshotPromise;
6600
+ return snapshotPromise;
6601
+ }
6602
+ /**
6603
+ * 在用户消息定稿(message_end, role="user")时绑定或启动工作区影子快照:
6604
+ * - 空闲提问:复用 prompt() 已提前并发启动的 pendingWorkspaceSnapshot;
6605
+ * - 流式插队/排队(steer/followUp):在消息真正出队开跑的瞬间启动快照(入队阶段零 git 开销,不阻塞气泡上屏)。
6606
+ * SDK 在 _emit(message_end) 返回后的同一同步 tick 追加 sessionManager entry,因此用 queueMicrotask 精确捕获 entryId。
6607
+ */
6608
+ bindOrStartWorkspaceSnapshotForUserMessage(conv) {
6609
+ const snapshotPromise = conv.pendingWorkspaceSnapshot ?? this.startWorkspaceSnapshot(conv);
6610
+ queueMicrotask(() => {
6611
+ let entryId;
6612
+ const timestamp = Date.now();
6613
+ try {
6614
+ const entries = conv.session.sessionManager.buildContextEntries();
6615
+ const lastUserEntry = [...entries]
6616
+ .reverse()
6617
+ .find((e) => e.type === "message" && e.message?.role === "user");
6618
+ entryId = lastUserEntry?.id;
6619
+ }
6620
+ catch {
6621
+ // best-effort
6622
+ }
6623
+ void snapshotPromise
6624
+ .then((snapshotRef) => {
6625
+ if (conv.pendingWorkspaceSnapshot === snapshotPromise) {
6626
+ conv.pendingWorkspaceSnapshot = undefined;
6627
+ }
6628
+ if (!snapshotRef || this.disposed)
6629
+ return;
6630
+ try {
6631
+ // 若 이미为同一 entryId 记录过快照则不重复写
6632
+ if (entryId && conv.workspaceSnapshots.some((r) => r.entryId === entryId))
6633
+ return;
6634
+ const record = {
6635
+ entryId,
6636
+ timestamp,
6637
+ snapshotRef,
6638
+ };
6639
+ conv.workspaceSnapshots.push(record);
6640
+ if (conv.workspaceSnapshots.length > 50) {
6641
+ conv.workspaceSnapshots.shift();
6642
+ }
6643
+ appendWorkspaceSnapshotToSession(conv.session.sessionManager, record);
6644
+ }
6645
+ catch {
6646
+ // best-effort
6647
+ }
6648
+ })
6649
+ .catch(() => {
6650
+ if (conv.pendingWorkspaceSnapshot === snapshotPromise) {
6651
+ conv.pendingWorkspaceSnapshot = undefined;
6652
+ }
6653
+ });
6654
+ });
6655
+ }
6656
+ /** 检查并消费「流式入队前置阶段已被用户在前端点 ✕/↩ 取消」的待入队项。 */
6657
+ consumeCancelledInFlightQueue(conv, kind, rawText, fullPromptText) {
6658
+ const list = conv.cancelledInFlightQueue;
6659
+ if (!list || list.length === 0)
6660
+ return false;
6661
+ const normRaw = rawText.trim();
6662
+ const normFull = splitQuotedPrompt(fullPromptText).text.trim();
6663
+ const idx = list.findIndex((item) => item.kind === kind &&
6664
+ (item.text === fullPromptText ||
6665
+ item.text.trim() === normRaw ||
6666
+ splitQuotedPrompt(item.text).text.trim() === normFull));
6667
+ if (idx < 0)
6668
+ return false;
6669
+ list.splice(idx, 1);
6670
+ return true;
6671
+ }
6492
6672
  /**
6493
6673
  * 切换审查者模式(会话级,默认关)。
6494
6674
  * 开启后:① 本对话只审阅(写类/派发类工具硬闸门 + 提示词段);② 用户发的每条
@@ -6623,6 +6803,55 @@ export class ClientSession {
6623
6803
  });
6624
6804
  this.flushSnapshot();
6625
6805
  }
6806
+ /**
6807
+ * 目标模式 2.0 执行期(phase === "executing"):执行者在干活时,用户在主会话
6808
+ * 发送的补充信息/约束澄清自动 steer/followUp 进执行者会话,主会话不跑模型,杜绝双轨脱节与竞态 (#625)。
6809
+ */
6810
+ async dispatchToGoalExecutor(conv, text, queue = false) {
6811
+ if (conv.planMode === true)
6812
+ return false;
6813
+ if (conv.goal?.phase !== "executing")
6814
+ return false;
6815
+ const gc = conv;
6816
+ const execId = gc.roleExec?.convId;
6817
+ if (!execId)
6818
+ return false;
6819
+ const execConv = this.convs.get(execId);
6820
+ if (!execConv?.session)
6821
+ return false;
6822
+ const trimmed = text.trim();
6823
+ if (!trimmed)
6824
+ return false;
6825
+ // 原生斜杠命令(如 /model、/clear)由主会话本地消费,不转发给执行者
6826
+ const slash = parseSlash(trimmed);
6827
+ if (slash && (await this.slash.exec(slash.name, slash.args))) {
6828
+ this.flushSnapshot();
6829
+ return true;
6830
+ }
6831
+ try {
6832
+ await execConv.session.sendUserMessage(trimmed, execConv.session.isStreaming ? { deliverAs: queue ? "followUp" : "steer" } : undefined);
6833
+ }
6834
+ catch (err) {
6835
+ const msg = err instanceof Error ? err.message : String(err);
6836
+ this.emit({
6837
+ type: "notice",
6838
+ level: "error",
6839
+ text: `目标执行者:同步消息失败(${msg})`,
6840
+ textEn: `Goal executor: message sync failed (${msg})`,
6841
+ });
6842
+ this.flushSnapshot();
6843
+ // 返回 true 拦截本轮,绝不落回主会话并发起跑模型
6844
+ return true;
6845
+ }
6846
+ this.emit({
6847
+ type: "notice",
6848
+ level: "info",
6849
+ text: `🎯 已同步至目标执行者:${trimmed.slice(0, 120)}${trimmed.length > 120 ? "…" : ""}`,
6850
+ textEn: `🎯 Synchronized to goal executor: ${trimmed.slice(0, 120)}${trimmed.length > 120 ? "…" : ""}`,
6851
+ });
6852
+ this.flushSnapshot();
6853
+ return true;
6854
+ }
6626
6855
  /**
6627
6856
  * 切换计划模式(会话级,只规划不实施)。
6628
6857
  * 软约束(系统提示词段)+ 硬闸门(写类/旁路工具与非常规 bash 直接拒)双管:
@@ -7012,7 +7241,13 @@ export class ClientSession {
7012
7241
  // 对话执行,主会话这一轮**不跑模型**。接在 promptAc 之后、draft 清理之前:
7013
7242
  // 转走的内容不该把主对话的草稿也清掉(用户可能还想在主对话里追一句)。
7014
7243
  // 计划模式优先(那边直接返回 false)。
7015
- if (await this.dispatchToDelegate(conv, text)) {
7244
+ if (conv.delegateMode === true && (await this.dispatchToDelegate(conv, text))) {
7245
+ conv.presetLocked = true;
7246
+ return;
7247
+ }
7248
+ // 目标模式 2.0 执行期:执行者干活时,用户在主会话发送的补充说明自动 steer/followUp 给执行者,
7249
+ // 主会话不跑模型,杜绝双轨脱节与竞态 (#625)。
7250
+ if (await this.dispatchToGoalExecutor(conv, text, queue)) {
7016
7251
  conv.presetLocked = true;
7017
7252
  return;
7018
7253
  }
@@ -7369,15 +7604,18 @@ export class ClientSession {
7369
7604
  .map((a) => readTextQuote(a.quote))
7370
7605
  .filter((q) => q !== null)
7371
7606
  : [];
7372
- const asides = await buildAttachmentMessages({
7373
- cwd: this.cwd,
7374
- clientId: this.clientId,
7375
- emit: (msg) => this.emit(msg),
7376
- settings: this.settingsSvc.current,
7377
- session: this.session,
7378
- // issue #91:附件/视觉桥文案按客户端 UI 语言出中英(英文默认)。
7379
- getLang: () => this.getLang(),
7380
- }, streamingQuotes.length ? attachments?.filter((a) => a.mode !== "quote") : attachments);
7607
+ const nonQuoteAttachments = streamingQuotes.length ? attachments?.filter((a) => a.mode !== "quote") : attachments;
7608
+ const asides = nonQuoteAttachments && nonQuoteAttachments.length > 0
7609
+ ? await buildAttachmentMessages({
7610
+ cwd: this.cwd,
7611
+ clientId: this.clientId,
7612
+ emit: (msg) => this.emit(msg),
7613
+ settings: this.settingsSvc.current,
7614
+ session: this.session,
7615
+ // issue #91:附件/视觉桥文案按客户端 UI 语言出中英(英文默认)。
7616
+ getLang: () => this.getLang(),
7617
+ }, nonQuoteAttachments)
7618
+ : [];
7381
7619
  if (promptAc.signal.aborted) {
7382
7620
  conv.activePromptAc = undefined;
7383
7621
  // #492:displacement(新对话顶替/会话被移出)在 prompt 前置阶段 abort 时
@@ -7390,29 +7628,65 @@ export class ClientSession {
7390
7628
  });
7391
7629
  return;
7392
7630
  }
7393
- for (const aside of asides) {
7394
- if (s.isStreaming) {
7395
- await s.sendCustomMessage(aside.message, { deliverAs: "nextTurn" });
7631
+ const mainSupportsVision = s.model?.input?.includes("image") ?? false;
7632
+ const promptImages = [];
7633
+ const textAsides = [];
7634
+ const imageNames = [];
7635
+ if (s.isStreaming) {
7636
+ for (const aside of asides) {
7637
+ const details = aside.message.details;
7638
+ for (const b of aside.message.content) {
7639
+ if (typeof b === "string") {
7640
+ if (b.trim())
7641
+ textAsides.push(b.trim());
7642
+ continue;
7643
+ }
7644
+ if (!b || typeof b !== "object")
7645
+ continue;
7646
+ if (b.type === "image" && typeof b.data === "string") {
7647
+ if (mainSupportsVision) {
7648
+ promptImages.push({
7649
+ type: "image",
7650
+ data: b.data,
7651
+ mimeType: b.mimeType || "image/png",
7652
+ });
7653
+ if (details?.name) {
7654
+ imageNames.push(details.name);
7655
+ }
7656
+ }
7657
+ }
7658
+ else if (b.type === "text" &&
7659
+ typeof b.text === "string" &&
7660
+ b.text.trim()) {
7661
+ textAsides.push(b.text.trim());
7662
+ if (details?.mode === "bridged" && details?.name) {
7663
+ imageNames.push(details.name);
7664
+ }
7665
+ }
7666
+ }
7396
7667
  }
7397
- else {
7398
- await s.sendCustomMessage(aside.message);
7668
+ // 关键修复:流式排队/插队期间严禁使用 deliverAs: "nextTurn" 注入 custom message。
7669
+ // Pi SDK 的 _pendingNextTurnMessages 只在非流式 prompt() 消费;流式期间注入会导致
7670
+ // 排队消息无法获取附件,且附件残留泄露到下一次提问。
7671
+ // 保证 SDK 内部暂存队列清空,防止历史残留污染。
7672
+ if (Array.isArray(s._pendingNextTurnMessages)) {
7673
+ s._pendingNextTurnMessages = [];
7399
7674
  }
7400
7675
  }
7401
- // 附件处理完毕后立即刷新快照,让引用的文件卡片在等待模型首字前瞬间出现在界面上
7402
- if (asides.length > 0) {
7403
- this.flushSnapshot();
7404
- }
7405
- // 创建工作区版本影子快照(Dual-State Rollback)
7406
- let snapshotRef = null;
7407
- try {
7408
- snapshotRef = await createWorkspaceSnapshot(conv.cwd);
7409
- }
7410
- catch {
7411
- // best-effort
7676
+ else {
7677
+ for (const aside of asides) {
7678
+ await s.sendCustomMessage(aside.message);
7679
+ }
7680
+ if (asides.length > 0) {
7681
+ this.flushSnapshot();
7682
+ }
7683
+ if (Array.isArray(s._pendingNextTurnMessages)) {
7684
+ s._pendingNextTurnMessages = [];
7685
+ }
7412
7686
  }
7413
7687
  if (promptAc.signal.aborted) {
7414
7688
  conv.activePromptAc = undefined;
7415
- // #492:同上——影子快照阶段的 abort 也必须给回执,不能静默黑洞。
7689
+ // #492:同上——前置阶段的 abort 也必须给回执,不能静默黑洞。
7416
7690
  this.emit({
7417
7691
  type: "notice",
7418
7692
  level: "warning",
@@ -7422,7 +7696,7 @@ export class ClientSession {
7422
7696
  return;
7423
7697
  }
7424
7698
  conv.activePromptAc = undefined;
7425
- // 前置阶段(附件 / 影子快照)期间用户可能已经切走或新建了对话:消息仍然
7699
+ // 前置阶段(附件)期间用户可能已经切走或新建了对话:消息仍然
7426
7700
  // 落在本对话里,指给用户看,免得「发出去的消息不见了」。
7427
7701
  if (conv.id !== this.activeId) {
7428
7702
  this.emit({
@@ -7443,31 +7717,36 @@ export class ClientSession {
7443
7717
  // Enter-during-streaming semantic (docs/usage: Enter queues a
7444
7718
  // steering message); followUp would wait for the whole run
7445
7719
  // to finish, which users perceive as ordinary queueing.
7446
- await s.prompt(formatQuotedPrompt(text, streamingQuotes), {
7447
- streamingBehavior: queue ? "followUp" : "steer",
7720
+ //
7721
+ // 注意:流式期间入队仅进入 SDK 内存队列(尚未落盘为 sessionManager entry),
7722
+ // 严禁在此处启动或 await 工作区 Git 影子快照(否则在大型仓库或工具占锁时会把
7723
+ // 入队回执与 flushSnapshot 阻塞数秒至 15 秒,造成「按完 Enter 消息消失」)。
7724
+ // 排队/插队消息的工作区快照在其真正出队定稿(message_end, role="user")时异步生成。
7725
+ const kind = queue ? "followUp" : "steer";
7726
+ const fullPromptText = formatStreamingPrompt(text, textAsides, streamingQuotes, imageNames);
7727
+ if (this.consumeCancelledInFlightQueue(conv, kind, text, fullPromptText)) {
7728
+ this.flushSnapshot();
7729
+ return;
7730
+ }
7731
+ if (promptImages.length > 0) {
7732
+ conv.queuedImages.set(fullPromptText, promptImages);
7733
+ }
7734
+ await s.prompt(fullPromptText, {
7735
+ streamingBehavior: kind,
7736
+ images: promptImages.length > 0 ? promptImages : undefined,
7448
7737
  });
7449
7738
  }
7450
7739
  else {
7451
- await s.prompt(formatQuotedPrompt(text, streamingQuotes));
7452
- }
7453
- // 关联快照与本次 prompt 产生的用户消息 entry
7454
- if (snapshotRef) {
7740
+ // 空闲提问:启动工作区版本影子快照(与模型首字并发执行,写工具由门禁等待;
7741
+ // 绑定由 message_end 异步完成,绝不阻塞 prompt 收尾与气泡上屏)。
7742
+ const snapshotPromise = this.startWorkspaceSnapshot(conv);
7455
7743
  try {
7456
- const entries = conv.session.sessionManager.buildContextEntries();
7457
- const lastUserEntry = [...entries]
7458
- .reverse()
7459
- .find((e) => e.type === "message" && e.message?.role === "user");
7460
- conv.workspaceSnapshots.push({
7461
- entryId: lastUserEntry?.id,
7462
- timestamp: Date.now(),
7463
- snapshotRef,
7464
- });
7465
- if (conv.workspaceSnapshots.length > 50) {
7466
- conv.workspaceSnapshots.shift();
7467
- }
7744
+ await s.prompt(formatQuotedPrompt(text, streamingQuotes));
7468
7745
  }
7469
- catch {
7470
- // best-effort
7746
+ finally {
7747
+ if (conv.pendingWorkspaceSnapshot === snapshotPromise) {
7748
+ conv.pendingWorkspaceSnapshot = undefined;
7749
+ }
7471
7750
  }
7472
7751
  }
7473
7752
  }
@@ -7519,6 +7798,9 @@ export class ClientSession {
7519
7798
  this.conv.activePromptAc.abort();
7520
7799
  this.conv.activePromptAc = undefined;
7521
7800
  }
7801
+ if (Array.isArray(this.conv.session?._pendingNextTurnMessages)) {
7802
+ this.conv.session._pendingNextTurnMessages = [];
7803
+ }
7522
7804
  const isRunning = this.conversationStreaming(this.conv) || !this.conv.session.isIdle;
7523
7805
  if (!isRunning) {
7524
7806
  this.flushSnapshot();
@@ -7626,16 +7908,31 @@ export class ClientSession {
7626
7908
  const conv = this.conv;
7627
7909
  // Always-defined display mirrors; also the provenance of bubble rendering.
7628
7910
  const local = kind === "steer" ? conv.queueSteering : conv.queueFollowUp;
7629
- if (!local.includes(text)) {
7630
- // Already gone (delivered / cleared elsewhere) — just refresh the display.
7631
- this.flushSnapshot();
7632
- return;
7911
+ let targetText = text;
7912
+ if (!local.includes(targetText)) {
7913
+ // 前端乐观气泡在视觉桥等异步附件完成前只带基础文本,按净化后的正文匹配兜底
7914
+ const parsedTarget = splitQuotedPrompt(text).text.trim();
7915
+ const fallback = parsedTarget
7916
+ ? local.find((item) => splitQuotedPrompt(item).text.trim() === parsedTarget)
7917
+ : undefined;
7918
+ if (fallback !== undefined) {
7919
+ targetText = fallback;
7920
+ }
7921
+ else {
7922
+ // 若当前仍有流式 prompt 处于前置构建阶段(尚未进 SDK 队列),记录取消标记拦截其后续入队
7923
+ if (conv.promptInFlight) {
7924
+ (conv.cancelledInFlightQueue ??= []).push({ kind, text });
7925
+ }
7926
+ // Already gone (delivered / cleared elsewhere) — just refresh the display.
7927
+ this.flushSnapshot();
7928
+ return;
7929
+ }
7633
7930
  }
7634
7931
  const s = this.conv.session;
7635
7932
  if (!s) {
7636
7933
  // Runtime not bound yet (fresh conversation) — drop the display mirror;
7637
7934
  // a later queue_update reconciles any SDK-side state.
7638
- const next = removeQueuedByIndexOrText(local, text, index);
7935
+ const next = removeQueuedByIndexOrText(local, targetText, index);
7639
7936
  if (next.length !== local.length) {
7640
7937
  local.splice(0, local.length, ...next);
7641
7938
  }
@@ -7652,7 +7949,7 @@ export class ClientSession {
7652
7949
  // 回退到本地显示镜像移除,等 queue_update 对账;绝不把 reject 的 Promise
7653
7950
  // 扔回给 dispatch(无兜底 handler 时 unhandledRejection 直接崩进程)。
7654
7951
  console.error("[agent-service] clearQueue failed while removing a queued message:", err);
7655
- const next = removeQueuedByIndexOrText(local, text, index);
7952
+ const next = removeQueuedByIndexOrText(local, targetText, index);
7656
7953
  if (next.length !== local.length) {
7657
7954
  local.splice(0, local.length, ...next);
7658
7955
  }
@@ -7662,13 +7959,14 @@ export class ClientSession {
7662
7959
  // 气泡 ✕ 对应的是「第几个气泡」(index),不是「哪段文本」:同一文本排队两次时
7663
7960
  // 按文本只会删掉第一条,点第二个气泡却删掉第一个。用 index 定位,位置对不上
7664
7961
  // (队列在点击与执行之间变化)或旧客户端没发 index 时回落到第一处文本匹配。
7665
- const keptSteering = kind === "steer" ? removeQueuedByIndexOrText(steering, text, index) : steering;
7666
- const keptFollowUp = kind === "followUp" ? removeQueuedByIndexOrText(followUp, text, index) : followUp;
7962
+ const keptSteering = kind === "steer" ? removeQueuedByIndexOrText(steering, targetText, index) : steering;
7963
+ const keptFollowUp = kind === "followUp" ? removeQueuedByIndexOrText(followUp, targetText, index) : followUp;
7667
7964
  // Re-queue the survivors in original order. Guard each call so a single
7668
7965
  // failure can't leave the queue half-drained silently.
7669
7966
  for (const t of keptSteering) {
7670
7967
  try {
7671
- await s.steer(t);
7968
+ const imgs = conv.queuedImages?.get(t);
7969
+ await s.steer(t, imgs);
7672
7970
  }
7673
7971
  catch (err) {
7674
7972
  this.emit({
@@ -7681,7 +7979,8 @@ export class ClientSession {
7681
7979
  }
7682
7980
  for (const t of keptFollowUp) {
7683
7981
  try {
7684
- await s.followUp(t);
7982
+ const imgs = conv.queuedImages?.get(t);
7983
+ await s.followUp(t, imgs);
7685
7984
  }
7686
7985
  catch (err) {
7687
7986
  this.emit({
@@ -7692,6 +7991,10 @@ export class ClientSession {
7692
7991
  });
7693
7992
  }
7694
7993
  }
7994
+ conv.queuedImages?.delete(targetText);
7995
+ if (Array.isArray(s._pendingNextTurnMessages)) {
7996
+ s._pendingNextTurnMessages = [];
7997
+ }
7695
7998
  this.flushSnapshot();
7696
7999
  }
7697
8000
  // -----------------------------------------------------------------------
@@ -8036,11 +8339,12 @@ export class ClientSession {
8036
8339
  const openInProject = [...this.convs.values()].filter((c) => c.cwd === this.cwd && !c.isSubagent && !c.isEphemeral).length;
8037
8340
  const maxOpenConversations = getMaxOpenConversations();
8038
8341
  if (openInProject >= maxOpenConversations) {
8342
+ const notice = this.maxOpenConversationsNotice(maxOpenConversations);
8039
8343
  this.emit({
8040
8344
  type: "notice",
8041
8345
  level: "warning",
8042
- text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
8043
- textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
8346
+ text: notice.text,
8347
+ textEn: notice.textEn,
8044
8348
  });
8045
8349
  return false;
8046
8350
  }
@@ -8449,6 +8753,34 @@ export class ClientSession {
8449
8753
  return { manager, runtime, repair };
8450
8754
  }
8451
8755
  }
8756
+ /** 会话是否已产生内容或已被列入运行列表(非刚新建且一言未发的空白会话)。 */
8757
+ isConversationStarted(conv) {
8758
+ if (conv.listed)
8759
+ return true;
8760
+ if (conv.title !== DEFAULT_CONV_TITLE)
8761
+ return true;
8762
+ if (conv.forkFrom)
8763
+ return true;
8764
+ try {
8765
+ return conv.session.getSessionStats().totalMessages > 0;
8766
+ }
8767
+ catch {
8768
+ return false;
8769
+ }
8770
+ }
8771
+ maxOpenConversationsNotice(limit) {
8772
+ const retain = Boolean(this.settingsSvc?.current.retainFinishedConversations);
8773
+ if (retain) {
8774
+ return {
8775
+ text: `当前项目运行的对话已达上限(${limit} 个),请先在「运行的对话」中点击 ✕ 移出不需要的对话(钉住的对话需先取消钉住)`,
8776
+ textEn: `This project already has the max open conversations (${limit}). Please remove unneeded conversations with ✕ in "Running Chats" first (pinned chats must be unpinned first).`,
8777
+ };
8778
+ }
8779
+ return {
8780
+ text: `当前项目运行的对话已达上限(${limit} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
8781
+ textEn: `This project already has the max open conversations (${limit}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
8782
+ };
8783
+ }
8452
8784
  displaceActive() {
8453
8785
  const conv = this.conv;
8454
8786
  // 正在过户给其他会话:绝不就地释放(runtime/终端等整体搬迁给 target)。
@@ -8479,7 +8811,9 @@ export class ClientSession {
8479
8811
  // points at it: dropping an idle in-memory parent orphans the child row
8480
8812
  // (the child vanishes from Running Chats with no result available).
8481
8813
  const hasLiveChild = [...this.convs.values()].some((child) => child.parentId === conv.id);
8814
+ const retainFinished = Boolean(this.settingsSvc?.current.retainFinishedConversations) && this.isConversationStarted(conv);
8482
8815
  const retained = hasLiveChild ||
8816
+ retainFinished ||
8483
8817
  shouldRetainActive({
8484
8818
  reviewing: conv.goal.reviewing,
8485
8819
  wizardRunning: conv.wizardRunning,
@@ -9306,21 +9640,10 @@ export class ClientSession {
9306
9640
  // (<agentDir>/sessions/--<cwd>--/), the same files the pi CLI/TUI
9307
9641
  // use — one listing covers every conversation of the current folder.
9308
9642
  const infos = await this.loadSessionInfos();
9309
- // 隐藏「被 fork 掉的父会话」,历史列表只保留每条 fork 链最新的链尾会话
9310
- // (全文搜索 searchSessions 保留全部会话,不受此影响)。
9311
- const normSessionPath = (p) => normalizePathKey(p);
9312
- const forkedParentPaths = new Set();
9313
- for (const info of infos) {
9314
- if (typeof info.parentSessionPath === "string" && info.parentSessionPath) {
9315
- forkedParentPaths.add(normSessionPath(info.parentSessionPath));
9316
- }
9317
- }
9318
- const visibleInfos = forkedParentPaths.size > 0
9319
- ? (() => {
9320
- const kept = infos.filter((info) => !forkedParentPaths.has(normSessionPath(info.path)));
9321
- return kept.length > 0 ? kept : infos;
9322
- })()
9323
- : infos;
9643
+ // 默认隐藏「被 fork 掉的父会话」(仅保留每条 fork 链最新的链尾会话);
9644
+ // 开启 showForkedParentSessions 时保留全部会话(全文搜索 searchSessions 始终保留全部)。
9645
+ const showForkedParents = this.settingsSvc.current.showForkedParentSessions === true;
9646
+ const visibleInfos = filterForkedParentSessions(infos, showForkedParents);
9324
9647
  const sessions = new Map();
9325
9648
  for (const s of visibleInfos) {
9326
9649
  const isPinned = this.stateStore?.isSessionPinned(this.cwd, s.path);
@@ -9333,6 +9656,7 @@ export class ClientSession {
9333
9656
  modified: s.modified.getTime(),
9334
9657
  source: "web",
9335
9658
  ...(isPinned ? { pinned: true } : {}),
9659
+ ...(s.parentSessionPath ? { parentSessionPath: s.parentSessionPath } : {}),
9336
9660
  });
9337
9661
  }
9338
9662
  const sorted = [...sessions.values()].sort((a, b) => b.modified - a.modified).slice(0, 200); // newest first — the panel shows recent history
@@ -10358,11 +10682,12 @@ export class ClientSession {
10358
10682
  text: `当前项目运行的对话已达上限(${maxOpenConversations} 个)`,
10359
10683
  textEn: `Max open conversations (${maxOpenConversations}) reached`,
10360
10684
  });
10685
+ const notice = this.maxOpenConversationsNotice(maxOpenConversations);
10361
10686
  this.emit({
10362
10687
  type: "notice",
10363
10688
  level: "warning",
10364
- text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
10365
- textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
10689
+ text: notice.text,
10690
+ textEn: notice.textEn,
10366
10691
  });
10367
10692
  return;
10368
10693
  }
@@ -10575,11 +10900,12 @@ export class ClientSession {
10575
10900
  this.conv.listed = oldListed;
10576
10901
  terminals.killAll();
10577
10902
  await runtime.dispose();
10903
+ const notice = this.maxOpenConversationsNotice(maxOpenConversations);
10578
10904
  this.emit({
10579
10905
  type: "notice",
10580
10906
  level: "warning",
10581
- text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
10582
- textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
10907
+ text: notice.text,
10908
+ textEn: notice.textEn,
10583
10909
  });
10584
10910
  return;
10585
10911
  }
@@ -10588,6 +10914,8 @@ export class ClientSession {
10588
10914
  if (displaced)
10589
10915
  this.removeConversation(displaced.id);
10590
10916
  await this.bindSession();
10917
+ this.invalidateSessionInfos();
10918
+ this.scheduleSessionsRefresh();
10591
10919
  // #436:同 switchSession —— 派生出的会话若从转录回放恢复了 planMode,
10592
10920
  // 工厂里的门控当时读不到它,注册后补一次。
10593
10921
  this.applyToolGating(newConv.session, newConv.agentPreset);
@@ -10675,6 +11003,7 @@ export class ClientSession {
10675
11003
  targetConv.lastMessagesArray = [];
10676
11004
  targetConv.queueSteering = [];
10677
11005
  targetConv.queueFollowUp = [];
11006
+ targetConv.queuedImages = new Map();
10678
11007
  try {
10679
11008
  targetConv.session.clearQueue?.();
10680
11009
  }
@@ -10684,6 +11013,14 @@ export class ClientSession {
10684
11013
  // 联动还原物理工作区文件(Dual-State Rollback)
10685
11014
  let workspaceRestored = false;
10686
11015
  if (restoreWorkspace) {
11016
+ if (targetConv.pendingWorkspaceSnapshot) {
11017
+ try {
11018
+ await targetConv.pendingWorkspaceSnapshot;
11019
+ }
11020
+ catch {
11021
+ // best-effort
11022
+ }
11023
+ }
10687
11024
  const entryTs = entry.message?.timestamp ??
10688
11025
  entry.timestamp ??
10689
11026
  0;
@@ -10793,6 +11130,8 @@ export class ClientSession {
10793
11130
  return;
10794
11131
  }
10795
11132
  await this.bindSession();
11133
+ this.invalidateSessionInfos();
11134
+ this.scheduleSessionsRefresh();
10796
11135
  this.conv.uiMessageCache.clear();
10797
11136
  this.conv.msgIds.clear();
10798
11137
  this.conv.userSeqByTs.clear();
@@ -10801,6 +11140,7 @@ export class ClientSession {
10801
11140
  this.conv.lastMessagesArray = [];
10802
11141
  this.conv.queueSteering = [];
10803
11142
  this.conv.queueFollowUp = [];
11143
+ this.conv.queuedImages = new Map();
10804
11144
  // Restore the previously-selected model on the forked branch.
10805
11145
  if (prevModel && this.sharedModelRuntime) {
10806
11146
  try {
@@ -10822,11 +11162,16 @@ export class ClientSession {
10822
11162
  }
10823
11163
  }
10824
11164
  await this.prompt(trimmed, attachments);
11165
+ const showParents = this.settingsSvc.current.showForkedParentSessions === true;
10825
11166
  this.emit({
10826
11167
  type: "notice",
10827
11168
  level: "info",
10828
- text: "已从该问题重新提问(原对话保留在会话列表中)",
10829
- textEn: "Re-asked from that question (the original stays in the session list)",
11169
+ text: showParents
11170
+ ? "已从该问题重新提问(原对话保留在会话列表中)"
11171
+ : "已从该问题重新提问(原对话已保留,但默认不在历史列表中显示)",
11172
+ textEn: showParents
11173
+ ? "Re-asked from that question (the original stays in the session list)"
11174
+ : "Re-asked from that question (the original is kept, but hidden from the history list by default)",
10830
11175
  });
10831
11176
  }
10832
11177
  catch (err) {
@@ -11220,10 +11565,10 @@ export class ClientSession {
11220
11565
  // 别处无可见行时不扫目录(首访切项目的常见情形零开销)。
11221
11566
  if ((this.listExternalRunning?.() ?? []).length > 0) {
11222
11567
  try {
11223
- const infos = await SessionManager.list(sessionBaseDir, piSessionsRoot());
11224
- const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
11568
+ const recentPath = await findMostRecentSessionFileFast(sessionBaseDir, abs);
11569
+ const recent = recentPath ? resolve(recentPath) : undefined;
11225
11570
  const owner = recent ? this.findSessionOwner?.(recent) : null;
11226
- if (owner) {
11571
+ if (owner && (owner.connected || owner.isStreaming)) {
11227
11572
  resumeSkipped = owner;
11228
11573
  }
11229
11574
  }
@@ -11239,7 +11584,7 @@ export class ClientSession {
11239
11584
  cwd: sessionBaseDir,
11240
11585
  agentDir: this.agentDir,
11241
11586
  sessionManager: m,
11242
- }), async () => (await SessionManager.list(sessionBaseDir))[0]?.path, async (m) => {
11587
+ }), () => findMostRecentSessionFileFast(sessionBaseDir, abs), async (m) => {
11243
11588
  const { totalMessages, previewMessages } = this.extractTranscriptPreview(m, 16);
11244
11589
  this.emit({
11245
11590
  type: "transition_progress",
@@ -11335,6 +11680,7 @@ export class ClientSession {
11335
11680
  // 切项目即换了当前打开对话 → 插件重拉。
11336
11681
  this.notifyConversationChanged();
11337
11682
  this.pushSettings();
11683
+ void this.refreshWorktreeInfo();
11338
11684
  }
11339
11685
  catch (err) {
11340
11686
  this.emit({
@@ -11568,6 +11914,48 @@ export class ClientSession {
11568
11914
  });
11569
11915
  }
11570
11916
  }
11917
+ /** 刷新当前工作区的 Git 工作树状态并推送快照。 */
11918
+ async refreshWorktreeInfo() {
11919
+ try {
11920
+ this.worktreeInfo = await getWorktreeContext(this.cwd);
11921
+ }
11922
+ catch {
11923
+ this.worktreeInfo = null;
11924
+ }
11925
+ this.flushSnapshot();
11926
+ }
11927
+ /** 切换当前工作区至指定 Git 工作树目录。 */
11928
+ async switchWorktree(targetPath) {
11929
+ await this.setCwd(targetPath);
11930
+ }
11931
+ /** 移除指定 Git 工作树;若移除的是当前工作区则先切回主仓库。 */
11932
+ async removeWorktree(targetPath, force = false) {
11933
+ try {
11934
+ const { resolve } = await import("node:path");
11935
+ const normTarget = normalizeWirePath(resolve(this.cwd, targetPath));
11936
+ const isCurrent = this.worktreeInfo?.currentPath === normTarget;
11937
+ const fallback = this.worktreeInfo?.mainPath || this.cwd;
11938
+ if (isCurrent && fallback !== normTarget) {
11939
+ await this.setCwd(fallback);
11940
+ }
11941
+ await removeWorktree(this.cwd, normTarget, force, () => this.getLang());
11942
+ await this.refreshWorktreeInfo();
11943
+ this.emit({
11944
+ type: "notice",
11945
+ level: "info",
11946
+ text: `🗑️ 已移除 Git 工作树:${normTarget}`,
11947
+ textEn: `🗑️ Removed Git worktree: ${normTarget}`,
11948
+ });
11949
+ }
11950
+ catch (err) {
11951
+ this.emit({
11952
+ type: "notice",
11953
+ level: "error",
11954
+ text: `移除工作树失败:${err.message}`,
11955
+ textEn: `Failed to remove worktree: ${err.message}`,
11956
+ });
11957
+ }
11958
+ }
11571
11959
  /** Strip the "(New)" freshness marker some catalogs append to display names
11572
11960
  * (pi.dev data, e.g. "DeepSeek V4 Pro (New)") — display-only; the model id
11573
11961
  * is untouched so switching still uses the exact official id. */