@andares/pi-toolkits 1.2.0 → 1.2.1

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.
@@ -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[] = [];
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The port pool is a shared one: `/ask-spec`, `/ask-uat` and `/ask-talk` all
3
+ * walk from 7600, and a walk that left the hundred block would silently give
4
+ * the next feature's pool away. These tests pin the range, not the feature.
5
+ */
6
+ import { createServer as createNetServer, type AddressInfo } from "node:net";
7
+ import { afterEach, describe, expect, it } from "vitest";
8
+ import { portWalk, startWebServer, type WebServerHandle } from "./web-review.js";
9
+
10
+ const cleanups: Array<() => Promise<void>> = [];
11
+
12
+ afterEach(async () => {
13
+ for (const cleanup of cleanups.splice(0)) await cleanup();
14
+ });
15
+
16
+ describe("portWalk", () => {
17
+ it("walks the whole hundred block by default", () => {
18
+ const ports = portWalk(7600);
19
+ expect(ports[0]).toBe(7600);
20
+ expect(ports.at(-1)).toBe(7699);
21
+ expect(ports).toHaveLength(100);
22
+ });
23
+
24
+ it("honours an explicit attempt count", () => {
25
+ expect(portWalk(7600, 20)).toEqual(
26
+ Array.from({ length: 20 }, (_, index) => 7600 + index),
27
+ );
28
+ });
29
+
30
+ it("stops at the end of the block instead of spilling into the next one", () => {
31
+ expect(portWalk(7695, 20)).toEqual([7695, 7696, 7697, 7698, 7699]);
32
+ });
33
+
34
+ it("keeps a start on a boundary inside its own block", () => {
35
+ expect(portWalk(7700, 3)).toEqual([7700, 7701, 7702]);
36
+ });
37
+ });
38
+
39
+ describe("startWebServer", () => {
40
+ it("reports an exhausted pool as a range, and does not start", async () => {
41
+ const blocker = createNetServer();
42
+ await new Promise<void>((resolve, reject) => {
43
+ blocker.once("error", reject);
44
+ blocker.listen(0, "127.0.0.1", resolve);
45
+ });
46
+ const port = (blocker.address() as AddressInfo).port;
47
+ cleanups.push(() => new Promise<void>((resolve) => blocker.close(() => resolve())));
48
+
49
+ await expect(
50
+ startWebServer({
51
+ assetsDir: "/nonexistent-assets",
52
+ routes: () => false,
53
+ portStart: port,
54
+ portAttempts: 1,
55
+ bindHost: "127.0.0.1",
56
+ }),
57
+ ).rejects.toThrow(`cannot bind a review server on ports ${port}–${port}`);
58
+ });
59
+
60
+ it("takes the next port in the same block for a second page", async () => {
61
+ const start = 63_100 + Math.floor(Math.random() * 60);
62
+ const first: WebServerHandle = await startWebServer({
63
+ assetsDir: "/nonexistent-assets",
64
+ routes: () => false,
65
+ portStart: start,
66
+ bindHost: "127.0.0.1",
67
+ });
68
+ cleanups.push(() => first.close());
69
+ const second: WebServerHandle = await startWebServer({
70
+ assetsDir: "/nonexistent-assets",
71
+ routes: () => false,
72
+ portStart: start,
73
+ bindHost: "127.0.0.1",
74
+ });
75
+ cleanups.push(() => second.close());
76
+
77
+ expect(second.port).toBe(first.port + 1);
78
+ expect(Math.floor(second.port / 100)).toBe(Math.floor(start / 100));
79
+ });
80
+ });
@@ -55,6 +55,7 @@ export interface WebServerOptions {
55
55
  /** Called for authenticated `/api/*` requests; return true when handled. */
56
56
  routes: (ctx: WebRequestContext) => boolean | Promise<boolean>;
57
57
  portStart?: number;
58
+ /** How many ports to try; the walk still stops at the end of `portStart`'s hundred. */
58
59
  portAttempts?: number;
59
60
  /** Header the page echoes the token in. Default `x-plan-token`. */
60
61
  tokenHeader?: string;
@@ -129,11 +130,33 @@ function parseHost(value: string | undefined): string {
129
130
  return (value ?? "").toLowerCase();
130
131
  }
131
132
 
133
+ /**
134
+ * Ports to try, in order.
135
+ *
136
+ * The walk never leaves the hundred block `portStart` lives in (7600 → 7600…7699):
137
+ * every review page shares one pool, so an exhausted pool must fail loudly
138
+ * instead of drifting into 7700+, where the URL stops telling the operator
139
+ * anything and the next feature's own pool begins.
140
+ *
141
+ * The block sits high on purpose: 34xx is a range WSL and Windows-side
142
+ * forwarders grab for themselves, and a review page that silently loses its
143
+ * port to a forwarder is indistinguishable from one that never started.
144
+ */
145
+ export function portWalk(portStart: number, attempts = 100): number[] {
146
+ const blockEnd = Math.floor(portStart / 100) * 100 + 99;
147
+ // At least the start port: a zero attempt count must not turn the failure
148
+ // message into "ports undefined–undefined".
149
+ const last = Math.max(portStart, Math.min(portStart + Math.max(0, attempts) - 1, blockEnd));
150
+ const ports: number[] = [];
151
+ for (let port = portStart; port <= last; port += 1) ports.push(port);
152
+ return ports;
153
+ }
154
+
132
155
  export async function startWebServer(options: WebServerOptions): Promise<WebServerHandle> {
133
156
  const token = randomBytes(12).toString("hex");
134
157
  const tokenHeader = options.tokenHeader ?? "x-plan-token";
135
- const portStart = options.portStart ?? 3401;
136
- const attempts = options.portAttempts ?? 20;
158
+ const portStart = options.portStart ?? 7600;
159
+ const ports = portWalk(portStart, options.portAttempts);
137
160
  const host = options.bindHost ?? "127.0.0.1";
138
161
  const displayHost = options.urlHost ?? "127.0.0.1";
139
162
  const assetsRoot = resolve(options.assetsDir);
@@ -285,8 +308,7 @@ export async function startWebServer(options: WebServerOptions): Promise<WebServ
285
308
  const state = { closing: false };
286
309
  let currentPort = 0;
287
310
  let server: ReturnType<typeof createServer> | undefined;
288
- for (let attempt = 0; attempt < attempts; attempt += 1) {
289
- const port = portStart + attempt;
311
+ for (const port of ports) {
290
312
  const candidate = createServer((req, res) => {
291
313
  void handler(req, res, port, state).catch((error: unknown) => {
292
314
  text(res, `internal error: ${error instanceof Error ? error.message : String(error)}`, 500);
@@ -304,7 +326,7 @@ export async function startWebServer(options: WebServerOptions): Promise<WebServ
304
326
  candidate.close();
305
327
  }
306
328
  if (!server) {
307
- throw new Error(`cannot bind a review server on ports ${portStart}–${portStart + attempts - 1}`);
329
+ throw new Error(`cannot bind a review server on ports ${ports[0]}–${ports.at(-1)}`);
308
330
  }
309
331
  server.unref();
310
332
  heartbeat = setInterval(() => {
@@ -1 +0,0 @@
1
- :root{--paper:#fdf9f5;--paper-deep:#f4e7e2;--surface:#fffdfb;--surface-muted:#f6e9e2;--border:#ead8d1;--ink:#2b1a24;--muted:#8a7280;--brand:#e0446b;--brand-2:#f2704f;--accent:#7c5cfc;--success:#0f8a6a;--warning:#c97a15;--danger:#d23b4e;--tint-success:#e7f4ef;--tint-warning:#fbf0dc;--tint-accent:#ede8ff;--tint-danger:#fbe9ea;--tint-blush:#fdf0ec;--tint-paper:#f8ede8;--shadow:0 10px 32px #471b2712;--shadow-soft:0 18px 50px #471b2724;--serif:"P052", "Palatino Linotype", Palatino, "Iowan Old Style", Georgia, "Noto Serif", "Songti SC", serif;--sans:"Ubuntu Sans", "Noto Sans", "Droid Sans Fallback", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;--mono:"Noto Sans Mono", ui-monospace, SFMono-Regular, Menlo, monospace;--footer-h:96px;--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light}*{box-sizing:border-box}body{min-height:100vh;color:var(--ink);font:15px/1.65 var(--sans);background:radial-gradient(680px 680px at 108% -6%, #f8b7ad8c, transparent 68%), radial-gradient(620px 620px at -10% 38%, #cbb9ff59, transparent 70%), radial-gradient(460px 460px at 106% 82%, #ffc7a857, transparent 70%), linear-gradient(180deg, var(--paper), var(--paper-deep));background-attachment:fixed;margin:0}.page{max-width:1440px;padding:0 140px calc(var(--footer-h) + 54px);margin:0 auto}.topbar{border-bottom:1px solid #c8a69c8c;padding:26px 0 18px}.masthead{justify-content:space-between;align-items:center;gap:16px;display:flex}.brand{align-items:center;gap:12px;display:flex}.brand-mark{width:32px;height:32px;color:var(--surface);background:linear-gradient(135deg, var(--brand), var(--brand-2));border-radius:10px;place-items:center;display:grid;box-shadow:0 6px 16px #e0446b59}.brand-mark svg{width:17px;height:17px}.eyebrow{letter-spacing:2.2px;text-transform:uppercase;color:var(--muted);font-size:10px;font-weight:700;line-height:1.2;display:inline-block}.top-actions{align-items:center;gap:10px;display:flex}.title-block{margin-top:18px}h1{font-family:var(--serif);letter-spacing:-.8px;color:var(--ink);overflow-wrap:anywhere;margin:0;font-size:clamp(38px,4.2vw,52px);font-weight:400;line-height:1.05}.meta{color:var(--muted);flex-wrap:wrap;align-items:center;gap:10px;margin-top:12px;font-size:12.5px;display:flex}.meta-path{text-overflow:ellipsis;white-space:nowrap;max-width:360px;font-family:var(--mono);font-size:12px;overflow:hidden}.meta-dot{background:#d9c6c0;border-radius:50%;flex:none;width:4px;height:4px}.meta-changed{color:var(--brand);font-weight:600}.readonly{border:1px solid var(--warning);color:var(--warning);border-radius:999px;padding:1px 8px;font-size:11px;line-height:1.5}.history{flex-wrap:wrap;align-items:center;gap:8px;margin-top:22px;display:flex}.history-label{margin-right:4px}.history-summary{color:var(--muted);margin-left:auto;font-size:11.5px}button{font:inherit;cursor:pointer}button:disabled{opacity:.45;cursor:not-allowed}.ghost{border:1px solid var(--border);height:34px;color:var(--ink);background:#fffdfbb8;border-radius:999px;justify-content:center;align-items:center;padding:0 14px;font-size:12.5px;transition:border-color .15s,background .15s;display:inline-flex}.ghost:hover:not(:disabled){background:var(--surface);border-color:#ddbfb5}.ghost:focus-visible,.chip:focus-visible,.add:focus-visible,.rail-note:focus-visible,.btn-feedback:focus-visible,.btn-approve:focus-visible,.primary:focus-visible,.link:focus-visible,.remove:focus-visible{outline:2px solid var(--brand);outline-offset:2px}.lang{min-width:52px}.link{color:var(--brand);font-size:inherit;background:0 0;border:none;padding:0;font-weight:600;text-decoration:underline}.chip{border:1px solid var(--border);height:30px;color:var(--muted);font-family:var(--mono);background:#fffdfb99;border-radius:999px;align-items:center;gap:6px;padding:0 12px;font-size:12px;transition:border-color .15s,background .15s,color .15s;display:inline-flex}.chip:hover{color:var(--ink);border-color:#ddbfb5}.chip.active{background:linear-gradient(100deg, var(--brand), var(--brand-2));color:var(--surface);border-color:#0000;box-shadow:0 6px 14px #e0446b52}.chip-changed{color:var(--warning);font-size:11px}.chip.active .chip-changed{color:#fffdfbd1}.layout{grid-template-columns:minmax(0,748px) 364px;align-items:start;gap:48px;padding-top:28px;display:grid}.reading{flex-direction:column;gap:14px;display:flex}.rail{flex-direction:column;gap:18px;display:flex}.error{color:#8e2433;background:#fbe9ead9;border:1px solid #d23b4e66;border-radius:14px;margin-bottom:14px;padding:12px 16px;font-size:13px}.banner{color:#7a4a0e;background:#fbf0dccc;border:1px solid #c97a1559;border-radius:14px;justify-content:space-between;align-items:center;gap:12px;padding:10px 14px;font-size:12.5px;display:flex}.done{border:1px solid var(--border);background:var(--surface);box-shadow:var(--shadow);border-radius:16px;padding:18px}.done-title{font-family:var(--serif);font-size:20px;line-height:1.3}.done-hint{color:var(--muted);margin-top:4px;font-size:13px}.empty{border:1px dashed var(--border);color:var(--muted);text-align:center;background:#fffdfb99;border-radius:16px;margin:0;padding:22px}.collapsed{border:1px solid var(--border);height:44px;color:var(--muted);background:#fff9f5b3;border-radius:12px;justify-content:center;align-items:center;gap:8px;font-size:12px;display:flex}.global-card{border:1px solid var(--border);background:var(--surface);box-shadow:var(--shadow);border-radius:16px;flex-direction:column;gap:12px;padding:18px 22px;scroll-margin-top:24px;display:flex}.global-head{align-items:center;gap:10px;display:flex}.global-head .add{margin-left:auto}.global-count{background:var(--tint-blush);color:#b72847;border-radius:999px;justify-content:center;align-items:center;min-width:22px;height:20px;padding:0 8px;font-size:11px;font-weight:700;display:inline-flex}.blocks{flex-direction:column;gap:14px;display:flex}.block{border:1px solid var(--border);background:var(--surface);box-shadow:var(--shadow);border-radius:16px;scroll-margin-top:24px;overflow:hidden}.block-bar{width:100%;height:3px}.bar-added{background:linear-gradient(90deg, var(--success), #0f8a6a00)}.bar-modified{background:linear-gradient(90deg, var(--warning), #c97a1500)}.bar-moved{background:linear-gradient(90deg, var(--accent), #7c5cfc00)}.bar-removed{background:linear-gradient(90deg, var(--danger), #d23b4e00)}.bar-unchanged{background:linear-gradient(90deg,#ead8d1e6,#ead8d100)}.block-inner{flex-direction:column;gap:12px;padding:18px 22px 20px;display:flex}.block.is-removed .block-body{opacity:.68}.block-head{align-items:center;gap:10px;min-height:24px;display:flex}.badge{letter-spacing:1.1px;text-transform:uppercase;white-space:nowrap;border-radius:999px;align-items:center;gap:6px;height:22px;padding:0 9px;font-size:10px;font-weight:700;line-height:1;display:inline-flex}.badge .dot{width:5px;height:5px}.badge-added{background:var(--tint-success);color:var(--success)}.badge-modified{background:var(--tint-warning);color:var(--warning)}.badge-moved{background:var(--tint-accent);color:var(--accent)}.badge-removed{background:var(--tint-danger);color:var(--danger)}.badge-unchanged{background:var(--surface-muted);color:var(--muted)}.dot{border-radius:50%;flex:none;width:6px;height:6px;display:inline-block}.badge .dot-added,.dot-added{background:var(--success)}.badge .dot-modified,.dot-modified{background:var(--warning)}.badge .dot-moved,.dot-moved{background:var(--accent)}.badge .dot-removed,.dot-removed{background:var(--danger)}.badge-unchanged .dot{background:var(--muted)}.rail-row .dot-removed{background:#d9c6c0}.dot-change,.dot-brand{background:var(--brand)}.dot-suggest{background:var(--accent)}.dot-question{background:var(--muted)}.block-id{font-family:var(--mono);color:var(--muted);font-size:10.5px;line-height:1}.add{color:var(--muted);background:0 0;border:none;border-radius:8px;margin-left:auto;padding:4px 6px;font-size:11.5px;transition:color .15s,background .15s}.add:hover{background:var(--tint-blush);color:var(--brand)}.block-body{color:var(--ink);overflow-wrap:anywhere;font-size:15px;line-height:1.65}.block-body>:first-child{margin-top:0}.block-body>:last-child{margin-bottom:0}.block-body p{margin:0 0 12px}.block-body h1,.block-body h2,.block-body h3,.block-body h4{font-family:var(--serif);letter-spacing:-.2px;color:var(--ink);margin:8px 0 10px;font-weight:400;line-height:1.25}.block-body h1{font-size:26px}.block-body h2{font-size:23px}.block-body h3{font-size:19px}.block-body h4{font-size:16px}.block-body ul,.block-body ol{margin:0 0 12px;padding-left:22px}.block-body li{margin:4px 0}.block-body code{color:#a9304a;font-family:var(--mono);background:#f1e4de;border-radius:5px;padding:1px 5px;font-size:.9em}.block-body pre{color:#ffe9e2;font-family:var(--mono);background:#2a1a22;border-radius:12px;margin:0 0 12px;padding:14px 16px;font-size:12.5px;line-height:1.6;overflow:auto}.block-body pre code{color:inherit;font-size:inherit;background:0 0;padding:0}.block-body a{color:var(--brand);text-underline-offset:2px;text-decoration:underline}.block-body blockquote{border-left:3px solid var(--border);color:var(--muted);margin:0 0 12px;padding-left:12px}.block-body table{border-collapse:collapse;width:100%;margin:0 0 12px;font-size:13.5px}.block-body th,.block-body td{border:1px solid var(--border);text-align:left;padding:6px 8px}.block-body th{background:var(--surface-muted);font-weight:600}.block-body hr{border:none;border-top:1px solid var(--border);margin:16px 0}.note{background:var(--tint-blush);border:1px solid #f3d3c8;border-radius:12px;align-items:flex-start;gap:10px;padding:11px 12px;font-size:13px;line-height:1.5;display:flex}.note-suggest{background:#f4f0ff;border-color:#dcd2f5}.note-question{border-color:var(--border);background:#f7f1ed}.note-verdict{letter-spacing:1px;text-transform:uppercase;white-space:nowrap;border-radius:999px;flex:none;padding:4px 8px;font-size:9.5px;font-weight:700;line-height:1}.verdict-change{color:#b72847;background:#f8dde2}.verdict-suggest{color:#5b3fc9;background:#ede8ff}.verdict-question{color:#7a5a4c;background:#efe4de}.note-text{white-space:pre-wrap;overflow-wrap:anywhere;flex:1;min-width:0}.remove{color:var(--muted);background:0 0;border:none;padding:0 0 0 4px;font-size:11.5px}.remove:hover{color:var(--danger)}.editor{background:#fffbf8;border:1px solid #ebcbc1;border-radius:14px;flex-direction:column;gap:10px;padding:14px;display:flex}.verdicts{flex-wrap:wrap;align-items:center;gap:8px;display:flex}.verdicts label{border:1px solid var(--border);height:28px;color:var(--muted);cursor:pointer;border-radius:999px;align-items:center;padding:0 12px;font-size:11.5px;transition:border-color .15s,background .15s,color .15s;display:inline-flex;position:relative}.verdicts label input{opacity:0;pointer-events:none;position:absolute}.verdicts label.active{background:var(--brand);color:var(--surface);border-color:#0000;font-weight:600}.editor textarea{resize:vertical;border:1px solid var(--border);background:var(--surface);width:100%;min-height:62px;color:var(--ink);font:inherit;border-radius:10px;outline:none;padding:10px 12px;font-size:13px;line-height:1.5}.editor textarea:focus{border-color:var(--brand);box-shadow:0 0 0 3px #e0446b1f}.editor-actions{justify-content:flex-end;align-items:center;gap:10px;display:flex}.primary{background:linear-gradient(100deg, var(--brand), var(--brand-2));height:32px;color:var(--surface);border:none;border-radius:999px;padding:0 16px;font-size:12px;font-weight:600}.rail-card{border:1px solid var(--border);background:var(--surface);box-shadow:var(--shadow);border-radius:16px;flex-direction:column;gap:12px;padding:20px;display:flex}.rail-big{align-items:flex-end;gap:10px;display:flex}.rail-number{font-family:var(--serif);color:var(--brand);font-size:50px;line-height:1}.rail-caption{color:var(--ink);flex-direction:column;gap:2px;padding-bottom:6px;font-size:12.5px;display:flex}.rail-caption .muted{color:var(--muted);font-size:11px}.rail-breakdown{flex-direction:column;gap:2px;display:flex}.rail-row{height:22px;color:var(--muted);align-items:center;gap:8px;font-size:12.5px;display:flex}.rail-row>span:nth-child(2){text-transform:capitalize}.rail-row b{color:var(--ink);margin-left:auto;font-weight:600}.rail-head{justify-content:space-between;align-items:center;gap:10px;display:flex}.rail-badge{background:var(--tint-blush);color:#b72847;border-radius:999px;justify-content:center;align-items:center;min-width:22px;height:20px;padding:0 8px;font-size:11px;font-weight:700;display:inline-flex}.rail-notes{flex-direction:column;gap:4px;display:flex}.rail-note{text-align:left;background:0 0;border:none;border-radius:10px;align-items:flex-start;gap:8px;width:100%;padding:8px;display:flex}.rail-note:hover{background:#fbf3ee}.rail-note .dot{margin-top:5px}.rail-note-body{flex-direction:column;gap:2px;min-width:0;display:flex}.rail-note-label{color:var(--muted);letter-spacing:.8px;text-transform:uppercase;white-space:nowrap;text-overflow:ellipsis;font-size:10px;overflow:hidden}.rail-note-text{color:var(--ink);-webkit-line-clamp:2;-webkit-box-orient:vertical;font-size:12.5px;line-height:1.45;display:-webkit-box;overflow:hidden}.rail-empty{color:var(--muted);margin:0;font-size:12.5px;line-height:1.5}.footer{z-index:30;width:min(1232px,100vw - 48px);min-height:76px;box-shadow:var(--shadow-soft);-webkit-backdrop-filter:blur(18px);backdrop-filter:blur(18px);background:#fffdfbf0;border:1px solid #ebd8d1;border-radius:24px;grid-template-columns:1fr auto 1fr;align-items:center;gap:16px;padding:14px 24px;display:grid;position:fixed;bottom:18px;left:50%;transform:translate(-50%)}.footer-left,.footer-actions{align-items:center;gap:10px;display:flex}.footer-actions{justify-self:end}.footer-center{justify-self:center}.notes-count{background:var(--tint-paper);height:30px;color:var(--muted);white-space:nowrap;border-radius:999px;align-items:center;gap:8px;padding:0 12px;font-size:12px;font-weight:600;display:inline-flex}.notes-count .dot{width:7px;height:7px}.btn-feedback{background:var(--surface);color:#a9304a;border:1px solid #e7c9c1;border-radius:999px;height:44px;padding:0 20px;font-size:13px;font-weight:600;transition:background .15s,border-color .15s}.btn-feedback:hover:not(:disabled){background:#fff7f4;border-color:#d9a99c}.btn-approve{background:linear-gradient(100deg, var(--brand), var(--brand-2));height:44px;color:var(--surface);border:none;border-radius:999px;justify-content:center;align-items:center;gap:8px;padding:0 22px;font-size:13px;font-weight:600;transition:filter .15s,box-shadow .15s;display:inline-flex;box-shadow:0 8px 20px #e0446b61}.btn-approve:hover:not(:disabled){filter:brightness(1.03)}.btn-approve svg{width:15px;height:15px}@media (max-width:1200px){.page{padding:0 64px 150px}.layout{grid-template-columns:minmax(0,1fr) 332px;gap:32px}}@media (max-width:1040px){.page{padding:0 40px 150px}.layout{grid-template-columns:minmax(0,1fr)}}@media (max-width:800px){.history-summary{display:none}.footer{border-radius:20px;grid-template-columns:1fr;gap:8px;padding:12px}.footer-left{flex-wrap:wrap;order:1}.footer-center{order:2;justify-self:start}.footer-actions{order:3;justify-self:stretch}.footer-actions .btn-feedback,.footer-actions .btn-approve{flex:1}}@media (max-width:720px){.page{padding:0 20px 220px}.topbar{padding-top:20px}.block-inner{padding:14px 16px 16px}.global-card{padding:14px 16px}.meta-path{max-width:100%}.footer{width:calc(100vw - 24px);bottom:10px}}.bar-talk{background:linear-gradient(90deg,#e0446b4d,#e0446b00)}.block-talk .block-head{justify-content:space-between}.block-talk .block-id{display:none}.note-talk{align-items:center}.verdict-talk{color:#b72847;background:#f8dde2}.note-input{background:var(--surface);width:100%;min-height:84px;color:var(--ink);font:inherit;resize:vertical;border:1px solid #e7c9c1;border-radius:12px;padding:12px 14px;font-size:13px;line-height:1.55}.note-input:focus{border-color:#e0446b8c;outline:none;box-shadow:0 0 0 3px #e0446b1f}.rail-hint{color:var(--muted);margin:10px 0 14px;font-size:12px;line-height:1.5}.block.is-target{animation:1.2s ease-out target-flash}@keyframes target-flash{0%,55%{box-shadow:0 0 0 3px #e0446b29, var(--shadow);border-color:#e0446bbf}to{border-color:var(--border);box-shadow:var(--shadow)}}.footer-talk{grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:18px;padding:14px 20px}.footer-composer{min-width:0}.composer-input{background:var(--surface);width:100%;height:24px;max-height:220px;color:var(--ink);font:inherit;resize:none;border:1px solid #e7c9c1;border-radius:14px;padding:6px 12px;font-size:13.5px;line-height:1.55;transition:border-color .15s,box-shadow .15s,height .12s;display:block;overflow-y:hidden}.composer-input:focus{border-color:#e0446b80;outline:none;box-shadow:0 0 0 3px #e0446b1a}.outline{z-index:40;pointer-events:none;justify-content:flex-end;align-items:center;display:flex;position:fixed;top:40vh;right:max(20px,50vw - 624px)}.outline-bars{pointer-events:auto;cursor:pointer;flex-direction:column;align-items:flex-end;gap:6px;width:16px;display:flex;-webkit-mask-image:linear-gradient(#0000 0,#000 14px calc(100% - 14px),#0000 100%);mask-image:linear-gradient(#0000 0,#000 14px calc(100% - 14px),#0000 100%)}.outline-bars:hover .outline-bar{background:#a06c70bf}.outline-bar{background:#d3b3ac;border-radius:999px;height:2px;transition:background .15s,width .15s}.outline-bar.is-active{background:var(--brand);height:3px}.outline.is-open .outline-bars{opacity:.5}.outline-panel{border:1px solid var(--border);-webkit-backdrop-filter:blur(18px);backdrop-filter:blur(18px);pointer-events:none;opacity:0;transform-origin:100%;background:#fffdfbf7;border-radius:16px;flex-direction:column;width:292px;max-height:min(60vh,460px);transition:opacity .18s,transform .18s;display:flex;position:absolute;top:50%;right:26px;transform:translateY(-50%)translate(10px)scaleX(.96);box-shadow:0 18px 50px #471b2729}.outline.is-open .outline-panel{pointer-events:auto;opacity:1;transform:translateY(-50%)translate(0)scaleX(1)}.outline-head{justify-content:space-between;align-items:baseline;gap:12px;padding:14px 16px 8px;display:flex}.outline-count{color:var(--muted);font-size:10.5px}.outline-list{overscroll-behavior:contain;flex-direction:column;gap:1px;padding:0 6px 10px;display:flex;overflow-y:auto;-webkit-mask-image:linear-gradient(#0000 0,#000 10px calc(100% - 12px),#0000 100%);mask-image:linear-gradient(#0000 0,#000 10px calc(100% - 12px),#0000 100%)}.outline-row{color:var(--ink);font:inherit;text-align:left;white-space:nowrap;text-overflow:ellipsis;background:0 0;border:none;border-radius:8px;padding:7px 10px;font-size:13px;line-height:1.35;transition:background .12s,color .12s;position:relative;overflow:hidden}.outline-row:hover{color:#b79aa2;background:#e0446b0d}.outline-row.is-active{color:var(--brand);background:#e0446b12;font-weight:600}.outline-row.is-active:before{content:"";background:var(--brand);border-radius:999px;width:2px;position:absolute;top:6px;bottom:6px;left:0}.outline-text{text-overflow:ellipsis;display:block;overflow:hidden}.back-to-top{right:max(20px,50vw - 624px);bottom:calc(var(--footer-h) + 16px);z-index:35;border:1px solid var(--border);color:#a9304a;height:38px;font:inherit;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);cursor:pointer;background:#fffdfbf5;border-radius:999px;align-items:center;gap:8px;padding:0 16px;font-size:12.5px;font-weight:600;animation:.18s ease-out back-to-top-in;display:inline-flex;position:fixed;box-shadow:0 12px 30px #471b2724}.back-to-top svg{width:14px;height:14px}.back-to-top:hover{background:#fff7f4;border-color:#e7c9c1}@keyframes back-to-top-in{0%{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}@media (max-width:1040px){.outline{display:none}}@media (max-width:800px){.footer-talk{grid-template-columns:1fr;align-items:stretch}.footer-talk .footer-center{justify-self:start}.footer-talk .footer-actions{justify-self:stretch}.footer-talk .btn-approve{flex:1}.back-to-top{right:16px}}@media (prefers-reduced-motion:reduce){.outline-panel,.outline-bar,.composer-input{transition:none}.back-to-top{animation:none}}