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

main
ts 260 lines 8.68 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { describe, expect, it } from "@effect/vitest";
3 import type { ModelCapabilities } from "@t3tools/contracts";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 import { createModelCapabilities } from "@t3tools/shared/model";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 import * as Result from "effect/Result";
9 import * as Sink from "effect/Sink";
10 import * as Stream from "effect/Stream";
11 import * as ChildProcess from "effect/process/ChildProcess";
12 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13
14 import {
15 isCommandMissingCause,
16 resolveProviderProbeTimeoutMs,
17 parseGenericCliVersion,
18 providerModelsFromSettings,
19 spawnAndCollect,
20 } from "./snapshotProbe.ts";
21
22 const OPENCODE_CUSTOM_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
23 optionDescriptors: [
24 {
25 id: "variant",
26 label: "Reasoning",
27 type: "select",
28 options: [{ id: "medium", label: "Medium", isDefault: true }],
29 currentValue: "medium",
30 },
31 {
32 id: "agent",
33 label: "Agent",
34 type: "select",
35 options: [{ id: "build", label: "Build", isDefault: true }],
36 currentValue: "build",
37 },
38 ],
39 });
40
41 describe("providerModelsFromSettings", () => {
42 it("keeps an entry's own name and capabilities over the driver default", () => {
43 const capabilities = createModelCapabilities({
44 optionDescriptors: [{ id: "fastMode", label: "Fast Mode", type: "boolean" }],
45 });
46 const models = providerModelsFromSettings(
47 [],
48 ["bare", { slug: "named", name: "Named", capabilities }],
49 OPENCODE_CUSTOM_MODEL_CAPABILITIES,
50 );
51
52 expect(models).toEqual([
53 {
54 slug: "bare",
55 name: "bare",
56 isCustom: true,
57 capabilities: OPENCODE_CUSTOM_MODEL_CAPABILITIES,
58 },
59 { slug: "named", name: "Named", isCustom: true, capabilities },
60 ]);
61 });
62
63 it("renames a built-in model when a named entry uses its slug", () => {
64 const capabilities = createModelCapabilities({ optionDescriptors: [] });
65 const models = providerModelsFromSettings(
66 [
67 {
68 slug: "gpt-5.5",
69 name: "GPT-5.5",
70 shortName: "5.5",
71 isCustom: false,
72 capabilities,
73 },
74 ],
75 [{ slug: "gpt-5.5", name: "Team GPT" }],
76 capabilities,
77 );
78
79 expect(models).toEqual([{ slug: "gpt-5.5", name: "Team GPT", isCustom: false, capabilities }]);
80 });
81
82 it("preserves a custom slug that collides with a provider alias", () => {
83 const capabilities = createModelCapabilities({ optionDescriptors: [] });
84 const models = providerModelsFromSettings(
85 [
86 {
87 slug: "claude-opus-4-8",
88 name: "Claude Opus 4.8",
89 isCustom: false,
90 capabilities,
91 },
92 ],
93 [" opus "],
94 capabilities,
95 );
96
97 expect(models.map((model) => model.slug)).toEqual(["claude-opus-4-8", "opus"]);
98 expect(models[1]?.isCustom).toBe(true);
99 });
100 });
101
102 describe("parseGenericCliVersion", () => {
103 it("parses a v-prefixed version", () => {
104 expect(parseGenericCliVersion("opencode v2.0.3")).toBe("2.0.3");
105 expect(parseGenericCliVersion("v22.19.0")).toBe("22.19.0");
106 });
107
108 it("parses a version embedded in other output", () => {
109 expect(parseGenericCliVersion("codex-cli 0.53.0 (build abc)")).toBe("0.53.0");
110 });
111
112 it("ignores versions glued to other word characters", () => {
113 expect(parseGenericCliVersion("build2.0.3artifact")).toBeNull();
114 });
115 });
116
117 describe("ProviderCommandNotFoundError", () => {
118 it.effect("retains safe failed-command diagnostics without process output", () => {
119 const stderr = "'codex' is not recognized: secret-token-value";
120 const spawner = ChildProcessSpawner.make(() =>
121 Effect.succeed(
122 ChildProcessSpawner.makeHandle({
123 pid: ChildProcessSpawner.ProcessId(1),
124 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(9009)),
125 isRunning: Effect.succeed(false),
126 kill: () => Effect.void,
127 unref: Effect.succeed(Effect.void),
128 stdin: Sink.drain,
129 stdout: Stream.empty,
130 stderr: Stream.encodeText(Stream.make(stderr)),
131 all: Stream.empty,
132 getInputFd: () => Sink.drain,
133 getOutputFd: () => Stream.empty,
134 }),
135 ),
136 );
137 return Effect.gen(function* () {
138 const error = yield* spawnAndCollect(
139 "C:\\tools\\codex.cmd",
140 ChildProcess.make("codex", ["--version"]),
141 ).pipe(
142 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
143 Effect.provideService(HostProcess.Platform, "win32"),
144 Effect.flip,
145 );
146
147 if (error._tag !== "ProviderCommandNotFoundError") {
148 throw new Error(`Unexpected error: ${error._tag}`);
149 }
150
151 expect(error.binaryPath).toBe("C:\\tools\\codex.cmd");
152 expect(error.exitCode).toBe(9009);
153 expect(error.stdoutLength).toBe(0);
154 expect(error.stderrLength).toBe(stderr.length);
155 expect(error.message).toBe(
156 "Provider command C:\\tools\\codex.cmd was not found (exit code 9009).",
157 );
158 expect(isCommandMissingCause(error)).toBe(true);
159 expect(error).not.toHaveProperty("stdout");
160 expect(error).not.toHaveProperty("stderr");
161 expect(error.message).not.toContain("secret-token-value");
162 });
163 });
164 });
165
166 describe("resolveProviderProbeTimeoutMs", () => {
167 it.each([
168 "codex",
169 "claude",
170 "cursor",
171 "antigravity",
172 "grok",
173 "kiro",
174 "fx",
175 "pi",
176 "muse",
177 "opencode",
178 "acp_registry",
179 ])("uses only %s's readiness override", (provider) => {
180 const key = `T3CODE_${provider.toUpperCase()}_PROBE_TIMEOUT_MS`;
181 expect(resolveProviderProbeTimeoutMs(provider, 25000, { [key]: "60000" })).toBe(60000);
182 expect(resolveProviderProbeTimeoutMs(provider, 25000, { [key]: "1000" })).toBe(25000);
183 expect(
184 resolveProviderProbeTimeoutMs(provider, 25000, { T3CODE_OTHER_PROBE_TIMEOUT_MS: "60000" }),
185 ).toBe(25000);
186 });
187 it.each([undefined, "", " ", "bad", "0", "-1", "1.5", "Infinity", "2147483648"])(
188 "retains the phase default for invalid value %s",
189 (value) => {
190 expect(
191 resolveProviderProbeTimeoutMs("claude", 25000, { T3CODE_CLAUDE_PROBE_TIMEOUT_MS: value }),
192 ).toBe(25000);
193 },
194 );
195 });
196
197 describe("spawnAndCollect", () => {
198 it.effect.each(["stdout", "stderr"] as const)(
199 "rejects oversized %s after draining the process streams",
200 (stream) =>
201 Effect.gen(function* () {
202 let drainedChunks = 0;
203 const chunk = new Uint8Array(1024 * 1024).fill(120);
204 const output = Stream.fromIterable(Array.from({ length: 9 }, () => chunk)).pipe(
205 Stream.tap(() =>
206 Effect.sync(() => {
207 drainedChunks += 1;
208 }),
209 ),
210 );
211 const spawner = ChildProcessSpawner.make(() =>
212 Effect.succeed(
213 ChildProcessSpawner.makeHandle({
214 pid: ChildProcessSpawner.ProcessId(1),
215 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
216 isRunning: Effect.succeed(false),
217 kill: () => Effect.void,
218 unref: Effect.succeed(Effect.void),
219 stdin: Sink.drain,
220 stdout: stream === "stdout" ? output : Stream.empty,
221 stderr: stream === "stderr" ? output : Stream.empty,
222 all: Stream.empty,
223 getInputFd: () => Sink.drain,
224 getOutputFd: () => Stream.empty,
225 }),
226 ),
227 );
228 const result = yield* spawnAndCollect(
229 "fixture-cli",
230 ChildProcess.make("fixture-cli", ["--version"]),
231 ).pipe(
232 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
233 Effect.result,
234 );
235 expect(Result.isFailure(result)).toBe(true);
236 if (Result.isFailure(result)) {
237 expect(result.failure).toMatchObject({
238 _tag: "ProviderProbeOutputLimitError",
239 stream,
240 maxBytes: 8 * 1024 * 1024,
241 });
242 }
243 expect(drainedChunks).toBe(9);
244 }),
245 );
246
247 // regression: #35262 - without forceKillAfter a timed-out probe whose CLI ignores
248 // SIGTERM waits for it to exit, so the caller's timeout never returns.
249 it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
250 "lets a timed-out probe return when the CLI ignores SIGTERM",
251 () =>
252 Effect.gen(function* () {
253 const result = yield* spawnAndCollect(
254 "sh",
255 ChildProcess.make("sh", ["-c", 'trap "" TERM; sleep 30']),
256 ).pipe(Effect.timeoutOption("200 millis"));
257 expect(Option.isNone(result)).toBe(true);
258 }).pipe(Effect.provide(NodeServices.layer)),
259 );
260 });