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