Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Sink from "effect/Sink";
7import * as TestClock from "effect/testing/TestClock";
8import * as Result from "effect/Result";
9import * as Stream from "effect/Stream";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12
13import {
14 makeAcpClientTerminals,
15 resolveEmbeddedTerminalContent,
16 type AcpClientTerminals,
17} from "./clientTerminals.ts";
18
19const withTerminals = <A, E>(use: (terminals: AcpClientTerminals) => Effect.Effect<A, E>) =>
20 Effect.gen(function* () {
21 const terminals = yield* makeAcpClientTerminals({
22 defaultCwd: process.cwd(),
23 });
24 return yield* use(terminals).pipe(Effect.ensuring(terminals.disposeAll));
25 }).pipe(Effect.provide(NodeServices.layer));
26
27describe("AcpClientTerminals", () => {
28 it.live("runs a command, buffers output, and reports the exit status", () =>
29 withTerminals((terminals) =>
30 Effect.gen(function* () {
31 const created = yield* terminals.create({
32 sessionId: "session",
33 command: process.execPath,
34 args: ["-e", "console.log('hello from acp'); process.exit(3);"],
35 });
36
37 const exit = yield* terminals.waitForExit({
38 sessionId: "session",
39 terminalId: created.terminalId,
40 });
41 expect(exit.exitCode).toBe(3);
42
43 const output = yield* terminals.output({
44 sessionId: "session",
45 terminalId: created.terminalId,
46 });
47 expect(output.output).toContain("hello from acp");
48 expect(output.truncated).toBe(false);
49 expect(output.exitStatus?.exitCode).toBe(3);
50 }),
51 ),
52 );
53
54 it.effect("preserves UTF-8 when stderr interleaves a split stdout character", () =>
55 Effect.gen(function* () {
56 const stdoutStarted = yield* Deferred.make<void>();
57 const stderrWritten = yield* Deferred.make<void>();
58 const child = ChildProcessSpawner.makeHandle({
59 pid: ChildProcessSpawner.ProcessId(1),
60 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
61 exitStatus: Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) }),
62 isRunning: Effect.succeed(false),
63 kill: () => Effect.void,
64 stdin: Sink.drain,
65 stdout: Stream.make(new Uint8Array([0xe2])).pipe(
66 Stream.concat(Stream.fromEffectDrain(Deferred.succeed(stdoutStarted, undefined))),
67 Stream.concat(Stream.fromEffectDrain(Deferred.await(stderrWritten))),
68 Stream.concat(Stream.make(new Uint8Array([0x82, 0xac]))),
69 ),
70 stderr: Stream.fromEffectDrain(Deferred.await(stdoutStarted)).pipe(
71 Stream.concat(Stream.make(new Uint8Array([0x58]))),
72 Stream.concat(Stream.fromEffectDrain(Deferred.succeed(stderrWritten, undefined))),
73 ),
74 all: Stream.empty,
75 getInputFd: () => Sink.drain,
76 getOutputFd: () => Stream.empty,
77 unref: Effect.succeed(Effect.void),
78 });
79 const terminals = yield* makeAcpClientTerminals({ defaultCwd: process.cwd() }).pipe(
80 Effect.provideService(
81 ChildProcessSpawner.ChildProcessSpawner,
82 ChildProcessSpawner.make(() => Effect.succeed(child)),
83 ),
84 );
85 yield* Effect.addFinalizer(() => terminals.disposeAll);
86 const terminal = yield* terminals.create({ sessionId: "session", command: "fixture" });
87 const request = { sessionId: "session", ...terminal };
88 yield* terminals.waitForExit(request);
89
90 const output = yield* terminals.output(request);
91 expect(output.output).toContain("€");
92 expect(output.output).toContain("X");
93 expect(output.output).not.toContain("\uFFFD");
94 expect(output.truncated).toBe(false);
95 expect(terminals.readOutputSnapshot("session", terminal.terminalId)?.output).toBe(
96 output.output,
97 );
98 }),
99 );
100
101 it.live("resolves terminal environment from the requesting ACP session", () =>
102 Effect.gen(function* () {
103 const inheritedEnvironment = yield* HostProcess.Environment;
104 const terminals = yield* makeAcpClientTerminals({
105 defaultCwd: process.cwd(),
106 environmentForSession: (sessionId) =>
107 sessionId === "unknown"
108 ? undefined
109 : {
110 T3_ACP_MCP_AUTHORIZATION: sessionId === "session-a" ? "token-a" : "token-b",
111 T3CODE_THREAD_ID: sessionId,
112 },
113 });
114 yield* Effect.addFinalizer(() => terminals.disposeAll);
115 inheritedEnvironment.T3_TEST_INHERITED = "refreshed";
116
117 for (const [sessionId, expected] of [
118 ["session-a", "token-a||session-a|refreshed|T3_TEST_OVERRIDE=request"],
119 ["session-b", "token-b||session-b|refreshed|T3_TEST_OVERRIDE=request"],
120 ["unknown", "|||refreshed|T3_TEST_OVERRIDE=inherited"],
121 ] as const) {
122 const created = yield* terminals.create({
123 sessionId,
124 command: process.execPath,
125 args: [
126 "-e",
127 "const env = process.env; process.stdout.write([env.T3_ACP_MCP_AUTHORIZATION ?? '', env.t3_Acp_Mcp_Endpoint ?? '', env.T3CODE_THREAD_ID ?? '', env.T3_TEST_INHERITED, ...Object.keys(env).filter((name) => name.toUpperCase() === 'T3_TEST_OVERRIDE').map((name) => name + '=' + env[name])].join('|'))",
128 ],
129 ...(sessionId === "unknown"
130 ? {}
131 : {
132 env: [
133 { name: "T3_TEST_OVERRIDE", value: "first" },
134 { name: "t3_Test_Override", value: "second" },
135 { name: "T3_TEST_OVERRIDE", value: "request" },
136 ],
137 }),
138 });
139 yield* terminals.waitForExit({ sessionId, terminalId: created.terminalId });
140 const output = yield* terminals.output({ sessionId, terminalId: created.terminalId });
141 expect(output.output).toBe(expected);
142 }
143 }).pipe(
144 Effect.provideService(HostProcess.Environment, {
145 ...process.env,
146 T3_ACP_MCP_AUTHORIZATION: "launching-thread-token",
147 t3_Acp_Mcp_Endpoint: "launching-thread-endpoint",
148 T3CODE_THREAD_ID: "launching-thread",
149 T3_TEST_INHERITED: "kept",
150 T3_TEST_OVERRIDE: "inherited",
151 }),
152 // Exercise Windows' case-insensitive variable names on every OS.
153 Effect.provideService(HostProcess.Platform, "win32"),
154 Effect.provide(NodeServices.layer),
155 ),
156 );
157
158 it.live("runs Devin shell source with arguments, pipes, and session fallback variables", () =>
159 Effect.gen(function* () {
160 const terminals = yield* makeAcpClientTerminals({
161 defaultCwd: process.cwd(),
162 shellCommands: true,
163 environmentForSession: () => ({ T3_ACP_MCP_NODE: "mailbox-probe" }),
164 });
165 yield* Effect.addFinalizer(() => terminals.disposeAll);
166 const terminal = yield* terminals.create({
167 sessionId: "devin",
168 command: 'printf "%s\\n" "$T3_ACP_MCP_NODE" | tr a-z A-Z',
169 });
170 const exit = yield* terminals.waitForExit({ sessionId: "devin", ...terminal });
171 const output = yield* terminals.output({ sessionId: "devin", ...terminal });
172 expect(exit.exitCode).toBe(0);
173 expect(output.output.trim()).toBe("MAILBOX-PROBE");
174 }).pipe(Effect.provide(NodeServices.layer)),
175 );
176
177 it.live.each([
178 { text: "a".repeat(64) + "TAIL", limit: 16 },
179 { text: "€".repeat(16) + "TAIL", limit: 6 },
180 ])("truncates buffered output from the beginning at the $limit byte limit", ({ text, limit }) =>
181 withTerminals((terminals) =>
182 Effect.gen(function* () {
183 const created = yield* terminals.create({
184 sessionId: "session",
185 command: process.execPath,
186 args: ["-e", `process.stdout.write(${JSON.stringify(text)});`],
187 outputByteLimit: limit,
188 });
189 yield* terminals.waitForExit({ sessionId: "session", terminalId: created.terminalId });
190
191 const output = yield* terminals.output({
192 sessionId: "session",
193 terminalId: created.terminalId,
194 });
195 expect(output.truncated).toBe(true);
196 expect(output.output.endsWith("TAIL")).toBe(true);
197 expect(Buffer.byteLength(output.output)).toBeLessThanOrEqual(limit);
198 expect(output.output).not.toContain("\uFFFD");
199 }),
200 ),
201 );
202
203 it.live("kills long-running commands and rejects released terminal handles", () =>
204 withTerminals((terminals) =>
205 Effect.gen(function* () {
206 const created = yield* terminals.create({
207 sessionId: "session",
208 command: process.execPath,
209 args: ["-e", "setInterval(() => {}, 1000);"],
210 });
211 yield* terminals.kill({ sessionId: "session", terminalId: created.terminalId });
212 const exit = yield* terminals.waitForExit({
213 sessionId: "session",
214 terminalId: created.terminalId,
215 });
216 expect(exit.exitCode === 0 ? null : exit.exitCode).not.toBe(0);
217 // Windows has no signals: a killed process only reports an exit code.
218 if (yield* HostProcess.isWindows) {
219 expect(exit.signal).toBeNull();
220 } else {
221 expect(exit.signal).toBe("SIGTERM");
222 }
223
224 yield* terminals.release({ sessionId: "session", terminalId: created.terminalId });
225 const rejected = yield* Effect.flip(
226 terminals.output({ sessionId: "session", terminalId: created.terminalId }),
227 );
228 expect(rejected.message).toContain("unknown terminal ID");
229
230 expect(terminals.readOutputSnapshot("session", created.terminalId)).toBeDefined();
231 }),
232 ),
233 );
234
235 it.effect("answers wait_for_exit when a background child keeps the output pipes open", () =>
236 Effect.gen(function* () {
237 // Models `sh -c "setsid server & echo done"`: sh exits, the orphan inherits stdout/stderr.
238 const orphanExited = yield* Deferred.make<void>();
239 const heldOpen = Stream.fromEffectDrain(Deferred.await(orphanExited));
240 const child = ChildProcessSpawner.makeHandle({
241 pid: ChildProcessSpawner.ProcessId(1),
242 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
243 exitStatus: Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) }),
244 isRunning: Effect.succeed(false),
245 kill: () => Effect.void,
246 stdin: Sink.drain,
247 stdout: Stream.make(new TextEncoder().encode("done\n")).pipe(Stream.concat(heldOpen)),
248 stderr: heldOpen,
249 all: Stream.empty,
250 getInputFd: () => Sink.drain,
251 getOutputFd: () => Stream.empty,
252 unref: Effect.succeed(Effect.void),
253 });
254 const terminals = yield* makeAcpClientTerminals({ defaultCwd: process.cwd() }).pipe(
255 Effect.provideService(
256 ChildProcessSpawner.ChildProcessSpawner,
257 ChildProcessSpawner.make(() => Effect.succeed(child)),
258 ),
259 );
260 yield* Effect.addFinalizer(() =>
261 Deferred.succeed(orphanExited, undefined).pipe(Effect.andThen(terminals.disposeAll)),
262 );
263 const terminal = yield* terminals.create({ sessionId: "session", command: "fixture" });
264 const request = { sessionId: "session", ...terminal };
265 const waiting = yield* terminals.waitForExit(request).pipe(Effect.forkChild);
266
267 yield* TestClock.adjust("5 seconds");
268 expect(waiting.pollUnsafe()).toBeDefined();
269 expect(yield* Fiber.join(waiting)).toEqual({ exitCode: 0, signal: null });
270 const output = yield* terminals.output(request);
271 expect(output.output).toBe("done\n");
272 expect(output.exitStatus).toEqual({ exitCode: 0, signal: null });
273 }),
274 );
275
276 it.effect.each([
277 { deadline: "default", forceKillAfter: undefined, deadlineMillis: 5000 },
278 { deadline: "configured", forceKillAfter: "250 millis" as const, deadlineMillis: 250 },
279 ])(
280 "waits for the $deadline deadline before force-killing a SIGTERM-ignoring terminal",
281 ({ forceKillAfter, deadlineMillis }) =>
282 Effect.gen(function* () {
283 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
284 const child = ChildProcessSpawner.makeHandle({
285 pid: ChildProcessSpawner.ProcessId(1),
286 exitCode: Deferred.await(exited),
287 exitStatus: Effect.map(Deferred.await(exited), (code) => ({
288 _tag: "Exited",
289 code,
290 })),
291 isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
292 // Model a process that only exits when the spawner escalates after its deadline.
293 kill: (options) =>
294 options?.forceKillAfter === undefined
295 ? Deferred.await(exited).pipe(Effect.asVoid)
296 : Effect.sleep(options.forceKillAfter).pipe(
297 Effect.andThen(Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137))),
298 Effect.asVoid,
299 ),
300 stdin: Sink.drain,
301 stdout: Stream.empty,
302 stderr: Stream.empty,
303 all: Stream.empty,
304 getInputFd: () => Sink.drain,
305 getOutputFd: () => Stream.empty,
306 unref: Effect.succeed(Effect.void),
307 });
308 const terminals = yield* makeAcpClientTerminals({
309 defaultCwd: process.cwd(),
310 ...(forceKillAfter === undefined ? {} : { forceKillAfter }),
311 }).pipe(
312 Effect.provideService(
313 ChildProcessSpawner.ChildProcessSpawner,
314 ChildProcessSpawner.make(() => Effect.succeed(child)),
315 ),
316 );
317 yield* Effect.addFinalizer(() =>
318 Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137)).pipe(
319 Effect.andThen(terminals.disposeAll),
320 ),
321 );
322 const terminal = yield* terminals.create({
323 sessionId: "session",
324 command: "ignores-SIGTERM",
325 });
326 const request = { sessionId: "session", ...terminal };
327 const killing = yield* terminals.kill(request).pipe(Effect.forkChild);
328 const waiting = yield* terminals.waitForExit(request).pipe(Effect.forkChild);
329
330 yield* TestClock.adjust(deadlineMillis - 1);
331 expect(yield* child.isRunning).toBe(true);
332 expect(killing.pollUnsafe()).toBeUndefined();
333 expect(waiting.pollUnsafe()).toBeUndefined();
334 yield* TestClock.adjust("1 millis");
335 expect(yield* child.isRunning).toBe(false);
336 yield* Fiber.join(killing);
337 expect(yield* Fiber.join(waiting)).toEqual({ exitCode: 137, signal: null });
338 }),
339 );
340
341 it.live("force-kills commands that ignore SIGTERM and resolves wait_for_exit", () =>
342 Effect.gen(function* () {
343 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
344 const ready = yield* Deferred.make<void>();
345 const spawned = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>();
346 let stdout = "";
347 const terminals = yield* makeAcpClientTerminals({
348 defaultCwd: process.cwd(),
349 forceKillAfter: "50 millis",
350 }).pipe(
351 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, {
352 ...spawner,
353 spawn: (command) =>
354 spawner.spawn(command).pipe(
355 Effect.tap((child) => Deferred.succeed(spawned, child)),
356 Effect.map((child) => ({
357 ...child,
358 stdout: child.stdout.pipe(
359 Stream.tap((chunk) => {
360 stdout += Buffer.from(chunk).toString("utf8");
361 return stdout.includes("ready")
362 ? Deferred.succeed(ready, undefined)
363 : Effect.void;
364 }),
365 ),
366 })),
367 ),
368 }),
369 );
370 yield* Effect.addFinalizer(() => terminals.disposeAll);
371 const terminal = yield* terminals.create({
372 sessionId: "session",
373 command: process.execPath,
374 args: [
375 "-e",
376 "process.on('SIGTERM', () => {}); console.log('ready'); setInterval(() => {}, 1000);",
377 ],
378 });
379 const child = yield* Deferred.await(spawned);
380 // Reap only this test's captured child, including when the regression fails.
381 yield* Effect.addFinalizer(() => child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore));
382 yield* Deferred.await(ready);
383
384 const request = { sessionId: "session", ...terminal };
385 yield* terminals.kill(request);
386 const exit = yield* terminals.waitForExit(request);
387 // Windows has no signals: the command is terminated without a signal name.
388 if (!(yield* HostProcess.isWindows)) {
389 expect(exit).toEqual({ exitCode: null, signal: "SIGKILL" });
390 }
391 expect(yield* child.isRunning).toBe(false);
392 }).pipe(Effect.provide(NodeServices.layer)),
393 );
394
395 it.live("reserves terminal capacity across concurrent creates", () =>
396 withTerminals((terminals) =>
397 Effect.gen(function* () {
398 const results = yield* Effect.all(
399 Array.from({ length: 17 }, () =>
400 terminals
401 .create({
402 sessionId: "session",
403 command: process.execPath,
404 args: ["-e", "setInterval(() => {}, 1000);"],
405 })
406 .pipe(Effect.result),
407 ),
408 { concurrency: "unbounded" },
409 );
410
411 expect(results.filter(Result.isSuccess)).toHaveLength(16);
412 expect(results.filter(Result.isFailure)).toHaveLength(1);
413 }),
414 ),
415 );
416
417 it.live("bounds unreleased terminal handles without invalidating existing ids", () =>
418 withTerminals((terminals) =>
419 Effect.gen(function* () {
420 const terminalIds: string[] = [];
421 for (let index = 0; index < 64; index += 1) {
422 const created = yield* terminals.create({
423 sessionId: "session",
424 command: process.execPath,
425 args: ["-e", `process.stdout.write('${index}');`],
426 });
427 yield* terminals.waitForExit({
428 sessionId: "session",
429 terminalId: created.terminalId,
430 });
431 terminalIds.push(created.terminalId);
432 }
433
434 const rejected = yield* terminals
435 .create({
436 sessionId: "session",
437 command: process.execPath,
438 args: ["-e", ""],
439 })
440 .pipe(Effect.result);
441 expect(Result.isFailure(rejected)).toBe(true);
442 expect(terminals.readOutputSnapshot("session", terminalIds[0]!)).toBeDefined();
443 expect(terminals.readOutputSnapshot("session", terminalIds.at(-1)!)).toBeDefined();
444 }),
445 ),
446 );
447
448 it.live("bounds aggregate output retained across unreleased terminals", () =>
449 withTerminals((terminals) =>
450 Effect.gen(function* () {
451 const terminalIds: string[] = [];
452 for (let index = 0; index < 3; index += 1) {
453 const created = yield* terminals.create({
454 sessionId: "session",
455 command: process.execPath,
456 args: ["-e", "process.stdout.write('x'.repeat(8 * 1024 * 1024));"],
457 outputByteLimit: 8 * 1024 * 1024,
458 });
459 yield* terminals.waitForExit({
460 sessionId: "session",
461 terminalId: created.terminalId,
462 });
463 terminalIds.push(created.terminalId);
464 }
465
466 const snapshots = terminalIds.map((terminalId) =>
467 terminals.readOutputSnapshot("session", terminalId)!,
468 );
469 const retainedBytes = snapshots.reduce(
470 (total, snapshot) => total + Buffer.byteLength(snapshot.output),
471 0,
472 );
473 expect(retainedBytes).toBeLessThanOrEqual(16 * 1024 * 1024);
474 expect(snapshots.some((snapshot) => snapshot.truncated)).toBe(true);
475 }),
476 ),
477 );
478
479 it.live("rejects terminal handles from a different ACP session", () =>
480 withTerminals((terminals) =>
481 Effect.gen(function* () {
482 const created = yield* terminals.create({
483 sessionId: "owner-session",
484 command: process.execPath,
485 args: ["-e", "process.stdout.write('owned');"],
486 });
487 const foreignRequest = {
488 sessionId: "foreign-session",
489 terminalId: created.terminalId,
490 };
491 const results = yield* Effect.forEach(
492 [
493 terminals.output(foreignRequest),
494 terminals.waitForExit(foreignRequest),
495 terminals.kill(foreignRequest),
496 terminals.release(foreignRequest),
497 ],
498 (effect) => effect.pipe(Effect.result),
499 { concurrency: "unbounded" },
500 );
501
502 expect(results.every(Result.isFailure)).toBe(true);
503 expect(terminals.readOutputSnapshot("foreign-session", created.terminalId)).toBeUndefined();
504 expect(terminals.readOutputSnapshot("owner-session", created.terminalId)).toBeDefined();
505 }),
506 ),
507 );
508});
509
510describe("resolveEmbeddedTerminalContent", () => {
511 it("rewrites terminal content into text from the buffered snapshot", () => {
512 const notification = {
513 sessionId: "session",
514 update: {
515 sessionUpdate: "tool_call_update" as const,
516 toolCallId: "call-1",
517 content: [
518 { type: "content" as const, content: { type: "text" as const, text: "before" } },
519 { type: "terminal" as const, terminalId: "t3-term-1" },
520 { type: "terminal" as const, terminalId: "t3-term-unknown" },
521 ],
522 },
523 };
524
525 const resolved = resolveEmbeddedTerminalContent(notification, (sessionId, terminalId) =>
526 sessionId === "session" && terminalId === "t3-term-1"
527 ? { output: "compiled 3 files", truncated: false, exitStatus: undefined }
528 : undefined,
529 );
530
531 expect(resolved.update).toMatchObject({
532 content: [
533 { type: "content", content: { type: "text", text: "before" } },
534 { type: "content", content: { type: "text", text: "compiled 3 files" } },
535 { type: "content", content: { type: "text", text: "[terminal t3-term-unknown]" } },
536 ],
537 });
538 });
539});