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