#5149 · Empty catalog persistence and query recovery
Verdict: PARTIALLY REPRODUCED · Root-cause confidence: medium overall; high for empty-cache persistence, low for the reported permanent lock.
1. TL;DR
A successful catalog response with no models is indeed saved to renderer localStorage. However, an enabled execution-options query still fetches after a simulated renderer restart and replaces that empty placeholder with a healthy catalog. This happened in both clean checkouts of trusted main. Explicitly disabling the query produces the reported combination of successful placeholder data, idle fetch status, no prior fetch, and isStale: false; enabling it starts the fetch. Empty persistence alone therefore does not explain the permanent failure, and this investigation does not establish which missing condition held in the desktop incident.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| An empty successful response is persisted. | Verified | The first added test executes the actual hook and reads the actual cache: both model arrays are empty. |
| An empty cached placeholder prevents an enabled never-fetched query from loading on mount. | Not supported at this boundary | A fresh QueryClient loads the empty placeholder, starts exactly one SDK request, and accepts the subsequent nonempty response. |
| The reported idle, never-fetched, non-stale placeholder state is possible. | Verified with an additional condition | The second added test observes all seven query-state fields when enabled: false; changing to true starts the request. |
| A stale provider preference can influence the request route. | Code finding only | A stored provider wins before availability is checked, while the ready-provider fallback is gated on an empty selection. This was not established as the cause of this incident. |
| The desktop picker remains blocked across real restarts after Pi credentials are repaired. | Unverified | No macOS/Electron or real credential reproduction was attempted. Query lifecycle evidence does not reproduce this claim. |
3. Environment and isolation
- Trusted target: public
get-bb/bb; full base commit7ea48db13ebed5371b057ca024260e213ec63d0c, fetched from itsorigin/main. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.1; TanStack React Query 5.90.20; jsdom hook environment.
- Two separately cloned source directories. Each installs the frozen lockfile; each test run uses fresh in-memory QueryClients and jsdom localStorage. The second run forces execution instead of using cached test results.
- No server, host daemon, browser session, ports, database directory, real provider credentials, or live user state was used. Only the SDK transport response is stubbed; the app hook, query client factory, TanStack lifecycle, validation, and storage code are real.
- The first checkout's full
pnpm exec turbo run buildcompleted: 64 successful tasks, 4 cached. Both focused suites completed successfully.
4. Minimal repeatable reproduction
- Clone the trusted repository into a new scratch checkout and detach at the recorded base:
git clone --branch main --single-branch https://github.com/get-bb/bb.git bb-5149-check cd bb-5149-check git checkout --detach 7ea48db13ebed5371b057ca024260e213ec63d0c pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build
- Save the patch in the next block as
/tmp/catalog-recovery.patch, apply it, and run the owning suite:git apply /tmp/catalog-recovery.patch pnpm exec turbo run test --filter=@bb/app --force -- src/hooks/queries/system-queries.test.tsx
- The first test fetches an empty successful Pi catalog, verifies the persisted empty arrays, unmounts, clears the first QueryClient, and creates another QueryClient with the same localStorage. It holds the next SDK response pending to observe the placeholder and in-flight request, then returns a nonempty catalog.
- The second test repeats the empty warm-up but disables the new query. It verifies the idle query-state signature, then enables the query and verifies that it fetches.
Expected if the proposed permanent-cache mechanism were sufficient: the enabled restarted query would stay idle and would not request the recovered catalog. Actual: it calls the SDK once, reports fetching while the response is pending, then exposes the recovered model and isFetchedAfterMount: true. The expected-recovery assertions pass on unchanged production code, so they do not qualify as a failing-before-fix regression.
Complete reproduction patch (copy this block into the patch file)
diff --git a/apps/app/src/hooks/queries/system-queries.test.tsx b/apps/app/src/hooks/queries/system-queries.test.tsx
index 71bb70810..e232a61a6 100644
--- a/apps/app/src/hooks/queries/system-queries.test.tsx
+++ b/apps/app/src/hooks/queries/system-queries.test.tsx
@@ -12,6 +12,10 @@ import type { ProviderCliStatusResponse } from "@bb/host-daemon-contract";
import { afterEach, describe, expect, it, vi } from "vitest";
import { sdk } from "@/lib/sdk";
import { createQueryClientTestHarness } from "@/test/queryClientTestHarness";
+import {
+ modelCatalogCacheKey,
+ readCachedModelCatalog,
+} from "@/lib/model-catalog-cache";
import {
hostProviderCliStatusQueryKey,
systemExecutionOptionsQueryKey,
@@ -360,6 +364,95 @@ describe("useSystemExecutionOptions", () => {
};
const pendingForever = () => new Promise<never>(() => {});
+ it("recovers a persisted empty catalog after a renderer restart", async () => {
+ const routing = { hostId: "host-repro", providerId: "pi" };
+ const emptyCatalog: SystemExecutionOptionsResponse = {
+ ...EXECUTION_OPTIONS_RESPONSE,
+ providers: [makeProviderInfo({ id: "pi" })],
+ };
+ const recoveredCatalog: SystemExecutionOptionsResponse = {
+ ...emptyCatalog,
+ models: [{ ...CODEX_MODEL, id: "repro-model", model: "repro-model" }],
+ };
+ vi.mocked(sdk.system.executionOptions).mockResolvedValue(emptyCatalog);
+ const first = createQueryClientTestHarness();
+ const initial = renderHook(() => useSystemExecutionOptions(routing), {
+ wrapper: first.wrapper,
+ });
+ await waitFor(() => expect(initial.result.current.isFetched).toBe(true));
+ expect(initial.result.current.data?.models).toEqual([]);
+ expect(
+ readCachedModelCatalog(
+ modelCatalogCacheKey({ environmentId: null, ...routing }),
+ ),
+ ).toEqual({ models: [], selectedOnlyModels: [] });
+ initial.unmount();
+ first.queryClient.clear();
+ vi.mocked(sdk.system.executionOptions).mockClear();
+ let finishRecovery: (
+ response: SystemExecutionOptionsResponse,
+ ) => void = () => {};
+ vi.mocked(sdk.system.executionOptions).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finishRecovery = resolve;
+ }),
+ );
+ const restarted = createQueryClientTestHarness();
+ const recovered = renderHook(() => useSystemExecutionOptions(routing), {
+ wrapper: restarted.wrapper,
+ });
+ expect(recovered.result.current.isPlaceholderData).toBe(true);
+ expect(recovered.result.current.data?.models).toEqual([]);
+ await waitFor(() =>
+ expect(sdk.system.executionOptions).toHaveBeenCalledTimes(1),
+ );
+ expect(recovered.result.current.fetchStatus).toBe("fetching");
+ await act(async () => finishRecovery(recoveredCatalog));
+ await waitFor(() =>
+ expect(recovered.result.current.data?.models).toEqual(
+ recoveredCatalog.models,
+ ),
+ );
+ expect(recovered.result.current.isFetchedAfterMount).toBe(true);
+ expect(recovered.result.current.isPlaceholderData).toBe(false);
+ });
+
+ it("leaves a persisted empty placeholder idle only while explicitly disabled", async () => {
+ const routing = { hostId: "host-disabled", providerId: "pi" };
+ const emptyCatalog: SystemExecutionOptionsResponse = {
+ ...EXECUTION_OPTIONS_RESPONSE,
+ providers: [makeProviderInfo({ id: "pi" })],
+ };
+ vi.mocked(sdk.system.executionOptions).mockResolvedValue(emptyCatalog);
+ const first = createQueryClientTestHarness();
+ const initial = renderHook(() => useSystemExecutionOptions(routing), {
+ wrapper: first.wrapper,
+ });
+ await waitFor(() => expect(initial.result.current.isFetched).toBe(true));
+ initial.unmount();
+ first.queryClient.clear();
+ vi.mocked(sdk.system.executionOptions).mockClear();
+ const restarted = createQueryClientTestHarness();
+ const disabled = renderHook(
+ ({ enabled }) => useSystemExecutionOptions({ ...routing, enabled }),
+ { wrapper: restarted.wrapper, initialProps: { enabled: false } },
+ );
+ expect(disabled.result.current).toMatchObject({
+ status: "success",
+ fetchStatus: "idle",
+ isFetched: false,
+ isFetchedAfterMount: false,
+ isStale: false,
+ isPlaceholderData: true,
+ dataUpdatedAt: 0,
+ });
+ expect(sdk.system.executionOptions).not.toHaveBeenCalled();
+ disabled.rerender({ enabled: true });
+ await waitFor(() => expect(disabled.result.current.isFetched).toBe(true));
+ expect(sdk.system.executionOptions).toHaveBeenCalledTimes(1);
+ });
+
it("preloads a provider's last verified catalog until the probe lands", async () => {
vi.mocked(sdk.system.executionOptions).mockResolvedValue(CODEX_CATALOG);
const first = createQueryClientTestHarness();
@@ -510,13 +603,16 @@ describe("useSystemExecutionOptions", () => {
};
vi.mocked(sdk.system.executionOptions).mockResolvedValue(initialCatalog);
const { result } = renderHook(
- () =>
- useSystemExecutionOptions({ hostId: "host-a", providerId }),
+ () => useSystemExecutionOptions({ hostId: "host-a", providerId }),
{ wrapper },
);
await waitFor(() => expect(result.current.data).toEqual(initialCatalog));
const loadedAt = result.current.dataUpdatedAt;
- const modelLoadError = { providerId: refreshProviderId, code, detail: null };
+ const modelLoadError = {
+ providerId: refreshProviderId,
+ code,
+ detail: null,
+ };
vi.mocked(sdk.system.executionOptions).mockResolvedValue({
...CODEX_CATALOG,
providers: [makeProviderInfo({ id: refreshProviderId })],
The exact disabled-state assertions that pass are:
{
status: "success",
fetchStatus: "idle",
isFetched: false,
isFetchedAfterMount: false,
isStale: false,
isPlaceholderData: true,
dataUpdatedAt: 0
}
5. Root cause and limits
Confirmed persistence mechanism: the response write path checks only response.modelLoadError === null before saving the catalog. An empty successful catalog therefore qualifies. The placeholder resolver can read those empty arrays and presents them with no load error.
if (response.modelLoadError === null) {
const catalog = {
models: response.models,
selectedOnlyModels: response.selectedOnlyModels,
};
writeCachedModelCatalog(
modelCatalogCacheKey({ environmentId, hostId, providerId }),
catalog,
);
}
This is not proof of a permanent lock: the public query hook defaults to enabled and supplies the saved data as placeholderData, not as fetched query data. The installed TanStack queryObserver.ts loads an enabled query on mount when query.state.data === undefined. Its isStale calculation also explicitly returns false for a disabled query. Both behaviors were exercised rather than inferred solely from source.
Unresolved routing risk: stored provider selection precedes availability checking, and ready-provider discovery only runs for an empty stored selection. The issue's additional stale-provider allegation is a separate hypothesis, not a verified explanation for why a Pi-only recovery would never fetch.
6. Fix proposal and simple-fix gate
No production fix or pull request is offered. The reported permanent failure has not been reproduced on trusted main, and there is no focused regression that fails before a fix for that failure. Merely skipping empty writes would not explain or repair an explicitly disabled query or an incorrectly routed provider request.
The next decisive experiment is an isolated desktop reproduction that records the mounted composer's execution-options enabled value, actual query key/provider route, observer identity, and request activity before and after credential repair. If an empty response overwrites a useful prior catalog, deciding whether to retain it is a separate cache-policy question: a legitimate zero-model response must not silently become an indefinitely stale nonempty catalog.
7. Verification: second clean checkout
The same agent cloned a second checkout from the trusted repository, detached it at the exact recorded base, installed the frozen lockfile, and applied only the locally authored reproduction patch. No production file changed. A forced Turbo test run repeated all 28 tests with fresh query clients and fresh jsdom storage. Without sharing the first checkout's runtime state, it confirmed empty persistence, successful enabled-query recovery, and the disabled-state control. This is a second clean run by the same investigator, not an independent-agent review.
No ports or instance data directories exist because neither run needed a live instance. No report correction was necessary after the second run.
First clean run:
✓ |@bb/app:isolated| src/hooks/queries/system-queries.test.tsx (28 tests) 2458ms
Test Files 1 passed (1)
Tests 28 passed (28)
Start at 22:45:26
Duration 6.08s
Tasks: 5 successful, 5 total; Cached: 0 cached, 5 total
Second clean run (--force):
✓ |@bb/app:isolated| src/hooks/queries/system-queries.test.tsx (28 tests) 2462ms
Test Files 1 passed (1)
Tests 28 passed (28)
Start at 22:46:22
Duration 6.06s
Tasks: 5 successful, 5 total; Cached: 0 cached, 5 total
8. Linked pull requests and related issues
No open linked pull request was found by an issue-number search or the issue's cross-reference/connected-event metadata at investigation time. Other model-catalog reports exist, but this report does not assume they share the mechanism.
9. Evidence handling
Issue content was treated as untrusted claims. No issue-supplied command, patch, branch, script, external link, or test was executed or fetched. The reproduction was authored from trusted main code and existing owning-package test patterns. Public evidence is self-contained in this HTML; raw logs and scratch checkouts remain local. There is no screenshot because this report verifies the query/storage boundary, not the macOS visual incident.
Reproduction label: partial-repro. The original permanent desktop symptom remains unresolved; the partial verdict is not a claim that it is fixed.
> AGENT GENERATED