Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import type * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Redacted from "effect/Redacted";
10import * as Schema from "effect/Schema";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import * as ChildProcess from "effect/process/ChildProcess";
14import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15import * as TestClock from "effect/testing/TestClock";
16
17import { FxSettings } from "../settings.ts";
18import { checkFxProviderStatus, readFxDefaultChoice } from "./status.ts";
19
20const encoder = new TextEncoder();
21const settings = Schema.decodeSync(FxSettings)({ enabled: true });
22
23/** Holds stdout and the exit back until `answered` completes, like a CLI slow to answer. */
24function processHandle(stdout: string, code: number, answered: Effect.Effect<void> = Effect.void) {
25 return ChildProcessSpawner.makeHandle({
26 pid: ChildProcessSpawner.ProcessId(900_000_101),
27 exitCode: Effect.as(answered, ChildProcessSpawner.ExitCode(code)),
28 exitStatus: Effect.as(answered, { _tag: "Exited", code: ChildProcessSpawner.ExitCode(code) }),
29 isRunning: Effect.succeed(false),
30 kill: () => Effect.void,
31 unref: Effect.succeed(Effect.void),
32 stdin: Sink.drain,
33 stdout: Stream.unwrap(
34 Effect.as(
35 answered,
36 stdout.length === 0 ? Stream.empty : Stream.succeed(encoder.encode(stdout)),
37 ),
38 ),
39 stderr: Stream.empty,
40 all: Stream.empty,
41 getInputFd: () => Sink.drain,
42 getOutputFd: () => Stream.empty,
43 });
44}
45
46// `fx status --json` and `fx models --json` from fx 0.0.15, trimmed to the
47// fields T3 reads plus a few it ignores.
48const status = (auth: string, fields: Record<string, unknown> = {}) =>
49 JSON.stringify({ kind: "status", model: "default", auth, auth_refreshable: false, ...fields });
50const models = (ids: ReadonlyArray<string>) =>
51 JSON.stringify({ kind: "models", count: ids.length, private_models_hidden: false, ids });
52const GATEWAY_MODELS = models(["anthropic/claude-sonnet-5.5", "anthropic/claude-opus-5.5"]);
53const SIGNED_OUT_LISTING = JSON.stringify({
54 kind: "models",
55 error: "could not list models: AuthenticationRejected",
56 code: "AuthenticationRejected",
57});
58
59interface Invocation {
60 readonly args: string;
61 readonly backend: string | undefined;
62 readonly cwd: string | undefined;
63}
64
65/**
66 * Answers `fx` invocations keyed by `FX_PROVIDER` and arguments, such as
67 * `codex status --json`; the unscoped status is ` status --json`. HOME holds
68 * an fx profile whose settings define `profileProviders`, or `FX_HOME` does
69 * when `profileInFxHome` is set.
70 */
71const check = (
72 outputs: Record<string, string>,
73 profileProviders: ReadonlyArray<string> = [],
74 versionDelay: Duration.Input = 0,
75 versionSpawned?: Deferred.Deferred<void>,
76 profileInFxHome = false,
77) =>
78 Effect.gen(function* () {
79 const fileSystem = yield* FileSystem.FileSystem;
80 const path = yield* Path.Path;
81 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-fx-status-" });
82 const profile = path.join(home, profileInFxHome ? "fx-home" : ".fx");
83 yield* fileSystem.makeDirectory(profile);
84 yield* fileSystem.writeFileString(
85 path.join(profile, "settings.json"),
86 JSON.stringify({
87 providers: Object.fromEntries(profileProviders.map((id) => [id, { protocol: "x" }])),
88 }),
89 );
90 const invoked: Array<Invocation> = [];
91 const spawner = ChildProcessSpawner.make((command) => {
92 const standard = ChildProcess.isStandardCommand(command) ? command : undefined;
93 const args = standard?.args.join(" ") ?? "";
94 const backendValue = standard?.options.env?.FX_PROVIDER;
95 const backend =
96 typeof backendValue === "string" || backendValue === undefined
97 ? backendValue
98 : Redacted.value(backendValue);
99 invoked.push({ args, backend, cwd: standard?.options.cwd });
100 const stdout = args === "--version" ? "fx 0.0.15\n" : outputs[`${backend ?? ""} ${args}`];
101 return Effect.gen(function* () {
102 if (args === "--version" && versionSpawned)
103 yield* Deferred.succeed(versionSpawned, undefined);
104 return processHandle(
105 stdout ?? "",
106 stdout === undefined ? 2 : 0,
107 args === "--version" ? Effect.sleep(versionDelay) : Effect.void,
108 );
109 });
110 });
111 const draft = yield* checkFxProviderStatus(
112 settings,
113 profileInFxHome ? { HOME: home, FX_HOME: profile } : { HOME: home },
114 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
115 return { draft, invoked };
116 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
117
118describe("checkFxProviderStatus", () => {
119 it.effect.each([
120 {
121 label: "answers after 6 s",
122 versionDelay: "6 seconds",
123 status: "ready",
124 version: "0.0.15",
125 message: undefined,
126 invoked: [
127 "--version",
128 "status --json",
129 "status --json",
130 "status --json",
131 "status --json",
132 "models --json",
133 ],
134 },
135 {
136 label: "never answers",
137 versionDelay: "Infinity",
138 status: "error",
139 version: null,
140 message: "Failed to run `fx --version`.",
141 invoked: ["--version"],
142 },
143 ] as const)("gives `fx --version` 10 s when it $label", (row) =>
144 Effect.gen(function* () {
145 const versionSpawned = yield* Deferred.make<void>();
146 const fiber = yield* check(
147 {
148 " status --json": status("fx login"),
149 "gateway status --json": status("fx login"),
150 "gateway models --json": GATEWAY_MODELS,
151 "codex status --json": status("missing"),
152 "grok status --json": status("missing"),
153 },
154 [],
155 row.versionDelay,
156 versionSpawned,
157 ).pipe(Effect.forkChild);
158 yield* Deferred.await(versionSpawned);
159 yield* TestClock.adjust("10 seconds");
160 const { draft, invoked } = yield* Fiber.join(fiber);
161 assert.equal(draft.status, row.status);
162 assert.equal(draft.version, row.version);
163 assert.equal(draft.message, row.message);
164 assert.deepEqual(invoked.map(({ args }) => args).toSorted(), [...row.invoked].toSorted());
165 }),
166 );
167
168 it.effect("lists each backend's models and marks signed-out backends", () =>
169 Effect.gen(function* () {
170 const { draft, invoked } = yield* check(
171 {
172 " status --json": status("chatgpt subscription", {
173 model: "gpt-5.5",
174 model_source: "Codex subscription",
175 }),
176 "gateway status --json": status("fx login"),
177 "gateway models --json": GATEWAY_MODELS,
178 "codex status --json": status("chatgpt subscription"),
179 "codex models --json": models(["gpt-5.5", "gpt-5.4-mini"]),
180 "grok status --json": status("missing"),
181 "local status --json": status("missing", {
182 auth_help: "The configured provider credential is unavailable.",
183 }),
184 },
185 ["local"],
186 );
187 // Never `fx acp`, which saves a session; signed-out backends list nothing.
188 assert.deepEqual(invoked.map(({ backend, args }) => `${backend ?? ""} ${args}`).toSorted(), [
189 " --version",
190 " status --json",
191 "codex models --json",
192 "codex status --json",
193 "gateway models --json",
194 "gateway status --json",
195 "grok status --json",
196 "local status --json",
197 ]);
198 assert.equal(draft.status, "ready");
199 assert.deepEqual(draft.auth, { status: "authenticated", label: "chatgpt subscription" });
200 assert.deepEqual(
201 draft.models.map((model) => [model.slug, model.name, model.subProvider]),
202 [
203 ["default", "Default (gpt-5.5)", undefined],
204 [
205 "gateway:anthropic/claude-sonnet-5.5",
206 "anthropic/claude-sonnet-5.5",
207 "Vercel AI Gateway",
208 ],
209 ["gateway:anthropic/claude-opus-5.5", "anthropic/claude-opus-5.5", "Vercel AI Gateway"],
210 ["codex:gpt-5.5", "gpt-5.5", "Codex subscription"],
211 ["codex:gpt-5.4-mini", "gpt-5.4-mini", "Codex subscription"],
212 ],
213 );
214 assert.deepEqual(draft.subProviders, [
215 { name: "Vercel AI Gateway" },
216 { name: "Codex subscription" },
217 {
218 name: "Grok subscription",
219 unavailableReason: "Signed out. Run `fx login grok` on this machine.",
220 },
221 { name: "local", unavailableReason: "The configured provider credential is unavailable." },
222 ]);
223 assert.isDefined(draft.versionAdvisory);
224 }),
225 );
226
227 it.effect("reads configured backends from the profile `FX_HOME` names", () =>
228 Effect.gen(function* () {
229 const { draft } = yield* check(
230 {
231 " status --json": status("fx login"),
232 "gateway status --json": status("fx login"),
233 "gateway models --json": GATEWAY_MODELS,
234 "codex status --json": status("missing"),
235 "grok status --json": status("missing"),
236 "local status --json": status("fx login"),
237 "local models --json": models([]),
238 },
239 ["local"],
240 0,
241 undefined,
242 true,
243 );
244 assert.deepEqual(
245 draft.subProviders?.map((subProvider) => subProvider.name),
246 ["Vercel AI Gateway", "Codex subscription", "Grok subscription", "local"],
247 );
248 }),
249 );
250
251 it.effect("stays usable while fx's default backend is signed out", () =>
252 Effect.gen(function* () {
253 const { draft } = yield* check({
254 " status --json": status("missing", { model: "spacexai/grok-4.7" }),
255 "gateway status --json": status("missing"),
256 "gateway models --json": GATEWAY_MODELS,
257 "codex status --json": status("chatgpt subscription"),
258 "codex models --json": models(["gpt-5.5"]),
259 "grok status --json": status("missing"),
260 });
261 assert.equal(draft.status, "warning");
262 assert.deepEqual(draft.auth, { status: "authenticated", label: "Codex subscription" });
263 assert.equal(
264 draft.message,
265 "fx's default backend, Vercel AI Gateway, is signed out. Pick a model on another backend or sign in.",
266 );
267 // The gateway lists its public catalog signed out, but none of it can run.
268 assert.deepEqual(
269 draft.models.map((model) => model.slug),
270 ["default", "codex:gpt-5.5"],
271 );
272
273 // An earlier backend whose sign-in fx could not report does not hide Codex's.
274 const unreadable = yield* check({
275 " status --json": status("missing", { model: "spacexai/grok-4.7" }),
276 "gateway models --json": GATEWAY_MODELS,
277 "codex status --json": status("chatgpt subscription"),
278 "codex models --json": models(["gpt-5.5"]),
279 "grok status --json": status("missing"),
280 });
281 assert.deepEqual(unreadable.draft.auth, {
282 status: "authenticated",
283 label: "Codex subscription",
284 });
285 }),
286 );
287
288 it.effect("offers Full access only when `fx status` lists that mode", () =>
289 Effect.gen(function* () {
290 const backends = {
291 "gateway status --json": status("fx login"),
292 "gateway models --json": GATEWAY_MODELS,
293 "codex status --json": status("missing"),
294 "grok status --json": status("missing"),
295 };
296 // fx 0.0.13 lists no modes and has no full-access mode.
297 const withoutModes = yield* check({ ...backends, " status --json": status("fx login") });
298 assert.deepEqual(withoutModes.draft.supportedRuntimeModes, ["approval-required", "auto"]);
299 // fx 0.0.14+ lists the ACP session modes (src/core/output/output_contracts.zig).
300 const withModes = yield* check({
301 ...backends,
302 " status --json": status("fx login", {
303 modes: [{ id: "auto" }, { id: "ask" }, { id: "full-access" }],
304 }),
305 });
306 assert.deepEqual(withModes.draft.supportedRuntimeModes, [
307 "approval-required",
308 "auto",
309 "full-access",
310 ]);
311 }),
312 );
313
314 it.effect("reports a machine signed out of every backend", () =>
315 Effect.gen(function* () {
316 const signedOut = yield* check({
317 " status --json": status("missing", { model: "spacexai/grok-4.7" }),
318 "gateway status --json": status("missing"),
319 "codex status --json": status("missing"),
320 "codex models --json": SIGNED_OUT_LISTING,
321 "grok status --json": status("missing"),
322 });
323 assert.equal(signedOut.draft.status, "error");
324 assert.equal(signedOut.draft.auth.status, "unauthenticated");
325 assert.equal(signedOut.draft.message, "Run `fx login` to sign in.");
326
327 // An fx whose status output T3 cannot read is not reported as signed out.
328 const unknown = yield* check({ " status --json": "not json" });
329 assert.equal(unknown.draft.status, "warning");
330 assert.equal(unknown.draft.auth.status, "unknown");
331 }),
332 );
333
334 // A ready snapshot drops models it does not list, so only a real listing may report ready.
335 it.effect("treats `fx models` output without ids as a failed listing", () =>
336 Effect.gen(function* () {
337 const outputs = (gatewayModels: string) => ({
338 " status --json": status("fx login"),
339 "gateway status --json": status("fx login"),
340 "gateway models --json": gatewayModels,
341 "codex status --json": status("chatgpt subscription"),
342 "codex models --json": models(["gpt-5.5"]),
343 "grok status --json": status("missing"),
344 });
345 const reshaped = yield* check(outputs(JSON.stringify({ kind: "models", models: [] })));
346 assert.equal(reshaped.draft.status, "warning");
347 assert.deepEqual(
348 reshaped.draft.models.map((model) => model.slug),
349 ["default", "codex:gpt-5.5"],
350 );
351 // The server keeps the gateway's earlier models, which can still run.
352 assert.deepEqual(reshaped.draft.subProviders?.[0], { name: "Vercel AI Gateway" });
353
354 const empty = yield* check(outputs(models([])));
355 assert.equal(empty.draft.status, "ready");
356 }),
357 );
358});
359
360describe("readFxDefaultChoice", () => {
361 // fx's settings can give one folder its own model, which `fx status` reports only there.
362 it.effect("reads fx's default backend and model in the thread's folder", () =>
363 Effect.forEach(
364 [
365 [{ model: "openai/gpt-5.5" }, { backend: "gateway", model: "openai/gpt-5.5" }],
366 [
367 { model: "gpt-5.5", model_source: "Codex subscription" },
368 { backend: "codex", model: "gpt-5.5" },
369 ],
370 [
371 { model: "llama3", model_source: "local" },
372 { backend: "local", model: "llama3" },
373 ],
374 ] as const,
375 ([fields, expected]) =>
376 Effect.gen(function* () {
377 const cwds: Array<string | undefined> = [];
378 const spawner = ChildProcessSpawner.make((command) => {
379 if (ChildProcess.isStandardCommand(command)) cwds.push(command.options.cwd);
380 return Effect.succeed(processHandle(status("fx login", fields), 0));
381 });
382 const choice = yield* readFxDefaultChoice(settings, {}, "/work/project").pipe(
383 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
384 );
385 assert.deepEqual(choice, expected);
386 assert.deepEqual(cwds, ["/work/project"]);
387 }),
388 { discard: true },
389 ).pipe(Effect.provide(NodeServices.layer)),
390 );
391});