@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.
- package/CHANGELOG.md +16 -0
- package/README.md +31 -5
- package/README.zh-CN.md +31 -5
- package/package.json +5 -3
- package/src/features/review-page/assets/index-DPWL_ipb.css +1 -0
- package/src/features/review-page/assets/index-XxrDCe96.js +1 -0
- package/src/features/{spec → review-page}/assets/index.html +2 -2
- package/src/features/{spec → review-page}/blocks.test.ts +17 -0
- package/src/features/{spec → review-page}/blocks.ts +9 -0
- package/src/features/review-page/headings.test.ts +44 -0
- package/src/features/review-page/headings.ts +67 -0
- package/src/features/spec/assets.test.ts +18 -3
- package/src/features/spec/diff.test.ts +1 -1
- package/src/features/spec/diff.ts +1 -1
- package/src/features/spec/feedback.test.ts +1 -1
- package/src/features/spec/feedback.ts +1 -1
- package/src/features/spec/index.test.ts +42 -1
- package/src/features/spec/index.ts +2 -2
- package/src/features/spec/server.test.ts +64 -6
- package/src/features/spec/server.ts +21 -3
- package/src/features/spec/store.ts +1 -1
- package/src/features/talk/index.test.ts +286 -0
- package/src/features/talk/index.ts +301 -0
- package/src/features/talk/message.test.ts +212 -0
- package/src/features/talk/message.ts +152 -0
- package/src/features/talk/reply.test.ts +116 -0
- package/src/features/talk/reply.ts +92 -0
- package/src/features/talk/sections.test.ts +39 -0
- package/src/features/talk/sections.ts +44 -0
- package/src/features/talk/server.test.ts +284 -0
- package/src/features/talk/server.ts +232 -0
- package/src/features/uat/index.test.ts +19 -1
- package/src/index.ts +4 -0
- package/src/lib/web-review.test.ts +80 -0
- package/src/lib/web-review.ts +27 -5
- package/src/features/spec/assets/index-CdTerMvN.css +0 -1
- package/src/features/spec/assets/index-Dv52AIjX.js +0 -1
- /package/src/features/{spec → review-page}/render.test.ts +0 -0
- /package/src/features/{spec → review-page}/render.ts +0 -0
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Wiring between the built UI and the review server.
|
|
3
3
|
*
|
|
4
4
|
* The UI is a separate Vite app whose output is committed to
|
|
5
|
-
* `src/features/
|
|
5
|
+
* `src/features/review-page/assets/` (see `pnpm ui:check`). These assertions catch the
|
|
6
6
|
* failure that would otherwise only show up in a browser: the page shipping a
|
|
7
7
|
* bundle path the server cannot resolve (Vite's `assetsDir` and the server's
|
|
8
8
|
* `/assets/<file>` route have to agree).
|
|
@@ -15,7 +15,22 @@ 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
|
-
|
|
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
|
+
|
|
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;
|
|
21
36
|
|
|
@@ -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:
|
|
50
|
+
portStart: takePort(),
|
|
36
51
|
portAttempts: 20,
|
|
37
52
|
bindHost: "127.0.0.1",
|
|
38
53
|
urlHost: "127.0.0.1",
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { parseBlocks } from "
|
|
2
|
+
import { parseBlocks } from "../review-page/blocks.js";
|
|
3
3
|
import { blockSimilarity, countChanged, diffBlocks } from "./diff.js";
|
|
4
4
|
|
|
5
5
|
const parse = (markdown: string) => parseBlocks(markdown);
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* bigrams because plans mix English and CJK (word splitting would collapse a
|
|
22
22
|
* Chinese sentence into one token).
|
|
23
23
|
*/
|
|
24
|
-
import type { Block } from "
|
|
24
|
+
import type { Block } from "../review-page/blocks.js";
|
|
25
25
|
|
|
26
26
|
export type BlockStatus = "unchanged" | "moved" | "modified" | "added" | "removed";
|
|
27
27
|
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* block notes (about one paragraph). There is no inline/range annotation, which
|
|
11
11
|
* is what keeps the block model from needing re-anchoring after an edit.
|
|
12
12
|
*/
|
|
13
|
-
import { blockLabel, type Block } from "
|
|
13
|
+
import { blockLabel, type Block } from "../review-page/blocks.js";
|
|
14
14
|
import type { DiffEntry } from "./diff.js";
|
|
15
15
|
|
|
16
16
|
export type AnnotationVerdict = "change" | "suggest" | "question";
|
|
@@ -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:
|
|
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;
|
|
@@ -34,7 +34,7 @@ import { parseCommandUnits } from "../permission/units.js";
|
|
|
34
34
|
import { buildFeedbackMarkdown } from "./feedback.js";
|
|
35
35
|
import { openInBrowser } from "../../lib/opener.js";
|
|
36
36
|
import { buildSpecKickoff, buildSpecSystemPrompt } from "./prompt.js";
|
|
37
|
-
import { renderBlockHtml } from "
|
|
37
|
+
import { renderBlockHtml } from "../review-page/render.js";
|
|
38
38
|
import { buildSpecState, startSpecServer, type SpecServerHandle } from "./server.js";
|
|
39
39
|
import {
|
|
40
40
|
appendSpecVersion,
|
|
@@ -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
|
|
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
|
|
|
@@ -3,11 +3,26 @@ import { request } from "node:http";
|
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
|
6
|
-
import { parseBlocks } from "
|
|
7
|
-
import { renderBlockHtml } from "
|
|
6
|
+
import { parseBlocks } from "../review-page/blocks.js";
|
|
7
|
+
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:
|
|
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[] = [];
|
|
@@ -126,6 +146,20 @@ describe("buildSpecState", () => {
|
|
|
126
146
|
expect(state.totalVersions).toBe(1);
|
|
127
147
|
});
|
|
128
148
|
|
|
149
|
+
it("declares spec mode and ships an outline over the viewed revision", () => {
|
|
150
|
+
const session = makeSession("# Top\n\nintro\n\n## Section\n\nbody");
|
|
151
|
+
const state = buildSpecState(session);
|
|
152
|
+
expect(state.mode).toBe("spec");
|
|
153
|
+
expect(state.headings.map((heading) => [heading.level, heading.text])).toEqual([
|
|
154
|
+
[1, "Top"],
|
|
155
|
+
[2, "Section"],
|
|
156
|
+
]);
|
|
157
|
+
// Anchors point at blocks the page actually renders.
|
|
158
|
+
for (const heading of state.headings) {
|
|
159
|
+
expect(state.items.some((item) => item.id === heading.blockId)).toBe(true);
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
|
|
129
163
|
it("carries the diff statuses and the previous-block ids for a later revision", () => {
|
|
130
164
|
const session = makeSession("## Spec\n\nwrite the block parser before the server\n\nsecond step");
|
|
131
165
|
const first = session.versions[0];
|
|
@@ -272,7 +306,10 @@ describe("startSpecServer", () => {
|
|
|
272
306
|
it("accepts only the first decision", async () => {
|
|
273
307
|
const session = makeSession();
|
|
274
308
|
const onDecision = vi.fn();
|
|
275
|
-
|
|
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 });
|
|
276
313
|
const first = await call({
|
|
277
314
|
port: server.port,
|
|
278
315
|
path: "/api/decide",
|
|
@@ -289,7 +326,8 @@ describe("startSpecServer", () => {
|
|
|
289
326
|
});
|
|
290
327
|
expect(first.status).toBe(200);
|
|
291
328
|
expect(second.status).toBe(409);
|
|
292
|
-
|
|
329
|
+
// onDecision is delivered on the close timer, not on the request.
|
|
330
|
+
await vi.waitFor(() => expect(onDecision).toHaveBeenCalledTimes(1), { timeout: 5_000 });
|
|
293
331
|
expect(session.versions[0].decision?.action).toBe("deny");
|
|
294
332
|
});
|
|
295
333
|
|
|
@@ -375,7 +413,7 @@ describe("startSpecServer", () => {
|
|
|
375
413
|
|
|
376
414
|
describe("review server lifecycle", () => {
|
|
377
415
|
it("walks to the next free port so two reviews can be open at once", async () => {
|
|
378
|
-
const portStart =
|
|
416
|
+
const portStart = takePort();
|
|
379
417
|
const first = await serve(makeSession("# first"), { portStart });
|
|
380
418
|
const second = await serve(makeSession("# second"), { portStart });
|
|
381
419
|
try {
|
|
@@ -414,6 +452,26 @@ describe("review server lifecycle", () => {
|
|
|
414
452
|
});
|
|
415
453
|
});
|
|
416
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
|
+
|
|
417
475
|
it("closes idempotently", async () => {
|
|
418
476
|
const server = await serve(makeSession());
|
|
419
477
|
await server.close();
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
* routes and payload.
|
|
17
17
|
*/
|
|
18
18
|
import { fileURLToPath } from "node:url";
|
|
19
|
-
import { blockLabel, type Block } from "
|
|
19
|
+
import { blockLabel, type Block } from "../review-page/blocks.js";
|
|
20
|
+
import { extractHeadings, type Heading } from "../review-page/headings.js";
|
|
20
21
|
import type { BlockStatus, DiffEntry } from "./diff.js";
|
|
21
22
|
import type { Annotation, BlockAnnotations } from "./feedback.js";
|
|
22
23
|
import {
|
|
@@ -28,7 +29,7 @@ import {
|
|
|
28
29
|
} from "./store.js";
|
|
29
30
|
import { bindHost, isWsl, urlHost } from "../../lib/opener.js";
|
|
30
31
|
import { startWebServer, type WebServerHandle } from "../../lib/web-review.js";
|
|
31
|
-
import { renderBlockHtml } from "
|
|
32
|
+
import { renderBlockHtml } from "../review-page/render.js";
|
|
32
33
|
|
|
33
34
|
export interface SpecStateItem {
|
|
34
35
|
status: BlockStatus;
|
|
@@ -41,6 +42,7 @@ export interface SpecStateItem {
|
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
export interface SpecStatePayload {
|
|
45
|
+
mode: "spec";
|
|
44
46
|
slug: string;
|
|
45
47
|
version: number;
|
|
46
48
|
totalVersions: number;
|
|
@@ -52,6 +54,8 @@ export interface SpecStatePayload {
|
|
|
52
54
|
decided: boolean;
|
|
53
55
|
/** Earlier revisions, newest first — the history drawer. */
|
|
54
56
|
history: Array<{ n: number; at: string; changed: number }>;
|
|
57
|
+
/** Outline entries over the revision being viewed (shared with talk mode). */
|
|
58
|
+
headings: Heading[];
|
|
55
59
|
}
|
|
56
60
|
|
|
57
61
|
/** Compose what the page renders: blocks of one revision, tagged with their diff status. */
|
|
@@ -88,6 +92,7 @@ export function buildSpecState(session: SpecSession, versionNumber?: number): Sp
|
|
|
88
92
|
}
|
|
89
93
|
|
|
90
94
|
return {
|
|
95
|
+
mode: "spec",
|
|
91
96
|
slug: session.slug,
|
|
92
97
|
version: version.n,
|
|
93
98
|
totalVersions: latestVersion(session).n,
|
|
@@ -104,6 +109,9 @@ export function buildSpecState(session: SpecSession, versionNumber?: number): Sp
|
|
|
104
109
|
changed: candidate.diff.filter((entry) => entry.status !== "unchanged").length,
|
|
105
110
|
}))
|
|
106
111
|
.sort((a, b) => b.n - a.n),
|
|
112
|
+
// Outline entries follow the revision being viewed, so "View a previous
|
|
113
|
+
// version" moves the table of contents with it.
|
|
114
|
+
headings: extractHeadings(version.blocks),
|
|
107
115
|
};
|
|
108
116
|
}
|
|
109
117
|
|
|
@@ -173,7 +181,7 @@ export function normalizeAnnotations(input: unknown): SpecAnnotations {
|
|
|
173
181
|
}
|
|
174
182
|
|
|
175
183
|
export async function startSpecServer(options: StartSpecServerOptions): Promise<SpecServerHandle> {
|
|
176
|
-
const assetsDir = options.assetsDir ?? fileURLToPath(new URL("
|
|
184
|
+
const assetsDir = options.assetsDir ?? fileURLToPath(new URL("../review-page/assets/", import.meta.url));
|
|
177
185
|
const render = options.render ?? renderBlockHtml;
|
|
178
186
|
const closeDelayMs = options.closeDelayMs ?? 1500;
|
|
179
187
|
let closing = false;
|
|
@@ -234,6 +242,16 @@ export async function startSpecServer(options: StartSpecServerOptions): Promise<
|
|
|
234
242
|
return true;
|
|
235
243
|
}
|
|
236
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
|
+
|
|
237
255
|
if (ctx.url.pathname === "/api/decide" && ctx.req.method === "POST") {
|
|
238
256
|
const body = (await ctx.readBody()) as { action?: unknown; version?: number };
|
|
239
257
|
const action =
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
writeFileSync,
|
|
23
23
|
} from "node:fs";
|
|
24
24
|
import { join } from "node:path";
|
|
25
|
-
import { parseBlocks, type Block } from "
|
|
25
|
+
import { parseBlocks, type Block } from "../review-page/blocks.js";
|
|
26
26
|
import { diffBlocks, type DiffEntry } from "./diff.js";
|
|
27
27
|
import type { Annotation, BlockAnnotations } from "./feedback.js";
|
|
28
28
|
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/ask-talk` wiring, with a real HTTP server.
|
|
3
|
+
*
|
|
4
|
+
* The pure reply/message tests cannot catch the dangerous part of this feature:
|
|
5
|
+
* which snapshot the still-open page is actually talking to after a new reply.
|
|
6
|
+
* These tests go through the registered command and its routes for that reason.
|
|
7
|
+
*/
|
|
8
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
9
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { registerTalk, TALK_COMMAND } from "./index.js";
|
|
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
|
+
|
|
27
|
+
type Handler = (event: unknown, ctx: ExtensionContext) => void;
|
|
28
|
+
|
|
29
|
+
interface Harness {
|
|
30
|
+
command: (args?: string) => Promise<void>;
|
|
31
|
+
ctx: ExtensionContext;
|
|
32
|
+
entries: unknown[];
|
|
33
|
+
setReply: (text: string) => void;
|
|
34
|
+
opened: ReturnType<typeof vi.fn>;
|
|
35
|
+
messages: ReturnType<typeof vi.fn>;
|
|
36
|
+
notify: ReturnType<typeof vi.fn>;
|
|
37
|
+
shutdown: () => void;
|
|
38
|
+
start: (sessionId?: string) => void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const cleanups: Array<() => void> = [];
|
|
42
|
+
|
|
43
|
+
afterEach(() => {
|
|
44
|
+
for (const cleanup of cleanups.splice(0)) cleanup();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
function assistant(text: string): object {
|
|
48
|
+
return {
|
|
49
|
+
id: `a-${Math.random().toString(36).slice(2)}`,
|
|
50
|
+
type: "message",
|
|
51
|
+
message: {
|
|
52
|
+
role: "assistant",
|
|
53
|
+
content: [{ type: "text", text }],
|
|
54
|
+
model: "test/model",
|
|
55
|
+
timestamp: 1_700_000_000_000,
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function harness(): Harness {
|
|
61
|
+
const commands = new Map<string, { handler: (args: string, ctx: ExtensionContext) => Promise<void> }>();
|
|
62
|
+
const handlers = new Map<string, Handler[]>();
|
|
63
|
+
const opened = vi.fn();
|
|
64
|
+
const messages = vi.fn();
|
|
65
|
+
const notify = vi.fn();
|
|
66
|
+
let entries: unknown[] = [];
|
|
67
|
+
const idle = true;
|
|
68
|
+
|
|
69
|
+
const pi = {
|
|
70
|
+
registerCommand: (name: string, definition: { handler: (args: string, ctx: ExtensionContext) => Promise<void> }) => {
|
|
71
|
+
commands.set(name, definition);
|
|
72
|
+
},
|
|
73
|
+
on: (event: string, handler: Handler) => {
|
|
74
|
+
handlers.set(event, [...(handlers.get(event) ?? []), handler]);
|
|
75
|
+
},
|
|
76
|
+
sendUserMessage: messages,
|
|
77
|
+
} as unknown as ExtensionAPI;
|
|
78
|
+
|
|
79
|
+
const ctx = {
|
|
80
|
+
isIdle: () => idle,
|
|
81
|
+
ui: { notify },
|
|
82
|
+
sessionManager: {
|
|
83
|
+
getSessionId: () => "session-one",
|
|
84
|
+
getSessionName: () => "Session Alpha",
|
|
85
|
+
getBranch: () => entries,
|
|
86
|
+
buildContextEntries: () => entries,
|
|
87
|
+
},
|
|
88
|
+
} as unknown as ExtensionContext;
|
|
89
|
+
|
|
90
|
+
const portStart = takePort();
|
|
91
|
+
registerTalk(pi, { openBrowser: opened, portStart, portAttempts: 20, closeDelayMs: 30 });
|
|
92
|
+
const definition = commands.get(TALK_COMMAND);
|
|
93
|
+
if (!definition) throw new Error("ask-talk was not registered");
|
|
94
|
+
|
|
95
|
+
const result: Harness = {
|
|
96
|
+
command: (args = "") => definition.handler(args, ctx),
|
|
97
|
+
ctx,
|
|
98
|
+
get entries() {
|
|
99
|
+
return entries;
|
|
100
|
+
},
|
|
101
|
+
setReply: (text) => {
|
|
102
|
+
entries = [
|
|
103
|
+
{ id: "u1", type: "message", message: { role: "user", content: [{ type: "text", text: "q" }] } },
|
|
104
|
+
assistant(text),
|
|
105
|
+
];
|
|
106
|
+
},
|
|
107
|
+
opened,
|
|
108
|
+
messages,
|
|
109
|
+
notify,
|
|
110
|
+
shutdown: () => {
|
|
111
|
+
for (const handler of handlers.get("session_shutdown") ?? []) handler({}, ctx);
|
|
112
|
+
},
|
|
113
|
+
start: (sessionId = "session-one") => {
|
|
114
|
+
(ctx.sessionManager as unknown as { getSessionId: () => string }).getSessionId = () => sessionId;
|
|
115
|
+
for (const handler of handlers.get("session_start") ?? []) handler({}, ctx);
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
result.setReply("## Alpha\n\nfirst reply");
|
|
119
|
+
cleanups.push(result.shutdown);
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Use loopback even on WSL, where the opener URL advertises the LAN address. */
|
|
124
|
+
function localUrl(url: string, path: string): string {
|
|
125
|
+
const parsed = new URL(url);
|
|
126
|
+
parsed.hostname = "127.0.0.1";
|
|
127
|
+
parsed.pathname = path;
|
|
128
|
+
return parsed.toString();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function state(url: string): Promise<{
|
|
132
|
+
title?: string;
|
|
133
|
+
items: Array<{ id: string; label: string }>;
|
|
134
|
+
notes: Record<string, string>;
|
|
135
|
+
draft: string;
|
|
136
|
+
sent: boolean;
|
|
137
|
+
}> {
|
|
138
|
+
const response = await fetch(localUrl(url, "/api/state"));
|
|
139
|
+
expect(response.status).toBe(200);
|
|
140
|
+
return (await response.json()) as Awaited<ReturnType<typeof state>>;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function post(url: string, path: string, body: unknown): Promise<Response> {
|
|
144
|
+
return fetch(localUrl(url, path), {
|
|
145
|
+
method: "POST",
|
|
146
|
+
headers: { "content-type": "application/json" },
|
|
147
|
+
body: JSON.stringify(body),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
describe("ask-talk command", () => {
|
|
152
|
+
it("refuses a running agent and a session with no reply", async () => {
|
|
153
|
+
const h = harness();
|
|
154
|
+
(h.ctx as unknown as { isIdle: () => boolean }).isIdle = () => false;
|
|
155
|
+
await h.command();
|
|
156
|
+
expect(h.opened).not.toHaveBeenCalled();
|
|
157
|
+
expect(h.notify.mock.calls.at(-1)?.[0]).toContain("still running");
|
|
158
|
+
|
|
159
|
+
(h.ctx as unknown as { isIdle: () => boolean }).isIdle = () => true;
|
|
160
|
+
h.entries.length = 0;
|
|
161
|
+
await h.command();
|
|
162
|
+
expect(h.opened).not.toHaveBeenCalled();
|
|
163
|
+
expect(h.notify.mock.calls.at(-1)?.[0]).toContain("no reply");
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("opens a snapshot, retains notes for the same reply, and closes with off", async () => {
|
|
167
|
+
const h = harness();
|
|
168
|
+
await h.command();
|
|
169
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
170
|
+
const initial = await state(url);
|
|
171
|
+
expect(initial.items.map((item) => item.label)).toEqual(["## Alpha", "first reply"]);
|
|
172
|
+
|
|
173
|
+
await post(url, "/api/notes", { notes: { [initial.items[1].id]: "rename" }, draft: "draft" });
|
|
174
|
+
await h.command();
|
|
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);
|
|
179
|
+
expect(await state(url)).toMatchObject({ notes: { [initial.items[1].id]: "rename" }, draft: "draft" });
|
|
180
|
+
|
|
181
|
+
await h.command("off");
|
|
182
|
+
expect((await fetch(localUrl(url, "/api/state")).catch(() => undefined))?.ok ?? false).toBe(false);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it("serves the NEW reply on the existing page and clears the old notes", async () => {
|
|
186
|
+
const h = harness();
|
|
187
|
+
await h.command();
|
|
188
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
189
|
+
const before = await state(url);
|
|
190
|
+
await post(url, "/api/notes", { notes: { [before.items[1].id]: "old note" }, draft: "old draft" });
|
|
191
|
+
|
|
192
|
+
h.setReply("## Beta\n\nsecond reply");
|
|
193
|
+
await h.command();
|
|
194
|
+
|
|
195
|
+
const after = await state(url);
|
|
196
|
+
expect(after.items.map((item) => item.label)).toEqual(["## Beta", "second reply"]);
|
|
197
|
+
expect(after.notes).toEqual({});
|
|
198
|
+
expect(after.draft).toBe("");
|
|
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"]);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it("sends notes for the CURRENT snapshot when Continue arrives", async () => {
|
|
239
|
+
const h = harness();
|
|
240
|
+
await h.command();
|
|
241
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
242
|
+
h.setReply("## Beta\n\nsecond reply");
|
|
243
|
+
await h.command();
|
|
244
|
+
const current = await state(url);
|
|
245
|
+
|
|
246
|
+
const response = await post(url, "/api/continue", {
|
|
247
|
+
notes: { [current.items[1].id]: "change this" },
|
|
248
|
+
message: "carry on",
|
|
249
|
+
});
|
|
250
|
+
expect(response.status).toBe(200);
|
|
251
|
+
expect(h.messages).toHaveBeenCalledTimes(1);
|
|
252
|
+
const message = h.messages.mock.calls[0]?.[0] as string;
|
|
253
|
+
expect(message).toContain("### Beta");
|
|
254
|
+
expect(message).toContain("> second reply");
|
|
255
|
+
expect(message).toContain("- change this");
|
|
256
|
+
expect(message).toContain("## Operator's message\n\ncarry on");
|
|
257
|
+
expect(message).not.toContain("first reply");
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it("rechecks context survival when Continue arrives, not only when the page opens", async () => {
|
|
261
|
+
const h = harness();
|
|
262
|
+
await h.command();
|
|
263
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
264
|
+
const current = await state(url);
|
|
265
|
+
(h.ctx.sessionManager as unknown as { buildContextEntries: () => unknown[] }).buildContextEntries = () => [];
|
|
266
|
+
const response = await post(url, "/api/continue", {
|
|
267
|
+
notes: { [current.items[1].id]: "still applies" },
|
|
268
|
+
message: "",
|
|
269
|
+
});
|
|
270
|
+
expect(response.status).toBe(200);
|
|
271
|
+
const message = h.messages.mock.calls[0]?.[0] as string;
|
|
272
|
+
expect(message).toContain("## Your last reply (full text)");
|
|
273
|
+
expect(message).toContain("## Alpha\n\nfirst reply");
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("drops the page when the session changes, but not on a duplicate start event", async () => {
|
|
277
|
+
const h = harness();
|
|
278
|
+
h.start();
|
|
279
|
+
await h.command();
|
|
280
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
281
|
+
h.start();
|
|
282
|
+
expect((await state(url)).sent).toBe(false);
|
|
283
|
+
h.start("session-two");
|
|
284
|
+
expect((await fetch(localUrl(url, "/api/state")).catch(() => undefined))?.ok ?? false).toBe(false);
|
|
285
|
+
});
|
|
286
|
+
});
|