@andares/pi-toolkits 1.2.0 → 1.2.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.
@@ -15,6 +15,21 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
15
15
  import { startSpecServer } from "./server.js";
16
16
  import { createSpecSession } from "./store.js";
17
17
 
18
+ /**
19
+ * Distinct port per server, never reused inside this file.
20
+ *
21
+ * The HTTP clients keep connections alive, and those pools are keyed by port:
22
+ * handing a new test a port whose previous server has just closed gives its
23
+ * first request a dead socket ("socket hang up"). A counter is also immune to
24
+ * the birthday collisions a narrow random range produces once the whole suite
25
+ * runs under the 4-way compatibility matrix.
26
+ */
27
+ let nextPort = 44_001;
28
+ function takePort(): number {
29
+ nextPort += 3;
30
+ return nextPort;
31
+ }
32
+
18
33
  const assetsDir = new URL("../review-page/assets/", import.meta.url).pathname;
19
34
  const built = existsSync(join(assetsDir, "index.html"));
20
35
  let agentDir: string;
@@ -32,7 +47,7 @@ describe.skipIf(!built)("built UI assets", () => {
32
47
  const session = createSpecSession({ agentDir, slug: "assets", text: "## Spec\n\nbody" });
33
48
  const server = await startSpecServer({
34
49
  session,
35
- portStart: 44_000 + Math.floor(Math.random() * 1000),
50
+ portStart: takePort(),
36
51
  portAttempts: 20,
37
52
  bindHost: "127.0.0.1",
38
53
  urlHost: "127.0.0.1",
@@ -18,6 +18,21 @@ import { setAskControl } from "../../lib/ask-control.js";
18
18
  import { LEGACY_SPEC_PHASE_TOOL } from "../../lib/phases.js";
19
19
  import { registerSpec, SPEC_COMMAND, SPEC_COMMAND_ALIAS, SPEC_SUBMIT_TOOL } from "./index.js";
20
20
 
21
+ /**
22
+ * Distinct port per server, never reused inside this file.
23
+ *
24
+ * The HTTP clients keep connections alive, and those pools are keyed by port:
25
+ * handing a new test a port whose previous server has just closed gives its
26
+ * first request a dead socket ("socket hang up"). A counter is also immune to
27
+ * the birthday collisions a narrow random range produces once the whole suite
28
+ * runs under the 4-way compatibility matrix.
29
+ */
30
+ let nextPort = 46_001;
31
+ function takePort(): number {
32
+ nextPort += 3;
33
+ return nextPort;
34
+ }
35
+
21
36
  let agentDir: string;
22
37
  let workDir: string;
23
38
 
@@ -103,7 +118,7 @@ function harness(): Harness {
103
118
  registerSpec(pi, { register: (def: never) => gates.push(def as never) } as unknown as GateHub, {
104
119
  agentDir,
105
120
  openBrowser,
106
- portStart: 46_000 + Math.floor(Math.random() * 1000),
121
+ portStart: takePort(),
107
122
  closeDelayMs: 25,
108
123
  });
109
124
  return { pi, commands, tools, gates, handlers, sendUserMessage, activeTools: () => activeTools, openBrowser, notify, ctx, control };
@@ -121,6 +136,7 @@ async function decide(url: string, action: "approve" | "deny"): Promise<number>
121
136
  path: "/api/decide",
122
137
  method: "POST",
123
138
  headers: { "content-type": "application/json", "x-plan-token": token },
139
+ agent: false,
124
140
  },
125
141
  (res) => {
126
142
  res.resume();
@@ -149,6 +165,7 @@ async function reviewState(url: string): Promise<{
149
165
  path: "/api/state",
150
166
  method: "GET",
151
167
  headers: { "x-plan-token": token },
168
+ agent: false,
152
169
  },
153
170
  (res) => {
154
171
  const chunks: Buffer[] = [];
@@ -288,6 +305,30 @@ describe("ask-spec command", () => {
288
305
  await handler("off", h.ctx);
289
306
  });
290
307
 
308
+ it("closes from the page without a decision or an agent message", async () => {
309
+ const h = harness();
310
+ const handler = h.commands.get(SPEC_COMMAND)!.handler;
311
+ await handler("topic", h.ctx);
312
+ writeSpec("specs/topic.md", "# SPEC: one");
313
+ const submitted = await h.tools.get(SPEC_SUBMIT_TOOL)!.execute("id", { path: "specs/topic.md" });
314
+ const url = (submitted.details as { url: string }).url;
315
+ const messagesBefore = h.sendUserMessage.mock.calls.length;
316
+
317
+ const parsed = new URL(url);
318
+ const response = await fetch(`http://127.0.0.1:${parsed.port}/api/close`, {
319
+ method: "POST",
320
+ headers: { "x-plan-token": parsed.searchParams.get("t") ?? "" },
321
+ });
322
+ expect(response.status).toBe(200);
323
+ await waitUntilClosed(url);
324
+ expect(h.sendUserMessage).toHaveBeenCalledTimes(messagesBefore);
325
+ expect(h.activeTools()).toContain(SPEC_SUBMIT_TOOL); // closing is not leaving the phase
326
+
327
+ await handler("open", h.ctx);
328
+ expect(h.openBrowser).toHaveBeenCalledTimes(2);
329
+ await handler("off", h.ctx);
330
+ });
331
+
291
332
  it("refuses to start twice and can be turned off", async () => {
292
333
  const h = harness();
293
334
  const handler = h.commands.get(SPEC_COMMAND)!.handler;
@@ -98,7 +98,7 @@ 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). */
101
+ /** How many ports the review server may try before giving up (default: the whole 7600–7699 pool). */
102
102
  portAttempts?: number;
103
103
  }
104
104
 
@@ -8,6 +8,21 @@ import { renderBlockHtml } from "../review-page/render.js";
8
8
  import { buildSpecState, normalizeAnnotations, startSpecServer, type SpecServerHandle } from "./server.js";
9
9
  import { appendSpecVersion, createSpecSession, type SpecSession } from "./store.js";
10
10
 
11
+ /**
12
+ * Distinct port per server, never reused inside this file.
13
+ *
14
+ * The HTTP clients keep connections alive, and those pools are keyed by port:
15
+ * handing a new test a port whose previous server has just closed gives its
16
+ * first request a dead socket ("socket hang up"). A counter is also immune to
17
+ * the birthday collisions a narrow random range produces once the whole suite
18
+ * runs under the 4-way compatibility matrix.
19
+ */
20
+ let nextPort = 42_001;
21
+ function takePort(): number {
22
+ nextPort += 3;
23
+ return nextPort;
24
+ }
25
+
11
26
  let agentDir: string;
12
27
 
13
28
  beforeAll(() => {
@@ -35,7 +50,7 @@ async function serve(
35
50
  session,
36
51
  assetsDir: join(agentDir, "no-assets"),
37
52
  render: renderBlockHtml,
38
- portStart: 42_000 + Math.floor(Math.random() * 2000),
53
+ portStart: takePort(),
39
54
  portAttempts: 20,
40
55
  bindHost: "127.0.0.1",
41
56
  urlHost: "127.0.0.1",
@@ -73,6 +88,11 @@ async function call(options: CallOptions): Promise<CallResult> {
73
88
  ...(options.body !== undefined ? { "content-type": "application/json" } : {}),
74
89
  ...options.headers,
75
90
  },
91
+ // A fresh socket per call: a pooled keep-alive socket outlives the
92
+ // server it was opened to (these tests close servers mid-file), and
93
+ // the next request then dies with ECONNRESET instead of returning the
94
+ // status the test is about.
95
+ agent: false,
76
96
  },
77
97
  (res) => {
78
98
  const chunks: Buffer[] = [];
@@ -286,7 +306,10 @@ describe("startSpecServer", () => {
286
306
  it("accepts only the first decision", async () => {
287
307
  const session = makeSession();
288
308
  const onDecision = vi.fn();
289
- const server = await serve(session, { onDecision, closeDelayMs: 50 });
309
+ // Long enough that the second decision lands before the port closes (50ms
310
+ // is a race once four sandboxes share the machine), short enough that the
311
+ // delayed onDecision still arrives inside the waitFor below.
312
+ const server = await serve(session, { onDecision, closeDelayMs: 1_000 });
290
313
  const first = await call({
291
314
  port: server.port,
292
315
  path: "/api/decide",
@@ -303,7 +326,8 @@ describe("startSpecServer", () => {
303
326
  });
304
327
  expect(first.status).toBe(200);
305
328
  expect(second.status).toBe(409);
306
- await vi.waitFor(() => expect(onDecision).toHaveBeenCalledTimes(1));
329
+ // onDecision is delivered on the close timer, not on the request.
330
+ await vi.waitFor(() => expect(onDecision).toHaveBeenCalledTimes(1), { timeout: 5_000 });
307
331
  expect(session.versions[0].decision?.action).toBe("deny");
308
332
  });
309
333
 
@@ -389,7 +413,7 @@ describe("startSpecServer", () => {
389
413
 
390
414
  describe("review server lifecycle", () => {
391
415
  it("walks to the next free port so two reviews can be open at once", async () => {
392
- const portStart = 44_000 + Math.floor(Math.random() * 500);
416
+ const portStart = takePort();
393
417
  const first = await serve(makeSession("# first"), { portStart });
394
418
  const second = await serve(makeSession("# second"), { portStart });
395
419
  try {
@@ -428,6 +452,26 @@ describe("review server lifecycle", () => {
428
452
  });
429
453
  });
430
454
 
455
+ it("closes manually without recording a decision or notifying the agent", async () => {
456
+ const session = makeSession();
457
+ const onDecision = vi.fn();
458
+ const server = await serve(session, { onDecision });
459
+ const response = await call({
460
+ port: server.port,
461
+ path: "/api/close",
462
+ method: "POST",
463
+ token: server.token,
464
+ });
465
+ expect(response.status).toBe(200);
466
+ expect(response.json()).toEqual({ ok: true });
467
+ expect(server.active()).toBe(false);
468
+ expect(session.versions[0].decision).toBeUndefined();
469
+ expect(onDecision).not.toHaveBeenCalled();
470
+ await vi.waitFor(async () => {
471
+ await expect(call({ port: server.port, path: "/api/state" })).rejects.toThrow();
472
+ });
473
+ });
474
+
431
475
  it("closes idempotently", async () => {
432
476
  const server = await serve(makeSession());
433
477
  await server.close();
@@ -242,6 +242,16 @@ export async function startSpecServer(options: StartSpecServerOptions): Promise<
242
242
  return true;
243
243
  }
244
244
 
245
+ if (ctx.url.pathname === "/api/close" && ctx.req.method === "POST") {
246
+ // Manual close is deliberately NOT a decision: no message, no approval,
247
+ // no revision change. It only stops this review's HTTP server. Reply to
248
+ // the page first; closing on the next tick lets the response flush.
249
+ closing = true;
250
+ ctx.json({ ok: true });
251
+ setTimeout(() => void closeHandle(), 0).unref();
252
+ return true;
253
+ }
254
+
245
255
  if (ctx.url.pathname === "/api/decide" && ctx.req.method === "POST") {
246
256
  const body = (await ctx.readBody()) as { action?: unknown; version?: number };
247
257
  const action =
@@ -9,6 +9,21 @@ import { afterEach, describe, expect, it, vi } from "vitest";
9
9
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
10
10
  import { registerTalk, TALK_COMMAND } from "./index.js";
11
11
 
12
+ /**
13
+ * Distinct port per server, never reused inside this file.
14
+ *
15
+ * The HTTP clients keep connections alive, and those pools are keyed by port:
16
+ * handing a new test a port whose previous server has just closed gives its
17
+ * first request a dead socket ("socket hang up"). A counter is also immune to
18
+ * the birthday collisions a narrow random range produces once the whole suite
19
+ * runs under the 4-way compatibility matrix.
20
+ */
21
+ let nextPort = 48_001;
22
+ function takePort(): number {
23
+ nextPort += 3;
24
+ return nextPort;
25
+ }
26
+
12
27
  type Handler = (event: unknown, ctx: ExtensionContext) => void;
13
28
 
14
29
  interface Harness {
@@ -49,7 +64,7 @@ function harness(): Harness {
49
64
  const messages = vi.fn();
50
65
  const notify = vi.fn();
51
66
  let entries: unknown[] = [];
52
- let idle = true;
67
+ const idle = true;
53
68
 
54
69
  const pi = {
55
70
  registerCommand: (name: string, definition: { handler: (args: string, ctx: ExtensionContext) => Promise<void> }) => {
@@ -66,12 +81,13 @@ function harness(): Harness {
66
81
  ui: { notify },
67
82
  sessionManager: {
68
83
  getSessionId: () => "session-one",
84
+ getSessionName: () => "Session Alpha",
69
85
  getBranch: () => entries,
70
86
  buildContextEntries: () => entries,
71
87
  },
72
88
  } as unknown as ExtensionContext;
73
89
 
74
- const portStart = 48_000 + Math.floor(Math.random() * 1500);
90
+ const portStart = takePort();
75
91
  registerTalk(pi, { openBrowser: opened, portStart, portAttempts: 20, closeDelayMs: 30 });
76
92
  const definition = commands.get(TALK_COMMAND);
77
93
  if (!definition) throw new Error("ask-talk was not registered");
@@ -113,6 +129,7 @@ function localUrl(url: string, path: string): string {
113
129
  }
114
130
 
115
131
  async function state(url: string): Promise<{
132
+ title?: string;
116
133
  items: Array<{ id: string; label: string }>;
117
134
  notes: Record<string, string>;
118
135
  draft: string;
@@ -155,7 +172,10 @@ describe("ask-talk command", () => {
155
172
 
156
173
  await post(url, "/api/notes", { notes: { [initial.items[1].id]: "rename" }, draft: "draft" });
157
174
  await h.command();
158
- expect(h.opened).toHaveBeenCalledTimes(1);
175
+ // The second run is an explicit "show me": it re-opens the same page (the
176
+ // operator may have closed the tab) without rebuilding the snapshot.
177
+ expect(h.opened).toHaveBeenCalledTimes(2);
178
+ expect(h.opened.mock.calls[1]?.[0]).toBe(url);
159
179
  expect(await state(url)).toMatchObject({ notes: { [initial.items[1].id]: "rename" }, draft: "draft" });
160
180
 
161
181
  await h.command("off");
@@ -176,7 +196,43 @@ describe("ask-talk command", () => {
176
196
  expect(after.items.map((item) => item.label)).toEqual(["## Beta", "second reply"]);
177
197
  expect(after.notes).toEqual({});
178
198
  expect(after.draft).toBe("");
179
- expect(h.opened).toHaveBeenCalledTimes(1);
199
+ // Same server, new content: the refresh is broadcast to the open tab AND the
200
+ // window is opened again, so a closed tab comes back with the new reply.
201
+ expect(h.opened).toHaveBeenCalledTimes(2);
202
+ expect(h.opened.mock.calls[1]?.[0]).toBe(url);
203
+ });
204
+
205
+ it("titles the page with the session name, falling back to the first prompt", async () => {
206
+ const h = harness();
207
+ await h.command();
208
+ const url = h.opened.mock.calls[0]?.[0] as string;
209
+ expect((await state(url)).title).toBe("Session Alpha");
210
+
211
+ // A session the host has not named yet: the first user message is what the
212
+ // operator recognizes in a row of parallel windows.
213
+ (h.ctx.sessionManager as unknown as { getSessionName: () => string | undefined }).getSessionName =
214
+ () => undefined;
215
+ h.setReply("## Gamma\n\nthird reply");
216
+ await h.command();
217
+ expect((await state(url)).title).toBe("q");
218
+ });
219
+
220
+ it("manual close sends nothing and the same snapshot can be reopened", async () => {
221
+ const h = harness();
222
+ await h.command();
223
+ const url = h.opened.mock.calls[0]?.[0] as string;
224
+ const response = await post(url, "/api/close", {});
225
+ expect(response.status).toBe(200);
226
+ expect(h.messages).not.toHaveBeenCalled();
227
+ await vi.waitFor(async () => {
228
+ expect((await fetch(localUrl(url, "/api/state")).catch(() => undefined))?.ok ?? false).toBe(false);
229
+ });
230
+
231
+ await h.command();
232
+ expect(h.opened).toHaveBeenCalledTimes(2);
233
+ expect(h.messages).not.toHaveBeenCalled();
234
+ const reopened = h.opened.mock.calls[1]?.[0] as string;
235
+ expect((await state(reopened)).items.map((item) => item.label)).toEqual(["## Alpha", "first reply"]);
180
236
  });
181
237
 
182
238
  it("sends notes for the CURRENT snapshot when Continue arrives", async () => {
@@ -19,8 +19,15 @@ import { extractLastReply } from "./reply.js";
19
19
  import { startTalkServer, type TalkServerHandle, type TalkSession } from "./server.js";
20
20
 
21
21
  export const TALK_COMMAND = "ask-talk";
22
- /** 3501 — a different pool from spec/uat (3401), so a URL says which page it is. */
23
- const PORT_START = 3501;
22
+ /**
23
+ * 7600 — the same pool `/ask-spec` and `/ask-uat` walk.
24
+ *
25
+ * Pages are told apart by their title, not by a port block: sharing the pool
26
+ * means several review pages can be open at once without a second range that
27
+ * only exists to be remembered. The block sits high because 34xx is routinely
28
+ * claimed by WSL / Windows port forwarders.
29
+ */
30
+ const PORT_START = 7600;
24
31
 
25
32
  export interface TalkOptions {
26
33
  openBrowser?: (url: string) => unknown;
@@ -42,6 +49,50 @@ function noteList(notes: Record<string, string>): TalkNote[] {
42
49
  return Object.entries(notes).map(([blockId, text]) => ({ blockId, text }));
43
50
  }
44
51
 
52
+ /** Plain text of a message content field (string or text blocks). */
53
+ function contentText(content: unknown): string {
54
+ if (typeof content === "string") return content;
55
+ if (!Array.isArray(content)) return "";
56
+ const parts: string[] = [];
57
+ for (const part of content) {
58
+ if (!part || typeof part !== "object") continue;
59
+ const block = part as { type?: unknown; text?: unknown };
60
+ if (block.type === "text" && typeof block.text === "string") parts.push(block.text);
61
+ }
62
+ return parts.join(" ");
63
+ }
64
+
65
+ /**
66
+ * The title of the session this page belongs to.
67
+ *
68
+ * The operator runs several sessions in parallel; "the last reply" is the same
69
+ * phrase in every window, so the page has to say WHICH session it is annotating.
70
+ * The session name is the host's own answer; before auto-naming has produced
71
+ * one, the first user message is what the operator recognizes.
72
+ */
73
+ function sessionTitle(ctx: ExtensionContext): string | undefined {
74
+ try {
75
+ const named = ctx.sessionManager.getSessionName?.();
76
+ const name = typeof named === "string" ? named.trim() : "";
77
+ if (name !== "") return name;
78
+ } catch {
79
+ // Older host without session names: fall through to the first prompt.
80
+ }
81
+ try {
82
+ for (const entry of ctx.sessionManager.getBranch() as Array<{
83
+ type?: unknown;
84
+ message?: { role?: unknown; content?: unknown };
85
+ }>) {
86
+ if (entry?.type !== "message" || entry.message?.role !== "user") continue;
87
+ const text = contentText(entry.message.content).replace(/\s+/g, " ").trim();
88
+ if (text !== "") return text.length > 80 ? `${text.slice(0, 79)}…` : text;
89
+ }
90
+ } catch {
91
+ // A branch that cannot be read is not worth failing the command over.
92
+ }
93
+ return undefined;
94
+ }
95
+
45
96
  export function registerTalk(pi: ExtensionAPI, options: TalkOptions = {}): void {
46
97
  const open = options.openBrowser ?? openInBrowser;
47
98
 
@@ -174,12 +225,16 @@ export function registerTalk(pi: ExtensionAPI, options: TalkOptions = {}): void
174
225
 
175
226
  if (sameReply && session) {
176
227
  session.inContext = inContext;
228
+ session.title = sessionTitle(ctx) ?? session.title;
177
229
  if (server?.active() !== true) {
178
230
  await openFresh(session, ctx);
179
231
  return;
180
232
  }
181
- // Nothing about the snapshot changed. Re-fetching here would overwrite
182
- // keystrokes still inside the page's save debounce window.
233
+ // Nothing about the snapshot changed, but the command is an explicit
234
+ // "show me": re-open the window instead of printing a URL the operator
235
+ // has to find. Re-fetching here would overwrite keystrokes still inside
236
+ // the page's save debounce window, so only the tab is new.
237
+ open(server.url);
183
238
  ctx.ui.notify(`ask-talk: already showing this reply — ${server.url}`, "info");
184
239
  return;
185
240
  }
@@ -189,6 +244,7 @@ export function registerTalk(pi: ExtensionAPI, options: TalkOptions = {}): void
189
244
  text: reply.text,
190
245
  blocks,
191
246
  headings: extractHeadings(blocks),
247
+ title: sessionTitle(ctx),
192
248
  entryId: reply.entryId,
193
249
  model: reply.model,
194
250
  at: reply.at,
@@ -210,6 +266,10 @@ export function registerTalk(pi: ExtensionAPI, options: TalkOptions = {}): void
210
266
  Object.assign(previous, next);
211
267
  session = previous;
212
268
  server.broadcast("refresh", {});
269
+ // A refresh is also an explicit "show me": the old tab may have been
270
+ // closed, and a broadcast reaches no window. /ask-spec opens on every
271
+ // submit for the same reason.
272
+ open(server.url);
213
273
  ctx.ui.notify(
214
274
  `ask-talk: review refreshed${replaced ? " (notes cleared — this is a new reply)" : ""} — ${server.url}`,
215
275
  "info",
@@ -1,9 +1,24 @@
1
1
  import { request } from "node:http";
2
- import { describe, expect, it } from "vitest";
2
+ import { describe, expect, it, vi } from "vitest";
3
3
  import { parseBlocks } from "../review-page/blocks.js";
4
4
  import { renderBlockHtml } from "../review-page/render.js";
5
5
  import { buildTalkState, sanitizeNotes, startTalkServer, type TalkServerHandle, type TalkSession } from "./server.js";
6
6
 
7
+ /**
8
+ * Distinct port per server, never reused inside this file.
9
+ *
10
+ * The HTTP clients keep connections alive, and those pools are keyed by port:
11
+ * handing a new test a port whose previous server has just closed gives its
12
+ * first request a dead socket ("socket hang up"). A counter is also immune to
13
+ * the birthday collisions a narrow random range produces once the whole suite
14
+ * runs under the 4-way compatibility matrix.
15
+ */
16
+ let nextPort = 45_001;
17
+ function takePort(): number {
18
+ nextPort += 3;
19
+ return nextPort;
20
+ }
21
+
7
22
  const REPLY = "## Approach\n\nfirst block\n\n## Milestones\n\nsecond block";
8
23
 
9
24
  function makeSession(overrides: Partial<TalkSession> = {}): TalkSession {
@@ -32,7 +47,7 @@ async function serve(
32
47
  session,
33
48
  assetsDir: "/nonexistent-assets",
34
49
  render: renderBlockHtml,
35
- portStart: 45_000 + Math.floor(Math.random() * 2000),
50
+ portStart: takePort(),
36
51
  portAttempts: 20,
37
52
  bindHost: "127.0.0.1",
38
53
  urlHost: "127.0.0.1",
@@ -63,6 +78,9 @@ function call(
63
78
  method: options.method ?? "GET",
64
79
  path,
65
80
  headers,
81
+ // Fresh socket per call: pooled sockets outlive the server that opened
82
+ // them, and reusing one turns the next request into ECONNRESET.
83
+ agent: false,
66
84
  },
67
85
  (res) => {
68
86
  const chunks: Buffer[] = [];
@@ -81,9 +99,10 @@ function call(
81
99
 
82
100
  describe("buildTalkState", () => {
83
101
  it("describes the snapshot without any version or diff fields", () => {
84
- const session = makeSession();
102
+ const session = makeSession({ title: "Parallel session A" });
85
103
  const state = buildTalkState(session);
86
104
  expect(state.mode).toBe("talk");
105
+ expect(state.title).toBe("Parallel session A");
87
106
  expect(state.reply).toEqual({ model: "provider/model", at: "2026-11-25T00:00:00.000Z", chars: REPLY.length });
88
107
  expect(state.items).toHaveLength(4);
89
108
  expect(state.items.every((item) => item.html === "")).toBe(true);
@@ -244,4 +263,22 @@ describe("talk server", () => {
244
263
  await server.close();
245
264
  }
246
265
  });
266
+
267
+ it("closes manually without sending Continue or changing the snapshot", async () => {
268
+ const session = makeSession({ draft: "unsent draft" });
269
+ const onContinue = vi.fn();
270
+ const onNotes = vi.fn();
271
+ const server = await serve(session, { onContinue, onNotes });
272
+ const response = await call(server.port, "/api/close", { method: "POST", token: server.token });
273
+ expect(response.status).toBe(200);
274
+ expect(response.json()).toEqual({ ok: true });
275
+ expect(server.active()).toBe(false);
276
+ expect(session.sent).toBe(false);
277
+ expect(session.draft).toBe("unsent draft");
278
+ expect(onContinue).not.toHaveBeenCalled();
279
+ expect(onNotes).not.toHaveBeenCalled();
280
+ await vi.waitFor(async () => {
281
+ await expect(call(server.port, "/api/state", { token: server.token })).rejects.toThrow();
282
+ });
283
+ });
247
284
  });
@@ -25,6 +25,15 @@ export interface TalkSession {
25
25
  text: string;
26
26
  blocks: Block[];
27
27
  headings: Heading[];
28
+ /**
29
+ * Session title at the time the page was (re)opened.
30
+ *
31
+ * Several talk pages can be open at once across parallel sessions, and every
32
+ * one of them annotates "the last reply" — without this, the windows are
33
+ * indistinguishable. Undefined when the session has no name yet; the page
34
+ * falls back to its own label.
35
+ */
36
+ title?: string;
28
37
  model?: string;
29
38
  at: string;
30
39
  /** Session entry id, rechecked when Continue actually arrives. */
@@ -48,6 +57,7 @@ export interface TalkStateItem {
48
57
 
49
58
  export interface TalkStatePayload {
50
59
  mode: "talk";
60
+ title?: string;
51
61
  reply: { model?: string; at: string; chars: number };
52
62
  items: TalkStateItem[];
53
63
  headings: Heading[];
@@ -60,6 +70,7 @@ export interface TalkStatePayload {
60
70
  export function buildTalkState(session: TalkSession): TalkStatePayload {
61
71
  return {
62
72
  mode: "talk",
73
+ title: session.title,
63
74
  reply: { model: session.model, at: session.at, chars: session.text.length },
64
75
  items: session.blocks.map((block) => ({
65
76
  id: block.id,
@@ -145,7 +156,7 @@ export async function startTalkServer(
145
156
 
146
157
  const server = await startWebServer({
147
158
  assetsDir,
148
- portStart: options.portStart ?? 3501,
159
+ portStart: options.portStart ?? 7600,
149
160
  portAttempts: options.portAttempts,
150
161
  bindHost: options.bindHost ?? bindHost(isWsl()),
151
162
  urlHost: options.urlHost ?? urlHost(isWsl()),
@@ -176,6 +187,16 @@ export async function startTalkServer(
176
187
  return true;
177
188
  }
178
189
 
190
+ if (ctx.url.pathname === "/api/close" && ctx.req.method === "POST") {
191
+ // Manual close is not Continue: leave the snapshot untouched, send no
192
+ // message to the agent, and only stop this page's HTTP server. Reply
193
+ // before closing on the next tick so the page gets the acknowledgement.
194
+ closing = true;
195
+ ctx.json({ ok: true });
196
+ setTimeout(() => void closeHandle(), 0).unref();
197
+ return true;
198
+ }
199
+
179
200
  if (ctx.url.pathname === "/api/continue" && ctx.req.method === "POST") {
180
201
  if (closing || options.session.sent) {
181
202
  ctx.json({ error: "this reply has already been sent" }, 409);
@@ -16,6 +16,21 @@ import { registerUat, uatSummary } from "./index.js";
16
16
  import { RECORD_CHANGE_TOOL, UAT_COMMAND, UAT_ITEM_TOOL } from "./constants.js";
17
17
  import { createRecord, isoMinute } from "./records.js";
18
18
 
19
+ /**
20
+ * Distinct port per server, never reused inside this file.
21
+ *
22
+ * The HTTP clients keep connections alive, and those pools are keyed by port:
23
+ * handing a new test a port whose previous server has just closed gives its
24
+ * first request a dead socket ("socket hang up"). A counter is also immune to
25
+ * the birthday collisions a narrow random range produces once the whole suite
26
+ * runs under the 4-way compatibility matrix.
27
+ */
28
+ let nextPort = 47_001;
29
+ function takePort(): number {
30
+ nextPort += 3;
31
+ return nextPort;
32
+ }
33
+
19
34
  /**
20
35
  * Every timestamp in this file is derived from this one date. Headers carry the
21
36
  * machine's UTC offset, so writing the offset out by hand makes the assertion
@@ -89,7 +104,7 @@ function harness(): Harness {
89
104
  openBrowser,
90
105
  root: (cwd) => cwd,
91
106
  now: () => fixedNow,
92
- portStart: 47_000 + Math.floor(Math.random() * 800),
107
+ portStart: takePort(),
93
108
  idleCloseMs: 0,
94
109
  });
95
110
  return {
@@ -120,6 +135,9 @@ async function post(url: string, path: string, body: unknown): Promise<{ status:
120
135
  path,
121
136
  method: "POST",
122
137
  headers: { "content-type": "application/json", "x-plan-token": token },
138
+ // Fresh socket per call: pooled sockets outlive the server that opened
139
+ // them, and reusing one turns the next request into ECONNRESET.
140
+ agent: false,
123
141
  },
124
142
  (res) => {
125
143
  const chunks: Buffer[] = [];
package/src/index.ts CHANGED
@@ -14,7 +14,6 @@
14
14
  * - permission — session-scoped boundary permission checks (/ask-perm)
15
15
  * - init — agent memory framework install / adoption (/ask-init)
16
16
  * - uat — acceptance ledger and browser page (/ask-uat, record_change)
17
- * - quit-guard — quit watchdog: force-exit when pi's shutdown hangs (/quit-guard)
18
17
  * - keep — session backlog: keep-quit / keep-load / keep-drop
19
18
  * - whats-new — automatic release notes on the first start after an upgrade
20
19
  *
@@ -33,7 +32,6 @@ import { registerInit } from "./features/init/index.js";
33
32
  import { registerKeep } from "./features/keep/index.js";
34
33
  import { registerPermission } from "./features/permission/index.js";
35
34
  import { registerSpec } from "./features/spec/index.js";
36
- import { registerQuitGuard } from "./features/quit-guard/index.js";
37
35
  import { registerReview } from "./features/review/index.js";
38
36
  import { registerStash } from "./features/stash/index.js";
39
37
  import { registerTalk } from "./features/talk/index.js";
@@ -58,7 +56,6 @@ export default function piToolkits(pi: ExtensionAPI): void {
58
56
  registerFavorites(pi);
59
57
  registerInit(pi);
60
58
  registerKeep(pi);
61
- registerQuitGuard(pi);
62
59
  registerReview(pi);
63
60
  registerStash(pi);
64
61
  // Not a phase: no tools, no gates, no prompt banner. Registered after the
@@ -264,9 +264,9 @@ const REDACTIONS: ReadonlyArray<readonly [RegExp, Replacer]> = [
264
264
  /**
265
265
  * Apply the credential patterns below to one string.
266
266
  *
267
- * Exported for the quit-guard hang report, which writes process arguments and
268
- * must not store `pi --api-key …` verbatim; the approval log ships one copy of
269
- * these rules so the two artifacts cannot drift apart.
267
+ * The approval log owns the only copy of these rules; anything else that writes
268
+ * process arguments to disk (the retired quit-guard hang report was one) imports
269
+ * this instead of growing a second, drifting list.
270
270
  */
271
271
  export function redactText(value: string): string {
272
272
  let out = value;