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

client.test.ts

450 lines15.5 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 { encodeJsonl, jsonRpcRequest, jsonRpcResponse } from "./_internal/shared.ts";
21import { makeInMemoryStdio } from "./_internal/stdio.ts";
22​
23const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
24const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
25const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
26const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
27​
28const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
29 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
30);
31​
32it.layer(NodeServices.layer)("effect-acp client", (it) => {
33 const makeHandle = (env?: Record<string, string>) =>
34 Effect.gen(function* () {
35 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
36 const path = yield* Path.Path;
37 const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
38 cwd: path.join(import.meta.dirname, ".."),
39 shell: process.platform === "win32",
40 ...(env ? { env: { ...process.env, ...env } } : {}),
41 });
42 return yield* spawner.spawn(command);
43 });
44​
45 it.effect("initializes, prompts, receives updates, and handles permission requests", () =>
46 Effect.gen(function* () {
47 const updates = yield* Ref.make<Array<unknown>>([]);
48 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
49 const typedRequests = yield* Ref.make<Array<unknown>>([]);
50 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
51 const handle = yield* makeHandle();
52 const scope = yield* Scope.make();
53 const acpLayer = AcpClient.layerChildProcess(handle);
54 const context = yield* Layer.buildWithScope(acpLayer, scope);
55​
56 const ext = yield* Effect.gen(function* () {
57 const acp = yield* AcpClient.AcpClient;
58​
59 yield* acp.handleRequestPermission(() =>
60 Effect.succeed({
61 outcome: {
62 outcome: "selected",
63 optionId: "allow",
64 },
65 }),
66 );
67 yield* acp.handleElicitation(() =>
68 Effect.succeed({
69 action: {
70 action: "accept",
71 content: {
72 approved: true,
73 },
74 },
75 }),
76 );
77 yield* acp.handleSessionUpdate((notification) =>
78 Ref.update(updates, (current) => [...current, notification]),
79 );
80 yield* acp.handleElicitationComplete((notification) =>
81 Ref.update(elicitationCompletions, (current) => [...current, notification]),
82 );
83 yield* acp.handleExtRequest(
84 "x/typed_request",
85 Schema.Struct({ message: Schema.String }),
86 (payload) =>
87 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
88 Effect.as({
89 ok: true,
90 echoedMessage: payload.message,
91 }),
92 ),
93 );
94 yield* acp.handleExtNotification(
95 "x/typed_notification",
96 Schema.Struct({ count: Schema.Number }),
97 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
98 );
99​
100 const init = yield* acp.agent.initialize({
101 protocolVersion: 1,
102 clientCapabilities: {
103 fs: { readTextFile: false, writeTextFile: false },
104 terminal: false,
105 },
106 clientInfo: {
107 name: "effect-acp-test",
108 version: "0.0.0",
109 },
110 });
111 assert.equal(init.protocolVersion, 1);
112​
113 yield* acp.agent.authenticate({ methodId: "cursor_login" });
114​
115 const session = yield* acp.agent.createSession({
116 cwd: process.cwd(),
117 mcpServers: [],
118 });
119 assert.equal(session.sessionId, "mock-session-1");
120​
121 const prompt = yield* acp.agent.prompt({
122 sessionId: session.sessionId,
123 prompt: [{ type: "text", text: "hello" }],
124 });
125 assert.equal(prompt.stopReason, "end_turn");
126​
127 const streamed = yield* Stream.runCollect(Stream.take(acp.raw.notifications, 2));
128 assert.equal(streamed.length, 2);
129 assert.equal(streamed[0]?._tag, "SessionUpdate");
130 assert.equal(streamed[1]?._tag, "ElicitationComplete");
131 assert.equal((yield* Ref.get(updates)).length, 1);
132 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
133 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
134 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
135​
136 return yield* acp.raw.request("x/echo", {
137 hello: "world",
138 });
139 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
140​
141 assert.deepEqual(ext, {
142 echoedMethod: "x/echo",
143 echoedParams: {
144 hello: "world",
145 },
146 });
147 }),
148 );
149​
150 it.effect(
151 "returns formatted invalid params when a typed extension request payload is wrong",
152 () =>
153 Effect.gen(function* () {
154 const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" });
155 const scope = yield* Scope.make();
156 const acpLayer = AcpClient.layerChildProcess(handle);
157 const context = yield* Layer.buildWithScope(acpLayer, scope);
158​
159 const result = yield* Effect.gen(function* () {
160 const acp = yield* AcpClient.AcpClient;
161​
162 yield* acp.handleRequestPermission(() =>
163 Effect.succeed({
164 outcome: {
165 outcome: "selected",
166 optionId: "allow",
167 },
168 }),
169 );
170 yield* acp.handleElicitation(() =>
171 Effect.succeed({
172 action: {
173 action: "accept",
174 content: {
175 approved: true,
176 },
177 },
178 }),
179 );
180 yield* acp.handleExtRequest(
181 "x/typed_request",
182 Schema.Struct({ message: Schema.String }),
183 () => Effect.succeed({ ok: true }),
184 );
185​
186 yield* acp.agent.initialize({
187 protocolVersion: 1,
188 clientCapabilities: {
189 fs: { readTextFile: false, writeTextFile: false },
190 terminal: false,
191 },
192 clientInfo: {
193 name: "effect-acp-test",
194 version: "0.0.0",
195 },
196 });
197​
198 yield* acp.agent.authenticate({ methodId: "cursor_login" });
199​
200 const session = yield* acp.agent.createSession({
201 cwd: process.cwd(),
202 mcpServers: [],
203 });
204​
205 return yield* Effect.exit(
206 acp.agent.prompt({
207 sessionId: session.sessionId,
208 prompt: [{ type: "text", text: "hello" }],
209 }),
210 );
211 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
212​
213 if (result._tag !== "Failure") {
214 assert.fail("Expected prompt to fail for invalid typed extension payload");
215 }
216 const rendered = Cause.pretty(result.cause);
217 assert.include(rendered, "Invalid x/typed_request payload:");
218 assert.include(rendered, "Expected string, got 123");
219 }),
220 );
221​
222 it.effect("replays buffered notifications to handlers registered after they arrive", () =>
223 Effect.gen(function* () {
224 const updates = yield* Ref.make<Array<unknown>>([]);
225 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
226 const typedRequests = yield* Ref.make<Array<unknown>>([]);
227 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
228 const handle = yield* makeHandle();
229 const scope = yield* Scope.make();
230 const acpLayer = AcpClient.layerChildProcess(handle);
231 const context = yield* Layer.buildWithScope(acpLayer, scope);
232​
233 yield* Effect.gen(function* () {
234 const acp = yield* AcpClient.AcpClient;
235​
236 yield* acp.handleRequestPermission(() =>
237 Effect.succeed({
238 outcome: {
239 outcome: "selected",
240 optionId: "allow",
241 },
242 }),
243 );
244 yield* acp.handleElicitation(() =>
245 Effect.succeed({
246 action: {
247 action: "accept",
248 content: {
249 approved: true,
250 },
251 },
252 }),
253 );
254 yield* acp.handleExtRequest(
255 "x/typed_request",
256 Schema.Struct({ message: Schema.String }),
257 (payload) =>
258 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
259 Effect.as({
260 ok: true,
261 echoedMessage: payload.message,
262 }),
263 ),
264 );
265 yield* acp.handleExtNotification(
266 "x/typed_notification",
267 Schema.Struct({ count: Schema.Number }),
268 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
269 );
270​
271 yield* acp.agent.initialize({
272 protocolVersion: 1,
273 clientCapabilities: {
274 fs: { readTextFile: false, writeTextFile: false },
275 terminal: false,
276 },
277 clientInfo: {
278 name: "effect-acp-test",
279 version: "0.0.0",
280 },
281 });
282 yield* acp.agent.authenticate({ methodId: "cursor_login" });
283​
284 const session = yield* acp.agent.createSession({
285 cwd: process.cwd(),
286 mcpServers: [],
287 });
288 yield* acp.agent.prompt({
289 sessionId: session.sessionId,
290 prompt: [{ type: "text", text: "hello" }],
291 });
292​
293 yield* acp.handleSessionUpdate((notification) =>
294 Ref.update(updates, (current) => [...current, notification]),
295 );
296 yield* acp.handleElicitationComplete((notification) =>
297 Ref.update(elicitationCompletions, (current) => [...current, notification]),
298 );
299​
300 assert.equal((yield* Ref.get(updates)).length, 1);
301 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
302 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
303 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
304 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
305 }),
306 );
307​
308 it.effect("continues dispatching session updates after one handler fails", () =>
309 Effect.gen(function* () {
310 const successfulHandlers = yield* Ref.make(0);
311 const handle = yield* makeHandle();
312 const scope = yield* Scope.make();
313 const acpLayer = AcpClient.layerChildProcess(handle);
314 const context = yield* Layer.buildWithScope(acpLayer, scope);
315​
316 yield* Effect.gen(function* () {
317 const acp = yield* AcpClient.AcpClient;
318​
319 yield* acp.handleRequestPermission(() =>
320 Effect.succeed({
321 outcome: {
322 outcome: "selected",
323 optionId: "allow",
324 },
325 }),
326 );
327 yield* acp.handleElicitation(() =>
328 Effect.succeed({
329 action: {
330 action: "accept",
331 content: {
332 approved: true,
333 },
334 },
335 }),
336 );
337 yield* acp.handleExtRequest(
338 "x/typed_request",
339 Schema.Struct({ message: Schema.String }),
340 () => Effect.succeed({ ok: true }),
341 );
342 yield* acp.handleExtNotification(
343 "x/typed_notification",
344 Schema.Struct({ count: Schema.Number }),
345 () => Effect.void,
346 );
347 yield* acp.handleSessionUpdate(() =>
348 Effect.fail(AcpError.AcpRequestError.internalError("session update handler failed")),
349 );
350 yield* acp.handleSessionUpdate(() => Ref.update(successfulHandlers, (count) => count + 1));
351​
352 yield* acp.agent.initialize({
353 protocolVersion: 1,
354 clientCapabilities: {
355 fs: { readTextFile: false, writeTextFile: false },
356 terminal: false,
357 },
358 clientInfo: {
359 name: "effect-acp-test",
360 version: "0.0.0",
361 },
362 });
363 yield* acp.agent.authenticate({ methodId: "cursor_login" });
364​
365 const session = yield* acp.agent.createSession({
366 cwd: process.cwd(),
367 mcpServers: [],
368 });
369 yield* acp.agent.prompt({
370 sessionId: session.sessionId,
371 prompt: [{ type: "text", text: "hello" }],
372 });
373​
374 assert.equal(yield* Ref.get(successfulHandlers), 1);
375 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
376 }),
377 );
378​
379 it.effect("uses distinct ids for RPC calls and extension requests", () =>
380 Effect.gen(function* () {
381 const { stdio, input, output } = yield* makeInMemoryStdio();
382 const scope = yield* Scope.make();
383 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
384​
385 const initializeFiber = yield* acp.agent
386 .initialize({
387 protocolVersion: 1,
388 clientCapabilities: {
389 fs: { readTextFile: false, writeTextFile: false },
390 terminal: false,
391 },
392 clientInfo: {
393 name: "effect-acp-test",
394 version: "0.0.0",
395 },
396 })
397 .pipe(Effect.forkScoped);
398 const extFiber = yield* acp.raw.request("x/test", { hello: "world" }).pipe(Effect.forkScoped);
399​
400 const firstOutbound = yield* Queue.take(output);
401 const secondOutbound = yield* Queue.take(output);
402​
403 const decodedInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequest));
404 const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
405 const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe(
406 Effect.match({
407 onFailure: () => false,
408 onSuccess: () => true,
409 }),
410 );
411​
412 const initializeRequest = firstIsInitialize
413 ? yield* decodedInitialize(firstOutbound)
414 : yield* decodedInitialize(secondOutbound);
415 const extRequest = firstIsInitialize
416 ? yield* decodedExt(secondOutbound)
417 : yield* decodedExt(firstOutbound);
418​
419 assert.notEqual(initializeRequest.id, extRequest.id);
420​
421 yield* Queue.offer(
422 input,
423 yield* encodeJsonl(InitializeResponse, {
424 jsonrpc: "2.0",
425 id: initializeRequest.id,
426 result: {
427 protocolVersion: 1,
428 agentCapabilities: {},
429 agentInfo: {
430 name: "mock-agent",
431 version: "0.0.0",
432 },
433 },
434 }),
435 );
436 yield* Queue.offer(
437 input,
438 yield* encodeJsonl(ExtResponse, {
439 jsonrpc: "2.0",
440 id: extRequest.id,
441 result: { ok: true },
442 }),
443 );
444​
445 yield* Fiber.join(initializeFiber);
446 assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
447 yield* Scope.close(scope, Exit.void);
448 }),
449 );
450});