pi-webapp 0.1.57 → 0.1.58-alpha.2
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/bin/launcher-diagnostics.mjs +179 -0
- package/bin/launcher-logs.mjs +145 -0
- package/bin/pi-webapp.mjs +183 -39
- package/dist/extension.js +71 -71
- package/dist/hosted-recovery.js +2 -2
- package/dist/hosted-worker.js +2 -2
- package/docs/desktop.md +16 -5
- package/package.json +3 -2
- package/web/dist/.vite/manifest.json +80 -64
- package/web/dist/assets/{MarkdownText-Ca6_qCyr.js → MarkdownText-BmWua1fx.js} +11 -11
- package/web/dist/assets/WorkspacePanel.module-q1UBTZQr.js +2 -0
- package/web/dist/assets/app-Bl_vjH4f.js +53 -0
- package/web/dist/assets/app.css +1 -1
- package/web/dist/assets/app.js +4 -4
- package/web/dist/assets/{code-editor-B5kVAtku.js → code-editor-bWuZTiS2.js} +4 -4
- package/web/dist/assets/{icons-D8yiYkWB.js → code-file-types-BZAEsqNG.js} +3 -3
- package/web/dist/assets/{dist-CWWynAS-.js → dist-B8Mp_VTU.js} +2 -2
- package/web/dist/assets/{dist-o-4nubru.js → dist-BD_2QeWa.js} +2 -2
- package/web/dist/assets/{dist-Im2q9dJ0.js → dist-C2WSXtwq.js} +2 -2
- package/web/dist/assets/{dist-BRYLL4VU.js → dist-C7kRRV1b.js} +2 -2
- package/web/dist/assets/{dist-CaNhruaD.js → dist-CCfANS3F.js} +2 -2
- package/web/dist/assets/{dist-BFhI7cEI.js → dist-CP5SBgQB.js} +2 -2
- package/web/dist/assets/{dist-DAlictfL.js → dist-CmPE8_f_.js} +2 -2
- package/web/dist/assets/{dist-CszBAiM6.js → dist-D-nx7RRS.js} +2 -2
- package/web/dist/assets/{dist-BYJ4SXpR.js → dist-DFTCmV51.js} +2 -2
- package/web/dist/assets/{dist-CsFhAvz7.js → dist-Dr0qO3Zr.js} +2 -2
- package/web/dist/assets/{dist-CqXTRhJp.js → dist-Nlb4zANG.js} +2 -2
- package/web/dist/assets/{graphql-Cz1_wnUp.js → graphql-B5jxVvgN.js} +2 -2
- package/web/dist/assets/{http-CTlzQwRP.js → http-C6M1fy61.js} +2 -2
- package/web/dist/assets/{php-BHNgHgMp.js → php-B61pLHqK.js} +2 -2
- package/web/dist/assets/{plugin-D1z0mcl1.js → plugin-CE1WaS8V.js} +4 -4
- package/web/dist/assets/plugin-CsVaeNQM.js +6 -0
- package/web/dist/assets/plugin-Cyidq4oP.js +2 -0
- package/web/dist/assets/plugin-Gwwlx9MU.js +4 -0
- package/web/dist/assets/plugin.css +1 -1
- package/web/dist/assets/plugin2.css +1 -1
- package/web/dist/assets/plugin3.css +1 -0
- package/web/dist/assets/{rst-BdGjFUxD.js → rst-950N-2sy.js} +2 -2
- package/web/dist/assets/{ruby-D7-ny0V-.js → ruby-Qm2HAXfx.js} +2 -2
- package/web/dist/assets/{svelte-DoD3sicb.js → svelte-CoZSSs0h.js} +2 -2
- package/web/dist/assets/{vue-BYLUelN7.js → vue-as6FrWIW.js} +2 -2
- package/web/dist/assets/WorkspacePanel.module-V6gI-nG1.js +0 -2
- package/web/dist/assets/app-CIlV3hYO.js +0 -49
- package/web/dist/assets/plugin-CZx51rmJ.js +0 -6
- package/web/dist/assets/plugin-CvqNiFRV.js +0 -4
package/bin/pi-webapp.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { spawn as spawnNode } from "node:child_process";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import { closeSync, existsSync, openSync, watch } from "node:fs";
|
|
5
|
-
import { mkdir, open, readFile, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
5
|
+
import { lstat, mkdir, open, readFile, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
7
|
import { delimiter, dirname, join, resolve } from "node:path";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
@@ -47,8 +47,8 @@ function compatible(parts, required) {
|
|
|
47
47
|
return true;
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
function
|
|
51
|
-
const result = spawn.sync(command, ["--version"], { encoding: "utf8" });
|
|
50
|
+
function probeVersion(command, args = []) {
|
|
51
|
+
const result = spawn.sync(command, [...args, "--version"], { encoding: "utf8", timeout: 5000, windowsHide: true });
|
|
52
52
|
if (result.error?.code === "ENOENT") return null;
|
|
53
53
|
if (result.error || result.status !== 0) {
|
|
54
54
|
throw new Error(`无法运行 Pi:${result.error?.message || result.stderr?.trim() || command}`);
|
|
@@ -58,7 +58,15 @@ function probe(command) {
|
|
|
58
58
|
if (!parts || !compatible(parts, minimum)) {
|
|
59
59
|
throw new Error(`Pi 版本 ${version || "未知"} 不受支持,需要 0.87.1 或更新版本。请更新 Pi 后重试。`);
|
|
60
60
|
}
|
|
61
|
-
return
|
|
61
|
+
return version;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function probe(command) {
|
|
65
|
+
return probeVersion(command) ? command : null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function locatePiCli() {
|
|
69
|
+
return await packagePiCli(dirname(dirname(launcher))) ?? process.env.PI_WEBAPP_PI_CLI;
|
|
62
70
|
}
|
|
63
71
|
|
|
64
72
|
function installPi() {
|
|
@@ -85,22 +93,27 @@ function alive(pid) {
|
|
|
85
93
|
catch (error) { return error?.code === "EPERM"; }
|
|
86
94
|
}
|
|
87
95
|
|
|
88
|
-
async function
|
|
96
|
+
async function readLauncherState() {
|
|
97
|
+
try { return JSON.parse(await readFile(statePath, "utf8")); }
|
|
98
|
+
catch (error) { if (error?.code === "ENOENT") return null; throw error; }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function activeState({ cleanup = true } = {}) {
|
|
89
102
|
let state;
|
|
90
103
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
91
|
-
try { state =
|
|
104
|
+
try { state = await readLauncherState(); if (!state) return null; break; }
|
|
92
105
|
catch (error) {
|
|
93
106
|
if (error?.code === "ENOENT") return null;
|
|
94
107
|
if (!(error instanceof SyntaxError)) throw error;
|
|
95
108
|
if (attempt < 2) { await new Promise((resolveWait) => setTimeout(resolveWait, 50)); continue; }
|
|
96
109
|
const age = Date.now() - (await stat(statePath)).mtimeMs;
|
|
97
110
|
if (age < 5000) return { starting: true };
|
|
98
|
-
await unlink(statePath).catch(() => {});
|
|
111
|
+
if (cleanup) await unlink(statePath).catch(() => {});
|
|
99
112
|
return null;
|
|
100
113
|
}
|
|
101
114
|
}
|
|
102
115
|
if (alive(state?.pid)) return state;
|
|
103
|
-
await unlink(statePath).catch(() => {});
|
|
116
|
+
if (cleanup) await unlink(statePath).catch(() => {});
|
|
104
117
|
return null;
|
|
105
118
|
}
|
|
106
119
|
|
|
@@ -119,9 +132,12 @@ function notifyParent(message) {
|
|
|
119
132
|
function parseStartArgs(args) {
|
|
120
133
|
const piArgs = [];
|
|
121
134
|
let host, port;
|
|
135
|
+
let foreground = false, noOpen = false;
|
|
122
136
|
for (let i = 0; i < args.length; i++) {
|
|
123
137
|
const arg = args[i];
|
|
124
138
|
if (arg === "--") { piArgs.push(...args.slice(i)); break; }
|
|
139
|
+
if (arg === "--foreground") { foreground = true; continue; }
|
|
140
|
+
if (arg === "--no-open") { noOpen = true; continue; }
|
|
125
141
|
const match = /^(--host|--port)(?:=(.*))?$/.exec(arg);
|
|
126
142
|
if (!match) { piArgs.push(arg); continue; }
|
|
127
143
|
const value = match[2] ?? args[++i];
|
|
@@ -135,11 +151,11 @@ function parseStartArgs(args) {
|
|
|
135
151
|
port = Number(value);
|
|
136
152
|
}
|
|
137
153
|
}
|
|
138
|
-
return { host, port, piArgs };
|
|
154
|
+
return { host, port, piArgs, foreground, noOpen };
|
|
139
155
|
}
|
|
140
156
|
|
|
141
|
-
async function serve(pi, args) {
|
|
142
|
-
const { host = "127.0.0.1", port, piArgs } = parseStartArgs(args);
|
|
157
|
+
async function serve(pi, args, { report = notifyParent, piCli = process.env.PI_WEBAPP_PI_CLI } = {}) {
|
|
158
|
+
const { host = "127.0.0.1", port, piArgs, foreground, noOpen } = parseStartArgs(args);
|
|
143
159
|
const nonce = randomUUID();
|
|
144
160
|
await mkdir(dirname(statePath), { recursive: true });
|
|
145
161
|
let claimed = false;
|
|
@@ -150,14 +166,14 @@ async function serve(pi, args) {
|
|
|
150
166
|
await lock.writeFile(JSON.stringify({ pid: process.pid, nonce, cwd: process.cwd(), starting: true, ...runtimeInfo }));
|
|
151
167
|
} catch (error) {
|
|
152
168
|
if (claimed) await unlink(statePath).catch(() => {});
|
|
153
|
-
|
|
154
|
-
return;
|
|
169
|
+
report({ type: "error", message: error?.code === "EEXIST" ? "pi-webapp 已在启动或运行" : String(error) });
|
|
170
|
+
return 1;
|
|
155
171
|
} finally { await lock?.close().catch(() => {}); }
|
|
156
172
|
|
|
157
173
|
const pluginRoots = (process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS ?? "").split(delimiter).filter(Boolean).map((root) => resolve(root));
|
|
158
|
-
const piPrefix =
|
|
174
|
+
const piPrefix = piCli ? [resolve(piCli)] : [];
|
|
159
175
|
const child = spawn(pi, [...piPrefix, "--mode", "rpc", "-e", extension, ...pluginRoots.flatMap((root) => ["-e", root]), ...piArgs], {
|
|
160
|
-
cwd: process.cwd(), env: { ...process.env, NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --import=${JSON.stringify(new URL("./model-network-bootstrap.mjs", import.meta.url).href)}`.trim(), PI_WEBAPP_AUTO_OPEN: "0", PI_WEBAPP_LISTEN_HOST: host, PI_WEBAPP_LISTEN_PORT: port === undefined ? "" : String(port), PI_WEBAPP_LAUNCHER_NONCE: nonce, PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL: "1", PI_WEBAPP_LAUNCHER_VERSION: packageVersion }, stdio: ["pipe", "pipe", "pipe"],
|
|
176
|
+
cwd: process.cwd(), detached: foreground, windowsHide: foreground, env: { ...process.env, NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --import=${JSON.stringify(new URL("./model-network-bootstrap.mjs", import.meta.url).href)}`.trim(), PI_WEBAPP_AUTO_OPEN: "0", PI_WEBAPP_FOREGROUND: foreground ? "1" : "0", PI_WEBAPP_LISTEN_HOST: host, PI_WEBAPP_LISTEN_PORT: port === undefined ? "" : String(port), PI_WEBAPP_LAUNCHER_NONCE: nonce, PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL: "1", PI_WEBAPP_LAUNCHER_VERSION: packageVersion }, stdio: ["pipe", "pipe", "pipe"],
|
|
161
177
|
});
|
|
162
178
|
child.stderr?.pipe(process.stderr, { end: false });
|
|
163
179
|
let ready = false;
|
|
@@ -198,7 +214,7 @@ async function serve(pi, args) {
|
|
|
198
214
|
child.stdin?.end();
|
|
199
215
|
// A handoff is not permission to kill a stalled process. The new desktop
|
|
200
216
|
// must wait for this supervisor and its child to exit naturally.
|
|
201
|
-
if (handoffRequest) return;
|
|
217
|
+
if (handoffRequest || reason === "cli_restart" || (foreground && !forceStopRequested && reason.startsWith("signal_"))) return;
|
|
202
218
|
killTimer = setTimeout(() => {
|
|
203
219
|
forceStopRequested = true;
|
|
204
220
|
lifecycle("pi_force_stop", { reason, signal: "SIGTERM" });
|
|
@@ -214,7 +230,7 @@ async function serve(pi, args) {
|
|
|
214
230
|
// Keep the gate closed until the rejected request is gone. Otherwise the
|
|
215
231
|
// interval can read that same nonce again and launch an unsolicited drain,
|
|
216
232
|
// racing the caller's explicit retry (or leaving an idle host draining).
|
|
217
|
-
void readFile(stopPath, "utf8").then(value => value.trim()
|
|
233
|
+
void readFile(stopPath, "utf8").then(value => [nonce, `${nonce} restart`].includes(value.trim()) ? unlink(stopPath) : undefined)
|
|
218
234
|
.catch(() => {}).finally(() => { stopping = false; });
|
|
219
235
|
};
|
|
220
236
|
const shutdown = (reason, force = false) => {
|
|
@@ -224,7 +240,7 @@ async function serve(pi, args) {
|
|
|
224
240
|
stopReason = reason;
|
|
225
241
|
lifecycle("launcher_stop_requested", { reason });
|
|
226
242
|
// An explicit operator override: skip the save/drain preflight that an unresponsive view can block.
|
|
227
|
-
if (force) { lifecycle("launcher_stop_forced", { reason }); finishShutdown(reason); return; }
|
|
243
|
+
if (force) { forceStopRequested = true; lifecycle("launcher_stop_forced", { reason }); finishShutdown(reason); return; }
|
|
228
244
|
// RPC EOF can exit even when an extension's shutdown handler fails. Drain
|
|
229
245
|
// while the transport is alive and require an explicit successful response.
|
|
230
246
|
if (ready && stopCommand) {
|
|
@@ -238,7 +254,7 @@ async function serve(pi, args) {
|
|
|
238
254
|
const fail = (message) => {
|
|
239
255
|
if (failed || ready) return;
|
|
240
256
|
failed = true;
|
|
241
|
-
|
|
257
|
+
report({ type: "error", message });
|
|
242
258
|
shutdown("startup_failure");
|
|
243
259
|
};
|
|
244
260
|
const startupTimer = setTimeout(() => fail(`Pi 启动超时。日志:${logPath}`), 60000);
|
|
@@ -252,6 +268,7 @@ async function serve(pi, args) {
|
|
|
252
268
|
if (epoch !== stopEpoch || stopping) return;
|
|
253
269
|
if (request === nonce) shutdown("stop_request");
|
|
254
270
|
else if (request === `${nonce} force`) shutdown("stop_request", true);
|
|
271
|
+
else if (request === `${nonce} restart`) shutdown("cli_restart");
|
|
255
272
|
} catch { /* No stop request. */ }
|
|
256
273
|
if (stopping || epoch !== stopEpoch) return;
|
|
257
274
|
if (runtimeKind === "desktop") {
|
|
@@ -269,6 +286,9 @@ async function serve(pi, args) {
|
|
|
269
286
|
try {
|
|
270
287
|
const request = JSON.parse(await readFile(restartPath, "utf8"));
|
|
271
288
|
if (request.nonce !== nonce || (runtimeKind === "desktop" && !desktopPackages)) return;
|
|
289
|
+
// A service manager owns the foreground process. Don't activate a
|
|
290
|
+
// replacement launcher through the detached update handoff here.
|
|
291
|
+
if (foreground) return;
|
|
272
292
|
if (typeof request.candidate === "string") {
|
|
273
293
|
// The host only names its validated candidate. Selection, admission and rollback are ours.
|
|
274
294
|
const candidate = await readCandidate(agentDir);
|
|
@@ -290,8 +310,10 @@ async function serve(pi, args) {
|
|
|
290
310
|
} catch { /* No valid restart request. */ }
|
|
291
311
|
} finally { stopCheckRunning = false; }
|
|
292
312
|
}, 400);
|
|
293
|
-
|
|
294
|
-
|
|
313
|
+
const onTerminate = () => shutdown("signal_sigterm");
|
|
314
|
+
const onInterrupt = () => shutdown("signal_sigint");
|
|
315
|
+
process.on("SIGTERM", onTerminate);
|
|
316
|
+
process.on("SIGINT", onInterrupt);
|
|
295
317
|
child.stdout?.on("data", (chunk) => {
|
|
296
318
|
if (failed) return;
|
|
297
319
|
if (!sawStdout) { sawStdout = true; startupStage("first-rpc-output"); }
|
|
@@ -355,20 +377,20 @@ async function serve(pi, args) {
|
|
|
355
377
|
let url;
|
|
356
378
|
try { url = new URL(record.message.slice("pi-webapp: ".length)); }
|
|
357
379
|
catch { continue; }
|
|
358
|
-
if (url.hostname !== "127.0.0.1" || !url.hash) continue;
|
|
380
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.username || url.password || !url.hash) continue;
|
|
359
381
|
if (port !== undefined && Number(url.port || "80") !== port) {
|
|
360
382
|
fail(`Pi Web 未监听指定端口 ${port}。日志:${logPath}`);
|
|
361
383
|
return;
|
|
362
384
|
}
|
|
363
385
|
runningUrl = url.href;
|
|
364
386
|
opening = true;
|
|
365
|
-
stateWrite = saveState({ pid: process.pid, piPid: child.pid, nonce, cwd: process.cwd(), url: url.href, listenHost: host, ...runtimeInfo })
|
|
387
|
+
stateWrite = saveState({ pid: process.pid, piPid: child.pid, nonce, cwd: process.cwd(), url: url.href, listenHost: host, restartConfig: { piArgs, noOpen, foreground }, ...runtimeInfo })
|
|
366
388
|
.then(() => {
|
|
367
389
|
if (closed || failed) return;
|
|
368
390
|
ready = true;
|
|
369
391
|
clearTimeout(startupTimer);
|
|
370
392
|
lifecycle("launcher_ready", { port: Number(url.port || "80") });
|
|
371
|
-
|
|
393
|
+
report({ type: "ready", pid: process.pid, url: url.href });
|
|
372
394
|
for (const root of pluginRoots) {
|
|
373
395
|
try {
|
|
374
396
|
devWatchers.push(watch(join(root, "dist"), (_event, file) => {
|
|
@@ -403,6 +425,8 @@ async function serve(pi, args) {
|
|
|
403
425
|
});
|
|
404
426
|
await stateWrite;
|
|
405
427
|
if (handoffRequest) await writeHandoff(agentDir, { ...handoffRequest, phase: failed || child.exitCode !== 0 ? "failed" : "stopped" });
|
|
428
|
+
process.off("SIGTERM", onTerminate);
|
|
429
|
+
process.off("SIGINT", onInterrupt);
|
|
406
430
|
clearTimeout(startupTimer);
|
|
407
431
|
clearTimeout(stopPreflightTimer);
|
|
408
432
|
clearTimeout(devReloadTimer);
|
|
@@ -415,7 +439,7 @@ async function serve(pi, args) {
|
|
|
415
439
|
// A confirmed normal stop may supersede a restart this supervisor never
|
|
416
440
|
// accepted. Archive only our request after a natural successful exit,
|
|
417
441
|
// while the owner claim still excludes a successor writing its request.
|
|
418
|
-
if (!restartRequest &&
|
|
442
|
+
if (!restartRequest && ["cli_restart", "stop_request"].includes(stopReason) && ready && !failed && child.exitCode === 0 && !forceStopRequested) {
|
|
419
443
|
try {
|
|
420
444
|
const request = JSON.parse(await readFile(restartPath, "utf8"));
|
|
421
445
|
if (request.nonce === nonce) {
|
|
@@ -433,7 +457,7 @@ async function serve(pi, args) {
|
|
|
433
457
|
}
|
|
434
458
|
catch { /* Already removed. */ }
|
|
435
459
|
}
|
|
436
|
-
try { if ((await readFile(stopPath, "utf8")).trim()
|
|
460
|
+
try { if ([nonce, `${nonce} force`, `${nonce} restart`].includes((await readFile(stopPath, "utf8")).trim())) await unlink(stopPath); } catch { /* Already removed. */ }
|
|
437
461
|
if (restartRequest && runningUrl) {
|
|
438
462
|
await unlink(restartPath).catch(() => {});
|
|
439
463
|
const oldUrl = new URL(runningUrl);
|
|
@@ -457,6 +481,7 @@ async function serve(pi, args) {
|
|
|
457
481
|
}
|
|
458
482
|
} finally { closeSync(fd); }
|
|
459
483
|
}
|
|
484
|
+
return failed || !ready || forceStopRequested || child.exitCode !== 0 ? 1 : 0;
|
|
460
485
|
}
|
|
461
486
|
|
|
462
487
|
/** The launcher-owned upgrade transaction: select the candidate's pointer, admit the new host only
|
|
@@ -521,29 +546,43 @@ async function managedLauncher() {
|
|
|
521
546
|
} catch { return null; }
|
|
522
547
|
}
|
|
523
548
|
|
|
524
|
-
async function start(args) {
|
|
525
|
-
const { host, port, piArgs } = parseStartArgs(args);
|
|
549
|
+
async function start(args, { cwd = process.cwd(), requireNew = false } = {}) {
|
|
550
|
+
const { host, port, piArgs, foreground, noOpen } = parseStartArgs(args);
|
|
526
551
|
const existing = await activeState();
|
|
527
552
|
if (existing) {
|
|
553
|
+
if (foreground || requireNew) throw new Error("pi-webapp 已在启动或运行,请先停止服务。");
|
|
528
554
|
if ((host !== undefined || port !== undefined) && (!existing.url
|
|
529
555
|
|| (host !== undefined && host !== (existing.listenHost ?? "127.0.0.1"))
|
|
530
556
|
|| (port !== undefined && port !== Number(new URL(existing.url).port || "80")))) {
|
|
531
557
|
throw new Error("pi-webapp 已在启动或使用不同的监听配置。请先运行 pi-webapp stop,再使用指定参数启动。");
|
|
532
558
|
}
|
|
533
559
|
console.log(existing.url ? `pi-webapp 已在后台运行:${existing.url}` : "pi-webapp 正在启动");
|
|
534
|
-
if (existing.url) await openPageIfLocal(existing.url);
|
|
560
|
+
if (existing.url && !noOpen) await openPageIfLocal(existing.url);
|
|
535
561
|
return;
|
|
536
562
|
}
|
|
537
563
|
const managed = await managedLauncher();
|
|
538
564
|
if (managed) {
|
|
539
565
|
const selected = desktopPackages ? await readDesktopRelease(agentDir, packageVersion, desktopFallbackVersion) : null;
|
|
540
566
|
const env = selected?.launcher === managed ? { ...process.env, PI_WEBAPP_PI_CLI: selected.piCli } : process.env;
|
|
541
|
-
const next = spawnNode(process.execPath, [managed, "start", ...args], { cwd
|
|
542
|
-
const
|
|
567
|
+
const next = spawnNode(process.execPath, [managed, "start", ...args], { cwd, env, stdio: "inherit", detached: foreground, windowsHide: foreground });
|
|
568
|
+
const onTerminate = () => next.kill("SIGTERM");
|
|
569
|
+
const onInterrupt = () => next.kill("SIGINT");
|
|
570
|
+
if (foreground) {
|
|
571
|
+
process.on("SIGTERM", onTerminate);
|
|
572
|
+
process.on("SIGINT", onInterrupt);
|
|
573
|
+
}
|
|
574
|
+
let code;
|
|
575
|
+
try {
|
|
576
|
+
code = await new Promise((resolveExit, rejectExit) => { next.once("error", rejectExit); next.once("exit", (status) => resolveExit(status ?? 1)); });
|
|
577
|
+
} finally {
|
|
578
|
+
process.off("SIGTERM", onTerminate);
|
|
579
|
+
process.off("SIGINT", onInterrupt);
|
|
580
|
+
}
|
|
581
|
+
if (foreground) { process.exitCode = code; return; }
|
|
543
582
|
if (code !== 0) {
|
|
544
583
|
await clearManagedLauncher(managed);
|
|
545
584
|
console.error(`pi-webapp: 新版启动失败(代码 ${code ?? "未知"}),正在恢复当前安装`);
|
|
546
|
-
await start(args);
|
|
585
|
+
await start(args, { cwd, requireNew });
|
|
547
586
|
}
|
|
548
587
|
return;
|
|
549
588
|
}
|
|
@@ -551,14 +590,24 @@ async function start(args) {
|
|
|
551
590
|
if (!nodeVersion || !compatible(nodeVersion, [22, 19, 0])) throw new Error("需要 Node.js 22.19 或更新版本。");
|
|
552
591
|
if (!existsSync(extension)) throw new Error("找不到构建后的扩展。请先运行 npm run build。");
|
|
553
592
|
if (piArgs.some((arg) => ["--mode", "--print", "-p"].includes(arg))) throw new Error("后台启动不支持覆盖 Pi 的运行模式");
|
|
554
|
-
const piCli = await
|
|
593
|
+
const piCli = await locatePiCli();
|
|
555
594
|
const pi = piCli ? process.execPath : probe("pi") ?? installPi();
|
|
595
|
+
if (foreground) {
|
|
596
|
+
process.exitCode = await serve(pi, args, { piCli, report(message) {
|
|
597
|
+
if (message.type === "error") console.error(`pi-webapp: ${message.message}`);
|
|
598
|
+
else {
|
|
599
|
+
console.log(`pi-webapp 正在前台运行(PID ${message.pid}):${message.url}`);
|
|
600
|
+
if (!noOpen) void openPageIfLocal(message.url);
|
|
601
|
+
}
|
|
602
|
+
} });
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
556
605
|
await mkdir(dirname(statePath), { recursive: true });
|
|
557
606
|
const logFd = openSync(logPath, "a", 0o600);
|
|
558
607
|
let worker;
|
|
559
608
|
try {
|
|
560
609
|
worker = spawnNode(process.execPath, [launcher, "__serve", pi, ...args], {
|
|
561
|
-
detached: true, cwd
|
|
610
|
+
detached: true, cwd, env: { ...process.env, ...(piCli ? { PI_WEBAPP_PI_CLI: piCli } : {}) }, stdio: ["ignore", logFd, logFd, "ipc"],
|
|
562
611
|
});
|
|
563
612
|
} finally { closeSync(logFd); }
|
|
564
613
|
let ready;
|
|
@@ -579,7 +628,7 @@ async function start(args) {
|
|
|
579
628
|
}
|
|
580
629
|
console.log(`pi-webapp 已在后台运行(PID ${ready.pid}):${ready.url}`);
|
|
581
630
|
console.log("停止服务:pi-webapp stop(源码目录中可运行 npm run stop)");
|
|
582
|
-
await openPageIfLocal(ready.url);
|
|
631
|
+
if (!noOpen) await openPageIfLocal(ready.url);
|
|
583
632
|
}
|
|
584
633
|
|
|
585
634
|
async function openPageIfLocal(url) {
|
|
@@ -600,12 +649,13 @@ async function killTree(pid) {
|
|
|
600
649
|
try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ }
|
|
601
650
|
}
|
|
602
651
|
|
|
603
|
-
async function stop(force = false) {
|
|
652
|
+
async function stop(force = false, expectedNonce) {
|
|
604
653
|
const state = await activeState();
|
|
654
|
+
if (expectedNonce && state?.nonce !== expectedNonce) throw new Error("服务状态已改变,已取消重启。请重新查看 pi-webapp status。");
|
|
605
655
|
if (!state) { console.log("pi-webapp 未运行"); return; }
|
|
606
656
|
if (!state.nonce) throw new Error("pi-webapp 正在启动,请稍后再停止");
|
|
607
657
|
if (force) console.error("pi-webapp: 强制停止将跳过插件视图的保存确认,未保存的编辑可能丢失。");
|
|
608
|
-
await writeFile(stopPath, force ? `${state.nonce} force` : state.nonce, { mode: 0o600 });
|
|
658
|
+
await writeFile(stopPath, expectedNonce ? `${state.nonce} restart` : force ? `${state.nonce} force` : state.nonce, { mode: 0o600 });
|
|
609
659
|
for (let attempt = 0; attempt < 400; attempt++) {
|
|
610
660
|
await new Promise((resolveWait) => setTimeout(resolveWait, 100));
|
|
611
661
|
const outcome = await observeStopOutcome(activeState, stopPath, state.nonce);
|
|
@@ -625,12 +675,106 @@ async function stop(force = false) {
|
|
|
625
675
|
throw new Error(`停止超时。后台进程 PID:${state.pid};日志:${logPath}`);
|
|
626
676
|
}
|
|
627
677
|
|
|
678
|
+
async function restart() {
|
|
679
|
+
const state = await activeState();
|
|
680
|
+
if (!state?.url || !state.nonce) throw new Error("没有已就绪的后台服务。请运行 pi-webapp start 或等待启动完成。");
|
|
681
|
+
if (runtimeKind !== "npm" || state.runtimeKind !== "npm") throw new Error("请从桌面应用重新启动桌面服务。");
|
|
682
|
+
const config = state.restartConfig;
|
|
683
|
+
if (config?.foreground) throw new Error("请在原终端或服务管理器中重新启动前台服务。");
|
|
684
|
+
if (!Array.isArray(config?.piArgs) || !config.piArgs.every(arg => typeof arg === "string") || typeof state.cwd !== "string") {
|
|
685
|
+
throw new Error("此服务没有保存启动参数。请先执行 pi-webapp stop,再用原参数启动。");
|
|
686
|
+
}
|
|
687
|
+
const url = new URL(state.url);
|
|
688
|
+
const args = ["--host", state.listenHost ?? "127.0.0.1", "--port", url.port || "80", ...(config.noOpen ? ["--no-open"] : []), ...config.piArgs];
|
|
689
|
+
parseStartArgs(args);
|
|
690
|
+
if (!(await stat(state.cwd)).isDirectory()) throw new Error("原工作目录已不可用,已取消重启。");
|
|
691
|
+
await stop(false, state.nonce);
|
|
692
|
+
await start(args, { cwd: state.cwd, requireNew: true });
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function readNpmOutput(args, errorMessage) {
|
|
696
|
+
const command = npmCommand(args);
|
|
697
|
+
const result = spawn.sync(command.file, command.args, { encoding: "utf8", timeout: 20000, windowsHide: true });
|
|
698
|
+
if (result.error || result.status !== 0) throw new Error(`${errorMessage}:${result.error?.message || result.stderr?.trim() || `npm 退出码 ${result.status}`}`);
|
|
699
|
+
return result.stdout.trim();
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
async function update(checkOnly) {
|
|
703
|
+
if (!checkOnly) {
|
|
704
|
+
const unsupported = "仅支持自更新通过 npm 全局安装的 pi-webapp。npx 请使用 npx pi-webapp@latest;源码请通过 Git 更新;桌面版请在应用内更新。";
|
|
705
|
+
if (runtimeKind === "desktop" || existsSync(fileURLToPath(new URL("../.git", import.meta.url)))) throw new Error(unsupported);
|
|
706
|
+
const root = readNpmOutput(["root", "-g"], "无法定位 npm 全局安装目录");
|
|
707
|
+
const installed = join(root, "pi-webapp");
|
|
708
|
+
// Don't replace a linked checkout or install globally from an npx/local copy.
|
|
709
|
+
if (!root || !(await lstat(installed).catch(() => null))?.isDirectory()
|
|
710
|
+
|| await realpath(installed) !== await realpath(dirname(dirname(launcher)))) throw new Error(unsupported);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const output = readNpmOutput(["view", "pi-webapp@latest", "version", "--json"], "无法查询 pi-webapp 最新版本");
|
|
714
|
+
let latest;
|
|
715
|
+
try { latest = JSON.parse(output); parseVersion(latest); }
|
|
716
|
+
catch { throw new Error("npm 返回的 pi-webapp 最新版本无效"); }
|
|
717
|
+
const comparison = compareVersions(latest, packageVersion);
|
|
718
|
+
console.log(`pi-webapp CLI:${packageVersion};npm latest:${latest}`);
|
|
719
|
+
if (comparison <= 0) {
|
|
720
|
+
console.log(comparison === 0 ? "已是最新版本" : "当前版本更新,不会降级");
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
if (checkOnly) { console.log("有可用更新"); return; }
|
|
724
|
+
if (await activeState()) throw new Error("pi-webapp 正在启动或运行。请先完成任务并执行 pi-webapp stop,再更新 CLI。");
|
|
725
|
+
|
|
726
|
+
const command = npmCommand(["install", "-g", `pi-webapp@${latest}`]);
|
|
727
|
+
const result = spawn.sync(command.file, command.args, { stdio: "inherit", windowsHide: true });
|
|
728
|
+
if (result.error || result.status !== 0) throw new Error(`更新失败:${result.error?.message || `npm 退出码 ${result.status}`}`);
|
|
729
|
+
console.log(`pi-webapp CLI 已更新至 ${latest}。服务未启动,可运行 pi-webapp start。`);
|
|
730
|
+
}
|
|
731
|
+
|
|
628
732
|
async function main() {
|
|
629
733
|
const [argument, ...rest] = process.argv.slice(2);
|
|
630
734
|
if (argument === "__serve") { await serve(rest[0], rest.slice(1)); return; }
|
|
735
|
+
if (argument === "--version" || argument === "-v") {
|
|
736
|
+
if (rest.length) throw new Error("用法:pi-webapp --version");
|
|
737
|
+
console.log(packageVersion);
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
if (argument === "update") {
|
|
741
|
+
const usage = "用法:pi-webapp update [--check]";
|
|
742
|
+
if (rest.length === 1 && ["--help", "-h"].includes(rest[0])) { console.log(usage); return; }
|
|
743
|
+
if (rest.length && !(rest.length === 1 && rest[0] === "--check")) throw new Error(usage);
|
|
744
|
+
await update(rest.length === 1);
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
if (argument === "logs") {
|
|
748
|
+
if (rest.length === 1 && ["--help", "-h"].includes(rest[0])) { console.log("用法:pi-webapp logs [--tail <N>] [--follow]"); return; }
|
|
749
|
+
const { showLogs } = await import("./launcher-logs.mjs");
|
|
750
|
+
try { await showLogs(logPath, rest); }
|
|
751
|
+
catch (error) { if (error?.code !== "ENOENT") throw error; throw new Error("还没有后台日志。请先启动后台服务;前台模式的日志直接输出到终端。"); }
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
if (argument === "doctor") {
|
|
755
|
+
if (rest.length === 1 && ["--help", "-h"].includes(rest[0])) { console.log("用法:pi-webapp doctor [--host <127.0.0.1|0.0.0.0>] [--port <1–65535>]"); return; }
|
|
756
|
+
const { showDoctor } = await import("./launcher-diagnostics.mjs");
|
|
757
|
+
const passed = await showDoctor({ args: rest, readState: readLauncherState, agentDir, async probePi() {
|
|
758
|
+
const cli = await locatePiCli();
|
|
759
|
+
return cli ? probeVersion(process.execPath, [cli]) : probeVersion("pi");
|
|
760
|
+
} });
|
|
761
|
+
if (!passed) process.exitCode = 1;
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
if (argument === "restart") {
|
|
765
|
+
if (rest.length === 1 && ["--help", "-h"].includes(rest[0])) { console.log("用法:pi-webapp restart"); return; }
|
|
766
|
+
if (rest.length) throw new Error("用法:pi-webapp restart");
|
|
767
|
+
await restart();
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
if (argument === "status" && rest.length === 1 && rest[0] === "--json") {
|
|
771
|
+
const { showStatus } = await import("./launcher-diagnostics.mjs");
|
|
772
|
+
await showStatus({ state: await activeState({ cleanup: false }), cliVersion: packageVersion });
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
631
775
|
if (argument === "stop" || argument === "status") {
|
|
632
776
|
const force = argument === "stop" && rest.length === 1 && rest[0] === "--force";
|
|
633
|
-
if (rest.length && !force) throw new Error(`用法:pi-webapp ${argument}${argument === "stop" ? " [--force]" : ""}`);
|
|
777
|
+
if (rest.length && !force) throw new Error(`用法:pi-webapp ${argument}${argument === "stop" ? " [--force]" : " [--json]"}`);
|
|
634
778
|
if (argument === "stop") await stop(force);
|
|
635
779
|
else {
|
|
636
780
|
const state = await activeState();
|
|
@@ -638,7 +782,7 @@ async function main() {
|
|
|
638
782
|
}
|
|
639
783
|
return;
|
|
640
784
|
}
|
|
641
|
-
const usage = "用法:pi-webapp [start] [--port <1–65535>] [--host <127.0.0.1|0.0.0.0>] [Pi 参数]\n pi-webapp status | stop [--force]";
|
|
785
|
+
const usage = "用法:pi-webapp [start] [--port <1–65535>] [--host <127.0.0.1|0.0.0.0>] [--foreground] [--no-open] [Pi 参数]\n pi-webapp status [--json] | stop [--force] | restart\n pi-webapp logs [--tail <N>] [--follow]\n pi-webapp doctor [--host <127.0.0.1|0.0.0.0>] [--port <1–65535>]\n pi-webapp --version | update [--check]";
|
|
642
786
|
if (argument === "--help" || argument === "-h" || (argument === "start" && rest.length === 1 && ["--help", "-h"].includes(rest[0]))) { console.log(usage); return; }
|
|
643
787
|
if (argument && argument !== "start" && !argument.startsWith("-")) throw new Error(usage);
|
|
644
788
|
await start(argument === "start" || !argument ? rest : [argument, ...rest]);
|