pi-web-ui 0.100.0 → 0.102.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 (82) hide show
  1. package/CHANGELOG.md +53 -1
  2. package/README.md +46 -44
  3. package/README.zh-CN.md +41 -39
  4. package/bin/pi-web-ui.mjs +17 -19
  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 +9884 -12815
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +41 -167
  10. package/dist/server/ask-user-question-tool.js +104 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/bash-tool.js +83 -0
  13. package/dist/server/browser-page-tool.js +207 -0
  14. package/dist/server/client-id-utils.js +51 -0
  15. package/dist/server/client-state.js +38 -2
  16. package/dist/server/compaction-markers.js +34 -1
  17. package/dist/server/context-budget-runner.js +43 -0
  18. package/dist/server/dangling-tools.js +18 -5
  19. package/dist/server/delegate-mode.js +1 -0
  20. package/dist/server/dispatch-domain-handlers.js +631 -0
  21. package/dist/server/dispatch-plugin-handlers.js +300 -0
  22. package/dist/server/dsh/dsh-agent-service.js +30 -5
  23. package/dist/server/dsh/runtime/goal-rpc.mjs +5 -1
  24. package/dist/server/goal-evidence.js +9 -2
  25. package/dist/server/goal-service.js +1 -1
  26. package/dist/server/hashline-engine.js +1 -1
  27. package/dist/server/index.js +191 -969
  28. package/dist/server/left-panel-running.js +115 -0
  29. package/dist/server/lsp-tool.js +40 -12
  30. package/dist/server/markers-list-tool.js +34 -0
  31. package/dist/server/market-service.js +277 -0
  32. package/dist/server/mcp-bridge.js +137 -30
  33. package/dist/server/mcp-hot-reload.js +84 -27
  34. package/dist/server/mcp-manager.js +215 -0
  35. package/dist/server/message-entry-resolver.js +32 -0
  36. package/dist/server/orphan-manager.js +44 -0
  37. package/dist/server/persona-chain.js +63 -0
  38. package/dist/server/plan-mode.js +2 -0
  39. package/dist/server/plan-update-tool.js +96 -0
  40. package/dist/server/plugin-api-catalog.js +20 -0
  41. package/dist/server/plugin-facilities.js +13 -3
  42. package/dist/server/plugin-installer.js +6 -1
  43. package/dist/server/plugin-ui-slots.js +39 -0
  44. package/dist/server/plugins.js +72 -38
  45. package/dist/server/preset-fields.js +35 -0
  46. package/dist/server/preset-share.js +9 -0
  47. package/dist/server/process-utils.js +30 -0
  48. package/dist/server/prompt-assembler.js +80 -0
  49. package/dist/server/protocol-version.js +1 -1
  50. package/dist/server/scm-commitmsg.js +74 -0
  51. package/dist/server/serialize.js +97 -7
  52. package/dist/server/session-branch.js +367 -0
  53. package/dist/server/session-parser.js +235 -0
  54. package/dist/server/session-search.js +158 -0
  55. package/dist/server/settings-service.js +28 -1
  56. package/dist/server/skill-content-filler.js +33 -0
  57. package/dist/server/subagent-handoff.js +18 -0
  58. package/dist/server/subagent-helpers.js +88 -0
  59. package/dist/server/terminals.js +155 -58
  60. package/dist/server/tool-guards.js +527 -0
  61. package/dist/server/tool-host-factories.js +217 -0
  62. package/dist/server/tool-manager.js +30 -5
  63. package/dist/server/wait-subscription-scan.js +46 -1
  64. package/dist/server/workspace-snapshot.js +18 -0
  65. package/extensions/webui.ts +90 -24
  66. package/package.json +1 -1
  67. package/plugin-sdk/README.md +17 -0
  68. package/plugin-sdk/index.d.ts +17 -0
  69. package/plugin-sdk/index.mjs +5 -0
  70. package/plugins/catalog.json +20 -0
  71. package/themes/aetheris.css +3 -1
  72. package/themes/translucent.css +8 -1
  73. package/themes/transparent.css +9 -1
  74. package/themes/zhupi-dark.css +3 -14
  75. package/themes/zhupi.css +2 -16
  76. package/web/dist/assets/{TerminalPanel-C3I1Mc-C.js → TerminalPanel-CYGOzbPT.js} +1 -1
  77. package/web/dist/assets/index-CP71PHb6.js +680 -0
  78. package/web/dist/assets/index-ytRwL6j0.css +1 -0
  79. package/web/dist/index.html +2 -2
  80. package/web/dist/sw.js +1 -1
  81. package/web/dist/assets/index-B-E2EM_0.css +0 -1
  82. package/web/dist/assets/index-BYumAaGi.js +0 -379
@@ -0,0 +1,217 @@
1
+ /**
2
+ * tool-host-factories — 自定义工具宿主适配器工厂。
3
+ *
4
+ * 为 schedule_*、conversation_read、claim_files、compact_context、skill 等自定义工具
5
+ * 提供纯净的宿主环境数据映射,隔离工具运行态接口与 ClientSession 内部会话存储。
6
+ *
7
+ * 从 agent-service.ts 抽出为独立模块。
8
+ */
9
+ import { readFileSync, statSync } from "node:fs";
10
+ import { resolve } from "node:path";
11
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
12
+ import { parseTranscriptLines } from "./conversation-read-tool.js";
13
+ import { readTouchSidecar } from "./claim-store.js";
14
+ import { MAX_TRANSCRIPT_SCAN_BYTES, piSessionsRoot } from "./session-search.js";
15
+ /** 创建 schedule_* 工具的数据宿主 */
16
+ export function createScheduleToolHost(ctx) {
17
+ return {
18
+ store: () => ctx.getSchedulerStore(),
19
+ cwd: () => ctx.getCwd(),
20
+ activeConversationId: () => ctx.getActiveId(),
21
+ conversationInfo: (id) => {
22
+ try {
23
+ const activeId = ctx.getActiveId();
24
+ const target = (id ?? "").trim() ? ctx.getConversation((id ?? "").trim()) : ctx.getConversation(activeId);
25
+ if (!target)
26
+ return undefined;
27
+ let sessionFile = "";
28
+ try {
29
+ sessionFile = String(target.session.sessionFile ?? "");
30
+ }
31
+ catch {
32
+ sessionFile = "";
33
+ }
34
+ return { cwd: target.cwd ?? ctx.getCwd(), sessionFile };
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ },
40
+ };
41
+ }
42
+ /** 创建 conversation_read 工具的数据宿主 */
43
+ export function createConversationReadHost(ctx) {
44
+ return {
45
+ listRunningConversations: () => {
46
+ const out = [];
47
+ for (const c of ctx.getConversations()) {
48
+ let messageCount = 0;
49
+ let isStreaming = false;
50
+ try {
51
+ messageCount = c.session.getSessionStats().totalMessages;
52
+ isStreaming = c.session.isStreaming;
53
+ }
54
+ catch {
55
+ // 会话替换中——报默认值
56
+ }
57
+ out.push({
58
+ id: c.id,
59
+ title: c.title,
60
+ cwd: c.cwd,
61
+ messageCount,
62
+ isStreaming,
63
+ isSubagent: !!c.isSubagent,
64
+ ...(c.parentId ? { parentId: c.parentId } : {}),
65
+ });
66
+ }
67
+ return out;
68
+ },
69
+ readRunningConversation: (id) => {
70
+ const c = ctx.getConversation(id);
71
+ if (!c)
72
+ return undefined;
73
+ return { title: c.title, cwd: c.cwd, isSubagent: !!c.isSubagent, messages: ctx.getConvTranscript(c) };
74
+ },
75
+ listHistorySessions: async (scope, cwd) => {
76
+ const infos = scope === "all"
77
+ ? await SessionManager.listAll(piSessionsRoot())
78
+ : await SessionManager.list(cwd || ctx.getCwd(), piSessionsRoot());
79
+ return infos.map((s) => ({
80
+ path: s.path,
81
+ name: s.name,
82
+ firstMessage: s.firstMessage,
83
+ messageCount: s.messageCount,
84
+ modified: s.modified.getTime(),
85
+ cwd: s.cwd,
86
+ }));
87
+ },
88
+ readTouchSidecar: (id, path) => {
89
+ try {
90
+ if (id) {
91
+ const c = ctx.getConversation(id);
92
+ let file;
93
+ try {
94
+ file = c?.session.sessionFile ?? undefined;
95
+ }
96
+ catch {
97
+ file = undefined;
98
+ }
99
+ return readTouchSidecar(file);
100
+ }
101
+ if (path)
102
+ return readTouchSidecar(path);
103
+ return undefined;
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ },
109
+ readHistorySession: async (path) => {
110
+ const all = await SessionManager.listAll(piSessionsRoot());
111
+ const norm = (p) => {
112
+ const r = resolve(p);
113
+ return process.platform === "win32" ? r.toLowerCase() : r;
114
+ };
115
+ const hit = all.find((s) => norm(s.path) === norm(path));
116
+ if (!hit)
117
+ return undefined;
118
+ try {
119
+ if (statSync(hit.path).size > MAX_TRANSCRIPT_SCAN_BYTES)
120
+ return undefined;
121
+ const text = readFileSync(hit.path, "utf8");
122
+ return {
123
+ title: hit.name || hit.firstMessage,
124
+ cwd: hit.cwd,
125
+ sessionPath: hit.path,
126
+ messages: parseTranscriptLines(text),
127
+ };
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ },
133
+ };
134
+ }
135
+ /** 创建 claim_files 工具的数据宿主 */
136
+ export function createClaimToolHost(ctx) {
137
+ const target = () => ctx.resolveTarget(ctx.ownerId);
138
+ return {
139
+ cwd: () => target()?.cwd ?? ctx.getCwd(),
140
+ self: () => {
141
+ const t = target();
142
+ return { convId: t?.id ?? ctx.getActiveId(), title: t?.title ?? "" };
143
+ },
144
+ store: () => ctx.getClaimStore(),
145
+ };
146
+ }
147
+ /** 创建 compact_context 工具的数据宿主 */
148
+ export function createCompactContextHost(ctx) {
149
+ const target = () => ctx.resolveTarget(ctx.ownerId);
150
+ return {
151
+ conversationId: () => target()?.id ?? ctx.getActiveId(),
152
+ getContextStats: () => {
153
+ const conv = target();
154
+ if (!conv)
155
+ return { messageCount: 0, estimatedTokens: 0 };
156
+ let messages = [];
157
+ try {
158
+ messages = conv.session.messages;
159
+ }
160
+ catch {
161
+ messages = [];
162
+ }
163
+ let totalChars = 0;
164
+ for (const m of messages) {
165
+ if (m && typeof m === "object" && "content" in m) {
166
+ const content = m.content;
167
+ if (Array.isArray(content)) {
168
+ for (const c of content) {
169
+ if (c &&
170
+ typeof c === "object" &&
171
+ "type" in c &&
172
+ c.type === "text" &&
173
+ typeof c.text === "string") {
174
+ totalChars += c.text.length;
175
+ }
176
+ }
177
+ }
178
+ else if (typeof content === "string") {
179
+ totalChars += content.length;
180
+ }
181
+ }
182
+ }
183
+ return {
184
+ messageCount: messages.length,
185
+ estimatedTokens: Math.ceil(totalChars / 4),
186
+ };
187
+ },
188
+ scheduleCompaction: (pending) => {
189
+ const conv = target();
190
+ if (conv) {
191
+ conv.pendingCompaction = pending;
192
+ }
193
+ },
194
+ };
195
+ }
196
+ /** 创建 skill 工具的数据宿主 */
197
+ export function createSkillToolHost(ctx) {
198
+ return {
199
+ listSkills: () => {
200
+ try {
201
+ const target = ctx.resolveTarget(ctx.ownerId);
202
+ const all = target?.session.resourceLoader.getSkills().skills ?? [];
203
+ const disabled = new Set(ctx.getDisabledSkills());
204
+ return all
205
+ .filter((s) => !disabled.has(s.name))
206
+ .map((s) => ({
207
+ name: s.name,
208
+ description: s.description ?? "",
209
+ filePath: s.filePath ?? "",
210
+ }));
211
+ }
212
+ catch {
213
+ return [];
214
+ }
215
+ },
216
+ };
217
+ }
@@ -79,6 +79,10 @@ export const COMPACT_CONTEXT_TOOL_NAME = "compact_context";
79
79
  export const PATCH_TOOL_NAME = "patch";
80
80
  /** 原生语言服务器工具(定义见 lsp-tool.ts):代码定义跳转、引用查询、类型悬停与诊断。 */
81
81
  export const LSP_TOOL_NAME = "lsp";
82
+ /** QuickJS WASM 沙箱代码执行与批量调用工具(SDK 内置 codemode 扩展)。 */
83
+ export const CODEMODE_TOOL_NAME = "codemode";
84
+ /** 基于 BM25 算法的延迟工具检索与激活工具(SDK 内置 tool-search 扩展)。 */
85
+ export const TOOL_SEARCH_TOOL_NAME = "tool_search";
82
86
  /** 按需加载工具(定义见 load-tools-tool.ts):延迟加载模式下模型的唯一入口 ——
83
87
  * 系统提示词只给全部工具的**名字 + 一行摘要**,模型先把要用的名字交给它,那些
84
88
  * 工具的完整参数 schema 才会进入会话(SDK 中途新增工具,支持 defer_loading /
@@ -88,7 +92,7 @@ export const LOAD_TOOLS_TOOL_NAME = "load_tools";
88
92
  export const LAZY_CORE_TOOL_NAMES = ["bash", "read", "edit", "write"];
89
93
  /** 旧工具名(持久化迁移用;新代码一律用 MARKERS_LIST_TOOL_NAME)。 */
90
94
  export const LEGACY_MARKERS_LIST_TOOL_NAME = "markers_list";
91
- /** 可开关的 Agent 工具总目录(共 23 个)。核心内置工具 bash/read/edit/write 不进
95
+ /** 可开关的 Agent 工具总目录(共 25 个)。核心内置工具 bash/read/edit/write 不进
92
96
  * 目录——目录条目 = OTHER_AGENT_TOOLS 自动渲染的设置行,而这四个在设置页
93
97
  * 「核心工具」区单独开关(见 SettingsModal 的 CORE_BUILTIN_TOOL_NAMES 区块),
94
98
  * 禁用名单同样接受它们(normalizeDisabledAgentTools)。 */
@@ -214,6 +218,24 @@ export const AGENT_TOOL_CATALOG = [
214
218
  descKey: "evalEnabledDesc",
215
219
  offHintKey: "evalOffHint",
216
220
  },
221
+ // QuickJS WASM 沙箱代码执行与批量调用工具:默认关(opt-in);DSH 引擎无此扩展。
222
+ {
223
+ name: CODEMODE_TOOL_NAME,
224
+ group: "other",
225
+ defaultOn: false,
226
+ dshVisible: false,
227
+ descKey: "codemodeEnabledDesc",
228
+ offHintKey: "codemodeOffHint",
229
+ },
230
+ // 基于 BM25 的延迟工具检索与激活(特别适用于大规模 MCP 场景):默认关(opt-in)。
231
+ {
232
+ name: TOOL_SEARCH_TOOL_NAME,
233
+ group: "other",
234
+ defaultOn: false,
235
+ dshVisible: false,
236
+ descKey: "toolSearchEnabledDesc",
237
+ offHintKey: "toolSearchOffHint",
238
+ },
217
239
  // 定时/延时唤醒(单 action:create/list/cancel):默认开(不打开 AI 根本不知道能定时;
218
240
  // 60s 间隔底线+面板可随时取消),DSH 引擎没有该 customTool(走 goal-rpc,无 customTool 注册面)。
219
241
  {
@@ -365,10 +387,12 @@ export function applyAgentToolsGating(session, disabled, preset, options) {
365
387
  for (const t of AGENT_TOOL_CATALOG) {
366
388
  if (off.has(t.name)) {
367
389
  // issue #481: 若第三方扩展注册了同名工具(如 nicobailon/pi-subagents 的 subagent),
368
- // 关闭内置工具时允许扩展工具透传,不从活跃名单删除
369
- const hasExtensionTool = Boolean(session?.extensionRunner
370
- ?.getAllRegisteredTools?.()
371
- ?.some((tool) => tool.definition?.name === t.name));
390
+ // 关闭内置工具时允许扩展工具透传,不从活跃名单删除;其余由扩展自身注册的工具(如 codemode)正常随禁用名单剔除
391
+ const isShadowedCustomTool = t.name === "subagent";
392
+ const hasExtensionTool = isShadowedCustomTool &&
393
+ Boolean(session?.extensionRunner
394
+ ?.getAllRegisteredTools?.()
395
+ ?.some((tool) => tool.definition?.name === t.name));
372
396
  if (!hasExtensionTool) {
373
397
  names.delete(t.name);
374
398
  }
@@ -530,6 +554,7 @@ export function filterToolsByPreset(tools, preset) {
530
554
  "terminal_input",
531
555
  "terminal_close",
532
556
  "terminal_key",
557
+ "codemode",
533
558
  ]);
534
559
  return all.filter((n) => !writeTools.has(n));
535
560
  }
@@ -236,11 +236,51 @@ export function hasPendingWaitSubscription(options) {
236
236
  }
237
237
  return false;
238
238
  }
239
+ /**
240
+ * 磁盘扫描:该会话在本进程里是否还有 running 的第三方后台任务(pi-background-tasks 的 bg_run)。
241
+ * 任务元数据位于 <cwd>/.pi/tasks/<会话UUID>-<pid>/<taskId>.json;本进程起的任务目录 pid
242
+ * 必为 process.pid,因此只看这一个目录——上次进程崩溃遗留的 status:"running" 不算活跃证据。
243
+ * 只要有 running 任务,移出/置换/切目录都会 dispose 运行时、把它 SIGTERM 掉且永不补通知(#576),
244
+ * 故与 pending wake 同级保留。任何 I/O / 解析错误按「无证据」处理(fail-open)。
245
+ */
246
+ export function hasRunningBackgroundTask(options) {
247
+ const { cwd, sessionFile } = options;
248
+ if (!cwd || !sessionFile)
249
+ return false;
250
+ const sessionUuid = path
251
+ .basename(sessionFile)
252
+ .replace(/\.jsonl$/i, "")
253
+ .split("_")
254
+ .pop();
255
+ if (!sessionUuid)
256
+ return false;
257
+ const ownDir = path.join(cwd, ".pi", "tasks", `${sessionUuid}-${options.pid ?? process.pid}`);
258
+ let files;
259
+ try {
260
+ files = readdirSync(ownDir);
261
+ }
262
+ catch {
263
+ return false; // 目录不存在 / 不可读 → 无证据
264
+ }
265
+ for (const f of files) {
266
+ if (!f.endsWith(".json"))
267
+ continue;
268
+ try {
269
+ const task = JSON.parse(readFileSync(path.join(ownDir, f), "utf-8"));
270
+ if (task && task.status === "running")
271
+ return true;
272
+ }
273
+ catch {
274
+ // 缺失 / 损坏 → 无证据(fail-open)
275
+ }
276
+ }
277
+ return false;
278
+ }
239
279
  /**
240
280
  * 纯函数版置换决策:true = 保留(不得 dispose),false = 调用方可释放。
241
281
  * Pure decision core of displaceActive(): true = retain, false = may dispose.
242
282
  * 顺序与 displaceActive 保持一致:pin → review/wizard → streaming → terminals →
243
- * active subagent run → pending wake → listed+continued(「打开后继续过」的会话也保留)。
283
+ * active subagent run → pending wake → running background task → listed+continued(「打开后继续过」的会话也保留)。
244
284
  */
245
285
  export function shouldRetainActive(input) {
246
286
  if (input.pinned)
@@ -259,6 +299,11 @@ export function shouldRetainActive(input) {
259
299
  const hasPendingWake = typeof input.hasPendingWake === "function" ? input.hasPendingWake() : input.hasPendingWake;
260
300
  if (hasPendingWake)
261
301
  return true;
302
+ const hasBgTask = typeof input.hasRunningBackgroundTask === "function"
303
+ ? input.hasRunningBackgroundTask()
304
+ : (input.hasRunningBackgroundTask ?? false);
305
+ if (hasBgTask)
306
+ return true;
262
307
  if (input.listed && input.promptedSinceActive)
263
308
  return true;
264
309
  return false;
@@ -142,3 +142,21 @@ export async function restoreWorkspaceSnapshot(cwd, snapshotRef) {
142
142
  return { success: false, error: msg };
143
143
  }
144
144
  }
145
+ /**
146
+ * 查找与指定消息 entryId/时间戳最匹配的工作区物理快照:
147
+ * 优先匹配 exact entryId,其次查找该 entry 时间戳之前(或 +2000ms 内)的最近一份快照。
148
+ */
149
+ export function findMatchingWorkspaceSnapshot(snapshots, entryId, entryTs = 0) {
150
+ if (!snapshots || snapshots.length === 0)
151
+ return undefined;
152
+ if (entryId) {
153
+ const exact = snapshots.find((s) => s.entryId === entryId);
154
+ if (exact)
155
+ return exact;
156
+ }
157
+ const eligible = snapshots.filter((s) => entryTs === 0 || s.timestamp <= entryTs + 2000);
158
+ if (eligible.length > 0) {
159
+ return eligible[eligible.length - 1];
160
+ }
161
+ return snapshots[0];
162
+ }
@@ -18,10 +18,10 @@
18
18
  */
19
19
 
20
20
  import { spawn, execSync } from "node:child_process";
21
- import { existsSync } from "node:fs";
21
+ import { closeSync, existsSync, mkdirSync, openSync } from "node:fs";
22
22
  import { homedir } from "node:os";
23
23
  import { dirname, join, resolve } from "node:path";
24
- import { fileURLToPath } from "node:url";
24
+ import { fileURLToPath, pathToFileURL } from "node:url";
25
25
  import net from "node:net";
26
26
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
27
27
 
@@ -92,11 +92,28 @@ interface RunningServer {
92
92
  port: number;
93
93
  cwd: string;
94
94
  url: string;
95
+ logFile?: string;
96
+ stop: () => void;
95
97
  }
96
98
 
97
99
  // 会话 → 运行实例(模块级 Map;每会话一个会话对象,无需清理全局)
98
100
  const running = new Map<string, RunningServer>();
99
101
 
102
+ /**
103
+ * 组装子进程参数。
104
+ * hookPath(resolve-global-sdk.js)必须以 file:// URL 形式传给 --import,
105
+ * 否则在 Windows 上传裸盘符路径(如 C:\...)会触发 Node ESM 的 ERR_UNSUPPORTED_ESM_URL_SCHEME 异常(issue #420 / #580)。
106
+ */
107
+ export function buildNodeArgs(
108
+ entry: string,
109
+ hookPath?: string,
110
+ hookExists = hookPath ? existsSync(hookPath) : false,
111
+ ): string[] {
112
+ return hookPath && hookExists ? ["--import", pathToFileURL(hookPath).href, entry] : [entry];
113
+ }
114
+
115
+ export { running };
116
+
100
117
  /** 找一个空闲端口 */
101
118
  function findFreePort(from = 8787): Promise<number> {
102
119
  return new Promise((resolve_, reject) => {
@@ -162,11 +179,13 @@ export default function (pi: ExtensionAPI): void {
162
179
  // 停止
163
180
  if (action === "stop" || action === "kill") {
164
181
  const inst = running.get(sid);
165
- if (!inst) {
182
+ const alive = inst && inst.proc.exitCode === null && inst.proc.signalCode === null;
183
+ if (!inst || !alive) {
184
+ running.delete(sid);
166
185
  ctx.ui.notify("没有正在运行的本机 pi-web-ui 服务器", "info");
167
186
  return;
168
187
  }
169
- inst.proc.kill("SIGTERM");
188
+ inst.stop();
170
189
  running.delete(sid);
171
190
  ctx.ui.notify(`已停止 pi-web-ui (${inst.url})`, "info");
172
191
  return;
@@ -179,13 +198,21 @@ export default function (pi: ExtensionAPI): void {
179
198
  ctx.ui.notify("本机 pi-web-ui 未运行", "info");
180
199
  return;
181
200
  }
182
- const alive = inst.proc.exitCode === null;
183
- ctx.ui.notify(
184
- alive
185
- ? `pi-web-ui 运行中 → ${inst.url}\n端口 ${inst.port} · cwd ${inst.cwd}`
186
- : `已退出(exit=${inst.proc.exitCode})`,
187
- alive ? "info" : "warning",
188
- );
201
+ const alive = inst.proc.exitCode === null && inst.proc.signalCode === null;
202
+ if (alive) {
203
+ ctx.ui.notify(
204
+ `pi-web-ui 运行中 → ${inst.url}\n端口 ${inst.port} · cwd ${inst.cwd}${inst.logFile ? `\n日志: ${inst.logFile}` : ""}`,
205
+ "info",
206
+ );
207
+ } else {
208
+ const exit =
209
+ inst.proc.exitCode !== null
210
+ ? `exit=${inst.proc.exitCode}`
211
+ : inst.proc.signalCode
212
+ ? `signal=${inst.proc.signalCode}`
213
+ : "unknown";
214
+ ctx.ui.notify(`pi-web-ui 已退出 (${exit})${inst.logFile ? ` · 日志: ${inst.logFile}` : ""}`, "warning");
215
+ }
189
216
  return;
190
217
  }
191
218
 
@@ -197,7 +224,7 @@ export default function (pi: ExtensionAPI): void {
197
224
 
198
225
  // 已运行则提示
199
226
  const existing = running.get(sid);
200
- if (existing && existing.proc.exitCode === null) {
227
+ if (existing && existing.proc.exitCode === null && existing.proc.signalCode === null) {
201
228
  ctx.ui.notify(`pi-web-ui 已在运行 → ${existing.url}`, "info");
202
229
  return;
203
230
  }
@@ -226,34 +253,73 @@ export default function (pi: ExtensionAPI): void {
226
253
  }
227
254
  } catch {}
228
255
 
256
+ const dataDir = process.env.PI_WEB_DATA_DIR ? resolve(process.env.PI_WEB_DATA_DIR) : join(cwd, ".pi-web");
229
257
  const env = {
230
258
  ...process.env,
231
259
  PORT: String(port),
232
260
  PI_WEB_PORT: String(port), // server/index.js 读取 PI_WEB_PORT
233
261
  PI_WEB_CWD: cwd,
234
262
  ...(hostSdkDir ? { PI_WEB_SDK_DIR: hostSdkDir } : {}),
235
- ...(process.env.PI_WEB_DATA_DIR ? {} : { PI_WEB_DATA_DIR: join(cwd, ".pi-web") }),
263
+ PI_WEB_DATA_DIR: dataDir,
236
264
  };
237
265
  const hookPath = join(PKG_ROOT, "dist", "server", "resolve-global-sdk.js");
238
- const nodeArgs = existsSync(hookPath) ? ["--import", hookPath, SERVER_ENTRY] : [SERVER_ENTRY];
266
+ const nodeArgs = buildNodeArgs(SERVER_ENTRY, hookPath);
267
+
268
+ let logFile: string | undefined;
269
+ let logFd: number | "ignore" = "ignore";
270
+ try {
271
+ mkdirSync(dataDir, { recursive: true });
272
+ logFile = join(dataDir, "webui.log");
273
+ logFd = openSync(logFile, "a");
274
+ } catch {
275
+ /* 无法创建日志目录或文件时静默回退 ignore */
276
+ }
277
+
239
278
  const proc = spawn(NODE, nodeArgs, {
240
279
  cwd,
241
280
  env,
242
- stdio: "ignore",
281
+ stdio: ["ignore", logFd, logFd],
243
282
  detached: process.platform !== "win32",
244
283
  windowsHide: true,
245
284
  });
285
+ if (typeof logFd === "number") {
286
+ try {
287
+ closeSync(logFd);
288
+ } catch {}
289
+ }
246
290
  proc.unref();
247
- running.set(sid, { proc, port, cwd, url });
248
291
 
249
- ctx.ui.notify(`pi-web-ui 启动中 → ${url}\n端口 ${port} · cwd ${cwd}\n(几秒后可用,/webui status 查看)`);
292
+ let stoppedManually = false;
293
+ const startTime = Date.now();
294
+ const inst: RunningServer = {
295
+ proc,
296
+ port,
297
+ cwd,
298
+ url,
299
+ logFile,
300
+ stop: () => {
301
+ stoppedManually = true;
302
+ proc.kill("SIGTERM");
303
+ },
304
+ };
305
+ running.set(sid, inst);
250
306
 
251
- if (!opts.noBrowser) await openBrowser(url);
307
+ proc.on("error", (err) => {
308
+ ctx.ui.notify(`pi-web-ui 启动失败: ${err.message}${logFile ? `\n日志: ${logFile}` : ""}`, "error");
309
+ });
252
310
 
253
- // 进程退出时清理
254
- proc.on("exit", () => {
255
- if (running.get(sid)?.proc === proc) running.delete(sid);
311
+ proc.on("exit", (code, signal) => {
312
+ const duration = Date.now() - startTime;
313
+ // 启动后 15 秒内非手动停止的异常退出,向用户告警
314
+ if (!stoppedManually && (code !== 0 || signal !== null) && duration < 15000) {
315
+ const reason = code !== null ? `exit=${code}` : `signal=${signal}`;
316
+ ctx.ui.notify(`pi-web-ui 启动异常退出 (${reason})。\n${logFile ? `查看日志: ${logFile}` : ""}`, "error");
317
+ }
256
318
  });
319
+
320
+ ctx.ui.notify(`pi-web-ui 启动中 → ${url}\n端口 ${port} · cwd ${cwd}\n(几秒后可用,/webui status 查看)`);
321
+
322
+ if (!opts.noBrowser) await openBrowser(url);
257
323
  },
258
324
  });
259
325
 
@@ -261,9 +327,9 @@ export default function (pi: ExtensionAPI): void {
261
327
  pi.on("session_shutdown", async (_event, ctx) => {
262
328
  const sid = ctx.sessionManager.getSessionId();
263
329
  const inst = running.get(sid);
264
- if (inst && inst.proc.exitCode === null) {
265
- inst.proc.kill("SIGTERM");
266
- running.delete(sid);
330
+ if (inst && inst.proc.exitCode === null && inst.proc.signalCode === null) {
331
+ inst.stop();
267
332
  }
333
+ running.delete(sid);
268
334
  });
269
335
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-ui",
3
- "version": "0.100.0",
3
+ "version": "0.102.0",
4
4
  "description": "Just open your browser to get all your work done — browser cockpit for AI coding agents (chat, code, files, terminal, Git in one tab)",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -129,6 +129,23 @@ describe("my-plugin", () => {
129
129
  | `schedule` 持久版(`{id, persistent, catchUp, label}`,落盘+补跑+进后台面板) | ✅ | — |
130
130
  | `host.requestPermission`(动态授权:net 补主机 / llm 限模型,用户逐条确认可记住) | ✅(基础族须已声明) | 确认框 + 设置面板「已授权能力」 |
131
131
 
132
+ ## 左栏运行条目:`host.leftPanel`(需要能力 `ui`)
133
+
134
+ 把「正在跑的事」登记到左栏「运行的对话」里,按插件分组显示(例如第三方子代理:谁在跑、进度多少)。
135
+ **只展示**:不是对话,没有停止按钮;点击条目时把 `action` 交给你的浏览器 bundle(`host.onUiAction`)。
136
+
137
+ ```js
138
+ // 整体替换本插件的条目;同时作为心跳(ttlMs 内不再调用 → 整组自动清空,缺省 60s,夹取 5s–1h)
139
+ host.leftPanel.setRunning(
140
+ [{ id: "sub-1", title: "代码审查", hint: "第 2/5 步", status: "running", icon: "🔍", action: "review:open" }],
141
+ { ttlMs: 30_000 },
142
+ );
143
+ host.leftPanel.clear(); // 立即清空
144
+ ```
145
+
146
+ `status`:`running`(进行中)/ `done` / `error`;缺省 `running`。`id` 在插件内唯一(重复的后者丢弃)。
147
+ 上限 50 条;超出、缺 id、非法字段都会丢弃并进入运行时诊断,不会抛错。
148
+
132
149
  ## 反激活与清理:`host.effect(label, dispose)`
133
150
 
134
151
  宿主的每个注册面(`ui.register` / `registerAgentTool` / `registerCommand` / `route` /
@@ -260,6 +260,23 @@ export interface PluginHost {
260
260
  error?: string;
261
261
  }>;
262
262
  };
263
+ /** P3:左栏「运行的对话」里的插件运行条目(仅展示,需要能力 "ui")。setRunning 整体替换本插件的
264
+ * 条目,同时作为心跳:超过 ttlMs(缺省 60 秒,夹取 5 秒–1 小时)没有再次调用就整组自动清空;
265
+ * clear() 立即清空;反激活时自动清空。item.action 点击时交给本插件浏览器 bundle 的 onUiAction。 */
266
+ leftPanel: {
267
+ setRunning(
268
+ items: Array<{
269
+ id: string;
270
+ title: string;
271
+ hint?: string;
272
+ status?: "running" | "done" | "error";
273
+ icon?: string;
274
+ action?: string;
275
+ }>,
276
+ opts?: { ttlMs?: number },
277
+ ): void;
278
+ clear(): void;
279
+ };
263
280
  /** 常驻后台任务(顶栏「后台任务」面板;返回 update/unregister)。 */
264
281
  registerBackgroundTask(task: { id: string; label: string; stop?: () => void; status?: string }): {
265
282
  update(next: Partial<{ label: string; status: string; stop: () => void }>): void;
@@ -407,6 +407,10 @@ export function createMockHost(overrides) {
407
407
  create: async () => ({ ok: false, error: "mock:未实现 project.create", log: [], dir: "" }),
408
408
  },
409
409
  registerBackgroundTask: () => ({ update: noop, unregister: noop }),
410
+ leftPanel: {
411
+ setRunning: noop,
412
+ clear: noop,
413
+ },
410
414
  getSettings: () => settingsState,
411
415
  onSettingsChanged: sub("onSettingsChanged"),
412
416
  scm: {
@@ -517,6 +521,7 @@ export function createMockHost(overrides) {
517
521
  "llm",
518
522
  "conversations",
519
523
  "ui",
524
+ "leftPanel",
520
525
  "storage",
521
526
  "secrets",
522
527
  "fs",