Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeReadline from "node:readline";
5import * as NodeURL from "node:url";
6
7import { describe, expect, it } from "@effect/vitest";
8
9import { parseReplayTurns, SCENARIOS, streamChunks } from "./dev-replay-agent.ts";
10
11interface AgentMessage {
12 readonly id?: number;
13 readonly method?: string;
14 readonly params?: {
15 readonly update?: {
16 readonly sessionUpdate?: string;
17 readonly toolCallId?: string;
18 readonly status?: string;
19 readonly rawInput?: { readonly path?: string };
20 };
21 };
22 readonly result?: { readonly sessionId?: string; readonly stopReason?: string };
23 readonly error?: { readonly code?: number };
24}
25
26/**
27 * Runs the agent over stdio and returns every message it sent until each request is answered.
28 * Permission requests get `permissionResult`.
29 */
30async function talkToAgent(
31 requests: ReadonlyArray<(sessionId: string) => object>,
32 permissionResult: object = { outcome: { outcome: "selected", optionId: "allow-once" } },
33) {
34 const agent = NodeChildProcess.spawn(
35 process.execPath,
36 [NodeURL.fileURLToPath(new URL("./dev-replay-agent.ts", import.meta.url))],
37 { stdio: ["pipe", "pipe", "inherit"] },
38 );
39 const lines = NodeReadline.createInterface({ input: agent.stdout })[Symbol.asyncIterator]();
40 const received: Array<AgentMessage> = [];
41 let sessionId = "";
42 try {
43 for (const [index, request] of requests.entries()) {
44 agent.stdin.write(
45 `${JSON.stringify({ jsonrpc: "2.0", id: index + 1, ...request(sessionId) })}\n`,
46 );
47 for (;;) {
48 const message = JSON.parse((await lines.next()).value as string) as AgentMessage;
49 received.push(message);
50 if (message.method === "session/request_permission") {
51 const answer = { jsonrpc: "2.0", id: message.id, result: permissionResult };
52 agent.stdin.write(`${JSON.stringify(answer)}\n`);
53 }
54 if (message.id !== index + 1 || message.method !== undefined) continue;
55 sessionId = message.result?.sessionId ?? sessionId;
56 break;
57 }
58 }
59 } finally {
60 agent.kill();
61 }
62 return { sessionId, received };
63}
64
65describe("dev replay agent", () => {
66 it("keeps sessions and tool ids unique across processes and reloads", async () => {
67 const prompt = (sessionId: string) => ({ method: "session/prompt", params: { sessionId } });
68 const selectTodoList = (sessionId: string) => ({
69 method: "session/set_model",
70 params: { sessionId, modelId: "todo-list" },
71 });
72 const run = () =>
73 talkToAgent([
74 () => ({ method: "session/new", params: { cwd: "/tmp" } }),
75 selectTodoList,
76 prompt,
77 prompt,
78 ]);
79 const [first, second] = await Promise.all([run(), run()]);
80 expect(first.sessionId).not.toBe(second.sessionId);
81 // A server restart loads the same session in a new agent process.
82 const reloaded = await talkToAgent([
83 () => ({ method: "session/load", params: { sessionId: first.sessionId, cwd: "/tmp" } }),
84 () => selectTodoList(first.sessionId),
85 () => prompt(first.sessionId),
86 ]);
87 const toolCallIds = [...first.received, ...reloaded.received].flatMap((message) =>
88 message.params?.update?.toolCallId === undefined ? [] : [message.params.update.toolCallId],
89 );
90 expect(new Set(toolCallIds).size).toBe(6);
91 });
92
93 it.each(SCENARIOS)("$id plays a turn without session setup frames", ({ file }) => {
94 const turns = parseReplayTurns(NodeFS.readFileSync(new URL(file, import.meta.url), "utf8"));
95 expect(turns.length).toBeGreaterThan(0);
96 const updates = turns.flatMap((turn) =>
97 turn.frames.flatMap(({ frame }) =>
98 frame.method === "session/update"
99 ? [(frame.params as { update: { sessionUpdate: string } }).update.sessionUpdate]
100 : [],
101 ),
102 );
103 expect(updates).toContain("agent_message_chunk");
104 expect(updates).not.toContain("available_commands_update");
105 });
106
107 it("keeps permission requests and the recorded stop reason in order", () => {
108 const turns = parseReplayTurns(
109 NodeFS.readFileSync(new URL(SCENARIOS[0].file, import.meta.url), "utf8"),
110 );
111 const methods = turns[0]!.frames.map(({ frame }) => frame.method);
112 expect(methods).toContain("session/request_permission");
113 expect(turns[0]!.stopReason).toBe("end_turn");
114 });
115
116 it("inserts a workspace path with dollar sequences literally", async () => {
117 const { received } = await talkToAgent([
118 () => ({ method: "session/new", params: { cwd: "/tmp/scout$&dir" } }),
119 (sessionId) => ({ method: "session/prompt", params: { sessionId } }),
120 ]);
121 const paths = received.flatMap((message) => message.params?.update?.rawInput?.path ?? []);
122 expect(paths[0]).toBe("/tmp/scout$&dir/package.json");
123 });
124
125 it("rejects an unknown scenario instead of playing another one", async () => {
126 const { received } = await talkToAgent([
127 () => ({ method: "session/new", params: { cwd: "/tmp" } }),
128 (sessionId) => ({ method: "session/set_model", params: { sessionId, modelId: "typo" } }),
129 ]);
130 expect(received.at(-1)?.error?.code).toBe(-32602);
131 });
132
133 it("ends the turn with a failed tool call when the user rejects an approval", async () => {
134 const { received } = await talkToAgent(
135 [
136 () => ({ method: "session/new", params: { cwd: "/tmp" } }),
137 (sessionId) => ({ method: "session/prompt", params: { sessionId } }),
138 ],
139 { outcome: { outcome: "selected", optionId: "reject-once" } },
140 );
141 const updates = received.flatMap((message) =>
142 message.params?.update === undefined ? [] : [message.params.update],
143 );
144 expect(updates.at(-1)).toMatchObject({ sessionUpdate: "tool_call_update", status: "failed" });
145 expect(updates.some((update) => update.toolCallId?.endsWith("showcase-test"))).toBe(false);
146 expect(received.at(-1)?.result?.stopReason).toBe("end_turn");
147 });
148
149 it("ends the turn as cancelled when the client cancels an open approval", async () => {
150 const { received } = await talkToAgent(
151 [
152 () => ({ method: "session/new", params: { cwd: "/tmp" } }),
153 (sessionId) => ({ method: "session/prompt", params: { sessionId } }),
154 ],
155 { outcome: { outcome: "cancelled" } },
156 );
157 const requestIndex = received.findIndex(
158 (message) => message.method === "session/request_permission",
159 );
160 expect(received.slice(requestIndex + 1).some((message) => message.method !== undefined)).toBe(
161 false,
162 );
163 expect(received.at(-1)?.result?.stopReason).toBe("cancelled");
164 });
165
166 it("leaves frames after a prompt's response out of that turn", () => {
167 const update = (text: string) => ({
168 type: "emit_inbound",
169 frame: {
170 kind: "notification",
171 method: "session/update",
172 params: {
173 update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
174 },
175 },
176 });
177 const transcript = [
178 { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
179 update("root"),
180 { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: {} } },
181 update("background"),
182 ]
183 .map((entry) => JSON.stringify(entry))
184 .join("\n");
185 const turns = parseReplayTurns(transcript);
186 expect(turns).toHaveLength(1);
187 expect(turns[0]!.frames).toHaveLength(1);
188 });
189
190 it("streams text in chunks that rebuild the original", () => {
191 const text = "One two three four five\n\n```ts\nx\n```";
192 const chunks = streamChunks(text);
193 expect(chunks.length).toBeGreaterThan(1);
194 expect(chunks.join("")).toBe(text);
195 });
196});