@andares/pi-toolkits 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +24 -1
- package/README.zh-CN.md +23 -1
- package/package.json +5 -3
- package/src/features/review-page/assets/index-CrDwcsqI.css +1 -0
- package/src/features/review-page/assets/index-DYxi32gA.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 +2 -2
- 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.ts +1 -1
- package/src/features/spec/server.test.ts +16 -2
- package/src/features/spec/server.ts +11 -3
- package/src/features/spec/store.ts +1 -1
- package/src/features/talk/index.test.ts +230 -0
- package/src/features/talk/index.ts +241 -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 +247 -0
- package/src/features/talk/server.ts +211 -0
- package/src/index.ts +4 -0
- 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
|
@@ -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;
|
|
@@ -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,230 @@
|
|
|
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
|
+
type Handler = (event: unknown, ctx: ExtensionContext) => void;
|
|
13
|
+
|
|
14
|
+
interface Harness {
|
|
15
|
+
command: (args?: string) => Promise<void>;
|
|
16
|
+
ctx: ExtensionContext;
|
|
17
|
+
entries: unknown[];
|
|
18
|
+
setReply: (text: string) => void;
|
|
19
|
+
opened: ReturnType<typeof vi.fn>;
|
|
20
|
+
messages: ReturnType<typeof vi.fn>;
|
|
21
|
+
notify: ReturnType<typeof vi.fn>;
|
|
22
|
+
shutdown: () => void;
|
|
23
|
+
start: (sessionId?: string) => void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const cleanups: Array<() => void> = [];
|
|
27
|
+
|
|
28
|
+
afterEach(() => {
|
|
29
|
+
for (const cleanup of cleanups.splice(0)) cleanup();
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
function assistant(text: string): object {
|
|
33
|
+
return {
|
|
34
|
+
id: `a-${Math.random().toString(36).slice(2)}`,
|
|
35
|
+
type: "message",
|
|
36
|
+
message: {
|
|
37
|
+
role: "assistant",
|
|
38
|
+
content: [{ type: "text", text }],
|
|
39
|
+
model: "test/model",
|
|
40
|
+
timestamp: 1_700_000_000_000,
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function harness(): Harness {
|
|
46
|
+
const commands = new Map<string, { handler: (args: string, ctx: ExtensionContext) => Promise<void> }>();
|
|
47
|
+
const handlers = new Map<string, Handler[]>();
|
|
48
|
+
const opened = vi.fn();
|
|
49
|
+
const messages = vi.fn();
|
|
50
|
+
const notify = vi.fn();
|
|
51
|
+
let entries: unknown[] = [];
|
|
52
|
+
let idle = true;
|
|
53
|
+
|
|
54
|
+
const pi = {
|
|
55
|
+
registerCommand: (name: string, definition: { handler: (args: string, ctx: ExtensionContext) => Promise<void> }) => {
|
|
56
|
+
commands.set(name, definition);
|
|
57
|
+
},
|
|
58
|
+
on: (event: string, handler: Handler) => {
|
|
59
|
+
handlers.set(event, [...(handlers.get(event) ?? []), handler]);
|
|
60
|
+
},
|
|
61
|
+
sendUserMessage: messages,
|
|
62
|
+
} as unknown as ExtensionAPI;
|
|
63
|
+
|
|
64
|
+
const ctx = {
|
|
65
|
+
isIdle: () => idle,
|
|
66
|
+
ui: { notify },
|
|
67
|
+
sessionManager: {
|
|
68
|
+
getSessionId: () => "session-one",
|
|
69
|
+
getBranch: () => entries,
|
|
70
|
+
buildContextEntries: () => entries,
|
|
71
|
+
},
|
|
72
|
+
} as unknown as ExtensionContext;
|
|
73
|
+
|
|
74
|
+
const portStart = 48_000 + Math.floor(Math.random() * 1500);
|
|
75
|
+
registerTalk(pi, { openBrowser: opened, portStart, portAttempts: 20, closeDelayMs: 30 });
|
|
76
|
+
const definition = commands.get(TALK_COMMAND);
|
|
77
|
+
if (!definition) throw new Error("ask-talk was not registered");
|
|
78
|
+
|
|
79
|
+
const result: Harness = {
|
|
80
|
+
command: (args = "") => definition.handler(args, ctx),
|
|
81
|
+
ctx,
|
|
82
|
+
get entries() {
|
|
83
|
+
return entries;
|
|
84
|
+
},
|
|
85
|
+
setReply: (text) => {
|
|
86
|
+
entries = [
|
|
87
|
+
{ id: "u1", type: "message", message: { role: "user", content: [{ type: "text", text: "q" }] } },
|
|
88
|
+
assistant(text),
|
|
89
|
+
];
|
|
90
|
+
},
|
|
91
|
+
opened,
|
|
92
|
+
messages,
|
|
93
|
+
notify,
|
|
94
|
+
shutdown: () => {
|
|
95
|
+
for (const handler of handlers.get("session_shutdown") ?? []) handler({}, ctx);
|
|
96
|
+
},
|
|
97
|
+
start: (sessionId = "session-one") => {
|
|
98
|
+
(ctx.sessionManager as unknown as { getSessionId: () => string }).getSessionId = () => sessionId;
|
|
99
|
+
for (const handler of handlers.get("session_start") ?? []) handler({}, ctx);
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
result.setReply("## Alpha\n\nfirst reply");
|
|
103
|
+
cleanups.push(result.shutdown);
|
|
104
|
+
return result;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Use loopback even on WSL, where the opener URL advertises the LAN address. */
|
|
108
|
+
function localUrl(url: string, path: string): string {
|
|
109
|
+
const parsed = new URL(url);
|
|
110
|
+
parsed.hostname = "127.0.0.1";
|
|
111
|
+
parsed.pathname = path;
|
|
112
|
+
return parsed.toString();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function state(url: string): Promise<{
|
|
116
|
+
items: Array<{ id: string; label: string }>;
|
|
117
|
+
notes: Record<string, string>;
|
|
118
|
+
draft: string;
|
|
119
|
+
sent: boolean;
|
|
120
|
+
}> {
|
|
121
|
+
const response = await fetch(localUrl(url, "/api/state"));
|
|
122
|
+
expect(response.status).toBe(200);
|
|
123
|
+
return (await response.json()) as Awaited<ReturnType<typeof state>>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function post(url: string, path: string, body: unknown): Promise<Response> {
|
|
127
|
+
return fetch(localUrl(url, path), {
|
|
128
|
+
method: "POST",
|
|
129
|
+
headers: { "content-type": "application/json" },
|
|
130
|
+
body: JSON.stringify(body),
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
describe("ask-talk command", () => {
|
|
135
|
+
it("refuses a running agent and a session with no reply", async () => {
|
|
136
|
+
const h = harness();
|
|
137
|
+
(h.ctx as unknown as { isIdle: () => boolean }).isIdle = () => false;
|
|
138
|
+
await h.command();
|
|
139
|
+
expect(h.opened).not.toHaveBeenCalled();
|
|
140
|
+
expect(h.notify.mock.calls.at(-1)?.[0]).toContain("still running");
|
|
141
|
+
|
|
142
|
+
(h.ctx as unknown as { isIdle: () => boolean }).isIdle = () => true;
|
|
143
|
+
h.entries.length = 0;
|
|
144
|
+
await h.command();
|
|
145
|
+
expect(h.opened).not.toHaveBeenCalled();
|
|
146
|
+
expect(h.notify.mock.calls.at(-1)?.[0]).toContain("no reply");
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("opens a snapshot, retains notes for the same reply, and closes with off", async () => {
|
|
150
|
+
const h = harness();
|
|
151
|
+
await h.command();
|
|
152
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
153
|
+
const initial = await state(url);
|
|
154
|
+
expect(initial.items.map((item) => item.label)).toEqual(["## Alpha", "first reply"]);
|
|
155
|
+
|
|
156
|
+
await post(url, "/api/notes", { notes: { [initial.items[1].id]: "rename" }, draft: "draft" });
|
|
157
|
+
await h.command();
|
|
158
|
+
expect(h.opened).toHaveBeenCalledTimes(1);
|
|
159
|
+
expect(await state(url)).toMatchObject({ notes: { [initial.items[1].id]: "rename" }, draft: "draft" });
|
|
160
|
+
|
|
161
|
+
await h.command("off");
|
|
162
|
+
expect((await fetch(localUrl(url, "/api/state")).catch(() => undefined))?.ok ?? false).toBe(false);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("serves the NEW reply on the existing page and clears the old notes", async () => {
|
|
166
|
+
const h = harness();
|
|
167
|
+
await h.command();
|
|
168
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
169
|
+
const before = await state(url);
|
|
170
|
+
await post(url, "/api/notes", { notes: { [before.items[1].id]: "old note" }, draft: "old draft" });
|
|
171
|
+
|
|
172
|
+
h.setReply("## Beta\n\nsecond reply");
|
|
173
|
+
await h.command();
|
|
174
|
+
|
|
175
|
+
const after = await state(url);
|
|
176
|
+
expect(after.items.map((item) => item.label)).toEqual(["## Beta", "second reply"]);
|
|
177
|
+
expect(after.notes).toEqual({});
|
|
178
|
+
expect(after.draft).toBe("");
|
|
179
|
+
expect(h.opened).toHaveBeenCalledTimes(1);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it("sends notes for the CURRENT snapshot when Continue arrives", async () => {
|
|
183
|
+
const h = harness();
|
|
184
|
+
await h.command();
|
|
185
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
186
|
+
h.setReply("## Beta\n\nsecond reply");
|
|
187
|
+
await h.command();
|
|
188
|
+
const current = await state(url);
|
|
189
|
+
|
|
190
|
+
const response = await post(url, "/api/continue", {
|
|
191
|
+
notes: { [current.items[1].id]: "change this" },
|
|
192
|
+
message: "carry on",
|
|
193
|
+
});
|
|
194
|
+
expect(response.status).toBe(200);
|
|
195
|
+
expect(h.messages).toHaveBeenCalledTimes(1);
|
|
196
|
+
const message = h.messages.mock.calls[0]?.[0] as string;
|
|
197
|
+
expect(message).toContain("### Beta");
|
|
198
|
+
expect(message).toContain("> second reply");
|
|
199
|
+
expect(message).toContain("- change this");
|
|
200
|
+
expect(message).toContain("## Operator's message\n\ncarry on");
|
|
201
|
+
expect(message).not.toContain("first reply");
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it("rechecks context survival when Continue arrives, not only when the page opens", async () => {
|
|
205
|
+
const h = harness();
|
|
206
|
+
await h.command();
|
|
207
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
208
|
+
const current = await state(url);
|
|
209
|
+
(h.ctx.sessionManager as unknown as { buildContextEntries: () => unknown[] }).buildContextEntries = () => [];
|
|
210
|
+
const response = await post(url, "/api/continue", {
|
|
211
|
+
notes: { [current.items[1].id]: "still applies" },
|
|
212
|
+
message: "",
|
|
213
|
+
});
|
|
214
|
+
expect(response.status).toBe(200);
|
|
215
|
+
const message = h.messages.mock.calls[0]?.[0] as string;
|
|
216
|
+
expect(message).toContain("## Your last reply (full text)");
|
|
217
|
+
expect(message).toContain("## Alpha\n\nfirst reply");
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("drops the page when the session changes, but not on a duplicate start event", async () => {
|
|
221
|
+
const h = harness();
|
|
222
|
+
h.start();
|
|
223
|
+
await h.command();
|
|
224
|
+
const url = h.opened.mock.calls[0]?.[0] as string;
|
|
225
|
+
h.start();
|
|
226
|
+
expect((await state(url)).sent).toBe(false);
|
|
227
|
+
h.start("session-two");
|
|
228
|
+
expect((await fetch(localUrl(url, "/api/state")).catch(() => undefined))?.ok ?? false).toBe(false);
|
|
229
|
+
});
|
|
230
|
+
});
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/ask-talk` — annotate the agent's last reply in the browser.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately NOT a phase: it registers no tool, changes no tool set, touches no
|
|
5
|
+
* permission mode and adds nothing to the system prompt, so it costs nothing
|
|
6
|
+
* until the operator types it, and it works inside `/ask`, `/ask-spec` and
|
|
7
|
+
* `/ask-uat` alike.
|
|
8
|
+
*
|
|
9
|
+
* The page is a snapshot. Running the command again refreshes it: same reply ⇒
|
|
10
|
+
* notes and draft survive, different reply ⇒ they are cleared (the block ids are
|
|
11
|
+
* content hashes, so a new reply means new ids and every note would be orphaned).
|
|
12
|
+
*/
|
|
13
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { openInBrowser } from "../../lib/opener.js";
|
|
15
|
+
import { parseBlocks } from "../review-page/blocks.js";
|
|
16
|
+
import { extractHeadings } from "../review-page/headings.js";
|
|
17
|
+
import { buildReplyMessage, type TalkNote } from "./message.js";
|
|
18
|
+
import { extractLastReply } from "./reply.js";
|
|
19
|
+
import { startTalkServer, type TalkServerHandle, type TalkSession } from "./server.js";
|
|
20
|
+
|
|
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;
|
|
24
|
+
|
|
25
|
+
export interface TalkOptions {
|
|
26
|
+
openBrowser?: (url: string) => unknown;
|
|
27
|
+
portStart?: number;
|
|
28
|
+
portAttempts?: number;
|
|
29
|
+
closeDelayMs?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function sessionIdOf(ctx: ExtensionContext): string {
|
|
33
|
+
try {
|
|
34
|
+
return ctx.sessionManager.getSessionId();
|
|
35
|
+
} catch {
|
|
36
|
+
return `pid-${process.pid}`;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Notes as an ordered list, for the message builder. */
|
|
41
|
+
function noteList(notes: Record<string, string>): TalkNote[] {
|
|
42
|
+
return Object.entries(notes).map(([blockId, text]) => ({ blockId, text }));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function registerTalk(pi: ExtensionAPI, options: TalkOptions = {}): void {
|
|
46
|
+
const open = options.openBrowser ?? openInBrowser;
|
|
47
|
+
|
|
48
|
+
let session: TalkSession | undefined;
|
|
49
|
+
let server: TalkServerHandle | undefined;
|
|
50
|
+
let talkSessionId: string | undefined;
|
|
51
|
+
let ctxRef: ExtensionContext | undefined;
|
|
52
|
+
|
|
53
|
+
function closeServer(): void {
|
|
54
|
+
if (!server) return;
|
|
55
|
+
const closing = server;
|
|
56
|
+
server = undefined;
|
|
57
|
+
void closing.close();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Start (or restart) a server for this snapshot, with one consistent error path. */
|
|
61
|
+
async function openFresh(current: TalkSession, ctx: ExtensionContext): Promise<void> {
|
|
62
|
+
closeServer();
|
|
63
|
+
try {
|
|
64
|
+
const handle = await startServer(current);
|
|
65
|
+
server = handle;
|
|
66
|
+
open(handle.url);
|
|
67
|
+
ctx.ui.notify(`ask-talk: review open at ${handle.url}`, "info");
|
|
68
|
+
} catch (error) {
|
|
69
|
+
ctx.ui.notify(
|
|
70
|
+
`ask-talk: cannot start the review server — ${error instanceof Error ? error.message : String(error)}`,
|
|
71
|
+
"warning",
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Whether the annotated reply is still in the model's active context.
|
|
78
|
+
*
|
|
79
|
+
* A compaction can summarize away the very message being annotated; the
|
|
80
|
+
* message builder then repeats the reply once, because the quotes would
|
|
81
|
+
* otherwise point at text the model cannot see.
|
|
82
|
+
*/
|
|
83
|
+
function replyInContext(ctx: ExtensionContext, entryId: string): boolean {
|
|
84
|
+
if (entryId === "") return true;
|
|
85
|
+
try {
|
|
86
|
+
const entries = ctx.sessionManager.buildContextEntries() as Array<{ id?: unknown }>;
|
|
87
|
+
return entries.some((entry) => entry.id === entryId);
|
|
88
|
+
} catch {
|
|
89
|
+
// Unknown shape on an older host: assume context is intact rather than
|
|
90
|
+
// paying for a full re-send of the reply on every Continue.
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function startServer(current: TalkSession): Promise<TalkServerHandle> {
|
|
96
|
+
return startTalkServer({
|
|
97
|
+
session: current,
|
|
98
|
+
portStart: options.portStart ?? PORT_START,
|
|
99
|
+
portAttempts: options.portAttempts,
|
|
100
|
+
closeDelayMs: options.closeDelayMs,
|
|
101
|
+
onContinue: ({ notes, message }) => {
|
|
102
|
+
// off / shutdown / a session switch invalidates the snapshot at once;
|
|
103
|
+
// an already in-flight HTTP request must not leak into the next session.
|
|
104
|
+
if (session !== current) return;
|
|
105
|
+
// The operator may have started another run (and a compaction) while the
|
|
106
|
+
// page was open. Context survival is a property of Continue time, not of
|
|
107
|
+
// the moment the page was opened.
|
|
108
|
+
current.inContext = ctxRef ? replyInContext(ctxRef, current.entryId) : current.inContext;
|
|
109
|
+
const text = buildReplyMessage({
|
|
110
|
+
blocks: current.blocks,
|
|
111
|
+
notes: noteList(notes),
|
|
112
|
+
message,
|
|
113
|
+
inContext: current.inContext,
|
|
114
|
+
replyText: current.text,
|
|
115
|
+
});
|
|
116
|
+
if (text.trim() === "") return;
|
|
117
|
+
pi.sendUserMessage(text);
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const command = {
|
|
123
|
+
description:
|
|
124
|
+
"Annotate the agent's last reply in the browser: block notes plus a message, sent back as one short message. `off` closes the page.",
|
|
125
|
+
handler: async (args: string, ctx: ExtensionContext) => {
|
|
126
|
+
const arg = args.trim();
|
|
127
|
+
ctxRef = ctx;
|
|
128
|
+
|
|
129
|
+
if (arg === "off") {
|
|
130
|
+
if (!session && !server) {
|
|
131
|
+
ctx.ui.notify("ask-talk: nothing open.", "info");
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
closeServer();
|
|
135
|
+
session = undefined;
|
|
136
|
+
ctx.ui.notify("ask-talk: closed.", "info");
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (arg !== "") {
|
|
141
|
+
ctx.ui.notify("ask-talk: takes no arguments (use `off` to close the page).", "warning");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// The host persists an assistant message on `message_end`, so while a run
|
|
146
|
+
// is in flight the branch still ends with the PREVIOUS reply. Showing it
|
|
147
|
+
// would be silently wrong; say so instead.
|
|
148
|
+
if (!ctx.isIdle()) {
|
|
149
|
+
ctx.ui.notify(
|
|
150
|
+
"ask-talk: the agent is still running — finish or abort first, then run /ask-talk.",
|
|
151
|
+
"warning",
|
|
152
|
+
);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
let entries: unknown[] = [];
|
|
157
|
+
try {
|
|
158
|
+
entries = ctx.sessionManager.getBranch() as unknown[];
|
|
159
|
+
} catch {
|
|
160
|
+
entries = [];
|
|
161
|
+
}
|
|
162
|
+
const reply = extractLastReply(entries);
|
|
163
|
+
if (!reply) {
|
|
164
|
+
ctx.ui.notify(
|
|
165
|
+
"ask-talk: no reply to annotate yet — send a prompt and wait for the answer.",
|
|
166
|
+
"warning",
|
|
167
|
+
);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const inContext = replyInContext(ctx, reply.entryId);
|
|
172
|
+
const sameReply =
|
|
173
|
+
session !== undefined && !session.sent && session.fingerprint === reply.fingerprint;
|
|
174
|
+
|
|
175
|
+
if (sameReply && session) {
|
|
176
|
+
session.inContext = inContext;
|
|
177
|
+
if (server?.active() !== true) {
|
|
178
|
+
await openFresh(session, ctx);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
// Nothing about the snapshot changed. Re-fetching here would overwrite
|
|
182
|
+
// keystrokes still inside the page's save debounce window.
|
|
183
|
+
ctx.ui.notify(`ask-talk: already showing this reply — ${server.url}`, "info");
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const blocks = parseBlocks(reply.text);
|
|
188
|
+
const next: TalkSession = {
|
|
189
|
+
text: reply.text,
|
|
190
|
+
blocks,
|
|
191
|
+
headings: extractHeadings(blocks),
|
|
192
|
+
entryId: reply.entryId,
|
|
193
|
+
model: reply.model,
|
|
194
|
+
at: reply.at,
|
|
195
|
+
fingerprint: reply.fingerprint,
|
|
196
|
+
notes: {},
|
|
197
|
+
draft: "",
|
|
198
|
+
sent: false,
|
|
199
|
+
inContext,
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const previous = session;
|
|
203
|
+
const replaced = previous !== undefined && previous.fingerprint !== reply.fingerprint;
|
|
204
|
+
talkSessionId = sessionIdOf(ctx);
|
|
205
|
+
|
|
206
|
+
if (previous && server?.active()) {
|
|
207
|
+
// The routes and the Continue callback both close over the object passed
|
|
208
|
+
// to startTalkServer. Replace its CONTENTS, not just the `session`
|
|
209
|
+
// variable, or a refresh would serve and submit the previous reply.
|
|
210
|
+
Object.assign(previous, next);
|
|
211
|
+
session = previous;
|
|
212
|
+
server.broadcast("refresh", {});
|
|
213
|
+
ctx.ui.notify(
|
|
214
|
+
`ask-talk: review refreshed${replaced ? " (notes cleared — this is a new reply)" : ""} — ${server.url}`,
|
|
215
|
+
"info",
|
|
216
|
+
);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
session = next;
|
|
221
|
+
await openFresh(next, ctx);
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
pi.registerCommand(TALK_COMMAND, command);
|
|
226
|
+
|
|
227
|
+
pi.on("session_shutdown", () => {
|
|
228
|
+
closeServer();
|
|
229
|
+
session = undefined;
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
pi.on("session_start", (_event, ctx) => {
|
|
233
|
+
const nextSessionId = sessionIdOf(ctx);
|
|
234
|
+
ctxRef = ctx;
|
|
235
|
+
if (nextSessionId === talkSessionId) return;
|
|
236
|
+
// A different session must not keep a page bound to the old reply.
|
|
237
|
+
talkSessionId = undefined;
|
|
238
|
+
session = undefined;
|
|
239
|
+
closeServer();
|
|
240
|
+
});
|
|
241
|
+
}
|