pi-web-ui 0.99.0 → 0.101.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 (109) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/README.md +48 -45
  3. package/README.zh-CN.md +43 -40
  4. package/bin/pi-web-ui.mjs +172 -40
  5. package/dist/server/agent-formatters.js +191 -0
  6. package/dist/server/agent-service-daemon.js +1266 -0
  7. package/dist/server/agent-service.js +9851 -11892
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +130 -184
  10. package/dist/server/ask-user-question-tool.js +94 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/attachments.js +55 -0
  13. package/dist/server/bash-tool.js +83 -0
  14. package/dist/server/bg-servers.js +82 -2
  15. package/dist/server/browser-page-tool.js +207 -0
  16. package/dist/server/claim-files-tool.js +4 -4
  17. package/dist/server/client-id-utils.js +51 -0
  18. package/dist/server/client-state.js +63 -1
  19. package/dist/server/compact-context-tool.js +10 -9
  20. package/dist/server/compaction-markers.js +34 -1
  21. package/dist/server/context-budget-runner.js +43 -0
  22. package/dist/server/conversation-read-tool.js +7 -8
  23. package/dist/server/conversation-touches.js +19 -0
  24. package/dist/server/dangling-tools.js +18 -5
  25. package/dist/server/delegate-mode.js +1 -0
  26. package/dist/server/delegate-task.js +10 -14
  27. package/dist/server/dispatch-domain-handlers.js +631 -0
  28. package/dist/server/dispatch-plugin-handlers.js +300 -0
  29. package/dist/server/dsh/dsh-agent-service.js +125 -13
  30. package/dist/server/edit-soft-tool.js +10 -12
  31. package/dist/server/eval-tool.js +4 -5
  32. package/dist/server/goal-evidence.js +180 -0
  33. package/dist/server/goal-service.js +49 -9
  34. package/dist/server/hashline-engine.js +199 -32
  35. package/dist/server/index.js +212 -944
  36. package/dist/server/left-panel-running.js +115 -0
  37. package/dist/server/load-tools-tool.js +100 -0
  38. package/dist/server/lsp-tool.js +50 -28
  39. package/dist/server/marker-service.js +53 -12
  40. package/dist/server/markers/builtins/action.js +108 -0
  41. package/dist/server/markers/index.js +4 -1
  42. package/dist/server/markers-list-tool.js +34 -0
  43. package/dist/server/market-service.js +277 -0
  44. package/dist/server/mcp-bridge.js +137 -30
  45. package/dist/server/mcp-hot-reload.js +84 -27
  46. package/dist/server/mcp-manager.js +215 -0
  47. package/dist/server/message-entry-resolver.js +32 -0
  48. package/dist/server/orphan-manager.js +44 -0
  49. package/dist/server/patch-remote-catalog.js +28 -10
  50. package/dist/server/patch-tool.js +9 -8
  51. package/dist/server/persona-chain.js +63 -0
  52. package/dist/server/plan-mode.js +9 -6
  53. package/dist/server/plan-update-tool.js +96 -0
  54. package/dist/server/plugin-api-catalog.js +30 -3
  55. package/dist/server/plugin-conversation-view.js +47 -0
  56. package/dist/server/plugin-facilities.js +13 -3
  57. package/dist/server/plugin-ui-slots.js +39 -0
  58. package/dist/server/plugins.js +183 -63
  59. package/dist/server/present-files-tool.js +10 -11
  60. package/dist/server/preset-fields.js +700 -0
  61. package/dist/server/preset-share.js +1179 -0
  62. package/dist/server/process-utils.js +30 -0
  63. package/dist/server/prompt-assembler.js +80 -0
  64. package/dist/server/prompt-composer.js +23 -9
  65. package/dist/server/protocol-version.js +1 -1
  66. package/dist/server/read-tool.js +8 -10
  67. package/dist/server/resolve-global-sdk.js +80 -18
  68. package/dist/server/schedule-agent-tool.js +147 -146
  69. package/dist/server/scm-commitmsg.js +74 -0
  70. package/dist/server/sdk-origin.js +125 -37
  71. package/dist/server/serialize.js +97 -7
  72. package/dist/server/session-branch.js +367 -0
  73. package/dist/server/session-parser.js +235 -0
  74. package/dist/server/session-search.js +158 -0
  75. package/dist/server/settings-service.js +115 -84
  76. package/dist/server/skill-content-filler.js +33 -0
  77. package/dist/server/skill-tool.js +3 -4
  78. package/dist/server/subagent-handoff.js +18 -0
  79. package/dist/server/subagent-helpers.js +88 -0
  80. package/dist/server/subagents.js +15 -22
  81. package/dist/server/terminals.js +171 -91
  82. package/dist/server/tool-approval.js +3 -1
  83. package/dist/server/tool-guards.js +527 -0
  84. package/dist/server/tool-host-factories.js +217 -0
  85. package/dist/server/tool-manager.js +84 -23
  86. package/dist/server/tool-prompt-overrides.js +158 -0
  87. package/dist/server/tool-prompts.js +42 -0
  88. package/dist/server/tool-signature.js +104 -0
  89. package/dist/server/wait-subscription-scan.js +46 -1
  90. package/dist/server/workspace-snapshot.js +60 -11
  91. package/extensions/webui.ts +90 -24
  92. package/package.json +5 -3
  93. package/plugin-sdk/README.md +25 -4
  94. package/plugin-sdk/import-check.mjs +210 -0
  95. package/plugin-sdk/index.d.ts +21 -1
  96. package/plugin-sdk/index.mjs +6 -0
  97. package/plugins/catalog.json +53 -2
  98. package/themes/aetheris.css +3 -1
  99. package/themes/translucent.css +8 -1
  100. package/themes/transparent.css +9 -1
  101. package/themes/zhupi-dark.css +1 -1
  102. package/themes/zhupi.css +1 -1
  103. package/web/dist/assets/{TerminalPanel-NerrJlTS.js → TerminalPanel-DD7I5_aC.js} +2 -2
  104. package/web/dist/assets/index-CpjA1YdT.css +1 -0
  105. package/web/dist/assets/index-nKn87VuM.js +678 -0
  106. package/web/dist/index.html +2 -2
  107. package/web/dist/sw.js +1 -1
  108. package/web/dist/assets/index-BdMaGCcs.css +0 -1
  109. package/web/dist/assets/index-ByCBN4Kt.js +0 -368
@@ -33,7 +33,7 @@ import { WebSocket, WebSocketServer } from "ws";
33
33
  import { VERSION, getAgentDir } from "@earendil-works/pi-coding-agent";
34
34
  import { sdkCopies, sdkOriginNote } from "./sdk-origin.js";
35
35
  import { PROTOCOL_VERSION } from "./protocol-version.js";
36
- import { AgentService, workspacePath, QuiesceRejectedError } from "./agent-service.js";
36
+ import { AgentService, workspacePath, QuiesceRejectedError, ClientSession } from "./agent-service.js";
37
37
  import { WS_MAX_PAYLOAD_BYTES, isAbsoluteWirePath, wireToAbs } from "./files-service.js";
38
38
  import { httpHostAllowed } from "./host-guard.js";
39
39
  import { registerFileTransferRoutes } from "./file-transfer-routes.js";
@@ -60,6 +60,8 @@ import { SchedulerStore, SchedulerValidationError } from "./scheduler-tasks.js";
60
60
  import { initHttpProxy } from "./http-proxy.js";
61
61
  import { globalLspPool } from "./lsp-tool.js";
62
62
  import { buildPiWebTokenCookie, decodeCookieToken, isTlsRequest } from "./auth-cookie.js";
63
+ import { handleFileMessage, handleScmMessage, handleBgServerMessage, handlePresetAndDshMessage, handleModelAndProviderMessage, handleTerminalMessage, handleSessionLifecycleMessage, handlePlanAndGoalMessage, handleScheduleMessage, handleSettingsMessage, handleInteractiveResponseMessage, } from "./dispatch-domain-handlers.js";
64
+ import { handlePluginMessage } from "./dispatch-plugin-handlers.js";
63
65
  /** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
64
66
  * `npm_lifecycle_*` into every child). Anything this server spawns — shells,
65
67
  * `pi update` — would otherwise inherit `npm_config_allow_scripts`, which npm
@@ -1343,13 +1345,19 @@ function pushNoticeToAll(level, text, textEn) {
1343
1345
  }
1344
1346
  }
1345
1347
  }
1346
- // MCP 工具桥:读取 <dataDir>/mcp.json 启动外部 MCP 服务器(stdio),把它们的
1348
+ // MCP 工具桥:读取配置启动外部 MCP 服务器(stdio),把它们的
1347
1349
  // 工具并入与插件工具相同的 customTools 管线;单服务器失败不炸进程。
1348
- const mcpBridge = new McpBridge(DATA_DIR, (...a) => console.log("[mcp]", ...a));
1350
+ const mcpBridge = new McpBridge(DATA_DIR, (...a) => console.log("[mcp]", ...a), {
1351
+ agentDir: getAgentDir(),
1352
+ cwd: CWD,
1353
+ });
1354
+ ClientSession.mcpBridge = mcpBridge;
1349
1355
  // mcp.json 热加载:保存文件即生效,改完不必再重启服务。两半都在这里收口 —— reload 换入
1350
1356
  // 新的服务器集合(只重启规格真变了的),applyPluginAgentTools 把新工具推给已有会话。
1351
1357
  const mcpHotReload = createMcpHotReload({
1352
1358
  dataDir: DATA_DIR,
1359
+ agentDir: getAgentDir(),
1360
+ cwd: CWD,
1353
1361
  reload: () => mcpBridge.reload(),
1354
1362
  onToolsChanged: () => service.applyPluginAgentTools(),
1355
1363
  onNotice: (level, text, textEn) => pushNoticeToAll(level, text, textEn),
@@ -1373,8 +1381,10 @@ service.onRunEvent = (ev) => pluginMgr.emitRunEvent(ev);
1373
1381
  // 插件扩展点:对话切换通知(轨迹视图切会话后即重拉;dsh 引擎暂无)。
1374
1382
  service.onConversationChanged = () => pluginMgr.emitConversationChanged();
1375
1383
  // 插件扩展点:当前打开对话的快照(轨迹视图直接显示打开对话的时间线;
1376
- // dsh 引擎无此方法时回退 null,插件显示空态)。
1377
- pluginMgr.conversationProvider = () => service.readConversationForPlugins?.() ?? null;
1384
+ // dsh 引擎无此方法时回退 null,插件显示空态)。#542:透传 {clientId} 选本标签页的对话。
1385
+ pluginMgr.conversationProvider = (opts) => service.readConversationForPlugins?.(opts) ?? null;
1386
+ // 插件扩展点:模型切换成功事件(#542;dsh 引擎无此钩子 = 不发事件)。
1387
+ service.onClientModelChanged = (snap) => pluginMgr.emitClientModelChanged(snap);
1378
1388
  // 插件扩展点:无头调用 agent(微信通道等经 host.chat 投递外部消息,无浏览器也能跑)。
1379
1389
  pluginMgr.chatProvider = (pluginId, req) => service.chatFromPlugin?.(pluginId, req) ?? Promise.reject(new Error("当前引擎不支持无头调用(仅标准 pi 引擎)"));
1380
1390
  // 插件扩展点:插件注册的 AI 工具(registerAgentTool)+ MCP 桥工具 → 会话创建时
@@ -1391,7 +1401,7 @@ service.pluginCommandsProvider = () => pluginMgr.listCommands();
1391
1401
  pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
1392
1402
  service.pluginBgTasksProvider = () => pluginMgr.bgTasks();
1393
1403
  service.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
1394
- // 定时任务 Agent 工具的数据源(schedule_task/list/cancel):标准 pi 引擎的
1404
+ // 定时任务 Agent 工具的数据源(schedule 单 action:create/list/cancel):标准 pi 引擎的
1395
1405
  // AgentService 才有 schedulerStore 字段,DSH service 没有 —— 有才设。
1396
1406
  if ("schedulerStore" in service) {
1397
1407
  service.schedulerStore = scheduler;
@@ -1631,13 +1641,15 @@ wss.on("connection", (ws) => {
1631
1641
  if ((msg.type === "snapshot" || msg.type === "snapshot_delta") &&
1632
1642
  lastSnapshotBytes > 0 &&
1633
1643
  ws.bufferedAmount > Math.max(SNAPSHOT_BACKPRESSURE_MIN_BYTES, SNAPSHOT_BACKPRESSURE_FACTOR * lastSnapshotBytes)) {
1644
+ const wasFull = msg.type === "snapshot";
1634
1645
  // 真正的慢客户端:丢弃是安全的,但不能「丢完就没了」——安排一次延迟
1635
1646
  // 重发,等缓冲排空后快照最终必达(否则若此后再无事件,客户端将永久
1636
- // 停留在旧快照)。重发仍走 flushSnapshot:缓冲未排空则再次顺延。
1647
+ // 停留在旧快照)。重发仍走 flushSnapshot:缓冲未排空则再次顺延;
1648
+ // 若被丢弃的是全量快照(snapshot),重发必须强制 forceFull 保证客户端能拿到完整基线。
1637
1649
  if (!snapshotRetryTimer) {
1638
1650
  snapshotRetryTimer = setTimeout(() => {
1639
1651
  snapshotRetryTimer = null;
1640
- service.get(clientId ?? "")?.flushSnapshot();
1652
+ service.get(clientId ?? "")?.flushSnapshot(wasFull);
1641
1653
  }, SNAPSHOT_RETRY_MS);
1642
1654
  }
1643
1655
  return;
@@ -1687,817 +1699,125 @@ wss.on("connection", (ws) => {
1687
1699
  send({ type: "notice", level: "error", text: refusal });
1688
1700
  return;
1689
1701
  }
1690
- switch (msg.type) {
1691
- case "prompt": {
1692
- const hasAttach = Boolean(msg.attachments && msg.attachments.length > 0);
1693
- if (!msg.text?.trim() && !hasAttach) {
1694
- send({
1695
- type: "notice",
1696
- level: "warning",
1697
- text: "发送已忽略:提示词为空且未附带文件或上下文引用。",
1698
- textEn: "Prompt ignored: text is empty and no attachments were provided.",
1699
- });
1702
+ try {
1703
+ if (handleFileMessage(msg, cs))
1704
+ return;
1705
+ if (handleScmMessage(msg, cs, send))
1706
+ return;
1707
+ if (handleBgServerMessage(msg, cs))
1708
+ return;
1709
+ if (handlePresetAndDshMessage(msg, cs))
1710
+ return;
1711
+ if (handleModelAndProviderMessage(msg, cs))
1712
+ return;
1713
+ if (handleTerminalMessage(msg, cs))
1714
+ return;
1715
+ if (handleSessionLifecycleMessage(msg, cs))
1716
+ return;
1717
+ if (handlePlanAndGoalMessage(msg, cs))
1718
+ return;
1719
+ if (handleScheduleMessage(msg, scheduler, send))
1720
+ return;
1721
+ if (handleSettingsMessage(msg, cs))
1722
+ return;
1723
+ if (handleInteractiveResponseMessage(msg, cs, service, clientId, send))
1724
+ return;
1725
+ if (handlePluginMessage(msg, {
1726
+ pluginMgr,
1727
+ pluginInstaller,
1728
+ cs,
1729
+ clientId,
1730
+ send,
1731
+ dataDir: DATA_DIR,
1732
+ cwd: CWD,
1733
+ clients: wss.clients,
1734
+ pendingPathRequests,
1735
+ pendingPermissionRequests,
1736
+ pendingDomConsents,
1737
+ findDomConsentById,
1738
+ applyDomConsent,
1739
+ pushPluginGrants,
1740
+ pushPluginPermissions,
1741
+ reloadPluginsAndPush,
1742
+ confirmPluginInstallHelper,
1743
+ }))
1744
+ return;
1745
+ switch (msg.type) {
1746
+ case "prompt": {
1747
+ const hasAttach = Boolean(msg.attachments && msg.attachments.length > 0);
1748
+ if (!msg.text?.trim() && !hasAttach) {
1749
+ send({
1750
+ type: "notice",
1751
+ level: "warning",
1752
+ text: "发送已忽略:提示词为空且未附带文件或上下文引用。",
1753
+ textEn: "Prompt ignored: text is empty and no attachments were provided.",
1754
+ });
1755
+ break;
1756
+ }
1757
+ void cs.prompt(msg.text, msg.attachments, msg.queue);
1700
1758
  break;
1701
1759
  }
1702
- void cs.prompt(msg.text, msg.attachments, msg.queue);
1703
- break;
1704
- }
1705
- case "queue_remove":
1706
- // #491:removeQueued 是 async——dispatch 是 fire-and-forget,缺 void 时
1707
- // 内部抛错即 unhandledRejection,而全仓没有兜底 handler,Node ≥15 直接崩进程。
1708
- void cs.removeQueued(msg.kind, msg.text, msg.index);
1709
- break;
1710
- case "draft_update":
1711
- cs.saveDraft?.(msg.sessionId, msg.text, msg.ts);
1712
- break;
1713
- case "abort":
1714
- void cs.abort();
1715
- break;
1716
- case "abort_bash":
1717
- void cs.abortBash();
1718
- break;
1719
- case "retry_last":
1720
- void cs.retryLast();
1721
- break;
1722
- case "kill_background_server":
1723
- void cs.killBackgroundServer(msg.port, msg.taskId);
1724
- break;
1725
- case "kill_background_servers":
1726
- void cs.killAllBackgroundServers();
1727
- break;
1728
- case "list_bg_servers":
1729
- void cs.listBgServers();
1730
- break;
1731
- case "new_chat":
1732
- void cs.newChat(msg.preset, msg.ephemeral);
1733
- break;
1734
- case "edit_message":
1735
- void cs.editMessage(msg.messageId, msg.text, msg.attachments);
1736
- break;
1737
- case "fork_session":
1738
- void cs.forkSession?.(msg.messageId, msg.position, msg.conversationId);
1739
- break;
1740
- case "rollback_session":
1741
- void cs.rollbackSession?.(msg.messageId, msg.conversationId, msg.restoreWorkspace);
1742
- break;
1743
- case "get_state":
1744
- // Always a FULL snapshot: the client is (re)connecting or detected
1745
- // a rev/seq gap — it needs an authoritative state to rebuild from.
1746
- cs.flushSnapshot(true);
1747
- break;
1748
- case "get_commands":
1749
- void cs.pushSlashCommands();
1750
- break;
1751
- case "get_tool_info":
1752
- // 工具卡右键菜单的「显示工具详细信息」:按需取一次工具定义(不进快照)。
1753
- // 引擎没实现(或旧版服务端)时回一条 unsupported,前端据此显示「不支持」
1754
- // 而不是永远转圈。
1755
- if (typeof cs.getToolInfo === "function") {
1756
- void cs.getToolInfo(msg.name);
1757
- }
1758
- else {
1759
- send({ type: "tool_info", name: msg.name, found: false, unsupported: true });
1760
- }
1761
- break;
1762
- case "get_compacted_messages":
1763
- void cs.getCompactedMessages?.(msg.compactionMessageId, msg.conversationId);
1764
- break;
1765
- case "list_sessions":
1766
- void cs.refreshSessions();
1767
- break;
1768
- case "list_projects":
1769
- void cs.pushProjects();
1770
- break;
1771
- case "remove_project":
1772
- void cs.removeProject(msg.path);
1773
- break;
1774
- case "delete_session":
1775
- void cs.deleteSession(msg.path);
1776
- break;
1777
- case "rename_session":
1778
- void cs.renameSession(msg.path, msg.name);
1779
- break;
1780
- case "rename_conversation":
1781
- void cs.renameConversation(msg.id, msg.name);
1782
- break;
1783
- case "dismiss_conversation":
1784
- void cs.dismissConversation(msg.id, msg.withFinishedSubagents, msg.force);
1785
- break;
1786
- case "persist_conversation":
1787
- if (typeof cs.persistConversation === "function") {
1788
- void cs.persistConversation(msg.id);
1789
- }
1790
- break;
1791
- case "pin_conversation":
1792
- if (typeof cs.setConversationPinned === "function") {
1793
- void cs.setConversationPinned(msg.id, msg.pinned);
1794
- }
1795
- break;
1796
- case "pin_session":
1797
- if (typeof cs.pinSession === "function") {
1798
- void cs.pinSession(msg.path, msg.pinned);
1799
- }
1800
- break;
1801
- case "dismiss_finished_subagents":
1802
- void cs.dismissFinishedSubagents(msg.parentId);
1803
- break;
1804
- case "switch_session":
1805
- void cs.switchSession(msg.path);
1806
- break;
1807
- case "switch_conversation":
1808
- void cs.switchConversation(msg.id);
1809
- break;
1810
- case "take_over_conversation":
1811
- if (typeof service.takeOverConversation === "function") {
1812
- void service.takeOverConversation(clientId, msg.owner, msg.id);
1813
- }
1814
- else {
1815
- send({
1816
- type: "notice",
1817
- level: "error",
1818
- text: "当前引擎不支持过户(take over),请用 pi 引擎",
1819
- textEn: "Takeover is not supported by the current engine; use the pi engine.",
1820
- });
1821
- }
1822
- break;
1823
- case "peek_elsewhere_question":
1824
- if (typeof service.peekElsewhereQuestion === "function") {
1825
- void service.peekElsewhereQuestion(clientId, msg.owner, msg.id);
1826
- }
1827
- else {
1828
- send({
1829
- type: "notice",
1830
- level: "error",
1831
- text: "当前引擎不支持跨页作答,请用 pi 引擎",
1832
- textEn: "Cross-page answering is not supported by the current engine; use the pi engine.",
1833
- });
1834
- }
1835
- break;
1836
- case "list_files":
1837
- void cs.listFiles(msg.path);
1838
- break;
1839
- case "search_files":
1840
- void cs.searchFiles(msg.query, msg.reqId);
1841
- break;
1842
- case "search_sessions":
1843
- void cs.searchSessions(msg.query, msg.reqId);
1844
- break;
1845
- case "scm_status":
1846
- void cs.scmQuery("status", msg.reqId);
1847
- break;
1848
- case "scm_history":
1849
- void cs.scmQuery("history", msg.reqId);
1850
- break;
1851
- case "scm_filediff":
1852
- void cs.scmQuery("filediff", msg.reqId, { path: msg.path });
1853
- break;
1854
- case "scm_commit":
1855
- void cs.scmQuery("commit", msg.reqId, { hash: msg.hash });
1856
- break;
1857
- case "scm_commitmsg":
1858
- if (typeof cs.scmGenCommitMessage === "function") {
1859
- void cs.scmGenCommitMessage(msg.reqId);
1860
- }
1861
- else {
1862
- // DSH 等引擎没有 pi 的 ModelRuntime——照样应答一次(ok:false),
1863
- // 前端按钮不能因引擎差异卡在转圈。
1864
- send({
1865
- type: "scm_data",
1866
- reqId: msg.reqId,
1867
- kind: "commitmsg",
1868
- ok: false,
1869
- error: "当前引擎不支持 AI 生成提交信息(请用 pi 引擎)/ AI commit messages need the pi engine",
1870
- });
1871
- }
1872
- break;
1873
- case "read_file":
1874
- void cs.readFile(msg.path);
1875
- break;
1876
- case "write_file":
1877
- void cs.writeFile(msg.path, msg.text);
1878
- break;
1879
- case "upload_file":
1880
- void cs.uploadFile(msg.dirPath, msg.name, msg.data);
1881
- break;
1882
- case "file_create":
1883
- void cs.createEntry(msg.dir, msg.name, msg.kind);
1884
- break;
1885
- case "file_rename":
1886
- void cs.renameEntry(msg.path, msg.newName);
1887
- break;
1888
- case "file_delete":
1889
- void cs.deleteEntry(msg.path);
1890
- break;
1891
- case "file_copy":
1892
- void cs.copyEntry(msg.src, msg.destDir, msg.move);
1893
- break;
1894
- case "file_reveal":
1895
- void cs.revealEntry(msg.path);
1896
- break;
1897
- case "file_open_default":
1898
- void cs.openDefaultEntry(msg.path);
1899
- break;
1900
- case "list_models":
1901
- void cs.listModels();
1902
- break;
1903
- case "set_model":
1904
- void cs.setModel(msg.modelId);
1905
- break;
1906
- case "set_default_model":
1907
- void cs.setDefaultModel?.(msg.modelId);
1908
- break;
1909
- case "clear_default_model":
1910
- cs.clearDefaultModel?.();
1911
- break;
1912
- case "set_thinking":
1913
- cs.setThinking(msg.level);
1914
- break;
1915
- case "set_cwd":
1916
- void cs.setCwd(msg.path);
1917
- break;
1918
- case "set_workspace_roots":
1919
- // 宿主侧多根(issue #146):只改「哪些路径算工作区内」与右栏文件树的根,
1920
- // 不动 cwd(AI 仍只在主 cwd 里干活)。
1921
- void cs.setWorkspaceRoots(msg.roots);
1922
- break;
1923
- case "set_locale":
1924
- // UI language report — per-client persist + lang-aware prompt
1925
- // refresh (streaming-safe). Engine-agnostic via DispatchSession.
1926
- void service.setLocale(clientId, msg.locale);
1927
- break;
1928
- case "complete_path":
1929
- void cs.completePath(msg.path);
1930
- break;
1931
- case "make_dir":
1932
- void cs.makeDir(msg.path, msg.setAsCwd === true);
1933
- break;
1934
- case "check_update":
1935
- void cs.checkUpdate();
1936
- break;
1937
- case "check_updates_all":
1938
- void cs.checkUpdatesAll(msg.force === true);
1939
- break;
1940
- case "check_plugin_updates":
1941
- if (typeof cs.checkPluginUpdates === "function") {
1942
- void cs.checkPluginUpdates(true);
1943
- }
1944
- break;
1945
- case "restart_service": {
1946
- // Same effect as `pi-web-ui server restart`: this process exits and its
1947
- // supervisor brings it back (launchd/systemd immediately, the Windows
1948
- // watchdog within ~10s). Refused without a supervisor — exiting there
1949
- // would just stop the server the user is looking at.
1950
- if (!ORIGIN.supervisor) {
1951
- send({
1952
- type: "notice",
1953
- level: "error",
1954
- text: "当前实例不是由 pi-web-ui 服务启动的(前台运行),无法自动重启;请在终端里重启,或先用 pi-web-ui server install 安装服务。",
1955
- textEn: "This instance runs in the foreground, not as a pi-web-ui service — nothing would bring it back. Restart it in its terminal, or install the service with `pi-web-ui server install`.",
1956
- });
1760
+ case "queue_remove":
1761
+ // #491:removeQueued 是 async——dispatch 是 fire-and-forget,缺 void 时
1762
+ // 内部抛错即 unhandledRejection,而全仓没有兜底 handler,Node ≥15 直接崩进程。
1763
+ void cs.removeQueued(msg.kind, msg.text, msg.index);
1957
1764
  break;
1958
- }
1959
- send({
1960
- type: "notice",
1961
- level: "info",
1962
- text: "正在重启服务…页面会在服务恢复后自动重连,进行中的对话会自动恢复并继续。",
1963
- textEn: "Restarting the service… this page reconnects once it is back; running conversations resume automatically.",
1964
- });
1965
- // Record streaming runs BEFORE exiting: under systemd this path
1966
- // exits via process.exit without shutdown(), so without this the
1967
- // post-restart resume would find nothing to continue.
1968
- try {
1969
- service.recordInterruptedRuns();
1970
- }
1971
- catch {
1972
- /* best effort — never block the restart on bookkeeping */
1973
- }
1974
- // Let the notice (and this socket's backlog) flush before we go down.
1975
- setTimeout(() => void scheduleQuit(), 400);
1976
- break;
1977
- }
1978
- case "dialog_response":
1979
- cs.resolveDialog(msg.id, msg.value);
1980
- break;
1981
- case "install_pi_agent":
1982
- void cs.installPiAgent();
1983
- break;
1984
- case "set_provider_api_key":
1985
- void cs.setProviderApiKey(msg.provider, msg.apiKey);
1986
- break;
1987
- case "clear_provider_api_key":
1988
- void cs.clearProviderApiKey(msg.provider);
1989
- break;
1990
- case "provider_oauth_start":
1991
- cs.startProviderOAuth(msg.provider);
1992
- break;
1993
- case "provider_oauth_reply":
1994
- cs.replyProviderOAuth(msg.flowId, msg.promptId, msg.value);
1995
- break;
1996
- case "provider_oauth_cancel":
1997
- cs.cancelProviderOAuth(msg.flowId);
1998
- break;
1999
- case "list_provider_oauth_flows":
2000
- cs.listProviderOAuthFlows();
2001
- break;
2002
- case "provider_oauth_logout":
2003
- void cs.logoutProviderOAuth(msg.provider);
2004
- break;
2005
- case "list_models_config":
2006
- void cs.listModelsConfig();
2007
- break;
2008
- case "reload_models_config":
2009
- void cs.reloadModelsConfig();
2010
- break;
2011
- case "save_model_config":
2012
- void cs.saveModelConfig(msg.providerId, msg.config);
2013
- break;
2014
- case "delete_model_config":
2015
- void cs.deleteModelConfig(msg.providerId);
2016
- break;
2017
- case "list_providers":
2018
- void cs.listProviders();
2019
- break;
2020
- case "fetch_models":
2021
- void cs.fetchModelsList(msg.reqId, msg.baseUrl, msg.apiKey, msg.authHeader, msg.api, msg.providerId);
2022
- break;
2023
- case "test_model_connection":
2024
- void cs.testModelConnection?.(msg.reqId, msg.baseUrl, msg.apiKey, msg.authHeader, msg.api, msg.providerId);
2025
- break;
2026
- case "refresh_provider_models":
2027
- void cs.refreshProviderModels(msg.providerId, msg.reqId);
2028
- break;
2029
- case "refresh_builtin_models":
2030
- void cs.refreshBuiltinModels(msg.reqId);
2031
- break;
2032
- case "append_builtin_model":
2033
- void cs.appendBuiltinModel(msg.providerId, msg.model, msg.reqId);
2034
- break;
2035
- case "clone_provider":
2036
- void cs.cloneProvider(msg.provider, msg.reqId);
2037
- break;
2038
- case "enrich_models":
2039
- void cs.enrichModels(msg.reqId, msg.ids, msg.hints);
2040
- break;
2041
- case "abort_enrich_models":
2042
- cs.abortEnrichModels(msg.reqId);
2043
- break;
2044
- case "list_provider_keys":
2045
- cs.listProviderKeys();
2046
- break;
2047
- case "add_provider_key":
2048
- void cs.addProviderKey(msg.provider, msg.apiKey, msg.name);
2049
- break;
2050
- case "activate_provider_key":
2051
- void cs.activateProviderKey(msg.provider, msg.keyName);
2052
- break;
2053
- case "remove_provider_key":
2054
- void cs.removeProviderKey(msg.provider, msg.keyName);
2055
- break;
2056
- case "terminal_create": {
2057
- const tm = cs.getTerminalManager(msg.conversationId);
2058
- if (tm) {
2059
- // agentBash 透传:前端重建已退出的 AI 终端时保留其身份(issue #147);
2060
- // 字段缺省(旧前端)时 create() 再从 history 继承。
2061
- const createOpts = msg.locale !== undefined || msg.agentBash !== undefined
2062
- ? { locale: msg.locale, agentBash: msg.agentBash }
2063
- : undefined;
2064
- tm.create(msg.terminalId, msg.cwd, msg.cols, msg.rows, cs.getTerminalCwd(msg.conversationId), msg.title, createOpts);
2065
- }
2066
- break;
2067
- }
2068
- case "terminal_input":
2069
- cs.getTerminalManager(msg.conversationId)?.input(msg.terminalId, msg.data);
2070
- break;
2071
- case "terminal_resize":
2072
- cs.getTerminalManager(msg.conversationId)?.resize(msg.terminalId, msg.cols, msg.rows);
2073
- break;
2074
- case "terminal_kill":
2075
- cs.getTerminalManager(msg.conversationId)?.kill(msg.terminalId);
2076
- break;
2077
- case "rename_terminal":
2078
- cs.getTerminalManager(msg.conversationId)?.rename(msg.terminalId, msg.title);
2079
- break;
2080
- case "run_command":
2081
- cs.getTerminalManager(msg.conversationId)?.runCommand(msg.terminalId, msg.command, msg.cols, msg.rows, cs.getTerminalCwd(msg.conversationId));
2082
- break;
2083
- case "list_commands":
2084
- void cs.listCommands();
2085
- break;
2086
- case "save_commands":
2087
- void cs.saveCommands(msg.commands);
2088
- break;
2089
- case "set_goal":
2090
- void cs.setGoal(msg.goal, {
2091
- reviewModel: msg.reviewModel,
2092
- maxRounds: msg.maxRounds,
2093
- locked: msg.locked,
2094
- execModel: msg.execModel,
2095
- });
2096
- break;
2097
- case "clear_goal":
2098
- void cs.clearGoal();
2099
- break;
2100
- case "start_goal_wizard":
2101
- void cs.startGoalWizard(msg.text, {
2102
- wizardModel: msg.wizardModel,
2103
- maxRounds: msg.maxRounds,
2104
- locked: msg.locked,
2105
- });
2106
- break;
2107
- case "set_goal_prefs":
2108
- void cs.setGoalPrefs({
2109
- reviewModel: msg.reviewModel,
2110
- maxRounds: msg.maxRounds,
2111
- locked: msg.locked,
2112
- execModel: msg.execModel,
2113
- });
2114
- break;
2115
- case "get_settings":
2116
- cs.pushSettings();
2117
- break;
2118
- case "set_settings":
2119
- // SAFETY: Both dispatch engines validate the explicitly enumerated settings fields below.
2120
- void cs.setSettings({
2121
- promptMode: msg.promptMode,
2122
- customSystemPrompt: msg.customSystemPrompt,
2123
- promptTemplate: msg.promptTemplate,
2124
- promptOverrides: msg.promptOverrides,
2125
- disabledSkills: msg.disabledSkills,
2126
- disabledExtensions: msg.disabledExtensions,
2127
- disabledAgentTools: msg.disabledAgentTools,
2128
- disabledPluginTools: msg.disabledPluginTools,
2129
- disabledPlugins: msg.disabledPlugins,
2130
- terminalToolsEnabled: msg.terminalToolsEnabled,
2131
- terminalBash: msg.terminalBash,
2132
- terminalBashIdleMs: msg.terminalBashIdleMs,
2133
- terminalBashMaxForegroundMs: msg.terminalBashMaxForegroundMs,
2134
- toolWatchdogTimeoutMs: msg.toolWatchdogTimeoutMs,
2135
- readDirEnabled: msg.readDirEnabled,
2136
- toolApprovalEnabled: msg.toolApprovalEnabled,
2137
- editSoftEnabled: msg.editSoftEnabled,
2138
- questionnaireEnabled: msg.questionnaireEnabled,
2139
- parallelReminderEnabled: msg.parallelReminderEnabled,
2140
- goalModeEnabled: msg.goalModeEnabled,
2141
- thinkingWrap: msg.thinkingWrap,
2142
- toolsWrap: msg.toolsWrap,
2143
- toolImagesEnabled: msg.toolImagesEnabled,
2144
- devNoCache: msg.devNoCache,
2145
- autoReload: msg.autoReload,
2146
- skillsFullText: msg.skillsFullText,
2147
- visionBridgeEnabled: msg.visionBridgeEnabled,
2148
- visionBridgeModel: msg.visionBridgeModel,
2149
- visionBridgePromptMode: msg.visionBridgePromptMode,
2150
- visionBridgePrompt: msg.visionBridgePrompt,
2151
- subagentDefaultModel: msg.subagentDefaultModel,
2152
- retryMaxAttempts: msg.retryMaxAttempts,
2153
- softCapTokens: msg.softCapTokens,
2154
- softCapByModel: msg.softCapByModel,
2155
- reviewPrompt: msg.reviewPrompt,
2156
- reviewDisabledSkills: msg.reviewDisabledSkills,
2157
- markersEnabled: msg.markersEnabled,
2158
- disabledMarkers: msg.disabledMarkers,
2159
- quickPhrases: msg.quickPhrases,
2160
- quickPhrasesEnabled: msg.quickPhrasesEnabled,
2161
- quickPhrasesSeeded: msg.quickPhrasesSeeded,
2162
- uiLayout: msg.uiLayout,
2163
- });
2164
- break;
2165
- case "extensions_reload":
2166
- void cs.reloadExtensions();
2167
- break;
2168
- case "plugin_message":
2169
- pluginMgr.handleMessage(msg.pluginId, msg.payload, clientId ?? undefined);
2170
- break;
2171
- case "plugin_settings": {
2172
- const r = pluginMgr.savePluginSettings(msg.pluginId, msg.values ?? {}, () => cs?.getLang() ?? "en");
2173
- if (r.error) {
2174
- cs?.emitNotice("error", `插件设置保存失败:${r.error}`, `Failed to save plugin settings: ${r.error}`);
2175
- }
2176
- else {
2177
- cs?.emitNotice("info", "插件设置已保存", "Plugin settings saved");
2178
- }
2179
- break;
2180
- }
2181
- case "plugins_reload":
2182
- void pluginMgr.reload(() => cs?.getLang() ?? "en").then(() => pluginMgr.pushToAll());
2183
- break;
2184
- case "plugin_catalog_add": {
2185
- const r = pluginMgr.addCatalogEntry(msg.entry ?? {}, () => cs?.getLang() ?? "en");
2186
- if (r.error) {
2187
- cs?.emitNotice("error", `添加到插件列表失败:${r.error}`, `Failed to add to plugin list: ${r.error}`);
2188
- }
2189
- else {
2190
- cs?.emitNotice("info", "已添加到插件列表", "Added to the plugin list");
2191
- }
2192
- break;
2193
- }
2194
- case "plugin_catalog_remove": {
2195
- const r = pluginMgr.removeCatalogEntry(msg.id, () => cs?.getLang() ?? "en");
2196
- if (r.error) {
2197
- cs?.emitNotice("error", `从插件列表移除失败:${r.error}`, `Failed to remove from plugin list: ${r.error}`);
2198
- }
2199
- else {
2200
- cs?.emitNotice("info", "已从插件列表移除", "Removed from the plugin list");
2201
- }
2202
- break;
2203
- }
2204
- // -- 插件后台作业(安装/更新/卸载,issue #152)----------------------------
2205
- // 不再是「开一个可见终端 tab 并关掉设置面板」:作业在服务端后台跑,输出按行
2206
- // 回给发起者,设置面板原就位显示。真正的执行者是 CLI(单一实现)。
2207
- case "plugin_job": {
2208
- const jobLang = () => cs?.getLang() ?? "en";
2209
- const jobId = String(msg.jobId ?? "");
2210
- const pluginId = String(msg.id ?? "");
2211
- // function 声明会提升、TS 对 msg 判别联合的收窄进不了闭包 —— 先拍平成常量。
2212
- const jobAction = msg.action;
2213
- const jobSpec = {
2214
- jobId,
2215
- action: jobAction,
2216
- id: pluginId,
2217
- source: msg.source,
2218
- build: msg.build === true,
2219
- noBuild: msg.noBuild === true,
2220
- };
2221
- const jobDone = (ok, error) => {
2222
- send({
2223
- type: "plugin_job",
2224
- jobId,
2225
- action: jobAction,
2226
- pluginId,
2227
- phase: "done",
2228
- ok,
2229
- ...(error ? { error } : {}),
2230
- output: "",
2231
- });
2232
- };
2233
- // 参数静态校验:参数非法直接拒绝,避免向客户端发起无意义/恶意的确认弹窗。
2234
- const argCheck = buildPluginJobArgs(jobSpec, DATA_DIR, jobLang);
2235
- if ("error" in argCheck) {
2236
- jobDone(false, argCheck.error);
1765
+ case "draft_update":
1766
+ cs.saveDraft?.(msg.sessionId, msg.text, msg.ts);
2237
1767
  break;
2238
- }
2239
- // 安装确认门(P0):install/update 先经用户确认。第三方页面脚本可以直发
2240
- // plugin_job;拒绝/超时直接回一条 done,让面板上的作业就地结束(不占
2241
- // 安装锁、不弹「失败」之外的噪音)。卸载不在本门范围内(由面板本身发起)。
2242
- if (jobAction === "install" || jobAction === "update") {
2243
- const alreadyGranted = pluginMgr.permGrants.has("plugin-installer", "net", { host: "github.com" });
2244
- if (!alreadyGranted) {
2245
- send({
2246
- type: "plugin_job",
2247
- jobId,
2248
- action: jobAction,
2249
- pluginId,
2250
- phase: "start",
2251
- });
2252
- send({
2253
- type: "plugin_job",
2254
- jobId,
2255
- action: jobAction,
2256
- pluginId,
2257
- phase: "log",
2258
- line: jobLang() === "zh" ? "等待确认安装授权…" : "Waiting for install confirmation…",
2259
- });
1768
+ case "abort":
1769
+ void cs.abort();
1770
+ break;
1771
+ case "abort_bash":
1772
+ void cs.abortBash();
1773
+ break;
1774
+ case "retry_last":
1775
+ void cs.retryLast();
1776
+ break;
1777
+ case "get_state":
1778
+ // Always a FULL snapshot: the client is (re)connecting or detected
1779
+ // a rev/seq gap — it needs an authoritative state to rebuild from.
1780
+ cs.flushSnapshot(true);
1781
+ break;
1782
+ case "get_commands":
1783
+ void cs.pushSlashCommands();
1784
+ break;
1785
+ case "get_tool_info":
1786
+ // 工具卡右键菜单的「显示工具详细信息」:按需取一次工具定义(不进快照)。
1787
+ // 引擎没实现(或旧版服务端)时回一条 unsupported,前端据此显示「不支持」
1788
+ // 而不是永远转圈。
1789
+ if (typeof cs.getToolInfo === "function") {
1790
+ void cs.getToolInfo(msg.name);
1791
+ }
1792
+ else {
1793
+ send({ type: "tool_info", name: msg.name, found: false, unsupported: true });
2260
1794
  }
2261
- void confirmPluginInstallHelper([{ id: pluginId, source: String(msg.source ?? "") }])
2262
- .then((confirmed) => {
2263
- if (!confirmed) {
2264
- jobDone(false, jobLang() === "zh"
2265
- ? "用户未确认安装(拒绝或 120 秒超时)"
2266
- : "Installation not confirmed (rejected or timed out after 120s)");
2267
- return;
2268
- }
2269
- startPluginJob();
2270
- })
2271
- .catch(() => jobDone(false, jobLang() === "zh" ? "安装确认流程异常" : "Installation confirmation error"));
2272
1795
  break;
2273
- }
2274
- startPluginJob();
2275
- // 真正派发作业(确认门通过后走这里):被拒(忙 / 托管实例 / 参数非法)也要回
2276
- // 一条 done,让面板上的作业就地结束。
2277
- function startPluginJob() {
2278
- const started = pluginInstaller.start(jobSpec, {
2279
- lang: jobLang,
2280
- emit: (m) => send(m),
2281
- done: async (ok, info) => {
2282
- if (ok) {
2283
- await reloadPluginsAndPush(jobLang);
2284
- if (typeof cs?.checkPluginUpdates === "function") {
2285
- void cs.checkPluginUpdates(false);
2286
- }
2287
- const isZh = jobLang() === "zh";
2288
- const actionLabel = jobAction === "uninstall"
2289
- ? isZh
2290
- ? "卸载"
2291
- : "uninstalled"
2292
- : jobAction === "update"
2293
- ? isZh
2294
- ? "更新"
2295
- : "updated"
2296
- : isZh
2297
- ? "安装"
2298
- : "installed";
2299
- cs?.emitNotice("info", `插件「${pluginId}」${actionLabel}完成`, `Plugin "${pluginId}" ${actionLabel} successfully`);
2300
- }
2301
- else if (info.error) {
2302
- cs?.emitNotice("error", `插件操作失败:${info.error}`, `Plugin operation failed: ${info.error}`);
2303
- }
2304
- },
2305
- });
2306
- if (!started.ok)
2307
- jobDone(false, started.error);
2308
- }
2309
- break;
2310
- }
2311
- case "plugin_job_cancel":
2312
- pluginInstaller.cancel(String(msg.jobId ?? ""));
2313
- break;
2314
- // 注册面目录(DSH P2-7):只读装配(slot/工具/宿主方法表+当前占用者),按需拉取。
2315
- case "plugin_api_catalog": {
2316
- const requestId = String(msg.requestId ?? "");
2317
- send({ type: "plugin_api_catalog_result", requestId, catalog: pluginMgr.getApiCatalog() });
2318
- break;
2319
- }
2320
- // 安装前先读 spec(DSH P0-3):不联网也能查(形状/已装),GitHub 源再探一次
2321
- // raw manifest。结果只作引导(UI 把 problem 渲染成输入框下的一句话),不阻塞安装。
2322
- case "plugin_install_inspect": {
2323
- const requestId = String(msg.requestId ?? "");
2324
- const source = String(msg.source ?? "");
2325
- void inspectInstallSpec(source, {
2326
- pluginsDir: pluginMgr.pluginsDir,
2327
- ...(typeof msg.explicitId === "string" && msg.explicitId.trim() ? { explicitId: msg.explicitId.trim() } : {}),
2328
- force: msg.force === true,
2329
- }).then((r) => {
2330
- send({
2331
- type: "plugin_install_inspect_result",
2332
- requestId,
2333
- source,
2334
- kind: r.spec.kind,
2335
- suggestedId: r.suggestedId,
2336
- installed: r.installed,
2337
- ...(r.problem ? { problem: r.problem } : {}),
2338
- ...(r.detail ? { detail: r.detail } : {}),
2339
- ...(r.manifest ? { manifest: r.manifest } : {}),
2340
- });
2341
- });
2342
- break;
2343
- }
2344
- // -- 插件目录授权(issue #146)------------------------------------------
2345
- case "plugin_path_response": {
2346
- const id = String(msg.id ?? "");
2347
- const pending = pendingPathRequests.get(id);
2348
- // 来源绑定:应答必须来自弹窗广播时在线的 clientId——广播后才连上的
2349
- // 端没见过弹窗,忽略其代答(pending 保留,真正的弹窗端仍可答复)。
2350
- if (pending && clientId && pending.recipients.has(clientId)) {
2351
- clearTimeout(pending.timer);
2352
- pendingPathRequests.delete(id);
2353
- pending.resolve(msg.ok === true);
2354
- }
2355
- break;
2356
- }
2357
- // -- 插件能力授权(host.requestPermission)-------------------------------
2358
- case "plugin_permission_response": {
2359
- const id = String(msg.id ?? "");
2360
- const pending = pendingPermissionRequests.get(id);
2361
- // 来源绑定:同 plugin_path_response——只有收到弹窗广播的端可代答。
2362
- if (pending && clientId && pending.recipients.has(clientId)) {
2363
- clearTimeout(pending.timer);
2364
- pendingPermissionRequests.delete(id);
2365
- // 先答复者胜:通知其它在线端收起同一条请求(与目录授权不同,这里要显式 resolved)。
2366
- const resolved = JSON.stringify({ type: "plugin_permission_resolved", id });
2367
- for (const client of wss.clients) {
2368
- if (client.readyState === WebSocket.OPEN) {
2369
- try {
2370
- client.send(resolved);
2371
- }
2372
- catch {
2373
- /* 死连接 */
2374
- }
2375
- }
1796
+ case "get_tool_prompt":
1797
+ // 设置页逐工具文案编辑器:取「出厂默认 + 当前覆盖」。
1798
+ if (typeof cs.getToolPrompt === "function") {
1799
+ void cs.getToolPrompt(msg.name);
2376
1800
  }
2377
- pending.resolve({ ok: msg.ok === true, remember: msg.remember === true });
2378
- }
2379
- break;
2380
- }
2381
- case "plugin_dom_consent": {
2382
- // grant 是提权方向:走两步握手——只生成在途 consent 请求并广播,不在此
2383
- // 处落盘;收到绑定来源的 plugin_dom_consent_response 后才 setDomConsent。
2384
- // 同 pluginId 已有在途请求时忽略(首个优先,120s 超时自动失效)。
2385
- if (msg.granted === true) {
2386
- const pid = typeof msg.pluginId === "string" ? msg.pluginId.trim() : "";
2387
- if (!pid || !pluginMgr.isDomPlugin(pid) || pendingDomConsents.has(pid))
2388
- break;
2389
- const id = randomUUID();
2390
- const timer = setTimeout(() => {
2391
- pendingDomConsents.delete(pid);
2392
- }, 120_000);
2393
- pendingDomConsents.set(pid, { id, pluginId: pid, recipients: new Set(pluginMgr.onlineClientIds()), timer });
2394
- // from = 发起端 clientId:前端只自动应答自己发起的授权(设置面板点击)。
2395
- const payload = JSON.stringify({ type: "plugin_dom_consent_request", id, pluginId: pid, from: clientId });
2396
- for (const client of wss.clients) {
2397
- if (client.readyState === WebSocket.OPEN) {
2398
- try {
2399
- client.send(payload);
2400
- }
2401
- catch {
2402
- /* 死连接 */
2403
- }
2404
- }
1801
+ else {
1802
+ send({ type: "tool_prompt", name: msg.name, found: false, unsupported: true });
2405
1803
  }
2406
1804
  break;
2407
- }
2408
- // revoke 是降权方向:单步直达(不在途等待),pluginId 校验交给 setDomConsent。
2409
- applyDomConsent(msg.pluginId, false);
2410
- break;
2411
- }
2412
- // -- DOM 授权两步握手的应答:按 id 回查在途请求,且应答连接必须在弹窗
2413
- // 广播时的在线端集合里,才允许把 grant 持久写盘。
2414
- case "plugin_dom_consent_response": {
2415
- const id = typeof msg.id === "string" ? msg.id : "";
2416
- const pendingConsent = findDomConsentById(id);
2417
- if (pendingConsent && clientId && pendingConsent.recipients.has(clientId)) {
2418
- clearTimeout(pendingConsent.timer);
2419
- pendingDomConsents.delete(pendingConsent.pluginId);
2420
- // ok=false = 显式拒绝:只清在途请求不落盘(当前前端自动应答只发
2421
- // true,这里守住协议语义,将来接拒绝按钮不用动服务端)。
2422
- if (msg.ok === true)
2423
- applyDomConsent(pendingConsent.pluginId, true);
2424
- }
2425
- break;
2426
- }
2427
- case "plugin_path_revoke": {
2428
- const removed = pluginMgr.grants.revoke(typeof msg.pluginId === "string" ? msg.pluginId : undefined, typeof msg.path === "string" ? msg.path : undefined);
2429
- cs?.emitNotice("info", `已撤销 ${removed} 条插件目录授权`, `Revoked ${removed} plugin path grant(s)`);
2430
- pushPluginGrants();
2431
- break;
2432
- }
2433
- case "plugin_permission_revoke": {
2434
- const family = msg.family === "net" || msg.family === "llm" ? msg.family : undefined;
2435
- const removed = pluginMgr.permGrants.revoke(typeof msg.pluginId === "string" ? msg.pluginId : undefined, family, typeof msg.host === "string" || typeof msg.model === "string"
2436
- ? {
2437
- ...(typeof msg.host === "string" ? { host: msg.host } : {}),
2438
- ...(typeof msg.model === "string" ? { model: msg.model } : {}),
1805
+ case "take_over_conversation":
1806
+ if (typeof service.takeOverConversation === "function") {
1807
+ void service.takeOverConversation(clientId, msg.owner, msg.id);
2439
1808
  }
2440
- : undefined);
2441
- cs?.emitNotice("info", `已撤销 ${removed} 条能力授权`, `Revoked ${removed} permission grant(s)`);
2442
- pushPluginPermissions();
2443
- break;
2444
- }
2445
- // -- 插件市场目录同步(issue #148)--------------------------------------
2446
- case "plugin_catalog_sync": {
2447
- const syncLang = () => cs?.getLang() ?? "en";
2448
- const requestId = String(msg.requestId ?? "");
2449
- void syncPluginCatalog(String(msg.source ?? ""), { install: msg.install === true, replace: msg.replace === true }, {
2450
- customCatalogPath: pluginMgr.customCatalogPath,
2451
- pluginsDir: join(DATA_DIR, "plugins"),
2452
- installer: pluginInstaller,
2453
- // 只更新市场列表时无需重启已激活插件,避免重复广播工作目录。
2454
- afterWrite: () => (msg.install === true ? reloadPluginsAndPush(syncLang) : pluginMgr.pushCatalog()),
2455
- lang: syncLang,
2456
- // 本地文件来源只允许工作区内(防任意路径文件探测 oracle)。
2457
- workspaceRoot: cs?.cwd ?? CWD,
2458
- // 安装确认门(P0):拒绝/超时只写目录不安装。
2459
- confirmInstall: (items) => confirmPluginInstallHelper(items),
2460
- }).then((r) => {
2461
- if (r.installRefused) {
2462
- cs?.emitNotice("warning", "目录已同步,但安装未获用户确认(拒绝或超时),未安装任何插件", "Catalog synced, but installation was not confirmed (denied or timed out) — nothing was installed");
1809
+ else {
1810
+ send({
1811
+ type: "notice",
1812
+ level: "error",
1813
+ text: "当前引擎不支持过户(take over),请用 pi 引擎",
1814
+ textEn: "Takeover is not supported by the current engine; use the pi engine.",
1815
+ });
2463
1816
  }
2464
- send({
2465
- type: "plugin_catalog_sync_result",
2466
- requestId,
2467
- ok: r.ok,
2468
- ...(r.error ? { error: r.error } : {}),
2469
- entries: pluginMgr.catalog(),
2470
- ...(r.installed ? { installed: r.installed } : {}),
2471
- });
2472
- });
2473
- break;
2474
- }
2475
- case "dsh_patches_list":
2476
- void cs.listDshPatches?.();
2477
- break;
2478
- case "dsh_preset_list":
2479
- void cs.refreshAgentPresets?.();
2480
- break;
2481
- case "dsh_preset_select":
2482
- void cs.selectAgentPreset?.(msg.preset);
2483
- break;
2484
- case "dsh_preset_default":
2485
- void cs.setDefaultAgentPreset?.(msg.preset);
2486
- break;
2487
- case "dsh_permission_set":
2488
- void cs.setPermissionPreset?.(msg.preset);
2489
- break;
2490
- case "dsh_permission_default":
2491
- void cs.setDefaultPermissionPreset?.(msg.preset);
2492
- break;
2493
- case "dsh_patches_rescan":
2494
- void cs.rescanDshPatches?.();
2495
- break;
2496
- case "question_answer":
2497
- if (msg.owner) {
2498
- // 跨页作答:答案转交持有方会话(本页不持有该问卷)。
2499
- if (typeof service.answerElsewhereQuestion === "function") {
2500
- void service.answerElsewhereQuestion(clientId, msg.owner, msg.id, msg.answers, msg.cancelled);
1817
+ break;
1818
+ case "peek_elsewhere_question":
1819
+ if (typeof service.peekElsewhereQuestion === "function") {
1820
+ void service.peekElsewhereQuestion(clientId, msg.owner, msg.id);
2501
1821
  }
2502
1822
  else {
2503
1823
  send({
@@ -2507,145 +1827,77 @@ wss.on("connection", (ws) => {
2507
1827
  textEn: "Cross-page answering is not supported by the current engine; use the pi engine.",
2508
1828
  });
2509
1829
  }
2510
- }
2511
- else {
2512
- void cs.answerQuestion?.(msg.id, msg.answers, msg.cancelled);
2513
- }
2514
- break;
2515
- case "tool_approval_response":
2516
- cs.resolveToolApproval?.(msg.id, msg.decision, msg.editedParams, msg.reason, msg.scope);
2517
- break;
2518
- case "set_approval_policy":
2519
- cs.setApprovalPolicy?.({
2520
- conversationId: msg.conversationId,
2521
- allowAll: msg.allowAll,
2522
- categories: msg.categories,
2523
- });
2524
- break;
2525
- case "plan_update":
2526
- cs.updatePlan?.(msg.steps, msg.activeStepId, msg.conversationId);
2527
- break;
2528
- case "plan_step_update":
2529
- cs.updatePlanStep?.(msg.stepId, msg.patch, msg.conversationId);
2530
- break;
2531
- case "plan_step_delete":
2532
- cs.deletePlanStep?.(msg.stepId, msg.conversationId);
2533
- break;
2534
- case "plan_step_add":
2535
- cs.addPlanStep?.(msg.step, msg.afterStepId, msg.conversationId);
2536
- break;
2537
- case "plan_clean_handoff":
2538
- void cs.planCleanHandoff?.(msg.steps, msg.prompt);
2539
- break;
2540
- case "set_plan_mode":
2541
- // 计划模式(只规划不实施):会话级开关,热生效(提示词重建 + 工具硬闸门)。
2542
- void cs.setPlanMode?.(msg.enabled, msg.conversationId);
2543
- break;
2544
- case "set_delegate_mode":
2545
- // 审查者模式(自动委派):会话级开关,默认关。开启后本对话只审阅,
2546
- // 用户 prompt 由服务端转给常驻落盘执行对话。DSH 引擎的实现在
2547
- // setDelegateMode 里直接拒(无 customTools 注册面 → 闸门无处可挂)。
2548
- void cs.setDelegateMode?.(msg.enabled, msg.conversationId);
2549
- break;
2550
- case "page_response":
2551
- // 浏览器(page-picker 扩展经前端)对 browser_page 的回包:恢复挂起的
2552
- // pageCall;id 不匹配(超时后迟到/页面刷新)由 resolvePageCall 静默忽略。
2553
- cs.resolvePageCall?.(msg.id, msg.ok, msg.result, msg.error);
2554
- break;
2555
- case "save_preset":
2556
- void cs.savePreset(msg.name);
2557
- break;
2558
- case "save_subagent_template":
2559
- void cs.saveSubagentTemplate(msg.template);
2560
- break;
2561
- case "delete_subagent_template":
2562
- void cs.deleteSubagentTemplate(msg.name);
2563
- break;
2564
- case "save_approval_rule":
2565
- void cs.saveApprovalRule?.(msg.rule);
2566
- break;
2567
- case "save_approval_rules":
2568
- void cs.saveApprovalRules?.(msg.rules);
2569
- break;
2570
- case "delete_approval_rule":
2571
- void cs.deleteApprovalRule?.(msg.id);
2572
- break;
2573
- case "reset_builtin_approval_rule":
2574
- void cs.resetBuiltinApprovalRule?.(msg.id);
2575
- break;
2576
- case "apply_preset":
2577
- void cs.applyPreset(msg.name);
2578
- break;
2579
- case "delete_preset":
2580
- void cs.deletePreset(msg.name);
2581
- break;
2582
- case "schedule_list":
2583
- try {
2584
- send({ type: "scheduler_tasks", tasks: scheduler.list() });
2585
- }
2586
- catch (err) {
2587
- send({
2588
- type: "notice",
2589
- level: "error",
2590
- text: `读取定时任务失败:${err.message}`,
2591
- textEn: `Failed to list scheduled tasks: ${err.message}`,
2592
- });
2593
- }
2594
- break;
2595
- case "schedule_save":
2596
- try {
2597
- scheduler.upsert(msg.task);
2598
- }
2599
- catch (err) {
2600
- const isVal = err instanceof SchedulerValidationError;
2601
- send({
2602
- type: "notice",
2603
- level: "error",
2604
- text: `保存定时任务失败:${isVal ? err.messageZh : err.message}`,
2605
- textEn: `Failed to save scheduled task: ${isVal ? err.messageEn : err.message}`,
2606
- });
2607
- }
2608
- break;
2609
- case "schedule_delete":
2610
- if (!scheduler.remove(msg.id)) {
2611
- send({
2612
- type: "notice",
2613
- level: "warning",
2614
- text: `定时任务不存在:${msg.id}`,
2615
- textEn: `No such scheduled task: ${msg.id}`,
2616
- });
2617
- }
2618
- break;
2619
- case "schedule_run":
2620
- void scheduler.runNow(msg.id).then((r) => {
2621
- if (!r.ok)
1830
+ break;
1831
+ case "set_locale":
1832
+ // UI language report — per-client persist + lang-aware prompt
1833
+ // refresh (streaming-safe). Engine-agnostic via DispatchSession.
1834
+ void service.setLocale(clientId, msg.locale);
1835
+ break;
1836
+ case "check_update":
1837
+ void cs.checkUpdate();
1838
+ break;
1839
+ case "check_updates_all":
1840
+ void cs.checkUpdatesAll(msg.force === true);
1841
+ break;
1842
+ case "check_plugin_updates":
1843
+ if (typeof cs.checkPluginUpdates === "function") {
1844
+ void cs.checkPluginUpdates(true);
1845
+ }
1846
+ break;
1847
+ case "restart_service": {
1848
+ // Same effect as `pi-web-ui server restart`: this process exits and its
1849
+ // supervisor brings it back (launchd/systemd immediately, the Windows
1850
+ // watchdog within ~10s). Refused without a supervisor — exiting there
1851
+ // would just stop the server the user is looking at.
1852
+ if (!ORIGIN.supervisor) {
2622
1853
  send({
2623
1854
  type: "notice",
2624
- level: "warning",
2625
- text: `定时任务手动触发失败:${r.error ?? "未知错误"}`,
2626
- textEn: `Manual scheduled-task run failed: ${r.error ?? "unknown error"}`,
1855
+ level: "error",
1856
+ text: "当前实例不是由 pi-web-ui 服务启动的(前台运行),无法自动重启;请在终端里重启,或先用 pi-web-ui server install 安装服务。",
1857
+ textEn: "This instance runs in the foreground, not as a pi-web-ui service — nothing would bring it back. Restart it in its terminal, or install the service with `pi-web-ui server install`.",
2627
1858
  });
2628
- });
2629
- break;
2630
- case "schedule_toggle":
2631
- if (!scheduler.setEnabled(msg.id, msg.enabled === true)) {
1859
+ break;
1860
+ }
2632
1861
  send({
2633
1862
  type: "notice",
2634
- level: "warning",
2635
- text: `定时任务不存在:${msg.id}`,
2636
- textEn: `No such scheduled task: ${msg.id}`,
1863
+ level: "info",
1864
+ text: "正在重启服务…页面会在服务恢复后自动重连,进行中的对话会自动恢复并继续。",
1865
+ textEn: "Restarting the service… this page reconnects once it is back; running conversations resume automatically.",
2637
1866
  });
1867
+ // Record streaming runs BEFORE exiting: under systemd this path
1868
+ // exits via process.exit without shutdown(), so without this the
1869
+ // post-restart resume would find nothing to continue.
1870
+ try {
1871
+ service.recordInterruptedRuns();
1872
+ }
1873
+ catch {
1874
+ /* best effort — never block the restart on bookkeeping */
1875
+ }
1876
+ // Let the notice (and this socket's backlog) flush before we go down.
1877
+ setTimeout(() => void scheduleQuit(), 400);
1878
+ break;
1879
+ }
1880
+ default: {
1881
+ // 未知 type 只计数 + 节流 warn,不改变已知类型行为。
1882
+ // default 分支里 msg 已收窄成 never,type 需从宽化后取。
1883
+ const raw = msg.type;
1884
+ const name = typeof raw === "string" ? raw : String(raw);
1885
+ const r = recordUnknownWsType(name);
1886
+ if (r.warn)
1887
+ console.warn(`[ws] unknown message type "${name}" (x${r.count})`);
1888
+ break;
2638
1889
  }
2639
- break;
2640
- default: {
2641
- // 未知 type 只计数 + 节流 warn,不改变已知类型行为。
2642
- // default 分支里 msg 已收窄成 never,type 需从宽化后取。
2643
- const raw = msg.type;
2644
- const name = typeof raw === "string" ? raw : String(raw);
2645
- const r = recordUnknownWsType(name);
2646
- if (r.warn)
2647
- console.warn(`[ws] unknown message type "${name}" (x${r.count})`);
2648
- break;
1890
+ }
1891
+ }
1892
+ catch (err) {
1893
+ console.error(`[dispatch error on "${msg.type}"]:`, err);
1894
+ if (!closed) {
1895
+ send({
1896
+ type: "notice",
1897
+ level: "error",
1898
+ text: `操作「${msg.type}」执行出错:${err instanceof Error ? err.message : String(err)}`,
1899
+ textEn: `Error executing "${msg.type}": ${err instanceof Error ? err.message : String(err)}`,
1900
+ });
2649
1901
  }
2650
1902
  }
2651
1903
  };
@@ -2711,8 +1963,10 @@ wss.on("connection", (ws) => {
2711
1963
  .attach(cid, send)
2712
1964
  .then((cs) => {
2713
1965
  clearTimeout(slowTimer);
2714
- if (closed)
1966
+ if (closed) {
1967
+ service.detach(cid, send);
2715
1968
  return;
1969
+ }
2716
1970
  // Plugin catalog: re-scan + activate new dirs on every attach so
2717
1971
  // freshly dropped plugins show up without a server restart.
2718
1972
  pluginMgr
@@ -2730,6 +1984,8 @@ wss.on("connection", (ws) => {
2730
1984
  // 让各插件向新接入的客户端推送自身初始状态(onAttach 钩子)——
2731
1985
  // 插件不要依赖客户端挂载后自己拉(见 plugins.ts onAttach 注释)。
2732
1986
  pluginMgr.notifyAttach(cid);
1987
+ // P3:左栏插件运行条目全量补发(之后的变更经 plugin_panel_items 广播)。
1988
+ send({ type: "plugin_panel_items", groups: pluginMgr.panelGroups() });
2733
1989
  // 插件目录授权表(设置面板展示 + 可撤销)
2734
1990
  send({ type: "plugin_grants", grants: pluginMgr.grants.list() });
2735
1991
  // 插件能力授权表(设置面板展示 + 可撤销;session 授权带标记)
@@ -2740,7 +1996,9 @@ wss.on("connection", (ws) => {
2740
1996
  // 插件清单【先于】快照推送:前端渲染历史消息前就拿到 renderer
2741
1997
  // 注册表(plugin-fence.ts),`` ```lang `` 围栏才能立即命中插件;
2742
1998
  // 否则消息先落成普通代码块,清单后到也不会重渲。
2743
- cs.flushSnapshot();
1999
+ // 新连接/新客户端 attach 首次快照必须强制全量(forceFull=true),
2000
+ // 保证新标签页/刷新页能立刻拿到完整的会话基线,绝不因增量 delta 而卡在加载中。
2001
+ cs.flushSnapshot(true);
2744
2002
  // 内置定时任务列表随附推一次(后续变更经 pushSchedulerTasks 广播)。
2745
2003
  try {
2746
2004
  send({ type: "scheduler_tasks", tasks: scheduler.list() });
@@ -2754,8 +2012,8 @@ wss.on("connection", (ws) => {
2754
2012
  if (closed)
2755
2013
  return;
2756
2014
  // ensureLoaded 失败(如磁盘读错)不能卡死快照——前端 30s 无消息
2757
- // 会重连,重连又失败会陷入循环。至少把状态推下去。
2758
- cs.flushSnapshot();
2015
+ // 会重连,重连又失败会陷入循环。至少把状态推下去(同样强制全量)。
2016
+ cs.flushSnapshot(true);
2759
2017
  replayQueued();
2760
2018
  });
2761
2019
  // hello may carry the UI locale — persist it before replaying
@@ -2775,6 +2033,10 @@ wss.on("connection", (ws) => {
2775
2033
  };
2776
2034
  })
2777
2035
  .catch((err) => {
2036
+ clearTimeout(slowTimer);
2037
+ if (closed) {
2038
+ service.detach(cid, send);
2039
+ }
2778
2040
  // Admission refused (quiesce): close the socket so the browser
2779
2041
  // reconnect loop keeps retrying until admission reopens. Do NOT
2780
2042
  // leave a half-alive connection that can only show an error.
@@ -3017,3 +2279,9 @@ async function shutdown(signal = "SIGINT") {
3017
2279
  }
3018
2280
  process.on("SIGINT", () => void shutdown("SIGINT"));
3019
2281
  process.on("SIGTERM", () => void shutdown("SIGTERM"));
2282
+ process.on("unhandledRejection", (reason) => {
2283
+ console.error("[pi-web-ui] Unhandled Promise Rejection:", reason);
2284
+ });
2285
+ process.on("uncaughtException", (err) => {
2286
+ console.error("[pi-web-ui] Uncaught Exception:", err);
2287
+ });