Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(catalog): log refresh failures and retry a refresh that threw
Jack Rudenkoc297881dee87
diff --git a/packages/cli/src/providers/catalog-client.ts b/packages/cli/src/providers/catalog-client.tsindex 211dec98..38619ed8 100644--- a/packages/cli/src/providers/catalog-client.ts+++ b/packages/cli/src/providers/catalog-client.ts@@ -1,3 +1,4 @@+import { log } from "../logger.js";import {type CachedSubscriptionPlan,type DiskCacheV3,@@ -584,9 +585,22 @@ async function fetchRouteRegistry(function startCatalogWarm(): Promise<void> {if (_warmPromise) return _warmPromise;- const promise = refreshCatalog(8000).then((result) => {- if (result.kind !== "refreshed" && _warmPromise === promise) _warmPromise = null;- });+ const promise = refreshCatalog(8000).then(+ (result) => {+ if (result.kind === "refreshed") return;+ // Without this line the reason is lost: callers only see "no snapshot".+ log(+ `[catalog] refresh failed: ${result.kind === "fetch_failed" ? result.reason : `incompatible contract ${result.serverContractVersion ?? "unknown"}`}`+ );+ if (_warmPromise === promise) _warmPromise = null;+ },+ (err: unknown) => {+ // A throw (a cache write refused, a bad CLAUDISH_CATALOG_URL) must not stay+ // the answer for the life of the process: the next caller tries again.+ log(`[catalog] refresh threw: ${err instanceof Error ? err.message : String(err)}`);+ if (_warmPromise === promise) _warmPromise = null;+ }+ );_warmPromise = promise;return promise;}@@ -625,8 +639,16 @@ export async function ensureRouteRegistryReady(timeoutMs = 5000): Promise<void>}async function waitForCatalogWarm(timeoutMs: number): Promise<void> {+ let timedOut = false;await Promise.race([startCatalogWarm(),- new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),+ new Promise<void>((resolve) =>+ setTimeout(() => {+ timedOut = true;+ resolve();+ }, timeoutMs)+ ),]);+ if (timedOut)+ log(`[catalog] still refreshing after ${timeoutMs} ms; the caller goes on without it`);}diff --git a/packages/cli/src/providers/catalog-warm-retry.test.ts b/packages/cli/src/providers/catalog-warm-retry.test.tsnew file mode 100644index 00000000..14edcf2e--- /dev/null+++ b/packages/cli/src/providers/catalog-warm-retry.test.ts@@ -0,0 +1,92 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL } from "node:url";++let root: string;+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "claudish-warm-retry-"));+});+afterEach(() => rmSync(root, { recursive: true, force: true }));++const catalogUrl = pathToFileURL(join(import.meta.dir, "catalog-client.ts")).href;+const loggerUrl = pathToFileURL(join(import.meta.dir, "..", "logger.ts")).href;++async function runWarm(url: string): Promise<{ fetches: number; log: string }> {+ const child = Bun.spawn(+ [+ process.execPath,+ "--no-env-file",+ "-e",+ `+ import { homedir } from "node:os";+ if (homedir() !== process.env.HOME) throw new Error("HOME isolation failed");+ let fetches = 0;+ const rejectFetch = async () => { fetches++; throw new Error("Network blocked by test"); };+ rejectFetch.preconnect = () => { throw new Error("Network preconnect forbidden"); };+ globalThis.fetch = rejectFetch;+ const { initLogger } = await import(${JSON.stringify(loggerUrl)});+ initLogger(false, "info", false, "claudish-mcp");+ const { warmCatalog } = await import(${JSON.stringify(catalogUrl)});+ await warmCatalog();+ await warmCatalog();+ console.log(JSON.stringify({ fetches }));+ process.exit(0);+ `,+ ],+ {+ cwd: root,+ env: {+ PATH: process.env.PATH ?? "",+ HOME: root,+ USERPROFILE: root,+ ZDOTDIR: root,+ XDG_CONFIG_HOME: join(root, ".config"),+ CLAUDE_CONFIG_DIR: join(root, ".claude"),+ CLAUDISH_CATALOG_URL: url,+ CLAUDISH_DISABLE_KEYCHAIN: "1",+ CLAUDISH_DISABLE_OP: "1",+ CLAUDISH_NO_PREDEFINED_ENDPOINTS: "1",+ },+ stdin: "ignore",+ stdout: "pipe",+ stderr: "pipe",+ }+ );+ const timer = setTimeout(() => child.kill("SIGKILL"), 5000);+ try {+ const [stdout, stderr, exit] = await Promise.all([+ new Response(child.stdout).text(),+ new Response(child.stderr).text(),+ child.exited,+ ]);+ expect({ exit, stderr }).toEqual({ exit: 0, stderr: "" });+ const logDir = join(root, ".claudish", "logs");+ const files = readdirSync(logDir);+ expect(files).toHaveLength(1);+ return {+ fetches: (JSON.parse(stdout) as { fetches: number }).fetches,+ log: readFileSync(join(logDir, files[0]), "utf8"),+ };+ } finally {+ clearTimeout(timer);+ if (child.exitCode === null) child.kill("SIGKILL");+ await child.exited;+ }+}++describe("startCatalogWarm failures via public warmCatalog", () => {+ test("logs failed refresh reasons and retries rather than caching failure", async () => {+ const result = await runWarm("https://catalog.test/queryModels?catalog=slim");+ expect(result.fetches).toBe(2);+ expect(result.log.match(/\[catalog\] refresh failed: network/g)).toHaveLength(2);+ });++ test("logs a thrown refresh and the next call tries again", async () => {+ const result = await runWarm("not a valid URL");+ expect(result.fetches).toBe(0);+ expect(result.log.match(/\[catalog\] refresh threw:/g)).toHaveLength(2);+ expect(result.log).toContain("Invalid URL");+ });+});