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 Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Fiber from "effect/Fiber";
13import * as Option from "effect/Option";
14import * as Scope from "effect/Scope";
15import * as TestClock from "effect/testing/TestClock";
16import * as Stream from "effect/Stream";
17import { describe, expect } from "vite-plus/test";
18
19import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
20import type * as EffectAcpProtocol from "effect-acp/protocol";
21import * as EffectAcpErrors from "effect-acp/errors";
22
23const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
24const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
25const mockAgentCommand = "node";
26const mockAgentArgs = [mockAgentPath];
27const mockRuntimeOptions = {
28 spawn: { command: mockAgentCommand, args: mockAgentArgs },
29 cwd: process.cwd(),
30 clientInfo: { name: "t3-test", version: "0.0.0" },
31 authMethodId: "test",
32} satisfies AcpSessionRuntime.AcpSessionRuntimeOptions;
33
34describe("AcpSessionRuntime", () => {
35 for (const setupMethod of ["session/new", "session/resume"] as const) {
36 it.effect(`buffers root metadata while ${setupMethod} startup is still pending`, () =>
37 Effect.gen(function* () {
38 const setupReplied = yield* Deferred.make<void>();
39 const allowStartup = yield* Deferred.make<void>();
40 const events: Array<AcpSessionRuntime.AcpSessionRuntimeEvent> = [];
41 const runtime = yield* AcpSessionRuntime.make({
42 ...mockRuntimeOptions,
43 ...(setupMethod === "session/resume"
44 ? { resumeSessionId: "mock-session-1", resumeMethod: "resume" as const }
45 : {}),
46 requestLogger: (event) =>
47 event.method === setupMethod && event.status === "succeeded"
48 ? Deferred.succeed(setupReplied, undefined).pipe(
49 Effect.andThen(Deferred.await(allowStartup)),
50 )
51 : Effect.void,
52 });
53 yield* runtime.getEvents().pipe(
54 Stream.runForEach((event) => {
55 if (event._tag === "EventStreamBarrier") {
56 return Deferred.succeed(event.acknowledge, undefined);
57 }
58 events.push(event);
59 return Effect.void;
60 }),
61 Effect.forkChild,
62 );
63 const startup = yield* runtime.start().pipe(Effect.forkChild);
64 yield* Deferred.await(setupReplied);
65 yield* runtime.request("_test/startup-metadata", {});
66 yield* Deferred.succeed(allowStartup, undefined);
67 yield* Fiber.join(startup);
68 yield* runtime.drainEvents;
69
70 expect(events.map((event) => event._tag)).toEqual([
71 "AvailableCommandsUpdated",
72 "ModeChanged",
73 "ConfigOptionsUpdated",
74 ]);
75 expect(events[0]).toMatchObject({
76 availableCommands: [{ name: "plan", description: "Native command" }],
77 });
78 expect(yield* runtime.getModeState).toMatchObject({ currentModeId: "code" });
79 expect(events[2]).toMatchObject({
80 configOptions: yield* runtime.getConfigOptions,
81 });
82 expect(
83 (yield* runtime.getConfigOptions).find((option) => option.category === "model"),
84 ).toMatchObject({ currentValue: "gpt-5.4" });
85 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
86 );
87 }
88
89 it.effect("publishes model changes returned by a config request and live notifications", () =>
90 Effect.gen(function* () {
91 const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions);
92 yield* runtime.start();
93 const updates = yield* Stream.toPull(
94 runtime.getEvents().pipe(Stream.filter((event) => event._tag === "ConfigOptionsUpdated")),
95 );
96 const selected = yield* runtime.setConfigOption("model", "composer-2");
97 expect((yield* updates)[0]?.configOptions).toEqual(selected.configOptions);
98 yield* runtime.request("_test/startup-metadata", {});
99 expect((yield* updates)[0]?.configOptions).toEqual(yield* runtime.getConfigOptions);
100 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
101 );
102
103 it.effect("awaits native resume instead of using the load replay idle fallback", () =>
104 Effect.gen(function* () {
105 const resumeStarted = yield* Deferred.make<void>();
106 const requestMethods: Array<string> = [];
107 const runtime = yield* AcpSessionRuntime.make({
108 ...mockRuntimeOptions,
109 spawn: {
110 ...mockRuntimeOptions.spawn,
111 env: { T3_ACP_WAIT_FOR_RESUME_RELEASE: "1" },
112 },
113 resumeSessionId: "mock-session-1",
114 resumeMethod: "resume",
115 sessionLoadReplayIdleGap: "1 second",
116 requestLogger: (event) =>
117 Effect.sync(() => {
118 if (event.status === "started") requestMethods.push(event.method);
119 }),
120 });
121 yield* runtime.handleSessionUpdate((notification) =>
122 notification.update.sessionUpdate === "user_message_chunk"
123 ? Deferred.succeed(resumeStarted, undefined).pipe(Effect.asVoid)
124 : Effect.void,
125 );
126 const startup = yield* runtime.start().pipe(Effect.forkChild);
127 yield* Deferred.await(resumeStarted);
128 yield* TestClock.adjust("3 seconds");
129 expect(startup.pollUnsafe()).toBeUndefined();
130 yield* runtime.request("_test/release-resume", {});
131 const started = yield* Fiber.join(startup);
132
133 expect(started.sessionSetupResult._meta).toEqual({ nativeResume: true });
134 expect(requestMethods).toContain("session/resume");
135 expect(requestMethods).not.toContain("session/load");
136 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
137 );
138
139 it.effect("waits for native cancellation and drains final updates before another prompt", () =>
140 Effect.gen(function* () {
141 const toolStarted = yield* Deferred.make<void>();
142 const cancelReceived = yield* Deferred.make<void>();
143 const events: Array<AcpSessionRuntime.AcpSessionRuntimeEvent> = [];
144 let promptRequests = 0;
145 const runtime = yield* AcpSessionRuntime.make({
146 ...mockRuntimeOptions,
147 spawn: {
148 ...mockRuntimeOptions.spawn,
149 env: { T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL: "1" },
150 },
151 cancelBehavior: "wait-for-prompt",
152 requestLogger: (event) =>
153 Effect.sync(() => {
154 if (event.method === "session/prompt" && event.status === "started")
155 promptRequests += 1;
156 }),
157 });
158 yield* runtime.getEvents().pipe(
159 Stream.runForEach((event) => {
160 if (event._tag === "EventStreamBarrier") {
161 return Deferred.succeed(event.acknowledge, undefined);
162 }
163 events.push(event);
164 if (event._tag === "ToolCallUpdated" && event.toolCall.status === "inProgress") {
165 return Deferred.succeed(toolStarted, undefined);
166 }
167 if (event._tag === "ThoughtDelta" && event.text === "native-cancel-received") {
168 return Deferred.succeed(cancelReceived, undefined);
169 }
170 return Effect.void;
171 }),
172 Effect.forkChild,
173 );
174 yield* runtime.start();
175 const prompt = yield* runtime
176 .prompt({
177 prompt: [{ type: "text", text: "first" }],
178 })
179 .pipe(Effect.forkChild);
180 yield* Deferred.await(toolStarted);
181 const cancellation = yield* runtime.cancel.pipe(Effect.forkChild);
182 yield* Deferred.await(cancelReceived);
183 const replacement = yield* runtime
184 .prompt({
185 prompt: [{ type: "text", text: "second" }],
186 })
187 .pipe(Effect.forkChild({ startImmediately: true }));
188
189 expect(prompt.pollUnsafe()).toBeUndefined();
190 expect(cancellation.pollUnsafe()).toBeUndefined();
191 expect(promptRequests).toBe(1);
192 yield* runtime.request("_test/finish-cancel", {});
193 yield* Fiber.join(cancellation);
194
195 expect(yield* Fiber.join(prompt)).toEqual({
196 stopReason: "cancelled",
197 _meta: { nativeCancel: true },
198 });
199 expect(
200 events.some(
201 (event) =>
202 event._tag === "ToolCallUpdated" &&
203 event.toolCall.status === "failed" &&
204 event.toolCall.detail === "Cancelled.",
205 ),
206 ).toBe(true);
207 const cancelledDelta = events.find(
208 (event) => event._tag === "ContentDelta" && event.text === "Request cancelled.",
209 );
210 expect(cancelledDelta?._tag).toBe("ContentDelta");
211 if (cancelledDelta?._tag === "ContentDelta") {
212 expect(
213 events.filter(
214 (event) =>
215 event._tag === "AssistantItemCompleted" && event.itemId === cancelledDelta.itemId,
216 ),
217 ).toHaveLength(1);
218 }
219 expect(yield* Fiber.join(replacement)).toMatchObject({ stopReason: "end_turn" });
220 expect(promptRequests).toBe(2);
221 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
222 );
223
224 it.effect("retires a process when native cancellation times out", () =>
225 Effect.gen(function* () {
226 const toolStarted = yield* Deferred.make<void>();
227 const cancelReceived = yield* Deferred.make<void>();
228 const runtime = yield* AcpSessionRuntime.make({
229 ...mockRuntimeOptions,
230 spawn: {
231 ...mockRuntimeOptions.spawn,
232 env: { T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL: "1" },
233 },
234 cancelBehavior: "wait-for-prompt",
235 cancelTimeout: "1 second",
236 });
237 yield* runtime.getEvents().pipe(
238 Stream.runForEach((event) => {
239 if (event._tag === "EventStreamBarrier") {
240 return Deferred.succeed(event.acknowledge, undefined);
241 }
242 if (event._tag === "ToolCallUpdated") {
243 return Deferred.succeed(toolStarted, undefined);
244 }
245 if (event._tag === "ThoughtDelta") {
246 return Deferred.succeed(cancelReceived, undefined);
247 }
248 return Effect.void;
249 }),
250 Effect.forkChild,
251 );
252 yield* runtime.start();
253 const prompt = yield* runtime
254 .prompt({
255 prompt: [{ type: "text", text: "first" }],
256 })
257 .pipe(Effect.forkChild);
258 yield* Deferred.await(toolStarted);
259 const cancellation = yield* runtime.cancel.pipe(Effect.forkChild);
260 yield* Deferred.await(cancelReceived);
261 yield* TestClock.adjust("2 seconds");
262
263 const error = yield* Fiber.join(cancellation).pipe(Effect.flip);
264 expect(error).toMatchObject({
265 _tag: "AcpTransportError",
266 method: "session/cancel",
267 });
268 expect(Exit.isFailure(yield* Fiber.await(prompt))).toBe(true);
269 expect(
270 yield* runtime
271 .prompt({
272 prompt: [{ type: "text", text: "must not run" }],
273 })
274 .pipe(Effect.flip),
275 ).toBe(error);
276 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
277 );
278
279 it.effect("reports an idle child exit and rejects later prompts", () =>
280 Effect.gen(function* () {
281 const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions);
282 yield* runtime.start();
283 yield* runtime.notify("_test/exit", {});
284 const events = yield* runtime.getEvents().pipe(Stream.take(1), Stream.runCollect);
285 const event = events[0];
286 expect(event).toMatchObject({ _tag: "ConnectionTerminated", error: { code: 19 } });
287 if (event?._tag !== "ConnectionTerminated") return;
288 expect(
289 yield* runtime
290 .prompt({
291 prompt: [{ type: "text", text: "must not run" }],
292 })
293 .pipe(Effect.flip),
294 ).toBe(event.error);
295 expect(yield* runtime.start().pipe(Effect.flip)).toBe(event.error);
296 expect(yield* runtime.initialize().pipe(Effect.flip)).toBe(event.error);
297 expect(
298 yield* runtime.request("_test/environment", {}).pipe(
299 Effect.match({
300 onFailure: (error) => error,
301 onSuccess: () => undefined,
302 }),
303 ),
304 ).toBe(event.error);
305 expect(yield* runtime.notify("_test/exit", {}).pipe(Effect.flip)).toBe(event.error);
306 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
307 );
308
309 it.effect("retires a native runtime when its prompt caller is interrupted", () =>
310 Effect.gen(function* () {
311 const dispatched = yield* Deferred.make<void>();
312 const runtime = yield* AcpSessionRuntime.make({
313 ...mockRuntimeOptions,
314 spawn: {
315 ...mockRuntimeOptions.spawn,
316 env: { T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL: "1" },
317 },
318 cancelBehavior: "wait-for-prompt",
319 });
320 yield* runtime.start();
321 const prompt = yield* runtime
322 .prompt(
323 {
324 prompt: [{ type: "text", text: "first" }],
325 },
326 { dispatched },
327 )
328 .pipe(Effect.forkChild);
329 yield* Deferred.await(dispatched);
330 yield* Fiber.interrupt(prompt);
331 const events = yield* runtime.getEvents().pipe(
332 Stream.filter((event) => event._tag === "ConnectionTerminated"),
333 Stream.take(1),
334 Stream.runCollect,
335 );
336 expect(events[0]).toMatchObject({
337 error: { _tag: "AcpTransportError", method: "session/prompt" },
338 });
339 expect(
340 yield* runtime
341 .prompt({
342 prompt: [{ type: "text", text: "must not run" }],
343 })
344 .pipe(Effect.flip),
345 ).toBe(events[0]?.error);
346 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
347 );
348
349 it.effect("fails a pending request when the stderr handler rejects the runtime", () =>
350 Effect.gen(function* () {
351 const failure = new EffectAcpErrors.AcpTransportError({
352 detail: "Sign in before continuing.",
353 cause: undefined,
354 });
355 const runtime = yield* AcpSessionRuntime.make({
356 ...mockRuntimeOptions,
357 spawn: { ...mockRuntimeOptions.spawn, env: { T3_ACP_FLOOD_STDERR: "1" } },
358 onStderr: () => Effect.fail(failure),
359 });
360 expect(yield* runtime.start().pipe(Effect.flip)).toBe(failure);
361 const events = yield* runtime.getEvents().pipe(
362 Stream.filter((event) => event._tag === "ConnectionTerminated"),
363 Stream.take(1),
364 Stream.runCollect,
365 );
366 expect(events[0]?.error).toBe(failure);
367 expect(yield* runtime.initialize().pipe(Effect.flip)).toBe(failure);
368 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
369 );
370
371 it.effect("drains large stderr output and keeps auth-sized logging chunks", () =>
372 Effect.gen(function* () {
373 const lengths: Array<number> = [];
374 for (const logStderr of [false, true]) {
375 yield* Effect.gen(function* () {
376 const runtime = yield* AcpSessionRuntime.make({
377 ...mockRuntimeOptions,
378 spawn: { ...mockRuntimeOptions.spawn, env: { T3_ACP_FLOOD_STDERR: "1" } },
379 ...(logStderr
380 ? {
381 onStderr: (text: string) =>
382 Effect.sync(() => {
383 lengths.push(text.length);
384 }),
385 }
386 : {}),
387 });
388 expect(yield* runtime.initialize()).toMatchObject({ protocolVersion: 1 });
389 }).pipe(Effect.scoped);
390 }
391 expect(lengths.length).toBeGreaterThan(0);
392 expect(Math.max(...lengths)).toBeGreaterThanOrEqual(16_384);
393 expect(Math.max(...lengths)).toBeLessThanOrEqual(32_768);
394 }).pipe(Effect.provide(NodeServices.layer)),
395 );
396
397 it.effect("releases a queued event drain when its runtime scope closes", () =>
398 Effect.gen(function* () {
399 const scope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
400 Scope.close(scope, Exit.void),
401 );
402 const barrierReceived = yield* Deferred.make<void>();
403 const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions).pipe(
404 Effect.provideService(Scope.Scope, scope),
405 );
406 yield* runtime.start();
407 yield* runtime.getEvents().pipe(
408 Stream.runForEach((event) =>
409 event._tag === "EventStreamBarrier"
410 ? Deferred.succeed(barrierReceived, undefined).pipe(Effect.andThen(Effect.never))
411 : Effect.void,
412 ),
413 Effect.forkIn(scope),
414 );
415 const drain = yield* runtime.drainEvents.pipe(Effect.forkChild);
416 yield* Deferred.await(barrierReceived);
417 yield* Scope.close(scope, Exit.void);
418 yield* Fiber.join(drain);
419 yield* runtime.drainEvents;
420 expect(yield* runtime.initialize().pipe(Effect.flip)).toMatchObject({
421 _tag: "AcpTransportError",
422 detail: "The ACP session runtime is closed.",
423 });
424 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
425 );
426
427 it.effect("bounds native cancellation when its event consumer is absent", () =>
428 Effect.gen(function* () {
429 const toolStarted = yield* Deferred.make<void>();
430 const cancelReceived = yield* Deferred.make<void>();
431 const runtime = yield* AcpSessionRuntime.make({
432 ...mockRuntimeOptions,
433 spawn: {
434 ...mockRuntimeOptions.spawn,
435 env: { T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL: "1" },
436 },
437 cancelBehavior: "wait-for-prompt",
438 cancelTimeout: "1 second",
439 });
440 yield* runtime.handleSessionUpdate((notification) => {
441 if (notification.update.sessionUpdate === "tool_call") {
442 return Deferred.succeed(toolStarted, undefined).pipe(Effect.asVoid);
443 }
444 if (notification.update.sessionUpdate === "agent_thought_chunk") {
445 return Deferred.succeed(cancelReceived, undefined).pipe(Effect.asVoid);
446 }
447 return Effect.void;
448 });
449 yield* runtime.start();
450 const prompt = yield* runtime
451 .prompt({
452 prompt: [{ type: "text", text: "first" }],
453 })
454 .pipe(Effect.forkChild);
455 yield* Deferred.await(toolStarted);
456 const cancellation = yield* runtime.cancel.pipe(Effect.forkChild);
457 yield* Deferred.await(cancelReceived);
458 yield* runtime.request("_test/finish-cancel", {});
459 expect(yield* Fiber.join(prompt)).toMatchObject({ stopReason: "cancelled" });
460 yield* TestClock.adjust("2 seconds");
461 expect(yield* Fiber.join(cancellation).pipe(Effect.flip)).toMatchObject({
462 _tag: "AcpTransportError",
463 method: "session/cancel",
464 });
465 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
466 );
467
468 it.effect("does not restore ambient variables to a sanitized child environment", () =>
469 Effect.gen(function* () {
470 yield* Effect.acquireRelease(
471 Effect.sync(() => {
472 const previous = process.env.T3_ACP_RUNTIME_AMBIENT;
473 process.env.T3_ACP_RUNTIME_AMBIENT = "sentinel";
474 return previous;
475 }),
476 (previous) =>
477 Effect.sync(() => {
478 if (previous === undefined) delete process.env.T3_ACP_RUNTIME_AMBIENT;
479 else process.env.T3_ACP_RUNTIME_AMBIENT = previous;
480 }),
481 );
482 const runtime = yield* AcpSessionRuntime.make({
483 ...mockRuntimeOptions,
484 spawn: {
485 command: process.execPath,
486 args: mockAgentArgs,
487 extendEnv: false,
488 env: { T3_ACP_RUNTIME_EXPLICIT: "kept" },
489 },
490 });
491 yield* runtime.initialize();
492 expect(yield* runtime.request("_test/environment", {})).toEqual({
493 inherited: false,
494 explicit: true,
495 });
496 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
497 );
498
499 it.effect("merges custom initialize client capabilities into the ACP handshake", () => {
500 const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
501 return Effect.gen(function* () {
502 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
503 yield* runtime.start();
504
505 const initializeStarted = requestEvents.find(
506 (event) => event.method === "initialize" && event.status === "started",
507 );
508 expect(initializeStarted?.payload).toMatchObject({
509 protocolVersion: 1,
510 clientCapabilities: {
511 fs: { readTextFile: false, writeTextFile: false },
512 terminal: false,
513 _meta: { parameterizedModelPicker: true },
514 },
515 });
516 }).pipe(
517 Effect.provide(
518 AcpSessionRuntime.layer({
519 spawn: {
520 command: mockAgentCommand,
521 args: mockAgentArgs,
522 },
523 cwd: process.cwd(),
524 clientCapabilities: {
525 _meta: {
526 parameterizedModelPicker: true,
527 },
528 },
529 clientInfo: { name: "t3-test", version: "0.0.0" },
530 authMethodId: "test",
531 requestLogger: (event) =>
532 Effect.sync(() => {
533 requestEvents.push(event);
534 }),
535 }),
536 ),
537 Effect.scoped,
538 Effect.provide(NodeServices.layer),
539 );
540 });
541
542 it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
543 Effect.gen(function* () {
544 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
545 const started = yield* runtime.start();
546
547 expect(started.initializeResult).toMatchObject({ protocolVersion: 1 });
548 expect(started.sessionId).toBe("mock-session-1");
549
550 const promptResult = yield* runtime.prompt({
551 prompt: [{ type: "text", text: "hi" }],
552 });
553 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
554
555 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
556 expect(notes).toHaveLength(4);
557 expect(notes.map((note) => note._tag)).toEqual([
558 "PlanUpdated",
559 "AssistantItemStarted",
560 "ContentDelta",
561 "AssistantItemCompleted",
562 ]);
563 const planUpdate = notes.find((note) => note._tag === "PlanUpdated");
564 expect(planUpdate?._tag).toBe("PlanUpdated");
565 if (planUpdate?._tag === "PlanUpdated") {
566 expect(planUpdate.payload.plan).toHaveLength(2);
567 }
568 const assistantStart = notes[1];
569 const assistantDelta = notes[2];
570 if (
571 assistantStart?._tag === "AssistantItemStarted" &&
572 assistantDelta?._tag === "ContentDelta"
573 ) {
574 expect(assistantDelta.itemId).toBe(assistantStart.itemId);
575 }
576 }).pipe(
577 Effect.provide(
578 AcpSessionRuntime.layer({
579 spawn: {
580 command: mockAgentCommand,
581 args: mockAgentArgs,
582 },
583 cwd: process.cwd(),
584 clientInfo: { name: "t3-test", version: "0.0.0" },
585 authMethodId: "test",
586 }),
587 ),
588 Effect.scoped,
589 Effect.provide(NodeServices.layer),
590 ),
591 );
592
593 it.effect("keeps assistant item IDs unique when a provider session restarts", () => {
594 const collectFirstAssistantItemId = Effect.gen(function* () {
595 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
596 const started = yield* runtime.start();
597 expect(started.sessionId).toBe("mock-session-1");
598
599 yield* runtime.prompt({
600 prompt: [{ type: "text", text: "hi" }],
601 });
602
603 const events = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
604 const assistantStart = events.find((event) => event._tag === "AssistantItemStarted");
605 expect(assistantStart?._tag).toBe("AssistantItemStarted");
606 return assistantStart?._tag === "AssistantItemStarted" ? assistantStart.itemId : "";
607 }).pipe(
608 Effect.provide(
609 AcpSessionRuntime.layer({
610 spawn: {
611 command: mockAgentCommand,
612 args: mockAgentArgs,
613 },
614 cwd: process.cwd(),
615 clientInfo: { name: "t3-test", version: "0.0.0" },
616 authMethodId: "test",
617 }),
618 ),
619 Effect.scoped,
620 );
621
622 return Effect.gen(function* () {
623 const beforeRestart = yield* collectFirstAssistantItemId;
624 const afterRestart = yield* collectFirstAssistantItemId;
625
626 expect(afterRestart).not.toBe(beforeRestart);
627 }).pipe(Effect.provide(NodeServices.layer));
628 });
629
630 it.effect("drops session updates emitted for a child ACP session", () =>
631 Effect.gen(function* () {
632 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
633 yield* runtime.start();
634
635 const promptResult = yield* runtime.prompt({
636 prompt: [{ type: "text", text: "hi" }],
637 });
638 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
639
640 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
641 expect(notes.map((note) => note._tag)).toEqual([
642 "AssistantItemStarted",
643 "ContentDelta",
644 "ContentDelta",
645 "AssistantItemCompleted",
646 ]);
647 expect(
648 notes
649 .filter((note) => note._tag === "ContentDelta")
650 .map((note) => note.text)
651 .join(""),
652 ).toBe("root before child root after child");
653 expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
654 }).pipe(
655 Effect.provide(
656 AcpSessionRuntime.layer({
657 spawn: {
658 command: mockAgentCommand,
659 args: mockAgentArgs,
660 env: {
661 T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
662 },
663 },
664 cwd: process.cwd(),
665 clientInfo: { name: "t3-test", version: "0.0.0" },
666 authMethodId: "test",
667 }),
668 ),
669 Effect.scoped,
670 Effect.provide(NodeServices.layer),
671 ),
672 );
673
674 it.effect("supports successive standard ACP prompts", () =>
675 Effect.gen(function* () {
676 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
677 yield* runtime.start();
678
679 const firstPromptResult = yield* runtime.prompt({
680 prompt: [{ type: "text", text: "first" }],
681 });
682 const secondPromptResult = yield* runtime.prompt({
683 prompt: [{ type: "text", text: "second" }],
684 });
685
686 expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" });
687 expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
688 }).pipe(
689 Effect.provide(
690 AcpSessionRuntime.layer({
691 spawn: {
692 command: mockAgentCommand,
693 args: mockAgentArgs,
694 },
695 cwd: process.cwd(),
696 clientInfo: { name: "t3-test", version: "0.0.0" },
697 authMethodId: "test",
698 }),
699 ),
700 Effect.scoped,
701 Effect.provide(NodeServices.layer),
702 ),
703 );
704
705 it.effect("releases a fully silent prompt when session/cancel is requested", () =>
706 Effect.gen(function* () {
707 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
708 yield* runtime.start();
709
710 const promptFiber = yield* runtime
711 .prompt({
712 prompt: [{ type: "text", text: "hang forever" }],
713 })
714 .pipe(Effect.forkChild({ startImmediately: true }));
715
716 yield* TestClock.adjust("500 millis");
717 yield* runtime.cancel;
718
719 const firstPromptResult = yield* Fiber.join(promptFiber);
720 expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
721
722 const secondPromptResult = yield* runtime.prompt({
723 prompt: [{ type: "text", text: "second" }],
724 });
725 expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
726 }).pipe(
727 Effect.provide(
728 AcpSessionRuntime.layer({
729 spawn: {
730 command: mockAgentCommand,
731 args: mockAgentArgs,
732 env: {
733 T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
734 },
735 },
736 cwd: process.cwd(),
737 clientInfo: { name: "t3-test", version: "0.0.0" },
738 authMethodId: "test",
739 }),
740 ),
741 Effect.scoped,
742 Effect.provide(NodeServices.layer),
743 ),
744 );
745
746 it.effect("segments assistant text around ACP tool calls", () =>
747 Effect.gen(function* () {
748 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
749 yield* runtime.start();
750
751 const promptResult = yield* runtime.prompt({
752 prompt: [{ type: "text", text: "hi" }],
753 });
754 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
755
756 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 7)));
757 expect(notes.map((note) => note._tag)).toEqual([
758 "AssistantItemStarted",
759 "ContentDelta",
760 "AssistantItemCompleted",
761 "ToolCallUpdated",
762 "ToolCallUpdated",
763 "AssistantItemStarted",
764 "ContentDelta",
765 ]);
766
767 const firstStarted = notes[0];
768 const firstDelta = notes[1];
769 const firstCompleted = notes[2];
770 const secondStarted = notes[5];
771 const secondDelta = notes[6];
772 expect(firstStarted?._tag).toBe("AssistantItemStarted");
773 expect(firstCompleted?._tag).toBe("AssistantItemCompleted");
774 expect(secondStarted?._tag).toBe("AssistantItemStarted");
775 if (
776 firstStarted?._tag === "AssistantItemStarted" &&
777 firstDelta?._tag === "ContentDelta" &&
778 firstCompleted?._tag === "AssistantItemCompleted" &&
779 secondStarted?._tag === "AssistantItemStarted" &&
780 secondDelta?._tag === "ContentDelta"
781 ) {
782 expect(firstDelta.itemId).toBe(firstStarted.itemId);
783 expect(firstCompleted.itemId).toBe(firstStarted.itemId);
784 expect(secondStarted.itemId).not.toBe(firstStarted.itemId);
785 expect(secondDelta.itemId).toBe(secondStarted.itemId);
786 }
787 }).pipe(
788 Effect.provide(
789 AcpSessionRuntime.layer({
790 spawn: {
791 command: mockAgentCommand,
792 args: mockAgentArgs,
793 env: {
794 T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS: "1",
795 },
796 },
797 cwd: process.cwd(),
798 clientInfo: { name: "t3-test", version: "0.0.0" },
799 authMethodId: "test",
800 }),
801 ),
802 Effect.scoped,
803 Effect.provide(NodeServices.layer),
804 ),
805 );
806
807 it.effect("emits status-only tool updates through completion", () =>
808 Effect.gen(function* () {
809 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
810 yield* runtime.start();
811
812 const promptResult = yield* runtime.prompt({
813 prompt: [{ type: "text", text: "hi" }],
814 });
815 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
816
817 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 3)));
818 expect(notes.map((note) => note._tag)).toEqual([
819 "ToolCallUpdated",
820 "ToolCallUpdated",
821 "ToolCallUpdated",
822 ]);
823 const toolCalls = notes.flatMap((note) =>
824 note._tag === "ToolCallUpdated" ? [note.toolCall] : [],
825 );
826 expect(toolCalls.map((toolCall) => toolCall.status)).toEqual([
827 "pending",
828 "inProgress",
829 "completed",
830 ]);
831 for (const toolCall of toolCalls) {
832 expect(toolCall.title).toBe("Read file");
833 }
834 }).pipe(
835 Effect.provide(
836 AcpSessionRuntime.layer({
837 spawn: {
838 command: mockAgentCommand,
839 args: mockAgentArgs,
840 env: {
841 T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1",
842 },
843 },
844 cwd: process.cwd(),
845 clientInfo: { name: "t3-test", version: "0.0.0" },
846 authMethodId: "test",
847 }),
848 ),
849 Effect.scoped,
850 Effect.provide(NodeServices.layer),
851 ),
852 );
853
854 it.effect("logs ACP requests from the shared runtime", () => {
855 const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
856 return Effect.gen(function* () {
857 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
858 yield* runtime.start();
859
860 yield* runtime.setModel("composer-2");
861 yield* runtime.prompt({
862 prompt: [{ type: "text", text: "hi" }],
863 });
864
865 expect(
866 requestEvents.some(
867 (event) => event.method === "session/set_config_option" && event.status === "started",
868 ),
869 ).toBe(true);
870 expect(
871 requestEvents.some(
872 (event) => event.method === "session/set_config_option" && event.status === "succeeded",
873 ),
874 ).toBe(true);
875 expect(
876 requestEvents.some(
877 (event) => event.method === "session/prompt" && event.status === "started",
878 ),
879 ).toBe(true);
880 expect(
881 requestEvents.some(
882 (event) => event.method === "session/prompt" && event.status === "succeeded",
883 ),
884 ).toBe(true);
885 }).pipe(
886 Effect.provide(
887 AcpSessionRuntime.layer({
888 authMethodId: "test",
889 spawn: {
890 command: mockAgentCommand,
891 args: mockAgentArgs,
892 },
893 cwd: process.cwd(),
894 clientInfo: { name: "t3-test", version: "0.0.0" },
895 requestLogger: (event) =>
896 Effect.sync(() => {
897 requestEvents.push(event);
898 }),
899 }),
900 ),
901 Effect.scoped,
902 Effect.provide(NodeServices.layer),
903 );
904 });
905
906 it.effect("skips no-op session config writes when the requested value is already active", () => {
907 const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
908 return Effect.gen(function* () {
909 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
910 yield* runtime.start();
911
912 yield* runtime.setConfigOption("model", "default");
913 yield* runtime.setMode("ask");
914
915 expect(
916 requestEvents.some(
917 (event) => event.method === "session/set_config_option" && event.status === "started",
918 ),
919 ).toBe(false);
920 }).pipe(
921 Effect.provide(
922 AcpSessionRuntime.layer({
923 authMethodId: "test",
924 spawn: {
925 command: mockAgentCommand,
926 args: mockAgentArgs,
927 },
928 cwd: process.cwd(),
929 clientInfo: { name: "t3-test", version: "0.0.0" },
930 requestLogger: (event) =>
931 Effect.sync(() => {
932 requestEvents.push(event);
933 }),
934 }),
935 ),
936 Effect.scoped,
937 Effect.provide(NodeServices.layer),
938 );
939 });
940
941 it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => {
942 const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
943 return Effect.gen(function* () {
944 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
945 yield* runtime.start();
946
947 yield* runtime.prompt({
948 prompt: [{ type: "text", text: "hi" }],
949 });
950
951 expect(
952 protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "raw"),
953 ).toBe(true);
954 expect(
955 protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "decoded"),
956 ).toBe(true);
957 expect(
958 protocolEvents.some((event) => event.direction === "incoming" && event.stage === "raw"),
959 ).toBe(true);
960 expect(
961 protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"),
962 ).toBe(true);
963 }).pipe(
964 Effect.provide(
965 AcpSessionRuntime.layer({
966 authMethodId: "test",
967 spawn: {
968 command: mockAgentCommand,
969 args: mockAgentArgs,
970 },
971 cwd: process.cwd(),
972 clientInfo: { name: "t3-test", version: "0.0.0" },
973 protocolLogging: {
974 logIncoming: true,
975 logOutgoing: true,
976 logger: (event) =>
977 Effect.sync(() => {
978 protocolEvents.push(event);
979 }),
980 },
981 }),
982 ),
983 Effect.scoped,
984 Effect.provide(NodeServices.layer),
985 );
986 });
987
988 it.effect("fails session startup when session/load returns an error", () =>
989 Effect.gen(function* () {
990 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
991 const error = yield* runtime.start().pipe(Effect.flip);
992
993 expect(error._tag).toBe("AcpRequestError");
994 }).pipe(
995 Effect.provide(
996 AcpSessionRuntime.layer({
997 authMethodId: "test",
998 spawn: {
999 command: mockAgentCommand,
1000 args: mockAgentArgs,
1001 env: {
1002 T3_ACP_FAIL_LOAD_SESSION: "1",
1003 },
1004 },
1005 cwd: process.cwd(),
1006 resumeSessionId: "stale-session-id",
1007 clientInfo: { name: "t3-test", version: "0.0.0" },
1008 }),
1009 ),
1010 Effect.scoped,
1011 Effect.provide(NodeServices.layer),
1012 ),
1013 );
1014
1015 it.effect("ignores session/update replay notifications during session/load", () =>
1016 Effect.gen(function* () {
1017 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
1018 yield* runtime.start();
1019
1020 yield* runtime.prompt({
1021 prompt: [{ type: "text", text: "hi" }],
1022 });
1023 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
1024 expect(notes.map((note) => note._tag)).toEqual([
1025 "PlanUpdated",
1026 "AssistantItemStarted",
1027 "ContentDelta",
1028 "AssistantItemCompleted",
1029 ]);
1030 expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
1031 }).pipe(
1032 Effect.provide(
1033 AcpSessionRuntime.layer({
1034 authMethodId: "test",
1035 spawn: {
1036 command: mockAgentCommand,
1037 args: mockAgentArgs,
1038 env: {
1039 T3_ACP_EMIT_LOAD_REPLAY: "1",
1040 },
1041 },
1042 cwd: process.cwd(),
1043 resumeSessionId: "mock-session-1",
1044 clientInfo: { name: "t3-test", version: "0.0.0" },
1045 }),
1046 ),
1047 Effect.scoped,
1048 Effect.provide(NodeServices.layer),
1049 ),
1050 );
1051
1052 it.effect("completes session/load after replay becomes idle while its RPC stays pending", () =>
1053 Effect.gen(function* () {
1054 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
1055 const started = yield* runtime.start().pipe(Effect.timeout("2 seconds"));
1056
1057 expect(started.sessionId).toBe("mock-session-1");
1058 expect(started.sessionSetupResult._meta).toMatchObject({
1059 t3SessionLoadReady: "replay_idle",
1060 });
1061
1062 const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe(
1063 Effect.timeoutOption("100 millis"),
1064 );
1065 expect(Option.isNone(unexpectedReplayEvent)).toBe(true);
1066 }).pipe(
1067 Effect.provide(
1068 AcpSessionRuntime.layer({
1069 authMethodId: "test",
1070 spawn: {
1071 command: mockAgentCommand,
1072 args: mockAgentArgs,
1073 env: {
1074 T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
1075 T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
1076 },
1077 },
1078 cwd: process.cwd(),
1079 resumeSessionId: "mock-session-1",
1080 sessionLoadReplayIdleGap: "50 millis",
1081 sessionLoadTimeout: "1 second",
1082 clientInfo: { name: "t3-test", version: "0.0.0" },
1083 }),
1084 ),
1085 Effect.scoped,
1086 Effect.provide(NodeServices.layer),
1087 TestClock.withLive,
1088 ),
1089 );
1090
1091 it.effect("rejects invalid config option values before sending session/set_config_option", () => {
1092 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
1093 const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
1094 return Effect.gen(function* () {
1095 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
1096 yield* runtime.start();
1097
1098 const error = yield* runtime.setModel("composer-2[fast=false]").pipe(Effect.flip);
1099 expect(error._tag).toBe("AcpRequestError");
1100 if (error._tag === "AcpRequestError") {
1101 expect(error.code).toBe(-32602);
1102 expect(error.message).toContain(
1103 'Invalid value "composer-2[fast=false]" for session config option "model"',
1104 );
1105 expect(error.message).toContain("composer-2[fast=true]");
1106 }
1107
1108 const recordedRequests = NodeFS.readFileSync(requestLogPath, "utf8")
1109 .trim()
1110 .split("\n")
1111 .filter((line) => line.length > 0)
1112 .map((line) => JSON.parse(line) as { method?: string; params?: { value?: unknown } });
1113 expect(
1114 recordedRequests.some(
1115 (message) =>
1116 message.method === "session/set_config_option" &&
1117 message.params?.value === "composer-2[fast=false]",
1118 ),
1119 ).toBe(false);
1120 }).pipe(
1121 Effect.provide(
1122 AcpSessionRuntime.layer({
1123 authMethodId: "test",
1124 spawn: {
1125 command: mockAgentCommand,
1126 args: mockAgentArgs,
1127 env: {
1128 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
1129 },
1130 },
1131 cwd: process.cwd(),
1132 clientInfo: { name: "t3-test", version: "0.0.0" },
1133 }),
1134 ),
1135 Effect.scoped,
1136 Effect.provide(NodeServices.layer),
1137 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
1138 );
1139 });
1140});