pi-web-ui 0.68.0 → 0.68.1

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.
@@ -36,7 +36,7 @@ import { startControlServer } from "./control-socket.js";
36
36
  import { scheduleUploadCleanup } from "./uploads.js";
37
37
  import { ensureWindowsBash, windowsBashDir } from "./ensure-bash.js";
38
38
  import { listThemes, resolveThemeFile } from "./themes.js";
39
- import { PluginManager, resolvePluginClientFile } from "./plugins.js";
39
+ import { PluginManager, resolvePluginClientFile, } from "./plugins.js";
40
40
  import { McpBridge } from "./mcp-bridge.js";
41
41
  /** 从 CLI 参数中取 flag 值:支持 --flag value 与 --flag=value 两种写法。
42
42
  * 让 `node dist/server/index.js --host 0.0.0.0 --port 9000` 这类直接启动也能生效,
@@ -447,6 +447,12 @@ void mcpBridge.load().then(() => {
447
447
  });
448
448
  // 插件扩展点:SDK 工具执行事件(bash/读文件等 start+end)转发给已注册的插件。
449
449
  service.onToolEvent = (ev) => pluginMgr.emitToolEvent(ev);
450
+ service.onRunEvent = (ev) => pluginMgr.emitRunEvent(ev);
451
+ // 插件扩展点:对话切换通知(轨迹视图切会话后即重拉;dsh 引擎暂无)。
452
+ service.onConversationChanged = () => pluginMgr.emitConversationChanged();
453
+ // 插件扩展点:当前打开对话的快照(轨迹视图直接显示打开对话的时间线;
454
+ // dsh 引擎无此方法时回退 null,插件显示空态)。
455
+ pluginMgr.conversationProvider = () => service.readConversationForPlugins?.() ?? null;
450
456
  // 插件扩展点:插件注册的 AI 工具(registerAgentTool)+ MCP 桥工具 → 会话创建时
451
457
  // 带上 + 变化时动态注入/移除已有会话。
452
458
  service.pluginToolsProvider = () => [...pluginMgr.getAgentTools(), ...mcpBridge.getTools()];
@@ -457,6 +457,50 @@ export class PluginManager {
457
457
  }
458
458
  }
459
459
  }
460
+ /** index.ts 注入:读取当前打开对话的快照(轨迹类插件经 host.getActiveConversation 调用)。 */
461
+ conversationProvider = undefined;
462
+ /** 当前打开对话的快照(无提供者/暂无对话时返回 null)。 */
463
+ getActiveConversation() {
464
+ try {
465
+ return this.conversationProvider?.() ?? null;
466
+ }
467
+ catch (err) {
468
+ console.error("[plugins] conversationProvider failed:", err);
469
+ return null;
470
+ }
471
+ }
472
+ /** agent-service 调:当前打开对话变了(切历史会话/切 running 对话/新对话)——
473
+ * 轨迹类插件靠它重拉时间线(异常隔离)。 */
474
+ emitConversationChanged() {
475
+ for (const p of this.loaded.values()) {
476
+ if (p.convChangeHandlers.size === 0)
477
+ continue;
478
+ for (const h of p.convChangeHandlers) {
479
+ try {
480
+ h();
481
+ }
482
+ catch (err) {
483
+ console.error(`[plugin:${p.info.id}] conversation-changed handler failed:`, err);
484
+ }
485
+ }
486
+ }
487
+ }
488
+ /** agent-service 调:把运行轨迹事件扇出给所有插件(异常隔离,
489
+ * 与 emitToolEvent 同级;订阅者崩了只记日志,不影响主流程)。 */
490
+ emitRunEvent(ev) {
491
+ for (const p of this.loaded.values()) {
492
+ if (p.runHandlers.size === 0)
493
+ continue;
494
+ for (const h of p.runHandlers) {
495
+ try {
496
+ h(ev);
497
+ }
498
+ catch (err) {
499
+ console.error(`[plugin:${p.info.id}] run-event handler failed:`, err);
500
+ }
501
+ }
502
+ }
503
+ }
460
504
  /** 当前全部插件注册的 AI 工具(扁平化,按插件 id 稳定排序)。 */
461
505
  getAgentTools() {
462
506
  const out = [];
@@ -697,6 +741,8 @@ export class PluginManager {
697
741
  const handlers = new Set();
698
742
  this.messageHandlers.set(info.id, handlers);
699
743
  const toolHandlers = new Set();
744
+ const runHandlers = new Set();
745
+ const convChangeHandlers = new Set();
700
746
  const attachHandlers = new Set();
701
747
  const cwdHandlers = new Set();
702
748
  const httpRoutes = new Map();
@@ -717,6 +763,8 @@ export class PluginManager {
717
763
  this.loaded.set(info.id, {
718
764
  info: { ...info, error: msg },
719
765
  toolHandlers,
766
+ runHandlers,
767
+ convChangeHandlers,
720
768
  attachHandlers,
721
769
  cwdHandlers,
722
770
  httpRoutes,
@@ -732,6 +780,8 @@ export class PluginManager {
732
780
  const p = {
733
781
  info,
734
782
  toolHandlers,
783
+ runHandlers,
784
+ convChangeHandlers,
735
785
  attachHandlers,
736
786
  cwdHandlers,
737
787
  commandUnsubscribers: unregisterCommands,
@@ -774,6 +824,15 @@ export class PluginManager {
774
824
  toolHandlers.add(h);
775
825
  return () => toolHandlers.delete(h);
776
826
  },
827
+ onRunEvent: (h) => {
828
+ runHandlers.add(h);
829
+ return () => runHandlers.delete(h);
830
+ },
831
+ onConversationChanged: (h) => {
832
+ convChangeHandlers.add(h);
833
+ return () => convChangeHandlers.delete(h);
834
+ },
835
+ getActiveConversation: () => self.getActiveConversation(),
777
836
  onAttach: (h) => {
778
837
  attachHandlers.add(h);
779
838
  return () => attachHandlers.delete(h);
@@ -893,6 +952,8 @@ export class PluginManager {
893
952
  info: { ...info },
894
953
  deactivate: typeof ret === "function" ? ret : undefined,
895
954
  toolHandlers,
955
+ runHandlers,
956
+ convChangeHandlers,
896
957
  attachHandlers,
897
958
  cwdHandlers,
898
959
  agentToolUnsubscribers: unregisterTools,
@@ -911,6 +972,8 @@ export class PluginManager {
911
972
  this.loaded.set(info.id, {
912
973
  info: { ...info, error: err.message },
913
974
  toolHandlers,
975
+ runHandlers,
976
+ convChangeHandlers,
914
977
  attachHandlers,
915
978
  cwdHandlers,
916
979
  httpRoutes,
@@ -59,6 +59,30 @@ function serializeAssistantContent(content) {
59
59
  return { type: "unknown", ...b };
60
60
  });
61
61
  }
62
+ /**
63
+ * Hide transient LLM failures while an auto-retry is pending.
64
+ *
65
+ * The SDK finalizes the failed assistant message (message_end, then agent_end
66
+ * with willRetry) BEFORE it slices the message out of state and backs off, so
67
+ * a snapshot taken in between would paint a red error that vanishes one frame
68
+ * later. While `retryActive` the trailing stopReason=error assistant messages
69
+ * are intermediate state: dropped here (retry success → the user never sees
70
+ * them; exhaustion → auto_retry_end clears the flag and the message renders
71
+ * red permanently). Non-trailing content is never touched.
72
+ */
73
+ export function stripTransientRetryErrors(messages, retryActive) {
74
+ if (!retryActive)
75
+ return messages;
76
+ let end = messages.length;
77
+ while (end > 0) {
78
+ const m = messages[end - 1];
79
+ if (m.role === "assistant" && m.stopReason === "error")
80
+ end -= 1;
81
+ else
82
+ break;
83
+ }
84
+ return end === messages.length ? messages : messages.slice(0, end);
85
+ }
62
86
  export function serializeMessage(m, seq) {
63
87
  switch (m.role) {
64
88
  case "user":
@@ -35,15 +35,15 @@ export function findVisionModels(runtime) {
35
35
  * Exported so the settings panel can offer a custom prompt (append to this
36
36
  * default or replace it entirely).
37
37
  */
38
- export const SYSTEM_PROMPT = `You are a vision bridge for a text-only language model. You receive one or more images and must transcribe them into precise, structured text evidence so another model that cannot see images can answer questions about them accurately.
39
-
40
- Follow these rules:
41
- 1. Transcribe ALL visible text verbatim, preserving wording, spelling, punctuation and line breaks. This is the most important part — the reader relies on your transcription, not on the image.
42
- 2. Describe the layout in reading order: headers, paragraphs, lists, tables, buttons, panels — say what appears where.
43
- 3. For tables/charts/diagrams: read axes, scales (note log scale), legend entries, series names, highlighted points and their coordinates, and any data values you can discern.
44
- 4. Name entities: people, products, companies, colors, style, objects, actions.
45
- 5. If part of the image is too blurry/low-resolution to read, say "(读不清)" or "unclear" for that part — NEVER invent or guess content you cannot see.
46
- 6. If there are multiple images, address them in order (图 1 / Image 1, 图 2 / Image 2, ...).
38
+ export const SYSTEM_PROMPT = `You are a vision bridge for a text-only language model. You receive one or more images and must transcribe them into precise, structured text evidence so another model that cannot see images can answer questions about them accurately.
39
+
40
+ Follow these rules:
41
+ 1. Transcribe ALL visible text verbatim, preserving wording, spelling, punctuation and line breaks. This is the most important part — the reader relies on your transcription, not on the image.
42
+ 2. Describe the layout in reading order: headers, paragraphs, lists, tables, buttons, panels — say what appears where.
43
+ 3. For tables/charts/diagrams: read axes, scales (note log scale), legend entries, series names, highlighted points and their coordinates, and any data values you can discern.
44
+ 4. Name entities: people, products, companies, colors, style, objects, actions.
45
+ 5. If part of the image is too blurry/low-resolution to read, say "(读不清)" or "unclear" for that part — NEVER invent or guess content you cannot see.
46
+ 6. If there are multiple images, address them in order (图 1 / Image 1, 图 2 / Image 2, ...).
47
47
  7. Output only the transcript. No preamble, no commentary about the image itself.`;
48
48
  /**
49
49
  * Assemble the final vision-model system prompt from the settings-panel prefs.
@@ -1,190 +1,190 @@
1
- /**
2
- * pi-web-ui 的 pi 扩展 —— 提供命令行集成。
3
- *
4
- * 能力:
5
- * /webui 启动本机 pi-web-ui 服务器,打开浏览器访问
6
- * /webui --port 9000 指定端口启动
7
- * /webui --no-browser 启动但不开浏览器
8
- * /webui stop 停止已启动的服务器
9
- * /webui status 查看运行状态 / URL
10
- *
11
- * 实现说明:
12
- * - 不依赖全局 bin(pi install 后 pi-web-ui 命令不一定在 PATH),直接用
13
- * node 调包内 dist/server/index.js,通过环境变量 PORT / PI_WEB_CWD /
14
- * PI_WEB_DATA_DIR 控制。
15
- * - 工作目录默认用当前 pi 会话的 ctx.cwd;可用 --cwd / path 覆盖。
16
- * - 服务器作为子进程后台运行,/webui 不阻塞 pi。
17
- * - 每个 pi 会话管理一个子进程;session_shutdown 时清理,避免孤儿进程。
18
- */
19
-
20
- import { spawn } from "node:child_process";
21
- import { existsSync } from "node:fs";
22
- import { dirname, join, resolve } from "node:path";
23
- import { fileURLToPath } from "node:url";
24
- import net from "node:net";
25
- import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
26
-
27
- // 本文件位于 <pkg>/extensions/webui.ts → 包根在上一级
28
- const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
29
- const SERVER_ENTRY = join(PKG_ROOT, "dist", "server", "index.js");
30
- const NODE = process.execPath;
31
-
32
- /** 每个会话的服务器子进程 + 元数据 */
33
- interface RunningServer {
34
- proc: ReturnType<typeof spawn>;
35
- port: number;
36
- cwd: string;
37
- url: string;
38
- }
39
-
40
- // 会话 → 运行实例(模块级 Map;每会话一个会话对象,无需清理全局)
41
- const running = new Map<string, RunningServer>();
42
-
43
- /** 找一个空闲端口 */
44
- function findFreePort(from = 8787): Promise<number> {
45
- return new Promise((resolve_, reject) => {
46
- const srv = net.createServer();
47
- srv.listen(from, () => {
48
- const port = (srv.address() as net.AddressInfo).port;
49
- srv.close(() => resolve_(port));
50
- });
51
- srv.on("error", () => {
52
- // 端口被占则顺延
53
- findFreePort(from + 1).then(resolve_, reject);
54
- });
55
- });
56
- }
57
-
58
- /** 解析 --key value / --flag 参数 */
59
- function parseArgs(args: string): { port?: number; cwd?: string; noBrowser: boolean } {
60
- const out: { port?: number; cwd?: string; noBrowser: boolean } = { noBrowser: false };
61
- const toks = args.split(/\s+/).filter(Boolean);
62
- for (let i = 0; i < toks.length; i++) {
63
- const t = toks[i];
64
- if ((t === "--port" || t === "-p") && toks[i + 1]) {
65
- const n = Number(toks[++i]);
66
- if (Number.isInteger(n) && n > 0 && n < 65536) out.port = n;
67
- } else if (t === "--cwd" && toks[i + 1]) {
68
- out.cwd = resolve(toks[++i]);
69
- } else if (t === "--no-browser") {
70
- out.noBrowser = true;
71
- }
72
- }
73
- return out;
74
- }
75
-
76
- /** 打开浏览器 */
77
- async function openBrowser(url: string): Promise<void> {
78
- const { platform } = process;
79
- const [cmd, ...rest] =
80
- platform === "darwin" ? ["open", url] : platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
81
- // 无界面环境缺少 xdg-open 等打开器时,ENOENT 以异步 'error' 事件触发,
82
- // try/catch 拦不住会崩掉整个进程 —— 必须挂 error 监听。
83
- spawn(cmd, rest, { stdio: "ignore", detached: true })
84
- .on("error", (err) => {
85
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
86
- console.warn(
87
- `[webui] 未找到浏览器打开器 (${(err as NodeJS.ErrnoException).path || "command not found"}),请用 --no-browser 关闭自动打开`,
88
- );
89
- } else {
90
- console.warn("[webui] 打开浏览器失败:", err.message);
91
- }
92
- })
93
- .unref();
94
- }
95
-
96
- export default function (pi: ExtensionAPI): void {
97
- pi.registerCommand("webui", {
98
- description: "启动本机 pi-web-ui Web 界面(/webui [--port N] [--cwd PATH] [--no-browser] | stop | status)",
99
- handler: async (args: string, ctx: ExtensionCommandContext) => {
100
- const sid = ctx.sessionManager.getSessionId();
101
- const opts = parseArgs(args);
102
- const action = (args.split(/\s+/)[0] || "start").toLowerCase();
103
-
104
- // 停止
105
- if (action === "stop" || action === "kill") {
106
- const inst = running.get(sid);
107
- if (!inst) {
108
- ctx.ui.notify("没有正在运行的本机 pi-web-ui 服务器", "info");
109
- return;
110
- }
111
- inst.proc.kill("SIGTERM");
112
- running.delete(sid);
113
- ctx.ui.notify(`已停止 pi-web-ui (${inst.url})`, "info");
114
- return;
115
- }
116
-
117
- // 状态
118
- if (action === "status") {
119
- const inst = running.get(sid);
120
- if (!inst) {
121
- ctx.ui.notify("本机 pi-web-ui 未运行", "info");
122
- return;
123
- }
124
- const alive = inst.proc.exitCode === null;
125
- ctx.ui.notify(
126
- alive
127
- ? `pi-web-ui 运行中 → ${inst.url}\n端口 ${inst.port} · cwd ${inst.cwd}`
128
- : `已退出(exit=${inst.proc.exitCode})`,
129
- alive ? "info" : "warning",
130
- );
131
- return;
132
- }
133
-
134
- // 默认 start
135
- if (action !== "start" && action !== "run") {
136
- ctx.ui.notify(`未知动作 ${action}(可用 start|stop|status)`, "warning");
137
- return;
138
- }
139
-
140
- // 已运行则提示
141
- const existing = running.get(sid);
142
- if (existing && existing.proc.exitCode === null) {
143
- ctx.ui.notify(`pi-web-ui 已在运行 → ${existing.url}`, "info");
144
- return;
145
- }
146
-
147
- // 检查是否已构建
148
- if (!existsSync(SERVER_ENTRY)) {
149
- ctx.ui.notify(
150
- "缺少 dist/ 产物(当前安装未包含已构建前端)。请运行 `npm run build` 后重试,或用 pi-web-ui 官方 npm 包。",
151
- "warning",
152
- );
153
- return;
154
- }
155
-
156
- const port = opts.port ?? (await findFreePort());
157
- const cwd = opts.cwd ?? ctx.cwd;
158
- const url = `http://localhost:${port}`;
159
-
160
- const env = {
161
- ...process.env,
162
- PORT: String(port),
163
- PI_WEB_CWD: cwd,
164
- ...(process.env.PI_WEB_DATA_DIR ? {} : { PI_WEB_DATA_DIR: join(cwd, ".pi-web") }),
165
- };
166
- const proc = spawn(NODE, [SERVER_ENTRY], { cwd, env, stdio: "ignore", detached: true });
167
- proc.unref();
168
- running.set(sid, { proc, port, cwd, url });
169
-
170
- ctx.ui.notify(`pi-web-ui 启动中 → ${url}\n端口 ${port} · cwd ${cwd}\n(几秒后可用,/webui status 查看)`);
171
-
172
- if (!opts.noBrowser) await openBrowser(url);
173
-
174
- // 进程退出时清理
175
- proc.on("exit", () => {
176
- if (running.get(sid)?.proc === proc) running.delete(sid);
177
- });
178
- },
179
- });
180
-
181
- // 会话结束清理子进程,避免孤儿
182
- pi.on("session_shutdown", async (_event, ctx) => {
183
- const sid = ctx.sessionManager.getSessionId();
184
- const inst = running.get(sid);
185
- if (inst && inst.proc.exitCode === null) {
186
- inst.proc.kill("SIGTERM");
187
- running.delete(sid);
188
- }
189
- });
190
- }
1
+ /**
2
+ * pi-web-ui 的 pi 扩展 —— 提供命令行集成。
3
+ *
4
+ * 能力:
5
+ * /webui 启动本机 pi-web-ui 服务器,打开浏览器访问
6
+ * /webui --port 9000 指定端口启动
7
+ * /webui --no-browser 启动但不开浏览器
8
+ * /webui stop 停止已启动的服务器
9
+ * /webui status 查看运行状态 / URL
10
+ *
11
+ * 实现说明:
12
+ * - 不依赖全局 bin(pi install 后 pi-web-ui 命令不一定在 PATH),直接用
13
+ * node 调包内 dist/server/index.js,通过环境变量 PORT / PI_WEB_CWD /
14
+ * PI_WEB_DATA_DIR 控制。
15
+ * - 工作目录默认用当前 pi 会话的 ctx.cwd;可用 --cwd / path 覆盖。
16
+ * - 服务器作为子进程后台运行,/webui 不阻塞 pi。
17
+ * - 每个 pi 会话管理一个子进程;session_shutdown 时清理,避免孤儿进程。
18
+ */
19
+
20
+ import { spawn } from "node:child_process";
21
+ import { existsSync } from "node:fs";
22
+ import { dirname, join, resolve } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import net from "node:net";
25
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
26
+
27
+ // 本文件位于 <pkg>/extensions/webui.ts → 包根在上一级
28
+ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
29
+ const SERVER_ENTRY = join(PKG_ROOT, "dist", "server", "index.js");
30
+ const NODE = process.execPath;
31
+
32
+ /** 每个会话的服务器子进程 + 元数据 */
33
+ interface RunningServer {
34
+ proc: ReturnType<typeof spawn>;
35
+ port: number;
36
+ cwd: string;
37
+ url: string;
38
+ }
39
+
40
+ // 会话 → 运行实例(模块级 Map;每会话一个会话对象,无需清理全局)
41
+ const running = new Map<string, RunningServer>();
42
+
43
+ /** 找一个空闲端口 */
44
+ function findFreePort(from = 8787): Promise<number> {
45
+ return new Promise((resolve_, reject) => {
46
+ const srv = net.createServer();
47
+ srv.listen(from, () => {
48
+ const port = (srv.address() as net.AddressInfo).port;
49
+ srv.close(() => resolve_(port));
50
+ });
51
+ srv.on("error", () => {
52
+ // 端口被占则顺延
53
+ findFreePort(from + 1).then(resolve_, reject);
54
+ });
55
+ });
56
+ }
57
+
58
+ /** 解析 --key value / --flag 参数 */
59
+ function parseArgs(args: string): { port?: number; cwd?: string; noBrowser: boolean } {
60
+ const out: { port?: number; cwd?: string; noBrowser: boolean } = { noBrowser: false };
61
+ const toks = args.split(/\s+/).filter(Boolean);
62
+ for (let i = 0; i < toks.length; i++) {
63
+ const t = toks[i];
64
+ if ((t === "--port" || t === "-p") && toks[i + 1]) {
65
+ const n = Number(toks[++i]);
66
+ if (Number.isInteger(n) && n > 0 && n < 65536) out.port = n;
67
+ } else if (t === "--cwd" && toks[i + 1]) {
68
+ out.cwd = resolve(toks[++i]);
69
+ } else if (t === "--no-browser") {
70
+ out.noBrowser = true;
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /** 打开浏览器 */
77
+ async function openBrowser(url: string): Promise<void> {
78
+ const { platform } = process;
79
+ const [cmd, ...rest] =
80
+ platform === "darwin" ? ["open", url] : platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
81
+ // 无界面环境缺少 xdg-open 等打开器时,ENOENT 以异步 'error' 事件触发,
82
+ // try/catch 拦不住会崩掉整个进程 —— 必须挂 error 监听。
83
+ spawn(cmd, rest, { stdio: "ignore", detached: true })
84
+ .on("error", (err) => {
85
+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
86
+ console.warn(
87
+ `[webui] 未找到浏览器打开器 (${(err as NodeJS.ErrnoException).path || "command not found"}),请用 --no-browser 关闭自动打开`,
88
+ );
89
+ } else {
90
+ console.warn("[webui] 打开浏览器失败:", err.message);
91
+ }
92
+ })
93
+ .unref();
94
+ }
95
+
96
+ export default function (pi: ExtensionAPI): void {
97
+ pi.registerCommand("webui", {
98
+ description: "启动本机 pi-web-ui Web 界面(/webui [--port N] [--cwd PATH] [--no-browser] | stop | status)",
99
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
100
+ const sid = ctx.sessionManager.getSessionId();
101
+ const opts = parseArgs(args);
102
+ const action = (args.split(/\s+/)[0] || "start").toLowerCase();
103
+
104
+ // 停止
105
+ if (action === "stop" || action === "kill") {
106
+ const inst = running.get(sid);
107
+ if (!inst) {
108
+ ctx.ui.notify("没有正在运行的本机 pi-web-ui 服务器", "info");
109
+ return;
110
+ }
111
+ inst.proc.kill("SIGTERM");
112
+ running.delete(sid);
113
+ ctx.ui.notify(`已停止 pi-web-ui (${inst.url})`, "info");
114
+ return;
115
+ }
116
+
117
+ // 状态
118
+ if (action === "status") {
119
+ const inst = running.get(sid);
120
+ if (!inst) {
121
+ ctx.ui.notify("本机 pi-web-ui 未运行", "info");
122
+ return;
123
+ }
124
+ const alive = inst.proc.exitCode === null;
125
+ ctx.ui.notify(
126
+ alive
127
+ ? `pi-web-ui 运行中 → ${inst.url}\n端口 ${inst.port} · cwd ${inst.cwd}`
128
+ : `已退出(exit=${inst.proc.exitCode})`,
129
+ alive ? "info" : "warning",
130
+ );
131
+ return;
132
+ }
133
+
134
+ // 默认 start
135
+ if (action !== "start" && action !== "run") {
136
+ ctx.ui.notify(`未知动作 ${action}(可用 start|stop|status)`, "warning");
137
+ return;
138
+ }
139
+
140
+ // 已运行则提示
141
+ const existing = running.get(sid);
142
+ if (existing && existing.proc.exitCode === null) {
143
+ ctx.ui.notify(`pi-web-ui 已在运行 → ${existing.url}`, "info");
144
+ return;
145
+ }
146
+
147
+ // 检查是否已构建
148
+ if (!existsSync(SERVER_ENTRY)) {
149
+ ctx.ui.notify(
150
+ "缺少 dist/ 产物(当前安装未包含已构建前端)。请运行 `npm run build` 后重试,或用 pi-web-ui 官方 npm 包。",
151
+ "warning",
152
+ );
153
+ return;
154
+ }
155
+
156
+ const port = opts.port ?? (await findFreePort());
157
+ const cwd = opts.cwd ?? ctx.cwd;
158
+ const url = `http://localhost:${port}`;
159
+
160
+ const env = {
161
+ ...process.env,
162
+ PORT: String(port),
163
+ PI_WEB_CWD: cwd,
164
+ ...(process.env.PI_WEB_DATA_DIR ? {} : { PI_WEB_DATA_DIR: join(cwd, ".pi-web") }),
165
+ };
166
+ const proc = spawn(NODE, [SERVER_ENTRY], { cwd, env, stdio: "ignore", detached: true });
167
+ proc.unref();
168
+ running.set(sid, { proc, port, cwd, url });
169
+
170
+ ctx.ui.notify(`pi-web-ui 启动中 → ${url}\n端口 ${port} · cwd ${cwd}\n(几秒后可用,/webui status 查看)`);
171
+
172
+ if (!opts.noBrowser) await openBrowser(url);
173
+
174
+ // 进程退出时清理
175
+ proc.on("exit", () => {
176
+ if (running.get(sid)?.proc === proc) running.delete(sid);
177
+ });
178
+ },
179
+ });
180
+
181
+ // 会话结束清理子进程,避免孤儿
182
+ pi.on("session_shutdown", async (_event, ctx) => {
183
+ const sid = ctx.sessionManager.getSessionId();
184
+ const inst = running.get(sid);
185
+ if (inst && inst.proc.exitCode === null) {
186
+ inst.proc.kill("SIGTERM");
187
+ running.delete(sid);
188
+ }
189
+ });
190
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-ui",
3
- "version": "0.68.0",
3
+ "version": "0.68.1",
4
4
  "description": "Web chat interface for the pi coding agent, powered by the pi SDK (@earendil-works/pi-coding-agent) — one-command run, Docker/systemd/launchd deployable",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -51,11 +51,12 @@
51
51
  "dev": "concurrently -k -n server,web -c blue,green \"npm:dev:server\" \"npm:dev:web\"",
52
52
  "dev:server": "cross-env PI_WEB_PORT=8788 PI_WEB_ALLOW_ORIGINS=http://localhost:5173,http://127.0.0.1:5173 node --watch --import tsx server/index.ts",
53
53
  "dev:web": "vite --config web/vite.config.ts",
54
- "build": "npm run build:web && npm run build:server && npm run build:dsh-runtime && npm run build:mermaid-vendor",
54
+ "build": "npm run build:web && npm run build:server && npm run build:dsh-runtime && npm run build:mermaid-vendor && npm run build:runtrace-vendor",
55
55
  "build:web": "vite build --config web/vite.config.ts",
56
56
  "build:server": "tsc -p tsconfig.server.json",
57
57
  "build:dsh-runtime": "node scripts/copy-dsh-runtime.mjs",
58
58
  "build:mermaid-vendor": "node scripts/build-mermaid-vendor.mjs",
59
+ "build:runtrace-vendor": "node scripts/build-runtrace-vendor.mjs",
59
60
  "typecheck": "tsc -p tsconfig.server.json --noEmit && tsc -p web/tsconfig.json --noEmit && tsc -p tsconfig.tests.json --noEmit",
60
61
  "test": "vitest run",
61
62
  "test:unit": "vitest run",
@@ -104,6 +105,7 @@
104
105
  "prettier": "^3.9.6",
105
106
  "tsx": "^4.19.2",
106
107
  "typescript": "^5.7.2",
108
+ "vis-timeline": "^8.5.4",
107
109
  "vite": "^6.0.3",
108
110
  "vitest": "^4.1.11"
109
111
  },
@@ -34,5 +34,14 @@
34
34
  "descriptionEn": "Renders ```mermaid fences in messages to SVG diagrams (fenced-code renderer plugin, offline-first local engine).",
35
35
  "source": "xing-shuyin/pi-web-ui/plugins/mermaid",
36
36
  "homepage": "https://github.com/xing-shuyin/pi-web-ui/tree/main/plugins/mermaid"
37
+ },
38
+ {
39
+ "id": "run-trace",
40
+ "name": "run-trace",
41
+ "icon": "🧭",
42
+ "description": "运行轨迹:任务 → 思考 → 工具 → 文件改动 → 结果的时间线聚合视图,支持回放与节点详情。",
43
+ "descriptionEn": "Run trajectory: task → thinking → tools → file changes → result timeline with replay and node details.",
44
+ "source": "xing-shuyin/pi-web-ui/plugins/run-trace",
45
+ "homepage": "https://github.com/xing-shuyin/pi-web-ui/tree/main/plugins/run-trace"
37
46
  }
38
47
  ]
@@ -1,4 +1,4 @@
1
- import{a as l,j as n}from"./markdown-DRBrS2Nf.js";import{u as O,b as M,T as z,a as W,F as Y,c as H,d as Z,e as q,f as ee,g as ne,h as te,i as se,r as ae}from"./index-fwF-jmiV.js";import{D as re,o as ie}from"./xterm-D1D2FVe3.js";import"./react-C9ovnpIm.js";function le(t){let c=null;return{clean:t.replace(/\r?\n?\[pi-term-exit:(-?\d+)\]\r?\n?/g,(a,h)=>(c=Number(h),`\r
1
+ import{a as l,j as n}from"./markdown-DRBrS2Nf.js";import{u as O,b as M,T as z,a as W,F as Y,c as H,d as Z,e as q,f as ee,g as ne,h as te,i as se,r as ae}from"./index-qoTr5KXy.js";import{D as re,o as ie}from"./xterm-D1D2FVe3.js";import"./react-C9ovnpIm.js";function le(t){let c=null;return{clean:t.replace(/\r?\n?\[pi-term-exit:(-?\d+)\]\r?\n?/g,(a,h)=>(c=Number(h),`\r
2
2
  `)).replace(/\r?\n?\x1b\[90m\[(?:进程已退出,退出码 |Process exited with code )-?\d+\]\x1b\[0m\r?\n?/g,`\r
3
3
  `),exitCode:c}}function ce({conversationId:t,terminalId:c,command:f,cwd:a,title:h,active:u,running:b,exitCode:y,send:j,register:T}){const k=l.useRef(null),N=l.useRef(null),{locale:o}=O(),w=l.useRef(o);w.current=o;const F=f?JSON.stringify(f):"";l.useEffect(()=>{const m=k.current;if(!m)return;const r=new re({theme:M(),fontFamily:'"SF Mono", "JetBrains Mono", ui-monospace, Menlo, Consolas, monospace',fontSize:13,cursorBlink:!0,scrollback:8e3}),g=new ie;r.loadAddon(g),r.open(m),N.current={term:r,fit:g},u&&r.focus();const C=()=>{r.options.theme=M()};window.addEventListener(z,C),r.attachCustomKeyEventHandler(d=>{var A;if(d.type!=="keydown")return!0;const D=(A=d.key)==null?void 0:A.toLowerCase();if((d.ctrlKey||d.metaKey)&&D==="v")return!1;if(d.ctrlKey&&!d.shiftKey&&!d.altKey&&D==="c"&&r.hasSelection()){const E=r.textarea;return E&&(E.value=r.getSelection(),E.select()),!1}return!0});const _=T(t,c,{write:d=>r.write(le(d).clean),dispose:()=>r.dispose()}),$=()=>{try{g.fit(),j({type:"terminal_resize",terminalId:c,conversationId:t,cols:r.cols,rows:r.rows})}catch{}},B=requestAnimationFrame(()=>{try{g.fit()}catch{}j(f?{type:"run_command",terminalId:c,conversationId:t,command:f,cols:r.cols,rows:r.rows}:{type:"terminal_create",terminalId:c,title:h,locale:w.current,conversationId:t,cwd:a,cols:r.cols,rows:r.rows})}),S=r.onData(d=>{j({type:"terminal_input",terminalId:c,conversationId:t,data:d})});let v=null;return typeof ResizeObserver<"u"&&(v=new ResizeObserver(()=>{m.offsetWidth>0&&m.offsetHeight>0&&$()}),v.observe(m)),()=>{cancelAnimationFrame(B),S.dispose(),window.removeEventListener(z,C),v==null||v.disconnect(),_(),r.dispose(),N.current=null}},[t,c,F,j,T]),l.useEffect(()=>{if(!u)return;const m=requestAnimationFrame(()=>{const r=N.current;if(r){try{r.fit.fit(),j({type:"terminal_resize",terminalId:c,conversationId:t,cols:r.term.cols,rows:r.term.rows})}catch{}r.term.focus()}});return()=>cancelAnimationFrame(m)},[u]);const{t:R}=O(),x=l.useRef(void 0);return l.useEffect(()=>{if(b===x.current||(x.current=b,b!==!1))return;const m=N.current;m&&m.term.write(`\r
4
4
  \x1B[90m${R("exitBanner",{code:y??""})}\x1B[0m\r