Open History to see the last commit
1import * as Path from "effect/Path";
2import * as AcpError from "./errors.ts";
3import * as Effect from "effect/Effect";
4import * as Deferred from "effect/Deferred";
5import * as Fiber from "effect/Fiber";
6import * as Queue from "effect/Queue";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import * as Ref from "effect/Ref";
10import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
11
12import { it, assert } from "@effect/vitest";
13import * as NodeServices from "@effect/platform-node/NodeServices";
14
15import * as AcpSchema from "./_generated/schema.gen.ts";
16import * as AcpProtocol from "./protocol.ts";
17import {
18 encodeJsonl,
19 jsonRpcNotification,
20 jsonRpcRequest,
21 jsonRpcResponse,
22} from "./_internal/shared.ts";
23import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts";
24
25const SessionCancelNotification = jsonRpcNotification(
26 "session/cancel",
27 AcpSchema.CancelNotification,
28);
29const SessionUpdateNotification = jsonRpcNotification(
30 "session/update",
31 AcpSchema.SessionNotification,
32);
33const ElicitationCompleteNotification = jsonRpcNotification(
34 "session/elicitation/complete",
35 AcpSchema.ElicitationCompleteNotification,
36);
37const RequestPermissionRequest = jsonRpcRequest(
38 "session/request_permission",
39 AcpSchema.RequestPermissionRequest,
40);
41const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
42const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
43const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
44const decodeSessionCancelNotification = Schema.decodeEffect(
45 Schema.fromJsonString(SessionCancelNotification),
46);
47const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
48const decodeExtResponse = Schema.decodeEffect(Schema.fromJsonString(ExtResponse));
49const decodeRequestPermissionResponse = Schema.decodeEffect(
50 Schema.fromJsonString(RequestPermissionResponse),
51);
52const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
53const encoder = new TextEncoder();
54const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
55 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
56);
57const mockPeerArgs = (path: string) => [path];
58
59const makeHandle = (env?: Record<string, string>) =>
60 Effect.gen(function* () {
61 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
62 const path = yield* Path.Path;
63 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
64 cwd: path.join(import.meta.dirname, ".."),
65 ...(env ? { env: { ...process.env, ...env } } : {}),
66 });
67 return yield* spawner.spawn(command);
68 });
69
70it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
71 it.effect(
72 "emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
73 () =>
74 Effect.gen(function* () {
75 const { stdio, input, output } = yield* makeInMemoryStdio();
76 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
77 stdio,
78 serverRequestMethods: new Set(),
79 });
80
81 const notifications =
82 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
83 yield* transport.incoming.pipe(
84 Stream.take(2),
85 Stream.runCollect,
86 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
87 Effect.forkScoped,
88 );
89
90 yield* transport.notify("session/cancel", { sessionId: "session-1" });
91 const outbound = yield* Queue.take(output);
92 assert.deepEqual(yield* decodeSessionCancelNotification(outbound), {
93 jsonrpc: "2.0",
94 method: "session/cancel",
95 params: {
96 sessionId: "session-1",
97 },
98 });
99
100 yield* Queue.offer(
101 input,
102 yield* encodeJsonl(SessionUpdateNotification, {
103 jsonrpc: "2.0",
104 method: "session/update",
105 params: {
106 sessionId: "session-1",
107 update: {
108 sessionUpdate: "plan",
109 entries: [
110 {
111 content: "Inspect repository",
112 priority: "high",
113 status: "in_progress",
114 },
115 ],
116 },
117 },
118 }),
119 );
120
121 yield* Queue.offer(
122 input,
123 yield* encodeJsonl(ElicitationCompleteNotification, {
124 jsonrpc: "2.0",
125 method: "session/elicitation/complete",
126 params: {
127 elicitationId: "elicitation-1",
128 },
129 }),
130 );
131
132 const [update, completion] = yield* Deferred.await(notifications);
133 assert.equal(update?._tag, "SessionUpdate");
134 assert.equal(completion?._tag, "ElicitationComplete");
135 }),
136 );
137
138 it.effect("keeps only recent raw notifications after their callbacks run", () =>
139 Effect.gen(function* () {
140 const { stdio, input } = yield* makeInMemoryStdio();
141 const handled = yield* Deferred.make<void>();
142 let handledCount = 0;
143 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
144 stdio,
145 serverRequestMethods: new Set(),
146 onNotification: () =>
147 Effect.sync(() => ++handledCount).pipe(
148 Effect.flatMap((count) =>
149 count === 64 ? Deferred.succeed(handled, undefined).pipe(Effect.asVoid) : Effect.void,
150 ),
151 ),
152 });
153
154 const messages = Array.from({ length: 64 }, (_, index) =>
155 encodeUnknownJsonString({
156 jsonrpc: "2.0",
157 method: "x/performance",
158 params: { index },
159 }),
160 );
161 yield* Queue.offer(input, encoder.encode(`${messages.join("\n")}\n`));
162 yield* Deferred.await(handled);
163
164 const retained = yield* transport.incoming.pipe(Stream.take(32), Stream.runCollect);
165
166 assert.equal(handledCount, 64);
167 assert.equal(retained.length, 32);
168 assert.deepEqual(retained[0]?.params, { index: 32 });
169 assert.deepEqual(retained[31]?.params, { index: 63 });
170 }),
171 );
172
173 it.effect("keeps invalid core notification values only in the schema cause", () =>
174 Effect.gen(function* () {
175 const secret = "acp-core-notification-secret-sentinel";
176 const { stdio, input } = yield* makeInMemoryStdio();
177 const termination = yield* Deferred.make<AcpError.AcpError>();
178 let transformCalls = 0;
179 yield* AcpProtocol.makeAcpPatchedProtocol({
180 stdio,
181 serverRequestMethods: new Set(),
182 transformSessionUpdate: (notification) => {
183 transformCalls += 1;
184 return notification;
185 },
186 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
187 });
188
189 yield* Queue.offer(
190 input,
191 encoder.encode(
192 `${encodeUnknownJsonString({
193 jsonrpc: "2.0",
194 method: "session/update",
195 params: {
196 sessionId: { secret },
197 update: {
198 sessionUpdate: "plan",
199 entries: [],
200 },
201 },
202 })}\n`,
203 ),
204 );
205
206 const error = yield* Deferred.await(termination);
207 assert.equal(transformCalls, 0);
208 assert.instanceOf(error, AcpError.AcpProtocolParseError);
209 const parseError = error as AcpError.AcpProtocolParseError;
210 const { cause, ...directDiagnostics } = parseError;
211 assert.equal(parseError.operation, "decode-notification-payload");
212 assert.equal(parseError.method, "session/update");
213 assert.isAbove(parseError.issueCount ?? 0, 0);
214 assert.include(parseError.issueKinds ?? [], "Pointer");
215 assert.isAbove(parseError.maximumPathDepth ?? 0, 0);
216 assert.isTrue(Schema.isSchemaError(cause));
217 assert.notInclude(parseError.message, secret);
218 assert.notInclude(encodeUnknownJsonString(directDiagnostics), secret);
219 }),
220 );
221
222 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
223 Effect.gen(function* () {
224 const { stdio } = yield* makeInMemoryStdio();
225 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
226 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
227 stdio,
228 serverRequestMethods: new Set(),
229 logOutgoing: true,
230 logger: (event) =>
231 Effect.sync(() => {
232 events.push(event);
233 }),
234 });
235
236 yield* transport.notify("session/cancel", { sessionId: "session-1" });
237
238 // A notification must not carry `id` or `headers`. Grok CLI drops frames that do.
239 assert.deepEqual(events, [
240 {
241 direction: "outgoing",
242 stage: "decoded",
243 payload: {
244 _tag: "Notification",
245 tag: "session/cancel",
246 payload: {
247 sessionId: "session-1",
248 },
249 },
250 },
251 {
252 direction: "outgoing",
253 stage: "raw",
254 payload:
255 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"}}\n',
256 },
257 ]);
258 }),
259 );
260
261 it.effect("logs decode failures without copying the cause or wire payload", () =>
262 Effect.gen(function* () {
263 const secret = "acp-wire-secret-sentinel";
264 const { stdio, input } = yield* makeInMemoryStdio();
265 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
266 const termination = yield* Deferred.make<AcpError.AcpError>();
267 yield* AcpProtocol.makeAcpPatchedProtocol({
268 stdio,
269 serverRequestMethods: new Set(),
270 logIncoming: true,
271 logger: (event) =>
272 Effect.sync(() => {
273 events.push(event);
274 }),
275 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
276 });
277
278 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
279 yield* Deferred.await(termination);
280
281 const event = events.find(({ stage }) => stage === "decode_failed");
282 assert.deepEqual(event, {
283 direction: "incoming",
284 stage: "decode_failed",
285 payload: {
286 operation: "decode-wire-message",
287 },
288 });
289 assert.notInclude(encodeUnknownJsonString(event), secret);
290 }),
291 );
292
293 it.effect("fails notification encoding through the declared ACP error channel", () =>
294 Effect.gen(function* () {
295 const { stdio } = yield* makeInMemoryStdio();
296 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
297 stdio,
298 serverRequestMethods: new Set(),
299 });
300
301 // Notifications encode through Schema, so the cause is the schema failure rather
302 // than the raw TypeError JSON.stringify throws. The ACP error shape is what callers see.
303 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
304 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
305 assert.equal(bigintError.operation, "encode-message");
306 assert.equal(bigintError.method, "x/test");
307 assert.isDefined(bigintError.cause);
308 assert.equal(
309 bigintError.message,
310 "ACP protocol operation 'encode-message' failed for method 'x/test'.",
311 );
312
313 const circular: Record<string, unknown> = {};
314 circular.self = circular;
315 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
316 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
317 assert.equal(circularError.operation, "encode-message");
318 assert.equal(circularError.method, "x/test");
319 assert.isDefined(circularError.cause);
320
321 const requestError = yield* transport.request("x/request", 1n).pipe(
322 Effect.match({
323 onFailure: (error) => error,
324 onSuccess: () => assert.fail("Expected request encoding to fail"),
325 }),
326 );
327 assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
328 assert.deepInclude(requestError, {
329 operation: "encode-message",
330 method: "x/request",
331 requestId: 1,
332 });
333 }),
334 );
335
336 it.effect("supports generic extension requests over the patched transport", () =>
337 Effect.gen(function* () {
338 const { stdio, input, output } = yield* makeInMemoryStdio();
339 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
340 stdio,
341 serverRequestMethods: new Set(),
342 });
343
344 const response = yield* transport
345 .request("x/test", { hello: "world" })
346 .pipe(Effect.forkScoped);
347 const outbound = yield* Queue.take(output);
348 assert.deepEqual(yield* decodeExtRequest(outbound), {
349 jsonrpc: "2.0",
350 id: 1,
351 method: "x/test",
352 params: {
353 hello: "world",
354 },
355 headers: [],
356 });
357
358 yield* Queue.offer(
359 input,
360 yield* encodeJsonl(ExtResponse, {
361 jsonrpc: "2.0",
362 id: 1,
363 result: {
364 ok: true,
365 },
366 }),
367 );
368
369 const resolved = yield* Fiber.join(response);
370 assert.deepEqual(resolved, { ok: true });
371 }),
372 );
373
374 it.effect("correlates extension response errors with the originating request", () =>
375 Effect.gen(function* () {
376 const { stdio, input, output } = yield* makeInMemoryStdio();
377 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
378 stdio,
379 serverRequestMethods: new Set(),
380 });
381
382 const response = yield* transport
383 .request("x/private", { hello: "world" })
384 .pipe(Effect.forkScoped);
385 yield* Queue.take(output);
386 yield* Queue.offer(
387 input,
388 encoder.encode(
389 `${encodeUnknownJsonString({
390 jsonrpc: "2.0",
391 id: 1,
392 error: {
393 _tag: "Cause",
394 code: -32602,
395 message: "Invalid params",
396 data: [
397 {
398 _tag: "Fail",
399 error: {
400 code: -32602,
401 message: "Invalid params",
402 data: { field: "hello" },
403 },
404 },
405 ],
406 },
407 })}\n`,
408 ),
409 );
410
411 const error = yield* Fiber.join(response).pipe(
412 Effect.match({
413 onFailure: (error) => error,
414 onSuccess: () => assert.fail("Expected extension request to fail"),
415 }),
416 );
417 assert.instanceOf(error, AcpError.AcpRequestError);
418 assert.deepInclude(error, {
419 code: -32602,
420 errorMessage: "Invalid params",
421 method: "x/private",
422 requestId: 1,
423 operation: "receive-response",
424 });
425 }),
426 );
427
428 it.effect("preserves numeric ids for inbound extension requests", () =>
429 Effect.gen(function* () {
430 const { stdio, input, output } = yield* makeInMemoryStdio();
431 yield* AcpProtocol.makeAcpPatchedProtocol({
432 stdio,
433 serverRequestMethods: new Set(),
434 onExtRequest: () => Effect.succeed({ ok: true }),
435 });
436
437 yield* Queue.offer(
438 input,
439 yield* encodeJsonl(ExtRequest, {
440 jsonrpc: "2.0",
441 id: 7,
442 method: "x/test",
443 params: {
444 hello: "world",
445 },
446 headers: [],
447 }),
448 );
449
450 const outbound = yield* Queue.take(output);
451 assert.deepEqual(yield* decodeExtResponse(outbound), {
452 jsonrpc: "2.0",
453 id: 7,
454 result: {
455 ok: true,
456 },
457 });
458 }),
459 );
460
461 it.effect("preserves zero-valued ids for inbound core client requests", () =>
462 Effect.gen(function* () {
463 const { stdio, input, output } = yield* makeInMemoryStdio();
464 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
465 stdio,
466 serverRequestMethods: new Set(["session/request_permission"]),
467 });
468 const inboundRequest = yield* Deferred.make<unknown>();
469
470 yield* transport.serverProtocol
471 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
472 .pipe(Effect.forkScoped);
473
474 yield* Queue.offer(
475 input,
476 yield* encodeJsonl(RequestPermissionRequest, {
477 jsonrpc: "2.0",
478 id: 0,
479 method: "session/request_permission",
480 params: {
481 sessionId: "session-1",
482 toolCall: {
483 toolCallId: "tool-1",
484 title: "Allow mock action",
485 },
486 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
487 },
488 headers: [],
489 }),
490 );
491
492 const message = yield* Deferred.await(inboundRequest);
493 assert.deepEqual(message, {
494 _tag: "Request",
495 id: 0,
496 tag: "session/request_permission",
497 payload: {
498 sessionId: "session-1",
499 toolCall: {
500 toolCallId: "tool-1",
501 title: "Allow mock action",
502 },
503 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
504 },
505 headers: [],
506 });
507
508 yield* transport.serverProtocol.send(0, {
509 _tag: "Exit",
510 requestId: 0,
511 exit: {
512 _tag: "Success",
513 value: {
514 outcome: {
515 outcome: "selected",
516 optionId: "allow",
517 },
518 },
519 },
520 });
521
522 const outbound = yield* Queue.take(output);
523 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
524 jsonrpc: "2.0",
525 id: 0,
526 result: {
527 outcome: {
528 outcome: "selected",
529 optionId: "allow",
530 },
531 },
532 });
533 }),
534 );
535
536 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
537 Effect.gen(function* () {
538 const { stdio, input, output } = yield* makeInMemoryStdio();
539 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
540 stdio,
541 serverRequestMethods: new Set(),
542 });
543 const lateResponse = yield* Deferred.make<unknown>();
544
545 yield* transport.clientProtocol
546 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
547 .pipe(Effect.forkScoped);
548
549 const response = yield* transport
550 .request("x/test", { hello: "world" })
551 .pipe(Effect.forkScoped);
552 const outbound = yield* Queue.take(output);
553 assert.deepEqual(yield* decodeExtRequest(outbound), {
554 jsonrpc: "2.0",
555 id: 1,
556 method: "x/test",
557 params: {
558 hello: "world",
559 },
560 headers: [],
561 });
562
563 yield* Fiber.interrupt(response);
564 yield* Queue.offer(
565 input,
566 yield* encodeJsonl(ExtResponse, {
567 jsonrpc: "2.0",
568 id: 1,
569 result: {
570 ok: true,
571 },
572 }),
573 );
574
575 const message = yield* Deferred.await(lateResponse);
576 assert.deepEqual(message, {
577 _tag: "Exit",
578 requestId: 1,
579 exit: {
580 _tag: "Success",
581 value: {
582 ok: true,
583 },
584 },
585 });
586 }),
587 );
588
589 it.effect("propagates the real child exit code when the input stream ends", () =>
590 Effect.gen(function* () {
591 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
592 const firstMessage = yield* Deferred.make<unknown>();
593 const termination = yield* Deferred.make<AcpError.AcpError>();
594 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
595 stdio: makeChildStdio(handle),
596 terminationError: makeTerminationError(handle),
597 serverRequestMethods: new Set(),
598 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
599 });
600
601 yield* transport.clientProtocol
602 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
603 .pipe(Effect.forkScoped);
604
605 const message = yield* Deferred.await(firstMessage);
606 const exitError = yield* Deferred.await(termination);
607 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
608 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
609 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
610 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
611 readonly _tag: string;
612 readonly message: string;
613 readonly cause: unknown;
614 };
615 assert.equal(defect._tag, "RpcClientDefect");
616 assert.equal(defect.message, "ACP protocol terminated.");
617 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
618 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
619 }),
620 );
621
622 it.effect("classifies an input stream ending without inventing a cause", () =>
623 Effect.gen(function* () {
624 const { stdio, input } = yield* makeInMemoryStdio();
625 const termination = yield* Deferred.make<AcpError.AcpError>();
626 yield* AcpProtocol.makeAcpPatchedProtocol({
627 stdio,
628 serverRequestMethods: new Set(),
629 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
630 });
631
632 yield* Queue.end(input);
633
634 const error = yield* Deferred.await(termination);
635 assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
636 assert.equal(error.message, "ACP input stream ended.");
637 assert.equal("cause" in error, false);
638 }),
639 );
640
641 it.effect("does not emit a second process-exit error after a decode failure", () =>
642 Effect.gen(function* () {
643 const handle = yield* makeHandle({
644 ACP_MOCK_MALFORMED_OUTPUT: "1",
645 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
646 });
647 const terminationCalls = yield* Ref.make(0);
648 const firstMessage = yield* Deferred.make<unknown>();
649 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
650 stdio: makeChildStdio(handle),
651 terminationError: makeTerminationError(handle),
652 serverRequestMethods: new Set(),
653 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
654 });
655
656 yield* transport.clientProtocol
657 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
658 .pipe(Effect.forkScoped);
659
660 const message = yield* Deferred.await(firstMessage);
661 assert.equal(yield* Ref.get(terminationCalls), 1);
662 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
663 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
664 readonly _tag: string;
665 readonly message: string;
666 readonly cause: unknown;
667 };
668 assert.equal(defect._tag, "RpcClientDefect");
669 assert.equal(defect.message, "ACP protocol terminated.");
670 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
671 }),
672 );
673
674 it.effect("keeps client send failure messages independent from the cause", () =>
675 Effect.gen(function* () {
676 const { stdio } = yield* makeInMemoryStdio();
677 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
678 stdio,
679 serverRequestMethods: new Set(),
680 });
681
682 const failure = yield* transport.clientProtocol
683 .send(0, {
684 _tag: "Request",
685 id: "request-1",
686 tag: "x/test",
687 payload: 1n,
688 headers: [],
689 })
690 .pipe(Effect.flip);
691 const defect = failure.reason as {
692 readonly _tag: string;
693 readonly message: string;
694 readonly cause: unknown;
695 };
696
697 assert.equal(defect._tag, "RpcClientDefect");
698 assert.equal(defect.message, "Failed to send ACP protocol message.");
699 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
700 }),
701 );
702
703 it.effect("fails pending extension requests with the propagated exit code", () =>
704 Effect.gen(function* () {
705 const { stdio, input, output } = yield* makeInMemoryStdio();
706 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
707 stdio,
708 terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
709 serverRequestMethods: new Set(),
710 });
711
712 const response = yield* transport
713 .request("x/test", { hello: "world" })
714 .pipe(Effect.forkScoped);
715 yield* Queue.take(output);
716 yield* Queue.end(input);
717
718 const error = yield* Fiber.join(response).pipe(
719 Effect.match({
720 onFailure: (error) => error,
721 onSuccess: () => assert.fail("Expected request to fail after process exit"),
722 }),
723 );
724 assert.instanceOf(error, AcpError.AcpProcessExitedError);
725 assert.equal(error.code, 0);
726 }),
727 );
728
729 for (const operation of ["request", "notification"] as const) {
730 it.effect(`rejects a ${operation} if the connection ends while its logger is running`, () =>
731 Effect.gen(function* () {
732 const { stdio, input, output } = yield* makeInMemoryStdio();
733 const writeStarted = yield* Deferred.make<void>();
734 const releaseWrite = yield* Deferred.make<void>();
735 const terminated = yield* Deferred.make<AcpError.AcpError>();
736 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
737 stdio,
738 serverRequestMethods: new Set(),
739 logOutgoing: true,
740 logger: (event) =>
741 event.stage === "raw"
742 ? Deferred.succeed(writeStarted, undefined).pipe(
743 Effect.andThen(Deferred.await(releaseWrite)),
744 )
745 : Effect.void,
746 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
747 });
748 const send = yield* (
749 operation === "request"
750 ? transport.request("x/test", { hello: "world" })
751 : transport.notify("session/cancel", { sessionId: "session-1" })
752 ).pipe(Effect.forkScoped);
753
754 yield* Deferred.await(writeStarted);
755 yield* Queue.end(input);
756 const error = yield* Deferred.await(terminated);
757 yield* Deferred.succeed(releaseWrite, undefined);
758
759 const failure = yield* Fiber.join(send).pipe(
760 Effect.match({
761 onFailure: (failure) => failure,
762 onSuccess: () => assert.fail("Expected the send to fail after termination"),
763 }),
764 );
765 assert.strictEqual(failure, error);
766 assert.equal(yield* Queue.size(output), 0);
767 }),
768 );
769 }
770});