diff --git a/docs/claude-routed-cache-investigation.md b/docs/claude-routed-cache-investigation.md index 2c8f8aebd29..37c333633ee 100644 --- a/docs/claude-routed-cache-investigation.md +++ b/docs/claude-routed-cache-investigation.md @@ -115,7 +115,7 @@ The confirmed defect was shared monitoring state: both the watcher and durable a ### Current review status -Exact snapshot v5 (`/Users/vadym/.claude/jobs/8b6d8320/tmp/current-attempt3-v5.diff`, SHA-256 `471e0c5d964cb0a66a72cf18e98fd458e1b06e5a007d8dec15a846fd41750822`) is superseded. Its accounting reviewer withdrew the only proposed finding after tracing the canonical usage contract and confirming that no durable discriminator exists for ambiguous historical `cachedInputTokens` rows. Canonical-first decomposition remains correct; legacy read-plus-write recovery is used only when canonical interpretation is impossible because read plus write exceeds inclusive input. +Exact snapshot v5 (`~/.claude/jobs/8b6d8320/tmp/current-attempt3-v5.diff`, SHA-256 `471e0c5d964cb0a66a72cf18e98fd458e1b06e5a007d8dec15a846fd41750822`) is superseded. Its accounting reviewer withdrew the only proposed finding after tracing the canonical usage contract and confirming that no durable discriminator exists for ambiguous historical `cachedInputTokens` rows. Canonical-first decomposition remains correct; legacy read-plus-write recovery is used only when canonical interpretation is impossible because read plus write exceeds inclusive input. Its transport review found three blocking defects, now fixed locally: @@ -125,7 +125,7 @@ Its transport review found three blocking defects, now fixed locally: Failing-first regressions proved all three defects: adaptive replay to Opus 4.6 returned 400, a final HTTP 200 root-error SSE was reshaped to 529, and malformed UTF-8 was relayed with HTTP 200. After repair, all three regressions passed; the expanded focused run passed 355 tests with 14,196 assertions and 0 failures. The changed suite and complete repository suite also passed. -Exact snapshot v6 (`/Users/vadym/.claude/jobs/8b6d8320/tmp/current-attempt3-v6.diff`, SHA-256 `beb657c7a65cd8e4d4bca4e9eb97b04fbbf8fb9c9995facb8549dbb1d08f136e`) is also superseded. It was generated twice, byte-compared, and measured 621,316 bytes across 76 cumulative files. Independent review confirmed six further defects: +Exact snapshot v6 (`~/.claude/jobs/8b6d8320/tmp/current-attempt3-v6.diff`, SHA-256 `beb657c7a65cd8e4d4bca4e9eb97b04fbbf8fb9c9995facb8549dbb1d08f136e`) is also superseded. It was generated twice, byte-compared, and measured 621,316 bytes across 76 cumulative files. Independent review confirmed six further defects: 1. Cache alerts recognized only provider names, so a custom-named provider using `adapter: "anthropic"` escaped Anthropic cache policy. 2. Strict canonical SSE inspection validated terminal shape but direct relay still forwarded raw chunks before validation, allowing malformed JSON, non-object JSON, `[DONE]`, or invalid UTF-8 to escape. @@ -233,7 +233,7 @@ Current evidence isolates the dominant historical root boundary to old combo too ## Astra v2.43.0 semantic transplant -The complete pre-upgrade tree is recoverable from rescue branch `rescue/pre-astra-v2430-20260906-5dba90e`, commit `8a071b8a01090ac258dc76400d16c31805e101e5`, and annotated tag `rescue/pre-astra-v2430-20260906`. The verified full-history bundle is `/Users/vadym/.opencodex/deploy-artifacts/opencodex-pre-astra-v2430-8a071b8a0.bundle`, 113,239,204 bytes, SHA-256 `5ba8a704ab750e6aa98d5920059710ff8fe3ef20d479fff985360185a193da30`. A disposable restore reproduced rescue tree `272bc3c28c75e820d6bb546646a8b3ea685b9328` and this investigation document before migration began. +The complete pre-upgrade tree is recoverable from rescue branch `rescue/pre-astra-v2430-20260906-5dba90e`, commit `8a071b8a01090ac258dc76400d16c31805e101e5`, and annotated tag `rescue/pre-astra-v2430-20260906`. The verified full-history bundle is `~/.opencodex/deploy-artifacts/opencodex-pre-astra-v2430-8a071b8a0.bundle`, 113,239,204 bytes, SHA-256 `5ba8a704ab750e6aa98d5920059710ff8fe3ef20d479fff985360185a193da30`. A disposable restore reproduced rescue tree `272bc3c28c75e820d6bb546646a8b3ea685b9328` and this investigation document before migration began. Migration branch `upgrade/astra-v2.43.0` starts directly from official annotated tag `v2.43.0`, peeled commit `06ec553630fa2ee51a96b5cbf694089021249194`, package `@bitkyc08/opencodex@2.43.0`. Local behavior is being transplanted semantically rather than by merging or broadly cherry-picking the rescue branch. Rejected reconstruction commits `8fa37f3cf`, `a9fc4f49d`, `08973660f`, `3d9f5dca9`, and `b98731f66` are not replayed. Upstream remains authoritative for Astra model catalog and generated provider data, model discovery, context limits, reasoning support, prices, package metadata, and lockfiles. @@ -271,7 +271,7 @@ The transplant also preserves strict canonical Anthropic source replay, exact co - 2026-09-01: All six v6 findings received failing-first regressions: six backend tests and one GUI contract failed before repair. Shared v7 fixes pass the repaired seven-file focused run with 267 tests, 13,667 assertions, and 0 failures. - 2026-09-01: Final v7 offline gates passed: `git diff --check`, pinned-Bun typecheck, privacy scan, Oxlint, React Doctor against audited baseline `870a2adb6eaccc9da9ea9832a596e1b2650ab1ea`, 1,118 GUI tests with 10,122 assertions, and GUI production build. The changed suite passed 13,709 tests, skipped 9, and failed 0 across 770 files. The first complete suite hit one unrelated parallel macOS/Bun `SQLITE_IOERR_VNODE` in `server-images.test.ts`; its isolated 63-test rerun passed, then the clean complete rerun passed 16,585 tests, skipped 12, and failed 0 across the 994-file parallel lane and all six serial lanes. Stable v7 snapshot and two clean same-hash reviews remain required. Fresh 24-send real comparison remains unused and blocked on those reviews. No gateway, live inference, Mini change, `claude-wa` change, commit, push, PR, or merge occurred. - 2026-09-02: Exact v7 snapshot was generated twice and byte-stable at SHA-256 `b55d9ae73878ea5098effd4bac16ce44e0001b9b5ce28e9484d4e84ef1ea2975`. Its transport review reported twelve candidate defects, so the hash is superseded pending independent verification and repair. Adapter-owned web-search and image retries were confirmed to pace under the previous response-header deadline: both failing-first regressions returned 504 instead of dispatching the retry. The shared sibling fix now clears that timer before deliberate pacing, starts a fresh response-header deadline afterward, and replaces the adapter's stale signal for the retry fetch. The repaired two-file suite passes 94 tests with 313 assertions and 0 failures. -- 2026-09-02: Native Responses key-pool and generic OAuth failover, rotated-account 401 ownership, terminal continuation OAuth rotation, and sidecar recovery labeling were all confirmed by failing-first regressions. Preserved outputs are `/Users/vadym/.claude/jobs/8b6d8320/tmp/v8-native-key-pool-failing-first.output`, `/Users/vadym/.claude/jobs/8b6d8320/tmp/v8-oauth-native-failing-first.output`, `/Users/vadym/.claude/jobs/8b6d8320/tmp/v8-oauth-terminal-failing-first.output`, and `/Users/vadym/.claude/jobs/8b6d8320/tmp/v8-oauth-sidecar-failing-first.output`. +- 2026-09-02: Native Responses key-pool and generic OAuth failover, rotated-account 401 ownership, terminal continuation OAuth rotation, and sidecar recovery labeling were all confirmed by failing-first regressions. Preserved outputs are `~/.claude/jobs/8b6d8320/tmp/v8-native-key-pool-failing-first.output`, `~/.claude/jobs/8b6d8320/tmp/v8-oauth-native-failing-first.output`, `~/.claude/jobs/8b6d8320/tmp/v8-oauth-terminal-failing-first.output`, and `~/.claude/jobs/8b6d8320/tmp/v8-oauth-sidecar-failing-first.output`. - 2026-09-02: Remaining confirmed v7 defects received shared root fixes for malformed Anthropic JSON success envelopes, typed pacing overload propagation, bounded strict SSE frame inspection, raw incomplete-frame body accounting, and geometric nonstream buffering. The compression-header proposal remained rejected because the physical header sanitizer already removes stale entity/transport headers. - 2026-09-02: Post-repair focused transport/OAuth group passed 402 tests with 14,249 assertions and 0 failures across 13 files. The generic OAuth suite, kept separate because it installs a process-global module mock, passed 25 tests with 74 assertions and 0 failures. Final repository gates, a new byte-stable exact snapshot, and two clean same-hash reviews remain required. No gateway, inference, Mini process, `claude-wa`, commit, push, PR, merge, or deployment was touched. - 2026-09-02: Fresh read-only host audits found both gateways stopped and no new routing traffic. The latest laptop strict controls remain healthy at 99.96% and 99.91% cache-read share with one send and no recovery; native controls remain `anthropic-native` with zero translated attempts. Mini has no newer evidence than its August 30 pre-fix AgentRadar sample, which remains a confirmed historical regression at 25.00% warmed cache-read share, all 179 post-warm calls above 100,000 raw input tokens, 12 large writes, and 6 extra sends. No current Mini quota consumer was active; two laptop agents showed no new OpenCodex ledger activity. diff --git a/gui/tests/dashboard-contracts.test.ts b/gui/tests/dashboard-contracts.test.ts index 8603d26f9f0..6b7ec2c6a6a 100644 --- a/gui/tests/dashboard-contracts.test.ts +++ b/gui/tests/dashboard-contracts.test.ts @@ -1,11 +1,6 @@ import { expect, test } from "bun:test"; -import { createElement } from "react"; -import { renderToStaticMarkup } from "react-dom/server"; import { en } from "../src/i18n/en"; -import { interpolate, type TFn } from "../src/i18n/shared"; -import { fetchRoutingAnalytics, normalizeInjectionSelection } from "../src/pages/dashboard-core-poll"; -import { DashboardQuotaObservability, UsageQuotaObservability } from "../src/pages/dashboard-quota-observability"; -import type { RoutingAnalyticsResult } from "../src/pages/dashboard-shared"; +import { normalizeInjectionSelection } from "../src/pages/dashboard-core-poll"; import { PROJECT_CONFIG_DIAGNOSTICS_POLL_MS, beginPollEpoch, beginPollEpochs } from "../src/startup-health-ui"; test("project-config diagnostics poll cadence is owned by the shared constant", () => { @@ -59,337 +54,6 @@ test("Dashboard usage polling cannot delay core health and settings", async () = expect(hook).toContain("fetchDashboardSidecars"); expect(hook).toContain("fetchDashboardOverview"); expect(hook).toMatch(/usageSummary30dResourceKey\(apiBase\)[\s\S]*pollMs: 60_000/); - const usageResourceStart = hook.indexOf("const usagePoll = useKeyedClientResource"); - const quotaResourceStart = hook.indexOf("const quotaAnalyticsPoll = useKeyedClientResource"); - expect(usageResourceStart).toBeGreaterThan(-1); - expect(quotaResourceStart).toBeGreaterThan(usageResourceStart); - expect(hook.slice(usageResourceStart, quotaResourceStart)).not.toContain("pollMs:"); -}); - -test("Dashboard quota analytics poll is independent of health and settings", async () => { - const core = await Bun.file(new URL("../src/pages/dashboard-core-poll.ts", import.meta.url)).text(); - const hook = await Bun.file(new URL("../src/pages/use-dashboard-data.ts", import.meta.url)).text(); - const panels = await Bun.file(new URL("../src/pages/dashboard-overview-panels.tsx", import.meta.url)).text(); - const quota = await Bun.file(new URL("../src/pages/dashboard-quota-observability.tsx", import.meta.url)).text(); - const overviewStart = core.indexOf("export async function fetchDashboardOverview"); - const multiStart = core.indexOf("export async function fetchDashboardMultiAgent"); - - expect(core).toContain("export async function fetchRoutingAnalytics"); - expect(core).toContain("data.repeatedSendAttempts"); - expect(core).toContain("data.sequentialRoutes"); - expect(core).toContain("data.warmedRoutes"); - expect(core).toContain("value.repeatedSendAttempts"); - expect(core).toContain("/api/routing-analytics"); - expect(core.slice(overviewStart, multiStart)).not.toContain("/api/routing-analytics"); - expect(hook).toContain("dashboard-routing-analytics:${apiBase}"); - expect(hook).toContain("quotaAnalyticsPoll"); - expect(hook).toContain('enabled: selectedSection === "overview"'); - expect(hook).toContain('range: "30d"'); - expect(hook).toContain("!quotaAnalyticsPoll.lastAttemptOk"); - expect(panels).toContain(" { - const originalFetch = globalThis.fetch; - globalThis.fetch = (async () => ({ - ok: true, - status: 200, - json: async () => payload, - })) as unknown as typeof fetch; - try { - return await fetchRoutingAnalytics("http://test", new AbortController().signal); - } finally { - globalThis.fetch = originalFetch; - } -} - -test("fetchRoutingAnalytics accepts recursively valid HTTP-200 payloads and preserves null shares", async () => { - const valid = routingAnalyticsPayload(); - expect(await fetchRoutingAnalyticsPayload(valid)).toBe(valid); - - const empty: RoutingAnalyticsResult = { - ...valid, - totalRequests: 0, - physicalSends: 0, - repeatedSendAttempts: 0, - recoveryEvents: 0, - requestRatePerHour: null, - attemptUsage: { - inclusiveInputTokens: 0, - rawInputTokens: 0, - cacheReadInputTokens: 0, - cacheWriteInputTokens: 0, - rawInputShare: null, - cacheReadShare: null, - cacheWriteShare: null, - }, - physicalUsageCoverage: { - totalAttempts: 0, - measuredAttempts: 0, - reportedAttempts: 0, - estimatedAttempts: 0, - unreportedAttempts: 0, - unsupportedAttempts: 0, - ratio: null, - supportedRatio: null, - }, - physicalBreakdown: [], - redAlerts: [], - sequentialRoutes: 0, - warmedRoutes: 0, - }; - const accepted = await fetchRoutingAnalyticsPayload(empty); - expect(accepted).toBe(empty); - expect(accepted.attemptUsage.rawInputShare).toBeNull(); - expect(accepted.physicalUsageCoverage.ratio).toBeNull(); -}); - -test("fetchRoutingAnalytics rejects malformed HTTP-200 payloads recursively", async () => { - const valid = routingAnalyticsPayload(); - const row = valid.physicalBreakdown[0]!; - const alert = valid.redAlerts[0]!; - const malformed: Array<[string, unknown]> = [ - ["NaN scalar", { ...valid, requestRatePerHour: Number.NaN }], - ["infinite usage", { ...valid, attemptUsage: { ...valid.attemptUsage, inclusiveInputTokens: Number.POSITIVE_INFINITY } }], - ["negative counter", { ...valid, physicalSends: -1 }], - ["invalid share", { ...valid, attemptUsage: { ...valid.attemptUsage, rawInputShare: 1.1 } }], - ["invalid null share", { ...valid, attemptUsage: { ...valid.attemptUsage, cacheReadShare: null } }], - ["coverage counter invariant", { - ...valid, - physicalUsageCoverage: { ...valid.physicalUsageCoverage, measuredAttempts: 0 }, - }], - ["coverage ratio invariant", { - ...valid, - physicalUsageCoverage: { ...valid.physicalUsageCoverage, ratio: null }, - }], - ["malformed physical row", { - ...valid, - physicalBreakdown: [{ ...row, recoveryEvents: -1 }], - }], - ["malformed row optional", { - ...valid, - physicalBreakdown: [{ ...row, accountRef: 42 }], - }], - ["unknown alert kind", { - ...valid, - redAlerts: [{ ...alert, kind: "unknown-alert" }], - }], - ["malformed alert optional", { - ...valid, - redAlerts: [{ ...alert, conversationId: null }], - }], - ["infinite alert value", { - ...valid, - redAlerts: [{ ...alert, value: Number.NEGATIVE_INFINITY }], - }], - ]; - - for (const [name, payload] of malformed) { - try { - await fetchRoutingAnalyticsPayload(payload); - throw new Error(`accepted malformed case: ${name}`); - } catch (error) { - expect(error).toEqual(new Error("invalid routing analytics response")); - } - } -}); - -test("quota state distinguishes physical-attempt telemetry gaps and historical warnings", () => { - const t: TFn = (key, vars) => interpolate(en[key], vars); - const coverage = { - totalAttempts: 1, - measuredAttempts: 1, - reportedAttempts: 1, - estimatedAttempts: 0, - unreportedAttempts: 0, - unsupportedAttempts: 0, - ratio: 1, - supportedRatio: 1, - }; - const data: RoutingAnalyticsResult = { - generatedAt: Date.UTC(2026, 7, 31, 0, 0), - totalRequests: 1, - physicalSends: 1, - repeatedSendAttempts: 0, - recoveryEvents: 0, - requestRatePerHour: 1, - attemptUsage: { - inclusiveInputTokens: 1, - rawInputTokens: 1, - cacheReadInputTokens: 0, - cacheWriteInputTokens: 0, - rawInputShare: 1, - cacheReadShare: 0, - cacheWriteShare: 0, - }, - physicalUsageCoverage: coverage, - physicalBreakdown: [], - redAlerts: [], - redAlertsPartial: false, - sequentialRoutes: 1, - warmedRoutes: 1, - }; - const render = (next: RoutingAnalyticsResult, error = false) => renderToStaticMarkup(createElement( - UsageQuotaObservability, - { data: next, loading: false, error, locale: "en", t }, - )); - - expect(render({ - ...data, - physicalUsageCoverage: { ...coverage, totalAttempts: 0, measuredAttempts: 0, reportedAttempts: 0, ratio: null, supportedRatio: null }, - })).toContain("none sent an upstream inference"); - expect(render({ - ...data, - physicalUsageCoverage: { ...coverage, measuredAttempts: 0, reportedAttempts: 0, unsupportedAttempts: 1, ratio: 0, supportedRatio: null }, - })).toContain("unsupported for 1 physical attempt"); - expect(render({ - ...data, - physicalUsageCoverage: { ...coverage, measuredAttempts: 0, reportedAttempts: 0, unreportedAttempts: 1, ratio: 0, supportedRatio: 0 }, - })).toContain("missing for 1 physical attempt"); - expect(render({ - ...data, - physicalUsageCoverage: { - ...coverage, - totalAttempts: 3, - measuredAttempts: 1, - unreportedAttempts: 1, - unsupportedAttempts: 1, - ratio: 1 / 3, - supportedRatio: 1 / 2, - }, - })).toContain("covers 1 of 3 physical attempts (1 unsupported, 1 unreported)"); - - const alert = { - kind: "repeated-send" as const, - requestId: "request-1", - timestamp: 1, - provider: "anthropic", - model: "claude-test", - attemptOrdinal: 1, - value: 2, - }; - const historical = render({ ...data, redAlerts: [alert] }); - expect(historical).toContain("1 route/session warning occurrence(s) in scanned history"); - expect(historical).not.toContain("active quota warning"); - - const invalidAlertTime = render({ - ...data, - redAlerts: [{ ...alert, timestamp: Number.MAX_SAFE_INTEGER }], - }); - expect(invalidAlertTime).toContain("—"); - expect(invalidAlertTime).not.toContain("Invalid Date"); - const invalidStaleTime = render({ ...data, generatedAt: Number.MAX_SAFE_INTEGER }, true); - expect(invalidStaleTime).toContain("The latest refresh failed. The values below may be stale."); - expect(invalidStaleTime).not.toContain("Invalid Date"); - - const partialAlert = render({ ...data, redAlerts: [alert], redAlertsPartial: true }); - expect(partialAlert).toContain("notice notice-err"); - expect(partialAlert).toContain("Results are partial because request history or alert output reached its limit."); - const alertWithPartialTelemetry = render({ - ...data, - redAlerts: [alert], - physicalUsageCoverage: { - ...coverage, - totalAttempts: 2, - unreportedAttempts: 1, - ratio: 0.5, - supportedRatio: 0.5, - }, - }); - expect(alertWithPartialTelemetry).toContain("notice notice-err"); - expect(alertWithPartialTelemetry).toContain("1 route/session warning occurrence(s) in scanned history"); - - const stale = render(data, true); - expect(stale).toContain("Latest refresh failed. Values below are stale from"); - expect(stale).toContain("2026"); - expect(stale).toContain("Inclusive input"); - expect(stale).not.toContain("No route/session warning occurrences in scanned history."); - - const warming = render({ ...data, sequentialRoutes: 2, warmedRoutes: 1 }); - expect(warming).toContain("notice notice-warn"); - expect(warming).toContain("Route is warming up"); - expect(render({ ...data, sequentialRoutes: 2, warmedRoutes: 2 })).toContain("notice notice-ok"); - - const dashboard = renderToStaticMarkup(createElement(DashboardQuotaObservability, { - data: { - ...data, - redAlerts: Array.from({ length: 4 }, (_, index) => ({ ...alert, requestId: `request-${index + 1}` })), - }, - loading: false, - error: false, - locale: "en", - t, - })); - expect(dashboard).toContain("Showing 3 of 4 returned warning occurrences."); - expect(dashboard).toContain("request-3"); - expect(dashboard).not.toContain("request-4"); }); test("Dashboard interactive controls load independently of health/providers", async () => { diff --git a/gui/tests/fr-localization.test.ts b/gui/tests/fr-localization.test.ts index 1c9b9040dff..221de55d009 100644 --- a/gui/tests/fr-localization.test.ts +++ b/gui/tests/fr-localization.test.ts @@ -135,7 +135,6 @@ const INTENTIONAL_ENGLISH = new Set([ "dash.version", "dash.mem.storeTotal", "dash.maintenance", - "usage.quota.col.session", "prov.port", "prov.openaiModeDirect", "logs.filter.conversation.label", diff --git a/gui/tests/usage-layout.test.ts b/gui/tests/usage-layout.test.ts index 9bd27ae2380..922bf9baf56 100644 --- a/gui/tests/usage-layout.test.ts +++ b/gui/tests/usage-layout.test.ts @@ -4,13 +4,6 @@ import { act, createElement } from "react"; import { clearClientResourceStoresForTests } from "../src/client-resource"; import { LanguageProvider } from "../src/i18n/provider"; import Usage from "../src/pages/Usage"; -import { localCalendarRangeStart } from "../src/pages/dashboard-shared"; - -test("quota windows start at local midnight on the first calendar day", () => { - const now = new Date(2026, 7, 31, 15, 48, 15).getTime(); - expect(localCalendarRangeStart(7, now)).toBe(new Date(2026, 7, 25).getTime()); - expect(localCalendarRangeStart(30, now)).toBe(new Date(2026, 7, 2).getTime()); -}); test("Usage renders every section in one scrollable column with a sticky strip", async () => { const page = await Bun.file(new URL("../src/pages/Usage.tsx", import.meta.url)).text(); @@ -53,7 +46,6 @@ test("Usage workspace sections mount report panels in order", async () => { const order = [ " { expect(src).toContain("usw-section"); }); -test("Usage quota observability uses independent durable routing analytics", async () => { - const page = await Bun.file(new URL("../src/pages/Usage.tsx", import.meta.url)).text(); - const quota = await Bun.file(new URL("../src/pages/dashboard-quota-observability.tsx", import.meta.url)).text(); - - expect(page).toContain("fetchRoutingAnalytics"); - expect(page).toContain("usage-routing-analytics:"); - expect(page).toContain("limit: 50_000"); - expect(page).toContain("const queryWindow = useCallback"); - expect(page.match(/const query = queryWindow\(\);/g)?.length).toBe(2); - expect(page).toContain("range: query.range"); - expect(page).not.toContain("const quotaFrom = useMemo"); - expect(page).not.toContain("quotaEnabled"); - expect(page).not.toContain("enabled: quotaEnabled"); - expect(page).toContain('state.kind === "failed-cold"'); - expect(page).toContain(" { - const globalKeys = ["document", "window", "navigator", "localStorage", "ResizeObserver", "IS_REACT_ACT_ENVIRONMENT"] as const; - const previous = Object.fromEntries(globalKeys.map(key => [key, Reflect.get(globalThis, key)])); - const originalFetch = globalThis.fetch; - const testWindow = new Window({ url: "http://localhost/" }); - Object.defineProperties(globalThis, { - document: { configurable: true, value: testWindow.document }, - window: { configurable: true, value: testWindow }, - navigator: { configurable: true, value: testWindow.navigator }, - localStorage: { configurable: true, value: testWindow.localStorage }, - ResizeObserver: { configurable: true, value: testWindow.ResizeObserver }, - }); - (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - clearClientResourceStoresForTests(); - globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { - if (String(input).includes("/api/usage?")) { - return new Promise((_resolve, reject) => { - init?.signal?.addEventListener("abort", () => reject(new DOMException("The operation was aborted.", "AbortError")), { once: true }); - }); - } - return Promise.resolve(Response.json({ - totalRequests: 1, - physicalSends: 1, - repeatedSendAttempts: 0, - recoveryEvents: 0, - requestRatePerHour: 1, - attemptUsage: { - inclusiveInputTokens: 10, - rawInputTokens: 1, - cacheReadInputTokens: 9, - cacheWriteInputTokens: 0, - rawInputShare: 0.1, - cacheReadShare: 0.9, - cacheWriteShare: 0, - }, - physicalUsageCoverage: { - totalAttempts: 1, - measuredAttempts: 1, - reportedAttempts: 1, - estimatedAttempts: 0, - unreportedAttempts: 0, - unsupportedAttempts: 0, - ratio: 1, - supportedRatio: 1, - }, - physicalBreakdown: [], - redAlerts: [], - redAlertsPartial: false, - sequentialRoutes: 1, - warmedRoutes: 1, - })); - }) as typeof fetch; - - const container = document.createElement("div"); - document.body.append(container); - const { createRoot } = await import("react-dom/client"); - const root = createRoot(container); - try { - await act(async () => { - root.render(createElement(LanguageProvider, null, createElement(Usage, { apiBase: "http://usage-independent-quota-test" }))); - }); - const deadline = Date.now() + 1_000; - while (!(container.textContent ?? "").includes("No route/session warning occurrences in scanned history.")) { - if (Date.now() >= deadline) throw new Error("Quota analytics waited for primary usage"); - await act(async () => { - await new Promise(resolve => testWindow.setTimeout(resolve, 10)); - }); - } - expect(container.textContent).toContain("Loading usage data…"); - } finally { - await act(async () => { root.unmount(); }); - container.remove(); - globalThis.fetch = originalFetch; - clearClientResourceStoresForTests(); - testWindow.close(); - for (const key of globalKeys) { - Object.defineProperty(globalThis, key, { configurable: true, value: previous[key] }); - } - } -}); - -test("Usage loading and empty states do not hide quota state", async () => { +test("Usage loading and empty states guard the workspace body", async () => { const src = await Bun.file(new URL("../src/pages/Usage.tsx", import.meta.url)).text(); - expect(src).toContain("state.showSkeleton && !data &&"); + expect(src).toContain("state.showSkeleton && !data"); expect(src).toContain("DataSurfaceSkeleton"); expect(src).toContain('t("usage.loading")'); expect(src).toContain('t("usage.empty")'); - expect(src).toContain("!!quotaData"); - expect(src).toContain("!quotaLoading"); - expect(src).toContain("!quotaError"); expect(src).toContain("data.summary.requests === 0"); }); @@ -199,14 +79,6 @@ test("usage workspace i18n keys exist in every locale", async () => { expect(dict).toContain('"usage.range.available":'); expect(dict).toContain('"usage.historyTruncated":'); expect(dict).toContain('"usage.historyTruncatedWindow":'); - expect(dict).toContain('"usage.quota.title":'); - expect(dict).toContain('"usage.quota.status.noAttempts":'); - expect(dict).toContain('"usage.quota.status.unsupportedTelemetry":'); - expect(dict).toContain('"usage.quota.status.unreportedTelemetry":'); - expect(dict).toContain('"usage.quota.status.partialTelemetry":'); - expect(dict).toContain('"usage.quota.status.observeOnly":'); - expect(dict).toContain('"usage.quota.alertsPreview":'); - expect(dict).toContain('"usage.quota.alert.combo-failover":'); expect(dict).toContain('"api.attribution.totalRequestsAvailable":'); expect(dict).toContain('"usage.source.connected":'); expect(dict).toContain('"usage.scope.machine":'); @@ -216,7 +88,7 @@ test("usage workspace i18n keys exist in every locale", async () => { }); test("Usage renders Available history and a persistent qualification when history is capped", async () => { - const globalKeys = ["document", "window", "navigator", "localStorage", "ResizeObserver", "IS_REACT_ACT_ENVIRONMENT"] as const; + const globalKeys = ["document", "window", "navigator", "localStorage", "IS_REACT_ACT_ENVIRONMENT"] as const; const previous = Object.fromEntries(globalKeys.map(key => [key, Reflect.get(globalThis, key)])); const originalFetch = globalThis.fetch; const testWindow = new Window({ url: "http://localhost/" }); @@ -225,7 +97,6 @@ test("Usage renders Available history and a persistent qualification when histor window: { configurable: true, value: testWindow }, navigator: { configurable: true, value: testWindow.navigator }, localStorage: { configurable: true, value: testWindow.localStorage }, - ResizeObserver: { configurable: true, value: testWindow.ResizeObserver }, }); (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; clearClientResourceStoresForTests(); @@ -304,7 +175,7 @@ test("Usage names the loaded window when history is truncated", async () => { }); test("Usage falls back to the generic caveat when a reported bound is unrenderable", async () => { - const globalKeys = ["document", "window", "navigator", "localStorage", "ResizeObserver", "IS_REACT_ACT_ENVIRONMENT"] as const; + const globalKeys = ["document", "window", "navigator", "localStorage", "IS_REACT_ACT_ENVIRONMENT"] as const; const previous = Object.fromEntries(globalKeys.map(key => [key, Reflect.get(globalThis, key)])); const originalFetch = globalThis.fetch; const testWindow = new Window({ url: "http://localhost/" }); @@ -313,7 +184,6 @@ test("Usage falls back to the generic caveat when a reported bound is unrenderab window: { configurable: true, value: testWindow }, navigator: { configurable: true, value: testWindow.navigator }, localStorage: { configurable: true, value: testWindow.localStorage }, - ResizeObserver: { configurable: true, value: testWindow.ResizeObserver }, }); (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; clearClientResourceStoresForTests(); diff --git a/package.json b/package.json index b9a96379c5e..35a6f8ca54e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.43.0", + "version": "2.65.0", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", diff --git a/src/codex/reset-credit-auto-redeem.ts b/src/codex/reset-credit-auto-redeem.ts index 19b6d3ae0e0..acd0681955c 100644 --- a/src/codex/reset-credit-auto-redeem.ts +++ b/src/codex/reset-credit-auto-redeem.ts @@ -91,9 +91,10 @@ function readJournal(path: string): Journal { } } -function writeJournal(path: string, journal: Journal): void { +function writeJournal(path: string, journal: Journal, nowMs: number): void { // Keep only entries whose credit could still matter: settled ones older than a week are noise. - const cutoff = Date.now() - 7 * 24 * 60 * 60_000; + // nowMs is the caller's clock (the same one that stamps updatedAt), never the wall clock. + const cutoff = nowMs - 7 * 24 * 60 * 60_000; journal.entries = journal.entries.filter(e => e.state !== "settled" || e.updatedAt > cutoff); atomicWriteFile(path, JSON.stringify(journal, null, 2)); } @@ -163,7 +164,7 @@ export function createResetCreditAutoRedeemer(deps: AutoRedeemDeps): ResetCredit entry = { accountKey, grantedAt: plan.grantedAt, expiresAt: plan.expiresAt, redeemRequestId: randomUUID(), state: "dispatched", updatedAt: now() }; journal.entries.push(entry); // Journal BEFORE the network call: a crash after this line replays the same request id. - writeJournal(path, journal); + writeJournal(path, journal, now()); } log(`[opencodex] reset-credit auto-redeem: dispatching for account ${accountKey} (credit expires ${plan.expiresAt})`); let result: { code: string }; @@ -176,7 +177,7 @@ export function createResetCreditAutoRedeemer(deps: AutoRedeemDeps): ResetCredit } entry.state = "settled"; entry.updatedAt = now(); - writeJournal(path, journal); + writeJournal(path, journal, now()); log(`[opencodex] reset-credit auto-redeem: upstream answered ${result.code} for account ${accountKey}`); schedule(idleRecheckMs); return { kind: "dispatched", code: result.code, redeemRequestId: entry.redeemRequestId };