@andares/pi-toolkits 1.0.2 → 1.1.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.
@@ -0,0 +1,271 @@
1
+ /**
2
+ * keep feature — session facts and the ledger rebuild.
3
+ *
4
+ * Everything here answers a question about a *session file*, not about the
5
+ * ledger: which session am I in, is it persisted, what was its first user
6
+ * message, and can an older session's keep breadcrumb be recovered from its
7
+ * tail. Nothing in this module calls `SessionManager.list` — the host's own
8
+ * listing costs 576 ms for this project's 109 sessions and 9.8 s for the whole
9
+ * agent dir, which is fine behind a progress spinner and far too slow here.
10
+ */
11
+ import {
12
+ closeSync,
13
+ existsSync,
14
+ openSync,
15
+ readSync,
16
+ readdirSync,
17
+ realpathSync,
18
+ statSync,
19
+ } from "node:fs";
20
+ import { join, resolve } from "node:path";
21
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
22
+ import { KEEP_ENTRY, KEEP_NOTE_MAX, KEEP_TAIL_BYTES } from "./constants.js";
23
+ import { appendKeep, isKeepLedgerEvent, type KeepState } from "./ledger.js";
24
+ import { readLedgerLines } from "../../lib/event-ledger.js";
25
+
26
+ /** What the current session is, as far as keep is concerned. */
27
+ export interface KeepSessionInfo {
28
+ readonly session: string;
29
+ readonly file: string;
30
+ readonly cwd: string;
31
+ readonly name?: string;
32
+ /** A user or assistant message exists, so the session file is on disk. */
33
+ readonly hasConversation: boolean;
34
+ readonly firstUserText?: string;
35
+ }
36
+
37
+ /** Resolve symlinks so the ledger always names one canonical session file. */
38
+ export function canonicalSessionFile(file: string): string {
39
+ try {
40
+ return realpathSync(file);
41
+ } catch {
42
+ // Keep a stable absolute path even when the file was just deleted; the
43
+ // caller still performs the separate persistence check.
44
+ return resolve(file);
45
+ }
46
+ }
47
+
48
+ type ContextEntry = ReturnType<ExtensionContext["sessionManager"]["buildContextEntries"]>[number];
49
+
50
+ /** Text of a message content field (`string` or text blocks). */
51
+ function contentText(content: unknown): string {
52
+ if (typeof content === "string") return content;
53
+ if (!Array.isArray(content)) return "";
54
+ const parts: string[] = [];
55
+ for (const part of content) {
56
+ if (!part || typeof part !== "object") continue;
57
+ const block = part as { type?: unknown; text?: unknown };
58
+ if (block.type === "text" && typeof block.text === "string") parts.push(block.text);
59
+ }
60
+ return parts.join(" ");
61
+ }
62
+
63
+ function roleOf(entry: ContextEntry): string | undefined {
64
+ if (entry.type !== "message") return undefined;
65
+ const message = entry.message as { role?: unknown } | undefined;
66
+ return typeof message?.role === "string" ? message.role : undefined;
67
+ }
68
+
69
+ /**
70
+ * Describe the session this context belongs to.
71
+ *
72
+ * Returns `undefined` for in-memory sessions (`--no-session`): there is no
73
+ * file to reload, so keep must refuse rather than record a path that will
74
+ * never exist.
75
+ */
76
+ export function currentSessionInfo(ctx: ExtensionContext): KeepSessionInfo | undefined {
77
+ const manager = ctx.sessionManager;
78
+ const file = manager.getSessionFile();
79
+ if (!file) return undefined;
80
+
81
+ const entries = manager.buildContextEntries();
82
+ let hasConversation = false;
83
+ let firstUserText: string | undefined;
84
+ for (const entry of entries) {
85
+ const role = roleOf(entry);
86
+ if (role !== "user" && role !== "assistant") continue;
87
+ hasConversation = true;
88
+ if (role === "user" && firstUserText === undefined && entry.type === "message") {
89
+ const text = contentText((entry.message as { content?: unknown }).content).trim();
90
+ if (text.length > 0) firstUserText = text;
91
+ }
92
+ }
93
+
94
+ return {
95
+ session: manager.getSessionId(),
96
+ file: canonicalSessionFile(file),
97
+ cwd: manager.getCwd(),
98
+ name: manager.getSessionName(),
99
+ hasConversation,
100
+ firstUserText,
101
+ };
102
+ }
103
+
104
+ /** Collapse whitespace and cap the note: a reminder, not a summary. */
105
+ export function truncateNote(text: string, max = KEEP_NOTE_MAX): string {
106
+ // Notes are rendered directly in the terminal and in the model transcript.
107
+ // Collapse whitespace, then remove terminal-control characters so a pasted
108
+ // escape sequence cannot become terminal input/output on the next list.
109
+ const clean = text.replace(/\s+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
110
+ const chars = [...clean];
111
+ if (chars.length <= max) return clean;
112
+ return `${chars.slice(0, Math.max(1, max - 1)).join("")}…`;
113
+ }
114
+
115
+ /**
116
+ * Pick the note for a keep: explicit argument, then the note this session got
117
+ * last time, then the session display name, then the first user message.
118
+ */
119
+ export function defaultNote(input: {
120
+ readonly explicit?: string;
121
+ readonly info: KeepSessionInfo;
122
+ readonly previous?: string;
123
+ }): string {
124
+ const explicit = input.explicit?.trim();
125
+ if (explicit) return truncateNote(explicit);
126
+ const previous = input.previous?.trim();
127
+ if (previous) return truncateNote(previous);
128
+ const name = input.info.name?.trim();
129
+ if (name) return truncateNote(name);
130
+ const first = input.info.firstUserText?.trim();
131
+ if (first) return truncateNote(first);
132
+ return "(no note)";
133
+ }
134
+
135
+ /** First line of a session file (the header), read without loading the file. */
136
+ export function readSessionHeader(file: string): { id?: string; cwd?: string } | undefined {
137
+ let fd: number;
138
+ try {
139
+ fd = openSync(file, "r");
140
+ } catch {
141
+ return undefined;
142
+ }
143
+ try {
144
+ const size = statSync(file).size;
145
+ const length = Math.min(8192, size);
146
+ if (length === 0) return undefined;
147
+ const buffer = Buffer.allocUnsafe(length);
148
+ readSync(fd, buffer, 0, length, 0);
149
+ const text = buffer.toString("utf8");
150
+ const end = text.indexOf("\n");
151
+ const line = end === -1 ? text : text.slice(0, end);
152
+ const parsed = JSON.parse(line) as { type?: unknown; id?: unknown; cwd?: unknown };
153
+ if (parsed.type !== "session") return undefined;
154
+ return {
155
+ id: typeof parsed.id === "string" ? parsed.id : undefined,
156
+ cwd: typeof parsed.cwd === "string" ? parsed.cwd : undefined,
157
+ };
158
+ } catch {
159
+ return undefined;
160
+ } finally {
161
+ closeSync(fd);
162
+ }
163
+ }
164
+
165
+ /** Complete lines from the end of a file (the first, partial line is dropped). */
166
+ export function readTailLines(file: string, bytes = KEEP_TAIL_BYTES): string[] {
167
+ let fd: number;
168
+ let size: number;
169
+ try {
170
+ size = statSync(file).size;
171
+ fd = openSync(file, "r");
172
+ } catch {
173
+ return [];
174
+ }
175
+ try {
176
+ const length = Math.min(bytes, size);
177
+ if (length === 0) return [];
178
+ const buffer = Buffer.allocUnsafe(length);
179
+ readSync(fd, buffer, 0, length, size - length);
180
+ const text = buffer.toString("utf8");
181
+ const lines = text.split("\n");
182
+ // The window almost never starts on a line boundary.
183
+ if (length < size) lines.shift();
184
+ return lines.filter((line) => line.trim().length > 0);
185
+ } catch {
186
+ return [];
187
+ } finally {
188
+ closeSync(fd);
189
+ }
190
+ }
191
+
192
+ export interface RebuildResult {
193
+ readonly scanned: number;
194
+ readonly restored: number;
195
+ }
196
+
197
+ /**
198
+ * Re-add keeps whose ledger line was lost, using the breadcrumb the session
199
+ * file still carries. Only the tail is read: a breadcrumb is appended at quit
200
+ * time, so it sits at the end (and if the session was reopened afterwards the
201
+ * last keep is no longer the tail's business — `keep` events are authoritative
202
+ * and this path only ever adds).
203
+ */
204
+ export function rebuildKeepLedger(input: {
205
+ readonly dir: string;
206
+ readonly ledger: string;
207
+ readonly state: KeepState;
208
+ readonly now?: Date;
209
+ }): RebuildResult {
210
+ const now = input.now ?? new Date();
211
+ if (!existsSync(input.dir)) return { scanned: 0, restored: 0 };
212
+
213
+ // Any event for a session proves its keep history is present. In particular,
214
+ // an explicit drop must never be undone by its still-present breadcrumb.
215
+ const known = new Set(input.state.entries.map((entry) => entry.session));
216
+ for (const event of readLedgerLines(input.ledger, isKeepLedgerEvent).events) {
217
+ known.add(event.session);
218
+ }
219
+ const files = readdirSync(input.dir).filter((name) => name.endsWith(".jsonl"));
220
+ let scanned = 0;
221
+ let restored = 0;
222
+
223
+ for (const name of files) {
224
+ const file = join(input.dir, name);
225
+ scanned += 1;
226
+ const lines = readTailLines(file);
227
+ if (lines.length === 0) continue;
228
+ if (!lines.some((line) => line.includes(KEEP_ENTRY))) continue;
229
+
230
+ const header = readSessionHeader(file);
231
+ if (!header?.id || known.has(header.id)) continue;
232
+
233
+ let breadcrumb: { note?: unknown; at?: unknown } | undefined;
234
+ for (const line of lines) {
235
+ if (!line.includes(KEEP_ENTRY)) continue;
236
+ try {
237
+ const parsed = JSON.parse(line) as { customType?: unknown; data?: unknown };
238
+ if (parsed.customType !== KEEP_ENTRY) continue;
239
+ if (!parsed.data || typeof parsed.data !== "object") continue;
240
+ breadcrumb = parsed.data as { note?: unknown; at?: unknown };
241
+ } catch {
242
+ // A malformed line is not a breadcrumb; keep looking.
243
+ }
244
+ }
245
+ if (!breadcrumb) continue;
246
+
247
+ const note = typeof breadcrumb.note === "string" ? truncateNote(breadcrumb.note) : "(no note)";
248
+ const at = typeof breadcrumb.at === "number" && Number.isFinite(breadcrumb.at)
249
+ ? new Date(breadcrumb.at)
250
+ : now;
251
+ appendKeep(
252
+ input.ledger,
253
+ {
254
+ session: header.id,
255
+ file: canonicalSessionFile(file),
256
+ cwd: header.cwd ?? input.state.entries[0]?.cwd ?? "",
257
+ note,
258
+ },
259
+ at,
260
+ );
261
+ known.add(header.id);
262
+ restored += 1;
263
+ }
264
+
265
+ return { scanned, restored };
266
+ }
267
+
268
+ /** Cheap existence probe used by tests and by the picker's `missing` flag. */
269
+ export function sessionFileExists(file: string): boolean {
270
+ return existsSync(file);
271
+ }
@@ -133,6 +133,55 @@ async function decide(url: string, action: "approve" | "deny"): Promise<number>
133
133
  });
134
134
  }
135
135
 
136
+ /** Read `/api/state` the way the page does. */
137
+ async function reviewState(url: string): Promise<{
138
+ totalVersions: number;
139
+ version: number;
140
+ history: Array<{ n: number }>;
141
+ }> {
142
+ const parsed = new URL(url);
143
+ const token = parsed.searchParams.get("t") ?? "";
144
+ return new Promise((resolve, reject) => {
145
+ const req = request(
146
+ {
147
+ host: "127.0.0.1",
148
+ port: Number(parsed.port),
149
+ path: "/api/state",
150
+ method: "GET",
151
+ headers: { "x-plan-token": token },
152
+ },
153
+ (res) => {
154
+ const chunks: Buffer[] = [];
155
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
156
+ res.on("end", () => {
157
+ if (res.statusCode !== 200) {
158
+ reject(new Error(`state HTTP ${res.statusCode}`));
159
+ return;
160
+ }
161
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")) as never);
162
+ });
163
+ },
164
+ );
165
+ req.on("error", reject);
166
+ req.end();
167
+ });
168
+ }
169
+
170
+ /** Resolve once nothing accepts connections on that URL's port any more. */
171
+ async function waitUntilClosed(url: string): Promise<void> {
172
+ const port = Number(new URL(url).port);
173
+ for (let attempt = 0; attempt < 100; attempt += 1) {
174
+ const up = await new Promise<boolean>((resolve) => {
175
+ const req = request({ host: "127.0.0.1", port, path: "/", method: "GET" }, () => resolve(true));
176
+ req.on("error", () => resolve(false));
177
+ req.end();
178
+ });
179
+ if (!up) return;
180
+ await new Promise((done) => setTimeout(done, 20));
181
+ }
182
+ throw new Error(`server on port ${port} never closed`);
183
+ }
184
+
136
185
  describe("ask-spec command", () => {
137
186
  it("enters spec mode: permission on, submit tool active, kickoff sent", async () => {
138
187
  const h = harness();
@@ -167,6 +216,78 @@ describe("ask-spec command", () => {
167
216
  expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("specs/spec.md"), "info");
168
217
  });
169
218
 
219
+ it("leaves spec mode when the bare command is run again", async () => {
220
+ const h = harness();
221
+ const handler = h.commands.get(SPEC_COMMAND)!.handler;
222
+ await handler("topic", h.ctx);
223
+ h.notify.mockClear();
224
+
225
+ await handler("", h.ctx);
226
+ expect(h.control.restore).toHaveBeenCalled();
227
+ expect(h.activeTools()).not.toContain(SPEC_SUBMIT_TOOL);
228
+ expect(h.notify).toHaveBeenCalledWith(expect.stringContaining("spec mode off"), "info");
229
+ expect(h.sendUserMessage).toHaveBeenCalledTimes(1);
230
+
231
+ // The next bare invocation starts a fresh default-topic review.
232
+ await handler("", h.ctx);
233
+ expect(h.activeTools()).toContain(SPEC_SUBMIT_TOOL);
234
+ expect(h.notify).toHaveBeenLastCalledWith(expect.stringContaining("specs/spec.md"), "info");
235
+ expect(h.sendUserMessage).toHaveBeenCalledTimes(2);
236
+ });
237
+
238
+ it("opens a new window and server for the revision after feedback, keeping history", async () => {
239
+ const h = harness();
240
+ const handler = h.commands.get(SPEC_COMMAND)!.handler;
241
+ await handler("topic", h.ctx);
242
+
243
+ writeSpec("specs/topic.md", "# SPEC: one");
244
+ const first = await h.tools.get(SPEC_SUBMIT_TOOL)!.execute("id", { path: "specs/topic.md" });
245
+ const firstUrl = (first.details as { url: string }).url;
246
+ expect(h.openBrowser).toHaveBeenCalledTimes(1);
247
+
248
+ // Feedback closes the review server shortly after the decision.
249
+ expect(await decide(firstUrl, "deny")).toBe(200);
250
+ await waitUntilClosed(firstUrl);
251
+
252
+ // The next revision must get its own server and its own window.
253
+ writeSpec("specs/topic.md", "# SPEC: one\n\nA second paragraph.");
254
+ const second = await h.tools.get(SPEC_SUBMIT_TOOL)!.execute("id", {
255
+ path: "specs/topic.md",
256
+ });
257
+ const secondUrl = (second.details as { url: string }).url;
258
+
259
+ expect(secondUrl).not.toBe(firstUrl);
260
+ expect(h.openBrowser).toHaveBeenCalledTimes(2);
261
+ const state = await reviewState(secondUrl);
262
+ expect(state.totalVersions).toBe(2);
263
+ expect(state.history.map((entry) => entry.n)).toEqual([2, 1]);
264
+
265
+ await handler("off", h.ctx);
266
+ });
267
+
268
+ it("restarts a closed review server when the page is reopened", async () => {
269
+ const h = harness();
270
+ const handler = h.commands.get(SPEC_COMMAND)!.handler;
271
+ await handler("topic", h.ctx);
272
+
273
+ writeSpec("specs/topic.md", "# SPEC: one");
274
+ const first = await h.tools.get(SPEC_SUBMIT_TOOL)!.execute("id", { path: "specs/topic.md" });
275
+ const firstUrl = (first.details as { url: string }).url;
276
+ expect(await decide(firstUrl, "deny")).toBe(200);
277
+ await waitUntilClosed(firstUrl);
278
+
279
+ h.notify.mockClear();
280
+ await handler("open", h.ctx);
281
+ expect(h.openBrowser).toHaveBeenCalledTimes(2);
282
+ const notified = String(h.notify.mock.calls.at(-1)?.[0] ?? "");
283
+ const secondUrl = /http:\/\/\S+/.exec(notified)?.[0] ?? "";
284
+ expect(secondUrl).not.toBe("");
285
+ expect(secondUrl).not.toBe(firstUrl);
286
+ expect((await reviewState(secondUrl)).totalVersions).toBe(1);
287
+
288
+ await handler("off", h.ctx);
289
+ });
290
+
170
291
  it("refuses to start twice and can be turned off", async () => {
171
292
  const h = harness();
172
293
  const handler = h.commands.get(SPEC_COMMAND)!.handler;
@@ -98,6 +98,8 @@ export interface SpecOptions {
98
98
  closeDelayMs?: number;
99
99
  /** Port search starts here; the review server walks upward. */
100
100
  portStart?: number;
101
+ /** How many ports the review server may try before giving up (default 20). */
102
+ portAttempts?: number;
101
103
  }
102
104
 
103
105
  export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOptions = {}): void {
@@ -116,8 +118,47 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
116
118
 
117
119
  function closeServer(): void {
118
120
  if (!server) return;
119
- void server.close();
121
+ const closing = server;
120
122
  server = undefined;
123
+ void closing.close();
124
+ }
125
+
126
+ /**
127
+ * Start the review server for the current session.
128
+ *
129
+ * Every start gets its own token and walks the port range, so a restarted
130
+ * review never reuses a dead socket and two sessions cannot share a window.
131
+ */
132
+ function startReviewServer(current: SpecSession): Promise<SpecServerHandle> {
133
+ return startSpecServer({
134
+ session: current,
135
+ render: renderBlockHtml,
136
+ portStart: options.portStart,
137
+ portAttempts: options.portAttempts,
138
+ closeDelayMs: options.closeDelayMs,
139
+ onDecision: ({ action, version: decidedVersion }) => {
140
+ const ctx = ctxRef;
141
+ if (ctx) void handleDecision({ action, version: decidedVersion }, ctx);
142
+ },
143
+ });
144
+ }
145
+
146
+ /**
147
+ * A live handle, or a freshly started one with its window opened.
148
+ *
149
+ * A review server closes itself shortly after a decision. The handle that
150
+ * produced that decision is dead: broadcasting a revision into it reaches no
151
+ * page, and printing its URL gives the operator a dead link. Detect that and
152
+ * start a new server instead — the next window is a new window on purpose.
153
+ */
154
+ async function ensureReviewServer(): Promise<{ handle: SpecServerHandle; started: boolean }> {
155
+ if (server && server.active()) return { handle: server, started: false };
156
+ if (!session) throw new Error("no spec revision to review yet");
157
+ server = undefined;
158
+ const handle = await startReviewServer(session);
159
+ server = handle;
160
+ open(handle.url);
161
+ return { handle, started: true };
121
162
  }
122
163
 
123
164
  function toolSetWithSubmit(): string[] {
@@ -218,7 +259,7 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
218
259
 
219
260
  const specCommand = {
220
261
  description:
221
- "Spec first: research, write a spec, review it in the browser with block annotations, then implement after approval. `off` leaves the phase, `open` re-opens the review.",
262
+ "Spec first: research, write a spec, review it in the browser with block annotations, then implement after approval. Run without arguments again, or use `off`, to leave the phase; `open` re-opens the review.",
222
263
  handler: async (args: string, ctx: ExtensionContext) => {
223
264
  const arg = args.trim();
224
265
  ctxRef = ctx;
@@ -234,12 +275,27 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
234
275
  }
235
276
 
236
277
  if (arg === "open") {
237
- if (!server) {
278
+ if (!session) {
238
279
  ctx.ui.notify("ask-spec: no review is open — submit a spec first.", "warning");
239
280
  return;
240
281
  }
241
- open(server.url);
242
- ctx.ui.notify(`ask-spec: ${server.url}`, "info");
282
+ try {
283
+ const ensured = await ensureReviewServer();
284
+ // A fresh server already opened its window; an existing one is
285
+ // simply pointed at again.
286
+ if (!ensured.started) open(ensured.handle.url);
287
+ ctx.ui.notify(`ask-spec: ${ensured.handle.url}`, "info");
288
+ } catch (error) {
289
+ ctx.ui.notify(
290
+ `ask-spec: cannot start the review server — ${error instanceof Error ? error.message : String(error)}`,
291
+ "warning",
292
+ );
293
+ }
294
+ return;
295
+ }
296
+
297
+ if (active && arg === "") {
298
+ leave(ctx, specPath ? `spec mode off — draft left at ${specPath}.` : "spec mode off.");
243
299
  return;
244
300
  }
245
301
 
@@ -353,21 +409,24 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
353
409
  appendSpecVersion(session, { text, source });
354
410
  }
355
411
  const version = latestVersion(session);
356
- if (!server) {
357
- server = await startSpecServer({
358
- session,
359
- render: renderBlockHtml,
360
- portStart: options.portStart,
361
- closeDelayMs: options.closeDelayMs,
362
- onDecision: ({ action, version: decidedVersion }) => {
363
- const ctx = ctxRef;
364
- if (ctx) void handleDecision({ action, version: decidedVersion }, ctx);
365
- },
366
- });
367
- open(server.url);
368
- ctxRef?.ui.notify(`ask-spec: review open at ${server.url}`, "info");
369
- } else {
370
- server.broadcast("revision", { version: version.n });
412
+ let handle: SpecServerHandle;
413
+ try {
414
+ const ensured = await ensureReviewServer();
415
+ handle = ensured.handle;
416
+ if (!ensured.started) handle.broadcast("revision", { version: version.n });
417
+ if (ensured.started) {
418
+ ctxRef?.ui.notify(`ask-spec: review open at ${handle.url}`, "info");
419
+ }
420
+ } catch (error) {
421
+ return {
422
+ content: [
423
+ {
424
+ type: "text" as const,
425
+ text: `Cannot open the review page: ${error instanceof Error ? error.message : String(error)}. The spec is saved; retry spec_submit.`,
426
+ },
427
+ ],
428
+ details: {},
429
+ };
371
430
  }
372
431
  const changed = buildSpecState(session, version.n).items.filter(
373
432
  (item) => item.status !== "unchanged",
@@ -378,10 +437,10 @@ export function registerSpec(pi: ExtensionAPI, gates: GateHub, options: SpecOpti
378
437
  type: "text" as const,
379
438
  text:
380
439
  `Submitted v${version.n} of ${session.versions.length} (${changed} changed blocks). ` +
381
- `Review: ${server.url}\nEnd your turn now — the decision arrives as a new message.`,
440
+ `Review: ${handle.url}\nEnd your turn now — the decision arrives as a new message.`,
382
441
  },
383
442
  ],
384
- details: { version: version.n, url: server.url },
443
+ details: { version: version.n, url: handle.url },
385
444
  };
386
445
  },
387
446
  });
@@ -372,3 +372,52 @@ describe("startSpecServer", () => {
372
372
  }
373
373
  });
374
374
  });
375
+
376
+ describe("review server lifecycle", () => {
377
+ it("walks to the next free port so two reviews can be open at once", async () => {
378
+ const portStart = 44_000 + Math.floor(Math.random() * 500);
379
+ const first = await serve(makeSession("# first"), { portStart });
380
+ const second = await serve(makeSession("# second"), { portStart });
381
+ try {
382
+ // The pool is 20 ports walked upward: the second review must not
383
+ // silently take the first one's address.
384
+ expect(second.port).toBeGreaterThan(first.port);
385
+ expect(second.url).not.toBe(first.url);
386
+ expect(second.token).not.toBe(first.token);
387
+ expect(first.active()).toBe(true);
388
+ expect(second.active()).toBe(true);
389
+ } finally {
390
+ await first.close();
391
+ await second.close();
392
+ }
393
+ expect(first.active()).toBe(false);
394
+ expect(second.active()).toBe(false);
395
+ });
396
+
397
+ it("reports the handle dead as soon as a decision is accepted", async () => {
398
+ const session = makeSession();
399
+ const server = await serve(session, { closeDelayMs: 20 });
400
+ expect(server.active()).toBe(true);
401
+ const response = await call({
402
+ port: server.port,
403
+ path: "/api/decide",
404
+ method: "POST",
405
+ token: server.token,
406
+ body: { action: "deny" },
407
+ });
408
+ expect(response.status).toBe(200);
409
+ // The extension keys "broadcast a revision" vs "start a new window" off
410
+ // this flag, so it must flip before the socket is actually gone.
411
+ expect(server.active()).toBe(false);
412
+ await vi.waitFor(async () => {
413
+ await expect(call({ port: server.port, path: "/api/state" })).rejects.toThrow();
414
+ });
415
+ });
416
+
417
+ it("closes idempotently", async () => {
418
+ const server = await serve(makeSession());
419
+ await server.close();
420
+ await server.close();
421
+ expect(server.active()).toBe(false);
422
+ });
423
+ });
@@ -130,6 +130,12 @@ export interface SpecServerHandle {
130
130
  token: string;
131
131
  close: () => Promise<void>;
132
132
  broadcast: (event: string, data: unknown) => void;
133
+ /**
134
+ * False once a decision has been accepted (the port closes shortly after) or
135
+ * after `close()`. Callers must start a new server instead of broadcasting
136
+ * into a handle whose socket is gone — the old page cannot come back.
137
+ */
138
+ active: () => boolean;
133
139
  }
134
140
 
135
141
  function isVerdict(value: unknown): value is Annotation["verdict"] {
@@ -171,8 +177,17 @@ export async function startSpecServer(options: StartSpecServerOptions): Promise<
171
177
  const render = options.render ?? renderBlockHtml;
172
178
  const closeDelayMs = options.closeDelayMs ?? 1500;
173
179
  let closing = false;
180
+ let closed = false;
174
181
  let handle: WebServerHandle | undefined;
175
182
 
183
+ /** Idempotent: a decision, `/ask-spec off` and process teardown may all call it. */
184
+ const closeHandle = async (): Promise<void> => {
185
+ if (closed) return;
186
+ closed = true;
187
+ closing = true;
188
+ await handle?.close();
189
+ };
190
+
176
191
  const server = await startWebServer({
177
192
  assetsDir,
178
193
  portStart: options.portStart,
@@ -251,7 +266,7 @@ export async function startSpecServer(options: StartSpecServerOptions): Promise<
251
266
  closing = true;
252
267
  setTimeout(() => {
253
268
  options.onDecision?.({ action, version });
254
- void handle?.close();
269
+ void closeHandle();
255
270
  }, closeDelayMs).unref();
256
271
  }
257
272
  return true;
@@ -266,7 +281,8 @@ export async function startSpecServer(options: StartSpecServerOptions): Promise<
266
281
  url: server.url,
267
282
  port: server.port,
268
283
  token: server.token,
269
- close: server.close,
284
+ close: closeHandle,
270
285
  broadcast: server.broadcast,
286
+ active: () => !closing && !closed,
271
287
  };
272
288
  }