pi-web-ui 0.113.0 → 0.114.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 (228) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/README.md +117 -252
  3. package/README.zh-CN.md +145 -223
  4. package/README.zh-TW.md +145 -223
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/pi-device-hub.mjs +9 -0
  7. package/bin/pi-web-ui.mjs +145 -20
  8. package/dist/gh-comment-781.md +5 -0
  9. package/dist/server/agent-service-daemon.js +102 -24
  10. package/dist/server/agent-service.js +2296 -1121
  11. package/dist/server/approval-rules.js +29 -3
  12. package/dist/server/ask-user-question-tool.js +8 -8
  13. package/dist/server/atomic-file.js +35 -14
  14. package/dist/server/attachment-store.js +71 -35
  15. package/dist/server/attachments.js +18 -8
  16. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  17. package/dist/server/canvas/canvas-dispatch.js +61 -20
  18. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  19. package/dist/server/canvas/canvas-scheduler.js +99 -0
  20. package/dist/server/canvas/canvas-store.js +107 -54
  21. package/dist/server/canvas/canvas-validation.js +131 -0
  22. package/dist/server/canvas/canvas-workspace.js +284 -0
  23. package/dist/server/client-id-utils.js +8 -0
  24. package/dist/server/client-state.js +104 -22
  25. package/dist/server/communicate-tool.js +76 -0
  26. package/dist/server/compact-context-tool.js +2 -3
  27. package/dist/server/compaction-instructions.js +75 -0
  28. package/dist/server/compaction-markers.js +7 -2
  29. package/dist/server/compaction-state.js +84 -0
  30. package/dist/server/composer-drafts.js +43 -40
  31. package/dist/server/context-evidence.js +346 -0
  32. package/dist/server/control-socket.js +6 -2
  33. package/dist/server/conversation-communication.js +368 -0
  34. package/dist/server/conversation-read-tool.js +3 -4
  35. package/dist/server/conversation-tool-names.js +14 -0
  36. package/dist/server/conversation-tool.js +57 -0
  37. package/dist/server/delegate-mode.js +17 -4
  38. package/dist/server/device-center/bot-catalog.js +88 -0
  39. package/dist/server/device-center/bot-execution.js +106 -0
  40. package/dist/server/device-center/bots.js +170 -0
  41. package/dist/server/device-center/collab-service.js +153 -0
  42. package/dist/server/device-center/collab-tool.js +184 -0
  43. package/dist/server/device-center/connector.js +332 -0
  44. package/dist/server/device-center/desktop-linux.js +372 -0
  45. package/dist/server/device-center/desktop-native.js +413 -0
  46. package/dist/server/device-center/desktop-page.js +232 -0
  47. package/dist/server/device-center/desktop-setup.js +30 -0
  48. package/dist/server/device-center/desktop.js +387 -0
  49. package/dist/server/device-center/device-portals.js +241 -0
  50. package/dist/server/device-center/execution-failure.js +70 -0
  51. package/dist/server/device-center/executor.js +371 -0
  52. package/dist/server/device-center/file-sync.js +493 -0
  53. package/dist/server/device-center/hub-auth.js +69 -0
  54. package/dist/server/device-center/hub-page.js +68 -0
  55. package/dist/server/device-center/hub-setup.js +214 -0
  56. package/dist/server/device-center/hub.js +829 -0
  57. package/dist/server/device-center/local-page.js +17 -0
  58. package/dist/server/device-center/local.js +476 -0
  59. package/dist/server/device-center/main.js +118 -0
  60. package/dist/server/device-center/native-desktop/macos.js +192 -0
  61. package/dist/server/device-center/native-desktop/windows.js +118 -0
  62. package/dist/server/device-center/path-portal.js +120 -0
  63. package/dist/server/device-center/relay.js +959 -0
  64. package/dist/server/device-center/runtime.js +253 -0
  65. package/dist/server/device-center/smoke-preview.js +3 -0
  66. package/dist/server/device-center/store.js +122 -0
  67. package/dist/server/device-center/task-error.js +14 -0
  68. package/dist/server/device-center/transfers.js +293 -0
  69. package/dist/server/device-center/workspaces.js +45 -0
  70. package/dist/server/dispatch-domain-handlers.js +83 -27
  71. package/dist/server/dsh/dsh-agent-service.js +277 -158
  72. package/dist/server/dsh/dsh-client.js +12 -2
  73. package/dist/server/durable/durable-agent-service.js +1 -1
  74. package/dist/server/evidence-tool-hooks.js +49 -0
  75. package/dist/server/file-save.js +95 -0
  76. package/dist/server/file-transfer-routes.js +97 -47
  77. package/dist/server/files-service.js +110 -34
  78. package/dist/server/goal-review-gate.js +16 -6
  79. package/dist/server/goal-service.js +54 -30
  80. package/dist/server/http-proxy.js +120 -0
  81. package/dist/server/index.js +236 -232
  82. package/dist/server/load-timing.js +31 -0
  83. package/dist/server/mcp-bridge.js +219 -94
  84. package/dist/server/mcp-hot-reload.js +31 -5
  85. package/dist/server/mcp-manager.js +192 -93
  86. package/dist/server/mcp-oauth-login.js +169 -0
  87. package/dist/server/mcp-oauth-ui.js +137 -0
  88. package/dist/server/mcp-oauth.js +395 -0
  89. package/dist/server/mcp-project-runtime.js +207 -0
  90. package/dist/server/message-window.js +74 -21
  91. package/dist/server/net-guard.js +122 -20
  92. package/dist/server/payload-limits.js +17 -0
  93. package/dist/server/pending-question.js +82 -0
  94. package/dist/server/plan-mode.js +338 -137
  95. package/dist/server/plugin-assets.js +8 -4
  96. package/dist/server/plugin-chat-attachments.js +48 -0
  97. package/dist/server/plugin-facilities.js +67 -220
  98. package/dist/server/plugin-installer.js +2 -1
  99. package/dist/server/plugin-removal.js +49 -0
  100. package/dist/server/plugin-secrets.js +179 -0
  101. package/dist/server/plugins.js +262 -92
  102. package/dist/server/preset-fields.js +49 -0
  103. package/dist/server/preset-plugin-dependencies.js +57 -0
  104. package/dist/server/preset-share.js +112 -72
  105. package/dist/server/protocol-version.js +1 -1
  106. package/dist/server/queue-modes.js +10 -0
  107. package/dist/server/remote-ssh-service.js +160 -67
  108. package/dist/server/request-context.js +164 -0
  109. package/dist/server/sandbox-data.js +655 -0
  110. package/dist/server/sandbox-engines.js +7 -0
  111. package/dist/server/sandbox-runtime-gate.js +41 -0
  112. package/dist/server/sandbox-service.js +139 -698
  113. package/dist/server/sandbox-tool.js +21 -4
  114. package/dist/server/scheduler-tasks.js +63 -48
  115. package/dist/server/serialize.js +48 -19
  116. package/dist/server/session-branch.js +25 -3
  117. package/dist/server/session-parser.js +28 -18
  118. package/dist/server/session-scan.js +130 -0
  119. package/dist/server/session-search.js +51 -37
  120. package/dist/server/settings-service.js +267 -111
  121. package/dist/server/setup-config.js +58 -0
  122. package/dist/server/skill-maintenance.js +112 -24
  123. package/dist/server/subagent-helpers.js +4 -1
  124. package/dist/server/subagent-notify.js +4 -1
  125. package/dist/server/subagent-security-gate.js +52 -11
  126. package/dist/server/subagent-task.js +27 -0
  127. package/dist/server/subagents.js +217 -46
  128. package/dist/server/tabs.js +9 -1
  129. package/dist/server/terminals.js +467 -363
  130. package/dist/server/tool-guards.js +42 -6
  131. package/dist/server/tool-manager.js +47 -20
  132. package/dist/server/tool-overrides.js +13 -11
  133. package/dist/server/tool-prompt-overrides.js +32 -2
  134. package/dist/server/tool-prompts.js +1 -1
  135. package/dist/server/turn-timing.js +11 -0
  136. package/dist/server/universal/session-store.js +48 -6
  137. package/dist/server/universal/universal-service.js +1 -1
  138. package/dist/server/universal/universal-session.js +334 -231
  139. package/dist/server/uploads.js +64 -5
  140. package/dist/server/webui-context.js +6 -6
  141. package/dist/server/worktree-service.js +32 -24
  142. package/dist/server/ws-pending-queue.js +73 -27
  143. package/dist/test-artifact.md +9 -0
  144. package/dist/test-preview-modal.md +11 -0
  145. package/dist/test-report.html +20 -0
  146. package/docs/device-center.md +142 -0
  147. package/docs/device-desktop.md +48 -0
  148. package/package.json +4 -1
  149. package/plugin-sdk/index.d.ts +45 -9
  150. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  151. package/plugins/catalog.json +1 -1
  152. package/themes/aetheris.css +1 -107
  153. package/themes/ayu-light.css +5 -29
  154. package/themes/bases/flow-base.css +0 -6
  155. package/themes/bases/statusbar-flat-base.css +112 -0
  156. package/themes/bases/zhujian-base.css +1 -0
  157. package/themes/bases/zhupi-base.css +1 -0
  158. package/themes/catppuccin-latte.css +4 -27
  159. package/themes/catppuccin.css +4 -35
  160. package/themes/claude-code-dark.css +1 -0
  161. package/themes/codex.css +4 -28
  162. package/themes/cyberpunk.css +3 -61
  163. package/themes/dark-teal.css +0 -1
  164. package/themes/dazzle.css +3 -73
  165. package/themes/everforest-light.css +4 -27
  166. package/themes/geist.css +4 -28
  167. package/themes/gruvbox-light.css +4 -27
  168. package/themes/kanagawa-lotus.css +4 -27
  169. package/themes/md-preview.css +3 -213
  170. package/themes/mist.css +4 -24
  171. package/themes/nord.css +4 -35
  172. package/themes/one-dark.css +4 -37
  173. package/themes/paper.css +4 -16
  174. package/themes/rose-pine-dawn.css +4 -28
  175. package/themes/sakura.css +4 -24
  176. package/themes/solarized-light.css +4 -27
  177. package/themes/tokyo-night.css +3 -34
  178. package/themes/white.css +4 -26
  179. package/themes/zhujian-dark.css +1 -0
  180. package/themes/zhupi-dark.css +1 -0
  181. package/web/dist/.build-assets.json +1 -0
  182. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  183. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  184. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  185. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  186. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  187. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  188. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  189. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  190. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  191. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  192. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  193. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  194. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  195. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  196. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  197. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  198. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  199. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  200. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  201. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  202. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  203. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  204. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  205. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  206. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  207. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  208. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  209. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  210. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  211. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  212. package/web/dist/assets/index-Cje8iugL.js +83 -0
  213. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  214. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  215. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  216. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  217. package/web/dist/assets/math-BorAY7qD.css +1 -0
  218. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  219. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  220. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  221. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  222. package/web/dist/index.html +15 -9
  223. package/web/dist/sw.js +1 -1
  224. package/web/dist/assets/TerminalPanel-3wojLfLk.js +0 -3
  225. package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
  226. package/web/dist/assets/index-BwL7qBh6.css +0 -1
  227. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  228. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -5,7 +5,10 @@
5
5
  * 全部为无状态 fs 操作 + 两个自持的 watcher(当前列出目录、git dir),
6
6
  * 经 FilesHost 回调与 ClientSession 解耦。
7
7
  */
8
- import { Dirent, existsSync, mkdirSync, readFileSync, statSync, writeFileSync, watch } from "node:fs";
8
+ import { Dirent, existsSync, mkdirSync, readFileSync, statSync, watch } from "node:fs";
9
+ import { saveFilePreservingMetadata } from "./file-save.js";
10
+ import { isUploadDataTooLong, uploadLimitBytes } from "./payload-limits.js";
11
+ import { writeUploadExclusiveSync, writeRemoteUploadExclusive } from "./uploads.js";
9
12
  import { homedir } from "node:os";
10
13
  import { resolve, relative, sep, isAbsolute, posix } from "node:path";
11
14
  import { pick } from "./i18n.js";
@@ -91,17 +94,7 @@ export function absoluteParent(wire) {
91
94
  }
92
95
  /** 预览只读文件前 512KB。 */
93
96
  export const MAX_PREVIEW_BYTES = 512 * 1024;
94
- /** 右键上传单文件上限(内存中转 base64 → Buffer)。 */
95
- export const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
96
- /** 上传 cap 对应的 base64 文本长度上限(4/3 膨胀,向上取整到 4 字符边界)。 */
97
- export const MAX_UPLOAD_BASE64_CHARS = Math.ceil(MAX_UPLOAD_BYTES / 3) * 4;
98
- /** WS 入站帧上限:base64 上限 + 1MB JSON 包络余量(dirPath/name/type)。
99
- * server/index.ts 的 maxPayload 由此取值,两处上限保持对齐。 */
100
- export const WS_MAX_PAYLOAD_BYTES = MAX_UPLOAD_BASE64_CHARS + 1024 * 1024;
101
- /** base64 文本长度是否必定超 cap(解码前快拒,不分配 Buffer)。 */
102
- export function isUploadDataTooLong(dataLength, capBytes = MAX_UPLOAD_BYTES) {
103
- return dataLength > Math.ceil(capBytes / 3) * 4;
104
- }
97
+ export { MAX_UPLOAD_BYTES, MAX_UPLOAD_BASE64_CHARS, WS_MAX_PAYLOAD_BYTES, isUploadDataTooLong, } from "./payload-limits.js";
105
98
  // mac/linux: hide build & dependency noise (original behavior).
106
99
  const IGNORED_ENTRIES = new Set([
107
100
  "node_modules",
@@ -439,8 +432,8 @@ export class FilesService {
439
432
  }
440
433
  const { join } = await import("node:path");
441
434
  const fsp = await import("node:fs/promises");
442
- const q = query.trim().toLowerCase();
443
- if (!q) {
435
+ const rawQuery = query.trim();
436
+ if (!rawQuery) {
444
437
  this.host.emit({ type: "search_files_result", reqId, ok: true, results: [] });
445
438
  return;
446
439
  }
@@ -453,6 +446,49 @@ export class FilesService {
453
446
  const results = [];
454
447
  let visited = 0;
455
448
  let truncated = false;
449
+ // 1) 优先精确探测输入是否为已存在的绝对路径或相对路径
450
+ const normQuery = rawQuery.replace(/\\/g, "/");
451
+ const q = normQuery.toLowerCase();
452
+ try {
453
+ if (isAbsoluteWirePath(normQuery) ||
454
+ (normQuery.startsWith("~") && (normQuery === "~" || normQuery.startsWith("~/")))) {
455
+ const { homedir } = await import("node:os");
456
+ const home = homedir();
457
+ const targetAbs = normQuery.startsWith("~")
458
+ ? normQuery === "~"
459
+ ? home
460
+ : join(home, normQuery.slice(2))
461
+ : wireToAbs(normQuery);
462
+ const st = await fsp.stat(targetAbs).catch(() => null);
463
+ if (st) {
464
+ const wp = workspacePath(root, targetAbs);
465
+ const wirePath = wp ? wp.rel : targetAbs.split(sep).join("/");
466
+ const baseName = targetAbs.split(/[\\/]/).pop() || wirePath;
467
+ results.push({
468
+ path: wirePath,
469
+ name: baseName,
470
+ type: st.isDirectory() ? "dir" : "file",
471
+ });
472
+ }
473
+ }
474
+ else {
475
+ const directWp = workspacePath(root, normQuery);
476
+ if (directWp) {
477
+ const st = await fsp.stat(directWp.abs).catch(() => null);
478
+ if (st) {
479
+ const baseName = directWp.abs.split(/[\\/]/).pop() || directWp.rel;
480
+ results.push({
481
+ path: directWp.rel,
482
+ name: baseName,
483
+ type: st.isDirectory() ? "dir" : "file",
484
+ });
485
+ }
486
+ }
487
+ }
488
+ }
489
+ catch {
490
+ /* ignore probe failure */
491
+ }
456
492
  const budgetLeft = () => results.length < MAX_RESULTS && visited < MAX_VISITED && Date.now() - start < MAX_MS;
457
493
  // Breadth-first-ish iterative stack; depth cap is a symlink-cycle guard.
458
494
  const walk = async (abs, rel, depth) => {
@@ -487,7 +523,9 @@ export class FilesService {
487
523
  isDir = false; // broken link — treat as file
488
524
  }
489
525
  }
490
- if (d.name.toLowerCase().includes(q)) {
526
+ const childRelLower = childRel.toLowerCase();
527
+ const nameLower = d.name.toLowerCase();
528
+ if ((nameLower.includes(q) || childRelLower.includes(q)) && !results.some((r) => r.path === childRel)) {
491
529
  results.push({
492
530
  path: childRel,
493
531
  name: d.name,
@@ -954,7 +992,7 @@ export class FilesService {
954
992
  });
955
993
  return;
956
994
  }
957
- writeFileSync(abs, text, "utf8");
995
+ await saveFilePreservingMetadata(abs, text);
958
996
  this.host.emit({
959
997
  type: "notice",
960
998
  level: "info",
@@ -981,13 +1019,17 @@ export class FilesService {
981
1019
  * malicious payload can't escape the directory. Emits notice + file_changed
982
1020
  * for the target dir (the recursive watcher may not cover it on posix).
983
1021
  */
984
- async uploadFile(relDir, name, data) {
1022
+ async uploadFile(relDir, name, data, uploadId) {
985
1023
  const root = this.host.getCwd();
986
1024
  if (isRemoteWorkspaceUri(root)) {
987
- await this.uploadRemoteFile(root, relDir, name, data);
1025
+ await this.uploadRemoteFile(root, relDir, name, data, uploadId);
988
1026
  return;
989
1027
  }
990
- const emitErr = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
1028
+ const emitErr = (text, textEn) => {
1029
+ this.host.emit({ type: "notice", level: "error", text, textEn });
1030
+ if (typeof uploadId === "string")
1031
+ this.host.emit({ type: "file_upload_result", uploadId, ok: false, error: textEn ?? text });
1032
+ };
991
1033
  try {
992
1034
  const absDir = relDir ? isAbsoluteWirePath(relDir) : false;
993
1035
  let wp;
@@ -1027,8 +1069,9 @@ export class FilesService {
1027
1069
  }
1028
1070
  uploadRel = rawRel.split(sep).join("/");
1029
1071
  }
1030
- if (isUploadDataTooLong(data.length)) {
1031
- emitErr(`文件过大:${name}(上限 ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`, `File too large: ${name} (max ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`);
1072
+ const maxBytes = this.host.getUploadMaxBytes?.() ?? uploadLimitBytes({}, "workspace");
1073
+ if (isUploadDataTooLong(data.length, maxBytes)) {
1074
+ emitErr(`文件过大:${name}(上限 ${Math.round(maxBytes / 1024 / 1024)}MB)`, `File too large: ${name} (max ${Math.round(maxBytes / 1024 / 1024)}MB)`);
1032
1075
  return;
1033
1076
  }
1034
1077
  const buf = Buffer.from(data, "base64");
@@ -1036,8 +1079,8 @@ export class FilesService {
1036
1079
  emitErr(`空文件:${name}`, `Empty file: ${name}`);
1037
1080
  return;
1038
1081
  }
1039
- if (buf.length > MAX_UPLOAD_BYTES) {
1040
- emitErr(`文件过大:${name}(上限 ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`, `File too large: ${name} (max ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`);
1082
+ if (buf.length > maxBytes) {
1083
+ emitErr(`文件过大:${name}(上限 ${Math.round(maxBytes / 1024 / 1024)}MB)`, `File too large: ${name} (max ${Math.round(maxBytes / 1024 / 1024)}MB)`);
1041
1084
  return;
1042
1085
  }
1043
1086
  mkdirSync(wp.abs, { recursive: true });
@@ -1048,7 +1091,7 @@ export class FilesService {
1048
1091
  // wx:与预检之间存在窗口(TOCTOU),并发同名上传走 EEXIST 落到 catch
1049
1092
  // 报错 —— 两个上传路径语义统一为「目标已存在拒绝」,绝不静默截断覆盖
1050
1093
  // (/api/file-transfer/upload 一直是 open(dest, "wx") 拒绝)。
1051
- writeFileSync(abs, buf, { flag: "wx" });
1094
+ writeUploadExclusiveSync(abs, buf);
1052
1095
  this.host.emit({
1053
1096
  type: "notice",
1054
1097
  level: "info",
@@ -1062,6 +1105,8 @@ export class FilesService {
1062
1105
  type: "file_changed",
1063
1106
  path: wp.rel,
1064
1107
  });
1108
+ if (typeof uploadId === "string")
1109
+ this.host.emit({ type: "file_upload_result", uploadId, ok: true });
1065
1110
  }
1066
1111
  catch (err) {
1067
1112
  emitErr(`上传文件失败:${err.message}`, `Upload failed: ${err.message}`);
@@ -1760,8 +1805,8 @@ export class FilesService {
1760
1805
  }
1761
1806
  }
1762
1807
  async searchRemoteFiles(rawCwd, query, reqId) {
1763
- const q = query.trim().toLowerCase();
1764
- if (!q) {
1808
+ const rawQuery = query.trim();
1809
+ if (!rawQuery) {
1765
1810
  this.host.emit({ type: "search_files_result", reqId, ok: true, results: [] });
1766
1811
  return;
1767
1812
  }
@@ -1771,17 +1816,36 @@ export class FilesService {
1771
1816
  return;
1772
1817
  }
1773
1818
  try {
1819
+ const normQuery = rawQuery.replace(/\\/g, "/");
1820
+ const q = normQuery.toLowerCase();
1821
+ const results = [];
1822
+ let truncated = false;
1823
+ // 优先精确检查直接目标
1824
+ const target = this.resolveRemoteTarget(rawCwd, normQuery);
1825
+ if (target) {
1826
+ try {
1827
+ const st = await sshSvc.sftpStat(rawCwd, target.abs);
1828
+ const name = posix.basename(target.abs) || target.rel;
1829
+ results.push({
1830
+ path: target.rel,
1831
+ name,
1832
+ type: st.isDirectory ? "dir" : "file",
1833
+ });
1834
+ }
1835
+ catch {
1836
+ /* ignore stat error */
1837
+ }
1838
+ }
1774
1839
  const cmd = `find . -maxdepth 8 \\( -name node_modules -o -name .git -o -name .pi-web \\) -prune -o -print 2>/dev/null | head -n 5000`;
1775
1840
  const res = await sshSvc.execInWorkspace(rawCwd, cmd, { timeoutMs: 8000 });
1776
1841
  const lines = res.stdout.split(/\r?\n/);
1777
- const results = [];
1778
- let truncated = false;
1779
1842
  for (const line of lines) {
1780
1843
  const clean = line.trim().replace(/^\.\//, "");
1781
1844
  if (!clean || clean === ".")
1782
1845
  continue;
1783
1846
  const name = posix.basename(clean);
1784
- if (name.toLowerCase().includes(q)) {
1847
+ if ((name.toLowerCase().includes(q) || clean.toLowerCase().includes(q)) &&
1848
+ !results.some((r) => r.path === clean)) {
1785
1849
  results.push({
1786
1850
  path: clean,
1787
1851
  name,
@@ -1929,6 +1993,11 @@ export class FilesService {
1929
1993
  });
1930
1994
  return;
1931
1995
  }
1996
+ // Preserve the existing SFTP file object (ACLs, xattrs and symlink target).
1997
+ // Keep the established SFTP save path rather than GNU shell replacement.
1998
+ const info = await sshSvc.sftpStat(rawCwd, t.abs);
1999
+ if (!info.isFile || info.size > 2 * 1024 * 1024)
2000
+ throw new Error("Remote save target must be a regular file no larger than 2MB");
1932
2001
  await sshSvc.sftpWriteFile(rawCwd, t.abs, text);
1933
2002
  this.host.emit({
1934
2003
  type: "notice",
@@ -1947,8 +2016,12 @@ export class FilesService {
1947
2016
  });
1948
2017
  }
1949
2018
  }
1950
- async uploadRemoteFile(rawCwd, relDir, name, data) {
1951
- const emitErr = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
2019
+ async uploadRemoteFile(rawCwd, relDir, name, data, uploadId) {
2020
+ const emitErr = (text, textEn) => {
2021
+ this.host.emit({ type: "notice", level: "error", text, textEn });
2022
+ if (typeof uploadId === "string")
2023
+ this.host.emit({ type: "file_upload_result", uploadId, ok: false, error: textEn ?? text });
2024
+ };
1952
2025
  try {
1953
2026
  const sshSvc = getGlobalRemoteSshService();
1954
2027
  if (!sshSvc)
@@ -1963,12 +2036,13 @@ export class FilesService {
1963
2036
  emitErr(`文件名不合法:${name}`, `Invalid file name: ${name}`);
1964
2037
  return;
1965
2038
  }
1966
- if (isUploadDataTooLong(data.length)) {
2039
+ const maxBytes = this.host.getUploadMaxBytes?.() ?? uploadLimitBytes({}, "workspace");
2040
+ if (isUploadDataTooLong(data.length, maxBytes)) {
1967
2041
  emitErr(`文件过大:${name}`, `File too large: ${name}`);
1968
2042
  return;
1969
2043
  }
1970
2044
  const buf = Buffer.from(data, "base64");
1971
- if (buf.length === 0 || buf.length > MAX_UPLOAD_BYTES) {
2045
+ if (buf.length === 0 || buf.length > maxBytes) {
1972
2046
  emitErr(`文件大小不合法:${name}`, `Invalid file size: ${name}`);
1973
2047
  return;
1974
2048
  }
@@ -1978,7 +2052,7 @@ export class FilesService {
1978
2052
  emitErr(`已存在:${safe}`, `Already exists: ${safe}`);
1979
2053
  return;
1980
2054
  }
1981
- await sshSvc.sftpWriteFile(rawCwd, destAbs, buf, { createParents: true });
2055
+ await writeRemoteUploadExclusive(sshSvc, rawCwd, destAbs, buf);
1982
2056
  const uploadRel = dirTarget.rel ? `${dirTarget.rel}/${safe}` : safe;
1983
2057
  this.host.emit({
1984
2058
  type: "notice",
@@ -1990,6 +2064,8 @@ export class FilesService {
1990
2064
  type: "file_changed",
1991
2065
  path: dirTarget.rel,
1992
2066
  });
2067
+ if (typeof uploadId === "string")
2068
+ this.host.emit({ type: "file_upload_result", uploadId, ok: true });
1993
2069
  }
1994
2070
  catch (err) {
1995
2071
  emitErr(`上传文件失败:${err.message}`, `Upload failed: ${err.message}`);
@@ -16,7 +16,8 @@
16
16
  * 同样被包裹;但之后经 refreshPluginTools 动态补入已有会话的不在覆盖面。
17
17
  * 自研插件若绕过 wrapper 直接写文件同样拦不住 —— 只读是硬闸门,不是安全边界。
18
18
  */
19
- import { bashCommandIsReadOnly, SESSION_DISPATCH_TOOLS } from "./plan-mode.js";
19
+ import { bashCommandIsReadOnly, readOnlyToolCallAllowed, SESSION_DISPATCH_TOOLS } from "./plan-mode.js";
20
+ import { isReadOnlyConversationAction, isConversationTool } from "./conversation-tool-names.js";
20
21
  /** 审查回合禁写的工具:与计划/审查者模式同名单(写 / 改 / 增删 / git 写 / 形态变换)。 */
21
22
  const WRITE_TOOLS = new Set([
22
23
  // 文件写入与编辑(第一方 + SDK 内置 + 编辑器类扩展的常见名)
@@ -68,12 +69,12 @@ const WRITE_TOOLS = new Set([
68
69
  * 别的对话、排程、改模式 / 开新目标都会绕开「一轮 = 派活 + 判定」的口径。
69
70
  * 名单 = 三闸门共用的真实注册派发工具(SESSION_DISPATCH_TOOLS,#436 前是一堆
70
71
  * 幽灵名)。subagent 不在此列:上面的按 action 判定已拦掉全部写向 action,
71
- * 只读的 `conversation_read` / subagent get_result/list/templates 放行 ——
72
+ * conversation 的只读操作(read/files/status/get_result/list/templates)放行 ——
72
73
  * 审查者可以按需看执行者的转录(契约要求看实际状态,而不是信描述)。
73
74
  */
74
75
  const DISPATCH_TOOLS = SESSION_DISPATCH_TOOLS;
75
76
  /** bash 家族(要逐条判命令是否只读;与审查者模式同名单)。 */
76
- const BASH_TOOLS = new Set(["bash", "shell", "sh", "zsh", "terminal", "terminal_bash", "run_command", "exec"]);
77
+ const BASH_TOOLS = new Set(["bash", "shell", "sh", "zsh", "terminal_bash", "run_command", "exec"]);
77
78
  /** 引号感知的命令切分(按 | ; && || 换行拆段;含 $( / 反引号时整条视为一段交白名单判
78
79
  * —— 白名单必拒,方向是 fail-closed,这里的拆分只会让判定更严不会放宽)。 */
79
80
  function splitReviewSegments(cmd) {
@@ -206,11 +207,11 @@ export function goalReviewDenial(toolName, params) {
206
207
  reasonEn: "Goal review round: do not ask the user anything (this round is server-driven; dialogs go unanswered). Just review this round and reply with only the verdict JSON.",
207
208
  };
208
209
  }
209
- if (name === "subagent") {
210
+ if (isConversationTool(name)) {
210
211
  const action = typeof params === "object" && params !== null ? params.action : undefined;
211
212
  const act = typeof action === "string" ? action.trim().toLowerCase() : "";
212
- // 只读 action(get_result, list, templates)放行;其余(spawn, steer, stop, wait_all, handoff)或未传 action 均拒绝
213
- if (act === "get_result" || act === "list" || act === "templates") {
213
+ // Transcript inspection and collaboration queries are read-only; mutations and missing actions are rejected.
214
+ if (isReadOnlyConversationAction(act)) {
214
215
  return undefined;
215
216
  }
216
217
  return {
@@ -226,6 +227,15 @@ export function goalReviewDenial(toolName, params) {
226
227
  reasonEn: `Goal review round: ${name} is unavailable — the server owns the rounds. Just review this round and reply with only the verdict JSON.`,
227
228
  };
228
229
  }
230
+ if (name === "terminal") {
231
+ if (readOnlyToolCallAllowed(name, params))
232
+ return undefined;
233
+ return {
234
+ kind: "write-tool",
235
+ reason: "只读审查仅允许 terminal 的 list/read/wait。",
236
+ reasonEn: "Read-only review permits only terminal list/read/wait actions.",
237
+ };
238
+ }
229
239
  if (BASH_TOOLS.has(name)) {
230
240
  const cmd = commandOf(params);
231
241
  if (cmd.trim() === "") {
@@ -482,9 +482,13 @@ export class GoalService {
482
482
  * and not be thrown away.
483
483
  */
484
484
  async setGoal(goalText, opts) {
485
+ await this.commitGoal(goalText, opts);
486
+ }
487
+ /** Return the exact committed request so callers can guard follow-up work. */
488
+ async commitGoal(goalText, opts) {
485
489
  const text = (goalText ?? "").trim();
486
490
  if (!text) {
487
- await this.clearGoal();
491
+ await this.clearGoal(opts?.targetConvId);
488
492
  return;
489
493
  }
490
494
  if (!this.goalEnabled()) {
@@ -529,12 +533,14 @@ export class GoalService {
529
533
  }
530
534
  const conv = targetConv ?? this.host.activeConv();
531
535
  const goalConversationId = conv.id;
532
- conv.goalGeneration += 1;
536
+ const gen = ++conv.goalGeneration;
533
537
  // 上一轮目标可能还留着常驻执行者子代理(委托执行):先停掉再开新的,
534
538
  // 否则旧循环会在新目标上继续派活(代次已作废,但角色对话得收)。
535
539
  // await 到 dismiss 完全落定:后面的 spawn 名额检查才不会数到还在收尾的
536
540
  // 旧执行者而误报上限(issue #464;stopDelegated 自身已按会话串行化)。
537
541
  await this.stopDelegated(conv);
542
+ if (!this.isCurrentGoalRequest(conv, gen))
543
+ return;
538
544
  const goal = conv.goal;
539
545
  goal.reviewing = false;
540
546
  goal.conversationId = goalConversationId;
@@ -586,11 +592,8 @@ export class GoalService {
586
592
  text: `🎯 已设目标:${text.slice(0, 80)}${text.length > 80 ? "…" : ""}`,
587
593
  textEn: `🎯 Goal set: ${text.slice(0, 80)}${text.length > 80 ? "…" : ""}`,
588
594
  });
589
- // Auto-start generation right after setting the goal (unless this setGoal is
590
- // the wizard's internal one, which kicks off itself). This makes the direct
591
- // goal-bar path behave like the AI-提炼 path: set a target → agent begins.
595
+ // Direct requests auto-start; the wizard commits its plan before starting.
592
596
  if (opts?.autoStart !== false) {
593
- const gen = conv.goalGeneration;
594
597
  // #591:主对话若仍在跑设目标前的旧任务,首轮派发执行者前先中断让位,
595
598
  // 避免主对话与目标执行者在同一工作区并行动工、污染采样 diff。
596
599
  await this.preemptMainRunForGoal(conv, gen);
@@ -602,6 +605,7 @@ export class GoalService {
602
605
  this.startDelegatedLoop(conv, gen, text);
603
606
  this.host.flushSnapshot();
604
607
  }
608
+ return { conv, generation: gen };
605
609
  }
606
610
  /**
607
611
  * Collaborative target wizard. Turns a raw user requirement into a refined
@@ -631,6 +635,7 @@ export class GoalService {
631
635
  // new active conversation while the wizard is still finishing.
632
636
  const wizardConversationId = this.host.activeConvId();
633
637
  const wizardConversation = this.host.activeConv();
638
+ const wizardGeneration = wizardConversation.goalGeneration;
634
639
  // Human-readable name for notices that must say WHICH conversation the survey
635
640
  // belongs to (issue #292: the user is expected to switch away mid-survey).
636
641
  const wizardConversationTitle = wizardConversation.title;
@@ -1051,16 +1056,16 @@ export class GoalService {
1051
1056
  });
1052
1057
  return;
1053
1058
  }
1054
- const switchedAway = this.host.activeConvId() !== wizardConversationId;
1055
- if (parsedSteps.length > 0) {
1056
- this.host.setPlan?.(wizardConversationId, parsedSteps);
1059
+ if (targetConv !== wizardConversation || !this.isCurrentGoalRequest(wizardConversation, wizardGeneration)) {
1060
+ return;
1057
1061
  }
1062
+ const switchedAway = this.host.activeConvId() !== wizardConversationId;
1058
1063
  // Auto-set the refined goal. The wizard workflow implies "set a goal and
1059
1064
  // work until it passes", so default LOCKED=true unless the user explicitly
1060
1065
  // turned the lock off (a lock lets the review loop keep revising to pass;
1061
1066
  // without it the review is single-shot).
1062
1067
  const wantLocked = opts?.locked === undefined ? true : opts.locked;
1063
- await this.setGoal(refinedGoal, {
1068
+ const committed = await this.commitGoal(refinedGoal, {
1064
1069
  reviewModel: wgoal.reviewModel ?? undefined,
1065
1070
  maxRounds: opts?.maxRounds,
1066
1071
  locked: wantLocked,
@@ -1069,9 +1074,21 @@ export class GoalService {
1069
1074
  // Land the goal on the conversation that launched the survey, even if the
1070
1075
  // user is looking at another one right now (issue #292).
1071
1076
  targetConvId: wizardConversationId,
1072
- // The wizard kicks off generation itself below — avoid a double kick.
1073
1077
  autoStart: false,
1074
1078
  });
1079
+ if (!committed || !this.isCurrentDelegated(committed.conv, committed.generation))
1080
+ return;
1081
+ if (parsedSteps.length > 0) {
1082
+ this.host.setPlan?.(wizardConversationId, parsedSteps);
1083
+ }
1084
+ // Preserve plan-before-execution ordering, and retain the commit token across preemption.
1085
+ if (!this.isCurrentDelegated(committed.conv, committed.generation))
1086
+ return;
1087
+ await this.preemptMainRunForGoal(committed.conv, committed.generation);
1088
+ if (!this.isCurrentDelegated(committed.conv, committed.generation))
1089
+ return;
1090
+ this.startDelegatedLoop(committed.conv, committed.generation, refinedGoal);
1091
+ this.host.flushSnapshot();
1075
1092
  this.wizardCancelled = false;
1076
1093
  this.host.emit({
1077
1094
  type: "notice",
@@ -1083,12 +1100,6 @@ export class GoalService {
1083
1100
  ? `🎯 Survey done in "${wizardConversationTitle}", goal set: ${refinedGoal.slice(0, 80)}${refinedGoal.length > 80 ? "…" : ""} (switch back to that conversation to watch it generate)`
1084
1101
  : `🎯 Survey done, goal set: ${refinedGoal.slice(0, 80)}${refinedGoal.length > 80 ? "…" : ""}`,
1085
1102
  });
1086
- // 目标模式 2.0(唯一路径):不向主对话注入「开始实现」——它在目标模式下是审查者,
1087
- // 干活的另有执行对话,改由服务端循环驱动(setGoal 已把 goal 落在发起会话上)。
1088
- if (targetConv.goal.goal) {
1089
- this.startDelegatedLoop(targetConv, targetConv.goalGeneration, targetConv.goal.goal);
1090
- this.host.flushSnapshot();
1091
- }
1092
1103
  }
1093
1104
  /** Persist goal/review preference defaults (model, rounds cap, locked) without
1094
1105
  * touching the active goal — so changes in the goal bar are remembered across
@@ -1133,19 +1144,24 @@ export class GoalService {
1133
1144
  });
1134
1145
  this.emitGoalStatus();
1135
1146
  }
1136
- /** Clear the active goal (cancels the review loop AND aborts a running
1137
- * goal wizard — truly terminating its in-flight dialog + agent run). */
1138
- async clearGoal() {
1139
- const conv = this.host.activeConv();
1140
- conv.goalGeneration += 1;
1147
+ /** Clear the specified conversation's goal, or the active one by default.
1148
+ * Cancels its review loop and any running goal wizard. */
1149
+ async clearGoal(target) {
1150
+ const conv = typeof target === "string" ? this.host.getConv(target) : (target ?? this.host.activeConv());
1151
+ // Missing/stale explicit targets must never fall back to the active conversation.
1152
+ if (!conv || this.host.isDisposed() || this.host.getConv(conv.id) !== conv)
1153
+ return;
1154
+ const gen = ++conv.goalGeneration;
1141
1155
  // 委托执行:停掉在飞的执行者(循环靠代次作废 + 代次守卫退出)。
1142
1156
  // await 落定,保证旧执行者已移出会话表,后续重设目标不再误报名额(issue #464)。
1143
1157
  await this.stopDelegated(conv);
1158
+ if (!this.isCurrentGoalRequest(conv, gen))
1159
+ return;
1144
1160
  this.resetLoopCounters(conv);
1145
1161
  this.clearGoalFields(conv);
1146
1162
  this.emitGoalStatus();
1147
1163
  // Abort a running wizard for real (✗ in the goal bar while scoping).
1148
- if (this.wizardOwnerId === this.host.activeConvId()) {
1164
+ if (this.wizardOwnerId === conv.id) {
1149
1165
  await this.abortWizard();
1150
1166
  }
1151
1167
  }
@@ -1179,10 +1195,12 @@ export class GoalService {
1179
1195
  const conv = this.host.getConv(convId);
1180
1196
  if (!conv)
1181
1197
  continue;
1182
- conv.goalGeneration += 1; // 作废在飞回调(循环靠代次守卫退出)
1198
+ const gen = ++conv.goalGeneration; // 作废在飞回调(循环靠代次守卫退出)
1183
1199
  // 逐个 await 停/收落定(stopDelegated 已按会话串行化,issue #464):
1184
1200
  // 停执行者 + 唤醒 verdict 等待者 + 清 roles/phase
1185
1201
  await this.stopDelegated(conv);
1202
+ if (!this.isCurrentGoalRequest(conv, gen))
1203
+ continue;
1186
1204
  this.resetLoopCounters(conv);
1187
1205
  this.clearGoalFields(conv);
1188
1206
  stopped++;
@@ -1298,13 +1316,13 @@ export class GoalService {
1298
1316
  const v = this.host.roleDeadlineMs?.();
1299
1317
  return typeof v === "number" && v > 0 ? v : 20 * 60_000;
1300
1318
  }
1319
+ /** Mutation requests remain valid even before a goal exists. Never adopt a newer generation. */
1320
+ isCurrentGoalRequest(conv, goalGeneration) {
1321
+ return !this.host.isDisposed() && this.host.getConv(conv.id) === conv && conv.goalGeneration === goalGeneration;
1322
+ }
1301
1323
  /** 代次守卫:目标没被改/清、会话还在才算本轮有效。 */
1302
1324
  isCurrentDelegated(conv, goalGeneration) {
1303
- return (!this.host.isDisposed() &&
1304
- this.host.getConv(conv.id) === conv &&
1305
- conv.goal.conversationId === conv.id &&
1306
- conv.goalGeneration === goalGeneration &&
1307
- !!conv.goal.goal);
1325
+ return this.isCurrentGoalRequest(conv, goalGeneration) && conv.goal.conversationId === conv.id && !!conv.goal.goal;
1308
1326
  }
1309
1327
  isConvStreaming(conv) {
1310
1328
  try {
@@ -1326,6 +1344,8 @@ export class GoalService {
1326
1344
  * 仅在首轮派发前生效(按 goalGeneration 去重),委托执行期间用户在主对话发起的新聊天不受影响。
1327
1345
  */
1328
1346
  async preemptMainRunForGoal(conv, goalGeneration) {
1347
+ if (!this.isCurrentDelegated(conv, goalGeneration))
1348
+ return;
1329
1349
  if (!this.isConvStreaming(conv))
1330
1350
  return;
1331
1351
  if (conv.preemptedGoalGen === goalGeneration)
@@ -1357,6 +1377,8 @@ export class GoalService {
1357
1377
  }
1358
1378
  /** 启动委托循环(同一对话同时只允许一个在飞;旧循环退场中到来的请求排队接力)。 */
1359
1379
  startDelegatedLoop(conv, goalGeneration, goalText) {
1380
+ if (!this.isCurrentDelegated(conv, goalGeneration))
1381
+ return;
1360
1382
  if (this.delegatedLoops.has(conv.id)) {
1361
1383
  this.delegatedPending.set(conv.id, { goalGeneration, goalText });
1362
1384
  return;
@@ -1486,6 +1508,7 @@ export class GoalService {
1486
1508
  return run;
1487
1509
  }
1488
1510
  async stopDelegatedNow(conv) {
1511
+ const gen = conv.goalGeneration;
1489
1512
  // 排队的启动请求一并作废:setGoal 会在后面按新代次重新排,clearGoal 则不需要。
1490
1513
  this.delegatedPending.delete(conv.id);
1491
1514
  conv.awaitingVerdict = undefined;
@@ -1509,7 +1532,8 @@ export class GoalService {
1509
1532
  }
1510
1533
  catch { }
1511
1534
  }
1512
- conv.goal.phase = "idle";
1535
+ if (this.isCurrentGoalRequest(conv, gen))
1536
+ conv.goal.phase = "idle";
1513
1537
  }
1514
1538
  /** 会话过户时清理目标审查态并唤醒等待者(issue #457)。 */
1515
1539
  notifyTakeover(conv) {