pi-web-ui 0.87.1 → 0.88.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.
@@ -2228,6 +2228,40 @@ export class ClientSession {
2228
2228
  return { ok: false, error: err.message };
2229
2229
  }
2230
2230
  }
2231
+ /** 插件扩展点(供 llmProvider):孤立补全的环境(cwd/agentDir/回落模型)。
2232
+ * 取最近活跃的主对话(跳过子代理);model 读不到就只给 cwd(调用方再回落默认模型)。
2233
+ * 纯数据组装,不 emit、不改状态。 */
2234
+ llmEnvForPlugins() {
2235
+ let target = null;
2236
+ try {
2237
+ for (const c of this.convs.values()) {
2238
+ if (c.isSubagent)
2239
+ continue;
2240
+ if (!target || c.lastActiveAt > target.lastActiveAt)
2241
+ target = c;
2242
+ }
2243
+ if (!target) {
2244
+ for (const c of this.convs.values()) {
2245
+ if (!target || c.lastActiveAt > target.lastActiveAt)
2246
+ target = c;
2247
+ }
2248
+ }
2249
+ }
2250
+ catch {
2251
+ target = null;
2252
+ }
2253
+ const cwd = target?.cwd ?? this.cwd;
2254
+ let fallbackModel;
2255
+ try {
2256
+ const m = target?.session?.model;
2257
+ if (m?.provider && m.id)
2258
+ fallbackModel = { provider: m.provider, id: m.id };
2259
+ }
2260
+ catch {
2261
+ /* model 读不到就回落默认 */
2262
+ }
2263
+ return { cwd, agentDir: this.agentDir, ...(fallbackModel ? { fallbackModel } : {}) };
2264
+ }
2231
2265
  /** 插件扩展点 v2(供 modelLister):复用 listModels 的模型列表映射 {id,provider,vision}。
2232
2266
  * 与 listModels 唯一差别:不做网络 refresh(插件列表走缓存目录,15s 超时也不等),只读不 emit。 */
2233
2267
  async listModelsForPlugins() {
@@ -4649,7 +4683,9 @@ export class ClientSession {
4649
4683
  wizardRunning: conv.wizardRunning,
4650
4684
  streaming: conv.session.isStreaming,
4651
4685
  compacting: conv.session.isCompacting,
4652
- openTerminals: conv.terminals.countLive(),
4686
+ // 只看“用过”的存活终端:没动过的空 shell(点开终端 tab 自动建的
4687
+ // 那个)不保留对话,切走即随对话释放(见 countBlockingLive)。
4688
+ openTerminals: conv.terminals.countBlockingLive(),
4653
4689
  listed: conv.listed,
4654
4690
  promptedSinceActive: conv.promptedSinceActive,
4655
4691
  hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: conv.session.sessionFile }),
@@ -5084,7 +5120,8 @@ export class ClientSession {
5084
5120
  reviewing: conv.goal.reviewing,
5085
5121
  wizardRunning: conv.wizardRunning,
5086
5122
  streaming: false,
5087
- openTerminals: conv.terminals.countLive(),
5123
+ // 与 displaceActive 同口径:只看“用过”的存活终端。
5124
+ openTerminals: conv.terminals.countBlockingLive(),
5088
5125
  listed: false,
5089
5126
  promptedSinceActive: false,
5090
5127
  hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: conv.session.sessionFile }),
@@ -5155,7 +5192,7 @@ export class ClientSession {
5155
5192
  });
5156
5193
  return;
5157
5194
  }
5158
- if (conv.terminals.countLive() > 0) {
5195
+ if (conv.terminals.countBlockingLive() > 0) {
5159
5196
  this.emit({
5160
5197
  type: "notice",
5161
5198
  level: "warning",
@@ -5164,6 +5201,8 @@ export class ClientSession {
5164
5201
  });
5165
5202
  return;
5166
5203
  }
5204
+ // 没动过的空 shell(点开终端 tab 自动建的那个)不拦截:随对话一起释放
5205
+ // (removeConversation 里 killAll)。
5167
5206
  if (shouldRetainActive({
5168
5207
  reviewing: conv.goal.reviewing,
5169
5208
  wizardRunning: conv.wizardRunning,
@@ -5416,7 +5455,8 @@ export class ClientSession {
5416
5455
  reviewing: conv.goal.reviewing,
5417
5456
  wizardRunning: conv.wizardRunning,
5418
5457
  streaming: false,
5419
- openTerminals: conv.terminals.countLive(),
5458
+ // 与 displaceActive 同口径:只看“用过”的存活终端。
5459
+ openTerminals: conv.terminals.countBlockingLive(),
5420
5460
  listed: false,
5421
5461
  promptedSinceActive: false,
5422
5462
  hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: conv.session.sessionFile }),
@@ -6412,6 +6452,33 @@ export class AgentService {
6412
6452
  void cs.prompt(text);
6413
6453
  return { conversationId: before, clientId };
6414
6454
  }
6455
+ /** 插件直调模型(host.llm.complete 的落地):孤立无工具的一次性补全。
6456
+ * 不建对话、不进历史、不碰任何会话状态;花费走用户自己的模型额度。
6457
+ * quiesced 时拒绝;无客户端时用进程 cwd + 默认模型照常跑。 */
6458
+ async completeForPlugins(pluginId, req) {
6459
+ try {
6460
+ if (this.quiesced)
6461
+ return { ok: false, error: "插件 LLM 调用被拒绝,请等服务器恢复后重试" };
6462
+ let env;
6463
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
6464
+ try {
6465
+ const cs = this.pluginClient();
6466
+ env = cs?.llmEnvForPlugins() ?? { cwd: this.cwd, agentDir };
6467
+ }
6468
+ catch {
6469
+ env = { cwd: this.cwd, agentDir };
6470
+ }
6471
+ const mod = await import("./plugin-llm.js");
6472
+ const r = await mod.completeWithIsolatedSession(env, { ...req, prompt: String(req?.prompt ?? "") });
6473
+ if (!r.ok)
6474
+ return r;
6475
+ console.log(`[plugin:${pluginId}] llm.complete ok(模型 ${r.model},输出 ${r.text.length} 字)`);
6476
+ return r;
6477
+ }
6478
+ catch (err) {
6479
+ return { ok: false, error: err.message };
6480
+ }
6481
+ }
6415
6482
  /** index.ts calls this when a browser socket opens/closes. */
6416
6483
  noteSocketOpen() {
6417
6484
  this.socketCount += 1;
@@ -399,7 +399,8 @@ export class DshClientSession {
399
399
  continue;
400
400
  if (conv.isStreaming)
401
401
  continue;
402
- if (conv.terminals.list().length > 0)
402
+ // 只看“用过”的存活终端:没动过的空 shell 不阻止空闲回收。
403
+ if (conv.terminals.countBlockingLive() > 0)
403
404
  continue;
404
405
  const idle = now - conv.lastEventAt;
405
406
  const limit = conv.listed ? DshClientSession.CONV_RECLAIM_LISTED_IDLE_MS : DshClientSession.CONV_RECLAIM_IDLE_MS;
@@ -1402,7 +1403,7 @@ export class DshClientSession {
1402
1403
  }
1403
1404
  // 旧对话保留(listed 生命周期简化:不主动移除)。
1404
1405
  const prevModel = this.model;
1405
- active.listed = active.isStreaming || active.terminals.list().length > 0 || active.promptedSinceActive;
1406
+ active.listed = active.isStreaming || active.terminals.countBlockingLive() > 0 || active.promptedSinceActive;
1406
1407
  const conv = this.addConversation(`chat-${randomUUID().slice(0, 12)}`, this.cwd, false, preset);
1407
1408
  this.activeId = conv.id;
1408
1409
  this.model = prevModel;
@@ -1417,7 +1418,8 @@ export class DshClientSession {
1417
1418
  if (!this.convs.has(id) || id === this.activeId)
1418
1419
  return;
1419
1420
  const prev = this.conv;
1420
- prev.listed = prev.isStreaming || prev.terminals.list().length > 0 || prev.promptedSinceActive;
1421
+ // 只看“用过”的存活终端:没动过的空 shell 不钉住 listed(与 pi 的 displaceActive 同口径)。
1422
+ prev.listed = prev.isStreaming || prev.terminals.countBlockingLive() > 0 || prev.promptedSinceActive;
1421
1423
  this.activeId = id;
1422
1424
  // 后台列表可能属于另一项目 → 切会话同时切工作区(与 pi 一致:文件树/
1423
1425
  // 会话历史/最近项目跟着走)。DSH 单 runtime 换 cwd → 异步重启。
@@ -2112,7 +2114,7 @@ export class DshClientSession {
2112
2114
  });
2113
2115
  return;
2114
2116
  }
2115
- if (conv.terminals.list().length > 0 && !force) {
2117
+ if (conv.terminals.countBlockingLive() > 0 && !force) {
2116
2118
  this.emit({
2117
2119
  type: "notice",
2118
2120
  level: "warning",
@@ -2121,6 +2123,7 @@ export class DshClientSession {
2121
2123
  });
2122
2124
  return;
2123
2125
  }
2126
+ // 没动过的空 shell(点开终端 tab 自动建的那个)不拦截:随对话一起释放。
2124
2127
  // force + active:先让出 active(切到其他对话或新建),再移除。
2125
2128
  if (id === this.activeId) {
2126
2129
  const other = [...this.convs.values()].find((c) => c.id !== id);
@@ -2188,7 +2191,8 @@ export class DshClientSession {
2188
2191
  }
2189
2192
  }
2190
2193
  const prev = this.conv;
2191
- prev.listed = prev.isStreaming || prev.terminals.list().length > 0 || prev.promptedSinceActive;
2194
+ // 只看“用过”的存活终端:没动过的空 shell 不钉住 listed(与 pi 的 displaceActive 同口径)。
2195
+ prev.listed = prev.isStreaming || prev.terminals.countBlockingLive() > 0 || prev.promptedSinceActive;
2192
2196
  const conv = this.addConversation(sessionId, this.cwd, true);
2193
2197
  conv.fromDisk = true; // 磁盘回放 → prompt 时 fork
2194
2198
  this.activeId = conv.id;
@@ -3855,7 +3859,8 @@ export class DshClientSession {
3855
3859
  })
3856
3860
  .join("\n");
3857
3861
  const prev = this.conv;
3858
- prev.listed = prev.isStreaming || prev.terminals.list().length > 0 || prev.promptedSinceActive;
3862
+ // 只看“用过”的存活终端:没动过的空 shell 不钉住 listed(与 pi 的 displaceActive 同口径)。
3863
+ prev.listed = prev.isStreaming || prev.terminals.countBlockingLive() > 0 || prev.promptedSinceActive;
3859
3864
  this.activeId = fresh.id;
3860
3865
  // 编辑后的提问本身在 prompt 里;历史作为附加上下文(首条 prompt)。
3861
3866
  const headText = contextNote.trim()
@@ -3933,7 +3938,10 @@ export class DshClientSession {
3933
3938
  // (与 pi 的 displaceActive 语义一致);空白的直接弃(不列)。
3934
3939
  const prev = this.conv;
3935
3940
  prev.listed =
3936
- prev.isStreaming || prev.terminals.list().length > 0 || prev.promptedSinceActive || prev.messages.length > 0;
3941
+ prev.isStreaming ||
3942
+ prev.terminals.countBlockingLive() > 0 ||
3943
+ prev.promptedSinceActive ||
3944
+ prev.messages.length > 0;
3937
3945
  // 新项目 → 新会话。
3938
3946
  this.activeId = this.addConversation(`web-${randomUUID().slice(0, 12)}`, abs, false).id;
3939
3947
  // 旧项目非活跃 conversation 回收(pi 的 displaceActive 语义:切走后
@@ -3948,7 +3956,8 @@ export class DshClientSession {
3948
3956
  continue;
3949
3957
  if (c.isStreaming)
3950
3958
  continue;
3951
- if (c.terminals.list().length > 0)
3959
+ // 只看“用过”的存活终端:没动过的空 shell 不阻止项目切换时的旧会话回收。
3960
+ if (c.terminals.countBlockingLive() > 0)
3952
3961
  continue;
3953
3962
  this.removeConversation(id);
3954
3963
  }
@@ -0,0 +1,59 @@
1
+ import os from "node:os";
2
+ function calculateMemoryPercent(snapshot) {
3
+ const memoryUsed = Math.max(0, snapshot.memoryTotal - snapshot.memoryFree);
4
+ return snapshot.memoryTotal > 0 ? Math.max(0, Math.min(100, (memoryUsed / snapshot.memoryTotal) * 100)) : 0;
5
+ }
6
+ export function defaultReadSnapshot() {
7
+ const cpus = os.cpus();
8
+ let cpuIdle = 0;
9
+ let cpuTotal = 0;
10
+ for (const cpu of cpus) {
11
+ const times = cpu.times;
12
+ const total = (times.user ?? 0) + (times.nice ?? 0) + (times.sys ?? 0) + (times.idle ?? 0) + (times.irq ?? 0);
13
+ cpuIdle += times.idle ?? 0;
14
+ cpuTotal += total;
15
+ }
16
+ return {
17
+ cpuIdle,
18
+ cpuTotal,
19
+ memoryFree: os.freemem(),
20
+ memoryTotal: os.totalmem(),
21
+ };
22
+ }
23
+ export function calculateHostMetrics(previous, current) {
24
+ const totalDelta = current.cpuTotal - previous.cpuTotal;
25
+ const idleDelta = current.cpuIdle - previous.cpuIdle;
26
+ let cpuPercent = null;
27
+ if (totalDelta > 0) {
28
+ const rawPercent = (1 - idleDelta / totalDelta) * 100;
29
+ cpuPercent = Math.max(0, Math.min(100, rawPercent));
30
+ }
31
+ const memoryPercent = calculateMemoryPercent(current);
32
+ return {
33
+ cpuPercent,
34
+ memoryPercent,
35
+ };
36
+ }
37
+ export function createHostMetricsSampler(readSnapshot = defaultReadSnapshot) {
38
+ let previous = null;
39
+ try {
40
+ previous = readSnapshot();
41
+ }
42
+ catch {
43
+ // 初始基线读取异常时不击穿服务启动,待后续心跳重试
44
+ previous = null;
45
+ }
46
+ return () => {
47
+ const current = readSnapshot();
48
+ if (!previous) {
49
+ previous = current;
50
+ return {
51
+ cpuPercent: null,
52
+ memoryPercent: calculateMemoryPercent(current),
53
+ };
54
+ }
55
+ const metrics = calculateHostMetrics(previous, current);
56
+ previous = current;
57
+ return metrics;
58
+ };
59
+ }
@@ -45,6 +45,7 @@ import { PluginInstaller } from "./plugin-installer.js";
45
45
  import { syncPluginCatalog } from "./plugin-catalog-sync.js";
46
46
  import { McpBridge } from "./mcp-bridge.js";
47
47
  import { createMcpHotReload } from "./mcp-hot-reload.js";
48
+ import { createHostMetricsSampler } from "./host-metrics.js";
48
49
  /** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
49
50
  * `npm_lifecycle_*` into every child). Anything this server spawns — shells,
50
51
  * `pi update` — would otherwise inherit `npm_config_allow_scripts`, which npm
@@ -679,15 +680,27 @@ httpServer.on("upgrade", (req, socket, head) => {
679
680
  });
680
681
  });
681
682
  // Heartbeat: lets clients detect half-open connections (server killed without
682
- // closing sockets, sleep/wake, network partitions). Idle connections otherwise
683
- // carry no traffic and TCP keepalive defaults are far too slow (~2h).
683
+ // closing sockets, sleep/wake, network partitions). Also broadcasts lightweight
684
+ // server host metrics (CPU and memory usage) sampled every ~2s.
685
+ const HEARTBEAT_INTERVAL_MS = 2_000;
686
+ const sampleHostMetrics = createHostMetricsSampler();
684
687
  const heartbeatTimer = setInterval(() => {
685
- for (const ws of wss.clients) {
686
- if (ws.readyState === WebSocket.OPEN) {
687
- ws.send(JSON.stringify({ type: "heartbeat" }));
688
+ let message = { type: "heartbeat" };
689
+ try {
690
+ message = { type: "heartbeat", hostMetrics: sampleHostMetrics() };
691
+ }
692
+ catch {
693
+ // 继续发送普通心跳,下一轮重试采样。
694
+ }
695
+ if (wss.clients.size > 0) {
696
+ const payload = JSON.stringify(message);
697
+ for (const ws of wss.clients) {
698
+ if (ws.readyState === WebSocket.OPEN) {
699
+ ws.send(payload);
700
+ }
688
701
  }
689
702
  }
690
- }, 10_000);
703
+ }, HEARTBEAT_INTERVAL_MS);
691
704
  // 引擎分发:PI_WEB_ENGINE=dsh 时使用 DeepSeek Harness 引擎(server/dsh/),
692
705
  // 默认 pi 引擎。同一 wire 协议,前端无感知(ready/health 携带 engine 字段)。
693
706
  import { DshAgentService } from "./dsh/dsh-agent-service.js";
@@ -754,6 +767,60 @@ pluginMgr.pathAccessRequester = (pluginId, dir, reason) => new Promise((resolve)
754
767
  });
755
768
  // 用户点了「允许」→ 授权表变了 → 立刻重推给所有在线客户端(设置面板「已授权目录」即时可见)。
756
769
  pluginMgr.onGrantsChanged = () => pushPluginGrants();
770
+ const pendingPermissionRequests = new Map();
771
+ /** 把能力授权表推给所有在线客户端(设置面板展示 + 撤销后刷新)。 */
772
+ function pushPluginPermissions() {
773
+ const payload = JSON.stringify({ type: "plugin_permissions", grants: pluginMgr.permGrants.list() });
774
+ for (const client of wss.clients) {
775
+ if (client.readyState === WebSocket.OPEN) {
776
+ try {
777
+ client.send(payload);
778
+ }
779
+ catch {
780
+ /* 死连接 */
781
+ }
782
+ }
783
+ }
784
+ }
785
+ pluginMgr.permissionRequester = (pluginId, req) => new Promise((resolve) => {
786
+ const id = randomUUID();
787
+ const resolved = JSON.stringify({ type: "plugin_permission_resolved", id });
788
+ const timer = setTimeout(() => {
789
+ pendingPermissionRequests.delete(id);
790
+ for (const client of wss.clients) {
791
+ if (client.readyState === WebSocket.OPEN) {
792
+ try {
793
+ client.send(resolved);
794
+ }
795
+ catch {
796
+ /* 死连接 */
797
+ }
798
+ }
799
+ }
800
+ resolve({ ok: false, remember: false });
801
+ }, 120_000);
802
+ pendingPermissionRequests.set(id, { resolve, timer });
803
+ const ask = JSON.stringify({
804
+ type: "plugin_permission_request",
805
+ id,
806
+ pluginId,
807
+ family: req.family,
808
+ ...(req.hosts ? { hosts: req.hosts } : {}),
809
+ ...(req.models ? { models: req.models } : {}),
810
+ ...(req.reason ? { reason: req.reason } : {}),
811
+ });
812
+ for (const client of wss.clients) {
813
+ if (client.readyState === WebSocket.OPEN) {
814
+ try {
815
+ client.send(ask);
816
+ }
817
+ catch {
818
+ /* 死连接 */
819
+ }
820
+ }
821
+ }
822
+ });
823
+ pluginMgr.onPermGrantsChanged = () => pushPluginPermissions();
757
824
  /** 广播通知条给全部在线客户端(全局事件,不属于某个 ClientSession —— 如 mcp.json 坏)。 */
758
825
  function pushNoticeToAll(level, text, textEn) {
759
826
  const payload = JSON.stringify({ type: "notice", level, text, textEn });
@@ -907,6 +974,19 @@ service.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
907
974
  return { ok: false, error: err.message };
908
975
  }
909
976
  };
977
+ // llmProvider:插件直调模型(孤立无工具的一次性补全,不建对话)。
978
+ // 标准 pi 引擎走 service.completeForPlugins;DSH/未知引擎回 {ok:false},绝不抛错。
979
+ pm.llmProvider = async (pluginId, req) => {
980
+ try {
981
+ const svc = service;
982
+ if (typeof svc.completeForPlugins !== "function")
983
+ return { ok: false, error: "当前引擎不支持 LLM 直调(仅标准 pi 引擎)" };
984
+ return await svc.completeForPlugins(pluginId, (req ?? {}));
985
+ }
986
+ catch (err) {
987
+ return { ok: false, error: err.message };
988
+ }
989
+ };
910
990
  }
911
991
  // 插件宿主工作区实时跟随当前项目:任意客户端 set_cwd 成功后同步给
912
992
  // PluginManager,编辑器等工作区跟随型插件随即切根(详见 plugins.ts notifyCwd)。
@@ -1492,6 +1572,29 @@ wss.on("connection", (ws) => {
1492
1572
  }
1493
1573
  break;
1494
1574
  }
1575
+ // -- 插件能力授权(host.requestPermission)-------------------------------
1576
+ case "plugin_permission_response": {
1577
+ const id = String(msg.id ?? "");
1578
+ const pending = pendingPermissionRequests.get(id);
1579
+ if (pending) {
1580
+ clearTimeout(pending.timer);
1581
+ pendingPermissionRequests.delete(id);
1582
+ // 先答复者胜:通知其它在线端收起同一条请求(与目录授权不同,这里要显式 resolved)。
1583
+ const resolved = JSON.stringify({ type: "plugin_permission_resolved", id });
1584
+ for (const client of wss.clients) {
1585
+ if (client.readyState === WebSocket.OPEN) {
1586
+ try {
1587
+ client.send(resolved);
1588
+ }
1589
+ catch {
1590
+ /* 死连接 */
1591
+ }
1592
+ }
1593
+ }
1594
+ pending.resolve({ ok: msg.ok === true, remember: msg.remember === true });
1595
+ }
1596
+ break;
1597
+ }
1495
1598
  case "plugin_dom_consent": {
1496
1599
  void pluginMgr
1497
1600
  .setDomConsent(msg.pluginId, msg.granted === true)
@@ -1514,6 +1617,18 @@ wss.on("connection", (ws) => {
1514
1617
  pushPluginGrants();
1515
1618
  break;
1516
1619
  }
1620
+ case "plugin_permission_revoke": {
1621
+ const family = msg.family === "net" || msg.family === "llm" ? msg.family : undefined;
1622
+ const removed = pluginMgr.permGrants.revoke(typeof msg.pluginId === "string" ? msg.pluginId : undefined, family, typeof msg.host === "string" || typeof msg.model === "string"
1623
+ ? {
1624
+ ...(typeof msg.host === "string" ? { host: msg.host } : {}),
1625
+ ...(typeof msg.model === "string" ? { model: msg.model } : {}),
1626
+ }
1627
+ : undefined);
1628
+ cs?.emitNotice("info", `已撤销 ${removed} 条能力授权`, `Revoked ${removed} permission grant(s)`);
1629
+ pushPluginPermissions();
1630
+ break;
1631
+ }
1517
1632
  // -- 插件市场目录同步(issue #148)--------------------------------------
1518
1633
  case "plugin_catalog_sync": {
1519
1634
  const syncLang = () => cs?.getLang() ?? "en";
@@ -1634,6 +1749,8 @@ wss.on("connection", (ws) => {
1634
1749
  pluginMgr.notifyAttach(cid);
1635
1750
  // 插件目录授权表(设置面板展示 + 可撤销)
1636
1751
  send({ type: "plugin_grants", grants: pluginMgr.grants.list() });
1752
+ // 插件能力授权表(设置面板展示 + 可撤销;session 授权带标记)
1753
+ send({ type: "plugin_permissions", grants: pluginMgr.permGrants.list() });
1637
1754
  // 插件命令可能在本客户端 attach 过程中才注册(首载竞态)——
1638
1755
  // 重推一次目录,保证选择器完整。
1639
1756
  service.applyPluginCommandCatalog();
@@ -1755,22 +1872,66 @@ if (BOOT_CATALOG_URL) {
1755
1872
  // Local control socket (status / quiesce / unquiesce) — same data dir the
1756
1873
  // CLI uses, so `pi-web-ui server status|quiesce|unquiesce` just works.
1757
1874
  const stopControl = startControlServer({ service, dataDir: DATA_DIR, port: PORT });
1875
+ /**
1876
+ * Graceful shutdown budget (issue #172): disposeAll() can hang forever on a
1877
+ * stuck session runtime / PTY / pending handle, and the process would then
1878
+ * sit forever with no way out. The watchdog guarantees the process is gone
1879
+ * within this long no matter what — unref'd so a clean shutdown never
1880
+ * waits on it.
1881
+ */
1882
+ const SHUTDOWN_FORCE_EXIT_MS = 5000;
1758
1883
  let shuttingDown = false;
1759
- async function shutdown() {
1760
- if (shuttingDown)
1761
- return;
1884
+ /**
1885
+ * SIGINT / SIGTERM handler. A second signal while a shutdown is already
1886
+ * running exits immediately (130 = killed by SIGINT, 143 = SIGTERM) instead
1887
+ * of being swallowed by the shuttingDown guard — previously a hung first
1888
+ * shutdown made Ctrl+C look completely dead (issue #172).
1889
+ */
1890
+ async function shutdown(signal = "SIGINT") {
1891
+ if (shuttingDown) {
1892
+ console.log("\n再次收到中断信号,强制退出…");
1893
+ process.exit(signal === "SIGTERM" ? 143 : 130);
1894
+ }
1762
1895
  shuttingDown = true;
1763
1896
  console.log("\nshutting down…");
1764
- clearInterval(heartbeatTimer);
1765
- stopControl();
1766
- pluginMgr.dispose();
1767
- pluginInstaller.dispose();
1768
- mcpHotReload.dispose();
1769
- mcpBridge.dispose();
1770
- await service.disposeAll();
1771
- wss.close();
1772
- httpServer.close();
1773
- process.exit(0);
1897
+ const forceExitTimer = setTimeout(() => {
1898
+ console.error("shutdown 超时仍未完成,强制退出…");
1899
+ process.exit(1);
1900
+ }, SHUTDOWN_FORCE_EXIT_MS);
1901
+ forceExitTimer.unref();
1902
+ let code = 0;
1903
+ try {
1904
+ clearInterval(heartbeatTimer);
1905
+ stopControl();
1906
+ pluginMgr.dispose();
1907
+ pluginInstaller.dispose();
1908
+ mcpHotReload.dispose();
1909
+ mcpBridge.dispose();
1910
+ await service.disposeAll();
1911
+ // Don't let dead browsers hold the exit open: half-open WebSocket /
1912
+ // keep-alive HTTP connections (e.g. test clients killed without
1913
+ // closing) would otherwise keep close() from ever finishing — drop
1914
+ // them first so shutdown stays prompt.
1915
+ for (const ws of wss.clients) {
1916
+ try {
1917
+ ws.terminate();
1918
+ }
1919
+ catch {
1920
+ /* already gone */
1921
+ }
1922
+ }
1923
+ wss.close();
1924
+ httpServer.closeAllConnections();
1925
+ httpServer.close();
1926
+ }
1927
+ catch (err) {
1928
+ code = 1;
1929
+ console.error("shutdown 释放资源时出错:", err);
1930
+ }
1931
+ finally {
1932
+ clearTimeout(forceExitTimer);
1933
+ process.exit(code);
1934
+ }
1774
1935
  }
1775
- process.on("SIGINT", () => void shutdown());
1776
- process.on("SIGTERM", () => void shutdown());
1936
+ process.on("SIGINT", () => void shutdown("SIGINT"));
1937
+ process.on("SIGTERM", () => void shutdown("SIGTERM"));