pi-web-ui 0.113.1 → 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 (222) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/README.md +117 -246
  3. package/README.zh-CN.md +145 -217
  4. package/README.zh-TW.md +145 -217
  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 +47 -15
  8. package/dist/server/agent-service-daemon.js +102 -24
  9. package/dist/server/agent-service.js +2289 -1120
  10. package/dist/server/approval-rules.js +29 -3
  11. package/dist/server/ask-user-question-tool.js +8 -8
  12. package/dist/server/atomic-file.js +35 -14
  13. package/dist/server/attachment-store.js +71 -35
  14. package/dist/server/attachments.js +18 -8
  15. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  16. package/dist/server/canvas/canvas-dispatch.js +61 -20
  17. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  18. package/dist/server/canvas/canvas-scheduler.js +99 -0
  19. package/dist/server/canvas/canvas-store.js +107 -54
  20. package/dist/server/canvas/canvas-validation.js +131 -0
  21. package/dist/server/canvas/canvas-workspace.js +284 -0
  22. package/dist/server/client-id-utils.js +8 -0
  23. package/dist/server/client-state.js +104 -22
  24. package/dist/server/communicate-tool.js +76 -0
  25. package/dist/server/compact-context-tool.js +2 -3
  26. package/dist/server/compaction-instructions.js +75 -0
  27. package/dist/server/compaction-markers.js +7 -2
  28. package/dist/server/compaction-state.js +84 -0
  29. package/dist/server/composer-drafts.js +43 -40
  30. package/dist/server/context-evidence.js +346 -0
  31. package/dist/server/conversation-communication.js +368 -0
  32. package/dist/server/conversation-read-tool.js +3 -4
  33. package/dist/server/conversation-tool-names.js +14 -0
  34. package/dist/server/conversation-tool.js +57 -0
  35. package/dist/server/delegate-mode.js +17 -4
  36. package/dist/server/device-center/bot-catalog.js +88 -0
  37. package/dist/server/device-center/bot-execution.js +106 -0
  38. package/dist/server/device-center/bots.js +170 -0
  39. package/dist/server/device-center/collab-service.js +153 -0
  40. package/dist/server/device-center/collab-tool.js +184 -0
  41. package/dist/server/device-center/connector.js +332 -0
  42. package/dist/server/device-center/desktop-linux.js +372 -0
  43. package/dist/server/device-center/desktop-native.js +413 -0
  44. package/dist/server/device-center/desktop-page.js +232 -0
  45. package/dist/server/device-center/desktop-setup.js +30 -0
  46. package/dist/server/device-center/desktop.js +387 -0
  47. package/dist/server/device-center/device-portals.js +241 -0
  48. package/dist/server/device-center/execution-failure.js +70 -0
  49. package/dist/server/device-center/executor.js +371 -0
  50. package/dist/server/device-center/file-sync.js +493 -0
  51. package/dist/server/device-center/hub-auth.js +69 -0
  52. package/dist/server/device-center/hub-page.js +68 -0
  53. package/dist/server/device-center/hub-setup.js +214 -0
  54. package/dist/server/device-center/hub.js +829 -0
  55. package/dist/server/device-center/local-page.js +17 -0
  56. package/dist/server/device-center/local.js +476 -0
  57. package/dist/server/device-center/main.js +118 -0
  58. package/dist/server/device-center/native-desktop/macos.js +192 -0
  59. package/dist/server/device-center/native-desktop/windows.js +118 -0
  60. package/dist/server/device-center/path-portal.js +120 -0
  61. package/dist/server/device-center/relay.js +959 -0
  62. package/dist/server/device-center/runtime.js +253 -0
  63. package/dist/server/device-center/smoke-preview.js +3 -0
  64. package/dist/server/device-center/store.js +122 -0
  65. package/dist/server/device-center/task-error.js +14 -0
  66. package/dist/server/device-center/transfers.js +293 -0
  67. package/dist/server/device-center/workspaces.js +45 -0
  68. package/dist/server/dispatch-domain-handlers.js +83 -27
  69. package/dist/server/dsh/dsh-agent-service.js +277 -158
  70. package/dist/server/dsh/dsh-client.js +12 -2
  71. package/dist/server/durable/durable-agent-service.js +1 -1
  72. package/dist/server/evidence-tool-hooks.js +49 -0
  73. package/dist/server/file-save.js +95 -0
  74. package/dist/server/file-transfer-routes.js +97 -47
  75. package/dist/server/files-service.js +38 -26
  76. package/dist/server/goal-review-gate.js +16 -6
  77. package/dist/server/goal-service.js +54 -30
  78. package/dist/server/http-proxy.js +120 -0
  79. package/dist/server/index.js +229 -223
  80. package/dist/server/load-timing.js +31 -0
  81. package/dist/server/mcp-bridge.js +219 -94
  82. package/dist/server/mcp-hot-reload.js +31 -5
  83. package/dist/server/mcp-manager.js +192 -93
  84. package/dist/server/mcp-oauth-login.js +169 -0
  85. package/dist/server/mcp-oauth-ui.js +137 -0
  86. package/dist/server/mcp-oauth.js +395 -0
  87. package/dist/server/mcp-project-runtime.js +207 -0
  88. package/dist/server/message-window.js +74 -21
  89. package/dist/server/net-guard.js +122 -20
  90. package/dist/server/payload-limits.js +17 -0
  91. package/dist/server/pending-question.js +82 -0
  92. package/dist/server/plan-mode.js +338 -137
  93. package/dist/server/plugin-assets.js +8 -4
  94. package/dist/server/plugin-chat-attachments.js +48 -0
  95. package/dist/server/plugin-facilities.js +67 -220
  96. package/dist/server/plugin-installer.js +2 -1
  97. package/dist/server/plugin-removal.js +49 -0
  98. package/dist/server/plugin-secrets.js +179 -0
  99. package/dist/server/plugins.js +262 -92
  100. package/dist/server/preset-fields.js +49 -0
  101. package/dist/server/preset-plugin-dependencies.js +57 -0
  102. package/dist/server/preset-share.js +112 -72
  103. package/dist/server/protocol-version.js +1 -1
  104. package/dist/server/queue-modes.js +10 -0
  105. package/dist/server/remote-ssh-service.js +160 -67
  106. package/dist/server/request-context.js +164 -0
  107. package/dist/server/sandbox-data.js +655 -0
  108. package/dist/server/sandbox-engines.js +7 -0
  109. package/dist/server/sandbox-runtime-gate.js +41 -0
  110. package/dist/server/sandbox-service.js +139 -698
  111. package/dist/server/sandbox-tool.js +21 -4
  112. package/dist/server/scheduler-tasks.js +63 -48
  113. package/dist/server/serialize.js +48 -19
  114. package/dist/server/session-branch.js +25 -3
  115. package/dist/server/session-parser.js +28 -18
  116. package/dist/server/session-scan.js +130 -0
  117. package/dist/server/session-search.js +51 -37
  118. package/dist/server/settings-service.js +267 -111
  119. package/dist/server/setup-config.js +58 -0
  120. package/dist/server/skill-maintenance.js +112 -24
  121. package/dist/server/subagent-helpers.js +4 -1
  122. package/dist/server/subagent-notify.js +4 -1
  123. package/dist/server/subagent-security-gate.js +52 -11
  124. package/dist/server/subagent-task.js +27 -0
  125. package/dist/server/subagents.js +217 -46
  126. package/dist/server/tabs.js +9 -1
  127. package/dist/server/terminals.js +467 -363
  128. package/dist/server/tool-guards.js +42 -6
  129. package/dist/server/tool-manager.js +47 -20
  130. package/dist/server/tool-overrides.js +13 -11
  131. package/dist/server/tool-prompt-overrides.js +32 -2
  132. package/dist/server/tool-prompts.js +1 -1
  133. package/dist/server/turn-timing.js +11 -0
  134. package/dist/server/universal/session-store.js +48 -6
  135. package/dist/server/universal/universal-service.js +1 -1
  136. package/dist/server/universal/universal-session.js +334 -231
  137. package/dist/server/uploads.js +64 -5
  138. package/dist/server/worktree-service.js +32 -24
  139. package/dist/server/ws-pending-queue.js +73 -27
  140. package/docs/device-center.md +142 -0
  141. package/docs/device-desktop.md +48 -0
  142. package/package.json +4 -1
  143. package/plugin-sdk/index.d.ts +28 -6
  144. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  145. package/plugins/catalog.json +1 -1
  146. package/themes/aetheris.css +1 -107
  147. package/themes/ayu-light.css +5 -29
  148. package/themes/bases/flow-base.css +0 -6
  149. package/themes/bases/statusbar-flat-base.css +112 -0
  150. package/themes/bases/zhujian-base.css +1 -0
  151. package/themes/bases/zhupi-base.css +1 -0
  152. package/themes/catppuccin-latte.css +4 -27
  153. package/themes/catppuccin.css +4 -35
  154. package/themes/claude-code-dark.css +1 -0
  155. package/themes/codex.css +4 -28
  156. package/themes/cyberpunk.css +3 -61
  157. package/themes/dark-teal.css +0 -1
  158. package/themes/dazzle.css +3 -73
  159. package/themes/everforest-light.css +4 -27
  160. package/themes/geist.css +4 -28
  161. package/themes/gruvbox-light.css +4 -27
  162. package/themes/kanagawa-lotus.css +4 -27
  163. package/themes/md-preview.css +3 -213
  164. package/themes/mist.css +4 -24
  165. package/themes/nord.css +4 -35
  166. package/themes/one-dark.css +4 -37
  167. package/themes/paper.css +4 -16
  168. package/themes/rose-pine-dawn.css +4 -28
  169. package/themes/sakura.css +4 -24
  170. package/themes/solarized-light.css +4 -27
  171. package/themes/tokyo-night.css +3 -34
  172. package/themes/white.css +4 -26
  173. package/themes/zhujian-dark.css +1 -0
  174. package/themes/zhupi-dark.css +1 -0
  175. package/web/dist/.build-assets.json +1 -0
  176. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  177. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  178. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  179. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  180. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  181. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  182. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  183. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  184. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  185. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  186. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  187. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  188. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  189. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  190. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  191. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  192. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  193. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  194. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  195. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  196. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  197. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  198. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  199. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  200. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  201. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  202. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  203. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  204. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  205. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  206. package/web/dist/assets/index-Cje8iugL.js +83 -0
  207. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  208. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  209. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  210. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  211. package/web/dist/assets/math-BorAY7qD.css +1 -0
  212. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  213. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  214. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  215. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  216. package/web/dist/index.html +15 -9
  217. package/web/dist/sw.js +1 -1
  218. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  219. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  220. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  221. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  222. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -70,9 +70,18 @@ export function makeSandboxTool(host, getLang) {
70
70
  const cwd = host.getCwd();
71
71
  const activeSbx = host.sandboxes.getByCwd(cwd);
72
72
  try {
73
+ if (activeSbx) {
74
+ if (!["list", "persist"].includes(params.action)) {
75
+ throw new Error("Sandbox control and source comparison must be requested from outside the sandbox");
76
+ }
77
+ const target = params.sandbox?.trim();
78
+ if (target && target !== activeSbx.id && target !== activeSbx.path) {
79
+ throw new Error("Sandbox tools cannot access another sandbox");
80
+ }
81
+ }
73
82
  switch (params.action) {
74
83
  case "list": {
75
- const list = host.sandboxes.list();
84
+ const list = activeSbx ? [activeSbx] : host.sandboxes.list();
76
85
  if (list.length === 0) {
77
86
  return {
78
87
  content: [
@@ -183,7 +192,9 @@ export function makeSandboxTool(host, getLang) {
183
192
  }
184
193
  case "reset": {
185
194
  const target = params.sandbox?.trim() || activeSbx?.id || cwd;
186
- const { sandbox, copiedFiles } = await host.sandboxes.reset(target);
195
+ if (activeSbx)
196
+ throw new Error("Reset must be requested from outside the sandbox");
197
+ const { sandbox, copiedFiles } = await host.resetSandbox(target);
187
198
  await host.onSandboxesChanged();
188
199
  return {
189
200
  content: [
@@ -297,7 +308,9 @@ export function makeSandboxTool(host, getLang) {
297
308
  };
298
309
  }
299
310
  }
300
- const res = await host.sandboxes.applyToSource(diff.sandbox.id);
311
+ if (activeSbx)
312
+ throw new Error("Apply must be requested from outside the sandbox");
313
+ const res = await host.applySandboxToSource(diff.sandbox.id, diff.expectedRevision);
301
314
  await host.onSandboxesChanged();
302
315
  return {
303
316
  content: [
@@ -374,7 +387,11 @@ export function makeSandboxTool(host, getLang) {
374
387
  if (activeSbx?.id === targetInfo.id) {
375
388
  await host.setCwd(targetInfo.sourcePath && existsSync(targetInfo.sourcePath) ? targetInfo.sourcePath : homedir());
376
389
  }
377
- const destroyed = await host.sandboxes.destroy(targetInfo.id);
390
+ if (activeSbx)
391
+ throw new Error("Destroy must be requested from outside the sandbox");
392
+ const destroyed = await host.destroySandbox(targetInfo.id);
393
+ if (!destroyed)
394
+ throw new Error("Sandbox was not destroyed");
378
395
  await host.onSandboxesChanged();
379
396
  return {
380
397
  content: [
@@ -224,7 +224,7 @@ export class SchedulerStore {
224
224
  if (next <= now && task.catchUp === "once" && lastAt < now) {
225
225
  // 重启发现漏跑:补一次,补完按这次重排。
226
226
  this.nextFire.set(task.id, now + 5000);
227
- void this.fire(task.id, false);
227
+ void this.fire(task.id, false).catch((err) => this.reportFailure(err));
228
228
  }
229
229
  else if (next <= now) {
230
230
  this.nextFire.set(task.id, computeNextFire(task, now) ?? now + TICK_MS);
@@ -233,7 +233,7 @@ export class SchedulerStore {
233
233
  this.nextFire.set(task.id, next);
234
234
  }
235
235
  }
236
- this.timer = setInterval(() => void this.tick(), TICK_MS);
236
+ this.timer = setInterval(() => void this.tick().catch((err) => this.reportFailure(err)), TICK_MS);
237
237
  this.timer.unref?.();
238
238
  }
239
239
  stop() {
@@ -288,15 +288,20 @@ export class SchedulerStore {
288
288
  this.tasks = new Map();
289
289
  }
290
290
  }
291
- save() {
291
+ save(next) {
292
+ const tasks = Object.fromEntries(next);
293
+ writeJsonAtomicSync(schedulerFile(this.dataDir), { v: 1, tasks });
294
+ this.tasks = next;
295
+ }
296
+ reportFailure(err) {
297
+ console.error("[scheduler] execution failed:", err);
298
+ }
299
+ notify(...args) {
292
300
  try {
293
- const tasks = {};
294
- for (const [id, t] of this.tasks)
295
- tasks[id] = t;
296
- writeJsonAtomicSync(schedulerFile(this.dataDir), { v: 1, tasks });
301
+ this.opts.notify?.(...args);
297
302
  }
298
303
  catch (err) {
299
- console.error("[scheduler] persist failed:", err);
304
+ this.reportFailure(err);
300
305
  }
301
306
  }
302
307
  changed() {
@@ -353,18 +358,19 @@ export class SchedulerStore {
353
358
  }
354
359
  }
355
360
  const history = prev?.history ? sanitizeHistory(prev.history) : [];
356
- this.tasks.set(task.id, { ...task, history });
361
+ this.save(new Map(this.tasks).set(task.id, { ...task, history }));
357
362
  // spec/cwd/开关变了 → 按现在重排下次触发
358
363
  this.nextFire.set(task.id, computeNextFire(task, Date.now()) ?? Date.now() + TICK_MS);
359
- this.save();
360
364
  this.changed();
361
365
  return task;
362
366
  }
363
367
  remove(id) {
364
- const ok = this.tasks.delete(id);
365
- this.nextFire.delete(id);
368
+ const ok = this.tasks.has(id);
366
369
  if (ok) {
367
- this.save();
370
+ const next = new Map(this.tasks);
371
+ next.delete(id);
372
+ this.save(next);
373
+ this.nextFire.delete(id);
368
374
  this.changed();
369
375
  try {
370
376
  this.opts.onTaskRemoved?.(id);
@@ -376,23 +382,23 @@ export class SchedulerStore {
376
382
  return ok;
377
383
  }
378
384
  setEnabled(id, enabled) {
379
- const t = this.tasks.get(id);
380
- if (!t)
385
+ const prev = this.tasks.get(id);
386
+ if (!prev)
381
387
  return null;
382
- t.enabled = enabled;
383
- t.updatedAt = Date.now();
388
+ const t = { ...prev, enabled, updatedAt: Date.now() };
389
+ this.save(new Map(this.tasks).set(id, t));
384
390
  this.nextFire.set(id, computeNextFire(t, Date.now()) ?? Date.now() + TICK_MS);
385
- this.save();
386
391
  this.changed();
387
- return t;
392
+ return { ...t };
388
393
  }
389
394
  /** 会话重绑定(issue #231):触发时按稳定键找到了新的对话句柄,把任务的
390
395
  * 投递目标迁移过去(只改 conversationId/sessionFile/updatedAt,不碰下次触发
391
396
  * 与历史)。无变化回 false(调用方免一次落盘+推送);未知任务回 false。 */
392
397
  rebind(id, binding) {
393
- const t = this.tasks.get(id);
394
- if (!t)
398
+ const prev = this.tasks.get(id);
399
+ if (!prev)
395
400
  return false;
401
+ const t = { ...prev };
396
402
  let dirty = false;
397
403
  if (binding.conversationId !== undefined) {
398
404
  const v = String(binding.conversationId ?? "")
@@ -415,7 +421,7 @@ export class SchedulerStore {
415
421
  if (!dirty)
416
422
  return false;
417
423
  t.updatedAt = Date.now();
418
- this.save();
424
+ this.save(new Map(this.tasks).set(id, t));
419
425
  this.changed();
420
426
  return true;
421
427
  }
@@ -447,52 +453,61 @@ export class SchedulerStore {
447
453
  if (!task)
448
454
  return { ok: false, error: "任务不存在" };
449
455
  const executor = this.opts.executor;
450
- if (!executor) {
451
- const err = "调度器执行器未接入(当前引擎不支持定时任务)";
452
- this.recordRun(id, { at: Date.now(), ok: false, durationMs: 0, error: err, ...(manual ? { manual } : {}) });
453
- return { ok: false, error: err };
454
- }
455
456
  this.running.add(id);
456
457
  this.changed();
457
458
  const startedAt = Date.now();
458
459
  let result;
459
460
  try {
460
- result = await executor({ ...task });
461
+ result = executor
462
+ ? await executor({ ...task })
463
+ : { ok: false, error: "调度器执行器未接入(当前引擎不支持定时任务)" };
461
464
  }
462
465
  catch (err) {
463
- result = { ok: false, error: err.message };
466
+ result = { ok: false, error: String(err instanceof Error ? err.message : err) };
464
467
  }
465
468
  const durationMs = Date.now() - startedAt;
466
- this.running.delete(id);
467
- this.recordRun(id, {
468
- at: Date.now(),
469
- ok: result.ok,
470
- durationMs,
471
- ...(result.conversationId ? { conversationId: result.conversationId } : {}),
472
- ...(result.error ? { error: result.error.slice(0, 500) } : {}),
473
- ...(manual ? { manual } : {}),
474
- });
475
- // 按这次完成时间重排下次触发(间隔任务从完成起算,避免长任务连击)。
476
- const cur = this.tasks.get(id);
477
- if (cur && cur.enabled && !manual) {
478
- this.nextFire.set(id, computeNextFire(cur, Date.now()) ?? Date.now() + TICK_MS);
479
- this.save();
469
+ try {
470
+ this.recordRun(id, {
471
+ at: Date.now(),
472
+ ok: result.ok,
473
+ durationMs,
474
+ ...(result.conversationId ? { conversationId: result.conversationId } : {}),
475
+ ...(result.error ? { error: result.error.slice(0, 500) } : {}),
476
+ ...(manual ? { manual } : {}),
477
+ });
478
+ }
479
+ catch (err) {
480
+ result = {
481
+ ok: false,
482
+ error: `Failed to persist scheduled-task run: ${String(err instanceof Error ? err.message : err)}`,
483
+ };
484
+ this.reportFailure(err);
485
+ }
486
+ finally {
487
+ // 执行可能已产生外部副作用;记录写失败也不能在每个 tick 立即重试。
488
+ // 仅推进内存调度,使用执行期间更新后的配置,不伪造成功历史。
489
+ // 进程重启后仍可能补跑:本地记录与外部副作用不保证跨进程 exactly-once。
490
+ const cur = this.tasks.get(id);
491
+ if (cur && cur.enabled && !manual) {
492
+ this.nextFire.set(id, computeNextFire(cur, Date.now()) ?? Date.now() + TICK_MS);
493
+ }
494
+ this.running.delete(id);
495
+ this.changed();
480
496
  }
481
497
  const label = `⏰ ${task.name}`;
482
498
  if (result.ok) {
483
- this.opts.notify?.("info", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发完成(${(durationMs / 1000).toFixed(0)}s)——${label}`, `Scheduled task "${task.name}" ${manual ? "manually" : "automatically"} finished (${Math.round(durationMs / 1000)}s) — ${label}`);
499
+ this.notify("info", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发完成(${(durationMs / 1000).toFixed(0)}s)——${label}`, `Scheduled task "${task.name}" ${manual ? "manually" : "automatically"} finished (${Math.round(durationMs / 1000)}s) — ${label}`);
484
500
  }
485
501
  else {
486
- this.opts.notify?.("warning", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发失败:${result.error ?? "未知错误"}`, `Scheduled task "${task.name}" ${manual ? "manual" : "automatic"} run failed: ${result.error ?? "unknown error"}`);
502
+ this.notify("warning", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发失败:${result.error ?? "未知错误"}`, `Scheduled task "${task.name}" ${manual ? "manual" : "automatic"} run failed: ${result.error ?? "unknown error"}`);
487
503
  }
488
- this.changed();
489
504
  return result;
490
505
  }
491
506
  recordRun(id, run) {
492
507
  const t = this.tasks.get(id);
493
508
  if (!t)
494
509
  return;
495
- t.history = [run, ...sanitizeHistory(t.history)].slice(0, SCHEDULER_HISTORY_MAX);
496
- this.save();
510
+ const next = { ...t, history: [run, ...sanitizeHistory(t.history)].slice(0, SCHEDULER_HISTORY_MAX) };
511
+ this.save(new Map(this.tasks).set(id, next));
497
512
  }
498
513
  }
@@ -278,6 +278,19 @@ export function findEntryByUiId(entries, messageId, seqOf) {
278
278
  }
279
279
  return null;
280
280
  }
281
+ function serializeAssistantMessage(m, id, streaming = false) {
282
+ return {
283
+ id,
284
+ role: "assistant",
285
+ content: serializeAssistantContent(m.content, streaming),
286
+ timestamp: m.timestamp,
287
+ model: m.model,
288
+ provider: m.provider,
289
+ usageCost: typeof m.usage?.cost?.total === "number" ? m.usage.cost.total : undefined,
290
+ stopReason: m.stopReason,
291
+ errorMessage: m.errorMessage,
292
+ };
293
+ }
281
294
  export function serializeMessage(m, seq) {
282
295
  // SDK 的 system 消息是 prompt sections 的内部差量
283
296
  // (content 空串 + sections 结构化内存)、compaction 的
@@ -318,26 +331,41 @@ export function serializeMessage(m, seq) {
318
331
  };
319
332
  }
320
333
  case "assistant":
321
- return {
322
- id,
323
- role: "assistant",
324
- content: serializeAssistantContent(m.content),
325
- timestamp: m.timestamp,
326
- model: m.model,
327
- provider: m.provider,
328
- usageCost: typeof m.usage?.cost?.total === "number" ? m.usage.cost.total : undefined,
329
- stopReason: m.stopReason,
330
- errorMessage: m.errorMessage,
331
- };
334
+ return serializeAssistantMessage(m, id);
332
335
  case "toolResult": {
333
336
  // 工具结果里的图片(web_shot 截图、read 读到的图……)要下发浏览器:
334
337
  // 卡片里直接显示缩略图、点开放大(见 ToolCallBlock)。以前这里统一丢成
335
338
  // "[image result]",用户只能看到占位文本。超限/超数的图仍回落占位文本。
336
339
  const textParts = [];
340
+ let textLength = 0;
341
+ let hasTextPart = false;
342
+ let truncated = false;
343
+ const appendChunk = (chunk) => {
344
+ if (truncated)
345
+ return;
346
+ const remaining = TOOL_OUTPUT_CAP - textLength;
347
+ if (chunk.length > remaining) {
348
+ if (remaining > 0)
349
+ textParts.push(chunk.slice(0, remaining));
350
+ textLength = TOOL_OUTPUT_CAP;
351
+ truncated = true;
352
+ }
353
+ else if (chunk.length > 0) {
354
+ textParts.push(chunk);
355
+ textLength += chunk.length;
356
+ }
357
+ };
358
+ const appendText = (part) => {
359
+ // Empty parts still contribute join separators, even at the cap.
360
+ if (hasTextPart)
361
+ appendChunk("\n");
362
+ hasTextPart = true;
363
+ appendChunk(part);
364
+ };
337
365
  const images = [];
338
366
  for (const c of m.content) {
339
367
  if (c.type === "text") {
340
- textParts.push(c.text);
368
+ appendText(c.text);
341
369
  continue;
342
370
  }
343
371
  if (c.type === "image" && images.length < TOOL_RESULT_IMAGE_MAX) {
@@ -347,10 +375,10 @@ export function serializeMessage(m, seq) {
347
375
  continue;
348
376
  }
349
377
  }
350
- textParts.push("[image result]");
378
+ appendText("[image result]");
351
379
  }
352
- const raw = textParts.join("\n");
353
- const { text, truncated } = truncate(raw, TOOL_OUTPUT_CAP);
380
+ const raw = textParts.join("");
381
+ const text = truncated ? `${raw}\n\n… [truncated]` : raw;
354
382
  const content = raw || images.length === 0 ? [{ type: "text", text, truncated }, ...images] : [...images];
355
383
  const msg = {
356
384
  id,
@@ -467,9 +495,10 @@ export function serializeMessage(m, seq) {
467
495
  * constant for the whole stream.
468
496
  */
469
497
  export function serializeStreamingMessage(m) {
498
+ const id = `stream-${m.timestamp ?? 0}`;
499
+ // Streamed assistant blocks must be converted only once per snapshot.
500
+ if (m.role === "assistant")
501
+ return serializeAssistantMessage(m, id, true);
470
502
  const msg = serializeMessage(m, 0);
471
- if (!msg)
472
- return null;
473
- const content = m.role === "assistant" ? serializeAssistantContent(m.content, true) : msg.content;
474
- return { ...msg, id: `stream-${m.timestamp ?? 0}`, content };
503
+ return msg ? { ...msg, id } : null;
475
504
  }
@@ -68,6 +68,18 @@ export function findBranchCandidates(entries) {
68
68
  if (leaves.length === 0)
69
69
  return [];
70
70
  const candidates = [];
71
+ // Shared ancestors are visited for every leaf. Cache by object (not ID, which
72
+ // may be duplicated), and only for this call so later entry edits stay visible.
73
+ // Path traversal and pathIds output still cost the sum of all branch depths.
74
+ const timestamps = new WeakMap();
75
+ const timestampOf = (entry) => {
76
+ const cached = timestamps.get(entry);
77
+ if (cached !== undefined)
78
+ return cached;
79
+ const timestamp = parseEntryTimestamp(entry.timestamp);
80
+ timestamps.set(entry, timestamp);
81
+ return timestamp;
82
+ };
71
83
  for (const leaf of leaves) {
72
84
  const leafId = leaf.id;
73
85
  const path = [];
@@ -85,13 +97,13 @@ export function findBranchCandidates(entries) {
85
97
  for (const node of path) {
86
98
  if (node.type === "message") {
87
99
  messageCount += 1;
88
- const ts = parseEntryTimestamp(node.timestamp);
100
+ const ts = timestampOf(node);
89
101
  if (ts > lastMessageTimestamp) {
90
102
  lastMessageTimestamp = ts;
91
103
  }
92
104
  }
93
105
  }
94
- const tailTimestamp = parseEntryTimestamp(leaf.timestamp);
106
+ const tailTimestamp = timestampOf(leaf);
95
107
  candidates.push({
96
108
  leafId,
97
109
  leafEntry: leaf,
@@ -129,9 +141,19 @@ function findLowestCommonAncestor(branchA, branchB) {
129
141
  * conversation in message count, selects the main branch leaf.
130
142
  */
131
143
  export function selectBestSessionLeaf(entries, currentLeafId) {
132
- const candidates = findBranchCandidates(entries);
144
+ let candidates = findBranchCandidates(entries);
133
145
  if (candidates.length === 0)
134
146
  return null;
147
+ // An edit/reask explicitly discards the later history in this same file.
148
+ // Honor the latest durable selection, even when abandoned history is longer.
149
+ const reask = [...entries]
150
+ .reverse()
151
+ .find((entry) => entry.type === "custom" && entry.customType === "pi-web-ui:reask");
152
+ if (reask?.id) {
153
+ const selected = candidates.filter((candidate) => candidate.pathIds.includes(reask.id));
154
+ if (selected.length > 0)
155
+ candidates = selected;
156
+ }
135
157
  if (candidates.length === 1) {
136
158
  const single = candidates[0];
137
159
  return {
@@ -8,6 +8,7 @@
8
8
  * 从 agent-service.ts 抽出为独立模块。
9
9
  */
10
10
  import { existsSync } from "node:fs";
11
+ import { sessionLines } from "./session-scan.js";
11
12
  import * as fsPromises from "node:fs/promises";
12
13
  import { basename, join, resolve } from "node:path";
13
14
  import { SessionManager } from "@earendil-works/pi-coding-agent";
@@ -149,13 +150,12 @@ export async function discoverRecentProjectsFromDisk(sessionRoots, limit = 30) {
149
150
  * 以及可选的转录全文 allMessagesText)。仅用于会话列表发现与搜索,避免调用 SDK 重型的全量树解析。
150
151
  *
151
152
  * withAllMessagesText=false(默认,列表路径)时不收集转录全文,allMessagesText 返回空串 ——
152
- * 全文单条可达 MB 级,绝不随列表进任何缓存(issue #440);true(搜索路径)时收集全文并在
153
- * MAX_SEARCH_TEXT_CHARS 处截断。
153
+ * 全文单条可达 MB 级,绝不随列表进任何缓存(issue #440);true 仅兼容旧调用,返回
154
+ * MAX_SEARCH_TEXT_CHARS 内的文本预览。全文搜索请使用 scanSessionForSearch,避免截断漏查。
155
+ * 逐行异步读取,内存仅保留当前 JSONL 记录及列表字段。
154
156
  */
155
157
  export async function parseSessionInfoFast(filePath, fileMtime, withAllMessagesText = false) {
156
158
  try {
157
- const content = await fsPromises.readFile(filePath, "utf8");
158
- const lines = content.split("\n");
159
159
  let id = "";
160
160
  let cwd = "";
161
161
  let name;
@@ -166,7 +166,7 @@ export async function parseSessionInfoFast(filePath, fileMtime, withAllMessagesT
166
166
  let headerTime = 0;
167
167
  const allMessages = withAllMessagesText ? [] : null;
168
168
  let collectedChars = 0;
169
- for (const line of lines) {
169
+ for await (const line of sessionLines(filePath)) {
170
170
  if (!line.trim())
171
171
  continue;
172
172
  // 列表路径(withAllMessagesText=false)已拿到 id 与首条消息后,跳过对大块长行
@@ -229,8 +229,10 @@ export async function parseSessionInfoFast(filePath, fileMtime, withAllMessagesT
229
229
  if (!firstMessage && msg.role === "user")
230
230
  firstMessage = text;
231
231
  if (allMessages && collectedChars < MAX_SEARCH_TEXT_CHARS) {
232
- allMessages.push(text);
233
- collectedChars += text.length + 1;
232
+ const remaining = MAX_SEARCH_TEXT_CHARS - collectedChars;
233
+ const excerpt = text.slice(0, remaining);
234
+ allMessages.push(excerpt);
235
+ collectedChars += excerpt.length + 1;
234
236
  }
235
237
  }
236
238
  }
@@ -293,26 +295,34 @@ export function filterForkedParentSessions(infos, showForkedParents = false) {
293
295
  }
294
296
  if (childrenOf.size === 0)
295
297
  return infos;
298
+ // 从去重后的边构建反向关系;重复 path 可能让同一节点有多个父节点。
299
+ const parentsOf = new Map();
300
+ for (const [parentKey, children] of childrenOf) {
301
+ for (const childKey of children) {
302
+ let parents = parentsOf.get(childKey);
303
+ if (!parents) {
304
+ parents = [];
305
+ parentsOf.set(childKey, parents);
306
+ }
307
+ parents.push(parentKey);
308
+ }
309
+ }
296
310
  const canReachLeaf = new Set();
311
+ const queue = [];
297
312
  for (const key of byKey.keys()) {
298
313
  const children = childrenOf.get(key);
299
314
  if (!children || children.size === 0) {
300
315
  canReachLeaf.add(key);
316
+ queue.push(key);
301
317
  }
302
318
  }
303
- let changed = true;
304
- while (changed) {
305
- changed = false;
306
- for (const [parentKey, children] of childrenOf.entries()) {
319
+ // 每个节点最多入队一次,每条反向边最多访问一次,避免长链反复全图扫描。
320
+ for (let head = 0; head < queue.length; head++) {
321
+ for (const parentKey of parentsOf.get(queue[head]) ?? []) {
307
322
  if (canReachLeaf.has(parentKey))
308
323
  continue;
309
- for (const childKey of children) {
310
- if (canReachLeaf.has(childKey)) {
311
- canReachLeaf.add(parentKey);
312
- changed = true;
313
- break;
314
- }
315
- }
324
+ canReachLeaf.add(parentKey);
325
+ queue.push(parentKey);
316
326
  }
317
327
  }
318
328
  const kept = infos.filter((info) => {
@@ -0,0 +1,130 @@
1
+ /** Shared streaming transcript reader. Memory scales with textual JSONL records,
2
+ * not the file or embedded binary `data` strings. */
3
+ import { createReadStream } from "node:fs";
4
+ import { setImmediate } from "node:timers/promises";
5
+ /** Discard JSON string values of `data` properties (embedded image/base64 payloads)
6
+ * before assembling lines. Preserve the empty string so JSON syntax stays valid.
7
+ * Text/content strings remain intact, including escaped quotes and newlines. */
8
+ class BinaryStringFilter {
9
+ inString = false;
10
+ escaped = false;
11
+ token = "";
12
+ dataKey = false;
13
+ awaitingValue = false;
14
+ discard = false;
15
+ push(chunk) {
16
+ const output = [];
17
+ for (const char of chunk) {
18
+ if (char === "\n") {
19
+ this.inString = false;
20
+ this.escaped = false;
21
+ this.discard = false;
22
+ }
23
+ if (this.inString) {
24
+ if (!this.discard)
25
+ output.push(char);
26
+ if (this.escaped) {
27
+ this.escaped = false;
28
+ if (this.token.length < 16)
29
+ this.token += char;
30
+ }
31
+ else if (char === "\\") {
32
+ this.escaped = true;
33
+ if (this.token.length < 16)
34
+ this.token += char;
35
+ }
36
+ else if (char === '"') {
37
+ this.inString = false;
38
+ if (this.discard)
39
+ output.push(char);
40
+ try {
41
+ this.dataKey = JSON.parse('"' + this.token + '"') === "data";
42
+ }
43
+ catch {
44
+ this.dataKey = false;
45
+ }
46
+ this.discard = false;
47
+ }
48
+ else if (this.token.length < 16)
49
+ this.token += char;
50
+ continue;
51
+ }
52
+ output.push(char);
53
+ if (char === '"') {
54
+ this.inString = true;
55
+ this.token = "";
56
+ this.discard = this.awaitingValue;
57
+ this.awaitingValue = false;
58
+ this.dataKey = false;
59
+ }
60
+ else if (!/\s/.test(char)) {
61
+ this.awaitingValue = char === ":" && this.dataKey;
62
+ this.dataKey = false;
63
+ }
64
+ // JSONL records are independent, including after malformed lines.
65
+ if (char === "\n") {
66
+ this.dataKey = false;
67
+ this.awaitingValue = false;
68
+ }
69
+ }
70
+ return output.join("");
71
+ }
72
+ }
73
+ /** Early return and errors close the file. Non-binary text records are not capped:
74
+ * an exceptionally large single text message still requires one record in memory. */
75
+ export async function* sessionLines(filePath, signal) {
76
+ signal?.throwIfAborted();
77
+ const input = createReadStream(filePath, { encoding: "utf8", highWaterMark: 64 * 1024, signal });
78
+ const filter = new BinaryStringFilter();
79
+ let pending = "";
80
+ let count = 0;
81
+ try {
82
+ for await (const chunk of input) {
83
+ signal?.throwIfAborted();
84
+ const text = filter.push(chunk);
85
+ let start = 0;
86
+ let end;
87
+ while ((end = text.indexOf("\n", start)) !== -1) {
88
+ const line = pending + text.slice(start, end);
89
+ pending = "";
90
+ if (++count % 128 === 0)
91
+ await setImmediate();
92
+ signal?.throwIfAborted();
93
+ yield line.endsWith("\r") ? line.slice(0, -1) : line;
94
+ start = end + 1;
95
+ }
96
+ pending += text.slice(start);
97
+ await setImmediate();
98
+ }
99
+ signal?.throwIfAborted();
100
+ if (pending)
101
+ yield pending;
102
+ signal?.throwIfAborted();
103
+ }
104
+ catch (error) {
105
+ signal?.throwIfAborted();
106
+ throw error;
107
+ }
108
+ finally {
109
+ input.destroy();
110
+ }
111
+ }
112
+ /** Bounded worker pool; results retain input order. No implicit list/result limit. */
113
+ export async function mapSessionsConcurrent(items, visit, concurrency = 4, signal) {
114
+ signal?.throwIfAborted();
115
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 32) {
116
+ throw new RangeError("concurrency must be an integer between 1 and 32");
117
+ }
118
+ const results = new Array(items.length);
119
+ let next = 0;
120
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {
121
+ while (next < items.length) {
122
+ signal?.throwIfAborted();
123
+ const index = next++;
124
+ results[index] = await visit(items[index], index);
125
+ signal?.throwIfAborted();
126
+ }
127
+ }));
128
+ signal?.throwIfAborted();
129
+ return results;
130
+ }