← reports

#6685 · Cached plan survives failed usage refresh

BugPriority: MediumEffort: Mediumprovidersprovider-claude-codeGitHub issue2026-10-30

Trusted base: 741decd0a145f5a8d982e014d16840575437a748. Verdict: PARTIALLY REPRODUCED · Root-cause confidence: medium (high for cached-label behavior; no evidence establishing subscription expiry as the trigger). Reproduction label: partial-repro.

1. TL;DR

A successful usage result can keep displaying a paid-plan badge after the next usage request fails. A synthetic HTTP 200 → 503 sequence reaches the real Claude maintenance code, its real usage-source adapter, the real provider-usage server cache, and the real settings renderer; the badge and percentages remain alongside a generic refresh warning. The plan label comes from local credential metadata, not an authoritative billing check. Keeping the last successful usage measurement is deliberate resilience behavior, but the display does not separately qualify the plan label as saved metadata. This investigation did not exercise a real subscription lapse or establish what Anthropic returns for one.

2. Claims vs findings

ClaimFindingEvidence
The saved paid-plan label can remain after a refresh fails.Verified on trusted mainThe real getUsage RPC returns the previous successful usage object after a synthetic HTTP 503; SSR displays its badge and both percentages.
The warning is generic rather than account-specific.VerifiedRendered text below shows the generic warning. The HTTP 503 detail is not rendered. Source errors are aggregated at machine scope.
The plan label is based on saved OAuth metadata.VerifiedThe mocked HTTP 200 body contains only usage counters, not a plan. The returned label is derived from synthetic credential fields.
The account actually lost paid entitlement and that caused the reported refresh failure.UnverifiedNo account transition, real credentials, or incident HTTP response was available or accessed. HTTP 503 is a synthetic failure, not a subscription-ended signal.
Token health verifies subscription validity.Not supported by sourceHealth checks installation, credentials and token expiry; it makes no authoritative billing-status request.
Main already corrects this behavior.No relevant correction foundA subsequent origin/main fetch advanced main, but git log BASE..origin/main over both provider directories was empty.

3. Environment and isolation

4. Minimal reproduction

  1. Clone the public repository and check out the trusted base, then install and build:
    git clone https://github.com/get-bb/bb.git bb-6685
    cd bb-6685
    git checkout --detach 741decd0a145f5a8d982e014d16840575437a748
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
  2. Save the two inline files below into plugins/provider-usage/. Do not modify production files. The custom config uses the repository's sharedWorkerProjects helper and source exports; it avoids a cross-plugin TypeScript declaration alias being executed as runtime code.
  3. Run the isolated reproduction:
    cd plugins/provider-usage
    pnpm exec vitest run --config slopcop-6685.vitest.config.ts

    This explicit Vitest invocation is a deliberate cross-plugin investigation exception after normal Turbo builds. The package script already supplies --config, so passing a second config through Turbo is rejected by Vitest. Existing owner tests were run separately through Turbo.

  4. The test seeds a successful usage response, forces another read with HTTP 503, then calls the production settings renderer using the actual cached server result. It asserts exactly two upstream requests, the error result from the maintenance layer, equality with the previous successful usage object, and the actual visible label and counters. It does not inject a stale measurement directly into the display cache.

Expected vs actual

Expected product behavior: a retained plan label should communicate that it is saved metadata and does not establish current paid entitlement. An ordinary usage failure must not be interpreted as proof that a subscription ended. The precise account-status vocabulary has not been selected, and this observation test does not invent one.

Actual production component text (verbatim extraction from generated HTML):

6685 actual component rendering
Isolated production component; synthetic account and mocked HTTP 503. Not a live subscription lapse. Layout CSS only; source markup is unmodified.
Usage limits
Your provider subscription usage.
Couldn’t refresh. Showing last update.
Claude Code
fixture@example.com
Max (20x)
Five-hour limit
9% used
Weekly limit
14% used

The test passes because it asserts the observed behavior. It is a repeatable observation, not a red/green proof of a proposed fix. No production fix or purported subscription-expiry regression test is supplied.

slopcop-6685.repro.test.tsx

import { writeFileSync } from "node:fs";
import { renderToStaticMarkup } from "react-dom/server";
import { installTestPluginRuntime } from "@get-bb/plugin-sdk/testing/app";
import { expect, it, vi } from "vitest";
import {
  createFakePluginHost,
  makeHostResponse,
} from "@get-bb/plugin-sdk/testing";
import { getClaudeProviderUsage } from "../provider-claude-code/src/bridge/provider-maintenance.js";
import { registerUsageSource } from "../provider-claude-code/src/usage-source.js";
import providerUsagePlugin from "./server.js";
import { UsageSettingsContent } from "./settings.js";
import { usageSnapshotSchema } from "./usage-schema.js";
import { usageListMethod } from "./usage-source-contract.js";

vi.mock("node:fs/promises", () => ({
  default: {
    readFile: async (file: string) =>
      JSON.stringify(
        file.endsWith(".credentials.json")
          ? {
              claudeAiOauth: {
                accessToken: "synthetic-test-value",
                expiresAt: null,
                subscriptionType: "max",
                rateLimitTier: "default_claude_max_20x",
              },
            }
          : { oauthAccount: { emailAddress: "fixture@example.com" } },
      ),
  },
}));

vi.mock("@get-bb/plugin-sdk/provider-bridge", async (importOriginal) => ({
  ...(await importOriginal<
    typeof import("@get-bb/plugin-sdk/provider-bridge")
  >()),
  experimental_resolveExecutablePath: async () => "/synthetic/claude",
}));

it("retains a credential-derived plan through a failed HTTP refresh and renders only a generic warning", async () => {
  const upstream = vi.fn().mockResolvedValue({
    ok: true,
    status: 200,
    json: async () => ({
      five_hour: { utilization: 9, resets_at: null },
      seven_day: { utilization: 14, resets_at: null },
    }),
  });
  vi.stubGlobal("fetch", upstream);
  const machine = makeHostResponse({
    id: "fixture-host",
    name: "Synthetic machine",
    status: "connected",
  });
  const providers = [
    {
      id: "claude-code",
      pluginId: "provider-claude-code",
      displayName: "Claude Code",
      logoUrl: null,
    },
  ];
  let latestProviderResult: Awaited<ReturnType<typeof getClaudeProviderUsage>>;
  const source = createFakePluginHost({
    pluginId: "provider-claude-code",
    sdk: {
      hosts: { get: async () => machine, list: async () => [machine] },
      providers: { list: async () => providers },
      system: {
        usageLimits: async () => {
          latestProviderResult = await getClaudeProviderUsage();
          return { "claude-code": latestProviderResult.usage };
        },
      },
    },
  });
  registerUsageSource(source.bb);
  const display = createFakePluginHost({
    pluginId: "provider-usage",
    sdk: {
      hosts: { list: async () => [machine] },
      providers: { list: async () => providers },
      system: { config: async () => ({ primaryHostId: machine.id }) },
      plugins: {
        experimental_discoverRpc: async () => [
          {
            pluginId: "provider-claude-code",
            displayName: "Claude Code",
            method: usageListMethod,
          },
        ],
        callRpc: async ({ method, input }) =>
          source.harness.behavior.callRpc(method, input),
      },
    },
  });
  providerUsagePlugin(display.bb);
  const request = {
    force: true,
    machineIds: [machine.id],
    providerIds: ["claude-code"],
    maxAgeMs: 0,
  };
  try {
    const initial = usageSnapshotSchema.parse(
      await display.harness.behavior.callRpc("getUsage", request),
    );
    expect(initial.machines[0]?.providers[0]?.usage).toMatchObject({
      status: "ok",
      planLabel: "Max (20x)",
    });
    upstream.mockResolvedValue({ ok: false, status: 503 });
    const stale = usageSnapshotSchema.parse(
      await display.harness.behavior.callRpc("getUsage", request),
    );
    expect(latestProviderResult!).toMatchObject({
      usage: {
        status: "error",
        message: "Claude usage request failed (HTTP 503).",
        planLabel: "Max (20x)",
      },
    });
    expect(stale.machines[0]?.providers[0]?.usage).toEqual(
      initial.machines[0]?.providers[0]?.usage,
    );
    expect(stale.machines[0]?.error).toBe("Some usage could not be refreshed.");
    expect(upstream).toHaveBeenCalledTimes(2);
    const previousRuntime = Object.getOwnPropertyDescriptor(
      globalThis,
      "__bbPluginRuntime",
    );
    installTestPluginRuntime();
    let markup: string;
    try {
      markup = renderToStaticMarkup(
        <UsageSettingsContent
          machines={stale.machines}
          selectedId={machine.id}
          loading={false}
          error={false}
          onSelect={() => {}}
          onRefresh={() => {}}
        />,
      );
    } finally {
      if (previousRuntime)
        Object.defineProperty(globalThis, "__bbPluginRuntime", previousRuntime);
      else Reflect.deleteProperty(globalThis, "__bbPluginRuntime");
    }
    expect(markup).toContain("Max (20x)");
    expect(markup).toContain("Couldn’t refresh. Showing last update.");
    expect(markup).toContain("9% used");
    expect(markup).not.toContain("HTTP 503");
    writeFileSync(
      new URL("./slopcop-6685-render.html", import.meta.url),
      `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>6685 actual component rendering</title><style>body{font:16px system-ui;max-width:720px;margin:40px auto;padding:24px;background:#fafaf8;color:#1a1a1a}svg{width:20px;height:20px}button{padding:6px}section{margin:20px 0}h2,h3,p{margin:12px 0}div[role="status"]{padding:12px;border:1px solid #b26a00}span{margin-right:8px}</style></head><body><p>Isolated production component; synthetic account and mocked HTTP 503. Not a live subscription lapse. Layout CSS only; source markup is unmodified.</p>${markup}</body></html>`,
    );
    console.log(
      JSON.stringify({
        httpSequence: [200, 503],
        providerError: latestProviderResult!.usage,
        retainedUsage: stale.machines[0]?.providers[0]?.usage,
        panelWarning: "Couldn’t refresh. Showing last update.",
        actualSubscriptionLapseTested: false,
      }),
    );
  } finally {
    vi.unstubAllGlobals();
    await display.harness.lifecycle.dispose();
    await source.harness.lifecycle.dispose();
  }
});

slopcop-6685.vitest.config.ts

import { fileURLToPath } from "node:url";
import {
  defineWorkspaceTestConfig,
  sharedWorkerProjects,
} from "../../vitest.shared.js";

export default defineWorkspaceTestConfig({
  resolve: {
    alias: [
      {
        find: "@/components/ui/icon",
        replacement: fileURLToPath(
          new URL(
            "../../packages/plugin-registry/flavors/components/ui/icon.tsx",
            import.meta.url,
          ),
        ),
      },
      {
        find: /^@\//u,
        replacement: fileURLToPath(
          new URL("../../packages/shared-ui/src/", import.meta.url),
        ),
      },
    ],
  },
  test: {
    silent: false,
    projects: sharedWorkerProjects({
      pkgDir: fileURLToPath(new URL(".", import.meta.url)),
      name: "slopcop-6685",
      include: ["slopcop-6685.repro.test.tsx"],
    }),
  },
});

5. Root cause

  1. planLabel derives the badge from credential subscriptionType/rateLimitTier. normalizeUsage uses that label even though a successful usage response need not carry plan/entitlement data.
  2. getClaudeProviderHealth checks token presence/expiry, not paid subscription validity. getClaudeProviderUsage maps HTTP 401 to expired and other non-success HTTP responses to usage error, retaining known credential-derived metadata. None of that establishes an authoritative subscription-ended signal.
  3. The real usage source adapter returns the error measurement. fetchResource throws on status error before replacing the last successful measurement; the selected refresh loop marks the resource as failed.
  4. Machine assembly still emits the cached successful account object and assigns a machine-level refresh error. It loses the new error detail from the visible account data.
  5. ProviderUsageBlock renders the retained plan badge. Notice selection renders a generic last-update notice for the machine. The sidebar account renderer similarly uses usage.planLabel for successful retained measurements.

Key production excerpts (at the linked base commit):

const maxMatch = (credentials.rateLimitTier ?? "").match(/max_(\d+)x/u);
if (maxMatch) return `Max (${maxMatch[1]}x)`;

if (value.usage.status === "error")
  throw new Error("Usage could not be refreshed.");
measurements.set(key, { value, loadedAt: Date.now() });

Verified mechanism: credential-derived plan metadata travels inside a last-good usage snapshot; the refresh error is exposed only as generic machine-level state, so the displayed account has no separate plan-source or entitlement-freshness qualifier. This is not proof of a provider billing bug, a known subscription-ended response, or the actual cause of the reporter's refresh failure.

6. Proposed fix and simple-fix gate

Keep last-good usage resilience, but distinguish locally saved plan metadata from verified current entitlement. First obtain a redacted authoritative provider response for an actual lapsed subscription, and decide how plan provenance/freshness should be represented per account. Only consume an explicit subscription-ended signal if the provider contract supports one. An HTTP 403/429/503 or token expiration alone cannot safely be relabeled as a billing outcome.

No automatic PR: the actual entitlement transition was not reproduced, and selecting entitlement/provenance semantics requires provider evidence and a product/contract decision. That fails the no-product-decision simple-fix condition. No fix branch, production patch, new dependency, or push to the code repository was made. No open PR linked to this issue was found in timeline metadata or an open-PR search.

7. Verification

The same agent repeated the test in a second separately installed, clean trusted checkout at the identical full commit; this is a second clean run, not independent verification. Only the two authored reproduction files were copied. Both builds completed all 72 tasks. Each test runs with fresh in-memory caches and synthetic credentials; there are no reused ports or persisted data directories.

First checkout:

 RUN  v4.1.1 WORK/first/plugins/provider-usage


 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  18:46:23
   Duration  2.19s (transform 1.25s, setup 0ms, import 1.94s, tests 40ms, environment 0ms)


Second checkout:

 RUN  v4.1.1 WORK/second/plugins/provider-usage


 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  18:46:40
   Duration  2.11s (transform 1.20s, setup 0ms, import 1.86s, tests 41ms, environment 0ms)

No report claim was broadened after verification. Early harness failures involved resolving a declaration file as runtime, passing duplicate config flags, an incomplete synthetic provider logo field, and a missing test UI runtime. Those setup problems were corrected before both final successful runs; none is evidence of this product bug. Production source remained unchanged throughout.

8. Related issues

#6669 concerns throttled usage collection and cache/backoff behavior, not authoritative paid entitlement. It is related but does not establish what HTTP response occurred here. The current test uses synthetic 503 rather than assuming throttling. No linked pull request was available to review.

9. Appendix and evidence limits

Relevant existing tests were run with the normal orchestrator:

pnpm exec turbo run test --filter=bb-plugin-bb--provider-usage --filter=bb-plugin-provider-claude-code -- server.test.ts settings.test.tsx src/bridge/provider-maintenance.test.ts src/bridge/provider-maintenance.credentials.test.ts

provider-usage: 12 tests passed (2 files)
provider-claude-code: 10 tests passed (2 files)
Turbo: 8 successful tasks

The repro's authoring boundary is the real provider → source RPC → display cache → renderer chain. Existing tests cover individual retention/normalization behaviors; this observation reaches all of them with a credential-derived label and a concrete HTTP failure. It uses no new production seam. The synthetic external boundary supplies only credentials/HTTP/executable availability, not the retained snapshot being asserted.

Additional checks: repository visibility is public; both clean checkout commits were verified; the issue's comments and cross-reference metadata were read; no comments existed; trusted main was fetched again; relevant-path history showed no subsequent correction; original checkout was left unchanged. Raw evidence and reproduction artifacts are retained locally but are not published as loose files, per reports-repository policy. The complete test/config and observable output are inline above.

Trust boundary: issue content was treated only as untrusted claims. No issue-provided command, link, script, branch or patch was executed. No real subscription was cancelled, no credential files were accessed, and no provider account was contacted. Browser evidence is unavailable; this report verifies data flow and actual SSR text, not a pixel-level live UI or a real billing transition.