Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Result from "effect/Result";
5import { ChildProcessSpawner } from "effect/unstable/process";
6
7import {
8 makeAcpClientTerminals,
9 resolveEmbeddedTerminalContent,
10 type AcpClientTerminals,
11} from "./AcpClientTerminals.ts";
12
13const withTerminals = <A, E>(use: (terminals: AcpClientTerminals) => Effect.Effect<A, E>) =>
14 Effect.gen(function* () {
15 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
16 const terminals = yield* makeAcpClientTerminals({
17 spawner,
18 defaultCwd: process.cwd(),
19 });
20 return yield* use(terminals).pipe(Effect.ensuring(terminals.disposeAll));
21 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
22
23describe("AcpClientTerminals", () => {
24 it.effect("runs a command, buffers output, and reports the exit status", () =>
25 withTerminals((terminals) =>
26 Effect.gen(function* () {
27 const created = yield* terminals.create({
28 sessionId: "session",
29 command: process.execPath,
30 args: ["-e", "console.log('hello from acp'); process.exit(3);"],
31 });
32
33 const exit = yield* terminals.waitForExit({
34 sessionId: "session",
35 terminalId: created.terminalId,
36 });
37 expect(exit.exitCode).toBe(3);
38
39 const output = yield* terminals.output({
40 sessionId: "session",
41 terminalId: created.terminalId,
42 });
43 expect(output.output).toContain("hello from acp");
44 expect(output.truncated).toBe(false);
45 expect(output.exitStatus?.exitCode).toBe(3);
46 }),
47 ),
48 );
49
50 it.effect("resolves terminal environment from the requesting ACP session", () =>
51 Effect.gen(function* () {
52 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
53 const terminals = yield* makeAcpClientTerminals({
54 spawner,
55 defaultCwd: process.cwd(),
56 environmentForSession: (sessionId) => ({
57 T3_TEST_ACP_SESSION_TOKEN: sessionId === "session-a" ? "token-a" : "token-b",
58 }),
59 });
60 yield* Effect.addFinalizer(() => terminals.disposeAll);
61
62 for (const [sessionId, expected] of [
63 ["session-a", "token-a"],
64 ["session-b", "token-b"],
65 ] as const) {
66 const created = yield* terminals.create({
67 sessionId,
68 command: process.execPath,
69 args: ["-e", "process.stdout.write(process.env.T3_TEST_ACP_SESSION_TOKEN ?? '')"],
70 });
71 yield* terminals.waitForExit({ sessionId, terminalId: created.terminalId });
72 const output = yield* terminals.output({ sessionId, terminalId: created.terminalId });
73 expect(output.output).toBe(expected);
74 }
75 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
76 );
77
78 it.effect("truncates buffered output from the beginning at the byte limit", () =>
79 withTerminals((terminals) =>
80 Effect.gen(function* () {
81 const created = yield* terminals.create({
82 sessionId: "session",
83 command: process.execPath,
84 args: ["-e", "process.stdout.write('a'.repeat(64) + 'TAIL');"],
85 outputByteLimit: 16,
86 });
87 yield* terminals.waitForExit({ sessionId: "session", terminalId: created.terminalId });
88
89 const output = yield* terminals.output({
90 sessionId: "session",
91 terminalId: created.terminalId,
92 });
93 expect(output.truncated).toBe(true);
94 expect(output.output.endsWith("TAIL")).toBe(true);
95 expect(output.output.length).toBeLessThanOrEqual(16);
96 }),
97 ),
98 );
99
100 it.effect("kills long-running commands and rejects released terminal handles", () =>
101 withTerminals((terminals) =>
102 Effect.gen(function* () {
103 const created = yield* terminals.create({
104 sessionId: "session",
105 command: process.execPath,
106 args: ["-e", "setInterval(() => {}, 1000);"],
107 });
108 yield* terminals.kill({ sessionId: "session", terminalId: created.terminalId });
109 const exit = yield* terminals.waitForExit({
110 sessionId: "session",
111 terminalId: created.terminalId,
112 });
113 expect(exit.exitCode === 0 ? null : exit.exitCode).not.toBe(0);
114 expect(exit.signal).toBe("SIGTERM");
115
116 yield* terminals.release({ sessionId: "session", terminalId: created.terminalId });
117 const rejected = yield* Effect.flip(
118 terminals.output({ sessionId: "session", terminalId: created.terminalId }),
119 );
120 expect(rejected.message).toContain("unknown terminal ID");
121
122 // Embedded tool-call content still renders released terminals.
123 expect(terminals.readOutputSnapshot("session", created.terminalId)).toBeDefined();
124 }),
125 ),
126 );
127
128 it.effect("reserves terminal capacity across concurrent creates", () =>
129 withTerminals((terminals) =>
130 Effect.gen(function* () {
131 const results = yield* Effect.all(
132 Array.from({ length: 17 }, () =>
133 terminals
134 .create({
135 sessionId: "session",
136 command: process.execPath,
137 args: ["-e", "setInterval(() => {}, 1000);"],
138 })
139 .pipe(Effect.result),
140 ),
141 { concurrency: "unbounded" },
142 );
143
144 expect(results.filter(Result.isSuccess)).toHaveLength(16);
145 expect(results.filter(Result.isFailure)).toHaveLength(1);
146 }),
147 ),
148 );
149
150 it.effect("bounds retained snapshots after terminals are released", () =>
151 withTerminals((terminals) =>
152 Effect.gen(function* () {
153 const terminalIds: string[] = [];
154 for (let index = 0; index < 33; index += 1) {
155 const created = yield* terminals.create({
156 sessionId: "session",
157 command: process.execPath,
158 args: ["-e", `process.stdout.write('${index}');`],
159 });
160 yield* terminals.release({ sessionId: "session", terminalId: created.terminalId });
161 terminalIds.push(created.terminalId);
162 }
163
164 expect(terminals.readOutputSnapshot("session", terminalIds[0]!)).toBeUndefined();
165 expect(terminals.readOutputSnapshot("session", terminalIds.at(-1)!)).toBeDefined();
166 }),
167 ),
168 );
169
170 it.effect("bounds unreleased terminal handles without invalidating existing ids", () =>
171 withTerminals((terminals) =>
172 Effect.gen(function* () {
173 const terminalIds: string[] = [];
174 for (let index = 0; index < 64; index += 1) {
175 const created = yield* terminals.create({
176 sessionId: "session",
177 command: process.execPath,
178 args: ["-e", `process.stdout.write('${index}');`],
179 });
180 yield* terminals.waitForExit({
181 sessionId: "session",
182 terminalId: created.terminalId,
183 });
184 terminalIds.push(created.terminalId);
185 }
186
187 const rejected = yield* terminals
188 .create({
189 sessionId: "session",
190 command: process.execPath,
191 args: ["-e", ""],
192 })
193 .pipe(Effect.result);
194 expect(Result.isFailure(rejected)).toBe(true);
195 expect(terminals.readOutputSnapshot("session", terminalIds[0]!)).toBeDefined();
196 expect(terminals.readOutputSnapshot("session", terminalIds.at(-1)!)).toBeDefined();
197 }),
198 ),
199 );
200
201 it.effect("bounds aggregate output retained across unreleased terminals", () =>
202 withTerminals((terminals) =>
203 Effect.gen(function* () {
204 const terminalIds: string[] = [];
205 for (let index = 0; index < 3; index += 1) {
206 const created = yield* terminals.create({
207 sessionId: "session",
208 command: process.execPath,
209 args: ["-e", "process.stdout.write('x'.repeat(8 * 1024 * 1024));"],
210 outputByteLimit: 8 * 1024 * 1024,
211 });
212 yield* terminals.waitForExit({
213 sessionId: "session",
214 terminalId: created.terminalId,
215 });
216 terminalIds.push(created.terminalId);
217 }
218
219 const snapshots = terminalIds.map((terminalId) =>
220 terminals.readOutputSnapshot("session", terminalId)!,
221 );
222 const retainedBytes = snapshots.reduce(
223 (total, snapshot) => total + Buffer.byteLength(snapshot.output),
224 0,
225 );
226 expect(retainedBytes).toBeLessThanOrEqual(16 * 1024 * 1024);
227 expect(snapshots.some((snapshot) => snapshot.truncated)).toBe(true);
228 }),
229 ),
230 );
231
232 it.effect("rejects terminal handles from a different ACP session", () =>
233 withTerminals((terminals) =>
234 Effect.gen(function* () {
235 const created = yield* terminals.create({
236 sessionId: "owner-session",
237 command: process.execPath,
238 args: ["-e", "process.stdout.write('owned');"],
239 });
240 const foreignRequest = {
241 sessionId: "foreign-session",
242 terminalId: created.terminalId,
243 };
244 const results = yield* Effect.all(
245 [
246 terminals.output(foreignRequest),
247 terminals.waitForExit(foreignRequest),
248 terminals.kill(foreignRequest),
249 terminals.release(foreignRequest),
250 ].map((effect) => effect.pipe(Effect.result)),
251 { concurrency: "unbounded" },
252 );
253
254 expect(results.every(Result.isFailure)).toBe(true);
255 expect(terminals.readOutputSnapshot("foreign-session", created.terminalId)).toBeUndefined();
256 expect(terminals.readOutputSnapshot("owner-session", created.terminalId)).toBeDefined();
257 }),
258 ),
259 );
260});
261
262describe("resolveEmbeddedTerminalContent", () => {
263 it("rewrites terminal content into text from the buffered snapshot", () => {
264 const notification = {
265 sessionId: "session",
266 update: {
267 sessionUpdate: "tool_call_update" as const,
268 toolCallId: "call-1",
269 content: [
270 { type: "content" as const, content: { type: "text" as const, text: "before" } },
271 { type: "terminal" as const, terminalId: "t3-term-1" },
272 { type: "terminal" as const, terminalId: "t3-term-unknown" },
273 ],
274 },
275 };
276
277 const resolved = resolveEmbeddedTerminalContent(notification, (sessionId, terminalId) =>
278 sessionId === "session" && terminalId === "t3-term-1"
279 ? { output: "compiled 3 files", truncated: false, exitStatus: undefined }
280 : undefined,
281 );
282
283 expect(resolved.update).toMatchObject({
284 content: [
285 { type: "content", content: { type: "text", text: "before" } },
286 { type: "content", content: { type: "text", text: "compiled 3 files" } },
287 { type: "content", content: { type: "text", text: "[terminal t3-term-unknown]" } },
288 ],
289 });
290 });
291});