Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(recovery): a hung token refresh no longer wedges the single-flight latch
Jack Rudenkoe20b4083c6d0
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7f8e15ae..8c030386 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -117,7 +117,7 @@ negative case: if you are about to type one of those words, stop and use the lef- A bare Claude name (`claude-opus-5`, `opus`, `internal`) must never reach `route()`: `native-anthropic` has no credential store, so the credential filter drops it and the chain degrades to OpenRouter. Check `nativeRouteFor()` (`providers/native-route.ts`) FIRST, as the proxy does — `preflight` and the TUI probe once didn't and told agents to drop their own subscription's models. Native routes also cannot be probed from outside a session (the handler forwards the inbound Claude Code header); report them as a third outcome, never as success or failure.- A new `ClaudishProfileConfig` field MUST be added to `loadConfig`'s allowlist in `profile-config.ts`; otherwise it survives on disk until the first global save and is then dropped. Bit `onepasswordEnvironments`, then `keychain`.- A new `StatsEvent` field MUST also be pushed in `eventToLogRecord` — `stats-otlp.ts` is a HAND-WRITTEN attribute allowlist, so a field wired only into the interface and `stats.ts` is typed, buffered to `~/.claudish/stats-buffer.json`, and never sent. Nothing errors; the number is just missing from every dashboard, a quarter later. `stats-otlp.test.ts`'s table is `satisfies Record<OptionalStatsKey, …>`, so adding the field breaks compilation until it is listed there too — keep that.-- A connection failure can arrive wearing an AUTH status code, at FIVE sites in `composed-handler.ts` (`refreshAuth`, `forceRefreshAuth`, the parameter-recovery re-fetch, `getHeaders`, the primary fetch). 401 is retryable to `FallbackHandler`, so answering it for a network fault walks a subscription user onto metered billing mid-outage; an unclassified THROW is the same bug one layer out (`{status: 0}` + an unconditional advance, with no cost warning). Classify first or rethrow unchanged — never invent a status. `getHeaders()` is the non-obvious one: for `gk@` it is the request's first network touch, and refresh-conditional, so it is rare rather than safe.+- A connection failure can arrive wearing an AUTH status code, at FIVE sites in `composed-handler.ts` (`refreshAuth`, `forceRefreshAuth`, the parameter-recovery re-fetch, `getHeaders`, the primary fetch). 401 is retryable to `FallbackHandler`, so answering it for a network fault walks a subscription user onto metered billing mid-outage; an unclassified THROW is the same bug one layer out (`{status: 0}` + an unconditional advance, with no cost warning). Classify first or rethrow unchanged — never invent a status. `getHeaders()` is the non-obvious one: for `gk@` it is the request's first network touch, and refresh-conditional, so it is rare rather than safe. A TRANSPORT's own `refreshAuth` catch that returns normally is the same bug one layer earlier: `openai-codex.ts` swallowed an unreachable token host and fell through to the metered api-key path.## Commandsdiff --git a/ai-docs/architecture/network-recovery.md b/ai-docs/architecture/network-recovery.mdindex bd39dba6..5ac05565 100644--- a/ai-docs/architecture/network-recovery.md+++ b/ai-docs/architecture/network-recovery.md@@ -462,20 +462,39 @@ returning a false success to attempt two.*abandoned*, not cancelled — threading a real signal through every transport's auth call is thedeeper fix and is still worth doing.- **The reserve that buys this costs the auth path its whole budget below `API_TIMEOUT_MS = 75 s`,- silently.** The auth catches use `refreshDeadlineAt(tier1DeadlineAt(c))` = deadline − 45 s, and the- deadline is `max(15 s, min(API_TIMEOUT_MS, 300 s) − 30 s)` — so at 60 000 the auth deadline is- −15 s, `shouldSkipTier1` answers `no-budget` before attempt 1, and a stopped local server or a- failed token exchange gets today's immediate 400 while the FETCH path on the same machine still- recovers. Measured on a real run: `[Recovery] skipped (no-budget) … site=refreshAuth` at t+0 with- `API_TIMEOUT_MS=60000`. It is inside the design, not a bug, but it is a whole fault class losing- recovery on a user-settable knob with nothing printed — the shape RISK-7 and the truncated rung- both have. A floor, or a `[Recovery]` line when the reserve eats the budget, is the fix; and any- harness that shortens a local-provider run this way is testing a path that is switched off.+ **Abandoning is only bounded if the operation is.** Grok and Codex refresh behind a single-flight+ latch (both servers ROTATE the refresh token, so two concurrent refreshes produce `invalid_grant`).+ With no ceiling on the refresh `fetch`, a half-open socket held the latch until the kernel's+ retransmit timeout — minutes — and every attempt `untilAborted` abandoned was followed by one that+ re-entered the latch and joined the same dead promise: attempts in the banner and the log that+ never reached the network. Both refreshes now carry `TOKEN_REFRESH_TIMEOUT_MS` (20 s), BELOW the+ 45 s per-attempt cap, so a hung refresh fails inside its own attempt and the latch clears; the+ latch itself stays. Its `TimeoutError` is tagged `markOwnTimeout`, because a token host that does+ not answer in 20 s is a reachability fact — measured: untagged it classifies `null`, tagged it+ classifies `unreachable`, and for Codex `null` would mean the metered fallback. Antigravity's+ refresh already ran under a 12 s subprocess timeout.++ **The reserve that buys this cost the auth path its whole budget below `API_TIMEOUT_MS = 75 s`,+ silently — fixed.** The auth catches use `refreshDeadlineAt(tier1DeadlineAt(c))`, which reserved a+ flat 45 s against a deadline of `max(15 s, min(API_TIMEOUT_MS, 300 s) − 30 s)` — so at 60 000 the+ auth deadline was −15 s, `shouldSkipTier1` answered `no-budget` before attempt 1, and a failed token+ exchange got the immediate 400 while the FETCH path on the same machine still recovered (measured:+ `[Recovery] skipped (no-budget) … site=refreshAuth` at t+0). The reserve is now capped at half the+ budget: unchanged at the default (45 s), 22.5 s of auth budget at 75 000 where there was none. What+ the reserve still buys is the primary fetch's right to a real attempt after a slow refresh — the+ request ceiling (`deadlineClamp`) already stops that fetch outliving the deadline on its own.- **The error must name the host that actually failed.** `connectionEndpointFor` falls back to theMODEL endpoint when the error carries no `claudishEndpoint`, so an `auth.x.ai` outage was reported- — in the banner, in the log and in the episode key — as `api.x.ai`. Grok's refresh wrapper now- attaches it, as `local.ts` already did.+ — in the banner, in the log and in the episode key — as `api.x.ai`. Grok's and Codex's refresh+ wrappers now attach it, as `local.ts` already did.+- **A transport can swallow the failure before any of the five sites sees it.** `openai-codex.ts`'s+ `refreshAuth` caught EVERY throw from the credential authority and fell through to the api-key+ path — the METERED `api.openai.com`. That fallback is meant for a REJECTED refresh; a refresh that+ merely could not reach `auth.openai.com` took it too, billing a subscriber per token for an outage.+ It now rethrows a classified connection failure, so the `refreshAuth` site holds it like any other.+ The credential's own error said "OAuth credentials invalid. Please run `claudish login codex`+ again" for a network failure; it now says "Could not reach …", with `{ cause }`. When auditing a+ new transport, look for a `catch` in `refreshAuth`/`getHeaders` that returns normally.- **`noteTargetReachable` closes by PROVIDER, not by host.** Because an auth episode can be keyed ona different host than the one a later success reaches, a strict key lookup missed it and the bannerpainted "waiting for Claude Code to retry" over a working session for the full 120 s grace. Adiff --git a/packages/cli/src/auth/codex-oauth.ts b/packages/cli/src/auth/codex-oauth.tsindex 01f19067..09ae4378 100644--- a/packages/cli/src/auth/codex-oauth.ts+++ b/packages/cli/src/auth/codex-oauth.ts@@ -19,6 +19,8 @@ import { type IncomingMessage, type ServerResponse, createServer } from "node:htimport { homedir } from "node:os";import { join } from "node:path";import { promisify } from "node:util";+import { markOwnTimeout } from "../handlers/shared/connection-error.js";+import { TOKEN_REFRESH_TIMEOUT_MS } from "../handlers/shared/transient-retry.js";import { log } from "../logger.js";const execAsync = promisify(exec);@@ -271,13 +273,20 @@ export class CodexOAuth {refresh_token: this.credentials.refresh_token,client_id: OAUTH_CONFIG.clientId,}),+ // Bounds `refreshPromise`'s single-flight latch — see+ // TOKEN_REFRESH_TIMEOUT_MS.+ signal: AbortSignal.timeout(TOKEN_REFRESH_TIMEOUT_MS),});} catch (e) {log(`[CodexOAuth] Could not reach ${OAUTH_CONFIG.tokenUrl}: ${(e as Error).message}`);+ // `markOwnTimeout`: the ceiling above is ours, so its `TimeoutError` is a+ // reachability fact. Untagged it would go unclassified, and+ // `openai-codex.ts` would read it as a rejected refresh and fall back to+ // the METERED api-key path — the bug this function was just fixed for.throw Object.assign(new Error(`Could not reach ${OAUTH_CONFIG.tokenUrl} to refresh the Codex token: ${(e as Error).message}`,- { cause: e }+ { cause: markOwnTimeout(e) }),{ claudishEndpoint: OAUTH_CONFIG.tokenUrl });diff --git a/packages/cli/src/handlers/shared/transient-retry.ts b/packages/cli/src/handlers/shared/transient-retry.tsindex 2632882a..5e39aa1e 100644--- a/packages/cli/src/handlers/shared/transient-retry.ts+++ b/packages/cli/src/handlers/shared/transient-retry.ts@@ -76,6 +76,28 @@ export const PER_ATTEMPT_CONNECT_CAP_MS = 45_000;/** Below this much budget remaining, do not start another attempt. */export const MIN_ATTEMPT_SLOT_MS = 3_000;+/**+ * Ceiling on ONE OAuth token-refresh request (Grok, Codex).+ *+ * Both refreshes sit behind a single-flight latch, because the servers ROTATE+ * the refresh token and two concurrent refreshes turn a working session into+ * `invalid_grant`. With no ceiling, a refresh on a half-open socket — the+ * network gone after the handshake — waited out the kernel's retransmit+ * timeout, minutes long. The ladder's clamp abandons an attempt, not the+ * fetch under it, so every later attempt re-entered the latch and joined the+ * same dead promise: attempts counted in the banner and the log that never+ * reached the network, and real recovery delayed until the kernel gave up.+ *+ * The ceiling bounds how long the latch can be held, which keeps the latch.+ * It is BELOW `PER_ATTEMPT_CONNECT_CAP_MS` so that a hung refresh fails inside+ * its own attempt instead of being abandoned by the clamp. Callers must tag+ * the resulting `TimeoutError` with `markOwnTimeout`: a token host that does+ * not answer in 20 s is a reachability fact, unlike an inference ceiling, and+ * left untagged it would go unclassified — which for Codex means the METERED+ * fallback.+ */+export const TOKEN_REFRESH_TIMEOUT_MS = 20_000;+/*** The deadline the AUTH-path catches use, deliberately earlier than the fetch* catch's.diff --git a/packages/cli/src/providers/grok/grok-credentials.ts b/packages/cli/src/providers/grok/grok-credentials.tsindex c56a29c3..f4e2bd10 100644--- a/packages/cli/src/providers/grok/grok-credentials.ts+++ b/packages/cli/src/providers/grok/grok-credentials.ts@@ -43,6 +43,8 @@ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";import { GROK_PUBLIC_CLIENT_ID, GrokOAuth } from "../../auth/grok-oauth.js";+import { markOwnTimeout } from "../../handlers/shared/connection-error.js";+import { TOKEN_REFRESH_TIMEOUT_MS } from "../../handlers/shared/transient-retry.js";/** Base-URL override, the same variable the Grok CLI installer honours. */export const GROK_PROXY_URL_ENV = "GROK_PROXY_URL";@@ -419,6 +421,8 @@ async function performRefresh(cred: GrokCredential): Promise<string> {method: "POST",headers: { "Content-Type": "application/x-www-form-urlencoded" },body,+ // Bounds the single-flight latch below — see TOKEN_REFRESH_TIMEOUT_MS.+ signal: AbortSignal.timeout(TOKEN_REFRESH_TIMEOUT_MS),});} catch (error) {// A network failure is NOT terminal — it can self-heal, so let the normal@@ -436,10 +440,13 @@ async function performRefresh(cred: GrokCredential): Promise<string> {// reported — in the banner, in the log, and in the episode key — as// `api.x.ai`: the wrong host, and the wrong advice for a user trying to fix// it. `local.ts` attaches the same property for the same reason.+ //+ // `markOwnTimeout`: the ceiling above is ours, so a `TimeoutError` from it+ // is a reachability fact about the auth host, and must classify as one.throw Object.assign(new Error(`Could not reach ${tokenEndpoint} to refresh the Grok token: ${(error as Error).message}`,- { cause: error }+ { cause: markOwnTimeout(error) }),{ claudishEndpoint: tokenEndpoint });diff --git a/packages/cli/src/providers/grok/grok-refresh-timeout.test.ts b/packages/cli/src/providers/grok/grok-refresh-timeout.test.tsnew file mode 100644index 00000000..b43d2de0--- /dev/null+++ b/packages/cli/src/providers/grok/grok-refresh-timeout.test.ts@@ -0,0 +1,206 @@+/**+ * Black-box tests: the Grok OAuth token refresh must not hang on a half-open token host.+ *+ * Spec (from the caller's brief): claudish refreshes an expired Grok OAuth token by POSTing+ * to `<issuer>/oauth2/token` behind a single-flight latch. The refresh must give up after+ * TOKEN_REFRESH_TIMEOUT_MS (20000 ms), fail as a CONNECTION error that names the token host,+ * release the latch, and still share ONE in-flight refresh between concurrent callers.+ *+ * Coverage map (requirement -> test):+ * REQ-0 the ceiling is 20000 ms -> "REQ-0 ..."+ * REQ-T1 hung host -> rejects within ~ceiling (< 30 s) -> "REQ-T1 ..."+ * REQ-T2 the rejection classifies as "unreachable" -> "REQ-T2 ..."+ * REQ-T3 the rejection carries claudishEndpoint -> "REQ-T3 ..."+ * REQ-T4 the latch clears: 2 sequential calls = 2 POSTs -> "REQ-T4 ..."+ * REQ-T5 2 concurrent calls = exactly 1 POST -> "REQ-T5 ..."+ *+ * The hung host is a real `Bun.serve` on an ephemeral port, so the real client and its real+ * timeout are exercised: no fetch double, no module mock. These tests genuinely wait out the+ * ceiling (about 20 s per call), so each carries its own generous per-test timeout.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { classifyConnectionError } from "../../handlers/shared/connection-error.js";+import { TOKEN_REFRESH_TIMEOUT_MS } from "../../handlers/shared/transient-retry.js";+import { resolveGrokAccessToken, setGrokHomeForTesting } from "./grok-credentials.js";++const OIDC_SCOPE = "https://auth.x.ai::TEST-CLIENT-ID";++/** "About TOKEN_REFRESH_TIMEOUT_MS" with the generous slack the spec allows: < 30 s. */+const SETTLE_LIMIT_MS = TOKEN_REFRESH_TIMEOUT_MS + 10_000;+/** Per-test budgets, well above the ceiling so the in-test deadline reports first. */+const ONE_CALL_BUDGET_MS = 60_000;+const TWO_CALL_BUDGET_MS = 90_000;++const TOKEN_POST = { method: "POST", path: "/oauth2/token" } as const;++type Settled =+ | { state: "rejected"; error: unknown; elapsedMs: number }+ | { state: "resolved"; value: unknown; elapsedMs: number }+ | { state: "pending"; elapsedMs: number };++/**+ * Wait for `promise` to settle, but never longer than `limitMs`. A call that is still+ * unsettled at the deadline reports `pending` instead of hanging the test, so a missing+ * timeout shows up as a readable assertion failure rather than only as a test timeout.+ * Call this immediately after starting the operation: elapsedMs is measured from here.+ */+async function settleWithin(promise: Promise<unknown>, limitMs: number): Promise<Settled> {+ const startedAt = performance.now();+ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = new Promise<"deadline">((resolve) => {+ timer = setTimeout(() => resolve("deadline"), limitMs);+ });+ try {+ const outcome = await Promise.race([+ promise.then(+ (value) => ({ state: "resolved" as const, value }),+ (error: unknown) => ({ state: "rejected" as const, error })+ ),+ deadline,+ ]);+ const elapsedMs = performance.now() - startedAt;+ if (outcome === "deadline") return { state: "pending", elapsedMs };+ return { ...outcome, elapsedMs };+ } finally {+ clearTimeout(timer);+ }+}++function rejectionOf(outcome: Settled): unknown {+ expect(outcome.state).toBe("rejected");+ if (outcome.state !== "rejected") throw new Error(`expected a rejection, got ${outcome.state}`);+ return outcome.error;+}++let grokHome: string;+let tokenHost: ReturnType<typeof Bun.serve>;+let tokenRequests: Array<{ method: string; path: string }>;+let issuer: string;+let tokenEndpoint: string;++beforeEach(() => {+ tokenRequests = [];+ tokenHost = Bun.serve({+ hostname: "127.0.0.1",+ port: 0,+ // Bun's server closes a connection whose handler has not answered within `idleTimeout`+ // seconds (default 10). That server-side close would reject the client FOR us and hide+ // a missing client-side timeout, so it is disabled: this host accepts and stays silent+ // for as long as the client is willing to wait — the half-open socket from the spec.+ idleTimeout: 0,+ fetch(req) {+ tokenRequests.push({ method: req.method, path: new URL(req.url).pathname });+ return new Promise<Response>(() => {});+ },+ });+ issuer = `http://127.0.0.1:${tokenHost.port}`;+ tokenEndpoint = `${issuer}/oauth2/token`;++ grokHome = mkdtempSync(join(tmpdir(), "claudish-grok-refresh-timeout-"));+ setGrokHomeForTesting(grokHome);+ writeFileSync(+ join(grokHome, "auth.json"),+ `${JSON.stringify(+ {+ [OIDC_SCOPE]: {+ key: "tok-old",+ refresh_token: "ref-old",+ expires_at: "2000-01-01T00:00:00.000Z",+ auth_mode: "oidc",+ oidc_issuer: issuer,+ oidc_client_id: "TEST-CLIENT-ID",+ },+ },+ null,+ 2+ )}\n`+ );+});++afterEach(async () => {+ setGrokHomeForTesting(null);+ await tokenHost.stop(true);+ rmSync(grokHome, { recursive: true, force: true });+});++describe("Grok token refresh against a token host that accepts and never answers", () => {+ test("REQ-0: the refresh ceiling TOKEN_REFRESH_TIMEOUT_MS is 20000 ms", () => {+ expect(TOKEN_REFRESH_TIMEOUT_MS).toBe(20_000);+ });++ test(+ "REQ-T1: resolveGrokAccessToken rejects instead of hanging, within about the refresh ceiling",+ async () => {+ const outcome = await settleWithin(resolveGrokAccessToken(), SETTLE_LIMIT_MS);++ // A hung refresh holds the single-flight latch, so every later request would join it.+ expect(outcome.state).toBe("rejected");+ expect(outcome.elapsedMs).toBeLessThan(SETTLE_LIMIT_MS);+ // The rejection came from the hung token host, not from a precondition failing first.+ expect(tokenRequests).toEqual([TOKEN_POST]);+ },+ ONE_CALL_BUDGET_MS+ );++ test(+ "REQ-T2: the timed-out refresh is classified as a connection failure of kind unreachable",+ async () => {+ const error = rejectionOf(await settleWithin(resolveGrokAccessToken(), SETTLE_LIMIT_MS));++ // Unclassified, this error would escape into the fallback chain (metered billing).+ expect(classifyConnectionError(error)).toEqual({+ kind: "unreachable",+ code: expect.any(String),+ });+ },+ ONE_CALL_BUDGET_MS+ );++ test(+ "REQ-T3: the timed-out refresh names the token endpoint as claudishEndpoint",+ async () => {+ const error = rejectionOf(await settleWithin(resolveGrokAccessToken(), SETTLE_LIMIT_MS));++ // The user must be told about the AUTH host that went silent, not the inference host.+ expect((error as { claudishEndpoint?: unknown }).claudishEndpoint).toBe(tokenEndpoint);+ },+ ONE_CALL_BUDGET_MS+ );++ test(+ "REQ-T4: after a timed-out refresh the latch is released, so the next call makes a new request",+ async () => {+ const first = await settleWithin(resolveGrokAccessToken(), SETTLE_LIMIT_MS);+ expect(first.state).toBe("rejected");+ expect(tokenRequests).toEqual([TOKEN_POST]);++ const second = await settleWithin(resolveGrokAccessToken(), SETTLE_LIMIT_MS);++ // A latch left holding the dead promise would answer the second call with no request.+ expect(second.state).toBe("rejected");+ expect(tokenRequests).toEqual([TOKEN_POST, TOKEN_POST]);+ },+ TWO_CALL_BUDGET_MS+ );++ test(+ "REQ-T5: two concurrent calls against the hung host send exactly one refresh request",+ async () => {+ const firstCall = resolveGrokAccessToken();+ const secondCall = resolveGrokAccessToken();++ const outcomes = await Promise.all([+ settleWithin(firstCall, SETTLE_LIMIT_MS),+ settleWithin(secondCall, SETTLE_LIMIT_MS),+ ]);++ expect(outcomes.map((o) => o.state)).toEqual(["rejected", "rejected"]);+ // The server rotates the refresh token; a second concurrent refresh breaks the session.+ expect(tokenRequests).toEqual([TOKEN_POST]);+ },+ ONE_CALL_BUDGET_MS+ );+});