pi-mega-compact 0.4.19 → 0.4.20
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/dist/extensions/dashboard-server.js +47 -2
- package/dist/extensions/mega-compact.test.js +9 -4
- package/dist/extensions/mega-dashboard-cmds.js +89 -7
- package/extensions/dashboard-server.ts +42 -2
- package/extensions/mega-compact.test.ts +9 -4
- package/extensions/mega-dashboard-cmds.ts +81 -7
- package/package.json +1 -1
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
import { createServer } from "node:http";
|
|
14
14
|
import { existsSync, mkdirSync, readFileSync, unlinkSync, watch, writeFileSync } from "node:fs";
|
|
15
15
|
import { homedir } from "node:os";
|
|
16
|
-
import { join } from "node:path";
|
|
16
|
+
import { join, dirname } from "node:path";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
17
18
|
import Database from "better-sqlite3";
|
|
18
19
|
// --- Multi-repo index (Phase 5b) ------------------------------------------------
|
|
19
20
|
// The extension writes a machine-wide repo registry into a single SQLite DB
|
|
@@ -46,7 +47,7 @@ function readIndex() {
|
|
|
46
47
|
const rows = db
|
|
47
48
|
.prepare("SELECT * FROM repo_registry ORDER BY last_seen DESC")
|
|
48
49
|
.all();
|
|
49
|
-
const
|
|
50
|
+
const mapped = rows.map((r) => ({
|
|
50
51
|
repoRoot: String(r.repo_root ?? ""),
|
|
51
52
|
displayName: String(r.display_name ?? ""),
|
|
52
53
|
checkpointCount: Number(r.checkpoint_count ?? 0),
|
|
@@ -60,6 +61,23 @@ function readIndex() {
|
|
|
60
61
|
outputRate: r.output_rate ?? null,
|
|
61
62
|
lastSeen: Number(r.last_seen ?? 0),
|
|
62
63
|
}));
|
|
64
|
+
// Defensive display hygiene (belt-and-suspenders — the real fix is that
|
|
65
|
+
// tests now isolate via MEGACOMPACT_INDEX_DIR): drop transient test/temp
|
|
66
|
+
// paths that should never have been real repos, and collapse duplicate
|
|
67
|
+
// display names to the most-recently-seen row (rows are last_seen DESC, so
|
|
68
|
+
// the first occurrence wins). Keeps the All-repos list readable.
|
|
69
|
+
const isTransient = (p) => /^\/tmp\//.test(p) || /^\/private\/tmp\//.test(p) || /^\/var\/folders\//.test(p) ||
|
|
70
|
+
/\/mc-(ext|e2e|resume|recall)-/.test(p);
|
|
71
|
+
const seenName = new Set();
|
|
72
|
+
const repos = [];
|
|
73
|
+
for (const r of mapped) {
|
|
74
|
+
if (isTransient(r.repoRoot))
|
|
75
|
+
continue;
|
|
76
|
+
if (seenName.has(r.displayName))
|
|
77
|
+
continue;
|
|
78
|
+
seenName.add(r.displayName);
|
|
79
|
+
repos.push(r);
|
|
80
|
+
}
|
|
63
81
|
const summary = {
|
|
64
82
|
totalRepos: repos.length,
|
|
65
83
|
totalCheckpoints: repos.reduce((a, r) => a + r.checkpointCount, 0),
|
|
@@ -634,6 +652,26 @@ function dashboardHtml(tierName) {
|
|
|
634
652
|
// Server
|
|
635
653
|
// ---------------------------------------------------------------------------
|
|
636
654
|
export function launchDashboardServer(stateDir) {
|
|
655
|
+
// Our own package version — exposed at /api/version so the launcher can
|
|
656
|
+
// detect a stale server (started by an older build) and replace it on
|
|
657
|
+
// upgrade instead of reuse it.
|
|
658
|
+
let SERVER_VERSION = "0.0.0";
|
|
659
|
+
try {
|
|
660
|
+
// dashboard-server.js lives at <pkg>/dist/extensions/, so package.json is
|
|
661
|
+
// two levels up. Guard each candidate so a dev-checkout layout still works.
|
|
662
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
663
|
+
const candidates = [join(here, "..", "..", "package.json"), join(here, "..", "package.json")];
|
|
664
|
+
for (const p of candidates) {
|
|
665
|
+
if (!existsSync(p))
|
|
666
|
+
continue;
|
|
667
|
+
const pkg = JSON.parse(readFileSync(p, "utf-8"));
|
|
668
|
+
if (pkg.version) {
|
|
669
|
+
SERVER_VERSION = pkg.version;
|
|
670
|
+
break;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
catch { /* non-fatal */ }
|
|
637
675
|
const portFile = join(stateDir, "port.pid");
|
|
638
676
|
const snapshotPath = join(stateDir, "dashboard.json");
|
|
639
677
|
const eventsPath = join(stateDir, "events.log");
|
|
@@ -674,6 +712,13 @@ export function launchDashboardServer(stateDir) {
|
|
|
674
712
|
res.end(JSON.stringify(snap));
|
|
675
713
|
return;
|
|
676
714
|
}
|
|
715
|
+
// Server version — lets the /dashboard launcher detect a stale server from
|
|
716
|
+
// an older build and replace it on upgrade rather than reuse it.
|
|
717
|
+
if (req.url === "/api/version") {
|
|
718
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
719
|
+
res.end(JSON.stringify({ version: SERVER_VERSION }));
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
677
722
|
// Multi-repo aggregate (Phase 5b): the machine-wide repo registry read
|
|
678
723
|
// directly from SQLite (index.sqlite). Lets one dashboard show every repo's
|
|
679
724
|
// checkpoints, tokens saved, and active model. Read-only.
|
|
@@ -19,6 +19,9 @@ import { join } from "node:path";
|
|
|
19
19
|
import { createRequire } from "node:module";
|
|
20
20
|
const require = createRequire(import.meta.url);
|
|
21
21
|
const baseTmp = mkdtempSync(join(tmpdir(), "mc-ext-"));
|
|
22
|
+
// Isolate the machine-wide repo index so test runs (which call bindRepo ->
|
|
23
|
+
// upsertRepoRegistry) never pollute the developer's real ~/.mega-compact-index.
|
|
24
|
+
process.env.MEGACOMPACT_INDEX_DIR = join(baseTmp, "index");
|
|
22
25
|
let counter = 0;
|
|
23
26
|
/** Build a mock pi + ctx and load the extension into them. */
|
|
24
27
|
function harness(opts = {}) {
|
|
@@ -268,13 +271,14 @@ test("/dashboard-stop reports no server when pid file missing", async () => {
|
|
|
268
271
|
test("/dashboard skips server spawn when already running", async () => {
|
|
269
272
|
const h = harness();
|
|
270
273
|
const confirms = [];
|
|
271
|
-
// Set up a fake HTTP server
|
|
274
|
+
// Set up a fake HTTP server on a port inside the dashboard's scan range
|
|
275
|
+
// (9320–9329) — isServerRunning() probes those ports, not the port.pid value.
|
|
272
276
|
const { createServer } = await import("node:http");
|
|
273
277
|
const server = createServer((_req, res) => {
|
|
274
278
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
275
279
|
res.end(JSON.stringify({ updatedAt: new Date().toISOString(), tier: "test", version: 1, config: {}, session: {}, context: {}, trigger: {}, store: {} }));
|
|
276
280
|
});
|
|
277
|
-
await new Promise((r) => server.listen(
|
|
281
|
+
await new Promise((r) => server.listen(9320, "127.0.0.1", r));
|
|
278
282
|
const addr = server.address();
|
|
279
283
|
const { join: j } = await import("node:path");
|
|
280
284
|
const { writeFileSync: wf } = await import("node:fs");
|
|
@@ -295,7 +299,8 @@ test("/dashboard skips server spawn when already running", async () => {
|
|
|
295
299
|
});
|
|
296
300
|
test("/dashboard-status reports running after dashboard start", async () => {
|
|
297
301
|
const h = harness();
|
|
298
|
-
// Write a fake port.pid
|
|
302
|
+
// Write a fake port.pid; the server must listen inside the scan range
|
|
303
|
+
// (9320–9329) or isServerRunning() won't detect it.
|
|
299
304
|
const { createServer } = await import("node:http");
|
|
300
305
|
const { join: j } = await import("node:path");
|
|
301
306
|
const { writeFileSync: wf } = await import("node:fs");
|
|
@@ -303,7 +308,7 @@ test("/dashboard-status reports running after dashboard start", async () => {
|
|
|
303
308
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
304
309
|
res.end(JSON.stringify({ updatedAt: new Date().toISOString(), tier: "test" }));
|
|
305
310
|
});
|
|
306
|
-
await new Promise((r) => server.listen(
|
|
311
|
+
await new Promise((r) => server.listen(9321, "127.0.0.1", r));
|
|
307
312
|
const addr = server.address();
|
|
308
313
|
wf(j(h.stateDir, "port.pid"), JSON.stringify({ port: addr.port, pid: process.pid }));
|
|
309
314
|
const ctx = h.ctx();
|
|
@@ -32,7 +32,10 @@ export function registerDashboardCommands(pi, runtime) {
|
|
|
32
32
|
}
|
|
33
33
|
return null;
|
|
34
34
|
}
|
|
35
|
-
/** Try to reach a running dashboard server. Returns
|
|
35
|
+
/** Try to reach a running dashboard server. Returns details or null.
|
|
36
|
+
* `hasPidFile` tells the caller whether this server was launched by us
|
|
37
|
+
* (port.pid present) — a live server with NO pid file is an orphan from an
|
|
38
|
+
* older/detached spawn that we should replace rather than reuse. */
|
|
36
39
|
async function isServerRunning() {
|
|
37
40
|
const port = await findLivePort();
|
|
38
41
|
if (!port) {
|
|
@@ -45,7 +48,68 @@ export function registerDashboardCommands(pi, runtime) {
|
|
|
45
48
|
}
|
|
46
49
|
return null;
|
|
47
50
|
}
|
|
48
|
-
return { port, url: `http://localhost:${port}
|
|
51
|
+
return { port, url: `http://localhost:${port}`, hasPidFile: existsSync(portFile) }; // guardrails-allow PREVENT-PI-004: localhost URL of the dashboard server this extension spawned
|
|
52
|
+
}
|
|
53
|
+
/** Version the running server on `port` reports, or null. */
|
|
54
|
+
async function serverVersion(port) {
|
|
55
|
+
try {
|
|
56
|
+
const res = await fetch(`http://localhost:${port}/api/version`, { signal: AbortSignal.timeout(800) }); // guardrails-allow PREVENT-PI-004: localhost version probe of the dashboard server this extension spawned
|
|
57
|
+
if (!res.ok)
|
|
58
|
+
return null;
|
|
59
|
+
const j = await res.json();
|
|
60
|
+
return j.version ?? null;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Version of THIS extension (read from its own package.json). */
|
|
67
|
+
function ownVersion() {
|
|
68
|
+
try {
|
|
69
|
+
const here = dirname(fileURLToPath(import.meta.url)); // .../extensions
|
|
70
|
+
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf-8"));
|
|
71
|
+
return pkg.version ?? null;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** PID listening on 127.0.0.1:port (our own server), or null. Uses `ss`
|
|
78
|
+
* (Linux/macOS) — best-effort, returns null if unavailable. */
|
|
79
|
+
function pidOnPort(port) {
|
|
80
|
+
try {
|
|
81
|
+
const { execSync } = require("node:child_process"); // guardrails-allow PREVENT-PI-004: localhost-only, reads our own dashboard port owner
|
|
82
|
+
const out = execSync(`ss -ltnp 2>/dev/null | grep ':${port} '`, { encoding: "utf-8" });
|
|
83
|
+
const m = out.match(/pid=(\d+)/);
|
|
84
|
+
return m ? Number(m[1]) : null;
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Kill a running dashboard server (best-effort): read the pid from port.pid,
|
|
91
|
+
* or — when there's no marker (an orphan) — from the port owner. Then remove
|
|
92
|
+
* the marker so the next spawn starts fresh. */
|
|
93
|
+
function killServerOnPort(port) {
|
|
94
|
+
let pid = null;
|
|
95
|
+
try {
|
|
96
|
+
const info = JSON.parse(readFileSync(portFile, "utf-8"));
|
|
97
|
+
if (info && info.pid)
|
|
98
|
+
pid = info.pid;
|
|
99
|
+
}
|
|
100
|
+
catch { /* no marker */ }
|
|
101
|
+
if (pid == null)
|
|
102
|
+
pid = pidOnPort(port); // orphan with no pid.pid
|
|
103
|
+
if (pid != null) {
|
|
104
|
+
try {
|
|
105
|
+
process.kill(pid, "SIGTERM");
|
|
106
|
+
}
|
|
107
|
+
catch { /* already gone */ }
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
unlinkSync(portFile);
|
|
111
|
+
}
|
|
112
|
+
catch { /* ignore */ }
|
|
49
113
|
}
|
|
50
114
|
/**
|
|
51
115
|
* Resolve the launchable dashboard-server module.
|
|
@@ -119,11 +183,29 @@ export function registerDashboardCommands(pi, runtime) {
|
|
|
119
183
|
runtime.bindRepo(ctx.cwd);
|
|
120
184
|
let info = await isServerRunning();
|
|
121
185
|
if (info) {
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
186
|
+
// Replace the server when it's stale: either (a) an orphan — a live
|
|
187
|
+
// server with no port.pid (e.g. left running from a detached spawn or a
|
|
188
|
+
// previous upgrade) that keeps serving old HTML from memory; or (b) a
|
|
189
|
+
// server that reports a different version than this extension (an older
|
|
190
|
+
// build). A live server WITH a matching pid file and version is reused.
|
|
191
|
+
const orphan = !info.hasPidFile;
|
|
192
|
+
const running = await serverVersion(info.port);
|
|
193
|
+
const want = ownVersion();
|
|
194
|
+
const stale = orphan || (want != null && running != null && running !== want);
|
|
195
|
+
if (stale) {
|
|
196
|
+
ctx.ui.notify(orphan
|
|
197
|
+
? "[mega-compact] replacing orphaned dashboard server…"
|
|
198
|
+
: `[mega-compact] replacing stale dashboard (${running} → ${want})…`);
|
|
199
|
+
killServerOnPort(info.port);
|
|
200
|
+
info = null;
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
ctx.ui.notify(`[mega-compact] dashboard already running at ${info.url}`);
|
|
204
|
+
const open = await ctx.ui.confirm("mega-compact dashboard", `Open ${info.url} in browser?`);
|
|
205
|
+
if (open)
|
|
206
|
+
openBrowser(info.url);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
127
209
|
}
|
|
128
210
|
// Start the server
|
|
129
211
|
ctx.ui.notify("[mega-compact] starting dashboard server…");
|
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
15
15
|
import { existsSync, mkdirSync, readFileSync, unlinkSync, watch, writeFileSync } from "node:fs";
|
|
16
16
|
import { homedir } from "node:os";
|
|
17
|
-
import { join } from "node:path";
|
|
17
|
+
import { join, dirname } from "node:path";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
18
19
|
import Database from "better-sqlite3";
|
|
19
20
|
|
|
20
21
|
// --- Multi-repo index (Phase 5b) ------------------------------------------------
|
|
@@ -61,7 +62,7 @@ function readIndex(): { updatedAt: string; summary: unknown; repos: unknown[] }
|
|
|
61
62
|
const rows = db
|
|
62
63
|
.prepare("SELECT * FROM repo_registry ORDER BY last_seen DESC")
|
|
63
64
|
.all() as Record<string, unknown>[];
|
|
64
|
-
const
|
|
65
|
+
const mapped: IndexRepo[] = rows.map((r) => ({
|
|
65
66
|
repoRoot: String(r.repo_root ?? ""),
|
|
66
67
|
displayName: String(r.display_name ?? ""),
|
|
67
68
|
checkpointCount: Number(r.checkpoint_count ?? 0),
|
|
@@ -75,6 +76,22 @@ function readIndex(): { updatedAt: string; summary: unknown; repos: unknown[] }
|
|
|
75
76
|
outputRate: (r.output_rate as number | null) ?? null,
|
|
76
77
|
lastSeen: Number(r.last_seen ?? 0),
|
|
77
78
|
}));
|
|
79
|
+
// Defensive display hygiene (belt-and-suspenders — the real fix is that
|
|
80
|
+
// tests now isolate via MEGACOMPACT_INDEX_DIR): drop transient test/temp
|
|
81
|
+
// paths that should never have been real repos, and collapse duplicate
|
|
82
|
+
// display names to the most-recently-seen row (rows are last_seen DESC, so
|
|
83
|
+
// the first occurrence wins). Keeps the All-repos list readable.
|
|
84
|
+
const isTransient = (p: string) =>
|
|
85
|
+
/^\/tmp\//.test(p) || /^\/private\/tmp\//.test(p) || /^\/var\/folders\//.test(p) ||
|
|
86
|
+
/\/mc-(ext|e2e|resume|recall)-/.test(p);
|
|
87
|
+
const seenName = new Set<string>();
|
|
88
|
+
const repos: IndexRepo[] = [];
|
|
89
|
+
for (const r of mapped) {
|
|
90
|
+
if (isTransient(r.repoRoot)) continue;
|
|
91
|
+
if (seenName.has(r.displayName)) continue;
|
|
92
|
+
seenName.add(r.displayName);
|
|
93
|
+
repos.push(r);
|
|
94
|
+
}
|
|
78
95
|
const summary = {
|
|
79
96
|
totalRepos: repos.length,
|
|
80
97
|
totalCheckpoints: repos.reduce((a, r) => a + r.checkpointCount, 0),
|
|
@@ -722,6 +739,21 @@ function dashboardHtml(tierName: string): string {
|
|
|
722
739
|
// ---------------------------------------------------------------------------
|
|
723
740
|
|
|
724
741
|
export function launchDashboardServer(stateDir: string): Promise<{ port: number; url: string }> {
|
|
742
|
+
// Our own package version — exposed at /api/version so the launcher can
|
|
743
|
+
// detect a stale server (started by an older build) and replace it on
|
|
744
|
+
// upgrade instead of reuse it.
|
|
745
|
+
let SERVER_VERSION = "0.0.0";
|
|
746
|
+
try {
|
|
747
|
+
// dashboard-server.js lives at <pkg>/dist/extensions/, so package.json is
|
|
748
|
+
// two levels up. Guard each candidate so a dev-checkout layout still works.
|
|
749
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
750
|
+
const candidates = [join(here, "..", "..", "package.json"), join(here, "..", "package.json")];
|
|
751
|
+
for (const p of candidates) {
|
|
752
|
+
if (!existsSync(p)) continue;
|
|
753
|
+
const pkg = JSON.parse(readFileSync(p, "utf-8"));
|
|
754
|
+
if (pkg.version) { SERVER_VERSION = pkg.version; break; }
|
|
755
|
+
}
|
|
756
|
+
} catch { /* non-fatal */ }
|
|
725
757
|
const portFile = join(stateDir, "port.pid");
|
|
726
758
|
const snapshotPath = join(stateDir, "dashboard.json");
|
|
727
759
|
const eventsPath = join(stateDir, "events.log");
|
|
@@ -769,6 +801,14 @@ export function launchDashboardServer(stateDir: string): Promise<{ port: number;
|
|
|
769
801
|
return;
|
|
770
802
|
}
|
|
771
803
|
|
|
804
|
+
// Server version — lets the /dashboard launcher detect a stale server from
|
|
805
|
+
// an older build and replace it on upgrade rather than reuse it.
|
|
806
|
+
if (req.url === "/api/version") {
|
|
807
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
808
|
+
res.end(JSON.stringify({ version: SERVER_VERSION }));
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
|
|
772
812
|
// Multi-repo aggregate (Phase 5b): the machine-wide repo registry read
|
|
773
813
|
// directly from SQLite (index.sqlite). Lets one dashboard show every repo's
|
|
774
814
|
// checkpoints, tokens saved, and active model. Read-only.
|
|
@@ -22,6 +22,9 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
|
22
22
|
|
|
23
23
|
const require = createRequire(import.meta.url);
|
|
24
24
|
const baseTmp = mkdtempSync(join(tmpdir(), "mc-ext-"));
|
|
25
|
+
// Isolate the machine-wide repo index so test runs (which call bindRepo ->
|
|
26
|
+
// upsertRepoRegistry) never pollute the developer's real ~/.mega-compact-index.
|
|
27
|
+
process.env.MEGACOMPACT_INDEX_DIR = join(baseTmp, "index");
|
|
25
28
|
let counter = 0;
|
|
26
29
|
|
|
27
30
|
/** Build a mock pi + ctx and load the extension into them. */
|
|
@@ -297,13 +300,14 @@ test("/dashboard-stop reports no server when pid file missing", async () => {
|
|
|
297
300
|
test("/dashboard skips server spawn when already running", async () => {
|
|
298
301
|
const h = harness();
|
|
299
302
|
const confirms: boolean[] = [];
|
|
300
|
-
// Set up a fake HTTP server
|
|
303
|
+
// Set up a fake HTTP server on a port inside the dashboard's scan range
|
|
304
|
+
// (9320–9329) — isServerRunning() probes those ports, not the port.pid value.
|
|
301
305
|
const { createServer } = await import("node:http");
|
|
302
306
|
const server = createServer((_req, res) => {
|
|
303
307
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
304
308
|
res.end(JSON.stringify({ updatedAt: new Date().toISOString(), tier: "test", version: 1, config: {}, session: {}, context: {}, trigger: {}, store: {} }));
|
|
305
309
|
});
|
|
306
|
-
await new Promise<void>((r) => server.listen(
|
|
310
|
+
await new Promise<void>((r) => server.listen(9320, "127.0.0.1", r));
|
|
307
311
|
const addr = server.address() as any;
|
|
308
312
|
const { join: j } = await import("node:path");
|
|
309
313
|
const { writeFileSync: wf } = await import("node:fs");
|
|
@@ -328,7 +332,8 @@ test("/dashboard skips server spawn when already running", async () => {
|
|
|
328
332
|
|
|
329
333
|
test("/dashboard-status reports running after dashboard start", async () => {
|
|
330
334
|
const h = harness();
|
|
331
|
-
// Write a fake port.pid
|
|
335
|
+
// Write a fake port.pid; the server must listen inside the scan range
|
|
336
|
+
// (9320–9329) or isServerRunning() won't detect it.
|
|
332
337
|
const { createServer } = await import("node:http");
|
|
333
338
|
const { join: j } = await import("node:path");
|
|
334
339
|
const { writeFileSync: wf } = await import("node:fs");
|
|
@@ -336,7 +341,7 @@ test("/dashboard-status reports running after dashboard start", async () => {
|
|
|
336
341
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
337
342
|
res.end(JSON.stringify({ updatedAt: new Date().toISOString(), tier: "test" }));
|
|
338
343
|
});
|
|
339
|
-
await new Promise<void>((r) => server.listen(
|
|
344
|
+
await new Promise<void>((r) => server.listen(9321, "127.0.0.1", r));
|
|
340
345
|
const addr = server.address() as any;
|
|
341
346
|
wf(j(h.stateDir, "port.pid"), JSON.stringify({ port: addr.port, pid: process.pid }));
|
|
342
347
|
|
|
@@ -36,8 +36,11 @@ export function registerDashboardCommands(pi: ExtensionAPI, runtime: MegaRuntime
|
|
|
36
36
|
return null;
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
/** Try to reach a running dashboard server. Returns
|
|
40
|
-
|
|
39
|
+
/** Try to reach a running dashboard server. Returns details or null.
|
|
40
|
+
* `hasPidFile` tells the caller whether this server was launched by us
|
|
41
|
+
* (port.pid present) — a live server with NO pid file is an orphan from an
|
|
42
|
+
* older/detached spawn that we should replace rather than reuse. */
|
|
43
|
+
async function isServerRunning(): Promise<{ port: number; url: string; hasPidFile: boolean } | null> {
|
|
41
44
|
const port = await findLivePort();
|
|
42
45
|
if (!port) {
|
|
43
46
|
// Stale marker with no live server behind it — clean up.
|
|
@@ -46,7 +49,59 @@ export function registerDashboardCommands(pi: ExtensionAPI, runtime: MegaRuntime
|
|
|
46
49
|
}
|
|
47
50
|
return null;
|
|
48
51
|
}
|
|
49
|
-
return { port, url: `http://localhost:${port}
|
|
52
|
+
return { port, url: `http://localhost:${port}`, hasPidFile: existsSync(portFile) }; // guardrails-allow PREVENT-PI-004: localhost URL of the dashboard server this extension spawned
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Version the running server on `port` reports, or null. */
|
|
56
|
+
async function serverVersion(port: number): Promise<string | null> {
|
|
57
|
+
try {
|
|
58
|
+
const res = await fetch(`http://localhost:${port}/api/version`, { signal: AbortSignal.timeout(800) }); // guardrails-allow PREVENT-PI-004: localhost version probe of the dashboard server this extension spawned
|
|
59
|
+
if (!res.ok) return null;
|
|
60
|
+
const j = await res.json() as { version?: string };
|
|
61
|
+
return j.version ?? null;
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Version of THIS extension (read from its own package.json). */
|
|
68
|
+
function ownVersion(): string | null {
|
|
69
|
+
try {
|
|
70
|
+
const here = dirname(fileURLToPath(import.meta.url)); // .../extensions
|
|
71
|
+
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf-8"));
|
|
72
|
+
return pkg.version ?? null;
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** PID listening on 127.0.0.1:port (our own server), or null. Uses `ss`
|
|
79
|
+
* (Linux/macOS) — best-effort, returns null if unavailable. */
|
|
80
|
+
function pidOnPort(port: number): number | null {
|
|
81
|
+
try {
|
|
82
|
+
const { execSync } = require("node:child_process"); // guardrails-allow PREVENT-PI-004: localhost-only, reads our own dashboard port owner
|
|
83
|
+
const out = execSync(`ss -ltnp 2>/dev/null | grep ':${port} '`, { encoding: "utf-8" });
|
|
84
|
+
const m = out.match(/pid=(\d+)/);
|
|
85
|
+
return m ? Number(m[1]) : null;
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Kill a running dashboard server (best-effort): read the pid from port.pid,
|
|
92
|
+
* or — when there's no marker (an orphan) — from the port owner. Then remove
|
|
93
|
+
* the marker so the next spawn starts fresh. */
|
|
94
|
+
function killServerOnPort(port: number): void {
|
|
95
|
+
let pid: number | null = null;
|
|
96
|
+
try {
|
|
97
|
+
const info = JSON.parse(readFileSync(portFile, "utf-8"));
|
|
98
|
+
if (info && info.pid) pid = info.pid;
|
|
99
|
+
} catch { /* no marker */ }
|
|
100
|
+
if (pid == null) pid = pidOnPort(port); // orphan with no pid.pid
|
|
101
|
+
if (pid != null) {
|
|
102
|
+
try { process.kill(pid, "SIGTERM"); } catch { /* already gone */ }
|
|
103
|
+
}
|
|
104
|
+
try { unlinkSync(portFile); } catch { /* ignore */ }
|
|
50
105
|
}
|
|
51
106
|
|
|
52
107
|
/**
|
|
@@ -122,10 +177,29 @@ export function registerDashboardCommands(pi: ExtensionAPI, runtime: MegaRuntime
|
|
|
122
177
|
let info = await isServerRunning();
|
|
123
178
|
|
|
124
179
|
if (info) {
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
180
|
+
// Replace the server when it's stale: either (a) an orphan — a live
|
|
181
|
+
// server with no port.pid (e.g. left running from a detached spawn or a
|
|
182
|
+
// previous upgrade) that keeps serving old HTML from memory; or (b) a
|
|
183
|
+
// server that reports a different version than this extension (an older
|
|
184
|
+
// build). A live server WITH a matching pid file and version is reused.
|
|
185
|
+
const orphan = !info.hasPidFile;
|
|
186
|
+
const running = await serverVersion(info.port);
|
|
187
|
+
const want = ownVersion();
|
|
188
|
+
const stale = orphan || (want != null && running != null && running !== want);
|
|
189
|
+
if (stale) {
|
|
190
|
+
ctx.ui.notify(
|
|
191
|
+
orphan
|
|
192
|
+
? "[mega-compact] replacing orphaned dashboard server…"
|
|
193
|
+
: `[mega-compact] replacing stale dashboard (${running} → ${want})…`,
|
|
194
|
+
);
|
|
195
|
+
killServerOnPort(info.port);
|
|
196
|
+
info = null;
|
|
197
|
+
} else {
|
|
198
|
+
ctx.ui.notify(`[mega-compact] dashboard already running at ${info.url}`);
|
|
199
|
+
const open = await ctx.ui.confirm("mega-compact dashboard", `Open ${info.url} in browser?`);
|
|
200
|
+
if (open) openBrowser(info.url);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
129
203
|
}
|
|
130
204
|
|
|
131
205
|
// Start the server
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mega-compact",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.20",
|
|
4
4
|
"description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "BSD-2-Clause",
|