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

protocol.test.ts

693 lines25.6 KB

1import * as Deferred from "effect/Deferred";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as Queue from "effect/Queue";
5import * as Schema from "effect/Schema";
6import * as Stdio from "effect/Stdio";
7import * as Stream from "effect/Stream";
8import * as TestClock from "effect/testing/TestClock";
9​
10import * as NodeServices from "@effect/platform-node/NodeServices";
11import { assert, it } from "@effect/vitest";
12​
13import * as CodexError from "./errors.ts";
14import * as CodexProtocol from "./protocol.ts";
15import { makeInMemoryStdio } from "./_internal/stdio.ts";
16const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
17​
18const encoder = new TextEncoder();
19​
20const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
21​
22const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
23​
24it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
25 it.effect(
26 "encodes requests without a jsonrpc field and routes inbound requests and notifications",
27 () =>
28 Effect.gen(function* () {
29 const { stdio, input, output } = yield* makeInMemoryStdio();
30 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
31​
32 const notificationDeferred =
33 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingNotification>>();
34 const requestDeferred =
35 yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingRequest>>();
36​
37 yield* transport.incomingNotifications.pipe(
38 Stream.take(1),
39 Stream.runCollect,
40 Effect.flatMap((notifications) => Deferred.succeed(notificationDeferred, notifications)),
41 Effect.forkScoped,
42 );
43​
44 yield* transport.incomingRequests.pipe(
45 Stream.take(1),
46 Stream.runCollect,
47 Effect.flatMap((requests) => Deferred.succeed(requestDeferred, requests)),
48 Effect.forkScoped,
49 );
50​
51 yield* transport.notify("initialized");
52 assert.equal(yield* Queue.take(output), '{"method":"initialized"}\n');
53​
54 const initializeParams = {
55 clientInfo: {
56 name: "effect-codex-app-server-test",
57 title: "Effect Codex App Server Test",
58 version: "0.0.0",
59 },
60 capabilities: {
61 experimentalApi: true,
62 optOutNotificationMethods: null,
63 },
64 };
65​
66 const pendingInitialize = yield* transport
67 .request("initialize", initializeParams)
68 .pipe(Effect.forkScoped);
69 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
70 id: 1,
71 method: "initialize",
72 params: initializeParams,
73 });
74​
75 yield* Queue.offer(
76 input,
77 encodeJsonl({
78 method: "item/agentMessage/delta",
79 params: {
80 delta: "Hello from the mock peer.",
81 itemId: "item-1",
82 threadId: "thread-1",
83 turnId: "turn-1",
84 },
85 }),
86 );
87 yield* Queue.offer(
88 input,
89 encodeJsonl({
90 id: 77,
91 method: "item/tool/requestUserInput",
92 params: {
93 itemId: "item-approval-1",
94 threadId: "thread-1",
95 turnId: "turn-1",
96 questions: [
97 {
98 id: "approved",
99 header: "Approve",
100 question: "Continue?",
101 },
102 ],
103 },
104 }),
105 );
106 yield* Queue.offer(
107 input,
108 encodeJsonl({
109 id: 1,
110 result: {
111 userAgent: "mock-codex-app-server",
112 codexHome: "/tmp/codex-home",
113 platformFamily: "unix",
114 platformOs: "macos",
115 },
116 }),
117 );
118​
119 assert.deepEqual(yield* Fiber.join(pendingInitialize), {
120 userAgent: "mock-codex-app-server",
121 codexHome: "/tmp/codex-home",
122 platformFamily: "unix",
123 platformOs: "macos",
124 });
125 assert.deepEqual(yield* Deferred.await(notificationDeferred), [
126 {
127 method: "item/agentMessage/delta",
128 params: {
129 delta: "Hello from the mock peer.",
130 itemId: "item-1",
131 threadId: "thread-1",
132 turnId: "turn-1",
133 },
134 },
135 ]);
136 assert.deepEqual(yield* Deferred.await(requestDeferred), [
137 {
138 id: 77,
139 method: "item/tool/requestUserInput",
140 params: {
141 itemId: "item-approval-1",
142 threadId: "thread-1",
143 turnId: "turn-1",
144 questions: [
145 {
146 id: "approved",
147 header: "Approve",
148 question: "Continue?",
149 },
150 ],
151 },
152 },
153 ]);
154​
155 yield* transport.respond(77, {
156 answers: {
157 approved: {
158 answers: ["yes"],
159 },
160 },
161 });
162 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
163 id: 77,
164 result: {
165 answers: {
166 approved: {
167 answers: ["yes"],
168 },
169 },
170 },
171 });
172​
173 yield* transport.respondError(
174 78,
175 CodexError.CodexAppServerRequestError.methodNotFound("x/test"),
176 );
177 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
178 id: 78,
179 error: {
180 code: -32601,
181 message: "Method not found: x/test",
182 },
183 });
184 }),
185 );
186​
187 it.effect.each([1, 7, 1024])(
188 "preserves JSONL framing and UTF-8 across %i-byte input chunks",
189 (chunkSize) =>
190 Effect.gen(function* () {
191 const { stdio, input } = yield* makeInMemoryStdio();
192 const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
193 const rawLines: Array<unknown> = [];
194 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
195 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
196 stdio,
197 logIncoming: true,
198 logger: (event) =>
199 Effect.sync(() => {
200 if (event.stage === "raw") {
201 rawLines.push(event.payload);
202 }
203 }),
204 onNotification: (notification) =>
205 Effect.sync(() => {
206 notifications.push(notification);
207 }),
208 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
209 });
210​
211 const firstLine = '{"method":"x/first",\r"params":{"text":"hé🙂"}}';
212 const secondLine = '{"method":"x/second","params":{"value":2}}';
213 const finalLine = '{"method":"x/final","params":{"text":"最後"}}\r';
214 const bytes = encoder.encode(`\n \t\r\n${firstLine}\r\n\n${secondLine}\n${finalLine}`);
215 for (let offset = 0; offset < bytes.length; offset += chunkSize) {
216 yield* Queue.offer(input, bytes.subarray(offset, offset + chunkSize));
217 }
218 yield* Queue.end(input);
219​
220 assert.instanceOf(
221 yield* Deferred.await(termination),
222 CodexError.CodexAppServerInputStreamEndedError,
223 );
224 assert.deepEqual(notifications, [
225 { method: "x/first", params: { text: "hé🙂" } },
226 { method: "x/second", params: { value: 2 } },
227 { method: "x/final", params: { text: "最後" } },
228 ]);
229 assert.deepEqual(rawLines, [firstLine, secondLine, finalLine]);
230 }),
231 );
232​
233 it.effect.each(["newline-terminated", "unfinished"])(
234 "rejects an oversized %s message using UTF-8 bytes before logging or parsing",
235 (framing) =>
236 Effect.gen(function* () {
237 const { stdio, input, output } = yield* makeInMemoryStdio();
238 const notifications: Array<CodexProtocol.CodexAppServerIncomingNotification> = [];
239 const logged: Array<unknown> = [];
240 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
241 let reachedEnd = false;
242 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
243 stdio: Stdio.make({
244 ...stdio,
245 stdin: stdio.stdin.pipe(
246 Stream.concat(
247 Stream.suspend(() => {
248 reachedEnd = true;
249 return Stream.empty;
250 }),
251 ),
252 ),
253 }),
254 maxIncomingMessageBytes: 16,
255 logIncoming: true,
256 logger: (event) =>
257 Effect.sync(() => {
258 logged.push(event.payload);
259 }),
260 onNotification: (notification) =>
261 Effect.sync(() => {
262 notifications.push(notification);
263 }),
264 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
265 });
266 const pending = yield* Effect.forEach(["thread/read", "thread/list"], (method) =>
267 transport.request(method, {}).pipe(Effect.forkScoped),
268 );
269 yield* Effect.forEach(pending, () => Queue.take(output));
270​
271 // Two 16-byte lines must survive; the 17-byte line is only 15 UTF-16 code units.
272 const firstLine = '{"method":"xé"}';
273 const secondLine = '{"method":"x/a"}';
274 const bytes = encoder.encode(
275 `${firstLine}\n${secondLine}\n{"method":"éé"}${framing === "unfinished" ? "" : "\n"}`,
276 );
277 // Split a UTF-8 sequence on both sides of the byte limit.
278 const firstSplit = bytes.indexOf(0xc3) + 1;
279 yield* Queue.offer(input, bytes.subarray(0, firstSplit));
280 if (framing === "unfinished") {
281 const lastSplit = bytes.lastIndexOf(0xc3) + 1;
282 yield* Queue.offer(input, bytes.subarray(firstSplit, lastSplit));
283 yield* Queue.offer(input, bytes.subarray(lastSplit));
284 } else {
285 yield* Queue.offer(input, bytes.subarray(firstSplit));
286 }
287 yield* Queue.end(input);
288​
289 const error = yield* Deferred.await(termination);
290 assert.instanceOf(error, CodexError.CodexAppServerTransportError);
291 assert.equal(error.operation, "read-input-stream");
292 assert.isFalse(reachedEnd, "Must reject the unfinished line before reading EOF");
293 for (const response of pending) {
294 const failure = yield* Fiber.join(response).pipe(
295 Effect.match({
296 onFailure: (error) => error,
297 onSuccess: () => assert.fail("Expected the oversized message to fail the request"),
298 }),
299 );
300 assert.strictEqual(failure, error);
301 }
302 assert.deepEqual(notifications, [{ method: "xé" }, { method: "x/a" }]);
303 assert.deepEqual(logged, [firstLine, { method: "xé" }, secondLine, { method: "x/a" }]);
304 }),
305 );
306​
307 it.effect("reports a malformed fragmented final line before input stream termination", () =>
308 Effect.gen(function* () {
309 const { stdio, input, output } = yield* makeInMemoryStdio();
310 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
311 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
312 stdio,
313 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
314 });
315 const response = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
316 yield* Queue.take(output);
317​
318 yield* Queue.offer(input, encoder.encode('{"id":1,'));
319 yield* Queue.offer(input, encoder.encode('"result":'));
320 yield* Queue.end(input);
321​
322 const error = yield* Deferred.await(termination);
323 assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
324 assert.equal(error.operation, "decode-wire-message");
325 const responseError = yield* Fiber.join(response).pipe(
326 Effect.match({
327 onFailure: (failure) => failure,
328 onSuccess: () => assert.fail("Expected the malformed response to fail the request"),
329 }),
330 );
331 assert.strictEqual(responseError, error);
332 }),
333 );
334​
335 it.effect("keeps processing protocol messages while an approval is pending", () =>
336 Effect.gen(function* () {
337 const { stdio, input, output } = yield* makeInMemoryStdio();
338 const approvalStarted = yield* Deferred.make<void>();
339 const approvalDecision = yield* Deferred.make<{ readonly decision: string }>();
340 const notificationReceived = yield* Deferred.make<void>();
341 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
342 stdio,
343 onRequest: () =>
344 Deferred.succeed(approvalStarted, undefined).pipe(
345 Effect.andThen(Deferred.await(approvalDecision)),
346 ),
347 onNotification: () => Deferred.succeed(notificationReceived, undefined).pipe(Effect.asVoid),
348 });
349​
350 const pendingRequest = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
351 yield* Queue.take(output);
352 yield* Queue.offer(
353 input,
354 encoder.encode(
355 `${[
356 encodeUnknownJsonString({ id: 7, method: "item/tool/requestUserInput", params: {} }),
357 encodeUnknownJsonString({ method: "item/agentMessage/delta", params: { delta: "ok" } }),
358 encodeUnknownJsonString({ id: 1, result: { threadId: "thread-1" } }),
359 ].join("\n")}\n`,
360 ),
361 );
362​
363 yield* Deferred.await(approvalStarted);
364 yield* Deferred.await(notificationReceived);
365 assert.deepEqual(yield* Fiber.join(pendingRequest), { threadId: "thread-1" });
366​
367 yield* Deferred.succeed(approvalDecision, { decision: "accept" });
368 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
369 id: 7,
370 result: { decision: "accept" },
371 });
372 }),
373 );
374​
375 it.effect("rejects incoming requests after the active handler limit is reached", () =>
376 Effect.gen(function* () {
377 const { stdio, input, output } = yield* makeInMemoryStdio();
378 const handlersStarted = yield* Deferred.make<void>();
379 const releaseHandlers = yield* Deferred.make<void>();
380 let activeHandlers = 0;
381 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
382 stdio,
383 onRequest: () =>
384 Effect.sync(() => ++activeHandlers).pipe(
385 Effect.flatMap((count) =>
386 count === 32
387 ? Deferred.succeed(handlersStarted, undefined).pipe(Effect.asVoid)
388 : Effect.void,
389 ),
390 Effect.andThen(Deferred.await(releaseHandlers)),
391 Effect.as({ decision: "accept" }),
392 ),
393 });
394​
395 const requests = Array.from({ length: 33 }, (_, index) =>
396 encodeUnknownJsonString({
397 id: index + 1,
398 method: "item/tool/requestUserInput",
399 params: {},
400 }),
401 );
402 yield* Queue.offer(input, encoder.encode(`${requests.join("\n")}\n`));
403 yield* Deferred.await(handlersStarted);
404​
405 assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
406 id: 33,
407 error: {
408 code: -32001,
409 message: "Too many Codex requests are already active.",
410 },
411 });
412 assert.equal(activeHandlers, 32);
413​
414 yield* Deferred.succeed(releaseHandlers, undefined);
415 yield* Effect.forEach(Array.from({ length: 32 }), () => Queue.take(output), {
416 discard: true,
417 });
418 }),
419 );
420​
421 it.effect("interrupts pending request handlers when the protocol terminates", () =>
422 Effect.gen(function* () {
423 const { stdio, input } = yield* makeInMemoryStdio();
424 const approvalStarted = yield* Deferred.make<void>();
425 const approvalInterrupted = yield* Deferred.make<void>();
426 const terminated = yield* Deferred.make<void>();
427 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
428 stdio,
429 onRequest: () =>
430 Deferred.succeed(approvalStarted, undefined).pipe(
431 Effect.andThen(Effect.never),
432 Effect.onInterrupt(() =>
433 Deferred.succeed(approvalInterrupted, undefined).pipe(Effect.asVoid),
434 ),
435 ),
436 onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),
437 });
438​
439 yield* Queue.offer(
440 input,
441 encodeJsonl({ id: 7, method: "item/tool/requestUserInput", params: {} }),
442 );
443 yield* Deferred.await(approvalStarted);
444 yield* Queue.end(input);
445​
446 yield* Deferred.await(approvalInterrupted);
447 yield* Deferred.await(terminated);
448 }),
449 );
450​
451 it.effect("rejects outgoing messages after an approval response cannot be encoded", () =>
452 Effect.gen(function* () {
453 const { stdio: baseStdio, input } = yield* makeInMemoryStdio();
454 const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
455 const readerStopped = yield* Deferred.make<void>();
456 let notificationCount = 0;
457 let requestCount = 0;
458 const stdio = Stdio.make({
459 args: baseStdio.args,
460 stdin: baseStdio.stdin.pipe(
461 Stream.ensuring(Deferred.succeed(readerStopped, undefined).pipe(Effect.asVoid)),
462 ),
463 stdout: baseStdio.stdout,
464 stderr: baseStdio.stderr,
465 });
466 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
467 stdio,
468 onRequest: () =>
469 Effect.sync(() => ++requestCount).pipe(
470 Effect.map((count) => (count === 1 ? { invalid: 1n } : { ok: true })),
471 ),
472 onNotification: () => Effect.sync(() => notificationCount++).pipe(Effect.asVoid),
473 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
474 });
475​
476 yield* Queue.offer(
477 input,
478 encodeJsonl({ id: 7, method: "item/tool/requestUserInput", params: {} }),
479 );
480​
481 const failure = yield* Deferred.await(terminated);
482 assert.instanceOf(failure, CodexError.CodexAppServerProtocolParseError);
483 const requestFailure = yield* transport.request("thread/read", {}).pipe(
484 Effect.match({
485 onFailure: (error) => error,
486 onSuccess: () => assert.fail("Expected a terminated protocol request to fail"),
487 }),
488 );
489 const notificationFailure = yield* transport.notify("initialized").pipe(Effect.flip);
490 assert.strictEqual(requestFailure, failure);
491 assert.strictEqual(notificationFailure, failure);
492 yield* Deferred.await(readerStopped);
493​
494 yield* Queue.offer(
495 input,
496 encoder.encode(
497 `${[
498 encodeUnknownJsonString({ method: "x/late-notification" }),
499 encodeUnknownJsonString({ id: 8, method: "x/late-request" }),
500 ].join("\n")}\n`,
501 ),
502 );
503​
504 assert.equal(notificationCount, 0);
505 assert.equal(requestCount, 1);
506 assert.equal(yield* Queue.size(input), 1);
507 }),
508 );
509​
510 it.effect("fails pending requests before interrupted handler cleanup completes", () =>
511 Effect.gen(function* () {
512 const { stdio, input, output } = yield* makeInMemoryStdio();
513 const handlerStarted = yield* Deferred.make<void>();
514 const finalizerStarted = yield* Deferred.make<void>();
515 const releaseFinalizer = yield* Deferred.make<void>();
516 const terminated = yield* Deferred.make<CodexError.CodexAppServerError>();
517 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
518 stdio,
519 onRequest: () =>
520 Deferred.succeed(handlerStarted, undefined).pipe(
521 Effect.andThen(Effect.never),
522 Effect.onInterrupt(() =>
523 Deferred.succeed(finalizerStarted, undefined).pipe(
524 Effect.andThen(Deferred.await(releaseFinalizer)),
525 ),
526 ),
527 ),
528 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
529 });
530 const pending = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
531 yield* Queue.take(output);
532 yield* Queue.offer(input, encodeJsonl({ id: 7, method: "x/approval" }));
533 yield* Deferred.await(handlerStarted);
534 yield* Queue.end(input);
535​
536 const failure = yield* Deferred.await(terminated);
537 yield* Deferred.await(finalizerStarted);
538 const pendingFailure = yield* Fiber.join(pending).pipe(
539 Effect.match({
540 onFailure: (error) => error,
541 onSuccess: () => assert.fail("Expected the pending request to fail"),
542 }),
543 );
544 assert.strictEqual(pendingFailure, failure);
545​
546 yield* Deferred.succeed(releaseFinalizer, undefined);
547 }),
548 );
549​
550 it.effect("correlates response errors with the originating request", () =>
551 Effect.gen(function* () {
552 const { stdio, input, output } = yield* makeInMemoryStdio();
553 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
554​
555 const response = yield* transport.request("thread/start", {}).pipe(Effect.forkScoped);
556 yield* Queue.take(output);
557 yield* Queue.offer(
558 input,
559 encodeJsonl({
560 id: 1,
561 error: {
562 code: -32602,
563 message: "Invalid params",
564 data: { field: "cwd" },
565 },
566 }),
567 );
568​
569 const error = yield* Fiber.join(response).pipe(
570 Effect.match({
571 onFailure: (error) => error,
572 onSuccess: () => assert.fail("Expected Codex App Server request to fail"),
573 }),
574 );
575 assert.instanceOf(error, CodexError.CodexAppServerRequestError);
576 assert.deepInclude(error, {
577 code: -32602,
578 errorMessage: "Invalid params",
579 method: "thread/start",
580 requestId: "1",
581 operation: "receive-response",
582 });
583 }),
584 );
585​
586 it.effect("logs decode failures without copying the cause or wire payload", () =>
587 Effect.gen(function* () {
588 const secret = "codex-wire-secret-sentinel";
589 const { stdio, input } = yield* makeInMemoryStdio();
590 const events: Array<CodexProtocol.CodexAppServerProtocolLogEvent> = [];
591 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
592 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
593 stdio,
594 logIncoming: true,
595 logger: (event) =>
596 Effect.sync(() => {
597 events.push(event);
598 }),
599 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
600 });
601​
602 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
603 yield* Deferred.await(termination);
604​
605 const event = events.find(({ stage }) => stage === "decode_failed");
606 assert.exists(event);
607 assert.equal(event.direction, "incoming");
608 const payload = event.payload as Record<string, unknown>;
609 assert.equal(payload.operation, "decode-wire-message");
610 assert.isNumber(payload.issueCount);
611 assert.isArray(payload.issueKinds);
612 assert.isNumber(payload.maximumPathDepth);
613 assert.equal("cause" in payload, false);
614 assert.equal("detail" in payload, false);
615 assert.notInclude(encodeUnknownJsonString(event), secret);
616 }),
617 );
618​
619 it.effect("describes unroutable messages with safe structural diagnostics", () =>
620 Effect.gen(function* () {
621 const secret = "codex-unroutable-secret-sentinel";
622 const { stdio, input } = yield* makeInMemoryStdio();
623 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
624 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
625 stdio,
626 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
627 });
628​
629 yield* Queue.offer(
630 input,
631 encodeJsonl({ id: true, method: "thread/start", params: { token: secret } }),
632 );
633​
634 const error = yield* Deferred.await(termination);
635 assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
636 assert.deepInclude(error, {
637 operation: "route-wire-message",
638 method: "thread/start",
639 payloadKind: "object",
640 presentFields: ["id", "method", "params"],
641 });
642 assert.isUndefined(error.requestId);
643 assert.notProperty(error, "detail");
644 assert.notProperty(error, "cause");
645 assert.notInclude(error.message, secret);
646 }),
647 );
648​
649 it.effect("fails pending requests when input ends while the process is still running", () =>
650 Effect.gen(function* () {
651 const { stdio, input, output } = yield* makeInMemoryStdio();
652 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
653 stdio,
654 terminationError: Effect.never,
655 });
656 const pending = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped);
657 yield* Queue.take(output);
658​
659 yield* Queue.end(input);
660 yield* TestClock.adjust("249 millis");
661 assert.isUndefined(pending.pollUnsafe());
662 yield* TestClock.adjust("1 millis");
663​
664 const failure = yield* Fiber.join(pending).pipe(
665 Effect.match({
666 onFailure: (error) => error,
667 onSuccess: () => assert.fail("Expected the pending request to fail"),
668 }),
669 );
670 assert.instanceOf(failure, CodexError.CodexAppServerInputStreamEndedError);
671 }),
672 );
673​
674 it.effect("reports a process exit that follows input end", () =>
675 Effect.gen(function* () {
676 const { stdio, input } = yield* makeInMemoryStdio();
677 const exitError = new CodexError.CodexAppServerProcessExitedError({ code: 1, pid: 123 });
678 const exited = yield* Deferred.make<CodexError.CodexAppServerError>();
679 const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
680 yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
681 stdio,
682 terminationError: Deferred.await(exited),
683 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
684 });
685​
686 yield* Queue.end(input);
687 yield* TestClock.adjust("100 millis");
688 yield* Deferred.succeed(exited, exitError);
689​
690 assert.strictEqual(yield* Deferred.await(termination), exitError);
691 }),
692 );
693});