Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpJsonRpcConnection.test.ts

1,208 lines42.6 KB

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("attaches child stderr when the ACP process exits before initialize", () =>
372 Effect.gen(function* () {
373 const runtime = yield* AcpSessionRuntime.make({
374 ...mockRuntimeOptions,
375 spawn: {
376 command: process.execPath,
377 args: [
378 "-e",
379 "process.stderr.write(\"Invalid project config at /tmp/project/.cursor/cli.json: schema validation failed. Unrecognized key(s): 'approvalMode', 'sandbox'\\n\"); process.exit(1);",
380 ],
381 },
382 });
383 const error = yield* runtime.start().pipe(Effect.flip);
384 expect(error._tag).toBe("AcpProcessExitedError");
385 expect(error.message).toContain("cli.json");
386 expect(error.message).toContain("Unrecognized key");
387 expect(error.message).not.toContain("ACP process exited with code 1\nACP process exited");
388 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
389 );
390​
391 it.effect("drains large stderr output and keeps auth-sized logging chunks", () =>
392 Effect.gen(function* () {
393 const lengths: Array<number> = [];
394 for (const logStderr of [false, true]) {
395 yield* Effect.gen(function* () {
396 const runtime = yield* AcpSessionRuntime.make({
397 ...mockRuntimeOptions,
398 spawn: { ...mockRuntimeOptions.spawn, env: { T3_ACP_FLOOD_STDERR: "1" } },
399 ...(logStderr
400 ? {
401 onStderr: (text: string) =>
402 Effect.sync(() => {
403 lengths.push(text.length);
404 }),
405 }
406 : {}),
407 });
408 expect(yield* runtime.initialize()).toMatchObject({ protocolVersion: 1 });
409 }).pipe(Effect.scoped);
410 }
411 expect(lengths.length).toBeGreaterThan(0);
412 expect(Math.max(...lengths)).toBeGreaterThanOrEqual(16_384);
413 expect(Math.max(...lengths)).toBeLessThanOrEqual(32_768);
414 }).pipe(Effect.provide(NodeServices.layer)),
415 );
416​
417 it.effect("releases a queued event drain when its runtime scope closes", () =>
418 Effect.gen(function* () {
419 const scope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
420 Scope.close(scope, Exit.void),
421 );
422 const barrierReceived = yield* Deferred.make<void>();
423 const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions).pipe(
424 Effect.provideService(Scope.Scope, scope),
425 );
426 yield* runtime.start();
427 yield* runtime.getEvents().pipe(
428 Stream.runForEach((event) =>
429 event._tag === "EventStreamBarrier"
430 ? Deferred.succeed(barrierReceived, undefined).pipe(Effect.andThen(Effect.never))
431 : Effect.void,
432 ),
433 Effect.forkIn(scope),
434 );
435 const drain = yield* runtime.drainEvents.pipe(Effect.forkChild);
436 yield* Deferred.await(barrierReceived);
437 yield* Scope.close(scope, Exit.void);
438 yield* Fiber.join(drain);
439 yield* runtime.drainEvents;
440 expect(yield* runtime.initialize().pipe(Effect.flip)).toMatchObject({
441 _tag: "AcpTransportError",
442 detail: "The ACP session runtime is closed.",
443 });
444 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
445 );
446​
447 it.effect("bounds native cancellation when its event consumer is absent", () =>
448 Effect.gen(function* () {
449 const toolStarted = yield* Deferred.make<void>();
450 const cancelReceived = yield* Deferred.make<void>();
451 const runtime = yield* AcpSessionRuntime.make({
452 ...mockRuntimeOptions,
453 spawn: {
454 ...mockRuntimeOptions.spawn,
455 env: { T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL: "1" },
456 },
457 cancelBehavior: "wait-for-prompt",
458 cancelTimeout: "1 second",
459 });
460 yield* runtime.handleSessionUpdate((notification) => {
461 if (notification.update.sessionUpdate === "tool_call") {
462 return Deferred.succeed(toolStarted, undefined).pipe(Effect.asVoid);
463 }
464 if (notification.update.sessionUpdate === "agent_thought_chunk") {
465 return Deferred.succeed(cancelReceived, undefined).pipe(Effect.asVoid);
466 }
467 return Effect.void;
468 });
469 yield* runtime.start();
470 const prompt = yield* runtime
471 .prompt({
472 prompt: [{ type: "text", text: "first" }],
473 })
474 .pipe(Effect.forkChild);
475 yield* Deferred.await(toolStarted);
476 const cancellation = yield* runtime.cancel.pipe(Effect.forkChild);
477 yield* Deferred.await(cancelReceived);
478 yield* runtime.request("_test/finish-cancel", {});
479 expect(yield* Fiber.join(prompt)).toMatchObject({ stopReason: "cancelled" });
480 yield* TestClock.adjust("2 seconds");
481 expect(yield* Fiber.join(cancellation).pipe(Effect.flip)).toMatchObject({
482 _tag: "AcpTransportError",
483 method: "session/cancel",
484 });
485 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
486 );
487​
488 it.effect("does not restore ambient variables to a sanitized child environment", () =>
489 Effect.gen(function* () {
490 yield* Effect.acquireRelease(
491 Effect.sync(() => {
492 const previous = process.env.T3_ACP_RUNTIME_AMBIENT;
493 process.env.T3_ACP_RUNTIME_AMBIENT = "sentinel";
494 return previous;
495 }),
496 (previous) =>
497 Effect.sync(() => {
498 if (previous === undefined) delete process.env.T3_ACP_RUNTIME_AMBIENT;
499 else process.env.T3_ACP_RUNTIME_AMBIENT = previous;
500 }),
501 );
502 const runtime = yield* AcpSessionRuntime.make({
503 ...mockRuntimeOptions,
504 spawn: {
505 command: process.execPath,
506 args: mockAgentArgs,
507 extendEnv: false,
508 env: { T3_ACP_RUNTIME_EXPLICIT: "kept" },
509 },
510 });
511 yield* runtime.initialize();
512 expect(yield* runtime.request("_test/environment", {})).toEqual({
513 inherited: false,
514 explicit: true,
515 });
516 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
517 );
518​
519 it.effect("merges custom initialize client capabilities into the ACP handshake", () => {
520 const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
521 return Effect.gen(function* () {
522 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
523 yield* runtime.start();
524​
525 const initializeStarted = requestEvents.find(
526 (event) => event.method === "initialize" && event.status === "started",
527 );
528 expect(initializeStarted?.payload).toMatchObject({
529 protocolVersion: 1,
530 clientCapabilities: {
531 fs: { readTextFile: false, writeTextFile: false },
532 terminal: false,
533 _meta: { parameterizedModelPicker: true },
534 },
535 });
536 }).pipe(
537 Effect.provide(
538 AcpSessionRuntime.layer({
539 spawn: {
540 command: mockAgentCommand,
541 args: mockAgentArgs,
542 },
543 cwd: process.cwd(),
544 clientCapabilities: {
545 _meta: {
546 parameterizedModelPicker: true,
547 },
548 },
549 clientInfo: { name: "t3-test", version: "0.0.0" },
550 authMethodId: "test",
551 requestLogger: (event) =>
552 Effect.sync(() => {
553 requestEvents.push(event);
554 }),
555 }),
556 ),
557 Effect.scoped,
558 Effect.provide(NodeServices.layer),
559 );
560 });
561​
562 it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
563 Effect.gen(function* () {
564 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
565 const started = yield* runtime.start();
566​
567 expect(started.initializeResult).toMatchObject({ protocolVersion: 1 });
568 expect(started.sessionId).toBe("mock-session-1");
569​
570 const promptResult = yield* runtime.prompt({
571 prompt: [{ type: "text", text: "hi" }],
572 });
573 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
574​
575 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
576 expect(notes).toHaveLength(4);
577 expect(notes.map((note) => note._tag)).toEqual([
578 "PlanUpdated",
579 "AssistantItemStarted",
580 "ContentDelta",
581 "AssistantItemCompleted",
582 ]);
583 const planUpdate = notes.find((note) => note._tag === "PlanUpdated");
584 expect(planUpdate?._tag).toBe("PlanUpdated");
585 if (planUpdate?._tag === "PlanUpdated") {
586 expect(planUpdate.payload.plan).toHaveLength(2);
587 }
588 const assistantStart = notes[1];
589 const assistantDelta = notes[2];
590 if (
591 assistantStart?._tag === "AssistantItemStarted" &&
592 assistantDelta?._tag === "ContentDelta"
593 ) {
594 expect(assistantDelta.itemId).toBe(assistantStart.itemId);
595 }
596 }).pipe(
597 Effect.provide(
598 AcpSessionRuntime.layer({
599 spawn: {
600 command: mockAgentCommand,
601 args: mockAgentArgs,
602 },
603 cwd: process.cwd(),
604 clientInfo: { name: "t3-test", version: "0.0.0" },
605 authMethodId: "test",
606 }),
607 ),
608 Effect.scoped,
609 Effect.provide(NodeServices.layer),
610 ),
611 );
612​
613 it.effect("keeps assistant item IDs unique when a provider session restarts", () => {
614 const collectFirstAssistantItemId = Effect.gen(function* () {
615 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
616 const started = yield* runtime.start();
617 expect(started.sessionId).toBe("mock-session-1");
618​
619 yield* runtime.prompt({
620 prompt: [{ type: "text", text: "hi" }],
621 });
622​
623 const events = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
624 const assistantStart = events.find((event) => event._tag === "AssistantItemStarted");
625 expect(assistantStart?._tag).toBe("AssistantItemStarted");
626 return assistantStart?._tag === "AssistantItemStarted" ? assistantStart.itemId : "";
627 }).pipe(
628 Effect.provide(
629 AcpSessionRuntime.layer({
630 spawn: {
631 command: mockAgentCommand,
632 args: mockAgentArgs,
633 },
634 cwd: process.cwd(),
635 clientInfo: { name: "t3-test", version: "0.0.0" },
636 authMethodId: "test",
637 }),
638 ),
639 Effect.scoped,
640 );
641​
642 return Effect.gen(function* () {
643 const beforeRestart = yield* collectFirstAssistantItemId;
644 const afterRestart = yield* collectFirstAssistantItemId;
645​
646 expect(afterRestart).not.toBe(beforeRestart);
647 }).pipe(Effect.provide(NodeServices.layer));
648 });
649​
650 it.effect("drops session updates emitted for a child ACP session", () =>
651 Effect.gen(function* () {
652 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
653 yield* runtime.start();
654​
655 const promptResult = yield* runtime.prompt({
656 prompt: [{ type: "text", text: "hi" }],
657 });
658 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
659​
660 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
661 expect(notes.map((note) => note._tag)).toEqual([
662 "AssistantItemStarted",
663 "ContentDelta",
664 "ContentDelta",
665 "AssistantItemCompleted",
666 ]);
667 expect(
668 notes
669 .filter((note) => note._tag === "ContentDelta")
670 .map((note) => note.text)
671 .join(""),
672 ).toBe("root before child root after child");
673 expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
674 }).pipe(
675 Effect.provide(
676 AcpSessionRuntime.layer({
677 spawn: {
678 command: mockAgentCommand,
679 args: mockAgentArgs,
680 env: {
681 T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
682 },
683 },
684 cwd: process.cwd(),
685 clientInfo: { name: "t3-test", version: "0.0.0" },
686 authMethodId: "test",
687 }),
688 ),
689 Effect.scoped,
690 Effect.provide(NodeServices.layer),
691 ),
692 );
693​
694 it.effect("supports successive standard ACP prompts", () =>
695 Effect.gen(function* () {
696 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
697 yield* runtime.start();
698​
699 const firstPromptResult = yield* runtime.prompt({
700 prompt: [{ type: "text", text: "first" }],
701 });
702 const secondPromptResult = yield* runtime.prompt({
703 prompt: [{ type: "text", text: "second" }],
704 });
705​
706 expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" });
707 expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
708 }).pipe(
709 Effect.provide(
710 AcpSessionRuntime.layer({
711 spawn: {
712 command: mockAgentCommand,
713 args: mockAgentArgs,
714 },
715 cwd: process.cwd(),
716 clientInfo: { name: "t3-test", version: "0.0.0" },
717 authMethodId: "test",
718 }),
719 ),
720 Effect.scoped,
721 Effect.provide(NodeServices.layer),
722 ),
723 );
724​
725 it.effect("releases a fully silent prompt when session/cancel is requested", () =>
726 Effect.gen(function* () {
727 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
728 yield* runtime.start();
729​
730 const promptFiber = yield* runtime
731 .prompt({
732 prompt: [{ type: "text", text: "hang forever" }],
733 })
734 .pipe(Effect.forkChild({ startImmediately: true }));
735​
736 yield* TestClock.adjust("500 millis");
737 yield* runtime.cancel;
738​
739 const firstPromptResult = yield* Fiber.join(promptFiber);
740 expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
741​
742 const secondPromptResult = yield* runtime.prompt({
743 prompt: [{ type: "text", text: "second" }],
744 });
745 expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
746 }).pipe(
747 Effect.provide(
748 AcpSessionRuntime.layer({
749 spawn: {
750 command: mockAgentCommand,
751 args: mockAgentArgs,
752 env: {
753 T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
754 },
755 },
756 cwd: process.cwd(),
757 clientInfo: { name: "t3-test", version: "0.0.0" },
758 authMethodId: "test",
759 }),
760 ),
761 Effect.scoped,
762 Effect.provide(NodeServices.layer),
763 ),
764 );
765​
766 it.effect("segments assistant text around ACP tool calls", () =>
767 Effect.gen(function* () {
768 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
769 yield* runtime.start();
770​
771 const promptResult = yield* runtime.prompt({
772 prompt: [{ type: "text", text: "hi" }],
773 });
774 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
775​
776 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 7)));
777 expect(notes.map((note) => note._tag)).toEqual([
778 "AssistantItemStarted",
779 "ContentDelta",
780 "AssistantItemCompleted",
781 "ToolCallUpdated",
782 "ToolCallUpdated",
783 "AssistantItemStarted",
784 "ContentDelta",
785 ]);
786​
787 const firstStarted = notes[0];
788 const firstDelta = notes[1];
789 const firstCompleted = notes[2];
790 const secondStarted = notes[5];
791 const secondDelta = notes[6];
792 expect(firstStarted?._tag).toBe("AssistantItemStarted");
793 expect(firstCompleted?._tag).toBe("AssistantItemCompleted");
794 expect(secondStarted?._tag).toBe("AssistantItemStarted");
795 if (
796 firstStarted?._tag === "AssistantItemStarted" &&
797 firstDelta?._tag === "ContentDelta" &&
798 firstCompleted?._tag === "AssistantItemCompleted" &&
799 secondStarted?._tag === "AssistantItemStarted" &&
800 secondDelta?._tag === "ContentDelta"
801 ) {
802 expect(firstDelta.itemId).toBe(firstStarted.itemId);
803 expect(firstCompleted.itemId).toBe(firstStarted.itemId);
804 expect(secondStarted.itemId).not.toBe(firstStarted.itemId);
805 expect(secondDelta.itemId).toBe(secondStarted.itemId);
806 }
807 }).pipe(
808 Effect.provide(
809 AcpSessionRuntime.layer({
810 spawn: {
811 command: mockAgentCommand,
812 args: mockAgentArgs,
813 env: {
814 T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS: "1",
815 },
816 },
817 cwd: process.cwd(),
818 clientInfo: { name: "t3-test", version: "0.0.0" },
819 authMethodId: "test",
820 }),
821 ),
822 Effect.scoped,
823 Effect.provide(NodeServices.layer),
824 ),
825 );
826​
827 it.effect("keeps one answer when an earlier tool reports progress mid-stream", () =>
828 Effect.gen(function* () {
829 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
830 yield* runtime.start();
831 yield* runtime.prompt({ prompt: [{ type: "text", text: "hi" }] });
832​
833 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 9)));
834 // The coalesced progress tick emits nothing, and neither the completion
835 // nor a repeated one splits the markdown table across items.
836 expect(notes.map((note) => note._tag)).toEqual([
837 "ToolCallUpdated",
838 "AssistantItemStarted",
839 "ContentDelta",
840 "ContentDelta",
841 "ToolCallUpdated",
842 "ContentDelta",
843 "ToolCallUpdated",
844 "ContentDelta",
845 "AssistantItemCompleted",
846 ]);
847 const itemIds = new Set(
848 notes.flatMap((note) =>
849 note._tag === "ContentDelta" ||
850 note._tag === "AssistantItemStarted" ||
851 note._tag === "AssistantItemCompleted"
852 ? [note.itemId]
853 : [],
854 ),
855 );
856 expect(itemIds.size).toBe(1);
857 }).pipe(
858 Effect.provide(
859 AcpSessionRuntime.layer({
860 spawn: {
861 command: mockAgentCommand,
862 args: mockAgentArgs,
863 env: { T3_ACP_EMIT_BACKGROUND_TOOL_DURING_ANSWER: "1" },
864 },
865 cwd: process.cwd(),
866 clientInfo: { name: "t3-test", version: "0.0.0" },
867 authMethodId: "test",
868 }),
869 ),
870 Effect.scoped,
871 Effect.provide(NodeServices.layer),
872 ),
873 );
874​
875 it.effect("emits status-only tool updates through completion", () =>
876 Effect.gen(function* () {
877 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
878 yield* runtime.start();
879​
880 const promptResult = yield* runtime.prompt({
881 prompt: [{ type: "text", text: "hi" }],
882 });
883 expect(promptResult).toMatchObject({ stopReason: "end_turn" });
884​
885 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 3)));
886 expect(notes.map((note) => note._tag)).toEqual([
887 "ToolCallUpdated",
888 "ToolCallUpdated",
889 "ToolCallUpdated",
890 ]);
891 const toolCalls = notes.flatMap((note) =>
892 note._tag === "ToolCallUpdated" ? [note.toolCall] : [],
893 );
894 expect(toolCalls.map((toolCall) => toolCall.status)).toEqual([
895 "pending",
896 "inProgress",
897 "completed",
898 ]);
899 for (const toolCall of toolCalls) {
900 expect(toolCall.title).toBe("Read file");
901 }
902 }).pipe(
903 Effect.provide(
904 AcpSessionRuntime.layer({
905 spawn: {
906 command: mockAgentCommand,
907 args: mockAgentArgs,
908 env: {
909 T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1",
910 },
911 },
912 cwd: process.cwd(),
913 clientInfo: { name: "t3-test", version: "0.0.0" },
914 authMethodId: "test",
915 }),
916 ),
917 Effect.scoped,
918 Effect.provide(NodeServices.layer),
919 ),
920 );
921​
922 it.effect("logs ACP requests from the shared runtime", () => {
923 const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
924 return Effect.gen(function* () {
925 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
926 yield* runtime.start();
927​
928 yield* runtime.setModel("composer-2");
929 yield* runtime.prompt({
930 prompt: [{ type: "text", text: "hi" }],
931 });
932​
933 expect(
934 requestEvents.some(
935 (event) => event.method === "session/set_config_option" && event.status === "started",
936 ),
937 ).toBe(true);
938 expect(
939 requestEvents.some(
940 (event) => event.method === "session/set_config_option" && event.status === "succeeded",
941 ),
942 ).toBe(true);
943 expect(
944 requestEvents.some(
945 (event) => event.method === "session/prompt" && event.status === "started",
946 ),
947 ).toBe(true);
948 expect(
949 requestEvents.some(
950 (event) => event.method === "session/prompt" && event.status === "succeeded",
951 ),
952 ).toBe(true);
953 }).pipe(
954 Effect.provide(
955 AcpSessionRuntime.layer({
956 authMethodId: "test",
957 spawn: {
958 command: mockAgentCommand,
959 args: mockAgentArgs,
960 },
961 cwd: process.cwd(),
962 clientInfo: { name: "t3-test", version: "0.0.0" },
963 requestLogger: (event) =>
964 Effect.sync(() => {
965 requestEvents.push(event);
966 }),
967 }),
968 ),
969 Effect.scoped,
970 Effect.provide(NodeServices.layer),
971 );
972 });
973​
974 it.effect("skips no-op session config writes when the requested value is already active", () => {
975 const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
976 return Effect.gen(function* () {
977 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
978 yield* runtime.start();
979​
980 yield* runtime.setConfigOption("model", "default");
981 yield* runtime.setMode("ask");
982​
983 expect(
984 requestEvents.some(
985 (event) => event.method === "session/set_config_option" && event.status === "started",
986 ),
987 ).toBe(false);
988 }).pipe(
989 Effect.provide(
990 AcpSessionRuntime.layer({
991 authMethodId: "test",
992 spawn: {
993 command: mockAgentCommand,
994 args: mockAgentArgs,
995 },
996 cwd: process.cwd(),
997 clientInfo: { name: "t3-test", version: "0.0.0" },
998 requestLogger: (event) =>
999 Effect.sync(() => {
1000 requestEvents.push(event);
1001 }),
1002 }),
1003 ),
1004 Effect.scoped,
1005 Effect.provide(NodeServices.layer),
1006 );
1007 });
1008​
1009 it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => {
1010 const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
1011 return Effect.gen(function* () {
1012 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
1013 yield* runtime.start();
1014​
1015 yield* runtime.prompt({
1016 prompt: [{ type: "text", text: "hi" }],
1017 });
1018​
1019 expect(
1020 protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "raw"),
1021 ).toBe(true);
1022 expect(
1023 protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "decoded"),
1024 ).toBe(true);
1025 expect(
1026 protocolEvents.some((event) => event.direction === "incoming" && event.stage === "raw"),
1027 ).toBe(true);
1028 expect(
1029 protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"),
1030 ).toBe(true);
1031 }).pipe(
1032 Effect.provide(
1033 AcpSessionRuntime.layer({
1034 authMethodId: "test",
1035 spawn: {
1036 command: mockAgentCommand,
1037 args: mockAgentArgs,
1038 },
1039 cwd: process.cwd(),
1040 clientInfo: { name: "t3-test", version: "0.0.0" },
1041 protocolLogging: {
1042 logIncoming: true,
1043 logOutgoing: true,
1044 logger: (event) =>
1045 Effect.sync(() => {
1046 protocolEvents.push(event);
1047 }),
1048 },
1049 }),
1050 ),
1051 Effect.scoped,
1052 Effect.provide(NodeServices.layer),
1053 );
1054 });
1055​
1056 it.effect("fails session startup when session/load returns an error", () =>
1057 Effect.gen(function* () {
1058 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
1059 const error = yield* runtime.start().pipe(Effect.flip);
1060​
1061 expect(error._tag).toBe("AcpRequestError");
1062 }).pipe(
1063 Effect.provide(
1064 AcpSessionRuntime.layer({
1065 authMethodId: "test",
1066 spawn: {
1067 command: mockAgentCommand,
1068 args: mockAgentArgs,
1069 env: {
1070 T3_ACP_FAIL_LOAD_SESSION: "1",
1071 },
1072 },
1073 cwd: process.cwd(),
1074 resumeSessionId: "stale-session-id",
1075 clientInfo: { name: "t3-test", version: "0.0.0" },
1076 }),
1077 ),
1078 Effect.scoped,
1079 Effect.provide(NodeServices.layer),
1080 ),
1081 );
1082​
1083 it.effect("ignores session/update replay notifications during session/load", () =>
1084 Effect.gen(function* () {
1085 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
1086 yield* runtime.start();
1087​
1088 yield* runtime.prompt({
1089 prompt: [{ type: "text", text: "hi" }],
1090 });
1091 const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
1092 expect(notes.map((note) => note._tag)).toEqual([
1093 "PlanUpdated",
1094 "AssistantItemStarted",
1095 "ContentDelta",
1096 "AssistantItemCompleted",
1097 ]);
1098 expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
1099 }).pipe(
1100 Effect.provide(
1101 AcpSessionRuntime.layer({
1102 authMethodId: "test",
1103 spawn: {
1104 command: mockAgentCommand,
1105 args: mockAgentArgs,
1106 env: {
1107 T3_ACP_EMIT_LOAD_REPLAY: "1",
1108 },
1109 },
1110 cwd: process.cwd(),
1111 resumeSessionId: "mock-session-1",
1112 clientInfo: { name: "t3-test", version: "0.0.0" },
1113 }),
1114 ),
1115 Effect.scoped,
1116 Effect.provide(NodeServices.layer),
1117 ),
1118 );
1119​
1120 it.effect("completes session/load after replay becomes idle while its RPC stays pending", () =>
1121 Effect.gen(function* () {
1122 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
1123 const started = yield* runtime.start().pipe(Effect.timeout("2 seconds"));
1124​
1125 expect(started.sessionId).toBe("mock-session-1");
1126 expect(started.sessionSetupResult._meta).toMatchObject({
1127 t3SessionLoadReady: "replay_idle",
1128 });
1129​
1130 const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe(
1131 Effect.timeoutOption("100 millis"),
1132 );
1133 expect(Option.isNone(unexpectedReplayEvent)).toBe(true);
1134 }).pipe(
1135 Effect.provide(
1136 AcpSessionRuntime.layer({
1137 authMethodId: "test",
1138 spawn: {
1139 command: mockAgentCommand,
1140 args: mockAgentArgs,
1141 env: {
1142 T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
1143 T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
1144 },
1145 },
1146 cwd: process.cwd(),
1147 resumeSessionId: "mock-session-1",
1148 sessionLoadReplayIdleGap: "50 millis",
1149 sessionLoadTimeout: "1 second",
1150 clientInfo: { name: "t3-test", version: "0.0.0" },
1151 }),
1152 ),
1153 Effect.scoped,
1154 Effect.provide(NodeServices.layer),
1155 TestClock.withLive,
1156 ),
1157 );
1158​
1159 it.effect("rejects invalid config option values before sending session/set_config_option", () => {
1160 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
1161 const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
1162 return Effect.gen(function* () {
1163 const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
1164 yield* runtime.start();
1165​
1166 const error = yield* runtime.setModel("composer-2[fast=false]").pipe(Effect.flip);
1167 expect(error._tag).toBe("AcpRequestError");
1168 if (error._tag === "AcpRequestError") {
1169 expect(error.code).toBe(-32602);
1170 expect(error.message).toContain(
1171 'Invalid value "composer-2[fast=false]" for session config option "model"',
1172 );
1173 expect(error.message).toContain("composer-2[fast=true]");
1175​
1176 const recordedRequests = NodeFS.readFileSync(requestLogPath, "utf8")
1177 .trim()
1178 .split("\n")
1179 .filter((line) => line.length > 0)
1180 .map((line) => JSON.parse(line) as { method?: string; params?: { value?: unknown } });
1181 expect(
1182 recordedRequests.some(
1183 (message) =>
1184 message.method === "session/set_config_option" &&
1185 message.params?.value === "composer-2[fast=false]",
1186 ),
1187 ).toBe(false);
1188 }).pipe(
1189 Effect.provide(
1190 AcpSessionRuntime.layer({
1191 authMethodId: "test",
1192 spawn: {
1193 command: mockAgentCommand,
1194 args: mockAgentArgs,
1195 env: {
1196 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
1197 },
1198 },
1199 cwd: process.cwd(),
1200 clientInfo: { name: "t3-test", version: "0.0.0" },
1201 }),
1202 ),
1203 Effect.scoped,
1204 Effect.provide(NodeServices.layer),
1205 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
1206 );
1207 });
1208});