@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 192 lines 7.82 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off -- Exercise the CLI with isolated executable fixtures.
2 import * as NodeChildProcess from "node:child_process";
3 import * as NodeFS from "node:fs";
4 import * as NodeFSP from "node:fs/promises";
5 import * as NodeOS from "node:os";
6 import * as NodePath from "node:path";
7 import * as NodeURL from "node:url";
8
9 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
10 import * as NodeServices from "@effect/platform-node/NodeServices";
11 import { assert, it } from "@effect/vitest";
12 import { TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";
13 import * as HostProcess from "@t3tools/shared/HostProcess";
14 import * as NetService from "@t3tools/shared/Net";
15 import * as Effect from "effect/Effect";
16 import * as FileSystem from "effect/FileSystem";
17 import * as Layer from "effect/Layer";
18 import { Command } from "effect/cli";
19 import * as TestConsole from "effect/testing/TestConsole";
20 import { expect, vi } from "vite-plus/test";
21
22 import { cli } from "../binCli.ts";
23 import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts";
24
25 const cliPath = NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url));
26
27 async function fixture(commands: ReadonlyArray<string>) {
28 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-triage-"));
29 const bin = NodePath.join(root, "bin");
30 const record = NodePath.join(root, "launch.json");
31 await NodeFSP.mkdir(bin);
32 const script = NodePath.join(root, "agent.cjs");
33 await NodeFSP.writeFile(
34 script,
35 `require("node:fs").writeFileSync(process.env.TRIAGE_TEST_RECORD, JSON.stringify({ command: process.argv[2], args: process.argv.slice(3), cwd: process.cwd() }));`,
36 );
37 for (const command of commands) {
38 const windows = HostProcess.Platform.defaultValue() === "win32";
39 const executable = NodePath.join(bin, windows ? `${command}.cmd` : command);
40 const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
41 await NodeFSP.writeFile(
42 executable,
43 windows
44 ? `@"${process.execPath}" "${script}" ${command} %*\r\n`
45 : `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(script)} ${quote(command)} "$@"\n`,
46 { mode: 0o755 },
47 );
48 }
49 return {
50 root,
51 record,
52 run: (args: ReadonlyArray<string>) =>
53 new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
54 const child = NodeChildProcess.spawn(
55 process.execPath,
56 [cliPath, "triage", "--base-dir", NodePath.join(root, "home with spaces"), ...args],
57 {
58 env: {
59 ...process.env,
60 PATH: bin,
61 TRIAGE_TEST_RECORD: record,
62 },
63 stdio: ["ignore", "pipe", "pipe"],
64 },
65 );
66 let stdout = "";
67 let stderr = "";
68 child.stdout.on("data", (data) => (stdout += String(data)));
69 child.stderr.on("data", (data) => (stderr += String(data)));
70 child.once("error", reject);
71 child.once("close", (code) => resolve({ code, stdout, stderr }));
72 }),
73 async [Symbol.asyncDispose]() {
74 await NodeFSP.rm(root, { recursive: true, force: true });
75 },
76 };
77 }
78
79 it.live.each([
80 { commands: ["agy", "codex"], agent: "antigravity", command: "agy", model: "test-model" },
81 { commands: ["agy"], agent: undefined, command: "agy", model: undefined },
82 { commands: ["agy", "codex"], agent: "codex", command: "codex", model: "test-model" },
83 { commands: ["agy", "codex", "claude"], agent: "claude", command: "claude", model: undefined },
84 ])(
85 "launches $command with the triage prompt (agent=$agent, model=$model)",
86 ({ commands, agent, command, model }) =>
87 Effect.promise(async () => {
88 await using setup = await fixture(commands);
89 const result = await setup.run([
90 ...(agent === undefined ? [] : ["--agent", agent]),
91 ...(model === undefined ? [] : ["--model", model]),
92 ]);
93 expect(result.code, result.stdout + result.stderr).toBe(0);
94 const launch = JSON.parse(await NodeFSP.readFile(setup.record, "utf8")) as {
95 command: string;
96 args: string[];
97 cwd: string;
98 };
99 expect(launch.command).toBe(command);
100 expect(launch.args.slice(0, -1)).toEqual([
101 ...(model === undefined ? [] : ["--model", model]),
102 ...(command === "agy" ? ["--prompt-interactive"] : []),
103 ]);
104 expect(launch.args.at(-1)).toContain(NodePath.join(launch.cwd, "triage-playbook.md"));
105 expect(
106 await NodeFSP.readFile(NodePath.join(launch.cwd, "triage-playbook.md"), "utf8"),
107 ).toContain("context.md");
108 }),
109 );
110
111 it.live(
112 "requires an explicit choice when Codex and Antigravity are installed without a terminal",
113 () =>
114 Effect.promise(async () => {
115 await using setup = await fixture(["agy", "codex"]);
116 const result = await setup.run([]);
117 expect(result.code).toBe(1);
118 expect(result.stdout + result.stderr).toContain("--agent antigravity");
119 expect(result.stdout + result.stderr).toContain("--agent codex");
120 expect(result.stdout + result.stderr).not.toContain("Starting");
121 await expect(NodeFSP.stat(setup.record)).rejects.toMatchObject({ code: "ENOENT" });
122 }),
123 );
124
125 it.live("reports the missing agy executable when Antigravity is explicitly requested", () =>
126 Effect.promise(async () => {
127 await using setup = await fixture(["codex"]);
128 const result = await setup.run(["--agent", "antigravity"]);
129 expect(result.code).toBe(1);
130 expect(result.stdout + result.stderr).toContain(
131 "`agy` is not installed or was not found on PATH.",
132 );
133 await expect(NodeFSP.stat(setup.record)).rejects.toMatchObject({ code: "ENOENT" });
134 }),
135 );
136
137 const FAILING_AGENT_POSIX = `#!/bin/sh
138 echo "Error: There is not enough space on the disk. (os error 112)" >&2
139 exit 1
140 `;
141 const FAILING_AGENT_WINDOWS = `@echo Error: There is not enough space on the disk. (os error 112) 1>&2
142 @exit /b 1
143 `;
144
145 it.live("a failed agent launch points at the prompt it could not run", () =>
146 Effect.gen(function* () {
147 const fs = yield* FileSystem.FileSystem;
148 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" });
149 const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" });
150 const codexHome = NodePath.join(baseDir, "codex-home");
151 NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 });
152 NodeFS.writeFileSync(NodePath.join(binDir, "codex.cmd"), FAILING_AGENT_WINDOWS);
153 yield* Effect.acquireRelease(
154 // PATH holds only the fake agent, so a broken fixture can never fall through to a real codex.
155 Effect.sync(() => {
156 vi.stubEnv("PATH", binDir);
157 vi.stubEnv("CODEX_HOME", codexHome);
158 }),
159 () => Effect.sync(() => vi.unstubAllEnvs()),
160 );
161 const previousExitCode = process.exitCode;
162 yield* Effect.addFinalizer(() =>
163 Effect.sync(() => {
164 process.exitCode = previousExitCode;
165 }),
166 );
167
168 yield* Command.runWith(cli, { version: "0.0.0" })([
169 "triage",
170 "--agent",
171 "codex",
172 "--base-dir",
173 baseDir,
174 ]);
175 const output = (yield* TestConsole.logLines).join("\n");
176
177 assert.equal(process.exitCode, 1);
178 const promptFilePath = NodeFS.readdirSync(baseDir, { recursive: true, encoding: "utf8" })
179 .filter((entry) => NodePath.basename(entry) === TRIAGE_PROMPT_FILE_NAME)
180 .map((entry) => NodePath.join(baseDir, entry))[0];
181 assert.isDefined(promptFilePath);
182 assert.include(output, promptFilePath);
183 assert.include(output, buildTriageLaunchPrompt(promptFilePath));
184 assert.include(output, NodePath.join(NodePath.dirname(promptFilePath), "context.md"));
185 assert.include(output, `Codex keeps its state in ${codexHome}.`);
186 assert.include(output, "set CODEX_HOME to a folder on another drive");
187 }).pipe(
188 Effect.provide(
189 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer),
190 ),
191 ),
192 );