pi-web-ui 0.115.0 → 0.117.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +65 -2
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +159 -71
  4. package/dist/server/agent-service-daemon.js +136 -8
  5. package/dist/server/agent-service.js +594 -159
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +52 -8
  8. package/dist/server/compaction-markers.js +43 -24
  9. package/dist/server/dangling-tools.js +172 -16
  10. package/dist/server/device-center/bot-execution.js +77 -2
  11. package/dist/server/device-center/collab-service.js +61 -12
  12. package/dist/server/device-center/collab-tool.js +482 -21
  13. package/dist/server/device-center/connector.js +107 -37
  14. package/dist/server/device-center/delivery-authority.js +98 -0
  15. package/dist/server/device-center/delivery-subject.js +30 -0
  16. package/dist/server/device-center/device-integration.js +453 -183
  17. package/dist/server/device-center/execution-guides.js +17 -7
  18. package/dist/server/device-center/execution-instructions.js +2 -1
  19. package/dist/server/device-center/execution-settings.js +138 -25
  20. package/dist/server/device-center/executor.js +51 -6
  21. package/dist/server/device-center/file-sync.js +14 -13
  22. package/dist/server/device-center/group-context-message.js +3 -1
  23. package/dist/server/device-center/group-context.js +73 -3
  24. package/dist/server/device-center/hub-conversations.js +71 -6
  25. package/dist/server/device-center/hub-deliveries.js +120 -15
  26. package/dist/server/device-center/hub-integration.js +655 -334
  27. package/dist/server/device-center/hub-locks.js +320 -0
  28. package/dist/server/device-center/hub-page.js +16 -35
  29. package/dist/server/device-center/hub-setup.js +23 -1
  30. package/dist/server/device-center/hub-transaction-log.js +197 -0
  31. package/dist/server/device-center/hub-webhooks.js +165 -0
  32. package/dist/server/device-center/hub.js +1531 -305
  33. package/dist/server/device-center/integration-verification.js +113 -0
  34. package/dist/server/device-center/local-hub.js +8 -3
  35. package/dist/server/device-center/local-publication.js +423 -0
  36. package/dist/server/device-center/local-verification-job.js +97 -0
  37. package/dist/server/device-center/local-verification.js +274 -0
  38. package/dist/server/device-center/local.js +181 -13
  39. package/dist/server/device-center/main.js +4 -1
  40. package/dist/server/device-center/partition-log.js +330 -0
  41. package/dist/server/device-center/publication-journal.js +312 -0
  42. package/dist/server/device-center/publish-intent.js +379 -0
  43. package/dist/server/device-center/relay.js +134 -24
  44. package/dist/server/device-center/runtime.js +475 -42
  45. package/dist/server/device-center/store.js +366 -89
  46. package/dist/server/device-center/task-outcome.js +81 -0
  47. package/dist/server/device-center/task-recovery.js +603 -178
  48. package/dist/server/device-center/task-scheduler.js +48 -3
  49. package/dist/server/device-center/task-settlement.js +353 -0
  50. package/dist/server/device-center/task-workspace.js +443 -0
  51. package/dist/server/device-center/transfers.js +41 -15
  52. package/dist/server/device-center/verification-limits.js +10 -0
  53. package/dist/server/device-center/work-contract.js +995 -0
  54. package/dist/server/dispatch-domain-handlers.js +29 -3
  55. package/dist/server/dsh/dsh-agent-service.js +9 -2
  56. package/dist/server/engine-probe.js +112 -1
  57. package/dist/server/global-loader.js +119 -19
  58. package/dist/server/index.js +159 -17
  59. package/dist/server/managed.js +2 -0
  60. package/dist/server/model-admin.js +48 -6
  61. package/dist/server/model-enrich.js +10 -1
  62. package/dist/server/patch-node-pty.js +3 -2
  63. package/dist/server/patch-remote-catalog.js +3 -2
  64. package/dist/server/plugins.js +64 -7
  65. package/dist/server/preset-fields.js +17 -1
  66. package/dist/server/preset-share.js +1 -0
  67. package/dist/server/prompt-composer.js +39 -0
  68. package/dist/server/protocol-version.js +1 -1
  69. package/dist/server/quick-ask-settings.js +28 -0
  70. package/dist/server/quick-ask.js +164 -0
  71. package/dist/server/reasoning-registry.js +207 -0
  72. package/dist/server/resolve-global-sdk.js +61 -11
  73. package/dist/server/scheduler-tasks.js +35 -8
  74. package/dist/server/session-list-scan.js +223 -0
  75. package/dist/server/session-open.js +93 -0
  76. package/dist/server/session-parser.js +4 -0
  77. package/dist/server/session-scan.js +90 -38
  78. package/dist/server/settings-service.js +9 -1
  79. package/dist/server/soft-cap.js +5 -0
  80. package/dist/server/startup-banner.js +35 -0
  81. package/dist/server/subagents.js +2 -1
  82. package/dist/server/tool-manager.js +17 -9
  83. package/dist/server/transcript-prepare.js +73 -0
  84. package/dist/server/unauthorized-page.js +319 -0
  85. package/dist/server/universal/drivers/claude-code.js +98 -34
  86. package/dist/server/universal/universal-session.js +4 -0
  87. package/dist/server/workspace-handle.js +428 -0
  88. package/docs/architecture-plugins.md +959 -0
  89. package/docs/device-center.md +34 -20
  90. package/package.json +4 -4
  91. package/plugin-sdk/README.md +16 -8
  92. package/plugin-sdk/client.d.ts +27 -0
  93. package/plugin-sdk/client.mjs +82 -0
  94. package/plugin-sdk/index.d.ts +10 -0
  95. package/plugin-sdk/index.mjs +4 -683
  96. package/plugin-sdk/package.json +15 -4
  97. package/plugin-sdk/testing.d.ts +10 -0
  98. package/plugin-sdk/testing.mjs +566 -0
  99. package/themes/flow-cristallo.css +168 -0
  100. package/themes/flow-ink.css +169 -0
  101. package/themes/flow-obsidian.css +169 -0
  102. package/themes/flow-zurich.css +169 -0
  103. package/web/dist/.build-assets.json +1 -1
  104. package/web/dist/assets/{BgTasksModal-BYzPgmoq.js → BgTasksModal-BjNRIUIc.js} +1 -1
  105. package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0zuU8FE.js} +1 -1
  106. package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  107. package/web/dist/assets/{CanvasStudio-BCUeEf25.js → CanvasStudio-VQFjmTGq.js} +3 -3
  108. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  109. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  110. package/web/dist/assets/DeviceExecutionSettings-BLP1Su5G.js +1 -0
  111. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  112. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  113. package/web/dist/assets/{Dropdown-CGXD0DfT.js → Dropdown-CQtstPGv.js} +1 -1
  114. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  115. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  116. package/web/dist/assets/{GlobalSearchModal-mevF-ySi.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  117. package/web/dist/assets/{GlobalSearchModal-qL99FN_F.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  118. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  119. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  120. package/web/dist/assets/{HintTip-LHwkS2jV.js → HintTip-ChTW8o1m.js} +1 -1
  121. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  122. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  123. package/web/dist/assets/{PiSetupModal-DE5-gEtI.js → PiSetupModal-BX5rUuoI.js} +1 -1
  124. package/web/dist/assets/{ProviderOAuthControls-6UMARucA.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  125. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  126. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  127. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  128. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  129. package/web/dist/assets/{TerminalPanel-CTp_BZ4S.js → TerminalPanel-D4By_RVc.js} +2 -2
  130. package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-lZw8-i3j.js} +2 -2
  131. package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  132. package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  133. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  134. package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-BY6ojmle.js} +1 -1
  135. package/web/dist/assets/{desktop-kjBoE3Nu.js → desktop-CV6KKp9R.js} +1 -1
  136. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  137. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  138. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  139. package/web/dist/assets/{plugin-host-C8mNgghx.js → plugin-host-Dn8Dd6SC.js} +1 -1
  140. package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  141. package/web/dist/assets/{theme-BXGpyTMh.js → theme-D_bihpdN.js} +1 -1
  142. package/web/dist/index.html +11 -11
  143. package/web/dist/sw.js +1 -1
  144. package/dist/server/patch-turn-end-boundary.js +0 -77
  145. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +0 -3
  146. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +0 -3
  147. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +0 -1
  148. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +0 -1
  149. package/web/dist/assets/FilePreview-B8iqnBjy.js +0 -2
  150. package/web/dist/assets/FilePreview-BqviZKCN.js +0 -2
  151. package/web/dist/assets/GroupConversation-B88Yy-lt.js +0 -3
  152. package/web/dist/assets/GroupConversation-BwP5NVOE.js +0 -3
  153. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +0 -2
  154. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +0 -2
  155. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +0 -2
  156. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +0 -20
  157. package/web/dist/assets/SettingsModal-CF-7MwqS.js +0 -20
  158. package/web/dist/assets/app-globals-DZNa9v8u.js +0 -325
  159. package/web/dist/assets/index-CsFs_HMb.css +0 -1
  160. package/web/dist/assets/index-DHeeHS_l.js +0 -85
  161. package/web/dist/assets/index-DTZch8uz.js +0 -85
@@ -1,79 +1,10 @@
1
- import { execFile } from "node:child_process";
2
1
  import { createHash, randomUUID } from "node:crypto";
3
- import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
4
- import { isAbsolute, join, relative, resolve, sep } from "node:path";
5
- function checkSignal(signal) {
6
- signal?.throwIfAborted();
7
- }
8
- function safeId(value) {
9
- if (!/^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{0,127}$/.test(value) || value === "." || value === "..") {
10
- throw new Error(`Invalid canvas workspace identifier: ${value}`);
11
- }
12
- return value;
13
- }
14
- function inside(root, path) {
15
- const rel = relative(root, path);
16
- return !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
17
- }
18
- async function canonicalPath(path) {
19
- try {
20
- return await realpath(path);
21
- }
22
- catch (error) {
23
- if (error.code !== "ENOENT")
24
- throw error;
25
- const parent = resolve(path, "..");
26
- if (parent === path)
27
- throw error;
28
- return join(await canonicalPath(parent), relative(parent, path));
29
- }
30
- }
31
- async function git(cwd, args, signal, index, input) {
32
- checkSignal(signal);
33
- // Never let an inherited Git context redirect commands to the user's other repository/index.
34
- const env = { ...process.env };
35
- for (const key of Object.keys(env)) {
36
- if (/^GIT_/i.test(key))
37
- delete env[key];
38
- }
39
- if (index)
40
- env.GIT_INDEX_FILE = index;
41
- const stdout = await new Promise((done, reject) => {
42
- const child = execFile("git", ["-c", "core.hooksPath=", ...args], {
43
- cwd,
44
- signal,
45
- windowsHide: true,
46
- timeout: 60_000,
47
- maxBuffer: 64 * 1024 * 1024,
48
- env,
49
- }, (error, stdout) => (error ? reject(error) : done(stdout)));
50
- // Apply the bytes we validated, rather than reopening an attacker-replaceable path.
51
- child.stdin?.on("error", () => {
52
- /* execFile reports process failure. */
53
- });
54
- child.stdin?.end(input);
55
- });
56
- checkSignal(signal);
57
- return stdout;
58
- }
2
+ import { mkdir, readFile, realpath, writeFile } from "node:fs/promises";
3
+ import { join, relative, resolve, sep } from "node:path";
4
+ import { canonicalPath, checkSignal, createDetachedWorktree, git, inside, safeId, snapshotTree, verifyWorktreeIdentity, } from "../workspace-handle.js";
59
5
  function workspaceDir(workspace, kind) {
60
6
  return join(resolve(workspace.dataDir), "canvas", kind, safeId(workspace.graphId), safeId(workspace.runId), safeId(workspace.nodeId));
61
7
  }
62
- /** Build a tree without touching the user's index, branch, or commit history. Ignored files are excluded. */
63
- async function snapshotTree(cwd, dataDir, signal) {
64
- const scratch = join(resolve(dataDir), "canvas", "indexes");
65
- await mkdir(scratch, { recursive: true });
66
- const index = join(scratch, randomUUID());
67
- try {
68
- await git(cwd, ["read-tree", "HEAD"], signal, index);
69
- await git(cwd, ["add", "-A", "--", "."], signal, index);
70
- return (await git(cwd, ["write-tree"], signal, index)).trim();
71
- }
72
- finally {
73
- await rm(index, { force: true });
74
- await rm(`${index}.lock`, { force: true });
75
- }
76
- }
77
8
  function layersOf(artifacts) {
78
9
  const layers = new Map();
79
10
  for (const artifact of artifacts) {
@@ -102,6 +33,7 @@ async function trustedArtifactPath(workspace, path, nodeId) {
102
33
  }
103
34
  return resolved;
104
35
  }
36
+ const workspaceIdentities = new WeakMap();
105
37
  async function assertWorkspaceIdentity(workspace, signal) {
106
38
  const expected = workspaceDir(workspace, "workspaces");
107
39
  if (!workspace.worktreePath ||
@@ -110,18 +42,14 @@ async function assertWorkspaceIdentity(workspace, signal) {
110
42
  (await realpath(expected)) !== expected) {
111
43
  throw new Error("Canvas worktree identity mismatch: canonical path changed");
112
44
  }
113
- const top = (await git(expected, ["rev-parse", "--show-toplevel"], signal)).trim();
114
- const common = (await git(expected, ["rev-parse", "--path-format=absolute", "--git-common-dir"], signal)).trim();
115
- const sourceCommon = (await git(workspace.repoRoot, ["rev-parse", "--path-format=absolute", "--git-common-dir"], signal)).trim();
116
- const gitDir = (await git(expected, ["rev-parse", "--absolute-git-dir"], signal)).trim();
117
- const canonicalGitDir = await realpath(gitDir);
118
- const canonicalCommon = await realpath(common);
119
- if (resolve(top) !== expected ||
120
- canonicalCommon !== (await realpath(sourceCommon)) ||
121
- canonicalGitDir === canonicalCommon ||
122
- !inside(join(canonicalCommon, "worktrees"), canonicalGitDir) ||
123
- resolve((await readFile(join(canonicalGitDir, "gitdir"), "utf8")).trim()) !== join(expected, ".git")) {
124
- throw new Error("Canvas worktree identity mismatch: Git repository changed");
45
+ try {
46
+ const identity = workspaceIdentities.get(workspace);
47
+ if (!identity)
48
+ throw new Error("Unregistered canvas workspace");
49
+ await verifyWorktreeIdentity(expected, workspace.repoRoot, signal, identity.gitDir, identity.commonDir);
50
+ }
51
+ catch (error) {
52
+ throw new Error("Canvas worktree identity mismatch: Git repository changed", { cause: error });
125
53
  }
126
54
  }
127
55
  /** No fallback: an isolation request either returns a detached worktree or throws. */
@@ -199,7 +127,7 @@ export async function prepareCanvasWorkspace(options) {
199
127
  await mkdir(resolve(worktreePath, ".."), { recursive: true });
200
128
  if ((await canonicalPath(worktreePath)) !== worktreePath)
201
129
  throw new Error("Canvas worktree path is redirected");
202
- await git(repoRoot, ["worktree", "add", "--detach", worktreePath, baseCommit], options.signal);
130
+ await createDetachedWorktree(repoRoot, worktreePath, baseCommit, options.signal);
203
131
  // Once created, failures deliberately retain the workspace for inspection. Never remove dirty outputs.
204
132
  for (const { layer, bytes } of patches) {
205
133
  checkSignal(options.signal);
@@ -220,7 +148,7 @@ export async function prepareCanvasWorkspace(options) {
220
148
  if (!inside(worktreePath, await canonicalPath(preparedCwd)))
221
149
  throw new Error("Canvas integrated cwd escapes its worktree");
222
150
  checkSignal(options.signal);
223
- return {
151
+ const prepared = {
224
152
  ...workspace,
225
153
  cwd: preparedCwd,
226
154
  repoRoot,
@@ -228,6 +156,9 @@ export async function prepareCanvasWorkspace(options) {
228
156
  baseCommit,
229
157
  inputTree: await snapshotTree(worktreePath, workspace.dataDir, options.signal),
230
158
  };
159
+ const identity = await verifyWorktreeIdentity(worktreePath, repoRoot, options.signal);
160
+ workspaceIdentities.set(prepared, { gitDir: identity.gitDir, commonDir: identity.commonDir });
161
+ return prepared;
231
162
  }
232
163
  /** Includes tracked changes, deletions, and non-ignored untracked files, including binary additions. */
233
164
  export async function captureCanvasWorkspaceArtifact(workspace, options = {}) {
@@ -281,4 +212,5 @@ export async function cleanupCanvasWorkspace(workspace, options = {}) {
281
212
  throw new Error("Canvas workspace has pending artifacts or commits; retained for explicit adoption");
282
213
  }
283
214
  await git(workspace.repoRoot, ["worktree", "remove", workspace.worktreePath], options.signal);
215
+ workspaceIdentities.delete(workspace);
284
216
  }
@@ -11,14 +11,26 @@ import { normalizeUploadMaxMb } from "./payload-limits.js";
11
11
  import * as fsPromises from "node:fs/promises";
12
12
  import { dirname, isAbsolute, resolve } from "node:path";
13
13
  import { writeJsonAtomicSync } from "./atomic-file.js";
14
- import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
14
+ import { normalizeAutoCompactionInstructions, normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
15
15
  import { deriveLegacy, legacyToDisabled, normalizeDisabledAgentTools } from "./tool-manager.js";
16
16
  import { normalizeToolPromptOverrides } from "./tool-prompt-overrides.js";
17
17
  import { UI_SLOTS } from "./plugin-ui-slots.js";
18
+ import { DEFAULT_PROMPT_DISABLED } from "./prompt-composer.js";
19
+ import { mergeQuickAskSettings, normalizeQuickAskSettings } from "./quick-ask-settings.js";
18
20
  /** Persisted queue modes fall back to processing all queued messages. */
19
21
  export function normalizeQueueMode(value) {
20
22
  return value === "one-at-a-time" ? value : "all";
21
23
  }
24
+ export function normalizePromptDisabled(stored) {
25
+ if (!stored || stored.promptDisabled === undefined) {
26
+ return [...DEFAULT_PROMPT_DISABLED];
27
+ }
28
+ const list = [...stored.promptDisabled];
29
+ if (!stored._promptPluginDevConfigured && !list.includes("plugin_dev")) {
30
+ list.push("plugin_dev");
31
+ }
32
+ return list;
33
+ }
22
34
  /** 大模型 API 出错自动重试次数的默认值(SDK 默认 3)。 */
23
35
  export const DEFAULT_RETRY_MAX_ATTEMPTS = 6;
24
36
  /** 工具执行看门狗超时的默认值(默认 20 分钟;环境变量 PI_WEB_TOOL_TIMEOUT_MS 覆盖)。 */
@@ -464,6 +476,9 @@ export const CLIENT_STATE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
464
476
  * 淘汰最旧的。兜底上限:完全无时间戳可推断的存量键不按年龄淘汰,靠它保证
465
477
  * client-state.json 不随时间无界膨胀。 */
466
478
  export const MAX_TRACKED_CLIENTS = 50;
479
+ /** 最近项目上限(记录、合并读取、推送给左栏共用)。原为 30:项目多的用户有一部分永远出现不了。
480
+ * 读取时每个候选做一次异步 fs.access 探测(并发),100 次探测的开销可忽略。 */
481
+ export const RECENT_PROJECTS_MAX = 100;
467
482
  /** 死键清理扫描的最小间隔:load() 是所有读写的高频入口,扫描按 1 小时节流,
468
483
  * 首次加载必扫。 */
469
484
  export const CLIENT_STATE_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
@@ -541,8 +556,27 @@ export class ClientStateStore {
541
556
  }
542
557
  }
543
558
  }
544
- // 死键清理(issue #441):在墓碑迁移之后做——各 client 的墓碑已先并入全局键,
545
- // 淘汰死 client 不会丢墓碑;合并一次 save 落盘(迁移和淘汰只发生一次时也只写一遍)。
559
+ // 老版本的最近项目可能仅存在临时 clientId 下。先按全部墓碑过滤并迁移到全局,
560
+ // 再淘汰死 client,避免持久化列表丢失历史项目;只在首次加载时合并,不扫描磁盘历史。
561
+ const projectsByKey = new Map();
562
+ for (const state of Object.values(this.cache)) {
563
+ for (const project of state.projects ?? []) {
564
+ const key = normalizePathKey(project.path);
565
+ if (globalSet.has(key))
566
+ continue;
567
+ const existing = projectsByKey.get(key);
568
+ if (!existing || project.lastUsed > existing.lastUsed)
569
+ projectsByKey.set(key, project);
570
+ }
571
+ }
572
+ const projects = [...projectsByKey.values()].sort((a, b) => b.lastUsed - a.lastUsed).slice(0, RECENT_PROJECTS_MAX);
573
+ const previousProjects = globalState.projects ?? [];
574
+ if (projects.length !== previousProjects.length ||
575
+ projects.some((p, i) => p.path !== previousProjects[i].path || p.lastUsed !== previousProjects[i].lastUsed)) {
576
+ globalState.projects = projects;
577
+ migrated = true;
578
+ }
579
+ // 死键清理(issue #441):墓碑和最近项目均迁移完毕后再淘汰,合并一次 save 落盘。
546
580
  this.lastSweepAt = Date.now();
547
581
  const evicted = this.sweepDeadClients();
548
582
  if (migrated || evicted > 0) {
@@ -641,13 +675,13 @@ export class ClientStateStore {
641
675
  state.projects = [
642
676
  { path: cwd, lastUsed: now },
643
677
  ...state.projects.filter((p) => normalizePathKey(p.path) !== targetKey),
644
- ].slice(0, 30);
678
+ ].slice(0, RECENT_PROJECTS_MAX);
645
679
  // Also persist in global settings so new tabs and sessions inherit it immediately
646
680
  const globalState = (all[ClientStateStore.GLOBAL_SETTINGS_KEY] ??= { projects: [] });
647
681
  globalState.projects = [
648
682
  { path: cwd, lastUsed: now },
649
683
  ...(globalState.projects ?? []).filter((p) => normalizePathKey(p.path) !== targetKey),
650
- ].slice(0, 50);
684
+ ].slice(0, RECENT_PROJECTS_MAX);
651
685
  // Opening the workspace again clears its removal tombstone across all clients and global settings.
652
686
  for (const cState of Object.values(all)) {
653
687
  if (cState.removedProjects?.length) {
@@ -744,7 +778,7 @@ export class ClientStateStore {
744
778
  }
745
779
  }
746
780
  // 先截断后探测:探测次数 ≤ 30,且并发执行(Promise.allSettled 吸收单点失败)。
747
- const candidates = [...map.values()].sort((a, b) => b.lastUsed - a.lastUsed).slice(0, 30);
781
+ const candidates = [...map.values()].sort((a, b) => b.lastUsed - a.lastUsed).slice(0, RECENT_PROJECTS_MAX);
748
782
  const probes = await Promise.allSettled(candidates.map((p) => this.pathExists(p.path)));
749
783
  return candidates.filter((_, i) => {
750
784
  const probe = probes[i];
@@ -903,7 +937,8 @@ export class ClientStateStore {
903
937
  customSystemPrompt: stored?.customSystemPrompt ?? "",
904
938
  promptTemplate,
905
939
  promptOverrides,
906
- promptDisabled: stored?.promptDisabled ?? [],
940
+ promptDisabled: normalizePromptDisabled(stored),
941
+ _promptPluginDevConfigured: stored?._promptPluginDevConfigured,
907
942
  toolPromptOverrides: normalizeToolPromptOverrides(stored?.toolPromptOverrides),
908
943
  disabledSkills: stored?.disabledSkills ?? [],
909
944
  disabledExtensions: stored?.disabledExtensions ?? [],
@@ -965,6 +1000,7 @@ export class ClientStateStore {
965
1000
  visionBridgePrompt: stored?.visionBridgePrompt ?? "",
966
1001
  scmCommitMsgPromptMode: stored?.scmCommitMsgPromptMode === "replace" ? "replace" : "append",
967
1002
  scmCommitMsgPrompt: stored?.scmCommitMsgPrompt ?? "",
1003
+ ...normalizeQuickAskSettings(stored ?? {}),
968
1004
  planModePromptMode: stored?.planModePromptMode === "replace" ? "replace" : "append",
969
1005
  planModePrompt: stored?.planModePrompt ?? "",
970
1006
  subagentDefaultModel: stored?.subagentDefaultModel ?? null,
@@ -975,6 +1011,7 @@ export class ClientStateStore {
975
1011
  retryMaxAttempts: normalizeRetryMaxAttempts(stored?.retryMaxAttempts),
976
1012
  softCapTokens: normalizeSoftCapTokens(stored?.softCapTokens),
977
1013
  softCapByModel: normalizeSoftCapByModel(stored?.softCapByModel),
1014
+ autoCompactionInstructions: normalizeAutoCompactionInstructions(stored?.autoCompactionInstructions),
978
1015
  quickPhrases: stored?.quickPhrases ?? [],
979
1016
  quickPhrasesEnabled: stored?.quickPhrasesEnabled ?? true,
980
1017
  minimalNewChat: stored?.minimalNewChat ?? false,
@@ -1002,7 +1039,10 @@ export class ClientStateStore {
1002
1039
  customSystemPrompt: settings.customSystemPrompt ?? cur.customSystemPrompt ?? "",
1003
1040
  promptTemplate: settings.promptTemplate ?? cur.promptTemplate ?? "",
1004
1041
  promptOverrides: { ...(settings.promptOverrides ?? cur.promptOverrides) },
1005
- promptDisabled: settings.promptDisabled ?? cur.promptDisabled ?? [],
1042
+ promptDisabled: settings.promptDisabled !== undefined
1043
+ ? [...settings.promptDisabled]
1044
+ : (cur.promptDisabled ?? [...DEFAULT_PROMPT_DISABLED]),
1045
+ _promptPluginDevConfigured: settings.promptDisabled !== undefined ? true : (cur._promptPluginDevConfigured ?? false),
1006
1046
  toolPromptOverrides: normalizeToolPromptOverrides(settings.toolPromptOverrides ?? cur.toolPromptOverrides),
1007
1047
  disabledSkills: settings.disabledSkills ?? cur.disabledSkills ?? [],
1008
1048
  disabledExtensions: settings.disabledExtensions ?? cur.disabledExtensions ?? [],
@@ -1062,10 +1102,12 @@ export class ClientStateStore {
1062
1102
  retryMaxAttempts: normalizeRetryMaxAttempts(settings.retryMaxAttempts ?? cur.retryMaxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS),
1063
1103
  softCapTokens: normalizeSoftCapTokens(settings.softCapTokens ?? cur.softCapTokens ?? 0),
1064
1104
  softCapByModel: normalizeSoftCapByModel(settings.softCapByModel ?? cur.softCapByModel ?? {}),
1105
+ autoCompactionInstructions: normalizeAutoCompactionInstructions(settings.autoCompactionInstructions ?? cur.autoCompactionInstructions ?? ""),
1065
1106
  visionBridgePromptMode: settings.visionBridgePromptMode ?? cur.visionBridgePromptMode ?? "append",
1066
1107
  visionBridgePrompt: settings.visionBridgePrompt ?? cur.visionBridgePrompt ?? "",
1067
1108
  scmCommitMsgPromptMode: settings.scmCommitMsgPromptMode ?? cur.scmCommitMsgPromptMode ?? "append",
1068
1109
  scmCommitMsgPrompt: settings.scmCommitMsgPrompt ?? cur.scmCommitMsgPrompt ?? "",
1110
+ ...mergeQuickAskSettings(cur, settings),
1069
1111
  planModePromptMode: settings.planModePromptMode ?? cur.planModePromptMode ?? "append",
1070
1112
  planModePrompt: settings.planModePrompt ?? cur.planModePrompt ?? "",
1071
1113
  reviewPrompt: settings.reviewPrompt ?? cur.reviewPrompt ?? "",
@@ -1125,6 +1167,8 @@ export class ClientStateStore {
1125
1167
  }
1126
1168
  if (Object.hasOwn(p, "softCapByModel"))
1127
1169
  preset.softCapByModel = normalizeSoftCapByModel(p.softCapByModel);
1170
+ if (Object.hasOwn(p, "autoCompactionInstructions"))
1171
+ preset.autoCompactionInstructions = normalizeAutoCompactionInstructions(p.autoCompactionInstructions);
1128
1172
  return preset;
1129
1173
  });
1130
1174
  }
@@ -361,20 +361,23 @@ const HEALTHY_TRANSCRIPT_CACHE_MAX = 512;
361
361
  function rememberHealthyTranscript(filePath) {
362
362
  try {
363
363
  const st = statSync(filePath);
364
- const sig = `${st.mtimeMs}:${st.size}`;
365
- healthyTranscriptCache.delete(filePath);
366
- healthyTranscriptCache.set(filePath, sig);
367
- while (healthyTranscriptCache.size > HEALTHY_TRANSCRIPT_CACHE_MAX) {
368
- const oldest = healthyTranscriptCache.keys().next();
369
- if (oldest.done)
370
- break;
371
- healthyTranscriptCache.delete(oldest.value);
372
- }
364
+ rememberHealthyTranscriptSig(filePath, `${st.mtimeMs}:${st.size}`);
373
365
  }
374
366
  catch {
375
367
  /* best effort */
376
368
  }
377
369
  }
370
+ /** 以给定指纹记住健康文件(调用方已 stat;用于打开流程在悬空调用修复追加后统一刷新指纹)。 */
371
+ export function rememberHealthyTranscriptSig(filePath, sig) {
372
+ healthyTranscriptCache.delete(filePath);
373
+ healthyTranscriptCache.set(filePath, sig);
374
+ while (healthyTranscriptCache.size > HEALTHY_TRANSCRIPT_CACHE_MAX) {
375
+ const oldest = healthyTranscriptCache.keys().next();
376
+ if (oldest.done)
377
+ break;
378
+ healthyTranscriptCache.delete(oldest.value);
379
+ }
380
+ }
378
381
  /**
379
382
  * 落盘版修复:健康文件只读不写;坏文件先写 <原名>.bak(已存在则保留最早那份,
380
383
  * 不覆盖),再写回修复文本。读失败/写失败返回 null(调用方按原错误继续抛)。
@@ -383,21 +386,8 @@ export function repairSessionFile(filePath) {
383
386
  try {
384
387
  const st = statSync(filePath);
385
388
  const sig = `${st.mtimeMs}:${st.size}`;
386
- if (healthyTranscriptCache.get(filePath) === sig) {
387
- healthyTranscriptCache.delete(filePath);
388
- healthyTranscriptCache.set(filePath, sig);
389
- return {
390
- text: "",
391
- changed: false,
392
- removedPending: 0,
393
- renamedIds: 0,
394
- rewiredParents: 0,
395
- cyclesBroken: 0,
396
- interrupted: false,
397
- file: filePath,
398
- backup: null,
399
- };
400
- }
389
+ if (isTranscriptHealthyCached(filePath, sig))
390
+ return healthyRepairResult(filePath);
401
391
  }
402
392
  catch {
403
393
  return null;
@@ -409,6 +399,35 @@ export function repairSessionFile(filePath) {
409
399
  catch {
410
400
  return null;
411
401
  }
402
+ return repairSessionFileFromText(filePath, raw);
403
+ }
404
+ /** 健康指纹命中即续期(LRU)。sig = `${mtimeMs}:${size}`。 */
405
+ export function isTranscriptHealthyCached(filePath, sig) {
406
+ if (healthyTranscriptCache.get(filePath) !== sig)
407
+ return false;
408
+ healthyTranscriptCache.delete(filePath);
409
+ healthyTranscriptCache.set(filePath, sig);
410
+ return true;
411
+ }
412
+ /** 无需修复时的统一返回值(text 为空:调用方不读它)。 */
413
+ export function healthyRepairResult(filePath) {
414
+ return {
415
+ text: "",
416
+ changed: false,
417
+ removedPending: 0,
418
+ renamedIds: 0,
419
+ rewiredParents: 0,
420
+ cyclesBroken: 0,
421
+ interrupted: false,
422
+ file: filePath,
423
+ backup: null,
424
+ };
425
+ }
426
+ /**
427
+ * 与 repairSessionFile 相同,但使用调用方已读入的文本(打开会话时与悬空调用检查共用一次读盘)。
428
+ * 健康:记住指纹并返回 changed=false;有坏:写 .bak 与修复文本(同步写,仅坏文件才发生)。
429
+ */
430
+ export function repairSessionFileFromText(filePath, raw) {
412
431
  const r = repairSessionTranscript(raw);
413
432
  if (!r.changed) {
414
433
  rememberHealthyTranscript(filePath);
@@ -23,7 +23,7 @@
23
23
  * - healDanglingToolCallFile:落盘版,仅针对当前分支尾部生效的悬空调用追加合成 toolResult;
24
24
  * - 合成结果文案:danglingToolResultText(cause)(按成因归因,中英各一,toolResult content 只带一条文本)。
25
25
  */
26
- import { appendFileSync, existsSync, readFileSync } from "node:fs";
26
+ import { appendFileSync, existsSync, readFileSync, statSync } from "node:fs";
27
27
  import { randomUUID } from "node:crypto";
28
28
  const DANGLING_TEXT = {
29
29
  generic: {
@@ -178,6 +178,18 @@ export function tailAssistantToolCallIds(entries, lastId) {
178
178
  * 返回追加条数(0 = 健康,无需处理;-1 = 文件不可读/不可写)。
179
179
  */
180
180
  export function healDanglingToolCallFile(filePath, cause = "generic") {
181
+ // 健康指纹命中:文件自上次判定"无悬空调用"后 mtime/size 未变,结果必然仍为 0,
182
+ // 跳过整文件同步读取(打开大转录时这是阻塞事件循环的主要来源之一)。
183
+ let sig = null;
184
+ try {
185
+ const st = statSync(filePath);
186
+ sig = `${st.mtimeMs}:${st.size}`;
187
+ if (isDanglingHealthyCached(filePath, sig))
188
+ return 0;
189
+ }
190
+ catch {
191
+ return -1;
192
+ }
181
193
  let raw;
182
194
  try {
183
195
  raw = readFileSync(filePath, "utf8");
@@ -185,29 +197,173 @@ export function healDanglingToolCallFile(filePath, cause = "generic") {
185
197
  catch {
186
198
  return -1;
187
199
  }
200
+ const result = healDanglingToolCallsInText(filePath, raw, cause);
201
+ if (result === 0 && sig)
202
+ rememberHealthyDangling(filePath, sig);
203
+ else
204
+ healthyDanglingCache.delete(filePath);
205
+ return result;
206
+ }
207
+ /** 已判定无悬空调用的文件指纹(filePath -> `${mtimeMs}:${size}`,LRU)。 */
208
+ const healthyDanglingCache = new Map();
209
+ const HEALTHY_DANGLING_CACHE_MAX = 512;
210
+ /** 指纹命中即续期(LRU)。 */
211
+ export function isDanglingHealthyCached(filePath, sig) {
212
+ if (healthyDanglingCache.get(filePath) !== sig)
213
+ return false;
214
+ healthyDanglingCache.delete(filePath);
215
+ healthyDanglingCache.set(filePath, sig);
216
+ return true;
217
+ }
218
+ export function rememberHealthyDangling(filePath, sig) {
219
+ healthyDanglingCache.delete(filePath);
220
+ healthyDanglingCache.set(filePath, sig);
221
+ while (healthyDanglingCache.size > HEALTHY_DANGLING_CACHE_MAX) {
222
+ const oldest = healthyDanglingCache.keys().next();
223
+ if (oldest.done)
224
+ break;
225
+ healthyDanglingCache.delete(oldest.value);
226
+ }
227
+ }
228
+ export function forgetHealthyDangling(filePath) {
229
+ healthyDanglingCache.delete(filePath);
230
+ }
231
+ /** 测试用:清空健康指纹缓存。 */
232
+ export function resetHealthyDanglingCacheForTest() {
233
+ healthyDanglingCache.clear();
234
+ }
235
+ /** 长行只取开头的这段做头字段提取(type/id/parentId 在 SDK 落盘格式里总是最前面几个键)。 */
236
+ const HEADER_SCAN_CHARS = 260;
237
+ /** 不超过此长度的行直接完整解析(成本可忽略)。 */
238
+ const FULL_PARSE_MAX_LINE = 512;
239
+ function parseLineFully(line) {
240
+ try {
241
+ const parsed = JSON.parse(line);
242
+ return typeof parsed === "object" && parsed !== null ? parsed : null;
243
+ }
244
+ catch {
245
+ return null;
246
+ }
247
+ }
248
+ /**
249
+ * 取一行的 id / parentId。长行(数十 KB~数 MB 的工具输出、图片)只扫开头一小段:
250
+ * 要求 id 与 parentId 都出现在第一个嵌套 `{` 之前,确保匹配的是顶层键;否则回退完整解析。
251
+ * 返回 null = 该行不是合法 JSON 对象(脏行,SDK 加载时同样跳过)。
252
+ */
253
+ function lineHeader(line) {
254
+ if (line.length > FULL_PARSE_MAX_LINE) {
255
+ const head = line.slice(0, HEADER_SCAN_CHARS);
256
+ const brace = head.indexOf("{", 1);
257
+ const topLevel = brace === -1 ? head : head.slice(0, brace);
258
+ if (topLevel.startsWith("{")) {
259
+ const idMatch = /"id"\s*:\s*"([^"\\]+)"/.exec(topLevel);
260
+ const parentStr = /"parentId"\s*:\s*"([^"\\]*)"/.exec(topLevel);
261
+ const parentNull = !parentStr && /"parentId"\s*:\s*null/.test(topLevel);
262
+ if (idMatch && (parentStr || parentNull)) {
263
+ return { id: idMatch[1], parentId: parentStr ? parentStr[1] : null, entry: null };
264
+ }
265
+ }
266
+ }
267
+ const entry = parseLineFully(line);
268
+ if (!entry)
269
+ return null;
270
+ return {
271
+ id: typeof entry.id === "string" ? entry.id : null,
272
+ parentId: typeof entry.parentId === "string" ? entry.parentId : null,
273
+ entry,
274
+ };
275
+ }
276
+ /**
277
+ * 在转录文本上检测并落盘修复当前分支尾部的悬空 toolCall(语义同原全量版本)。
278
+ *
279
+ * 按需解析:先只取每行的 id/parentId(长行只扫行首),再沿 parentId 从尾部回溯,
280
+ * 只完整解析回溯经过的行与尾部 assistant 之后的行。健康长转录(最常见:尾部是
281
+ * 没有工具调用的 assistant 或 user)因此只需完整解析末尾几行,而不是逐行 JSON.parse
282
+ * 整个文件。
283
+ *
284
+ * 与全量版本等价性:某个 toolCallId 悬空 ⇔ 存在一次出现之后没有对应结果。尾部
285
+ * assistant 之前的同名调用若缺后继结果,尾部那次必然也缺,所以只看尾部 assistant
286
+ * 及其之后的行即可得到相同集合。
287
+ *
288
+ * 返回追加条数(0 = 健康;-1 = 写入失败)。
289
+ */
290
+ export function healDanglingToolCallsInText(filePath, raw, cause = "generic") {
188
291
  const lines = raw.split("\n");
189
- const entries = [];
190
- let lastId = null;
191
- for (const line of lines) {
292
+ const headers = new Array(lines.length).fill(null);
293
+ const byId = new Map();
294
+ for (let i = 0; i < lines.length; i++) {
295
+ const line = lines[i];
192
296
  if (!line.trim())
193
297
  continue;
194
- try {
195
- const parsed = JSON.parse(line);
196
- entries.push(parsed);
197
- if (typeof parsed === "object" && parsed !== null && typeof parsed.id === "string") {
198
- lastId = parsed.id;
199
- }
298
+ const h = lineHeader(line);
299
+ headers[i] = h;
300
+ // 同名 id:后出现者覆盖(与全量版本 Map.set 语义一致)
301
+ if (h?.id)
302
+ byId.set(h.id, i);
303
+ }
304
+ const fullEntry = (i) => {
305
+ const h = headers[i];
306
+ if (!h)
307
+ return null;
308
+ if (!h.entry)
309
+ h.entry = parseLineFully(lines[i]);
310
+ return h.entry;
311
+ };
312
+ // lastId = 文件里最后一条「能解析且带字符串 id」的条目。头字段提取不验证整行 JSON,
313
+ // 崩溃残留的半截尾行可能被误认,所以这里从尾部往前逐行完整解析确认。
314
+ let lastId = null;
315
+ for (let i = lines.length - 1; i >= 0; i--) {
316
+ if (!headers[i])
317
+ continue;
318
+ const e = fullEntry(i);
319
+ if (!e) {
320
+ headers[i] = null;
321
+ continue;
200
322
  }
201
- catch {
202
- // 脏行:SDK 加载时同样跳过,这里忽略。
323
+ if (typeof e.id === "string") {
324
+ lastId = e.id;
325
+ break;
203
326
  }
204
327
  }
205
- if (entries.length === 0 || !lastId)
328
+ if (!lastId)
206
329
  return 0;
207
- const tailIds = tailAssistantToolCallIds(entries, lastId);
208
- if (tailIds.size === 0)
330
+ // 沿当前分支回溯,定位尾部生效 assistant(规则同 tailAssistantToolCallIds)。
331
+ let tailIndex = -1;
332
+ let tailIds = new Set();
333
+ const seen = new Set();
334
+ let cursor = lastId;
335
+ while (cursor && !seen.has(cursor)) {
336
+ seen.add(cursor);
337
+ const idx = byId.get(cursor);
338
+ if (idx === undefined)
339
+ break;
340
+ const entry = fullEntry(idx);
341
+ if (!entry)
342
+ break;
343
+ const msg = typeof entry.message === "object" && entry.message !== null ? entry.message : null;
344
+ if (msg && "role" in msg) {
345
+ const m = msg;
346
+ if (m.role === "user")
347
+ break;
348
+ if (m.role === "assistant") {
349
+ if (m.stopReason !== "error" && m.stopReason !== "aborted") {
350
+ tailIds = new Set(toolCallsOfMessage(m).map((c) => c.toolCallId));
351
+ tailIndex = idx;
352
+ }
353
+ break;
354
+ }
355
+ }
356
+ cursor = typeof entry.parentId === "string" ? entry.parentId : null;
357
+ }
358
+ if (tailIds.size === 0 || tailIndex < 0)
209
359
  return 0;
210
- const dangling = findDanglingToolCalls(entries).filter((d) => tailIds.has(d.toolCallId));
360
+ const after = [];
361
+ for (let i = tailIndex; i < lines.length; i++) {
362
+ const e = fullEntry(i);
363
+ if (e)
364
+ after.push(e);
365
+ }
366
+ const dangling = findDanglingToolCalls(after).filter((d) => tailIds.has(d.toolCallId));
211
367
  if (dangling.length === 0)
212
368
  return 0;
213
369
  try {