pi-web-ui 0.62.0 → 0.63.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.
- package/LICENSE +21 -21
- package/README.md +504 -497
- package/README.zh-CN.md +427 -422
- package/bin/pi-web-ui.mjs +1809 -1881
- package/deploy/com.xingshuyin.pi-web-ui.plist +48 -48
- package/deploy/nginx-subpath.conf +88 -88
- package/deploy/pi-web-ui-task.xml +54 -54
- package/deploy/pi-web-ui.service +31 -31
- package/dist/server/agent-service.js +318 -88
- package/dist/server/attachments.js +37 -28
- package/dist/server/bg-servers.js +6 -1
- package/dist/server/client-state.js +15 -7
- package/dist/server/control-socket.js +1 -5
- package/dist/server/dsh/dsh-agent-service.js +454 -118
- package/dist/server/dsh/dsh-client.js +1 -3
- package/dist/server/dsh/dsh-sessions.js +4 -14
- package/dist/server/dsh/runtime/cordis.yml +1 -1
- package/dist/server/dsh/runtime/goal-rpc.mjs +645 -662
- package/dist/server/dsh/runtime/launcher.mjs +8 -18
- package/dist/server/dsh/runtime/override.patch.yml +9 -9
- package/dist/server/dsh/runtime/runtime-root.mjs +7 -11
- package/dist/server/ensure-bash.js +2 -5
- package/dist/server/files-service.js +42 -36
- package/dist/server/goal-service.js +59 -30
- package/dist/server/index.js +17 -10
- package/dist/server/mcp-bridge.js +11 -5
- package/dist/server/model-admin.js +78 -72
- package/dist/server/plugin-facilities.js +2 -4
- package/dist/server/plugin-updater.js +1 -1
- package/dist/server/plugins.js +26 -8
- package/dist/server/process-utils.js +4 -4
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/scm.js +27 -21
- package/dist/server/serialize.js +1 -3
- package/dist/server/settings-service.js +63 -21
- package/dist/server/slash-commands.js +29 -3
- package/dist/server/subagent-templates.js +249 -0
- package/dist/server/subagents.js +150 -0
- package/dist/server/terminals.js +101 -40
- package/dist/server/text-sniff.js +4 -24
- package/dist/server/update-check.js +2 -4
- package/dist/server/uploads.js +1 -3
- package/dist/server/vision-bridge.js +2 -7
- package/dist/server/wait-subscription-scan.js +102 -21
- package/dist/server/webui-context.js +1 -1
- package/extensions/webui.ts +190 -192
- package/package.json +109 -103
- package/web/dist/assets/TerminalPanel-B9vcI7-_.js +2 -0
- package/web/dist/assets/index-B8Wv29p5.css +10 -0
- package/web/dist/assets/index-CWUWD0rq.js +323 -0
- package/web/dist/favicon.svg +8 -8
- package/web/dist/index.html +15 -15
- package/web/public/favicon.svg +8 -8
- package/web/dist/assets/TerminalPanel-BkCWDsIG.js +0 -2
- package/web/dist/assets/index-BRVKed7W.js +0 -321
- package/web/dist/assets/index-ORTpR6ZQ.css +0 -10
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
// background subagent run, so its runtime must be kept alive across project /
|
|
25
25
|
// conversation switches. See the Chinese block above for the persistence layout
|
|
26
26
|
// and the fail-open vs fail-closed rationale.
|
|
27
|
-
import { readdirSync, readFileSync } from "node:fs";
|
|
27
|
+
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
28
28
|
import { homedir, tmpdir, userInfo } from "node:os";
|
|
29
29
|
import path from "node:path";
|
|
30
30
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
@@ -37,15 +37,17 @@ function parseRecord(value) {
|
|
|
37
37
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
38
38
|
return undefined;
|
|
39
39
|
const record = value;
|
|
40
|
-
if (record.version !== 1
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
40
|
+
if (record.version !== 1 ||
|
|
41
|
+
typeof record.token !== "string" ||
|
|
42
|
+
!UUID_RE.test(record.token) ||
|
|
43
|
+
typeof record.sessionId !== "string" ||
|
|
44
|
+
(record.targetKind !== "async" && record.targetKind !== "foreground") ||
|
|
45
|
+
typeof record.runId !== "string" ||
|
|
46
|
+
typeof record.requestedId !== "string" ||
|
|
47
|
+
typeof record.createdAt !== "number" ||
|
|
48
|
+
!Number.isFinite(record.createdAt) ||
|
|
49
|
+
typeof record.expiresAt !== "number" ||
|
|
50
|
+
!Number.isFinite(record.expiresAt))
|
|
49
51
|
return undefined;
|
|
50
52
|
return record;
|
|
51
53
|
}
|
|
@@ -98,13 +100,89 @@ export function resolveTempScopeId(env = process.env, getuid = process.getuid?.b
|
|
|
98
100
|
}
|
|
99
101
|
return "shared";
|
|
100
102
|
}
|
|
103
|
+
/** <pi-subagents 临时根>:PI_SUBAGENTS_TEMP_ROOT 优先,否则 tmpdir()/pi-subagents-<scope>。 */
|
|
104
|
+
function resolveTempRoot(env) {
|
|
105
|
+
const configured = env.PI_SUBAGENTS_TEMP_ROOT?.trim();
|
|
106
|
+
return configured ? path.resolve(configured) : path.join(tmpdir(), `pi-subagents-${resolveTempScopeId(env)}`);
|
|
107
|
+
}
|
|
101
108
|
/** wait-subscriptions 目录默认位置(与 pi-subagents 的推导一致)。 */
|
|
102
109
|
export function resolveSubscriptionsDir(env = process.env) {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
return path.join(
|
|
110
|
+
return path.join(resolveTempRoot(env), "wait-subscriptions");
|
|
111
|
+
}
|
|
112
|
+
/** 异步 run 目录根(asyncDirRoot)默认位置:<TEMP_ROOT>/async-subagent-runs。 */
|
|
113
|
+
export function resolveAsyncRunsDir(env = process.env) {
|
|
114
|
+
return path.join(resolveTempRoot(env), "async-subagent-runs");
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* 活跃 run marker 的最长可信存活期:对齐 pi-subagents
|
|
118
|
+
* active-run-index.ts 的 DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS(24h)。
|
|
119
|
+
* 崩溃遗留的 marker 超过该时长即视为孤儿,不阻止运行时释放(保留自限)。
|
|
120
|
+
*/
|
|
121
|
+
export const DEFAULT_STALE_ACTIVE_MARKER_MS = 24 * 60 * 60 * 1000;
|
|
122
|
+
/** 活跃 marker 索引目录名,与 pi-subagents 的 ACTIVE_RUN_INDEX_DIR 一致。 */
|
|
123
|
+
const ACTIVE_RUN_INDEX_DIR = ".active-runs";
|
|
124
|
+
/**
|
|
125
|
+
* 磁盘扫描:该会话是否还有活跃(queued/running)的 pi-subagents 异步 run。
|
|
126
|
+
* 任何 I/O / 解析 / 过期错误都按「无证据」处理(fail-open,见文件头说明)。
|
|
127
|
+
* ENOENT(目录/文件尚不存在、marker 刚被清掉)保持静默;其余 I/O 错误
|
|
128
|
+
* console.warn 一次(与 hasPendingWaitSubscription 对齐)。
|
|
129
|
+
*/
|
|
130
|
+
export function hasActiveSubagentRun(options) {
|
|
131
|
+
const sessionId = options.sessionId;
|
|
132
|
+
if (!sessionId)
|
|
133
|
+
return false;
|
|
134
|
+
const now = options.now ?? Date.now;
|
|
135
|
+
const staleMarkerMs = options.staleMarkerMs ?? DEFAULT_STALE_ACTIVE_MARKER_MS;
|
|
136
|
+
const warn = options.warn ?? ((message, error) => console.warn(message, error));
|
|
137
|
+
const isNotFound = (error) => typeof error === "object" &&
|
|
138
|
+
error !== null &&
|
|
139
|
+
"code" in error &&
|
|
140
|
+
error.code === "ENOENT";
|
|
141
|
+
const runsDir = options.asyncRunsDir ?? resolveAsyncRunsDir();
|
|
142
|
+
const indexDir = path.join(runsDir, ACTIVE_RUN_INDEX_DIR);
|
|
143
|
+
let markers;
|
|
144
|
+
try {
|
|
145
|
+
markers = readdirSync(indexDir);
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
if (!isNotFound(error))
|
|
149
|
+
warn(`Failed to scan active-run index in '${indexDir}':`, error);
|
|
150
|
+
return false; // 索引目录缺失 / 不可读 → 无证据
|
|
151
|
+
}
|
|
152
|
+
for (const runId of markers) {
|
|
153
|
+
if (runId.startsWith("."))
|
|
154
|
+
continue; // 不把隐藏文件当 run 证据
|
|
155
|
+
const markerFile = path.join(indexDir, runId);
|
|
156
|
+
// 孤儿防护:marker 太久没被 touch(崩溃遗留,run 早已不在)→ 无证据。
|
|
157
|
+
try {
|
|
158
|
+
const ageMs = now() - statSync(markerFile).mtimeMs;
|
|
159
|
+
if (ageMs > staleMarkerMs)
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
if (!isNotFound(error))
|
|
164
|
+
warn(`Failed to stat active-run marker '${markerFile}':`, error);
|
|
165
|
+
continue; // ENOENT(刚被清除的竞态)→ 无证据
|
|
166
|
+
}
|
|
167
|
+
let status;
|
|
168
|
+
try {
|
|
169
|
+
status = JSON.parse(readFileSync(path.join(runsDir, runId, "status.json"), "utf-8"));
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
if (!isNotFound(error))
|
|
173
|
+
warn(`Failed to read async run status '${path.join(runsDir, runId, "status.json")}':`, error);
|
|
174
|
+
continue; // 缺失 / 损坏 → 无证据(fail-open)
|
|
175
|
+
}
|
|
176
|
+
if (!status || typeof status !== "object" || Array.isArray(status))
|
|
177
|
+
continue;
|
|
178
|
+
const probe = status;
|
|
179
|
+
if (probe.sessionId !== sessionId)
|
|
180
|
+
continue; // 别的会话的 run
|
|
181
|
+
if (probe.state !== "queued" && probe.state !== "running")
|
|
182
|
+
continue; // 已结束
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
return false;
|
|
108
186
|
}
|
|
109
187
|
/**
|
|
110
188
|
* 磁盘扫描:该会话是否还有未过期的 wake 订阅记录。
|
|
@@ -119,8 +197,10 @@ export function hasPendingWaitSubscription(options) {
|
|
|
119
197
|
return false;
|
|
120
198
|
const now = options.now ?? Date.now;
|
|
121
199
|
const warn = options.warn ?? ((message, error) => console.warn(message, error));
|
|
122
|
-
const isNotFound = (error) => typeof error === "object" &&
|
|
123
|
-
|
|
200
|
+
const isNotFound = (error) => typeof error === "object" &&
|
|
201
|
+
error !== null &&
|
|
202
|
+
"code" in error &&
|
|
203
|
+
error.code === "ENOENT";
|
|
124
204
|
const dir = options.subscriptionsDir ?? resolveSubscriptionsDir();
|
|
125
205
|
let files;
|
|
126
206
|
try {
|
|
@@ -163,7 +243,7 @@ export function hasPendingWaitSubscription(options) {
|
|
|
163
243
|
* 纯函数版置换决策:true = 保留(不得 dispose),false = 调用方可释放。
|
|
164
244
|
* Pure decision core of displaceActive(): true = retain, false = may dispose.
|
|
165
245
|
* 顺序与 displaceActive 保持一致:review/wizard → streaming → terminals →
|
|
166
|
-
* pending wake → listed+continued(「打开后继续过」的会话也保留)。
|
|
246
|
+
* active subagent run → pending wake → listed+continued(「打开后继续过」的会话也保留)。
|
|
167
247
|
*/
|
|
168
248
|
export function shouldRetainActive(input) {
|
|
169
249
|
if (input.reviewing || input.wizardRunning)
|
|
@@ -172,9 +252,10 @@ export function shouldRetainActive(input) {
|
|
|
172
252
|
return true;
|
|
173
253
|
if (input.openTerminals > 0)
|
|
174
254
|
return true;
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
255
|
+
const hasActiveRun = typeof input.hasActiveSubagentRun === "function" ? input.hasActiveSubagentRun() : input.hasActiveSubagentRun;
|
|
256
|
+
if (hasActiveRun)
|
|
257
|
+
return true;
|
|
258
|
+
const hasPendingWake = typeof input.hasPendingWake === "function" ? input.hasPendingWake() : input.hasPendingWake;
|
|
178
259
|
if (hasPendingWake)
|
|
179
260
|
return true;
|
|
180
261
|
if (input.listed && input.promptedSinceActive)
|
|
@@ -17,7 +17,7 @@ const mockTheme = new Proxy({
|
|
|
17
17
|
if (prop in target)
|
|
18
18
|
return target[prop];
|
|
19
19
|
// Unknown theme methods → no-op passthrough.
|
|
20
|
-
return (_arg, text) => text !== undefined ? text : "";
|
|
20
|
+
return (_arg, text) => (text !== undefined ? text : "");
|
|
21
21
|
},
|
|
22
22
|
});
|
|
23
23
|
/** Mock TUI: any method call is a safe no-op. */
|
package/extensions/webui.ts
CHANGED
|
@@ -1,192 +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 (
|
|
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"
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
console.warn(
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
});
|
|
192
|
-
}
|
|
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
|
+
}
|