Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodePath from "node:path";
3import * as NodeOS from "node:os";
4import * as NodeURL from "node:url";
5import * as NodeFS from "node:fs";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as Option from "effect/Option";
12import * as TestClock from "effect/testing/TestClock";
13import * as Stream from "effect/Stream";
14import { describe, expect } from "vite-plus/test";
15
16import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
17import type * as EffectAcpProtocol from "effect-acp/protocol";
18
19const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
20const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
21const mockAgentCommand = "node";
22const mockAgentArgs = [mockAgentPath];
23
24describe("AcpSessionRuntime", () => {
25 it.effect("merges custom initialize client capabilities into the ACP handshake", () => {
26 const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
27 return Effect.gen(function* () {
28 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
29 yield* runtime.start();
30
31 const initializeStarted = requestEvents.find(
32 (event) => event.method === "initialize" && event.status === "started",
33 );
34 expect(initializeStarted?.payload).toMatchObject({
35 protocolVersion: 1,
36 clientCapabilities: {
37 fs: { readTextFile: false, writeTextFile: false },
38 terminal: false,
39 _meta: { parameterizedModelPicker: true },
40 },
41 });
42 }).pipe(
43 Effect.provide(
44 AcpSessionRuntime.layer({
45 spawn: {
46 command: mockAgentCommand,
47 args: mockAgentArgs,
48 },
49 cwd: process.cwd(),
50 clientCapabilities: {
51 _meta: {
52 parameterizedModelPicker: true,
53 },
54 },
55 clientInfo: { name: "t3-test", version: "0.0.0" },
56 authMethodId: "test",
57 requestLogger: (event) =>
58 Effect.sync(() => {
59 requestEvents.push(event);
60 }),
61 }),
62 ),
63 Effect.scoped,
64 Effect.provide(NodeServices.layer),
65 );
66 });
67
68 it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
69 Effect.gen(function* () {
70 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
71 const started = yield* runtime.start();
72
73 expect(started.initializeResult).toMatchObject({ protocolVersion: 1 });
74 expect(started.sessionId).toBe("mock-session-1");
75
76 const promptResult = yield* runtime.prompt({
77 prompt: [{ type: "text", text: "hi" }],
78 });
79 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
80
81 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
82 expect(notes).toHaveLength(4);
83 expect(notes.map((note) => note._tag)).toEqual([
84 "PlanUpdated",
85 "AssistantItemStarted",
86 "ContentDelta",
87 "AssistantItemCompleted",
88 ]);
89 const planUpdate = notes.find((note) => note._tag === "PlanUpdated");
90 expect(planUpdate?._tag).toBe("PlanUpdated");
91 if (planUpdate?._tag === "PlanUpdated") {
92 expect(planUpdate.payload.plan).toHaveLength(2);
93 }
94 const assistantStart = notes[1];
95 const assistantDelta = notes[2];
96 if (
97 assistantStart?._tag === "AssistantItemStarted" &&
98 assistantDelta?._tag === "ContentDelta"
99 ) {
100 expect(assistantDelta.itemId).toBe(assistantStart.itemId);
101 }
102 }).pipe(
103 Effect.provide(
104 AcpSessionRuntime.layer({
105 spawn: {
106 command: mockAgentCommand,
107 args: mockAgentArgs,
108 },
109 cwd: process.cwd(),
110 clientInfo: { name: "t3-test", version: "0.0.0" },
111 authMethodId: "test",
112 }),
113 ),
114 Effect.scoped,
115 Effect.provide(NodeServices.layer),
116 ),
117 );
118
119 it.effect("keeps assistant item IDs unique when a provider session restarts", () => {
120 const collectFirstAssistantItemId = Effect.gen(function* () {
121 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
122 const started = yield* runtime.start();
123 expect(started.sessionId).toBe("mock-session-1");
124
125 yield* runtime.prompt({
126 prompt: [{ type: "text", text: "hi" }],
127 });
128
129 const events = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
130 const assistantStart = events.find((event) => event._tag === "AssistantItemStarted");
131 expect(assistantStart?._tag).toBe("AssistantItemStarted");
132 return assistantStart?._tag === "AssistantItemStarted" ? assistantStart.itemId : "";
133 }).pipe(
134 Effect.provide(
135 AcpSessionRuntime.layer({
136 spawn: {
137 command: mockAgentCommand,
138 args: mockAgentArgs,
139 },
140 cwd: process.cwd(),
141 clientInfo: { name: "t3-test", version: "0.0.0" },
142 authMethodId: "test",
143 }),
144 ),
145 Effect.scoped,
146 );
147
148 return Effect.gen(function* () {
149 const beforeRestart = yield* collectFirstAssistantItemId;
150 const afterRestart = yield* collectFirstAssistantItemId;
151
152 expect(afterRestart).not.toBe(beforeRestart);
153 }).pipe(Effect.provide(NodeServices.layer));
154 });
155
156 it.effect("drops session updates emitted for a child ACP session", () =>
157 Effect.gen(function* () {
158 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
159 yield* runtime.start();
160
161 const promptResult = yield* runtime.prompt({
162 prompt: [{ type: "text", text: "hi" }],
163 });
164 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
165
166 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
167 expect(notes.map((note) => note._tag)).toEqual([
168 "AssistantItemStarted",
169 "ContentDelta",
170 "ContentDelta",
171 "AssistantItemCompleted",
172 ]);
173 expect(
174 notes
175 .filter((note) => note._tag === "ContentDelta")
176 .map((note) => note.text)
177 .join(""),
178 ).toBe("root before child root after child");
179 expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
180 }).pipe(
181 Effect.provide(
182 AcpSessionRuntime.layer({
183 spawn: {
184 command: mockAgentCommand,
185 args: mockAgentArgs,
186 env: {
187 T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
188 },
189 },
190 cwd: process.cwd(),
191 clientInfo: { name: "t3-test", version: "0.0.0" },
192 authMethodId: "test",
193 }),
194 ),
195 Effect.scoped,
196 Effect.provide(NodeServices.layer),
197 ),
198 );
199
200 it.effect("supports successive standard ACP prompts", () =>
201 Effect.gen(function* () {
202 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
203 yield* runtime.start();
204
205 const firstPromptResult = yield* runtime.prompt({
206 prompt: [{ type: "text", text: "first" }],
207 });
208 const secondPromptResult = yield* runtime.prompt({
209 prompt: [{ type: "text", text: "second" }],
210 });
211
212 expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" });
213 expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
214 }).pipe(
215 Effect.provide(
216 AcpSessionRuntime.layer({
217 spawn: {
218 command: mockAgentCommand,
219 args: mockAgentArgs,
220 },
221 cwd: process.cwd(),
222 clientInfo: { name: "t3-test", version: "0.0.0" },
223 authMethodId: "test",
224 }),
225 ),
226 Effect.scoped,
227 Effect.provide(NodeServices.layer),
228 ),
229 );
230
231 it.effect("releases a fully silent prompt when session/cancel is requested", () =>
232 Effect.gen(function* () {
233 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
234 yield* runtime.start();
235
236 const promptFiber = yield* runtime
237 .prompt({
238 prompt: [{ type: "text", text: "hang forever" }],
239 })
240 .pipe(Effect.forkChild({ startImmediately: true }));
241
242 yield* TestClock.adjust("500 millis");
243 yield* runtime.cancel;
244
245 const firstPromptResult = yield* Fiber.join(promptFiber);
246 expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
247
248 const secondPromptResult = yield* runtime.prompt({
249 prompt: [{ type: "text", text: "second" }],
250 });
251 expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
252 }).pipe(
253 Effect.provide(
254 AcpSessionRuntime.layer({
255 spawn: {
256 command: mockAgentCommand,
257 args: mockAgentArgs,
258 env: {
259 T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
260 },
261 },
262 cwd: process.cwd(),
263 clientInfo: { name: "t3-test", version: "0.0.0" },
264 authMethodId: "test",
265 }),
266 ),
267 Effect.scoped,
268 Effect.provide(NodeServices.layer),
269 ),
270 );
271
272 it.effect("segments assistant text around ACP tool calls", () =>
273 Effect.gen(function* () {
274 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
275 yield* runtime.start();
276
277 const promptResult = yield* runtime.prompt({
278 prompt: [{ type: "text", text: "hi" }],
279 });
280 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
281
282 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 7)));
283 expect(notes.map((note) => note._tag)).toEqual([
284 "AssistantItemStarted",
285 "ContentDelta",
286 "AssistantItemCompleted",
287 "ToolCallUpdated",
288 "ToolCallUpdated",
289 "AssistantItemStarted",
290 "ContentDelta",
291 ]);
292
293 const firstStarted = notes[0];
294 const firstDelta = notes[1];
295 const firstCompleted = notes[2];
296 const secondStarted = notes[5];
297 const secondDelta = notes[6];
298 expect(firstStarted?._tag).toBe("AssistantItemStarted");
299 expect(firstCompleted?._tag).toBe("AssistantItemCompleted");
300 expect(secondStarted?._tag).toBe("AssistantItemStarted");
301 if (
302 firstStarted?._tag === "AssistantItemStarted" &&
303 firstDelta?._tag === "ContentDelta" &&
304 firstCompleted?._tag === "AssistantItemCompleted" &&
305 secondStarted?._tag === "AssistantItemStarted" &&
306 secondDelta?._tag === "ContentDelta"
307 ) {
308 expect(firstDelta.itemId).toBe(firstStarted.itemId);
309 expect(firstCompleted.itemId).toBe(firstStarted.itemId);
310 expect(secondStarted.itemId).not.toBe(firstStarted.itemId);
311 expect(secondDelta.itemId).toBe(secondStarted.itemId);
312 }
313 }).pipe(
314 Effect.provide(
315 AcpSessionRuntime.layer({
316 spawn: {
317 command: mockAgentCommand,
318 args: mockAgentArgs,
319 env: {
320 T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS: "1",
321 },
322 },
323 cwd: process.cwd(),
324 clientInfo: { name: "t3-test", version: "0.0.0" },
325 authMethodId: "test",
326 }),
327 ),
328 Effect.scoped,
329 Effect.provide(NodeServices.layer),
330 ),
331 );
332
333 it.effect("emits status-only tool updates through completion", () =>
334 Effect.gen(function* () {
335 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
336 yield* runtime.start();
337
338 const promptResult = yield* runtime.prompt({
339 prompt: [{ type: "text", text: "hi" }],
340 });
341 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
342
343 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 3)));
344 expect(notes.map((note) => note._tag)).toEqual([
345 "ToolCallUpdated",
346 "ToolCallUpdated",
347 "ToolCallUpdated",
348 ]);
349 const toolCalls = notes.flatMap((note) =>
350 note._tag === "ToolCallUpdated" ? [note.toolCall] : [],
351 );
352 expect(toolCalls.map((toolCall) => toolCall.status)).toEqual([
353 "pending",
354 "inProgress",
355 "completed",
356 ]);
357 for (const toolCall of toolCalls) {
358 expect(toolCall.title).toBe("Read file");
359 }
360 }).pipe(
361 Effect.provide(
362 AcpSessionRuntime.layer({
363 spawn: {
364 command: mockAgentCommand,
365 args: mockAgentArgs,
366 env: {
367 T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1",
368 },
369 },
370 cwd: process.cwd(),
371 clientInfo: { name: "t3-test", version: "0.0.0" },
372 authMethodId: "test",
373 }),
374 ),
375 Effect.scoped,
376 Effect.provide(NodeServices.layer),
377 ),
378 );
379
380 it.effect("logs ACP requests from the shared runtime", () => {
381 const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
382 return Effect.gen(function* () {
383 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
384 yield* runtime.start();
385
386 yield* runtime.setModel("composer-2");
387 yield* runtime.prompt({
388 prompt: [{ type: "text", text: "hi" }],
389 });
390
391 expect(
392 requestEvents.some(
393 (event) => event.method === "session/set_config_option" && event.status === "started",
394 ),
395 ).toBe(true);
396 expect(
397 requestEvents.some(
398 (event) => event.method === "session/set_config_option" && event.status === "succeeded",
399 ),
400 ).toBe(true);
401 expect(
402 requestEvents.some(
403 (event) => event.method === "session/prompt" && event.status === "started",
404 ),
405 ).toBe(true);
406 expect(
407 requestEvents.some(
408 (event) => event.method === "session/prompt" && event.status === "succeeded",
409 ),
410 ).toBe(true);
411 }).pipe(
412 Effect.provide(
413 AcpSessionRuntime.layer({
414 authMethodId: "test",
415 spawn: {
416 command: mockAgentCommand,
417 args: mockAgentArgs,
418 },
419 cwd: process.cwd(),
420 clientInfo: { name: "t3-test", version: "0.0.0" },
421 requestLogger: (event) =>
422 Effect.sync(() => {
423 requestEvents.push(event);
424 }),
425 }),
426 ),
427 Effect.scoped,
428 Effect.provide(NodeServices.layer),
429 );
430 });
431
432 it.effect("skips no-op session config writes when the requested value is already active", () => {
433 const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
434 return Effect.gen(function* () {
435 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
436 yield* runtime.start();
437
438 yield* runtime.setConfigOption("model", "default");
439 yield* runtime.setMode("ask");
440
441 expect(
442 requestEvents.some(
443 (event) => event.method === "session/set_config_option" && event.status === "started",
444 ),
445 ).toBe(false);
446 }).pipe(
447 Effect.provide(
448 AcpSessionRuntime.layer({
449 authMethodId: "test",
450 spawn: {
451 command: mockAgentCommand,
452 args: mockAgentArgs,
453 },
454 cwd: process.cwd(),
455 clientInfo: { name: "t3-test", version: "0.0.0" },
456 requestLogger: (event) =>
457 Effect.sync(() => {
458 requestEvents.push(event);
459 }),
460 }),
461 ),
462 Effect.scoped,
463 Effect.provide(NodeServices.layer),
464 );
465 });
466
467 it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => {
468 const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
469 return Effect.gen(function* () {
470 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
471 yield* runtime.start();
472
473 yield* runtime.prompt({
474 prompt: [{ type: "text", text: "hi" }],
475 });
476
477 expect(
478 protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "raw"),
479 ).toBe(true);
480 expect(
481 protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "decoded"),
482 ).toBe(true);
483 expect(
484 protocolEvents.some((event) => event.direction === "incoming" && event.stage === "raw"),
485 ).toBe(true);
486 expect(
487 protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"),
488 ).toBe(true);
489 }).pipe(
490 Effect.provide(
491 AcpSessionRuntime.layer({
492 authMethodId: "test",
493 spawn: {
494 command: mockAgentCommand,
495 args: mockAgentArgs,
496 },
497 cwd: process.cwd(),
498 clientInfo: { name: "t3-test", version: "0.0.0" },
499 protocolLogging: {
500 logIncoming: true,
501 logOutgoing: true,
502 logger: (event) =>
503 Effect.sync(() => {
504 protocolEvents.push(event);
505 }),
506 },
507 }),
508 ),
509 Effect.scoped,
510 Effect.provide(NodeServices.layer),
511 );
512 });
513
514 it.effect("fails session startup when session/load returns an error", () =>
515 Effect.gen(function* () {
516 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
517 const error = yield* runtime.start().pipe(Effect.flip);
518
519 expect(error._tag).toBe("AcpRequestError");
520 }).pipe(
521 Effect.provide(
522 AcpSessionRuntime.layer({
523 authMethodId: "test",
524 spawn: {
525 command: mockAgentCommand,
526 args: mockAgentArgs,
527 env: {
528 T3_ACP_FAIL_LOAD_SESSION: "1",
529 },
530 },
531 cwd: process.cwd(),
532 resumeSessionId: "stale-session-id",
533 clientInfo: { name: "t3-test", version: "0.0.0" },
534 }),
535 ),
536 Effect.scoped,
537 Effect.provide(NodeServices.layer),
538 ),
539 );
540
541 it.effect("ignores session/update replay notifications during session/load", () =>
542 Effect.gen(function* () {
543 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
544 yield* runtime.start();
545
546 yield* runtime.prompt({
547 prompt: [{ type: "text", text: "hi" }],
548 });
549 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
550 expect(notes.map((note) => note._tag)).toEqual([
551 "PlanUpdated",
552 "AssistantItemStarted",
553 "ContentDelta",
554 "AssistantItemCompleted",
555 ]);
556 expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
557 }).pipe(
558 Effect.provide(
559 AcpSessionRuntime.layer({
560 authMethodId: "test",
561 spawn: {
562 command: mockAgentCommand,
563 args: mockAgentArgs,
564 env: {
565 T3_ACP_EMIT_LOAD_REPLAY: "1",
566 },
567 },
568 cwd: process.cwd(),
569 resumeSessionId: "mock-session-1",
570 clientInfo: { name: "t3-test", version: "0.0.0" },
571 }),
572 ),
573 Effect.scoped,
574 Effect.provide(NodeServices.layer),
575 ),
576 );
577
578 it.effect("completes session/load after replay becomes idle while its RPC stays pending", () =>
579 Effect.gen(function* () {
580 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
581 const started = yield* runtime.start().pipe(Effect.timeout("2 seconds"));
582
583 expect(started.sessionId).toBe("mock-session-1");
584 expect(started.sessionSetupResult._meta).toMatchObject({
585 t3SessionLoadReady: "replay_idle",
586 });
587
588 const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe(
589 Effect.timeoutOption("100 millis"),
590 );
591 expect(Option.isNone(unexpectedReplayEvent)).toBe(true);
592 }).pipe(
593 Effect.provide(
594 AcpSessionRuntime.layer({
595 authMethodId: "test",
596 spawn: {
597 command: mockAgentCommand,
598 args: mockAgentArgs,
599 env: {
600 T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
601 T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
602 },
603 },
604 cwd: process.cwd(),
605 resumeSessionId: "mock-session-1",
606 sessionLoadReplayIdleGap: "50 millis",
607 sessionLoadTimeout: "1 second",
608 clientInfo: { name: "t3-test", version: "0.0.0" },
609 }),
610 ),
611 Effect.scoped,
612 Effect.provide(NodeServices.layer),
613 TestClock.withLive,
614 ),
615 );
616
617 it.effect("rejects invalid config option values before sending session/set_config_option", () => {
618 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
619 const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
620 return Effect.gen(function* () {
621 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
622 yield* runtime.start();
623
624 const error = yield* runtime.setModel("composer-2[fast=false]").pipe(Effect.flip);
625 expect(error._tag).toBe("AcpRequestError");
626 if (error._tag === "AcpRequestError") {
627 expect(error.code).toBe(-32602);
628 expect(error.message).toContain(
629 'Invalid value "composer-2[fast=false]" for session config option "model"',
630 );
631 expect(error.message).toContain("composer-2[fast=true]");
632 }
633
634 const recordedRequests = NodeFS.readFileSync(requestLogPath, "utf8")
635 .trim()
636 .split("\n")
637 .filter((line) => line.length > 0)
638 .map((line) => JSON.parse(line) as { method?: string; params?: { value?: unknown } });
639 expect(
640 recordedRequests.some(
641 (message) =>
642 message.method === "session/set_config_option" &&
643 message.params?.value === "composer-2[fast=false]",
644 ),
645 ).toBe(false);
646 }).pipe(
647 Effect.provide(
648 AcpSessionRuntime.layer({
649 authMethodId: "test",
650 spawn: {
651 command: mockAgentCommand,
652 args: mockAgentArgs,
653 env: {
654 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
655 },
656 },
657 cwd: process.cwd(),
658 clientInfo: { name: "t3-test", version: "0.0.0" },
659 }),
660 ),
661 Effect.scoped,
662 Effect.provide(NodeServices.layer),
663 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
664 );
665 });
666});