pi-web-ui 0.103.3 → 0.104.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 (38) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/server/agent-formatters.js +9 -1
  3. package/dist/server/agent-service-daemon.js +4 -3
  4. package/dist/server/agent-service.js +586 -44
  5. package/dist/server/compaction-markers.js +111 -3
  6. package/dist/server/delegate-mode.js +2 -0
  7. package/dist/server/dispatch-domain-handlers.js +25 -0
  8. package/dist/server/dsh/dsh-agent-service.js +265 -11
  9. package/dist/server/goal-review-gate.js +2 -0
  10. package/dist/server/index.js +1 -0
  11. package/dist/server/market-service.js +36 -9
  12. package/dist/server/mcp-agent-tool.js +164 -0
  13. package/dist/server/mcp-manager.js +182 -0
  14. package/dist/server/plan-mode.js +3 -0
  15. package/dist/server/plugin-api-catalog.js +24 -0
  16. package/dist/server/plugins.js +113 -0
  17. package/dist/server/preset-share.js +52 -1
  18. package/dist/server/remote-ssh-service.js +90 -25
  19. package/dist/server/sandbox-service.js +705 -0
  20. package/dist/server/sandbox-tool.js +365 -0
  21. package/dist/server/session-parser.js +48 -21
  22. package/dist/server/terminals.js +210 -10
  23. package/dist/server/tool-manager.js +24 -0
  24. package/dist/server/webui-context.js +6 -0
  25. package/dist/server/workspace-snapshot.js +51 -13
  26. package/package.json +1 -1
  27. package/plugin-sdk/index.d.ts +39 -0
  28. package/plugin-sdk/index.mjs +14 -0
  29. package/plugins/catalog.json +101 -2
  30. package/themes/zhujian-dark.css +711 -0
  31. package/themes/zhujian.css +760 -0
  32. package/web/dist/assets/{TerminalPanel-CAqMqC49.js → TerminalPanel-28naZdcs.js} +1 -1
  33. package/web/dist/assets/index-DbGGBf5I.js +680 -0
  34. package/web/dist/assets/index-RqIdFOsh.css +1 -0
  35. package/web/dist/index.html +2 -2
  36. package/web/dist/sw.js +1 -1
  37. package/web/dist/assets/index-CYQdZEbx.css +0 -1
  38. package/web/dist/assets/index-Dt7CQ_Z6.js +0 -680
@@ -17,7 +17,7 @@ import { chmodSync, existsSync, readdirSync, realpathSync, statSync } from "node
17
17
  import { mkdir, readFile, writeFile } from "node:fs/promises";
18
18
  import { createRequire } from "node:module";
19
19
  import { homedir } from "node:os";
20
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
20
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
21
21
  // MUST run before node-pty is required: rewrites the installed node-pty copies
22
22
  // so their worker/agent handlers tolerate Node `--watch`'s IPC traffic (see the
23
23
  // module itself for details).
@@ -27,7 +27,7 @@ import { defineTool } from "@earendil-works/pi-coding-agent";
27
27
  import { Type } from "typebox";
28
28
  import { BASH_DESCRIPTION, BASH_PARAMETERS, BASH_PROMPT_GUIDELINES, BASH_PROMPT_SNIPPET } from "./tool-prompts.js";
29
29
  import { pick } from "./i18n.js";
30
- import { getGlobalRemoteSshService, isRemoteWorkspaceUri, resolveWorkspaceSessionDir } from "./remote-ssh-service.js";
30
+ import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveWorkspaceSessionDir, } from "./remote-ssh-service.js";
31
31
  /** Location of the command list for a project: <workspaceRoot>/.pi/commands.json */
32
32
  export function commandsFilePath(workspaceRoot) {
33
33
  if (isRemoteWorkspaceUri(workspaceRoot)) {
@@ -215,6 +215,9 @@ export function buildTerminalBashLine(command, tailFile, nonce = newSentinelNonc
215
215
  * - 尾随续行符 `\`:下一行被并入本命令,哨兵行成为命令的一部分。
216
216
  * - 未闭合引号:哨兵行被吞进字符串字面量,永远不会作为代码执行。
217
217
  * - 未闭合的 `{}` / `()` 组:shell 停在 PS2 续行,哨兵永远不会执行(#573)。
218
+ * - 未闭合的 heredoc(`<<`,非 `<<<`):哨兵行被当成 heredoc 正文吞掉,shell
219
+ * 停在 PS2 等 EOF——不仅本条零执行,持久 shell 的后续命令也会连环被吞。
220
+ * - 未闭合的 if/for/while/until/case 块:同样停在 PS2 等续行。
218
221
  * - 多行命令:经 `$'...'` 转义单行化后引号/换行全部字面化,总是安全 → null。
219
222
  *
220
223
  * 扫描按 POSIX 引号语义跟踪 `'`/`"`/`` ` `` 三种引号与转义;`$'...'`(ANSI-C
@@ -228,8 +231,49 @@ export function sentinelUnsafeReason(command) {
228
231
  // 当前单引号是否 $' 开头(ANSI-C 引号,内含转义语义)
229
232
  let ansiC = false;
230
233
  let escaped = false;
231
- // `{` / `(` 未闭合深度:残句(如 `{ a; b | tail -3`)注入后 shell 停在 PS2、哨兵永不执行(#573)
234
+ // `{` 未闭合深度:残句(如 `{ a; b | tail -3`)注入后 shell 停在 PS2、哨兵永不执行(#573)
232
235
  let depth = 0;
236
+ // `(` 栈:区分普通组与算术上下文(`(())`)——算术里的 `<<` 是左移不是 heredoc
237
+ const parenStack = [];
238
+ // 关键字块计数(命令位置的 if / for|while|until|select / case)
239
+ let ifDepth = 0;
240
+ let loopDepth = 0;
241
+ let caseDepth = 0;
242
+ let heredoc = false;
243
+ // [[ ]] 内是测试表达式,单词不是命令
244
+ let inDoubleBracket = false;
245
+ // 当前累积的词;wordCmdPos 记录该词是否处于命令位置
246
+ // (行首/`;|&(`/`{`/`}`/then|else|do 之后)——`echo if` 的 `if` 是参数不是关键字
247
+ let word = "";
248
+ let wordCmdPos = false;
249
+ let cmdPos = true;
250
+ const flushWord = () => {
251
+ if (!word)
252
+ return;
253
+ if (word === "[[")
254
+ inDoubleBracket = true;
255
+ else if (word === "]]")
256
+ inDoubleBracket = false;
257
+ else if (!inDoubleBracket && parenStack[parenStack.length - 1] !== "arith") {
258
+ if (wordCmdPos) {
259
+ if (word === "if")
260
+ ifDepth++;
261
+ else if (word === "fi")
262
+ ifDepth = Math.max(0, ifDepth - 1);
263
+ else if (word === "for" || word === "while" || word === "until" || word === "select")
264
+ loopDepth++;
265
+ else if (word === "done")
266
+ loopDepth = Math.max(0, loopDepth - 1);
267
+ else if (word === "case")
268
+ caseDepth++;
269
+ else if (word === "esac")
270
+ caseDepth = Math.max(0, caseDepth - 1);
271
+ else if (word === "then" || word === "else" || word === "elif" || word === "do")
272
+ cmdPos = true;
273
+ }
274
+ }
275
+ word = "";
276
+ };
233
277
  for (let i = 0; i < trimmed.length; i++) {
234
278
  const ch = trimmed[i];
235
279
  if (quote) {
@@ -257,23 +301,106 @@ export function sentinelUnsafeReason(command) {
257
301
  escaped = true;
258
302
  continue;
259
303
  }
304
+ if (/[A-Za-z0-9_#]/.test(ch)) {
305
+ if (!word) {
306
+ wordCmdPos = cmdPos;
307
+ cmdPos = false;
308
+ }
309
+ word += ch;
310
+ continue;
311
+ }
260
312
  if (ch === "'" || ch === '"' || ch === "`") {
313
+ flushWord();
261
314
  quote = ch;
262
315
  ansiC = ch === "'" && i > 0 && trimmed[i - 1] === "$";
263
316
  continue;
264
317
  }
265
- if (ch === "(" || ch === "{")
318
+ if (ch === "<" && trimmed[i + 1] === "<") {
319
+ flushWord();
320
+ cmdPos = false;
321
+ if (trimmed[i + 2] === "<") {
322
+ i += 2; // `<<<` here-string:不等待后续行,安全
323
+ }
324
+ else if (parenStack[parenStack.length - 1] !== "arith" && !inDoubleBracket) {
325
+ heredoc = true;
326
+ break; // 哨兵行必然被当 heredoc 正文吞掉
327
+ }
328
+ else {
329
+ i += 1; // 算术左移 / [[ 内:非 heredoc
330
+ }
331
+ continue;
332
+ }
333
+ if (ch === "(") {
334
+ flushWord();
335
+ cmdPos = true;
336
+ if (trimmed[i + 1] === "(") {
337
+ parenStack.push("arith");
338
+ i += 1;
339
+ }
340
+ else {
341
+ parenStack.push("group");
342
+ }
343
+ continue;
344
+ }
345
+ if (ch === ")") {
346
+ flushWord();
347
+ const top = parenStack[parenStack.length - 1];
348
+ if (top === "arith" && trimmed[i + 1] === ")") {
349
+ parenStack.pop();
350
+ i += 1;
351
+ }
352
+ else if (top === "group") {
353
+ parenStack.pop();
354
+ }
355
+ // 栈空/不匹配的 `)`(case 模式 `a)`、算术残留)保持忽略
356
+ cmdPos = true;
357
+ continue;
358
+ }
359
+ if (ch === "[" && trimmed[i + 1] === "[") {
360
+ flushWord();
361
+ inDoubleBracket = true;
362
+ i += 1;
363
+ continue;
364
+ }
365
+ if (ch === "]" && trimmed[i + 1] === "]" && inDoubleBracket) {
366
+ flushWord();
367
+ inDoubleBracket = false;
368
+ i += 1;
369
+ continue;
370
+ }
371
+ if (ch === "{") {
372
+ flushWord();
266
373
  depth++;
267
- else if ((ch === ")" || ch === "}") && depth > 0)
268
- depth--;
269
- }
374
+ cmdPos = true;
375
+ continue;
376
+ }
377
+ if (ch === "}") {
378
+ flushWord();
379
+ depth = Math.max(0, depth - 1);
380
+ cmdPos = true;
381
+ continue;
382
+ }
383
+ // 其余字符(空白/`;|&`/`$`/`!` 等)结束当前词
384
+ flushWord();
385
+ if (ch === ";" || ch === "|" || ch === "&" || ch === "!")
386
+ cmdPos = true;
387
+ else if (ch !== "$" && !/\s/.test(ch))
388
+ cmdPos = false;
389
+ }
390
+ flushWord();
270
391
  if (quote !== null)
271
392
  return "unclosed_quote";
272
393
  // 扫描结束仍在转义态 = 最后一个字符是引号外的 `\`(尾随续行符)
273
394
  if (escaped)
274
395
  return "trailing_backslash";
396
+ if (heredoc)
397
+ return "unclosed_heredoc";
398
+ if (ifDepth > 0 || loopDepth > 0 || caseDepth > 0)
399
+ return "unclosed_block";
275
400
  if (depth > 0)
276
401
  return "unclosed_group";
402
+ if (parenStack.length > 0)
403
+ return "unclosed_group";
277
404
  return null;
278
405
  }
279
406
  /** 顶层(引号/反引号/转义外、且不在 `()` / `{}` 组内)按 `|` 拆分的管道元素。
@@ -1194,6 +1321,30 @@ export class TerminalManager {
1194
1321
  return true;
1195
1322
  }
1196
1323
  safeCwd(raw) {
1324
+ // 远程工作区的根是 ssh:// URI:下面的本地文件系统边界(realpath/relative)
1325
+ // 无法解析它,会让远程终端的每次创建/接管命令都被「必须位于工作区内」拒掉,
1326
+ // spawnShell 的远程分支成为死代码。远程侧的目录边界由 SSH 服务在远端校验,
1327
+ // 这里只做同主机校验与 URI 规范化(spawnShell 的 URI 正则要求带端口)。
1328
+ if (isRemoteWorkspaceUri(this.workspaceRoot)) {
1329
+ const root = parseRemoteWorkspaceUri(this.workspaceRoot);
1330
+ if (!root)
1331
+ return null;
1332
+ if (isRemoteWorkspaceUri(raw)) {
1333
+ const cand = parseRemoteWorkspaceUri(raw);
1334
+ if (!cand)
1335
+ return null;
1336
+ if (cand.username !== root.username || cand.host !== root.host || cand.port !== root.port)
1337
+ return null;
1338
+ return `ssh://${cand.username}@${cand.host}:${cand.port}${cand.remotePath}`;
1339
+ }
1340
+ // 相对/本地写法一律挂到远程根下解析(与本地分支 resolve(root, raw) 同语义)
1341
+ const rel = String(raw).replace(/\\/g, "/").replace(/^\/+/, "");
1342
+ const joined = posix.normalize(`${root.remotePath}/${rel}`).replace(/\/+$/, "") || "/";
1343
+ const prefix = root.remotePath === "/" ? "/" : `${root.remotePath}/`;
1344
+ if (joined !== root.remotePath && !joined.startsWith(prefix))
1345
+ return null;
1346
+ return `ssh://${root.username}@${root.host}:${root.port}${joined}`;
1347
+ }
1197
1348
  try {
1198
1349
  const root = realpathSync(resolve(this.workspaceRoot));
1199
1350
  const candidate = realpathSync(isAbsolute(raw) ? resolve(raw) : resolve(root, raw));
@@ -1653,6 +1804,27 @@ export function cleanBashOutput(raw, nonce, command = "") {
1653
1804
  const anchor = (command.split("\n")[0] ?? "").trim().slice(0, 80);
1654
1805
  // 命令回显前那一行提示符(如 `user@host MINGW64 /cwd`):收尾时用它识别「哨兵前残留的新提示符」。
1655
1806
  let promptLine = "";
1807
+ // 锚点找不到(横向滚动只回显尾部 / 回显缺失)时的回落:首个非空行若呈
1808
+ // 提示符形状(`user@host … $ ` / `[user@host dir]$ `),按提示符+回显行剥掉,
1809
+ // 否则命令回显与提示符会整行留在返回给模型的输出里。
1810
+ const fallbackPromptDetect = () => {
1811
+ const idx = lines.findIndex((line) => line.trim() !== "");
1812
+ if (idx < 0)
1813
+ return;
1814
+ const first = lines[idx].trim();
1815
+ // 单行提示符:`user@host MINGW64 /tmp$ cmd`(MINGW)或 `user@host:~/p$ cmd`(Linux)
1816
+ if (/^[A-Za-z0-9._-]+@[A-Za-z0-9._-]+[^\n]*[$#] /.test(first) ||
1817
+ /^\[[A-Za-z0-9._-]+@[A-Za-z0-9._-]+[^\]]*\][$#] /.test(first)) {
1818
+ promptLine = first;
1819
+ lines = lines.slice(idx + 1);
1820
+ return;
1821
+ }
1822
+ // MINGW 双行提示符:`user@host MINGW64 /path` 换行后 `$ cmd`
1823
+ if (/^[A-Za-z0-9._-]+@[A-Za-z0-9._-]+ /.test(first) && /^[$#] /.test(lines[idx + 1]?.trim() ?? "")) {
1824
+ promptLine = first;
1825
+ lines = lines.slice(idx + 2);
1826
+ }
1827
+ };
1656
1828
  if (anchor) {
1657
1829
  const echoIdx = lines.findIndex((line) => line.includes(anchor));
1658
1830
  if (echoIdx >= 0) {
@@ -1661,9 +1833,29 @@ export function cleanBashOutput(raw, nonce, command = "") {
1661
1833
  if (t && t !== "$")
1662
1834
  promptLine = t;
1663
1835
  }
1664
- lines = lines.slice(echoIdx + 1);
1836
+ // 回显折行:锚点行只含命令的前一段,后续折行若恰好逐行拼接出命令的
1837
+ // 剩余文本,也一并剥掉(精确匹配,匹配不上即停,保守不误删输出)。
1838
+ const firstLine = (command.split("\n")[0] ?? "").trim();
1839
+ const echoLine = lines[echoIdx].trimEnd();
1840
+ const anchorAt = echoLine.indexOf(anchor);
1841
+ let pos = anchorAt >= 0 ? Math.min(echoLine.length - anchorAt, firstLine.length) : anchor.length;
1842
+ let idx = echoIdx + 1;
1843
+ while (pos < firstLine.length && idx < lines.length) {
1844
+ const chunk = lines[idx].trim();
1845
+ if (!chunk || firstLine.slice(pos, pos + chunk.length) !== chunk)
1846
+ break;
1847
+ pos += chunk.length;
1848
+ idx++;
1849
+ }
1850
+ lines = lines.slice(idx);
1851
+ }
1852
+ else {
1853
+ fallbackPromptDetect();
1665
1854
  }
1666
1855
  }
1856
+ else {
1857
+ fallbackPromptDetect();
1858
+ }
1667
1859
  // 最后一个本次哨兵之后的内容全是 shell 新提示符——整段截掉。
1668
1860
  const text = lines.join("\n");
1669
1861
  const re = sentinelReFor(nonce);
@@ -1770,12 +1962,20 @@ export function makeTerminalBashTool(terminals, opts) {
1770
1962
  ? "以续行符 \\ 结尾"
1771
1963
  : incomplete === "unclosed_quote"
1772
1964
  ? "存在未闭合引号"
1773
- : "存在未闭合的 { } / ( ) 组";
1965
+ : incomplete === "unclosed_heredoc"
1966
+ ? "存在未闭合的 heredoc(<<)"
1967
+ : incomplete === "unclosed_block"
1968
+ ? "存在未闭合的 if/for/case 块"
1969
+ : "存在未闭合的 { } / ( ) 组";
1774
1970
  const reasonEn = incomplete === "trailing_backslash"
1775
1971
  ? "ends with a line-continuation backslash"
1776
1972
  : incomplete === "unclosed_quote"
1777
1973
  ? "has an unclosed quote"
1778
- : "has an unclosed { } / ( ) group";
1974
+ : incomplete === "unclosed_heredoc"
1975
+ ? "has an unclosed heredoc (<<)"
1976
+ : incomplete === "unclosed_block"
1977
+ ? "has an unclosed if/for/case block"
1978
+ : "has an unclosed { } / ( ) group";
1779
1979
  throw new Error(pick(lang, `命令语法不完整(${reasonZh}),未执行。终端接管 bash 无法为它注入退出码哨兵,残句还会让 shell 停在续行提示符、零执行。请补全引号 / 续行符 / 括号后重试。`, `Command is syntactically incomplete (${reasonEn}); nothing was executed. The terminal bash path cannot inject an exit-code sentinel here, and the leftover fragment would leave the shell waiting at a continuation prompt. Complete the quote / continuation / bracket and retry.`, "terminals.bash.incomplete"));
1780
1980
  }
1781
1981
  const persist = p.persist ?? opts.defaultPersist();
@@ -79,6 +79,10 @@ export const COMPACT_CONTEXT_TOOL_NAME = "compact_context";
79
79
  export const PATCH_TOOL_NAME = "patch";
80
80
  /** 原生语言服务器工具(定义见 lsp-tool.ts):代码定义跳转、引用查询、类型悬停与诊断。 */
81
81
  export const LSP_TOOL_NAME = "lsp";
82
+ /** MCP 服务器检测与安装管理工具(定义见 mcp-agent-tool.ts):检查/安装/移除/重载 MCP 服务器。 */
83
+ export const MCP_MANAGE_TOOL_NAME = "mcp_manage";
84
+ /** 隔离沙盒项目管理工具(定义见 sandbox-tool.ts):创建空白/导入型隔离沙盒、查看 diff、重置或销毁。 */
85
+ export const SANDBOX_TOOL_NAME = "sandbox";
82
86
  /** QuickJS WASM 沙箱代码执行与批量调用工具(SDK 内置 codemode 扩展)。 */
83
87
  export const CODEMODE_TOOL_NAME = "codemode";
84
88
  /** 基于 BM25 算法的延迟工具检索与激活工具(SDK 内置 tool-search 扩展)。 */
@@ -256,6 +260,26 @@ export const AGENT_TOOL_CATALOG = [
256
260
  descKey: "compactContextEnabledDesc",
257
261
  offHintKey: "compactContextOffHint",
258
262
  },
263
+ // MCP 服务器检测与安装管理(单 action:list/check/install/remove/reload):默认关(opt-in),
264
+ // 开启后 AI 可检查某个 MCP 是否已安装并一键写入 mcp.json 热加载挂载。
265
+ {
266
+ name: MCP_MANAGE_TOOL_NAME,
267
+ group: "other",
268
+ defaultOn: false,
269
+ dshVisible: false,
270
+ descKey: "mcpManageEnabledDesc",
271
+ offHintKey: "mcpManageOffHint",
272
+ },
273
+ // 隔离沙盒项目管理(单 action:list/create/diff/reset/persist/promote/apply_to_source/destroy):默认开,
274
+ // 支持 AI 自主创建空白或导入型隔离副本实验,写回源项目强制经过用户审批。
275
+ {
276
+ name: SANDBOX_TOOL_NAME,
277
+ group: "other",
278
+ defaultOn: true,
279
+ dshVisible: false,
280
+ descKey: "sandboxEnabledDesc",
281
+ offHintKey: "sandboxOffHint",
282
+ },
259
283
  // todo_list 唯一例外:行不在「其他」组,固定在上面的 markers 分区(设置页循环
260
284
  // 跳过它,见 OTHER_AGENT_TOOLS;文案 key 照给,万一哪天搬家不用补)。
261
285
  {
@@ -34,6 +34,12 @@ export const mockThemeProxy = new Proxy({
34
34
  inverse: (text) => text,
35
35
  strikethrough: (text) => text,
36
36
  dim: (text) => text,
37
+ // 真实 SDK 的 Theme 里这两个返回**装饰函数**而非字符串——扩展 widget 会写
38
+ // `theme.getThinkingBorderColor(level)(text)`。兜底「取最后一个 string 参数」
39
+ // 会把 level 字符串(或空串)当装饰器返回,一调用即 TypeError,render 的
40
+ // try/catch 吞掉后 widget 内容静默消失(#592 的同类遗漏)。
41
+ getThinkingBorderColor: (_level) => (text) => text,
42
+ getBashModeBorderColor: () => (text) => text,
37
43
  }, {
38
44
  get(target, prop) {
39
45
  if (prop in target)
@@ -13,8 +13,8 @@
13
13
  */
14
14
  import { execFile } from "node:child_process";
15
15
  import { randomUUID } from "node:crypto";
16
- import { rm } from "node:fs/promises";
17
- import { join } from "node:path";
16
+ import { copyFile, rm } from "node:fs/promises";
17
+ import { join, resolve } from "node:path";
18
18
  import { promisify } from "node:util";
19
19
  import { gitDirOf } from "./scm.js";
20
20
  const exec = promisify(execFile);
@@ -104,6 +104,11 @@ export async function restoreWorkspaceSnapshot(cwd, snapshotRef) {
104
104
  if (!gitDir) {
105
105
  return { success: false, error: "Workspace is not a Git repository" };
106
106
  }
107
+ // index 备份:子目录回滚的第 1 步 rm --cached 直接改真实 index,后续 checkout/clean
108
+ // 中途失败时原子还原,暂存区不再留在损坏状态(见 catch 中的还原注释)
109
+ let indexRealPath = "";
110
+ let indexBackup = "";
111
+ let indexBackedUp = false;
107
112
  try {
108
113
  // 验证 snapshotRef 合法性
109
114
  await runGit(cwd, ["rev-parse", "--verify", snapshotRef]);
@@ -117,30 +122,63 @@ export async function restoreWorkspaceSnapshot(cwd, snapshotRef) {
117
122
  }
118
123
  // 子目录 cwd:作用域收敛到该子树,不误伤同仓兄弟目录与仓库根
119
124
  const pathspec = `:(top)${prefix}`;
125
+ indexRealPath = resolve(cwd, (await runGit(cwd, ["rev-parse", "--git-path", "index"])).trim());
126
+ indexBackup = join(gitDir, `temp-index-backup-${randomUUID()}`);
127
+ try {
128
+ await copyFile(indexRealPath, indexBackup);
129
+ indexBackedUp = true;
130
+ }
131
+ catch {
132
+ // 空仓库可能还没有 index 文件:rm --cached 无从破坏,无需备份
133
+ }
120
134
  // 1. 把 cwd 子树移出 index(不删除工作区文件),快照里不存在的文件由此退回未跟踪状态
121
135
  await runGit(cwd, ["rm", "-r", "--cached", "--quiet", "--ignore-unmatch", "--", pathspec]);
122
- // 2. 从快照树把 cwd 子树写回 index 与工作区(恢复被修改与被删除的跟踪文件)
123
- // 注:若快照时刻该子树为空(快照树内无匹配文件),checkout 会报
124
- // "did not match any file(s) known to git";此时快照树内本无文件,捕获忽略即可,
125
- // 第 3 步 clean 会清理掉新增文件完成空状态还原。
126
- try {
136
+ // 2. 快照树内确有该子树文件时才 checkout(恢复被修改与被删除的跟踪文件)。
137
+ // 先 ls-tree 判存在,替代老实现「捕获 checkout 的英文报错文案」的判空——
138
+ // 本地化 git(zh_CN 等)下文案不匹配会把「快照为空」误当真失败抛出。
139
+ // ls-tree 的 path 按 git 进程 cwd(= 本子目录)相对解析:用 :(top) 锚定
140
+ // 到仓库根的子树前缀,与第 1/3 步的 pathspec 同口径。
141
+ const listed = await runGit(cwd, [
142
+ "ls-tree",
143
+ "-r",
144
+ "--name-only",
145
+ snapshotRef,
146
+ "--",
147
+ `:(top)${prefix.replace(/\/+$/, "")}`,
148
+ ]);
149
+ if (listed.trim()) {
127
150
  await runGit(cwd, ["checkout", snapshotRef, "--", pathspec]);
128
151
  }
129
- catch (checkoutErr) {
130
- const errMsg = String(checkoutErr);
131
- if (!errMsg.includes("did not match any file(s) known to git")) {
132
- throw checkoutErr;
133
- }
134
- }
135
152
  // 3. 清理快照之后新增的未跟踪文件与空目录(含第 1 步退回未跟踪的那些)
136
153
  await runGit(cwd, ["clean", "-fd", "--", pathspec]);
137
154
  return { success: true };
138
155
  }
139
156
  catch (err) {
157
+ if (indexBackedUp) {
158
+ // 原子还原 index:第 1 步 rm --cached 已改真实 index,checkout 中途失败
159
+ //(文件被占用 EBUSY、磁盘满…)不能把暂存区留在「整棵子树 staged-deleted」
160
+ // 的损坏状态——回滚本身不能再制造新破坏。
161
+ //(还原窗口内的并发 git 写操作会被覆盖:窗口毫秒级,且损坏的暂存区
162
+ // 比丢一瞬间的暂存操作严重得多。)
163
+ try {
164
+ await copyFile(indexBackup, indexRealPath);
165
+ }
166
+ catch {
167
+ // 还原失败:错误照常上报
168
+ }
169
+ }
140
170
  const msg = err.message;
141
171
  console.error(`[workspace-snapshot] 还原快照失败 (${cwd}, ${snapshotRef}):`, msg);
142
172
  return { success: false, error: msg };
143
173
  }
174
+ finally {
175
+ try {
176
+ await rm(indexBackup, { force: true });
177
+ }
178
+ catch {
179
+ // ignore cleanup error
180
+ }
181
+ }
144
182
  }
145
183
  /**
146
184
  * 查找与指定消息 entryId/时间戳最匹配的工作区物理快照:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-ui",
3
- "version": "0.103.3",
3
+ "version": "0.104.0",
4
4
  "description": "Just open your browser to get all your work done — browser cockpit for AI coding agents (chat, code, files, terminal, Git in one tab)",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -286,6 +286,45 @@ export interface PluginHost {
286
286
  models: {
287
287
  list(): Array<{ id: string; [key: string]: unknown }> | Promise<Array<{ id: string; [key: string]: unknown }>>;
288
288
  };
289
+ /** MCP 服务器检测与便捷安装接口(list/check 只读免权限;install 要 "tools";promptInstall 要 "chat" 或 "tools")。 */
290
+ mcp: {
291
+ list(): Promise<Array<{ name: string; scope: "global" | "project"; status: string; [key: string]: unknown }>>;
292
+ check(query: string): Promise<{
293
+ installed: boolean;
294
+ running: boolean;
295
+ enabled: boolean;
296
+ server: Record<string, unknown> | null;
297
+ matches: Array<Record<string, unknown>>;
298
+ tools: Array<{ name: string; description?: string }>;
299
+ }>;
300
+ install(spec: {
301
+ name?: string;
302
+ package?: string;
303
+ command?: string;
304
+ args?: string[];
305
+ cwd?: string;
306
+ env?: Record<string, string>;
307
+ url?: string;
308
+ headers?: Record<string, string>;
309
+ type?: "stdio" | "http" | "streamable-http";
310
+ timeout?: number;
311
+ description?: string;
312
+ scope?: "global" | "project";
313
+ enabled?: boolean;
314
+ }): Promise<{
315
+ ok: boolean;
316
+ name?: string;
317
+ scope?: "global" | "project";
318
+ status?: string;
319
+ tools?: Array<{ name: string; description?: string }>;
320
+ server?: Record<string, unknown>;
321
+ error?: string;
322
+ }>;
323
+ promptInstall(
324
+ target: string | Record<string, unknown>,
325
+ opts?: { conversationId?: string; scope?: "global" | "project" },
326
+ ): Promise<{ ok: boolean; conversationId?: string; error?: string }>;
327
+ };
289
328
  /** 会话统计 / 流式增量订阅(返回注销函数)。 */
290
329
  onStats(handler: (s: unknown) => void): () => void;
291
330
  onStreaming(handler: (ev: { conversationId?: string; delta: string }) => void): () => void;
@@ -424,6 +424,19 @@ export function createMockHost(overrides) {
424
424
  models: {
425
425
  list: () => [],
426
426
  },
427
+ mcp: {
428
+ list: async () => [],
429
+ check: async () => ({
430
+ installed: false,
431
+ running: false,
432
+ enabled: false,
433
+ server: null,
434
+ matches: [],
435
+ tools: [],
436
+ }),
437
+ install: async () => okFalse("mcp.install(MCP 安装未接入)"),
438
+ promptInstall: async () => okFalse("mcp.promptInstall(对话通道未接入)"),
439
+ },
427
440
  onStats: sub("onStats"),
428
441
  onStreaming: sub("onStreaming"),
429
442
  net: {
@@ -528,6 +541,7 @@ export function createMockHost(overrides) {
528
541
  "project",
529
542
  "scm",
530
543
  "models",
544
+ "mcp",
531
545
  "net",
532
546
  "events",
533
547
  "dialogs",