@andares/pi-toolkits 1.1.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +31 -5
  3. package/README.zh-CN.md +31 -5
  4. package/package.json +5 -3
  5. package/src/features/review-page/assets/index-DPWL_ipb.css +1 -0
  6. package/src/features/review-page/assets/index-XxrDCe96.js +1 -0
  7. package/src/features/{spec → review-page}/assets/index.html +2 -2
  8. package/src/features/{spec → review-page}/blocks.test.ts +17 -0
  9. package/src/features/{spec → review-page}/blocks.ts +9 -0
  10. package/src/features/review-page/headings.test.ts +44 -0
  11. package/src/features/review-page/headings.ts +67 -0
  12. package/src/features/spec/assets.test.ts +18 -3
  13. package/src/features/spec/diff.test.ts +1 -1
  14. package/src/features/spec/diff.ts +1 -1
  15. package/src/features/spec/feedback.test.ts +1 -1
  16. package/src/features/spec/feedback.ts +1 -1
  17. package/src/features/spec/index.test.ts +42 -1
  18. package/src/features/spec/index.ts +2 -2
  19. package/src/features/spec/server.test.ts +64 -6
  20. package/src/features/spec/server.ts +21 -3
  21. package/src/features/spec/store.ts +1 -1
  22. package/src/features/talk/index.test.ts +286 -0
  23. package/src/features/talk/index.ts +301 -0
  24. package/src/features/talk/message.test.ts +212 -0
  25. package/src/features/talk/message.ts +152 -0
  26. package/src/features/talk/reply.test.ts +116 -0
  27. package/src/features/talk/reply.ts +92 -0
  28. package/src/features/talk/sections.test.ts +39 -0
  29. package/src/features/talk/sections.ts +44 -0
  30. package/src/features/talk/server.test.ts +284 -0
  31. package/src/features/talk/server.ts +232 -0
  32. package/src/features/uat/index.test.ts +19 -1
  33. package/src/index.ts +4 -0
  34. package/src/lib/web-review.test.ts +80 -0
  35. package/src/lib/web-review.ts +27 -5
  36. package/src/features/spec/assets/index-CdTerMvN.css +0 -1
  37. package/src/features/spec/assets/index-Dv52AIjX.js +0 -1
  38. /package/src/features/{spec → review-page}/render.test.ts +0 -0
  39. /package/src/features/{spec → review-page}/render.ts +0 -0
@@ -0,0 +1,116 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { extractLastReply } from "./reply.js";
3
+
4
+ function user(text: string): object {
5
+ return { id: `u-${text}`, type: "message", message: { role: "user", content: [{ type: "text", text }] } };
6
+ }
7
+
8
+ function assistant(content: unknown[], extra: Record<string, unknown> = {}): object {
9
+ return {
10
+ id: `a-${Math.random().toString(36).slice(2)}`,
11
+ type: "message",
12
+ message: { role: "assistant", content, model: "provider/model", timestamp: 1_700_000_000_000, ...extra },
13
+ };
14
+ }
15
+
16
+ describe("extractLastReply", () => {
17
+ it("returns the text of the last assistant message", () => {
18
+ const reply = extractLastReply([user("hi"), assistant([{ type: "text", text: " hello there " }])]);
19
+ expect(reply?.text).toBe("hello there");
20
+ expect(reply?.model).toBe("provider/model");
21
+ expect(reply?.at).toBe(new Date(1_700_000_000_000).toISOString());
22
+ });
23
+
24
+ it("excludes thinking and tool calls", () => {
25
+ const reply = extractLastReply([
26
+ user("hi"),
27
+ assistant([
28
+ { type: "thinking", thinking: "internal reasoning" },
29
+ { type: "toolCall", name: "bash", arguments: {} },
30
+ { type: "text", text: "the answer" },
31
+ ]),
32
+ ]);
33
+ expect(reply?.text).toBe("the answer");
34
+ });
35
+
36
+ it("drops commentary before a tool call inside the SAME assistant message", () => {
37
+ const reply = extractLastReply([
38
+ user("hi"),
39
+ assistant([
40
+ { type: "text", text: "I will check that first" },
41
+ { type: "toolCall", name: "read", arguments: {} },
42
+ { type: "text", text: "the actual answer" },
43
+ ]),
44
+ ]);
45
+ expect(reply?.text).toBe("the actual answer");
46
+ });
47
+
48
+ it("drops commentary before late thinking inside the SAME assistant message", () => {
49
+ const reply = extractLastReply([
50
+ user("hi"),
51
+ assistant([
52
+ { type: "text", text: "draft" },
53
+ { type: "thinking", thinking: "more reasoning" },
54
+ { type: "text", text: "final" },
55
+ ]),
56
+ ]);
57
+ expect(reply?.text).toBe("final");
58
+ });
59
+
60
+ it("takes only the final assistant message of a multi-step turn", () => {
61
+ const reply = extractLastReply([
62
+ user("do the thing"),
63
+ assistant([{ type: "text", text: "let me check" }]),
64
+ { id: "t1", type: "message", message: { role: "toolResult", content: [{ type: "text", text: "ok" }] } },
65
+ assistant([{ type: "text", text: "done, here is what changed" }]),
66
+ ]);
67
+ expect(reply?.text).toBe("done, here is what changed");
68
+ });
69
+
70
+ it("skips a tool-only assistant message instead of reporting no reply", () => {
71
+ const reply = extractLastReply([
72
+ user("go"),
73
+ assistant([{ type: "text", text: "the real answer" }]),
74
+ assistant([{ type: "toolCall", name: "read", arguments: {} }]),
75
+ ]);
76
+ expect(reply?.text).toBe("the real answer");
77
+ });
78
+
79
+ it("stops at the user message — an earlier turn is never the reply", () => {
80
+ const reply = extractLastReply([
81
+ user("first question"),
82
+ assistant([{ type: "text", text: "first answer" }]),
83
+ user("second question"),
84
+ ]);
85
+ expect(reply).toBeUndefined();
86
+ });
87
+
88
+ it("stops at a custom message", () => {
89
+ expect(
90
+ extractLastReply([
91
+ user("q"),
92
+ assistant([{ type: "text", text: "a" }]),
93
+ { id: "c1", type: "custom_message", customType: "keep:resumed", content: "note" },
94
+ ]),
95
+ ).toBeUndefined();
96
+ });
97
+
98
+ it("reports no reply for an empty turn", () => {
99
+ expect(extractLastReply([user("hi")])).toBeUndefined();
100
+ expect(extractLastReply([])).toBeUndefined();
101
+ });
102
+
103
+ it("fingerprints the text, so a refresh can tell same from different", () => {
104
+ const a = extractLastReply([user("q"), assistant([{ type: "text", text: "same" }])]);
105
+ const b = extractLastReply([user("q"), assistant([{ type: "text", text: "same" }])]);
106
+ const c = extractLastReply([user("q"), assistant([{ type: "text", text: "different" }])]);
107
+ expect(a?.fingerprint).toBe(b?.fingerprint);
108
+ expect(a?.fingerprint).not.toBe(c?.fingerprint);
109
+ });
110
+
111
+ it("carries the entry id so callers can test compaction survival", () => {
112
+ const entry = assistant([{ type: "text", text: "x" }]) as { id: string };
113
+ const reply = extractLastReply([user("q"), entry]);
114
+ expect(reply?.entryId).toBe(entry.id);
115
+ });
116
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * reply capture — "the agent's last formal reply", as text.
3
+ *
4
+ * The page annotates the answer, not the work that produced it: thinking blocks
5
+ * and tool calls are separate content types on the assistant message. Only the
6
+ * trailing run of `text` blocks is used, so commentary before a tool call inside
7
+ * the same message is excluded too. The other rule is the turn boundary — a run may contain several assistant messages ("let me check
8
+ * that first" → tools → the actual answer), and only the last one is the reply.
9
+ *
10
+ * The scan therefore walks backwards and stops at the first user/custom message
11
+ * (or compaction boundary). Anything older than that belongs to a previous turn
12
+ * and annotating it would be confusing: the model already moved on.
13
+ */
14
+ import { createHash } from "node:crypto";
15
+
16
+ export interface ReplySnapshot {
17
+ text: string;
18
+ /** Session entry id, so callers can ask whether it survived compaction. */
19
+ entryId: string;
20
+ model?: string;
21
+ /** ISO timestamp of the assistant message, when the host recorded one. */
22
+ at: string;
23
+ /** Hash of the text — how a re-run decides "same reply, keep the notes". */
24
+ fingerprint: string;
25
+ }
26
+
27
+ interface ContentBlock {
28
+ type?: unknown;
29
+ text?: unknown;
30
+ }
31
+
32
+ interface MessageLike {
33
+ role?: unknown;
34
+ content?: unknown;
35
+ model?: unknown;
36
+ timestamp?: unknown;
37
+ }
38
+
39
+ interface EntryLike {
40
+ id?: unknown;
41
+ type?: unknown;
42
+ message?: MessageLike;
43
+ }
44
+
45
+ function textOf(message: MessageLike): string {
46
+ if (!Array.isArray(message.content)) return "";
47
+ let parts: string[] = [];
48
+ for (const block of message.content as ContentBlock[]) {
49
+ if (block?.type === "text" && typeof block.text === "string") {
50
+ parts.push(block.text);
51
+ } else {
52
+ // Thinking and tool calls can occur BETWEEN text blocks in one assistant
53
+ // message. Text before that boundary is commentary, not the final reply.
54
+ parts = [];
55
+ }
56
+ }
57
+ return parts.join("").trim();
58
+ }
59
+
60
+ function isTurnBoundary(entry: EntryLike): boolean {
61
+ if (entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary") {
62
+ return true;
63
+ }
64
+ return entry.type === "message" && entry.message?.role === "user";
65
+ }
66
+
67
+ /**
68
+ * Last formal reply on the branch, or undefined when the current turn has none.
69
+ *
70
+ * `entries` is `ctx.sessionManager.getBranch()` (oldest → newest).
71
+ */
72
+ export function extractLastReply(entries: readonly unknown[]): ReplySnapshot | undefined {
73
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
74
+ const entry = entries[i] as EntryLike;
75
+ if (!entry || typeof entry !== "object") continue;
76
+ if (isTurnBoundary(entry)) return undefined;
77
+ if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
78
+ const text = textOf(entry.message);
79
+ // An assistant message with no text is a tool-only step of the same turn;
80
+ // keep walking instead of reporting "no reply".
81
+ if (text === "") continue;
82
+ const timestamp = typeof entry.message.timestamp === "number" ? entry.message.timestamp : undefined;
83
+ return {
84
+ text,
85
+ entryId: typeof entry.id === "string" ? entry.id : "",
86
+ model: typeof entry.message.model === "string" ? entry.message.model : undefined,
87
+ at: new Date(timestamp ?? Date.now()).toISOString(),
88
+ fingerprint: createHash("sha1").update(text).digest("hex").slice(0, 16),
89
+ };
90
+ }
91
+ return undefined;
92
+ }
@@ -0,0 +1,39 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { parseBlocks } from "../review-page/blocks.js";
3
+ import { headingDepth, sectionPaths } from "./sections.js";
4
+
5
+ describe("sectionPaths", () => {
6
+ it("labels every block with the chain of headings above it", () => {
7
+ const blocks = parseBlocks(
8
+ "# Plan\n\nintro\n\n## Approach\n\nbody\n\n### Milestones\n\ndetail\n\n## Risks\n\nrisk",
9
+ );
10
+ const paths = sectionPaths(blocks);
11
+ expect(paths.get(blocks[0].id)).toBe("Plan");
12
+ expect(paths.get(blocks[1].id)).toBe("Plan");
13
+ expect(paths.get(blocks[3].id)).toBe("Plan > Approach");
14
+ expect(paths.get(blocks[4].id)).toBe("Plan > Approach > Milestones");
15
+ expect(paths.get(blocks[5].id)).toBe("Plan > Approach > Milestones");
16
+ expect(paths.get(blocks[7].id)).toBe("Plan > Risks");
17
+ });
18
+
19
+ it("leaves blocks before the first heading without a path", () => {
20
+ const blocks = parseBlocks("preamble\n\n## Later\n\nbody");
21
+ expect(sectionPaths(blocks).get(blocks[0].id)).toBe("");
22
+ });
23
+
24
+ it("closes deeper sections when a shallower heading appears", () => {
25
+ const blocks = parseBlocks("## A\n\n### B\n\ntext\n\n## C\n\ntext");
26
+ const paths = sectionPaths(blocks);
27
+ expect(paths.get(blocks[2].id)).toBe("A > B");
28
+ expect(paths.get(blocks[4].id)).toBe("C");
29
+ });
30
+ });
31
+
32
+ describe("headingDepth", () => {
33
+ it("maps the levels actually present onto 0..3", () => {
34
+ expect(headingDepth(2, [2, 3, 4])).toBe(0);
35
+ expect(headingDepth(3, [2, 3, 4])).toBe(1);
36
+ expect(headingDepth(6, [2, 3, 4, 5, 6])).toBe(3);
37
+ expect(headingDepth(9, [2, 3])).toBe(0);
38
+ });
39
+ });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * sections — which chapter a block belongs to.
3
+ *
4
+ * Two consumers, one answer: the page indents outline rows by this, and the
5
+ * message back to the model labels each quote with the chapter it came from
6
+ * ("where exactly are you talking about?"). Both read the same structure, so a
7
+ * note can never be filed under a heading the operator did not see.
8
+ *
9
+ * Paths are outermost → nearest ("Approach > M2 · the review page"): the model
10
+ * is locating text, and the top-level chapters are what it remembers best.
11
+ */
12
+ import type { Block } from "../review-page/blocks.js";
13
+ import { headingOf } from "../review-page/headings.js";
14
+
15
+ export interface SectionEntry {
16
+ level: number;
17
+ text: string;
18
+ }
19
+
20
+ /** One breadcrumb string per block id (blocks outside any heading get ""). */
21
+ export function sectionPaths(blocks: readonly Block[]): Map<string, string> {
22
+ const paths = new Map<string, string>();
23
+ const stack: SectionEntry[] = [];
24
+ for (const block of blocks) {
25
+ const heading = headingOf(block);
26
+ if (heading) {
27
+ // A new heading closes every open section at the same or deeper level.
28
+ while (stack.length > 0 && (stack.at(-1)?.level ?? 0) >= heading.level) stack.pop();
29
+ stack.push(heading);
30
+ }
31
+ paths.set(
32
+ block.id,
33
+ stack.map((entry) => entry.text).join(" > "),
34
+ );
35
+ }
36
+ return paths;
37
+ }
38
+
39
+ /** Depth of a heading inside its outline (0 = top level present in the doc). */
40
+ export function headingDepth(level: number, levels: readonly number[]): number {
41
+ const distinct = [...new Set(levels)].sort((a, b) => a - b);
42
+ const index = distinct.indexOf(level);
43
+ return index < 0 ? 0 : Math.min(index, 3);
44
+ }
@@ -0,0 +1,284 @@
1
+ import { request } from "node:http";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { parseBlocks } from "../review-page/blocks.js";
4
+ import { renderBlockHtml } from "../review-page/render.js";
5
+ import { buildTalkState, sanitizeNotes, startTalkServer, type TalkServerHandle, type TalkSession } from "./server.js";
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
+
22
+ const REPLY = "## Approach\n\nfirst block\n\n## Milestones\n\nsecond block";
23
+
24
+ function makeSession(overrides: Partial<TalkSession> = {}): TalkSession {
25
+ const blocks = parseBlocks(REPLY);
26
+ return {
27
+ text: REPLY,
28
+ blocks,
29
+ headings: [],
30
+ model: "provider/model",
31
+ at: "2026-11-25T00:00:00.000Z",
32
+ entryId: "reply-entry",
33
+ fingerprint: "abc",
34
+ notes: {},
35
+ draft: "",
36
+ sent: false,
37
+ inContext: true,
38
+ ...overrides,
39
+ };
40
+ }
41
+
42
+ async function serve(
43
+ session: TalkSession,
44
+ overrides: Partial<Parameters<typeof startTalkServer>[0]> = {},
45
+ ): Promise<TalkServerHandle> {
46
+ return startTalkServer({
47
+ session,
48
+ assetsDir: "/nonexistent-assets",
49
+ render: renderBlockHtml,
50
+ portStart: takePort(),
51
+ portAttempts: 20,
52
+ bindHost: "127.0.0.1",
53
+ urlHost: "127.0.0.1",
54
+ closeDelayMs: 0,
55
+ ...overrides,
56
+ });
57
+ }
58
+
59
+ interface CallResult {
60
+ status: number;
61
+ text: string;
62
+ json: () => unknown;
63
+ }
64
+
65
+ function call(
66
+ port: number,
67
+ path: string,
68
+ options: { method?: string; token?: string; body?: unknown; headers?: Record<string, string> } = {},
69
+ ): Promise<CallResult> {
70
+ return new Promise((resolve, reject) => {
71
+ const headers: Record<string, string> = { ...(options.headers ?? {}) };
72
+ if (options.token) headers["x-plan-token"] = options.token;
73
+ if (options.body !== undefined) headers["content-type"] = "application/json";
74
+ const req = request(
75
+ {
76
+ host: "127.0.0.1",
77
+ port,
78
+ method: options.method ?? "GET",
79
+ path,
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,
84
+ },
85
+ (res) => {
86
+ const chunks: Buffer[] = [];
87
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
88
+ res.on("end", () => {
89
+ const text = Buffer.concat(chunks).toString("utf8");
90
+ resolve({ status: res.statusCode ?? 0, text, json: () => JSON.parse(text) as unknown });
91
+ });
92
+ },
93
+ );
94
+ req.on("error", reject);
95
+ if (options.body !== undefined) req.write(JSON.stringify(options.body));
96
+ req.end();
97
+ });
98
+ }
99
+
100
+ describe("buildTalkState", () => {
101
+ it("describes the snapshot without any version or diff fields", () => {
102
+ const session = makeSession({ title: "Parallel session A" });
103
+ const state = buildTalkState(session);
104
+ expect(state.mode).toBe("talk");
105
+ expect(state.title).toBe("Parallel session A");
106
+ expect(state.reply).toEqual({ model: "provider/model", at: "2026-11-25T00:00:00.000Z", chars: REPLY.length });
107
+ expect(state.items).toHaveLength(4);
108
+ expect(state.items.every((item) => item.html === "")).toBe(true);
109
+ expect(state).not.toHaveProperty("version");
110
+ expect(state).not.toHaveProperty("history");
111
+ expect(state.sent).toBe(false);
112
+ });
113
+ });
114
+
115
+ describe("sanitizeNotes", () => {
116
+ it("keeps only non-heading notes on blocks of this reply, with real text", () => {
117
+ const blocks = parseBlocks(REPLY);
118
+ const notes = sanitizeNotes(
119
+ { [blocks[0].id]: "heading notes are not allowed", [blocks[1].id]: "keep", "stale#0": "drop", [blocks[2].id]: " ", [blocks[3].id]: 42 },
120
+ blocks,
121
+ );
122
+ expect(notes).toEqual({ [blocks[1].id]: "keep" });
123
+ });
124
+ });
125
+
126
+ describe("talk server", () => {
127
+ it("serves state with rendered blocks and the headings index", async () => {
128
+ const session = makeSession();
129
+ const server = await serve(session);
130
+ try {
131
+ const response = await call(server.port, `/api/state?t=${server.token}`);
132
+ expect(response.status).toBe(200);
133
+ const state = response.json() as {
134
+ mode: string;
135
+ items: Array<{ html: string }>;
136
+ headings: unknown[];
137
+ sent: boolean;
138
+ };
139
+ expect(state.mode).toBe("talk");
140
+ expect(state.items[0].html).toContain("<h2>");
141
+ expect(Array.isArray(state.headings)).toBe(true);
142
+ expect(state.sent).toBe(false);
143
+ } finally {
144
+ await server.close();
145
+ }
146
+ });
147
+
148
+ it("stores notes and the draft so a page refresh does not lose them", async () => {
149
+ const session = makeSession();
150
+ const server = await serve(session);
151
+ try {
152
+ const blockId = session.blocks[1].id;
153
+ const posted = await call(server.port, "/api/notes", {
154
+ method: "POST",
155
+ token: server.token,
156
+ body: { notes: { [blockId]: "reword me" }, draft: "half-typed thought" },
157
+ });
158
+ expect(posted.status).toBe(200);
159
+ expect(session.notes).toEqual({ [blockId]: "reword me" });
160
+ const state = (await call(server.port, `/api/state?t=${server.token}`)).json() as {
161
+ notes: Record<string, string>;
162
+ draft: string;
163
+ };
164
+ expect(state.notes).toEqual({ [blockId]: "reword me" });
165
+ expect(state.draft).toBe("half-typed thought");
166
+ } finally {
167
+ await server.close();
168
+ }
169
+ });
170
+
171
+ it("accepts exactly one Continue and refuses every later write", async () => {
172
+ const session = makeSession();
173
+ const received: Array<{ notes: Record<string, string>; message: string }> = [];
174
+ const server = await serve(session, {
175
+ onContinue: (result) => received.push(result),
176
+ // Keep the socket open long enough that the follow-up writes hit the
177
+ // 409 guard instead of a closed port — that guard is what the test is about.
178
+ closeDelayMs: 400,
179
+ });
180
+ try {
181
+ const first = await call(server.port, "/api/continue", {
182
+ method: "POST",
183
+ token: server.token,
184
+ body: { notes: { [session.blocks[3].id]: "fix it" }, message: "go on" },
185
+ });
186
+ expect(first.status).toBe(200);
187
+ expect(received).toHaveLength(1);
188
+ expect(received[0].message).toBe("go on");
189
+ expect(server.active()).toBe(false);
190
+
191
+ const second = await call(server.port, "/api/continue", {
192
+ method: "POST",
193
+ token: server.token,
194
+ body: { message: "again" },
195
+ });
196
+ expect(second.status).toBe(409);
197
+ const notes = await call(server.port, "/api/notes", {
198
+ method: "POST",
199
+ token: server.token,
200
+ body: { notes: {} },
201
+ });
202
+ expect(notes.status).toBe(409);
203
+ expect(received).toHaveLength(1);
204
+ expect(session.sent).toBe(true);
205
+ } finally {
206
+ await server.close();
207
+ }
208
+ });
209
+
210
+ it("refuses unauthenticated and cross-origin writes like the spec server", async () => {
211
+ const server = await serve(makeSession());
212
+ try {
213
+ expect((await call(server.port, "/api/state")).status).toBe(401);
214
+ const crossOrigin = await call(server.port, "/api/notes", {
215
+ method: "POST",
216
+ token: server.token,
217
+ body: { notes: {} },
218
+ headers: { origin: "http://evil.example" },
219
+ });
220
+ expect(crossOrigin.status).toBe(403);
221
+ } finally {
222
+ await server.close();
223
+ }
224
+ });
225
+
226
+ it("broadcasts sent once so an open page can switch to the sent state", async () => {
227
+ const server = await serve(makeSession());
228
+ const seen: string[] = [];
229
+ try {
230
+ const response = await new Promise<{ status: number; text: string }>((resolve, reject) => {
231
+ const req = request(
232
+ { host: "127.0.0.1", port: server.port, path: `/api/events?t=${server.token}` },
233
+ (res) => {
234
+ const chunks: string[] = [];
235
+ res.on("data", (chunk: Buffer) => {
236
+ chunks.push(chunk.toString());
237
+ const text = chunks.join("");
238
+ if (!text.includes("event: sent")) {
239
+ if (text.includes(": connected")) {
240
+ void call(server.port, "/api/continue", {
241
+ method: "POST",
242
+ token: server.token,
243
+ body: { message: "go" },
244
+ });
245
+ }
246
+ return;
247
+ }
248
+ req.destroy();
249
+ for (const line of text.split("\n")) if (line.startsWith("event: ")) seen.push(line.slice(7));
250
+ resolve({ status: res.statusCode ?? 0, text });
251
+ });
252
+ },
253
+ );
254
+ req.on("error", (error) => {
255
+ if ((error as NodeJS.ErrnoException).code === "ECONNRESET") return;
256
+ reject(error);
257
+ });
258
+ req.end();
259
+ });
260
+ expect(response.status).toBe(200);
261
+ expect(seen).toContain("sent");
262
+ } finally {
263
+ await server.close();
264
+ }
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
+ });
284
+ });