pi-web-ui 0.104.3 → 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 +56 -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 +513 -115
  7. package/dist/server/approval-default-rules.js +15 -0
  8. package/dist/server/client-state.js +42 -2
  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 +30 -5
  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-VjlOOAig.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-5SITmQd_.js +0 -680
  52. package/web/dist/assets/index-D9wTa3O-.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";
@@ -47,14 +48,14 @@ import { SlashCommandsService, parseSlash } from "./slash-commands.js";
47
48
  import { ModelAdminService } from "./model-admin.js";
48
49
  import { FilesService, MACHINE_ROOT, desktopDirWire, workspacePath } from "./files-service.js";
49
50
  import { buildRemoteWorkspacePersona, createRemoteSdkOperations, formatCwdForPrompt, getGlobalRemoteSshService, isRemoteWorkspaceUri, RemoteSshService, resolveWorkspaceSessionDir, restoreWorkspaceUriFromSessionDir, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
50
- import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
51
+ import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, isInternalExtension, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
51
52
  import { pick, resolveServerLang } from "./i18n.js";
52
53
  import { SubagentTemplatesStore, pickTemplatePrompt } from "./subagent-templates.js";
53
54
  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";
@@ -195,7 +198,7 @@ export class QuiesceRejectedError extends Error {
195
198
  // /api/file HTTP endpoint instead of the WebSocket, so they are classified
196
199
  // here but never read into the snapshot path.
197
200
  // ---------------------------------------------------------------------------
198
- import { INLINE_PERSONA_EXT, splitAgentStartPrompt, PI_DOC_PATHS, WINDOWS_PERSONA } from "./persona-chain.js";
201
+ import { splitAgentStartPrompt, PI_DOC_PATHS, WINDOWS_PERSONA } from "./persona-chain.js";
199
202
  export { splitAgentStartPrompt };
200
203
  import { makeKillableBashTool, makeAdaptiveBashTool } from "./bash-tool.js";
201
204
  export { makeKillableBashTool, makeAdaptiveBashTool };
@@ -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
  /**
@@ -2066,8 +2085,8 @@ export class ClientSession {
2066
2085
  // 注意 SDK 在 extensionsOverride 之后才补 sourceInfo,包扩展此处只能靠路径
2067
2086
  // 匹配 —— isExtensionDisabled / isExtensionEnabled 同时比对 npm:<pkg> 候选键。
2068
2087
  extensionsOverride: (res) => {
2069
- // 自家内联扩展(灵魂替换)是基础设施,不参与白名单/禁用过滤。
2070
- const keepOwn = (e) => !e.path.startsWith(INLINE_PERSONA_EXT);
2088
+ // 内部基础设施扩展(codemode、tool-search、persona 等)不参与白名单/禁用过滤。
2089
+ const keepOwn = (e) => isInternalExtension(e);
2071
2090
  if (apply && apply.enabledExtensions.length > 0) {
2072
2091
  const set = new Set(apply.enabledExtensions);
2073
2092
  return {
@@ -2085,8 +2104,18 @@ export class ClientSession {
2085
2104
  // 覆盖,则用 composer 把 {{token}} 展开为各来源文本(工具列表/项目上下文/技能
2086
2105
  // 等都取自本次 run 的 systemPromptOptions,永远最新)。
2087
2106
  extensionFactories: [
2088
- createCodemodeExtension(),
2089
- createToolSearchExtension(),
2107
+ {
2108
+ name: "codemode",
2109
+ hidden: true,
2110
+ replaceable: true,
2111
+ factory: createCodemodeExtension(),
2112
+ },
2113
+ {
2114
+ name: "tool-search",
2115
+ hidden: true,
2116
+ replaceable: true,
2117
+ factory: createToolSearchExtension(),
2118
+ },
2090
2119
  {
2091
2120
  name: "pi-webui-persona",
2092
2121
  hidden: true,
@@ -2229,7 +2258,7 @@ export class ClientSession {
2229
2258
  // P1-5:bash/read 包插件拦截(pre 拒/问即拦、post 脱敏补上下文;
2230
2259
  // 未注入 toolGuard 时 withToolGuard 原样返回,零开销)。
2231
2260
  // 权限沙箱拦截(只读模式拦截终端执行)。
2232
- wrapBashToolWithPermission(withToolGuard(makeAdaptiveBashTool(
2261
+ wrapBashToolWithPermission(withToolGuard(withWorkspaceSnapshotGate(makeAdaptiveBashTool(
2233
2262
  // issue #91:bash 返回按客户端 UI 语言出中英(英文默认)。
2234
2263
  makeKillableBashTool(effectiveCwd, this.bashKills, () => this.getLang()), makeTerminalBashTool(terminals, {
2235
2264
  cwd: effectiveCwd,
@@ -2243,7 +2272,7 @@ export class ClientSession {
2243
2272
  lang: () => this.getLang(),
2244
2273
  }),
2245
2274
  // 设置关 → 原生 bash;开 → 终端 bash。
2246
- () => this.settingsSvc.current.terminalBash), {
2275
+ () => this.settingsSvc.current.terminalBash), () => this.awaitPendingWorkspaceSnapshot(ownerId)), {
2247
2276
  toolName: "bash",
2248
2277
  guard: this.lateToolGuard,
2249
2278
  conversationId: () => ownerId,
@@ -2291,7 +2320,7 @@ export class ClientSession {
2291
2320
  }
2292
2321
  return {};
2293
2322
  },
2294
- }),
2323
+ }).map((tool) => withWorkspaceSnapshotGate(tool, () => this.awaitPendingWorkspaceSnapshot(ownerId))),
2295
2324
  // read / write / edit 三处覆盖**不在这里注册**:创建时的 customTools 恒胜、与
2296
2325
  // 扩展加载顺序无关,直接塞进来会静默顶掉第三方扩展注册的同名工具(见
2297
2326
  // tool-overrides.ts);它们改在会话建好后由 installToolOverrides 注入。
@@ -2412,6 +2441,14 @@ export class ClientSession {
2412
2441
  askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category),
2413
2442
  getConversationId: () => ownerId,
2414
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()),
2415
2452
  ].map((t) =>
2416
2453
  // 目标审查闸门在最外层(理由最贴合此刻);插件工具也在这个数组里,
2417
2454
  // 创建时注册的同样被闸门覆盖(后续动态补入的走 syncPluginTools,与
@@ -2484,11 +2521,12 @@ export class ClientSession {
2484
2521
  lastMessagesArray: [],
2485
2522
  queueSteering: [],
2486
2523
  queueFollowUp: [],
2524
+ queuedImages: new Map(),
2487
2525
  toolStartTimes: new Map(),
2488
2526
  toolPendingArgs: new Map(),
2489
2527
  activeToolCalls: new Map(),
2490
2528
  toolWatchdogs: new Map(),
2491
- workspaceSnapshots: [],
2529
+ workspaceSnapshots: readWorkspaceSnapshotsFromSession(runtime.session.sessionManager),
2492
2530
  };
2493
2531
  this.restorePlan(conv);
2494
2532
  return conv;
@@ -3405,6 +3443,14 @@ export class ClientSession {
3405
3443
  case "queue_update":
3406
3444
  conv.queueSteering = [...event.steering];
3407
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
+ }
3408
3454
  break;
3409
3455
  // 手动 /compact 或阈值/溢出自动压缩开始——常驻进度条(快照 compaction
3410
3456
  // 字段),而不是一次性 toast(toast 几秒就消失,而摘要生成可能持续
@@ -3610,6 +3656,12 @@ export class ClientSession {
3610
3656
  }
3611
3657
  // 本轮真正结束且不再重试:立即向客户端广播最新会话状态(流式状态及时复位)
3612
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
+ }
3613
3665
  this.emitConversations();
3614
3666
  }
3615
3667
  break;
@@ -3652,6 +3704,14 @@ export class ClientSession {
3652
3704
  // 每条 assistant 气泡流式结束 → 立即解析其中的内联标记:每个气泡各自
3653
3705
  // 生效(不再等整轮 agent_end),同一轮里先前消息的标记也不再丢。
3654
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
+ }
3655
3715
  if (mm?.role !== "assistant")
3656
3716
  break;
3657
3717
  // 非 error 的 assistant 定稿 = 重试周期结束(与 SDK 重置
@@ -3740,11 +3800,16 @@ export class ClientSession {
3740
3800
  // 全量),它在左栏的运行态由 emitConversations 走另一条通道。
3741
3801
  if (conv.id !== this.conv.id)
3742
3802
  return;
3803
+ const eventMsgRole = event.type === "message_start" || event.type === "message_end"
3804
+ ? event.message?.role
3805
+ : undefined;
3743
3806
  if (event.type === "agent_end" ||
3744
3807
  event.type === "tool_execution_end" ||
3745
3808
  event.type === "compaction_end" ||
3746
3809
  event.type === "auto_retry_start" ||
3747
- event.type === "auto_retry_end") {
3810
+ event.type === "auto_retry_end" ||
3811
+ event.type === "queue_update" ||
3812
+ eventMsgRole === "user") {
3748
3813
  this.flushSnapshot();
3749
3814
  }
3750
3815
  else {
@@ -4013,6 +4078,7 @@ export class ClientSession {
4013
4078
  // `{...ui, ...d.state}` 浅合并,缺字段会把 true 残留下来。
4014
4079
  isEphemeral: !!this.conv?.isEphemeral,
4015
4080
  sandbox: this.sandboxes?.getByCwd(this.cwd) ?? null,
4081
+ worktree: this.worktreeInfo ?? null,
4016
4082
  rev,
4017
4083
  streamingMessage,
4018
4084
  isStreaming: this.session.isStreaming,
@@ -4795,7 +4861,36 @@ export class ClientSession {
4795
4861
  const cached = this.piCheckCache;
4796
4862
  if (cached && now - cached.at < 2000)
4797
4863
  return cached.configured;
4798
- 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
+ }
4799
4894
  this.piCheckCache = { at: now, configured };
4800
4895
  return configured;
4801
4896
  }
@@ -4817,6 +4912,10 @@ export class ClientSession {
4817
4912
  static piCliProbe = null;
4818
4913
  static PI_CLI_PROBE_TTL_MS = 10_000;
4819
4914
  isPiCliInstalled() {
4915
+ // 在便携模式或已加载智能体引擎(内置 SDK)时直接视为就绪,无需系统全局安装外部 pi CLI
4916
+ if (process.env.PI_PORTABLE === "1" || this.sharedModelRuntime != null) {
4917
+ return true;
4918
+ }
4820
4919
  const now = Date.now();
4821
4920
  const cached = ClientSession.piCliProbe;
4822
4921
  if (cached && now - cached.at < ClientSession.PI_CLI_PROBE_TTL_MS)
@@ -4828,8 +4927,14 @@ export class ClientSession {
4828
4927
  static piCliOnPath() {
4829
4928
  const dirs = (process.env.PATH ?? "").split(delimiter);
4830
4929
  for (const dir of dirs) {
4831
- if (dir && existsSync(join(dir, "pi")))
4930
+ if (!dir)
4931
+ continue;
4932
+ if (existsSync(join(dir, "pi")))
4832
4933
  return true;
4934
+ if (process.platform === "win32") {
4935
+ if (existsSync(join(dir, "pi.cmd")) || existsSync(join(dir, "pi.exe")))
4936
+ return true;
4937
+ }
4833
4938
  }
4834
4939
  return false;
4835
4940
  }
@@ -4908,15 +5013,7 @@ export class ClientSession {
4908
5013
  * resolved from this compiled module: <pkg>/dist/server → <pkg>).
4909
5014
  */
4910
5015
  static currentAppVersion() {
4911
- try {
4912
- const here = dirname(fileURLToPath(import.meta.url));
4913
- const pkgRoot = resolve(here, "..", "..");
4914
- const pkg = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
4915
- return pkg.version ?? "0.0.0";
4916
- }
4917
- catch {
4918
- return "0.0.0";
4919
- }
5016
+ return getAppVersion() || "0.0.0";
4920
5017
  }
4921
5018
  /** Simple numeric semver compare: >0 means a newer than b. */
4922
5019
  static compareVersions(a, b) {
@@ -6234,7 +6331,8 @@ export class ClientSession {
6234
6331
  };
6235
6332
  // 写/编的权限沙箱包装:同一个函数,有扩展同名工具时把它的定义当基底(末参)。
6236
6333
  // 目标审查闸门包在**最外层**(权限沙箱之前):审查回合只读核实,写类直接拒。
6237
- const planGate = (def) => withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(def, () => this.sandboxes.getByCwd(cwd), () => cwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang());
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));
6238
6336
  const composeWrite = (base) => planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
6239
6337
  const composeEdit = (base) => planGate(wrapEditToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
6240
6338
  const remoteOps = createRemoteSdkOperations(cwd);
@@ -6479,6 +6577,98 @@ export class ClientSession {
6479
6577
  const id = ownerId ?? this.activeId;
6480
6578
  return this.convs.get(id)?.awaitingVerdict != null;
6481
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
+ }
6482
6672
  /**
6483
6673
  * 切换审查者模式(会话级,默认关)。
6484
6674
  * 开启后:① 本对话只审阅(写类/派发类工具硬闸门 + 提示词段);② 用户发的每条
@@ -6613,6 +6803,55 @@ export class ClientSession {
6613
6803
  });
6614
6804
  this.flushSnapshot();
6615
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
+ }
6616
6855
  /**
6617
6856
  * 切换计划模式(会话级,只规划不实施)。
6618
6857
  * 软约束(系统提示词段)+ 硬闸门(写类/旁路工具与非常规 bash 直接拒)双管:
@@ -7002,7 +7241,13 @@ export class ClientSession {
7002
7241
  // 对话执行,主会话这一轮**不跑模型**。接在 promptAc 之后、draft 清理之前:
7003
7242
  // 转走的内容不该把主对话的草稿也清掉(用户可能还想在主对话里追一句)。
7004
7243
  // 计划模式优先(那边直接返回 false)。
7005
- 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)) {
7006
7251
  conv.presetLocked = true;
7007
7252
  return;
7008
7253
  }
@@ -7359,15 +7604,18 @@ export class ClientSession {
7359
7604
  .map((a) => readTextQuote(a.quote))
7360
7605
  .filter((q) => q !== null)
7361
7606
  : [];
7362
- const asides = await buildAttachmentMessages({
7363
- cwd: this.cwd,
7364
- clientId: this.clientId,
7365
- emit: (msg) => this.emit(msg),
7366
- settings: this.settingsSvc.current,
7367
- session: this.session,
7368
- // issue #91:附件/视觉桥文案按客户端 UI 语言出中英(英文默认)。
7369
- getLang: () => this.getLang(),
7370
- }, 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
+ : [];
7371
7619
  if (promptAc.signal.aborted) {
7372
7620
  conv.activePromptAc = undefined;
7373
7621
  // #492:displacement(新对话顶替/会话被移出)在 prompt 前置阶段 abort 时
@@ -7380,29 +7628,65 @@ export class ClientSession {
7380
7628
  });
7381
7629
  return;
7382
7630
  }
7383
- for (const aside of asides) {
7384
- if (s.isStreaming) {
7385
- 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
+ }
7386
7667
  }
7387
- else {
7388
- 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 = [];
7389
7674
  }
7390
7675
  }
7391
- // 附件处理完毕后立即刷新快照,让引用的文件卡片在等待模型首字前瞬间出现在界面上
7392
- if (asides.length > 0) {
7393
- this.flushSnapshot();
7394
- }
7395
- // 创建工作区版本影子快照(Dual-State Rollback)
7396
- let snapshotRef = null;
7397
- try {
7398
- snapshotRef = await createWorkspaceSnapshot(conv.cwd);
7399
- }
7400
- catch {
7401
- // 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
+ }
7402
7686
  }
7403
7687
  if (promptAc.signal.aborted) {
7404
7688
  conv.activePromptAc = undefined;
7405
- // #492:同上——影子快照阶段的 abort 也必须给回执,不能静默黑洞。
7689
+ // #492:同上——前置阶段的 abort 也必须给回执,不能静默黑洞。
7406
7690
  this.emit({
7407
7691
  type: "notice",
7408
7692
  level: "warning",
@@ -7412,7 +7696,7 @@ export class ClientSession {
7412
7696
  return;
7413
7697
  }
7414
7698
  conv.activePromptAc = undefined;
7415
- // 前置阶段(附件 / 影子快照)期间用户可能已经切走或新建了对话:消息仍然
7699
+ // 前置阶段(附件)期间用户可能已经切走或新建了对话:消息仍然
7416
7700
  // 落在本对话里,指给用户看,免得「发出去的消息不见了」。
7417
7701
  if (conv.id !== this.activeId) {
7418
7702
  this.emit({
@@ -7433,31 +7717,36 @@ export class ClientSession {
7433
7717
  // Enter-during-streaming semantic (docs/usage: Enter queues a
7434
7718
  // steering message); followUp would wait for the whole run
7435
7719
  // to finish, which users perceive as ordinary queueing.
7436
- await s.prompt(formatQuotedPrompt(text, streamingQuotes), {
7437
- 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,
7438
7737
  });
7439
7738
  }
7440
7739
  else {
7441
- await s.prompt(formatQuotedPrompt(text, streamingQuotes));
7442
- }
7443
- // 关联快照与本次 prompt 产生的用户消息 entry
7444
- if (snapshotRef) {
7740
+ // 空闲提问:启动工作区版本影子快照(与模型首字并发执行,写工具由门禁等待;
7741
+ // 绑定由 message_end 异步完成,绝不阻塞 prompt 收尾与气泡上屏)。
7742
+ const snapshotPromise = this.startWorkspaceSnapshot(conv);
7445
7743
  try {
7446
- const entries = conv.session.sessionManager.buildContextEntries();
7447
- const lastUserEntry = [...entries]
7448
- .reverse()
7449
- .find((e) => e.type === "message" && e.message?.role === "user");
7450
- conv.workspaceSnapshots.push({
7451
- entryId: lastUserEntry?.id,
7452
- timestamp: Date.now(),
7453
- snapshotRef,
7454
- });
7455
- if (conv.workspaceSnapshots.length > 50) {
7456
- conv.workspaceSnapshots.shift();
7457
- }
7744
+ await s.prompt(formatQuotedPrompt(text, streamingQuotes));
7458
7745
  }
7459
- catch {
7460
- // best-effort
7746
+ finally {
7747
+ if (conv.pendingWorkspaceSnapshot === snapshotPromise) {
7748
+ conv.pendingWorkspaceSnapshot = undefined;
7749
+ }
7461
7750
  }
7462
7751
  }
7463
7752
  }
@@ -7509,6 +7798,9 @@ export class ClientSession {
7509
7798
  this.conv.activePromptAc.abort();
7510
7799
  this.conv.activePromptAc = undefined;
7511
7800
  }
7801
+ if (Array.isArray(this.conv.session?._pendingNextTurnMessages)) {
7802
+ this.conv.session._pendingNextTurnMessages = [];
7803
+ }
7512
7804
  const isRunning = this.conversationStreaming(this.conv) || !this.conv.session.isIdle;
7513
7805
  if (!isRunning) {
7514
7806
  this.flushSnapshot();
@@ -7616,16 +7908,31 @@ export class ClientSession {
7616
7908
  const conv = this.conv;
7617
7909
  // Always-defined display mirrors; also the provenance of bubble rendering.
7618
7910
  const local = kind === "steer" ? conv.queueSteering : conv.queueFollowUp;
7619
- if (!local.includes(text)) {
7620
- // Already gone (delivered / cleared elsewhere) — just refresh the display.
7621
- this.flushSnapshot();
7622
- 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
+ }
7623
7930
  }
7624
7931
  const s = this.conv.session;
7625
7932
  if (!s) {
7626
7933
  // Runtime not bound yet (fresh conversation) — drop the display mirror;
7627
7934
  // a later queue_update reconciles any SDK-side state.
7628
- const next = removeQueuedByIndexOrText(local, text, index);
7935
+ const next = removeQueuedByIndexOrText(local, targetText, index);
7629
7936
  if (next.length !== local.length) {
7630
7937
  local.splice(0, local.length, ...next);
7631
7938
  }
@@ -7642,7 +7949,7 @@ export class ClientSession {
7642
7949
  // 回退到本地显示镜像移除,等 queue_update 对账;绝不把 reject 的 Promise
7643
7950
  // 扔回给 dispatch(无兜底 handler 时 unhandledRejection 直接崩进程)。
7644
7951
  console.error("[agent-service] clearQueue failed while removing a queued message:", err);
7645
- const next = removeQueuedByIndexOrText(local, text, index);
7952
+ const next = removeQueuedByIndexOrText(local, targetText, index);
7646
7953
  if (next.length !== local.length) {
7647
7954
  local.splice(0, local.length, ...next);
7648
7955
  }
@@ -7652,13 +7959,14 @@ export class ClientSession {
7652
7959
  // 气泡 ✕ 对应的是「第几个气泡」(index),不是「哪段文本」:同一文本排队两次时
7653
7960
  // 按文本只会删掉第一条,点第二个气泡却删掉第一个。用 index 定位,位置对不上
7654
7961
  // (队列在点击与执行之间变化)或旧客户端没发 index 时回落到第一处文本匹配。
7655
- const keptSteering = kind === "steer" ? removeQueuedByIndexOrText(steering, text, index) : steering;
7656
- 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;
7657
7964
  // Re-queue the survivors in original order. Guard each call so a single
7658
7965
  // failure can't leave the queue half-drained silently.
7659
7966
  for (const t of keptSteering) {
7660
7967
  try {
7661
- await s.steer(t);
7968
+ const imgs = conv.queuedImages?.get(t);
7969
+ await s.steer(t, imgs);
7662
7970
  }
7663
7971
  catch (err) {
7664
7972
  this.emit({
@@ -7671,7 +7979,8 @@ export class ClientSession {
7671
7979
  }
7672
7980
  for (const t of keptFollowUp) {
7673
7981
  try {
7674
- await s.followUp(t);
7982
+ const imgs = conv.queuedImages?.get(t);
7983
+ await s.followUp(t, imgs);
7675
7984
  }
7676
7985
  catch (err) {
7677
7986
  this.emit({
@@ -7682,6 +7991,10 @@ export class ClientSession {
7682
7991
  });
7683
7992
  }
7684
7993
  }
7994
+ conv.queuedImages?.delete(targetText);
7995
+ if (Array.isArray(s._pendingNextTurnMessages)) {
7996
+ s._pendingNextTurnMessages = [];
7997
+ }
7685
7998
  this.flushSnapshot();
7686
7999
  }
7687
8000
  // -----------------------------------------------------------------------
@@ -8026,11 +8339,12 @@ export class ClientSession {
8026
8339
  const openInProject = [...this.convs.values()].filter((c) => c.cwd === this.cwd && !c.isSubagent && !c.isEphemeral).length;
8027
8340
  const maxOpenConversations = getMaxOpenConversations();
8028
8341
  if (openInProject >= maxOpenConversations) {
8342
+ const notice = this.maxOpenConversationsNotice(maxOpenConversations);
8029
8343
  this.emit({
8030
8344
  type: "notice",
8031
8345
  level: "warning",
8032
- text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
8033
- textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
8346
+ text: notice.text,
8347
+ textEn: notice.textEn,
8034
8348
  });
8035
8349
  return false;
8036
8350
  }
@@ -8439,6 +8753,34 @@ export class ClientSession {
8439
8753
  return { manager, runtime, repair };
8440
8754
  }
8441
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
+ }
8442
8784
  displaceActive() {
8443
8785
  const conv = this.conv;
8444
8786
  // 正在过户给其他会话:绝不就地释放(runtime/终端等整体搬迁给 target)。
@@ -8469,7 +8811,9 @@ export class ClientSession {
8469
8811
  // points at it: dropping an idle in-memory parent orphans the child row
8470
8812
  // (the child vanishes from Running Chats with no result available).
8471
8813
  const hasLiveChild = [...this.convs.values()].some((child) => child.parentId === conv.id);
8814
+ const retainFinished = Boolean(this.settingsSvc?.current.retainFinishedConversations) && this.isConversationStarted(conv);
8472
8815
  const retained = hasLiveChild ||
8816
+ retainFinished ||
8473
8817
  shouldRetainActive({
8474
8818
  reviewing: conv.goal.reviewing,
8475
8819
  wizardRunning: conv.wizardRunning,
@@ -9296,21 +9640,10 @@ export class ClientSession {
9296
9640
  // (<agentDir>/sessions/--<cwd>--/), the same files the pi CLI/TUI
9297
9641
  // use — one listing covers every conversation of the current folder.
9298
9642
  const infos = await this.loadSessionInfos();
9299
- // 隐藏「被 fork 掉的父会话」,历史列表只保留每条 fork 链最新的链尾会话
9300
- // (全文搜索 searchSessions 保留全部会话,不受此影响)。
9301
- const normSessionPath = (p) => normalizePathKey(p);
9302
- const forkedParentPaths = new Set();
9303
- for (const info of infos) {
9304
- if (typeof info.parentSessionPath === "string" && info.parentSessionPath) {
9305
- forkedParentPaths.add(normSessionPath(info.parentSessionPath));
9306
- }
9307
- }
9308
- const visibleInfos = forkedParentPaths.size > 0
9309
- ? (() => {
9310
- const kept = infos.filter((info) => !forkedParentPaths.has(normSessionPath(info.path)));
9311
- return kept.length > 0 ? kept : infos;
9312
- })()
9313
- : infos;
9643
+ // 默认隐藏「被 fork 掉的父会话」(仅保留每条 fork 链最新的链尾会话);
9644
+ // 开启 showForkedParentSessions 时保留全部会话(全文搜索 searchSessions 始终保留全部)。
9645
+ const showForkedParents = this.settingsSvc.current.showForkedParentSessions === true;
9646
+ const visibleInfos = filterForkedParentSessions(infos, showForkedParents);
9314
9647
  const sessions = new Map();
9315
9648
  for (const s of visibleInfos) {
9316
9649
  const isPinned = this.stateStore?.isSessionPinned(this.cwd, s.path);
@@ -9323,6 +9656,7 @@ export class ClientSession {
9323
9656
  modified: s.modified.getTime(),
9324
9657
  source: "web",
9325
9658
  ...(isPinned ? { pinned: true } : {}),
9659
+ ...(s.parentSessionPath ? { parentSessionPath: s.parentSessionPath } : {}),
9326
9660
  });
9327
9661
  }
9328
9662
  const sorted = [...sessions.values()].sort((a, b) => b.modified - a.modified).slice(0, 200); // newest first — the panel shows recent history
@@ -10348,11 +10682,12 @@ export class ClientSession {
10348
10682
  text: `当前项目运行的对话已达上限(${maxOpenConversations} 个)`,
10349
10683
  textEn: `Max open conversations (${maxOpenConversations}) reached`,
10350
10684
  });
10685
+ const notice = this.maxOpenConversationsNotice(maxOpenConversations);
10351
10686
  this.emit({
10352
10687
  type: "notice",
10353
10688
  level: "warning",
10354
- text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
10355
- textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
10689
+ text: notice.text,
10690
+ textEn: notice.textEn,
10356
10691
  });
10357
10692
  return;
10358
10693
  }
@@ -10565,11 +10900,12 @@ export class ClientSession {
10565
10900
  this.conv.listed = oldListed;
10566
10901
  terminals.killAll();
10567
10902
  await runtime.dispose();
10903
+ const notice = this.maxOpenConversationsNotice(maxOpenConversations);
10568
10904
  this.emit({
10569
10905
  type: "notice",
10570
10906
  level: "warning",
10571
- text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
10572
- textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
10907
+ text: notice.text,
10908
+ textEn: notice.textEn,
10573
10909
  });
10574
10910
  return;
10575
10911
  }
@@ -10578,6 +10914,8 @@ export class ClientSession {
10578
10914
  if (displaced)
10579
10915
  this.removeConversation(displaced.id);
10580
10916
  await this.bindSession();
10917
+ this.invalidateSessionInfos();
10918
+ this.scheduleSessionsRefresh();
10581
10919
  // #436:同 switchSession —— 派生出的会话若从转录回放恢复了 planMode,
10582
10920
  // 工厂里的门控当时读不到它,注册后补一次。
10583
10921
  this.applyToolGating(newConv.session, newConv.agentPreset);
@@ -10665,6 +11003,7 @@ export class ClientSession {
10665
11003
  targetConv.lastMessagesArray = [];
10666
11004
  targetConv.queueSteering = [];
10667
11005
  targetConv.queueFollowUp = [];
11006
+ targetConv.queuedImages = new Map();
10668
11007
  try {
10669
11008
  targetConv.session.clearQueue?.();
10670
11009
  }
@@ -10674,6 +11013,14 @@ export class ClientSession {
10674
11013
  // 联动还原物理工作区文件(Dual-State Rollback)
10675
11014
  let workspaceRestored = false;
10676
11015
  if (restoreWorkspace) {
11016
+ if (targetConv.pendingWorkspaceSnapshot) {
11017
+ try {
11018
+ await targetConv.pendingWorkspaceSnapshot;
11019
+ }
11020
+ catch {
11021
+ // best-effort
11022
+ }
11023
+ }
10677
11024
  const entryTs = entry.message?.timestamp ??
10678
11025
  entry.timestamp ??
10679
11026
  0;
@@ -10783,6 +11130,8 @@ export class ClientSession {
10783
11130
  return;
10784
11131
  }
10785
11132
  await this.bindSession();
11133
+ this.invalidateSessionInfos();
11134
+ this.scheduleSessionsRefresh();
10786
11135
  this.conv.uiMessageCache.clear();
10787
11136
  this.conv.msgIds.clear();
10788
11137
  this.conv.userSeqByTs.clear();
@@ -10791,6 +11140,7 @@ export class ClientSession {
10791
11140
  this.conv.lastMessagesArray = [];
10792
11141
  this.conv.queueSteering = [];
10793
11142
  this.conv.queueFollowUp = [];
11143
+ this.conv.queuedImages = new Map();
10794
11144
  // Restore the previously-selected model on the forked branch.
10795
11145
  if (prevModel && this.sharedModelRuntime) {
10796
11146
  try {
@@ -10812,11 +11162,16 @@ export class ClientSession {
10812
11162
  }
10813
11163
  }
10814
11164
  await this.prompt(trimmed, attachments);
11165
+ const showParents = this.settingsSvc.current.showForkedParentSessions === true;
10815
11166
  this.emit({
10816
11167
  type: "notice",
10817
11168
  level: "info",
10818
- text: "已从该问题重新提问(原对话保留在会话列表中)",
10819
- 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)",
10820
11175
  });
10821
11176
  }
10822
11177
  catch (err) {
@@ -11210,10 +11565,10 @@ export class ClientSession {
11210
11565
  // 别处无可见行时不扫目录(首访切项目的常见情形零开销)。
11211
11566
  if ((this.listExternalRunning?.() ?? []).length > 0) {
11212
11567
  try {
11213
- const infos = await SessionManager.list(sessionBaseDir, piSessionsRoot());
11214
- const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
11568
+ const recentPath = await findMostRecentSessionFileFast(sessionBaseDir, abs);
11569
+ const recent = recentPath ? resolve(recentPath) : undefined;
11215
11570
  const owner = recent ? this.findSessionOwner?.(recent) : null;
11216
- if (owner) {
11571
+ if (owner && (owner.connected || owner.isStreaming)) {
11217
11572
  resumeSkipped = owner;
11218
11573
  }
11219
11574
  }
@@ -11229,7 +11584,7 @@ export class ClientSession {
11229
11584
  cwd: sessionBaseDir,
11230
11585
  agentDir: this.agentDir,
11231
11586
  sessionManager: m,
11232
- }), async () => (await SessionManager.list(sessionBaseDir))[0]?.path, async (m) => {
11587
+ }), () => findMostRecentSessionFileFast(sessionBaseDir, abs), async (m) => {
11233
11588
  const { totalMessages, previewMessages } = this.extractTranscriptPreview(m, 16);
11234
11589
  this.emit({
11235
11590
  type: "transition_progress",
@@ -11325,6 +11680,7 @@ export class ClientSession {
11325
11680
  // 切项目即换了当前打开对话 → 插件重拉。
11326
11681
  this.notifyConversationChanged();
11327
11682
  this.pushSettings();
11683
+ void this.refreshWorktreeInfo();
11328
11684
  }
11329
11685
  catch (err) {
11330
11686
  this.emit({
@@ -11558,6 +11914,48 @@ export class ClientSession {
11558
11914
  });
11559
11915
  }
11560
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
+ }
11561
11959
  /** Strip the "(New)" freshness marker some catalogs append to display names
11562
11960
  * (pi.dev data, e.g. "DeepSeek V4 Pro (New)") — display-only; the model id
11563
11961
  * is untouched so switching still uses the exact official id. */