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

protocol.test.ts

448 lines14.7 KB

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 }));
44​
45const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
46 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
47);
48​
49const makeHandle = (env?: Record<string, string>) =>
50 Effect.gen(function* () {
51 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
52 const path = yield* Path.Path;
53 const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
54 cwd: path.join(import.meta.dirname, ".."),
55 shell: process.platform === "win32",
56 ...(env ? { env: { ...process.env, ...env } } : {}),
57 });
58 return yield* spawner.spawn(command);
59 });
60​
61it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
62 it.effect(
63 "emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
64 () =>
65 Effect.gen(function* () {
66 const { stdio, input, output } = yield* makeInMemoryStdio();
67 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
68 stdio,
69 serverRequestMethods: new Set(),
70 });
71​
72 const notifications =
73 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
74 yield* transport.incoming.pipe(
75 Stream.take(2),
76 Stream.runCollect,
77 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
78 Effect.forkScoped,
79 );
80​
81 yield* transport.notify("session/cancel", { sessionId: "session-1" });
82 const outbound = yield* Queue.take(output);
83 assert.deepEqual(
84 yield* Schema.decodeEffect(Schema.fromJsonString(SessionCancelNotification))(outbound),
85 {
86 jsonrpc: "2.0",
87 method: "session/cancel",
88 params: {
89 sessionId: "session-1",
90 },
91 },
92 );
93​
94 yield* Queue.offer(
95 input,
96 yield* encodeJsonl(SessionUpdateNotification, {
97 jsonrpc: "2.0",
98 method: "session/update",
99 params: {
100 sessionId: "session-1",
101 update: {
102 sessionUpdate: "plan",
103 entries: [
104 {
105 content: "Inspect repository",
106 priority: "high",
107 status: "in_progress",
108 },
109 ],
110 },
111 },
112 }),
113 );
114​
115 yield* Queue.offer(
116 input,
117 yield* encodeJsonl(ElicitationCompleteNotification, {
118 jsonrpc: "2.0",
119 method: "session/elicitation/complete",
120 params: {
121 elicitationId: "elicitation-1",
122 },
123 }),
124 );
125​
126 const [update, completion] = yield* Deferred.await(notifications);
127 assert.equal(update?._tag, "SessionUpdate");
128 assert.equal(completion?._tag, "ElicitationComplete");
129 }),
130 );
131​
132 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
133 Effect.gen(function* () {
134 const { stdio } = yield* makeInMemoryStdio();
135 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
136 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
137 stdio,
138 serverRequestMethods: new Set(),
139 logOutgoing: true,
140 logger: (event) =>
141 Effect.sync(() => {
142 events.push(event);
143 }),
144 });
145​
146 yield* transport.notify("session/cancel", { sessionId: "session-1" });
147​
148 assert.deepEqual(events, [
149 {
150 direction: "outgoing",
151 stage: "decoded",
152 payload: {
153 _tag: "Request",
154 id: "",
155 tag: "session/cancel",
156 payload: {
157 sessionId: "session-1",
158 },
159 headers: [],
160 },
161 },
162 {
163 direction: "outgoing",
164 stage: "raw",
165 payload:
166 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"id":"","headers":[]}\n',
167 },
168 ]);
169 }),
170 );
171​
172 it.effect("fails notification encoding through the declared ACP error channel", () =>
173 Effect.gen(function* () {
174 const { stdio } = yield* makeInMemoryStdio();
175 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
176 stdio,
177 serverRequestMethods: new Set(),
178 });
179​
180 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
181 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
182 assert.equal(bigintError.detail, "Failed to encode ACP message");
183​
184 const circular: Record<string, unknown> = {};
185 circular.self = circular;
186 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
187 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
188 assert.equal(circularError.detail, "Failed to encode ACP message");
189 }),
190 );
191​
192 it.effect("supports generic extension requests over the patched transport", () =>
193 Effect.gen(function* () {
194 const { stdio, input, output } = yield* makeInMemoryStdio();
195 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
196 stdio,
197 serverRequestMethods: new Set(),
198 });
199​
200 const response = yield* transport
201 .request("x/test", { hello: "world" })
202 .pipe(Effect.forkScoped);
203 const outbound = yield* Queue.take(output);
204 assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), {
205 jsonrpc: "2.0",
206 id: 1,
207 method: "x/test",
208 params: {
209 hello: "world",
210 },
211 headers: [],
212 });
213​
214 yield* Queue.offer(
215 input,
216 yield* encodeJsonl(ExtResponse, {
217 jsonrpc: "2.0",
218 id: 1,
219 result: {
220 ok: true,
221 },
222 }),
223 );
224​
225 const resolved = yield* Fiber.join(response);
226 assert.deepEqual(resolved, { ok: true });
227 }),
228 );
229​
230 it.effect("preserves zero-valued ids for inbound core client requests", () =>
231 Effect.gen(function* () {
232 const { stdio, input, output } = yield* makeInMemoryStdio();
233 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
234 stdio,
235 serverRequestMethods: new Set(["session/request_permission"]),
236 });
237 const inboundRequest = yield* Deferred.make<unknown>();
238​
239 yield* transport.serverProtocol
240 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
241 .pipe(Effect.forkScoped);
242​
243 yield* Queue.offer(
244 input,
245 yield* encodeJsonl(RequestPermissionRequest, {
246 jsonrpc: "2.0",
247 id: 0,
248 method: "session/request_permission",
249 params: {
250 sessionId: "session-1",
251 toolCall: {
252 toolCallId: "tool-1",
253 title: "Allow mock action",
254 },
255 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
256 },
257 headers: [],
258 }),
259 );
260​
261 const message = yield* Deferred.await(inboundRequest);
262 assert.deepEqual(message, {
263 _tag: "Request",
264 id: "0",
265 tag: "session/request_permission",
266 payload: {
267 sessionId: "session-1",
268 toolCall: {
269 toolCallId: "tool-1",
270 title: "Allow mock action",
271 },
272 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
273 },
274 headers: [],
275 });
276​
277 yield* transport.serverProtocol.send(0, {
278 _tag: "Exit",
279 requestId: "0",
280 exit: {
281 _tag: "Success",
282 value: {
283 outcome: {
284 outcome: "selected",
285 optionId: "allow",
286 },
287 },
288 },
289 });
290​
291 const outbound = yield* Queue.take(output);
292 assert.deepEqual(
293 yield* Schema.decodeEffect(Schema.fromJsonString(RequestPermissionResponse))(outbound),
294 {
295 jsonrpc: "2.0",
296 id: 0,
297 result: {
298 outcome: {
299 outcome: "selected",
300 optionId: "allow",
301 },
302 },
303 },
304 );
305 }),
306 );
307​
308 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
309 Effect.gen(function* () {
310 const { stdio, input, output } = yield* makeInMemoryStdio();
311 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
312 stdio,
313 serverRequestMethods: new Set(),
314 });
315 const lateResponse = yield* Deferred.make<unknown>();
316​
317 yield* transport.clientProtocol
318 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
319 .pipe(Effect.forkScoped);
320​
321 const response = yield* transport
322 .request("x/test", { hello: "world" })
323 .pipe(Effect.forkScoped);
324 const outbound = yield* Queue.take(output);
325 assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), {
326 jsonrpc: "2.0",
327 id: 1,
328 method: "x/test",
329 params: {
330 hello: "world",
331 },
332 headers: [],
333 });
334​
335 yield* Fiber.interrupt(response);
336 yield* Queue.offer(
337 input,
338 yield* encodeJsonl(ExtResponse, {
339 jsonrpc: "2.0",
340 id: 1,
341 result: {
342 ok: true,
343 },
344 }),
345 );
346​
347 const message = yield* Deferred.await(lateResponse);
348 assert.deepEqual(message, {
349 _tag: "Exit",
350 requestId: "1",
351 exit: {
352 _tag: "Success",
353 value: {
354 ok: true,
355 },
356 },
357 });
358 }),
359 );
360​
361 it.effect("propagates the real child exit code when the input stream ends", () =>
362 Effect.gen(function* () {
363 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
364 const firstMessage = yield* Deferred.make<unknown>();
365 const termination = yield* Deferred.make<AcpError.AcpError>();
366 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
367 stdio: makeChildStdio(handle),
368 terminationError: makeTerminationError(handle),
369 serverRequestMethods: new Set(),
370 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
371 });
372​
373 yield* transport.clientProtocol
374 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
375 .pipe(Effect.forkScoped);
376​
377 const message = yield* Deferred.await(firstMessage);
378 const exitError = yield* Deferred.await(termination);
379 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
380 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
381 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
382 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
383 readonly _tag: string;
384 readonly cause: unknown;
385 };
386 assert.equal(defect._tag, "RpcClientDefect");
387 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
388 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
389 }),
390 );
391​
392 it.effect("does not emit a second process-exit error after a decode failure", () =>
393 Effect.gen(function* () {
394 const handle = yield* makeHandle({
395 ACP_MOCK_MALFORMED_OUTPUT: "1",
396 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
397 });
398 const terminationCalls = yield* Ref.make(0);
399 const firstMessage = yield* Deferred.make<unknown>();
400 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
401 stdio: makeChildStdio(handle),
402 terminationError: makeTerminationError(handle),
403 serverRequestMethods: new Set(),
404 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
405 });
406​
407 yield* transport.clientProtocol
408 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
409 .pipe(Effect.forkScoped);
410​
411 const message = yield* Deferred.await(firstMessage);
412 assert.equal(yield* Ref.get(terminationCalls), 1);
413 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
414 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
415 readonly _tag: string;
416 readonly cause: unknown;
417 };
418 assert.equal(defect._tag, "RpcClientDefect");
419 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
420 }),
421 );
422​
423 it.effect("fails pending extension requests with the propagated exit code", () =>
424 Effect.gen(function* () {
425 const { stdio, input, output } = yield* makeInMemoryStdio();
426 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
427 stdio,
428 terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
429 serverRequestMethods: new Set(),
430 });
431​
432 const response = yield* transport
433 .request("x/test", { hello: "world" })
434 .pipe(Effect.forkScoped);
435 yield* Queue.take(output);
436 yield* Queue.end(input);
437​
438 const error = yield* Fiber.join(response).pipe(
439 Effect.match({
440 onFailure: (error) => error,
441 onSuccess: () => assert.fail("Expected request to fail after process exit"),
442 }),
443 );
444 assert.instanceOf(error, AcpError.AcpProcessExitedError);
445 assert.equal(error.code, 0);
446 }),
447 );
448});