Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- Exercise the CLI with isolated executable fixtures.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeFSP from "node:fs/promises";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7import * as NodeStream from "node:stream";
8import * as NodeURL from "node:url";
9
10import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
11import * as NodeServices from "@effect/platform-node/NodeServices";
12import { assert, it } from "@effect/vitest";
13import { TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import * as NetService from "@t3tools/shared/Net";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import { Command } from "effect/cli";
20import * as TestConsole from "effect/testing/TestConsole";
21import { expect, vi } from "vite-plus/test";
22
23import { cli } from "../binCli.ts";
24import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts";
25import { matchAgentAnswer, pickAgent } from "./triage.ts";
26
27const cliPath = NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url));
28
29async function fixture(commands: ReadonlyArray<string>) {
30 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-triage-"));
31 const bin = NodePath.join(root, "bin");
32 const record = NodePath.join(root, "launch.json");
33 await NodeFSP.mkdir(bin);
34 const script = NodePath.join(root, "agent.cjs");
35 await NodeFSP.writeFile(
36 script,
37 `require("node:fs").writeFileSync(process.env.TRIAGE_TEST_RECORD, JSON.stringify({ command: process.argv[2], args: process.argv.slice(3), cwd: process.cwd() }));`,
38 );
39 for (const command of commands) {
40 const windows = HostProcess.Platform.defaultValue() === "win32";
41 const executable = NodePath.join(bin, windows ? `${command}.cmd` : command);
42 const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
43 await NodeFSP.writeFile(
44 executable,
45 windows
46 ? `@"${process.execPath}" "${script}" ${command} %*\r\n`
47 : `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(script)} ${quote(command)} "$@"\n`,
48 { mode: 0o755 },
49 );
50 }
51 return {
52 root,
53 record,
54 run: (args: ReadonlyArray<string>) =>
55 new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
56 const child = NodeChildProcess.spawn(
57 process.execPath,
58 [cliPath, "triage", "--base-dir", NodePath.join(root, "home with spaces"), ...args],
59 {
60 env: {
61 ...process.env,
62 PATH: bin,
63 TRIAGE_TEST_RECORD: record,
64 },
65 stdio: ["ignore", "pipe", "pipe"],
66 },
67 );
68 let stdout = "";
69 let stderr = "";
70 child.stdout.on("data", (data) => (stdout += String(data)));
71 child.stderr.on("data", (data) => (stderr += String(data)));
72 child.once("error", reject);
73 child.once("close", (code) => resolve({ code, stdout, stderr }));
74 }),
75 async [Symbol.asyncDispose]() {
76 await NodeFSP.rm(root, { recursive: true, force: true });
77 },
78 };
79}
80
81it.live.each([
82 { commands: ["agy", "codex"], agent: "antigravity", command: "agy", model: "test-model" },
83 { commands: ["agy"], agent: undefined, command: "agy", model: undefined },
84 { commands: ["agy", "codex"], agent: "codex", command: "codex", model: "test-model" },
85 { commands: ["agy", "codex", "claude"], agent: "claude", command: "claude", model: undefined },
86])(
87 "launches $command with the triage prompt (agent=$agent, model=$model)",
88 ({ commands, agent, command, model }) =>
89 Effect.promise(async () => {
90 await using setup = await fixture(commands);
91 const result = await setup.run([
92 ...(agent === undefined ? [] : ["--agent", agent]),
93 ...(model === undefined ? [] : ["--model", model]),
94 ]);
95 expect(result.code, result.stdout + result.stderr).toBe(0);
96 const launch = JSON.parse(await NodeFSP.readFile(setup.record, "utf8")) as {
97 command: string;
98 args: string[];
99 cwd: string;
100 };
101 expect(launch.command).toBe(command);
102 expect(launch.args.slice(0, -1)).toEqual([
103 ...(model === undefined ? [] : ["--model", model]),
104 ...(command === "agy" ? ["--prompt-interactive"] : []),
105 ]);
106 expect(launch.args.at(-1)).toContain(NodePath.join(launch.cwd, "triage-playbook.md"));
107 expect(
108 await NodeFSP.readFile(NodePath.join(launch.cwd, "triage-playbook.md"), "utf8"),
109 ).toContain("context.md");
110 }),
111);
112
113it.each([
114 { answer: "2", picked: "codex" },
115 { answer: " 1 ", picked: "claude" },
116 { answer: "CLAUDE", picked: "claude" },
117 { answer: "1.5", picked: undefined },
118 { answer: "1x", picked: undefined },
119 { answer: "2codex", picked: undefined },
120 { answer: "3", picked: undefined },
121])("the agent picker reads $answer as $picked", ({ answer, picked }) => {
122 expect(matchAgentAnswer([{ id: "claude" }, { id: "codex" }], answer)?.id).toBe(picked);
123});
124
125it.effect.each([
126 { label: "Ctrl+C", key: "\x03" },
127 { label: "Ctrl+D", key: "\x04" },
128])("returns undefined when the agent picker is cancelled with $label", ({ key }) =>
129 Effect.gen(function* () {
130 const input = new NodeStream.PassThrough();
131 const output = Object.assign(new NodeStream.PassThrough(), { isTTY: true });
132 output.once("data", () => input.write(key));
133
134 const picked = yield* pickAgent(
135 [
136 { id: "claude", label: "Claude Code" },
137 { id: "codex", label: "Codex" },
138 ],
139 input,
140 output,
141 );
142
143 assert.isUndefined(picked);
144 }),
145);
146
147it.live(
148 "requires an explicit choice when Codex and Antigravity are installed without a terminal",
149 () =>
150 Effect.promise(async () => {
151 await using setup = await fixture(["agy", "codex"]);
152 const result = await setup.run([]);
153 expect(result.code).toBe(1);
154 expect(result.stdout + result.stderr).toContain("--agent antigravity");
155 expect(result.stdout + result.stderr).toContain("--agent codex");
156 expect(result.stdout + result.stderr).not.toContain("Starting");
157 await expect(NodeFSP.stat(setup.record)).rejects.toMatchObject({ code: "ENOENT" });
158 }),
159);
160
161it.live("reports the missing agy executable when Antigravity is explicitly requested", () =>
162 Effect.promise(async () => {
163 await using setup = await fixture(["codex"]);
164 const result = await setup.run(["--agent", "antigravity"]);
165 expect(result.code).toBe(1);
166 expect(result.stdout + result.stderr).toContain(
167 "`agy` is not installed or was not found on PATH.",
168 );
169 await expect(NodeFSP.stat(setup.record)).rejects.toMatchObject({ code: "ENOENT" });
170 }),
171);
172
173const FAILING_AGENT_POSIX = `#!/bin/sh
174echo "Error: There is not enough space on the disk. (os error 112)" >&2
175exit 1
176`;
177const FAILING_AGENT_WINDOWS = `@echo Error: There is not enough space on the disk. (os error 112) 1>&2
178@exit /b 1
179`;
180
181it.live("a failed agent launch points at the prompt it could not run", () =>
182 Effect.gen(function* () {
183 const fs = yield* FileSystem.FileSystem;
184 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" });
185 const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" });
186 const codexHome = NodePath.join(baseDir, "codex-home");
187 NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 });
188 NodeFS.writeFileSync(NodePath.join(binDir, "codex.cmd"), FAILING_AGENT_WINDOWS);
189 yield* Effect.acquireRelease(
190 // PATH holds only the fake agent, so a broken fixture can never fall through to a real codex.
191 Effect.sync(() => {
192 vi.stubEnv("PATH", binDir);
193 vi.stubEnv("CODEX_HOME", codexHome);
194 }),
195 () => Effect.sync(() => vi.unstubAllEnvs()),
196 );
197 const previousExitCode = process.exitCode;
198 yield* Effect.addFinalizer(() =>
199 Effect.sync(() => {
200 process.exitCode = previousExitCode;
201 }),
202 );
203
204 yield* Command.runWith(cli, { version: "0.0.0" })([
205 "triage",
206 "--agent",
207 "codex",
208 "--base-dir",
209 baseDir,
210 ]);
211 const output = (yield* TestConsole.logLines).join("\n");
212
213 assert.equal(process.exitCode, 1);
214 const promptFilePath = NodeFS.readdirSync(baseDir, { recursive: true, encoding: "utf8" })
215 .filter((entry) => NodePath.basename(entry) === TRIAGE_PROMPT_FILE_NAME)
216 .map((entry) => NodePath.join(baseDir, entry))[0];
217 assert.isDefined(promptFilePath);
218 assert.include(output, promptFilePath);
219 assert.include(output, buildTriageLaunchPrompt(promptFilePath));
220 assert.include(output, NodePath.join(NodePath.dirname(promptFilePath), "context.md"));
221 assert.include(output, `Codex keeps its state in ${codexHome}.`);
222 assert.include(output, "set CODEX_HOME to a folder on another drive");
223 }).pipe(
224 Effect.provide(
225 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer),
226 ),
227 ),
228);
229
230it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
231 "starts an agent found through a relative PATH entry from the session directory",
232 () =>
233 Effect.gen(function* () {
234 const fs = yield* FileSystem.FileSystem;
235 const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" });
236 // Relative to this process, as an entry like "." is to the server that checked it.
237 const relativeBinDir = NodePath.relative(process.cwd(), binDir);
238 // Nested deeper than the entry climbs, so from the session directory it leads nowhere.
239 const climbs = relativeBinDir.split(NodePath.sep).filter((part) => part === "..").length;
240 const baseDir = NodePath.join(
241 yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" }),
242 ...Array.from({ length: climbs }, () => "nested"),
243 );
244 NodeFS.mkdirSync(baseDir, { recursive: true });
245 NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 });
246 yield* Effect.acquireRelease(
247 Effect.sync(() => {
248 vi.stubEnv("PATH", relativeBinDir);
249 vi.stubEnv("CODEX_HOME", NodePath.join(baseDir, "codex-home"));
250 }),
251 () => Effect.sync(() => vi.unstubAllEnvs()),
252 );
253 const previousExitCode = process.exitCode;
254 yield* Effect.addFinalizer(() =>
255 Effect.sync(() => {
256 process.exitCode = previousExitCode;
257 }),
258 );
259
260 yield* Command.runWith(cli, { version: "0.0.0" })([
261 "triage",
262 "--agent",
263 "codex",
264 "--base-dir",
265 baseDir,
266 ]);
267
268 // The fake agent ran and exited 1, rather than failing to start.
269 assert.equal(process.exitCode, 1);
270 assert.include((yield* TestConsole.logLines).join("\n"), "Codex exited with code 1.");
271 }).pipe(
272 Effect.provide(
273 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer),
274 ),
275 ),
276);