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), Effect.scoped);
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 isRunning: Effect.succeed(false),
62 kill: () => Effect.void,
63 stdin: Sink.drain,
64 stdout: Stream.make(new Uint8Array([0xe2])).pipe(
65 Stream.concat(Stream.fromEffectDrain(Deferred.succeed(stdoutStarted, undefined))),
66 Stream.concat(Stream.fromEffectDrain(Deferred.await(stderrWritten))),
67 Stream.concat(Stream.make(new Uint8Array([0x82, 0xac]))),
68 ),
69 stderr: Stream.fromEffectDrain(Deferred.await(stdoutStarted)).pipe(
70 Stream.concat(Stream.make(new Uint8Array([0x58]))),
71 Stream.concat(Stream.fromEffectDrain(Deferred.succeed(stderrWritten, undefined))),
72 ),
73 all: Stream.empty,
74 getInputFd: () => Sink.drain,
75 getOutputFd: () => Stream.empty,
76 unref: Effect.succeed(Effect.void),
77 });
78 const terminals = yield* makeAcpClientTerminals({ defaultCwd: process.cwd() }).pipe(
79 Effect.provideService(
80 ChildProcessSpawner.ChildProcessSpawner,
81 ChildProcessSpawner.make(() => Effect.succeed(child)),
82 ),
83 );
84 yield* Effect.addFinalizer(() => terminals.disposeAll);
85 const terminal = yield* terminals.create({ sessionId: "session", command: "fixture" });
86 const request = { sessionId: "session", ...terminal };
87 yield* terminals.waitForExit(request);
88
89 const output = yield* terminals.output(request);
90 expect(output.output).toContain("€");
91 expect(output.output).toContain("X");
92 expect(output.output).not.toContain("\uFFFD");
93 expect(output.truncated).toBe(false);
94 expect(terminals.readOutputSnapshot("session", terminal.terminalId)?.output).toBe(
95 output.output,
96 );
97 }).pipe(Effect.scoped),
98 );
99
100 it.live("resolves terminal environment from the requesting ACP session", () =>
101 Effect.gen(function* () {
102 const terminals = yield* makeAcpClientTerminals({
103 defaultCwd: process.cwd(),
104 environmentForSession: (sessionId) => ({
105 T3_TEST_ACP_SESSION_TOKEN: sessionId === "session-a" ? "token-a" : "token-b",
106 }),
107 });
108 yield* Effect.addFinalizer(() => terminals.disposeAll);
109
110 for (const [sessionId, expected] of [
111 ["session-a", "token-a"],
112 ["session-b", "token-b"],
113 ] as const) {
114 const created = yield* terminals.create({
115 sessionId,
116 command: process.execPath,
117 args: ["-e", "process.stdout.write(process.env.T3_TEST_ACP_SESSION_TOKEN ?? '')"],
118 });
119 yield* terminals.waitForExit({ sessionId, terminalId: created.terminalId });
120 const output = yield* terminals.output({ sessionId, terminalId: created.terminalId });
121 expect(output.output).toBe(expected);
122 }
123 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
124 );
125
126 it.live("runs Devin shell source with arguments, pipes, and session fallback variables", () =>
127 Effect.gen(function* () {
128 const terminals = yield* makeAcpClientTerminals({
129 defaultCwd: process.cwd(),
130 shellCommands: true,
131 environmentForSession: () => ({ T3_ACP_MCP_NODE: "mailbox-probe" }),
132 });
133 yield* Effect.addFinalizer(() => terminals.disposeAll);
134 const terminal = yield* terminals.create({
135 sessionId: "devin",
136 command: 'printf "%s\\n" "$T3_ACP_MCP_NODE" | tr a-z A-Z',
137 });
138 const exit = yield* terminals.waitForExit({ sessionId: "devin", ...terminal });
139 const output = yield* terminals.output({ sessionId: "devin", ...terminal });
140 expect(exit.exitCode).toBe(0);
141 expect(output.output.trim()).toBe("MAILBOX-PROBE");
142 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
143 );
144
145 it.live.each([
146 { text: "a".repeat(64) + "TAIL", limit: 16 },
147 { text: "€".repeat(16) + "TAIL", limit: 6 },
148 ])("truncates buffered output from the beginning at the $limit byte limit", ({ text, limit }) =>
149 withTerminals((terminals) =>
150 Effect.gen(function* () {
151 const created = yield* terminals.create({
152 sessionId: "session",
153 command: process.execPath,
154 args: ["-e", `process.stdout.write(${JSON.stringify(text)});`],
155 outputByteLimit: limit,
156 });
157 yield* terminals.waitForExit({ sessionId: "session", terminalId: created.terminalId });
158
159 const output = yield* terminals.output({
160 sessionId: "session",
161 terminalId: created.terminalId,
162 });
163 expect(output.truncated).toBe(true);
164 expect(output.output.endsWith("TAIL")).toBe(true);
165 expect(Buffer.byteLength(output.output)).toBeLessThanOrEqual(limit);
166 expect(output.output).not.toContain("\uFFFD");
167 }),
168 ),
169 );
170
171 it.live("kills long-running commands and rejects released terminal handles", () =>
172 withTerminals((terminals) =>
173 Effect.gen(function* () {
174 const created = yield* terminals.create({
175 sessionId: "session",
176 command: process.execPath,
177 args: ["-e", "setInterval(() => {}, 1000);"],
178 });
179 yield* terminals.kill({ sessionId: "session", terminalId: created.terminalId });
180 const exit = yield* terminals.waitForExit({
181 sessionId: "session",
182 terminalId: created.terminalId,
183 });
184 expect(exit.exitCode === 0 ? null : exit.exitCode).not.toBe(0);
185 // Windows has no signals: a killed process only reports an exit code.
186 if (yield* HostProcess.isWindows) {
187 expect(exit.signal).toBeNull();
188 } else {
189 expect(exit.signal).toBe("SIGTERM");
190 }
191
192 yield* terminals.release({ sessionId: "session", terminalId: created.terminalId });
193 const rejected = yield* Effect.flip(
194 terminals.output({ sessionId: "session", terminalId: created.terminalId }),
195 );
196 expect(rejected.message).toContain("unknown terminal ID");
197
198 expect(terminals.readOutputSnapshot("session", created.terminalId)).toBeDefined();
199 }),
200 ),
201 );
202
203 it.effect.each([
204 { deadline: "default", forceKillAfter: undefined, deadlineMillis: 5000 },
205 { deadline: "configured", forceKillAfter: "250 millis" as const, deadlineMillis: 250 },
206 ])(
207 "waits for the $deadline deadline before force-killing a SIGTERM-ignoring terminal",
208 ({ forceKillAfter, deadlineMillis }) =>
209 Effect.gen(function* () {
210 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
211 const child = ChildProcessSpawner.makeHandle({
212 pid: ChildProcessSpawner.ProcessId(1),
213 exitCode: Deferred.await(exited),
214 isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
215 // Model a process that only exits when the spawner escalates after its deadline.
216 kill: (options) =>
217 options?.forceKillAfter === undefined
218 ? Deferred.await(exited).pipe(Effect.asVoid)
219 : Effect.sleep(options.forceKillAfter).pipe(
220 Effect.andThen(Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137))),
221 Effect.asVoid,
222 ),
223 stdin: Sink.drain,
224 stdout: Stream.empty,
225 stderr: Stream.empty,
226 all: Stream.empty,
227 getInputFd: () => Sink.drain,
228 getOutputFd: () => Stream.empty,
229 unref: Effect.succeed(Effect.void),
230 });
231 const terminals = yield* makeAcpClientTerminals({
232 defaultCwd: process.cwd(),
233 ...(forceKillAfter === undefined ? {} : { forceKillAfter }),
234 }).pipe(
235 Effect.provideService(
236 ChildProcessSpawner.ChildProcessSpawner,
237 ChildProcessSpawner.make(() => Effect.succeed(child)),
238 ),
239 );
240 yield* Effect.addFinalizer(() =>
241 Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137)).pipe(
242 Effect.andThen(terminals.disposeAll),
243 ),
244 );
245 const terminal = yield* terminals.create({
246 sessionId: "session",
247 command: "ignores-SIGTERM",
248 });
249 const request = { sessionId: "session", ...terminal };
250 const killing = yield* terminals.kill(request).pipe(Effect.forkChild);
251 const waiting = yield* terminals.waitForExit(request).pipe(Effect.forkChild);
252
253 yield* TestClock.adjust(deadlineMillis - 1);
254 expect(yield* child.isRunning).toBe(true);
255 expect(killing.pollUnsafe()).toBeUndefined();
256 expect(waiting.pollUnsafe()).toBeUndefined();
257 yield* TestClock.adjust("1 millis");
258 expect(yield* child.isRunning).toBe(false);
259 yield* Fiber.join(killing);
260 expect(yield* Fiber.join(waiting)).toEqual({ exitCode: 137, signal: null });
261 }).pipe(Effect.scoped),
262 );
263
264 it.live("force-kills commands that ignore SIGTERM and resolves wait_for_exit", () =>
265 Effect.gen(function* () {
266 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
267 const ready = yield* Deferred.make<void>();
268 const spawned = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>();
269 let stdout = "";
270 const terminals = yield* makeAcpClientTerminals({
271 defaultCwd: process.cwd(),
272 forceKillAfter: "50 millis",
273 }).pipe(
274 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, {
275 ...spawner,
276 spawn: (command) =>
277 spawner.spawn(command).pipe(
278 Effect.tap((child) => Deferred.succeed(spawned, child)),
279 Effect.map((child) => ({
280 ...child,
281 stdout: child.stdout.pipe(
282 Stream.tap((chunk) => {
283 stdout += Buffer.from(chunk).toString("utf8");
284 return stdout.includes("ready")
285 ? Deferred.succeed(ready, undefined)
286 : Effect.void;
287 }),
288 ),
289 })),
290 ),
291 }),
292 );
293 yield* Effect.addFinalizer(() => terminals.disposeAll);
294 const terminal = yield* terminals.create({
295 sessionId: "session",
296 command: process.execPath,
297 args: [
298 "-e",
299 "process.on('SIGTERM', () => {}); console.log('ready'); setInterval(() => {}, 1000);",
300 ],
301 });
302 const child = yield* Deferred.await(spawned);
303 // Reap only this test's captured child, including when the regression fails.
304 yield* Effect.addFinalizer(() => child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore));
305 yield* Deferred.await(ready);
306
307 const request = { sessionId: "session", ...terminal };
308 yield* terminals.kill(request);
309 const exit = yield* terminals.waitForExit(request);
310 // Windows has no signals: the command is terminated without a signal name.
311 if (!(yield* HostProcess.isWindows)) {
312 expect(exit).toEqual({ exitCode: null, signal: "SIGKILL" });
313 }
314 expect(yield* child.isRunning).toBe(false);
315 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
316 );
317
318 it.live("reserves terminal capacity across concurrent creates", () =>
319 withTerminals((terminals) =>
320 Effect.gen(function* () {
321 const results = yield* Effect.all(
322 Array.from({ length: 17 }, () =>
323 terminals
324 .create({
325 sessionId: "session",
326 command: process.execPath,
327 args: ["-e", "setInterval(() => {}, 1000);"],
328 })
329 .pipe(Effect.result),
330 ),
331 { concurrency: "unbounded" },
332 );
333
334 expect(results.filter(Result.isSuccess)).toHaveLength(16);
335 expect(results.filter(Result.isFailure)).toHaveLength(1);
336 }),
337 ),
338 );
339
340 it.live("bounds unreleased terminal handles without invalidating existing ids", () =>
341 withTerminals((terminals) =>
342 Effect.gen(function* () {
343 const terminalIds: string[] = [];
344 for (let index = 0; index < 64; index += 1) {
345 const created = yield* terminals.create({
346 sessionId: "session",
347 command: process.execPath,
348 args: ["-e", `process.stdout.write('${index}');`],
349 });
350 yield* terminals.waitForExit({
351 sessionId: "session",
352 terminalId: created.terminalId,
353 });
354 terminalIds.push(created.terminalId);
355 }
356
357 const rejected = yield* terminals
358 .create({
359 sessionId: "session",
360 command: process.execPath,
361 args: ["-e", ""],
362 })
363 .pipe(Effect.result);
364 expect(Result.isFailure(rejected)).toBe(true);
365 expect(terminals.readOutputSnapshot("session", terminalIds[0]!)).toBeDefined();
366 expect(terminals.readOutputSnapshot("session", terminalIds.at(-1)!)).toBeDefined();
367 }),
368 ),
369 );
370
371 it.live("bounds aggregate output retained across unreleased terminals", () =>
372 withTerminals((terminals) =>
373 Effect.gen(function* () {
374 const terminalIds: string[] = [];
375 for (let index = 0; index < 3; index += 1) {
376 const created = yield* terminals.create({
377 sessionId: "session",
378 command: process.execPath,
379 args: ["-e", "process.stdout.write('x'.repeat(8 * 1024 * 1024));"],
380 outputByteLimit: 8 * 1024 * 1024,
381 });
382 yield* terminals.waitForExit({
383 sessionId: "session",
384 terminalId: created.terminalId,
385 });
386 terminalIds.push(created.terminalId);
387 }
388
389 const snapshots = terminalIds.map((terminalId) =>
390 terminals.readOutputSnapshot("session", terminalId)!,
391 );
392 const retainedBytes = snapshots.reduce(
393 (total, snapshot) => total + Buffer.byteLength(snapshot.output),
394 0,
395 );
396 expect(retainedBytes).toBeLessThanOrEqual(16 * 1024 * 1024);
397 expect(snapshots.some((snapshot) => snapshot.truncated)).toBe(true);
398 }),
399 ),
400 );
401
402 it.live("rejects terminal handles from a different ACP session", () =>
403 withTerminals((terminals) =>
404 Effect.gen(function* () {
405 const created = yield* terminals.create({
406 sessionId: "owner-session",
407 command: process.execPath,
408 args: ["-e", "process.stdout.write('owned');"],
409 });
410 const foreignRequest = {
411 sessionId: "foreign-session",
412 terminalId: created.terminalId,
413 };
414 const results = yield* Effect.forEach(
415 [
416 terminals.output(foreignRequest),
417 terminals.waitForExit(foreignRequest),
418 terminals.kill(foreignRequest),
419 terminals.release(foreignRequest),
420 ],
421 (effect) => effect.pipe(Effect.result),
422 { concurrency: "unbounded" },
423 );
424
425 expect(results.every(Result.isFailure)).toBe(true);
426 expect(terminals.readOutputSnapshot("foreign-session", created.terminalId)).toBeUndefined();
427 expect(terminals.readOutputSnapshot("owner-session", created.terminalId)).toBeDefined();
428 }),
429 ),
430 );
431});
432
433describe("resolveEmbeddedTerminalContent", () => {
434 it("rewrites terminal content into text from the buffered snapshot", () => {
435 const notification = {
436 sessionId: "session",
437 update: {
438 sessionUpdate: "tool_call_update" as const,
439 toolCallId: "call-1",
440 content: [
441 { type: "content" as const, content: { type: "text" as const, text: "before" } },
442 { type: "terminal" as const, terminalId: "t3-term-1" },
443 { type: "terminal" as const, terminalId: "t3-term-unknown" },
444 ],
445 },
446 };
447
448 const resolved = resolveEmbeddedTerminalContent(notification, (sessionId, terminalId) =>
449 sessionId === "session" && terminalId === "t3-term-1"
450 ? { output: "compiled 3 files", truncated: false, exitStatus: undefined }
451 : undefined,
452 );
453
454 expect(resolved.update).toMatchObject({
455 content: [
456 { type: "content", content: { type: "text", text: "before" } },
457 { type: "content", content: { type: "text", text: "compiled 3 files" } },
458 { type: "content", content: { type: "text", text: "[terminal t3-term-unknown]" } },
459 ],
460 });
461 });
462});