TypeScript
fix(server): retain Codex authentication when discovery times out (#20537)
Scott Norteman09548f614528
diff --git a/apps/server/src/provider/CodexProvider.test.ts b/apps/server/src/provider/CodexProvider.test.tsindex 2c67b6f144d..7474ce47c19 100644--- a/apps/server/src/provider/CodexProvider.test.ts+++ b/apps/server/src/provider/CodexProvider.test.ts@@ -1,6 +1,23 @@+import * as NodeServices from "@effect/platform-node/NodeServices";import { assert, it } from "@effect/vitest";+import { CodexSettings } from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Deferred from "effect/Deferred";+import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";+import * as FileSystem from "effect/FileSystem";+import * as Queue from "effect/Queue";+import * as Schema from "effect/Schema";+import * as Sink from "effect/Sink";+import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";-import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";+import {+ applyPreferredCodexDefaultModel,+ checkCodexProviderStatus,+ mapCodexModelCapabilities,+} from "./CodexProvider.ts";it("maps current Codex model capability fields", () => {const capabilities = mapCodexModelCapabilities({@@ -171,3 +188,211 @@ it("ignores custom models that shadow a preferred slug", () => {assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");});++const decodeCodexSettings = Schema.decodeSync(CodexSettings);+const decodeRequest = Schema.decodeUnknownSync(+ Schema.fromJsonString(+ Schema.Struct({+ id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Number])),+ method: Schema.String,+ }),+ ),+);+const account = {+ account: { type: "chatgpt", email: "[email protected]", planType: "pro" },+ requiresOpenaiAuth: false,+} as const;++const startProbe = Effect.fn("startProbe")(function* (hang: ReadonlyArray<string>) {+ const fs = yield* FileSystem.FileSystem;+ const homePath = yield* fs.makeTempDirectoryScoped();+ yield* fs.writeFileString(+ `${homePath}/models_cache.json`,+ JSON.stringify({ fetched_at: DateTime.formatIso(yield* DateTime.now) }),+ );+ const output = yield* Queue.unbounded<Uint8Array>();+ const requests = new Map(+ yield* Effect.forEach(+ ["account/read", "skills/list", "model/list/1", "model/list/2", "account/rateLimits/read"],+ (method) =>+ Deferred.make<string | number>().pipe(Effect.map((signal) => [method, signal] as const)),+ ),+ );+ const stopped = yield* Deferred.make<void>();+ const reply = (id: string | number, result: unknown) =>+ Queue.offer(output, new TextEncoder().encode(`${JSON.stringify({ id, result })}\n`));+ let modelRequests = 0;+ const spawner = ChildProcessSpawner.make(() =>+ Effect.gen(function* () {+ yield* Effect.addFinalizer(() => Deferred.succeed(stopped, undefined));+ return ChildProcessSpawner.makeHandle({+ pid: ChildProcessSpawner.ProcessId(1),+ exitCode: Deferred.await(stopped).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),+ isRunning: Deferred.isDone(stopped).pipe(Effect.map((done) => !done)),+ kill: () => Deferred.succeed(stopped, undefined).pipe(Effect.asVoid),+ unref: Effect.succeed(Effect.void),+ stdin: Sink.forEach((bytes: Uint8Array) =>+ Effect.forEach(+ new TextDecoder().decode(bytes).split("\n").filter(Boolean),+ (line) =>+ Effect.gen(function* () {+ const { id, method } = decodeRequest(line);+ if (id === undefined) return;+ const request = method === "model/list" ? `${method}/${++modelRequests}` : method;+ const signal = requests.get(request);+ if (signal) yield* Deferred.succeed(signal, id);+ if (hang.includes(request) || method === "account/read") return;+ if (method === "initialize") {+ yield* reply(id, {+ userAgent: "codex/0.163.0",+ codexHome: homePath,+ platformFamily: "unix",+ platformOs: "linux",+ });+ } else if (method === "model/list") {+ yield* reply(id, {+ data: [+ {+ id: "gpt-test",+ model: "gpt-test",+ displayName: "Test",+ description: "",+ hidden: false,+ isDefault: true,+ defaultReasoningEffort: "high",+ supportedReasoningEfforts: [],+ },+ ],+ nextCursor: null,+ });+ } else if (method === "skills/list") {+ yield* reply(id, { data: [] });+ } else if (method === "account/rateLimits/read") {+ yield* reply(id, {+ rateLimits: { primary: null, secondary: null, credits: null, planType: "pro" },+ });+ }+ }),+ { discard: true },+ ),+ ),+ stdout: Stream.fromQueue(output),+ stderr: Stream.empty,+ all: Stream.empty,+ getInputFd: () => Sink.drain,+ getOutputFd: () => Stream.empty,+ });+ }),+ );+ const fiber = yield* checkCodexProviderStatus(+ decodeCodexSettings({ homePath, customModels: [{ slug: "custom-model" }] }),+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.forkChild);+ const requested = (method: string) => Deferred.await(requests.get(method)!);+ return {+ fiber,+ requested,+ authenticate: requested("account/read").pipe(Effect.flatMap((id) => reply(id, account))),+ };+});++it.layer(NodeServices.layer)("Codex probe budget", (it) => {+ it.effect("keeps the first complete catalog when its refresh never answers", () =>+ Effect.gen(function* () {+ const probe = yield* startProbe(["model/list/2"]);+ yield* probe.authenticate;+ yield* probe.requested("model/list/2");+ yield* TestClock.adjust("20 seconds");+ const provider = yield* Fiber.join(probe.fiber);+ assert.strictEqual(provider.status, "ready");+ assert.strictEqual(provider.auth.status, "authenticated");+ assert.deepStrictEqual(+ provider.models.map((model) => model.slug),+ ["gpt-test", "custom-model"],+ );+ }).pipe(Effect.scoped),+ );++ it.effect("warns with authentication and custom models when no catalog arrives", () =>+ Effect.gen(function* () {+ const probe = yield* startProbe(["model/list/1"]);+ yield* probe.authenticate;+ yield* probe.requested("model/list/1");+ yield* TestClock.adjust("20 seconds");+ const provider = yield* Fiber.join(probe.fiber);+ assert.strictEqual(provider.status, "warning");+ assert.strictEqual(provider.auth.status, "authenticated");+ assert.strictEqual(provider.message, "Codex did not return its model catalog in time.");+ assert.deepStrictEqual(+ provider.models.map((model) => model.slug),+ ["custom-model"],+ );+ }).pipe(Effect.scoped),+ );++ it.effect("bounds stalled skills and usage discovery by the remaining account probe budget", () =>+ Effect.gen(function* () {+ const probe = yield* startProbe(["skills/list", "account/rateLimits/read"]);+ yield* probe.requested("account/read");+ yield* TestClock.adjust(18_500);+ yield* probe.authenticate;+ yield* probe.requested("skills/list");+ yield* probe.requested("account/rateLimits/read");+ yield* probe.requested("model/list/2");+ yield* TestClock.adjust(1_500);+ const provider = yield* Fiber.join(probe.fiber);+ assert.strictEqual(provider.status, "ready");+ assert.strictEqual(provider.auth.status, "authenticated");+ assert.deepStrictEqual(+ provider.models.map((model) => model.slug),+ ["gpt-test", "custom-model"],+ );+ assert.deepStrictEqual(provider.skills, []);+ assert.strictEqual(provider.usageLimits?.unavailable?.reason, "probeFailed");+ }).pipe(Effect.scoped),+ );++ it.effect("retains a completed probe when cleanup exceeds the work budget", () =>+ Effect.gen(function* () {+ const started = yield* Deferred.make<void>();+ const complete = yield* Deferred.make<void>();+ const cleanupStarted = yield* Deferred.make<void>();+ const cleanupFinished = yield* Deferred.make<void>();+ const fiber = yield* checkCodexProviderStatus(decodeCodexSettings({}), () =>+ Effect.gen(function* () {+ yield* Effect.addFinalizer(() =>+ Deferred.succeed(cleanupStarted, undefined).pipe(+ Effect.andThen(Deferred.await(cleanupFinished)),+ ),+ );+ yield* Deferred.succeed(started, undefined);+ yield* Deferred.await(complete);+ return { account, version: undefined, models: [], skills: [] };+ }),+ ).pipe(Effect.forkChild);+ yield* Deferred.await(started);+ yield* TestClock.adjust(18_500);+ yield* Deferred.succeed(complete, undefined);+ yield* Deferred.await(cleanupStarted);+ yield* TestClock.adjust("2 seconds");+ yield* Deferred.succeed(cleanupFinished, undefined);+ const provider = yield* Fiber.join(fiber);+ assert.strictEqual(provider.status, "ready");+ assert.strictEqual(provider.auth.status, "authenticated");+ }),+ );++ it.effect("still errors when account authentication never answers", () =>+ Effect.gen(function* () {+ const probe = yield* startProbe([]);+ yield* probe.requested("account/read");+ yield* TestClock.adjust("20 seconds");+ const provider = yield* Fiber.join(probe.fiber);+ assert.strictEqual(provider.status, "error");+ assert.strictEqual(provider.auth.status, "unknown");+ assert.strictEqual(+ provider.message,+ "Timed out while checking Codex app-server provider status.",+ );+ }).pipe(Effect.scoped),+ );+});diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.tsindex d31c91ec295..4a60f12891e 100644--- a/apps/server/src/provider/CodexProvider.ts+++ b/apps/server/src/provider/CodexProvider.ts@@ -67,8 +67,8 @@ type CodexRateLimitsProbe =| { readonly failure: string };const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;-const CODEX_CATALOG_REFRESH_TIMEOUT = "3 seconds" as const;-const CODEX_CONFIG_PROBE_TIMEOUT = "3 seconds" as const;+const CODEX_CATALOG_REFRESH_TIMEOUT_MS = 3_000;+const CODEX_CONFIG_PROBE_TIMEOUT_MS = 3_000;const CODEX_CATALOG_REFRESH_POLL = "100 millis" as const;const CODEX_CLIENT_NAME = "T3 Code";// Codex's probe does a full handshake plus account, models, and skills requests, which can@@ -76,6 +76,7 @@ const CODEX_CLIENT_NAME = "T3 Code";// (most often reported on Windows). Give Codex its own longer budget instead of raising the// timeout for every provider.const CODEX_AUTH_PROBE_TIMEOUT_MS = 20_000;+const CODEX_DISCOVERY_MARGIN_MS = 250;const CODEX_PRESENTATION = {displayName: "Codex",@@ -87,7 +88,8 @@ export interface CodexAppServerProviderSnapshot {readonly account: CodexSchema.V2GetAccountResponse;readonly rateLimits?: CodexRateLimitsProbe;readonly version: string | undefined;- readonly models: ReadonlyArray<ServerProviderModel>;+ readonly models: ReadonlyArray<ServerProviderModel> | undefined;+ readonly serviceTier?: string | undefined;readonly skills: ReadonlyArray<ServerProviderSkill>;}@@ -386,6 +388,19 @@ const readCodexModelsCacheFetchedAt = Effect.fn("readCodexModelsCacheFetchedAt"));});+const withCodexDiscoveryDeadline = Effect.fnUntraced(function* <A, E, R>(+ effect: Effect.Effect<A, E, R>,+ deadlineMs: number,+ timeoutMs = Infinity,+) {+ const remainingMs = Math.min(timeoutMs, deadlineMs - DateTime.toEpochMillis(yield* DateTime.now));+ if (remainingMs <= 0) return undefined;+ return yield* effect.pipe(+ Effect.timeoutOption(Duration.millis(remainingMs)),+ Effect.map(Option.getOrUndefined),+ );+});+/*** Every Codex client on the machine shares that file, and the backend tailors* the catalog to each client's originator: the plain CLI does not get Sol@@ -396,22 +411,33 @@ const requestCodexChatGptModels = Effect.fn("requestCodexChatGptModels")(functioreadonly client: CodexClient.CodexAppServerClient["Service"];readonly codexHome: string;readonly spawnedAtMs: number;+ readonly deadlineMs: number;}) {- const models = yield* requestAllCodexModels(input.client);- const refreshed = yield* readCodexModelsCacheFetchedAt(input.codexHome).pipe(- Effect.repeat({- schedule: Schedule.spaced(CODEX_CATALOG_REFRESH_POLL),- until: (fetchedAtMs) => fetchedAtMs >= input.spawnedAtMs,- }),- Effect.timeoutOption(CODEX_CATALOG_REFRESH_TIMEOUT),+ const models = yield* withCodexDiscoveryDeadline(+ requestAllCodexModels(input.client),+ input.deadlineMs,);- if (Option.isNone(refreshed)) {+ if (models === undefined) return undefined;+ const refreshed = yield* withCodexDiscoveryDeadline(+ readCodexModelsCacheFetchedAt(input.codexHome).pipe(+ Effect.repeat({+ schedule: Schedule.spaced(CODEX_CATALOG_REFRESH_POLL),+ until: (fetchedAtMs) => fetchedAtMs >= input.spawnedAtMs,+ }),+ ),+ input.deadlineMs,+ CODEX_CATALOG_REFRESH_TIMEOUT_MS,+ );+ if (refreshed === undefined) {yield* Effect.logWarning("Codex did not refresh its model catalog in time; using the cached catalog.",);return models;}- return yield* requestAllCodexModels(input.client);+ return (+ (yield* withCodexDiscoveryDeadline(requestAllCodexModels(input.client), input.deadlineMs)) ??+ models+ );});/**@@ -496,7 +522,6 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(funreadonly homePath?: string;readonly launchArgs?: string;readonly cwd: string;- readonly customModels?: ReadonlyArray<CustomModelSetting>;readonly environment?: NodeJS.ProcessEnv;readonly skipNativeUsage?: boolean;}) {@@ -511,42 +536,51 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(funreturn {account: accountResponse,version,- models: appendCustomCodexModels([], input.customModels ?? []),+ models: [],skills: [],} satisfies CodexAppServerProviderSnapshot;}+ // Optional discovery must finish before the outer timeout can discard the account result.+ const deadlineMs = spawnedAtMs + CODEX_AUTH_PROBE_TIMEOUT_MS - CODEX_DISCOVERY_MARGIN_MS;const [skillsResponse, models, serviceTier, rateLimits] = yield* Effect.all([- client.request("skills/list", {- cwds: [input.cwd],- }),+ withCodexDiscoveryDeadline(client.request("skills/list", { cwds: [input.cwd] }), deadlineMs),accountResponse.account?.type === "chatgpt"- ? requestCodexChatGptModels({ client, codexHome: initialize.codexHome, spawnedAtMs })- : requestAllCodexModels(client),+ ? requestCodexChatGptModels({+ client,+ codexHome: initialize.codexHome,+ spawnedAtMs,+ deadlineMs,+ })+ : withCodexDiscoveryDeadline(requestAllCodexModels(client), deadlineMs),// The shared catalog must exclude config from the server's launch project.- client.request("config/read", { includeLayers: false }).pipe(- Effect.map((response) => response.config.service_tier ?? undefined),- Effect.timeoutOption(CODEX_CONFIG_PROBE_TIMEOUT),- Effect.map(Option.getOrUndefined),+ withCodexDiscoveryDeadline(+ client.request("config/read", { includeLayers: false }),+ deadlineMs,+ CODEX_CONFIG_PROBE_TIMEOUT_MS,+ ).pipe(+ Effect.map((response) => response?.config.service_tier ?? undefined),Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined))),),// Usage is an enrichment: a failure or a slow answer degrades to "no// usage this probe" rather than costing the account and models.input.skipNativeUsage? Effect.succeed(undefined)- : client.request("account/rateLimits/read", null).pipe(- Effect.map((response): CodexRateLimitsProbe => ({- snapshot: response.rateLimits,- rateLimitsByLimitId: response.rateLimitsByLimitId,- resetCredits: response.rateLimitResetCredits,- accountId: response.accountId,- })),- Effect.timeoutOption(Duration.millis(RATE_LIMITS_PROBE_TIMEOUT_MS)),- Effect.map(- Option.getOrElse((): CodexRateLimitsProbe => ({- failure: "Codex did not answer the usage request.",- })),+ : withCodexDiscoveryDeadline(+ client.request("account/rateLimits/read", null),+ deadlineMs,+ RATE_LIMITS_PROBE_TIMEOUT_MS,+ ).pipe(+ Effect.map((response): CodexRateLimitsProbe =>+ response+ ? {+ snapshot: response.rateLimits,+ rateLimitsByLimitId: response.rateLimitsByLimitId,+ resetCredits: response.rateLimitResetCredits,+ accountId: response.accountId,+ }+ : { failure: "Codex did not answer the usage request." },),Effect.catch((error) =>Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe(@@ -562,11 +596,9 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(funaccount: accountResponse,...(rateLimits ? { rateLimits } : {}),version,- models: applyConfiguredCodexServiceTier(- applyPreferredCodexDefaultModel(appendCustomCodexModels(models, input.customModels ?? [])),- serviceTier,- ),- skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),+ models,+ serviceTier,+ skills: skillsResponse ? parseCodexSkillsListResponse(skillsResponse, input.cwd) : [],} satisfies CodexAppServerProviderSnapshot;});@@ -663,7 +695,6 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fureadonly homePath?: string;readonly launchArgs?: string;readonly cwd: string;- readonly customModels: ReadonlyArray<CustomModelSetting>;readonly environment?: NodeJS.ProcessEnv;readonly skipNativeUsage?: boolean;}) => Effect.Effect<@@ -704,12 +735,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fuhomePath: codexSettings.homePath,launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),cwd: process.cwd(),- customModels: codexSettings.customModels,environment: resolvedEnvironment,...(managedAuth ? { skipNativeUsage: true } : {}),}).pipe(- Effect.scoped,+ // Process teardown can outlast the work budget without discarding a completed snapshot.Effect.timeoutOption(Duration.millis(CODEX_AUTH_PROBE_TIMEOUT_MS)),+ Effect.scoped,Effect.result,);@@ -778,7 +809,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fupresentation: CODEX_PRESENTATION,enabled: codexSettings.enabled,checkedAt,- models: snapshot.models,+ models: applyConfiguredCodexServiceTier(+ applyPreferredCodexDefaultModel(+ appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels),+ ),+ snapshot.serviceTier,+ ),skills: snapshot.skills,slashCommands: [COMPACT_SLASH_COMMAND,@@ -796,9 +832,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fuprobe: {installed: true,version: snapshot.version ?? null,- status: accountStatus.status,+ status: snapshot.models === undefined ? "warning" : accountStatus.status,auth: accountStatus.auth,- ...(accountStatus.message ? { message: accountStatus.message } : {}),+ ...(accountStatus.message+ ? { message: accountStatus.message }+ : snapshot.models === undefined+ ? { message: "Codex did not return its model catalog in time." }+ : {}),...(managedAuth ? {} : { usageLimits }),},});diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.tsindex 644ff672d86..a44aadbd2f6 100644--- a/apps/server/src/provider/ProviderRegistry.test.ts+++ b/apps/server/src/provider/ProviderRegistry.test.ts@@ -1491,8 +1491,12 @@ it.layer(}});- it("keeps discovered models during startup and failed probes without restoring removed custom models", () => {- for (const provider of [pendingProvider, failedProvider]) {+ it("keeps discovered models during startup, errors, and discovery warnings without restoring removed custom models", () => {+ for (const provider of [+ pendingProvider,+ failedProvider,+ { ...failedProvider, status: "warning", auth: { status: "authenticated" } },+ ] satisfies ReadonlyArray<ServerProvider>) {assert.deepStrictEqual(ProviderRegistry.mergeProviderSnapshot({diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.tsindex 4927718bdc4..665c7488587 100644--- a/apps/server/src/provider/ProviderRegistry.ts+++ b/apps/server/src/provider/ProviderRegistry.ts@@ -197,10 +197,10 @@ const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean =>isAntigravity && provider.status === "warning" && provider.auth.status === "unknown";const isPendingInitialProbe =provider.enabled && !provider.installed && provider.status === "warning";- const didInstalledProviderProbeFail = provider.installed && provider.status === "error";- return (- isPendingAntigravityAuthentication || isPendingInitialProbe || didInstalledProviderProbeFail- );+ const isIncompleteInstalledProbe =+ provider.installed &&+ (provider.status === "error" || (isCodex && provider.status === "warning"));+ return isPendingAntigravityAuthentication || isPendingInitialProbe || isIncompleteInstalledProbe;};const shouldRetainMissingOpenCodeMetadata = (provider: ServerProvider): boolean =>