Open History to see the last commit
1import * as path from "node:path";
2import * as os from "node:os";
3import { fileURLToPath } from "node:url";
4import { mkdtempSync, readFileSync, rmSync } from "node:fs";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { it } from "@effect/vitest";
8import { Effect, Stream } from "effect";
9import { describe, expect } from "vitest";
10
11import { AcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
12import type * as EffectAcpProtocol from "effect-acp/protocol";
13
14const __dirname = path.dirname(fileURLToPath(import.meta.url));
15const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
16const bunExe = "bun";
17
18describe("AcpSessionRuntime", () => {
19 it.effect("merges custom initialize client capabilities into the ACP handshake", () => {
20 const requestEvents: Array<AcpSessionRequestLogEvent> = [];
21 return Effect.gen(function* () {
22 const runtime = yield* AcpSessionRuntime;
23 yield* runtime.start();
24
25 const initializeStarted = requestEvents.find(
26 (event) => event.method === "initialize" && event.status === "started",
27 );
28 expect(initializeStarted?.payload).toMatchObject({
29 protocolVersion: 1,
30 clientCapabilities: {
31 fs: { readTextFile: false, writeTextFile: false },
32 terminal: false,
33 _meta: { parameterizedModelPicker: true },
34 },
35 });
36 }).pipe(
37 Effect.provide(
38 AcpSessionRuntime.layer({
39 spawn: {
40 command: bunExe,
41 args: [mockAgentPath],
42 },
43 cwd: process.cwd(),
44 clientCapabilities: {
45 _meta: {
46 parameterizedModelPicker: true,
47 },
48 },
49 clientInfo: { name: "t3-test", version: "0.0.0" },
50 authMethodId: "test",
51 requestLogger: (event) =>
52 Effect.sync(() => {
53 requestEvents.push(event);
54 }),
55 }),
56 ),
57 Effect.scoped,
58 Effect.provide(NodeServices.layer),
59 );
60 });
61
62 it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
63 Effect.gen(function* () {
64 const runtime = yield* AcpSessionRuntime;
65 const started = yield* runtime.start();
66
67 expect(started.initializeResult).toMatchObject({ protocolVersion: 1 });
68 expect(started.sessionId).toBe("mock-session-1");
69
70 const promptResult = yield* runtime.prompt({
71 prompt: [{ type: "text", text: "hi" }],
72 });
73 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
74
75 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
76 expect(notes).toHaveLength(4);
77 expect(notes.map((note) => note._tag)).toEqual([
78 "PlanUpdated",
79 "AssistantItemStarted",
80 "ContentDelta",
81 "AssistantItemCompleted",
82 ]);
83 const planUpdate = notes.find((note) => note._tag === "PlanUpdated");
84 expect(planUpdate?._tag).toBe("PlanUpdated");
85 if (planUpdate?._tag === "PlanUpdated") {
86 expect(planUpdate.payload.plan).toHaveLength(2);
87 }
88 const assistantStart = notes[1];
89 const assistantDelta = notes[2];
90 if (
91 assistantStart?._tag === "AssistantItemStarted" &&
92 assistantDelta?._tag === "ContentDelta"
93 ) {
94 expect(assistantDelta.itemId).toBe(assistantStart.itemId);
95 }
96 }).pipe(
97 Effect.provide(
98 AcpSessionRuntime.layer({
99 spawn: {
100 command: bunExe,
101 args: [mockAgentPath],
102 },
103 cwd: process.cwd(),
104 clientInfo: { name: "t3-test", version: "0.0.0" },
105 authMethodId: "test",
106 }),
107 ),
108 Effect.scoped,
109 Effect.provide(NodeServices.layer),
110 ),
111 );
112
113 it.effect("segments assistant text around ACP tool calls", () =>
114 Effect.gen(function* () {
115 const runtime = yield* AcpSessionRuntime;
116 yield* runtime.start();
117
118 const promptResult = yield* runtime.prompt({
119 prompt: [{ type: "text", text: "hi" }],
120 });
121 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
122
123 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 7)));
124 expect(notes.map((note) => note._tag)).toEqual([
125 "AssistantItemStarted",
126 "ContentDelta",
127 "AssistantItemCompleted",
128 "ToolCallUpdated",
129 "ToolCallUpdated",
130 "AssistantItemStarted",
131 "ContentDelta",
132 ]);
133
134 const firstStarted = notes[0];
135 const firstDelta = notes[1];
136 const firstCompleted = notes[2];
137 const secondStarted = notes[5];
138 const secondDelta = notes[6];
139 expect(firstStarted?._tag).toBe("AssistantItemStarted");
140 expect(firstCompleted?._tag).toBe("AssistantItemCompleted");
141 expect(secondStarted?._tag).toBe("AssistantItemStarted");
142 if (
143 firstStarted?._tag === "AssistantItemStarted" &&
144 firstDelta?._tag === "ContentDelta" &&
145 firstCompleted?._tag === "AssistantItemCompleted" &&
146 secondStarted?._tag === "AssistantItemStarted" &&
147 secondDelta?._tag === "ContentDelta"
148 ) {
149 expect(firstDelta.itemId).toBe(firstStarted.itemId);
150 expect(firstCompleted.itemId).toBe(firstStarted.itemId);
151 expect(secondStarted.itemId).not.toBe(firstStarted.itemId);
152 expect(secondDelta.itemId).toBe(secondStarted.itemId);
153 }
154 }).pipe(
155 Effect.provide(
156 AcpSessionRuntime.layer({
157 spawn: {
158 command: bunExe,
159 args: [mockAgentPath],
160 env: {
161 T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS: "1",
162 },
163 },
164 cwd: process.cwd(),
165 clientInfo: { name: "t3-test", version: "0.0.0" },
166 authMethodId: "test",
167 }),
168 ),
169 Effect.scoped,
170 Effect.provide(NodeServices.layer),
171 ),
172 );
173
174 it.effect("suppresses generic placeholder tool updates until completion", () =>
175 Effect.gen(function* () {
176 const runtime = yield* AcpSessionRuntime;
177 yield* runtime.start();
178
179 const promptResult = yield* runtime.prompt({
180 prompt: [{ type: "text", text: "hi" }],
181 });
182 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
183
184 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 1)));
185 expect(notes.map((note) => note._tag)).toEqual(["ToolCallUpdated"]);
186 const toolCall = notes[0];
187 expect(toolCall?._tag).toBe("ToolCallUpdated");
188 if (toolCall?._tag === "ToolCallUpdated") {
189 expect(toolCall.toolCall.status).toBe("completed");
190 expect(toolCall.toolCall.title).toBe("Read file");
191 }
192 }).pipe(
193 Effect.provide(
194 AcpSessionRuntime.layer({
195 spawn: {
196 command: bunExe,
197 args: [mockAgentPath],
198 env: {
199 T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1",
200 },
201 },
202 cwd: process.cwd(),
203 clientInfo: { name: "t3-test", version: "0.0.0" },
204 authMethodId: "test",
205 }),
206 ),
207 Effect.scoped,
208 Effect.provide(NodeServices.layer),
209 ),
210 );
211
212 it.effect("logs ACP requests from the shared runtime", () => {
213 const requestEvents: Array<AcpSessionRequestLogEvent> = [];
214 return Effect.gen(function* () {
215 const runtime = yield* AcpSessionRuntime;
216 yield* runtime.start();
217
218 yield* runtime.setModel("composer-2");
219 yield* runtime.prompt({
220 prompt: [{ type: "text", text: "hi" }],
221 });
222
223 expect(
224 requestEvents.some(
225 (event) => event.method === "session/set_config_option" && event.status === "started",
226 ),
227 ).toBe(true);
228 expect(
229 requestEvents.some(
230 (event) => event.method === "session/set_config_option" && event.status === "succeeded",
231 ),
232 ).toBe(true);
233 expect(
234 requestEvents.some(
235 (event) => event.method === "session/prompt" && event.status === "started",
236 ),
237 ).toBe(true);
238 expect(
239 requestEvents.some(
240 (event) => event.method === "session/prompt" && event.status === "succeeded",
241 ),
242 ).toBe(true);
243 }).pipe(
244 Effect.provide(
245 AcpSessionRuntime.layer({
246 authMethodId: "test",
247 spawn: {
248 command: bunExe,
249 args: [mockAgentPath],
250 },
251 cwd: process.cwd(),
252 clientInfo: { name: "t3-test", version: "0.0.0" },
253 requestLogger: (event) =>
254 Effect.sync(() => {
255 requestEvents.push(event);
256 }),
257 }),
258 ),
259 Effect.scoped,
260 Effect.provide(NodeServices.layer),
261 );
262 });
263
264 it.effect("skips no-op session config writes when the requested value is already active", () => {
265 const requestEvents: Array<AcpSessionRequestLogEvent> = [];
266 return Effect.gen(function* () {
267 const runtime = yield* AcpSessionRuntime;
268 yield* runtime.start();
269
270 yield* runtime.setConfigOption("model", "default");
271 yield* runtime.setMode("ask");
272
273 expect(
274 requestEvents.some(
275 (event) => event.method === "session/set_config_option" && event.status === "started",
276 ),
277 ).toBe(false);
278 }).pipe(
279 Effect.provide(
280 AcpSessionRuntime.layer({
281 authMethodId: "test",
282 spawn: {
283 command: bunExe,
284 args: [mockAgentPath],
285 },
286 cwd: process.cwd(),
287 clientInfo: { name: "t3-test", version: "0.0.0" },
288 requestLogger: (event) =>
289 Effect.sync(() => {
290 requestEvents.push(event);
291 }),
292 }),
293 ),
294 Effect.scoped,
295 Effect.provide(NodeServices.layer),
296 );
297 });
298
299 it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => {
300 const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
301 return Effect.gen(function* () {
302 const runtime = yield* AcpSessionRuntime;
303 yield* runtime.start();
304
305 yield* runtime.prompt({
306 prompt: [{ type: "text", text: "hi" }],
307 });
308
309 expect(
310 protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "raw"),
311 ).toBe(true);
312 expect(
313 protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "decoded"),
314 ).toBe(true);
315 expect(
316 protocolEvents.some((event) => event.direction === "incoming" && event.stage === "raw"),
317 ).toBe(true);
318 expect(
319 protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"),
320 ).toBe(true);
321 }).pipe(
322 Effect.provide(
323 AcpSessionRuntime.layer({
324 authMethodId: "test",
325 spawn: {
326 command: bunExe,
327 args: [mockAgentPath],
328 },
329 cwd: process.cwd(),
330 clientInfo: { name: "t3-test", version: "0.0.0" },
331 protocolLogging: {
332 logIncoming: true,
333 logOutgoing: true,
334 logger: (event) =>
335 Effect.sync(() => {
336 protocolEvents.push(event);
337 }),
338 },
339 }),
340 ),
341 Effect.scoped,
342 Effect.provide(NodeServices.layer),
343 );
344 });
345
346 it.effect("rejects invalid config option values before sending session/set_config_option", () => {
347 const tempDir = mkdtempSync(path.join(os.tmpdir(), "acp-runtime-"));
348 const requestLogPath = path.join(tempDir, "requests.ndjson");
349 return Effect.gen(function* () {
350 const runtime = yield* AcpSessionRuntime;
351 yield* runtime.start();
352
353 const error = yield* runtime.setModel("composer-2[fast=false]").pipe(Effect.flip);
354 expect(error._tag).toBe("AcpRequestError");
355 if (error._tag === "AcpRequestError") {
356 expect(error.code).toBe(-32602);
357 expect(error.message).toContain(
358 'Invalid value "composer-2[fast=false]" for session config option "model"',
359 );
360 expect(error.message).toContain("composer-2[fast=true]");
361 }
362
363 const recordedRequests = readFileSync(requestLogPath, "utf8")
364 .trim()
365 .split("\n")
366 .filter((line) => line.length > 0)
367 .map((line) => JSON.parse(line) as { method?: string; params?: { value?: unknown } });
368 expect(
369 recordedRequests.some(
370 (message) =>
371 message.method === "session/set_config_option" &&
372 message.params?.value === "composer-2[fast=false]",
373 ),
374 ).toBe(false);
375 }).pipe(
376 Effect.provide(
377 AcpSessionRuntime.layer({
378 authMethodId: "test",
379 spawn: {
380 command: bunExe,
381 args: [mockAgentPath],
382 env: {
383 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
384 },
385 },
386 cwd: process.cwd(),
387 clientInfo: { name: "t3-test", version: "0.0.0" },
388 }),
389 ),
390 Effect.scoped,
391 Effect.provide(NodeServices.layer),
392 Effect.ensuring(Effect.sync(() => rmSync(tempDir, { recursive: true, force: true }))),
393 );
394 });
395});