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

client.test.ts

576 lines19.6 KB

1import * as Path from "effect/Path";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as Queue from "effect/Queue";
8import * as Ref from "effect/Ref";
9import * as Schema from "effect/Schema";
10import * as Scope from "effect/Scope";
11import * as Stream from "effect/Stream";
12import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13​
14import * as NodeServices from "@effect/platform-node/NodeServices";
15import { it, assert } from "@effect/vitest";
16​
17import * as AcpClient from "./client.ts";
18import * as AcpSchema from "./_generated/schema.gen.ts";
19import * as AcpError from "./errors.ts";
20import {
21 encodeJsonl,
22 jsonRpcNotification,
23 jsonRpcRequest,
24 jsonRpcResponse,
25} from "./_internal/shared.ts";
26import { makeInMemoryStdio } from "./_internal/stdio.ts";
27​
28const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
29const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
30const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
31const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
32const PromptRequest = jsonRpcRequest("session/prompt", AcpSchema.PromptRequest);
33const PromptResponse = jsonRpcResponse(AcpSchema.PromptResponse);
34const decodePromptRequestLine = Schema.decodeEffect(Schema.fromJsonString(PromptRequest));
35const XAiPromptCompleteNotification = jsonRpcNotification(
36 "_x.ai/session/prompt_complete",
37 Schema.Struct({
38 sessionId: Schema.String,
39 promptId: Schema.String,
40 stopReason: Schema.String,
41 agentResult: Schema.NullOr(Schema.Unknown),
42 }),
43);
44const XAiQueueChangedNotification = jsonRpcNotification(
45 "_x.ai/queue/changed",
46 Schema.Struct({
47 sessionId: Schema.String,
48 entries: Schema.Array(Schema.Unknown),
49 }),
50);
51const XAiSessionsChangedNotification = jsonRpcNotification(
52 "_x.ai/sessions/changed",
53 Schema.Struct({
54 upserted: Schema.Array(Schema.Unknown),
55 removed: Schema.Array(Schema.Unknown),
56 }),
57);
58const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
59 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
60);
61const mockPeerArgs = (path: string) => [path];
62​
63function concatBytes(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
64 const batch = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
65 let offset = 0;
66 for (const chunk of chunks) {
67 batch.set(chunk, offset);
68 offset += chunk.length;
69 }
70 return batch;
72​
73it.layer(NodeServices.layer)("effect-acp client", (it) => {
74 const makeHandle = (env?: Record<string, string>) =>
75 Effect.gen(function* () {
76 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
77 const path = yield* Path.Path;
78 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
79 cwd: path.join(import.meta.dirname, ".."),
80 ...(env ? { env: { ...process.env, ...env } } : {}),
81 });
82 return yield* spawner.spawn(command);
83 });
84​
85 it.effect("initializes, prompts, receives updates, and handles permission requests", () =>
86 Effect.gen(function* () {
87 const updates = yield* Ref.make<Array<unknown>>([]);
88 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
89 const typedRequests = yield* Ref.make<Array<unknown>>([]);
90 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
91 const handle = yield* makeHandle();
92 const scope = yield* Scope.make();
93 const acpLayer = AcpClient.layerChildProcess(handle);
94 const context = yield* Layer.buildWithScope(acpLayer, scope);
95​
96 const ext = yield* Effect.gen(function* () {
97 const acp = yield* AcpClient.AcpClient;
98​
99 yield* acp.handleRequestPermission(() =>
100 Effect.succeed({
101 outcome: {
102 outcome: "selected",
103 optionId: "allow",
104 },
105 }),
106 );
107 yield* acp.handleElicitation(() =>
108 Effect.succeed({
109 action: {
110 action: "accept",
111 content: {
112 approved: true,
113 },
114 },
115 }),
116 );
117 yield* acp.handleSessionUpdate((notification) =>
118 Ref.update(updates, (current) => [...current, notification]),
119 );
120 yield* acp.handleElicitationComplete((notification) =>
121 Ref.update(elicitationCompletions, (current) => [...current, notification]),
122 );
123 yield* acp.handleExtRequest(
124 "x/typed_request",
125 Schema.Struct({ message: Schema.String }),
126 (payload) =>
127 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
128 Effect.as({
129 ok: true,
130 echoedMessage: payload.message,
131 }),
132 ),
133 );
134 yield* acp.handleExtNotification(
135 "x/typed_notification",
136 Schema.Struct({ count: Schema.Number }),
137 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
138 );
139​
140 const init = yield* acp.agent.initialize({
141 protocolVersion: 1,
142 clientCapabilities: {
143 fs: { readTextFile: false, writeTextFile: false },
144 terminal: false,
145 },
146 clientInfo: {
147 name: "effect-acp-test",
148 version: "0.0.0",
149 },
150 });
151 assert.equal(init.protocolVersion, 1);
152​
153 yield* acp.agent.authenticate({ methodId: "cursor_login" });
154​
155 const session = yield* acp.agent.createSession({
156 cwd: process.cwd(),
157 mcpServers: [],
158 });
159 assert.equal(session.sessionId, "mock-session-1");
160​
161 const prompt = yield* acp.agent.prompt({
162 sessionId: session.sessionId,
163 prompt: [{ type: "text", text: "hello" }],
164 });
165 assert.equal(prompt.stopReason, "end_turn");
166​
167 const streamed = yield* Stream.runCollect(Stream.take(acp.raw.notifications, 2));
168 assert.equal(streamed.length, 2);
169 assert.equal(streamed[0]?._tag, "SessionUpdate");
170 assert.equal(streamed[1]?._tag, "ElicitationComplete");
171 assert.equal((yield* Ref.get(updates)).length, 1);
172 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
173 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
174 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
175​
176 return yield* acp.raw.request("x/echo", {
177 hello: "world",
178 });
179 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
180​
181 assert.deepEqual(ext, {
182 echoedMethod: "x/echo",
183 echoedParams: {
184 hello: "world",
185 },
186 });
187 }),
188 );
189​
190 it.effect(
191 "returns structured invalid params without exposing values from typed extension request payloads",
192 () =>
193 Effect.gen(function* () {
194 const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" });
195 const scope = yield* Scope.make();
196 const acpLayer = AcpClient.layerChildProcess(handle);
197 const context = yield* Layer.buildWithScope(acpLayer, scope);
198​
199 const result = yield* Effect.gen(function* () {
200 const acp = yield* AcpClient.AcpClient;
201​
202 yield* acp.handleRequestPermission(() =>
203 Effect.succeed({
204 outcome: {
205 outcome: "selected",
206 optionId: "allow",
207 },
208 }),
209 );
210 yield* acp.handleElicitation(() =>
211 Effect.succeed({
212 action: {
213 action: "accept",
214 content: {
215 approved: true,
216 },
217 },
218 }),
219 );
220 yield* acp.handleExtRequest(
221 "x/typed_request",
222 Schema.Struct({ message: Schema.String }),
223 () => Effect.succeed({ ok: true }),
224 );
225​
226 yield* acp.agent.initialize({
227 protocolVersion: 1,
228 clientCapabilities: {
229 fs: { readTextFile: false, writeTextFile: false },
230 terminal: false,
231 },
232 clientInfo: {
233 name: "effect-acp-test",
234 version: "0.0.0",
235 },
236 });
237​
238 yield* acp.agent.authenticate({ methodId: "cursor_login" });
239​
240 const session = yield* acp.agent.createSession({
241 cwd: process.cwd(),
242 mcpServers: [],
243 });
244​
245 return yield* Effect.exit(
246 acp.agent.prompt({
247 sessionId: session.sessionId,
248 prompt: [{ type: "text", text: "hello" }],
249 }),
250 );
251 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
252​
253 if (result._tag !== "Failure") {
254 assert.fail("Expected prompt to fail for invalid typed extension payload");
255 }
256 const rendered = Cause.pretty(result.cause);
257 assert.include(rendered, "Invalid payload for ACP extension method 'x/typed_request'.");
258 assert.notInclude(rendered, "Expected string, got 123");
259 }),
260 );
261​
262 it.effect("replays buffered notifications to handlers registered after they arrive", () =>
263 Effect.gen(function* () {
264 const updates = yield* Ref.make<Array<unknown>>([]);
265 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
266 const typedRequests = yield* Ref.make<Array<unknown>>([]);
267 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
268 const handle = yield* makeHandle();
269 const scope = yield* Scope.make();
270 const acpLayer = AcpClient.layerChildProcess(handle);
271 const context = yield* Layer.buildWithScope(acpLayer, scope);
272​
273 yield* Effect.gen(function* () {
274 const acp = yield* AcpClient.AcpClient;
275​
276 yield* acp.handleRequestPermission(() =>
277 Effect.succeed({
278 outcome: {
279 outcome: "selected",
280 optionId: "allow",
281 },
282 }),
283 );
284 yield* acp.handleElicitation(() =>
285 Effect.succeed({
286 action: {
287 action: "accept",
288 content: {
289 approved: true,
290 },
291 },
292 }),
293 );
294 yield* acp.handleExtRequest(
295 "x/typed_request",
296 Schema.Struct({ message: Schema.String }),
297 (payload) =>
298 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
299 Effect.as({
300 ok: true,
301 echoedMessage: payload.message,
302 }),
303 ),
304 );
305 yield* acp.handleExtNotification(
306 "x/typed_notification",
307 Schema.Struct({ count: Schema.Number }),
308 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
309 );
310​
311 yield* acp.agent.initialize({
312 protocolVersion: 1,
313 clientCapabilities: {
314 fs: { readTextFile: false, writeTextFile: false },
315 terminal: false,
316 },
317 clientInfo: {
318 name: "effect-acp-test",
319 version: "0.0.0",
320 },
321 });
322 yield* acp.agent.authenticate({ methodId: "cursor_login" });
323​
324 const session = yield* acp.agent.createSession({
325 cwd: process.cwd(),
326 mcpServers: [],
327 });
328 yield* acp.agent.prompt({
329 sessionId: session.sessionId,
330 prompt: [{ type: "text", text: "hello" }],
331 });
332​
333 yield* acp.handleSessionUpdate((notification) =>
334 Ref.update(updates, (current) => [...current, notification]),
335 );
336 yield* acp.handleElicitationComplete((notification) =>
337 Ref.update(elicitationCompletions, (current) => [...current, notification]),
338 );
339​
340 assert.equal((yield* Ref.get(updates)).length, 1);
341 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
342 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
343 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
344 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
345 }),
346 );
347​
348 it.effect("continues dispatching session updates after one handler fails", () =>
349 Effect.gen(function* () {
350 const successfulHandlers = yield* Ref.make(0);
351 const handle = yield* makeHandle();
352 const scope = yield* Scope.make();
353 const acpLayer = AcpClient.layerChildProcess(handle);
354 const context = yield* Layer.buildWithScope(acpLayer, scope);
355​
356 yield* Effect.gen(function* () {
357 const acp = yield* AcpClient.AcpClient;
358​
359 yield* acp.handleRequestPermission(() =>
360 Effect.succeed({
361 outcome: {
362 outcome: "selected",
363 optionId: "allow",
364 },
365 }),
366 );
367 yield* acp.handleElicitation(() =>
368 Effect.succeed({
369 action: {
370 action: "accept",
371 content: {
372 approved: true,
373 },
374 },
375 }),
376 );
377 yield* acp.handleExtRequest(
378 "x/typed_request",
379 Schema.Struct({ message: Schema.String }),
380 () => Effect.succeed({ ok: true }),
381 );
382 yield* acp.handleExtNotification(
383 "x/typed_notification",
384 Schema.Struct({ count: Schema.Number }),
385 () => Effect.void,
386 );
387 yield* acp.handleSessionUpdate(() =>
388 Effect.fail(AcpError.AcpRequestError.internalError("session update handler failed")),
389 );
390 yield* acp.handleSessionUpdate(() => Ref.update(successfulHandlers, (count) => count + 1));
391​
392 yield* acp.agent.initialize({
393 protocolVersion: 1,
394 clientCapabilities: {
395 fs: { readTextFile: false, writeTextFile: false },
396 terminal: false,
397 },
398 clientInfo: {
399 name: "effect-acp-test",
400 version: "0.0.0",
401 },
402 });
403 yield* acp.agent.authenticate({ methodId: "cursor_login" });
404​
405 const session = yield* acp.agent.createSession({
406 cwd: process.cwd(),
407 mcpServers: [],
408 });
409 yield* acp.agent.prompt({
410 sessionId: session.sessionId,
411 prompt: [{ type: "text", text: "hello" }],
412 });
413​
414 assert.equal(yield* Ref.get(successfulHandlers), 1);
415 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
416 }),
417 );
418​
419 it.effect("uses distinct ids for RPC calls and extension requests", () =>
420 Effect.gen(function* () {
421 const { stdio, input, output } = yield* makeInMemoryStdio();
422 const scope = yield* Scope.make();
423 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
424​
425 const initializeFiber = yield* acp.agent
426 .initialize({
427 protocolVersion: 1,
428 clientCapabilities: {
429 fs: { readTextFile: false, writeTextFile: false },
430 terminal: false,
431 },
432 clientInfo: {
433 name: "effect-acp-test",
434 version: "0.0.0",
435 },
436 })
437 .pipe(Effect.forkScoped);
438 const extFiber = yield* acp.raw.request("x/test", { hello: "world" }).pipe(Effect.forkScoped);
439​
440 const firstOutbound = yield* Queue.take(output);
441 const secondOutbound = yield* Queue.take(output);
442​
443 const decodedInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequest));
444 const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
445 const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe(
446 Effect.match({
447 onFailure: () => false,
448 onSuccess: () => true,
449 }),
450 );
451​
452 const initializeRequest = firstIsInitialize
453 ? yield* decodedInitialize(firstOutbound)
454 : yield* decodedInitialize(secondOutbound);
455 const extRequest = firstIsInitialize
456 ? yield* decodedExt(secondOutbound)
457 : yield* decodedExt(firstOutbound);
458​
459 assert.notEqual(initializeRequest.id, extRequest.id);
460​
461 yield* Queue.offer(
462 input,
463 yield* encodeJsonl(InitializeResponse, {
464 jsonrpc: "2.0",
465 id: initializeRequest.id,
466 result: {
467 protocolVersion: 1,
468 agentCapabilities: {},
469 agentInfo: {
470 name: "mock-agent",
471 version: "0.0.0",
472 },
473 },
474 }),
475 );
476 yield* Queue.offer(
477 input,
478 yield* encodeJsonl(ExtResponse, {
479 jsonrpc: "2.0",
480 id: extRequest.id,
481 result: { ok: true },
482 }),
483 );
484​
485 yield* Fiber.join(initializeFiber);
486 assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
487 yield* Scope.close(scope, Exit.void);
488 }),
489 );
490​
491 it.effect(
492 "routes a standard prompt response after Grok extension notifications in the same batch",
493 () =>
494 Effect.gen(function* () {
495 const { stdio, input, output } = yield* makeInMemoryStdio();
496 const scope = yield* Scope.make();
497 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
498​
499 const promptFiber = yield* acp.agent
500 .prompt({
501 sessionId: "grok-session-1",
502 prompt: [{ type: "text", text: "run the ls command" }],
503 })
504 .pipe(Effect.forkScoped);
505​
506 const outbound = yield* Queue.take(output);
507 const decodedPrompt = yield* decodePromptRequestLine(outbound);
508​
509 const responseBatch = concatBytes(
510 yield* Effect.all([
511 encodeJsonl(XAiQueueChangedNotification, {
512 jsonrpc: "2.0",
513 method: "_x.ai/queue/changed",
514 params: { sessionId: "grok-session-1", entries: [] },
515 }),
516 encodeJsonl(XAiPromptCompleteNotification, {
517 jsonrpc: "2.0",
518 method: "_x.ai/session/prompt_complete",
519 params: {
520 sessionId: "grok-session-1",
521 promptId: "prompt-1",
522 stopReason: "end_turn",
523 agentResult: null,
524 },
525 }),
526 encodeJsonl(XAiSessionsChangedNotification, {
527 jsonrpc: "2.0",
528 method: "_x.ai/sessions/changed",
529 params: {
530 upserted: [
531 {
532 sessionId: "grok-session-1",
533 title: null,
534 cwd: process.cwd(),
535 isWorktree: false,
536 modelId: "grok-composer-2.5-fast",
537 yolo: false,
538 activity: "idle",
539 resident: true,
540 lastChangeUnixMs: 1_710_000_000_000,
541 origin: { kind: "local" },
542 },
543 ],
544 removed: [],
545 },
546 }),
547 encodeJsonl(PromptResponse, {
548 jsonrpc: "2.0",
549 id: decodedPrompt.id,
550 result: {
551 stopReason: "end_turn",
552 _meta: {
553 sessionId: "grok-session-1",
554 requestId: "prompt-1",
555 promptId: "prompt-1",
556 modelId: "grok-composer-2.5-fast",
557 },
558 },
559 }),
560 ]),
561 );
562 yield* Queue.offer(input, responseBatch);
563​
564 assert.deepEqual(yield* Fiber.join(promptFiber), {
565 stopReason: "end_turn",
566 _meta: {
567 sessionId: "grok-session-1",
568 requestId: "prompt-1",
569 promptId: "prompt-1",
570 modelId: "grok-composer-2.5-fast",
571 },
572 });
573 yield* Scope.close(scope, Exit.void);
574 }),
575 );
576});