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

triage.test.ts

299 lines11.7 KB

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 };
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 { label: "an invalid choice and Ctrl+C", key: "9\r\x03" },
129 { label: "an invalid choice and Ctrl+D", key: "9\r\x04" },
130])("returns undefined when the agent picker is cancelled with $label", ({ key }) =>
131 Effect.gen(function* () {
132 const input = new NodeStream.PassThrough();
133 const output = Object.assign(new NodeStream.PassThrough(), { isTTY: true });
134 output.once("data", () => input.write(key));
135​
136 const picked = yield* pickAgent(
137 [
138 { id: "claude", label: "Claude Code" },
139 { id: "codex", label: "Codex" },
140 ],
141 input,
142 output,
143 );
144​
145 assert.isUndefined(picked);
146 }),
147);
148​
149it.effect.each([
150 { label: "no answer", lines: [], picked: undefined },
151 { label: "an invalid answer", lines: ["99\n"], picked: undefined },
152 { label: "an invalid answer and then a valid one", lines: ["9\n", "2\n"], picked: "codex" },
153])("the agent picker returns $picked when input ends after $label", ({ lines, picked }) =>
154 Effect.gen(function* () {
155 const input = NodeStream.Readable.from(lines.map((line) => Promise.resolve(line)));
156​
157 const agent = yield* pickAgent(
158 [
159 { id: "claude", label: "Claude Code" },
160 { id: "codex", label: "Codex" },
161 ],
162 input,
163 new NodeStream.PassThrough(),
164 );
165​
166 assert.strictEqual(agent?.id, picked);
167 }),
168);
169​
170it.live(
171 "requires an explicit choice when Codex and Antigravity are installed without a terminal",
172 () =>
173 Effect.promise(async () => {
174 await using setup = await fixture(["agy", "codex"]);
175 const result = await setup.run([]);
176 expect(result.code).toBe(1);
177 expect(result.stdout + result.stderr).toContain("--agent antigravity");
178 expect(result.stdout + result.stderr).toContain("--agent codex");
179 expect(result.stdout + result.stderr).not.toContain("Starting");
180 await expect(NodeFSP.stat(setup.record)).rejects.toMatchObject({ code: "ENOENT" });
181 }),
182);
183​
184it.live("reports the missing agy executable when Antigravity is explicitly requested", () =>
185 Effect.promise(async () => {
186 await using setup = await fixture(["codex"]);
187 const result = await setup.run(["--agent", "antigravity"]);
188 expect(result.code).toBe(1);
189 expect(result.stdout + result.stderr).toContain(
190 "`agy` is not installed or was not found on PATH.",
191 );
192 await expect(NodeFSP.stat(setup.record)).rejects.toMatchObject({ code: "ENOENT" });
193 }),
194);
195​
196const FAILING_AGENT_POSIX = `#!/bin/sh
197echo "Error: There is not enough space on the disk. (os error 112)" >&2
198exit 1
199`;
200const FAILING_AGENT_WINDOWS = `@echo Error: There is not enough space on the disk. (os error 112) 1>&2
201@exit /b 1
202`;
203​
204it.live("a failed agent launch points at the prompt it could not run", () =>
205 Effect.gen(function* () {
206 const fs = yield* FileSystem.FileSystem;
207 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" });
208 const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" });
209 const codexHome = NodePath.join(baseDir, "codex-home");
210 NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 });
211 NodeFS.writeFileSync(NodePath.join(binDir, "codex.cmd"), FAILING_AGENT_WINDOWS);
212 yield* Effect.acquireRelease(
213 // PATH holds only the fake agent, so a broken fixture can never fall through to a real codex.
214 Effect.sync(() => {
215 vi.stubEnv("PATH", binDir);
216 vi.stubEnv("CODEX_HOME", codexHome);
217 }),
218 () => Effect.sync(() => vi.unstubAllEnvs()),
219 );
220 const previousExitCode = process.exitCode;
221 yield* Effect.addFinalizer(() =>
222 Effect.sync(() => {
223 process.exitCode = previousExitCode;
224 }),
225 );
226​
227 yield* Command.runWith(cli, { version: "0.0.0" })([
228 "triage",
229 "--agent",
230 "codex",
231 "--base-dir",
232 baseDir,
233 ]);
234 const output = (yield* TestConsole.logLines).join("\n");
235​
236 assert.equal(process.exitCode, 1);
237 const promptFilePath = NodeFS.readdirSync(baseDir, { recursive: true, encoding: "utf8" })
238 .filter((entry) => NodePath.basename(entry) === TRIAGE_PROMPT_FILE_NAME)
239 .map((entry) => NodePath.join(baseDir, entry))[0];
240 assert.isDefined(promptFilePath);
241 assert.include(output, promptFilePath);
242 assert.include(output, buildTriageLaunchPrompt(promptFilePath));
243 assert.include(output, NodePath.join(NodePath.dirname(promptFilePath), "context.md"));
244 assert.include(output, `Codex keeps its state in ${codexHome}.`);
245 assert.include(output, "set CODEX_HOME to a folder on another drive");
246 }).pipe(
247 Effect.provide(
248 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer),
249 ),
250 ),
251);
252​
253it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
254 "starts an agent found through a relative PATH entry from the session directory",
255 () =>
256 Effect.gen(function* () {
257 const fs = yield* FileSystem.FileSystem;
258 const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" });
259 // Relative to this process, as an entry like "." is to the server that checked it.
260 const relativeBinDir = NodePath.relative(process.cwd(), binDir);
261 // Nested deeper than the entry climbs, so from the session directory it leads nowhere.
262 const climbs = relativeBinDir.split(NodePath.sep).filter((part) => part === "..").length;
263 const baseDir = NodePath.join(
264 yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" }),
265 ...Array.from({ length: climbs }, () => "nested"),
266 );
267 NodeFS.mkdirSync(baseDir, { recursive: true });
268 NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 });
269 yield* Effect.acquireRelease(
270 Effect.sync(() => {
271 vi.stubEnv("PATH", relativeBinDir);
272 vi.stubEnv("CODEX_HOME", NodePath.join(baseDir, "codex-home"));
273 }),
274 () => Effect.sync(() => vi.unstubAllEnvs()),
275 );
276 const previousExitCode = process.exitCode;
277 yield* Effect.addFinalizer(() =>
278 Effect.sync(() => {
279 process.exitCode = previousExitCode;
280 }),
281 );
282​
283 yield* Command.runWith(cli, { version: "0.0.0" })([
284 "triage",
285 "--agent",
286 "codex",
287 "--base-dir",
288 baseDir,
289 ]);
290​
291 // The fake agent ran and exited 1, rather than failing to start.
292 assert.equal(process.exitCode, 1);
293 assert.include((yield* TestConsole.logLines).join("\n"), "Codex exited with code 1.");
294 }).pipe(
295 Effect.provide(
296 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer),
297 ),
298 ),
299);