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

clientTerminals.test.ts

412 lines15.8 KB

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