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 unreleased terminal handles without invalidating existing ids", () =>
170 withTerminals((terminals) =>
171 Effect.gen(function* () {
172 const terminalIds: string[] = [];
173 for (let index = 0; index < 64; 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.waitForExit({
180 sessionId: "session",
181 terminalId: created.terminalId,
182 });
183 terminalIds.push(created.terminalId);
184 }
185
186 const rejected = yield* terminals
187 .create({
188 sessionId: "session",
189 command: process.execPath,
190 args: ["-e", ""],
191 })
192 .pipe(Effect.result);
193 expect(Result.isFailure(rejected)).toBe(true);
194 expect(terminals.readOutputSnapshot("session", terminalIds[0]!)).toBeDefined();
195 expect(terminals.readOutputSnapshot("session", terminalIds.at(-1)!)).toBeDefined();
196 }),
197 ),
198 );
199
200 it.effect("bounds aggregate output retained across unreleased terminals", () =>
201 withTerminals((terminals) =>
202 Effect.gen(function* () {
203 const terminalIds: string[] = [];
204 for (let index = 0; index < 3; index += 1) {
205 const created = yield* terminals.create({
206 sessionId: "session",
207 command: process.execPath,
208 args: ["-e", "process.stdout.write('x'.repeat(8 * 1024 * 1024));"],
209 outputByteLimit: 8 * 1024 * 1024,
210 });
211 yield* terminals.waitForExit({
212 sessionId: "session",
213 terminalId: created.terminalId,
214 });
215 terminalIds.push(created.terminalId);
216 }
217
218 const snapshots = terminalIds.map((terminalId) =>
219 terminals.readOutputSnapshot("session", terminalId)!,
220 );
221 const retainedBytes = snapshots.reduce(
222 (total, snapshot) => total + Buffer.byteLength(snapshot.output),
223 0,
224 );
225 expect(retainedBytes).toBeLessThanOrEqual(16 * 1024 * 1024);
226 expect(snapshots.some((snapshot) => snapshot.truncated)).toBe(true);
227 }),
228 ),
229 );
230
231 it.effect("rejects terminal handles from a different ACP session", () =>
232 withTerminals((terminals) =>
233 Effect.gen(function* () {
234 const created = yield* terminals.create({
235 sessionId: "owner-session",
236 command: process.execPath,
237 args: ["-e", "process.stdout.write('owned');"],
238 });
239 const foreignRequest = {
240 sessionId: "foreign-session",
241 terminalId: created.terminalId,
242 };
243 const results = yield* Effect.all(
244 [
245 terminals.output(foreignRequest),
246 terminals.waitForExit(foreignRequest),
247 terminals.kill(foreignRequest),
248 terminals.release(foreignRequest),
249 ].map((effect) => effect.pipe(Effect.result)),
250 { concurrency: "unbounded" },
251 );
252
253 expect(results.every(Result.isFailure)).toBe(true);
254 expect(terminals.readOutputSnapshot("foreign-session", created.terminalId)).toBeUndefined();
255 expect(terminals.readOutputSnapshot("owner-session", created.terminalId)).toBeDefined();
256 }),
257 ),
258 );
259});
260
261describe("resolveEmbeddedTerminalContent", () => {
262 it("rewrites terminal content into text from the buffered snapshot", () => {
263 const notification = {
264 sessionId: "session",
265 update: {
266 sessionUpdate: "tool_call_update" as const,
267 toolCallId: "call-1",
268 content: [
269 { type: "content" as const, content: { type: "text" as const, text: "before" } },
270 { type: "terminal" as const, terminalId: "t3-term-1" },
271 { type: "terminal" as const, terminalId: "t3-term-unknown" },
272 ],
273 },
274 };
275
276 const resolved = resolveEmbeddedTerminalContent(notification, (sessionId, terminalId) =>
277 sessionId === "session" && terminalId === "t3-term-1"
278 ? { output: "compiled 3 files", truncated: false, exitStatus: undefined }
279 : undefined,
280 );
281
282 expect(resolved.update).toMatchObject({
283 content: [
284 { type: "content", content: { type: "text", text: "before" } },
285 { type: "content", content: { type: "text", text: "compiled 3 files" } },
286 { type: "content", content: { type: "text", text: "[terminal t3-term-unknown]" } },
287 ],
288 });
289 });
290});