diff --git a/doc/COST-ACCOUNTING.md b/doc/COST-ACCOUNTING.md
index c63d6281a11..f8b287d3715 100644
--- a/doc/COST-ACCOUNTING.md
+++ b/doc/COST-ACCOUNTING.md
@@ -174,3 +174,10 @@ edits deliver hard-stop cancellation after their transaction commits.
Status-card update costs retain the ledger's fractional-cent storage precision.
The mutation gate retains partial results and per-run reports/logs under
`coverage/accounting/` when its baseline fails or a mutation survives.
+
+Failed native turns persist observed run-delta usage before semantic-result
+finalization. A matching terminal failure, cancellation, or interruption closes
+that receipt; missing terminal evidence and session-only totals remain pending.
+For multiple provider attempts, known prices remain in the exact spend total
+when another attempt is unpriced. The aggregate stays marked unpriced, so the
+configured unknown-price policy still controls whether new work may start.
diff --git a/doc/connections/AI-CONNECTIONS.md b/doc/connections/AI-CONNECTIONS.md
index d31ce5fea97..c0ca25fa2c6 100644
--- a/doc/connections/AI-CONNECTIONS.md
+++ b/doc/connections/AI-CONNECTIONS.md
@@ -186,6 +186,17 @@ and contain neither credentials nor raw provider errors. Expired credentials
report `authentication_required`; the probe does not exchange refresh tokens
or change connection health.
+The Costs dashboard uses the company quota endpoint. It reads each authorized
+managed subscription separately, retaining the last successful observation on
+transient errors. For managed Codex accounts, a 401 can trigger one persisted
+OAuth refresh; it defers while potentially competing OpenAI work is active.
+Refresh takes the company secret-mutation lock before database row locks and
+requires those row locks immediately, before exchanging a single-use token.
+Reconnect and runtime credential write-back follow the same lock order.
+Credential resolution checks its version after any database wait and reloads a
+rotated value before giving it to a new run. Unknown utilization has no progress
+bar, but any provider-reported reset time remains visible.
+
Verification:
```sh
diff --git a/packages/adapter-utils/src/usage-checkpoint.test.ts b/packages/adapter-utils/src/usage-checkpoint.test.ts
index 2b622ef60f0..a158f587c15 100644
--- a/packages/adapter-utils/src/usage-checkpoint.test.ts
+++ b/packages/adapter-utils/src/usage-checkpoint.test.ts
@@ -29,6 +29,29 @@ describe("usage checkpoint stream", () => {
expect(parser.mock.calls[0][0]).not.toContain("private content");
});
+ it("bounds large content strings before buffering and preserves usage on either side", async () => {
+ const saved = vi.fn(); const parser = vi.fn(createParser()); const output = vi.fn();
+ const log = createUsageCheckpointLog(output, saved, parser);
+ const line = JSON.stringify({ type: "result", usage: { inputTokens: 2, costUsd: 0.25 }, messages: [{ content: '"\\\n'.repeat(2 * 1024 * 1024) }], model: "after-large-content" });
+ for (let offset = 0; offset < line.length; offset += 4093) await log("stdout", line.slice(offset, offset + 4093));
+ await log.flush();
+ expect(saved).toHaveBeenLastCalledWith(expect.objectContaining({ costUsd: 0.25, complete: true }));
+ expect(parser.mock.calls[0][0]).toContain("after-large-content");
+ expect(parser.mock.calls[0][0].length).toBeLessThan(1000);
+ expect(output.mock.calls.map(call => call[1]).join("")).toBe(line);
+ });
+
+ it("preserves Unicode and escaped quotes across the string limit and chunk boundaries", async () => {
+ for (const suffix of ['\\u1234', '\\"', '\\\\']) {
+ const saved = vi.fn(); const parser = vi.fn(createParser());
+ const log = createUsageCheckpointLog(vi.fn(), saved, parser);
+ const line = '{"type":"result","text":"' + 'a'.repeat(249) + suffix + 'discarded","usage":{"costUsd":0.25}}\n';
+ for (const character of line) await log("stdout", character);
+ await log.flush();
+ expect(saved).toHaveBeenCalledWith(expect.objectContaining({ costUsd: 0.25 }));
+ }
+ });
+
it("surfaces a persistence failure outside the local process's best-effort log path", async () => {
const failure = new Error("Receipt storage unavailable");
const output = vi.fn(); const saved = vi.fn().mockRejectedValue(failure);
diff --git a/packages/adapter-utils/src/usage-checkpoint.ts b/packages/adapter-utils/src/usage-checkpoint.ts
index 1e0c44bd86e..123ae66615e 100644
--- a/packages/adapter-utils/src/usage-checkpoint.ts
+++ b/packages/adapter-utils/src/usage-checkpoint.ts
@@ -24,6 +24,41 @@ function project(value: unknown, depth = 0, field = ""): unknown {
: project(entry, depth + 1, key)]));
}
+/** Bound strings before buffering whole JSON lines. Provider records can carry
+ * many MiB of conversation text alongside a small usage object. Preserve JSON
+ * escapes across chunks so discarded text cannot corrupt the accounting fields. */
+function createStringCompactor() {
+ let inString = false, length = 0, escapeRemaining = 0;
+ let escapeCode = false, keepEscape = false;
+ return (chunk: string) => {
+ let output = "";
+ for (const character of chunk) {
+ if (character === "\n") {
+ inString = false; escapeRemaining = 0; escapeCode = false;
+ output += character;
+ } else if (!inString) {
+ output += character;
+ if (character === '"') { inString = true; length = 0; }
+ } else if (escapeRemaining > 0) {
+ if (keepEscape) output += character;
+ escapeRemaining = escapeCode && character === "u" ? 4 : escapeRemaining - 1;
+ escapeCode = false;
+ length++;
+ } else if (character === '"') {
+ output += character; inString = false;
+ } else if (character === "\\") {
+ keepEscape = length < 250;
+ if (keepEscape) output += character;
+ escapeRemaining = 1; escapeCode = true; length++;
+ } else {
+ if (length < 250) output += character;
+ length++;
+ }
+ }
+ return output;
+ };
+}
+
/** The consumer incrementally parses only new records (never the full history).
* A fresh instance belongs to one CLI attempt. Call flush() after its process
* exits, before retrying or final result handling. Checkpoint failures are
@@ -34,6 +69,7 @@ export function createUsageCheckpointLog(
consume: (records: string) => AdapterUsageCheckpoint | null,
) {
const attemptId = randomUUID();
+ const compactStrings = createStringCompactor();
let remainder = "", accounting = "", previous = "";
let snapshot: AdapterUsageCheckpoint | null = null;
let failure: unknown;
@@ -63,7 +99,7 @@ export function createUsageCheckpointLog(
const log = async (stream: "stdout" | "stderr", chunk: string) => {
if (onUsage && !failed && stream === "stdout") {
try {
- remainder += chunk;
+ remainder += compactStrings(chunk);
const lines = remainder.split("\n"); remainder = lines.pop() ?? "";
if (remainder.length > 8 * 1024 * 1024) throw new Error("Accounting protocol line exceeds 8 MiB");
for (const line of lines) retain(line);
diff --git a/packages/adapters/codex-local/src/server/codex-auth-cache.test.ts b/packages/adapters/codex-local/src/server/codex-auth-cache.test.ts
index 0ca1bee28ca..2cd6ba7c173 100644
--- a/packages/adapters/codex-local/src/server/codex-auth-cache.test.ts
+++ b/packages/adapters/codex-local/src/server/codex-auth-cache.test.ts
@@ -463,13 +463,15 @@ describe("codex auth cache store", () => {
releaseFirstCaller = resolve;
});
+ const entered = deferredSignal();
const firstCall = withAccountHomeSecretMutationLock(env, "company-shared", async () => {
events.push("first-enter");
+ entered.resolve();
await firstCallerGate;
events.push("first-exit");
return "first";
});
- await new Promise((resolve) => setTimeout(resolve, 20));
+ await entered.promise;
const secondCall = withAccountHomeSecretMutationLock(env, "company-shared", async () => {
events.push("second-enter");
events.push("second-exit");
@@ -497,12 +499,14 @@ describe("codex auth cache store", () => {
releaseCompanyA = resolve;
});
+ const entered = deferredSignal();
const companyACall = withAccountHomeSecretMutationLock(env, "company-a", async () => {
events.push("a-enter");
+ entered.resolve();
await companyAGate;
events.push("a-exit");
});
- await new Promise((resolve) => setTimeout(resolve, 20));
+ await entered.promise;
const companyBCall = withAccountHomeSecretMutationLock(env, "company-b", async () => {
events.push("b-enter");
events.push("b-exit");
@@ -536,6 +540,28 @@ describe("codex auth cache store", () => {
expect(events).toEqual(["promotion-enter", "mutation-enter", "mutation-exit", "promotion-exit"]);
});
+ it("allows awaited nested writes but expires inherited ownership after release", async () => {
+ const env = envFor(await makeInstanceRoot());
+ const detachedGate = deferredSignal();
+ let detached!: Promise;
+ let enteredDetached = false;
+ await withAccountHomeSecretMutationLock(env, "nested", async () => {
+ await expect(withAccountHomeSecretMutationLock(env, "nested", async () => "nested write")).resolves.toBe("nested write");
+ detached = detachedGate.promise.then(() => withAccountHomeSecretMutationLock(env, "nested", async () => { enteredDetached = true; }));
+ });
+ const holding = deferredSignal();
+ const release = deferredSignal();
+ const other = withAccountHomeSecretMutationLock(env, "nested", async () => { holding.resolve(); await release.promise; });
+ await holding.promise;
+ detachedGate.resolve();
+ try {
+ await new Promise(resolve => setTimeout(resolve, 30));
+ expect(enteredDetached).toBe(false);
+ } finally { release.resolve(); }
+ await Promise.all([other, detached]);
+ expect(enteredDetached).toBe(true);
+ });
+
});
describe("Phase 8: account-home directory validity before a secret write commits", () => {
@@ -581,3 +607,9 @@ describe("codex auth cache store", () => {
});
});
});
+
+function deferredSignal() {
+ let resolve!: () => void;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+}
diff --git a/packages/adapters/codex-local/src/server/codex-auth-cache.ts b/packages/adapters/codex-local/src/server/codex-auth-cache.ts
index c51921fff6b..d6dd757313a 100644
--- a/packages/adapters/codex-local/src/server/codex-auth-cache.ts
+++ b/packages/adapters/codex-local/src/server/codex-auth-cache.ts
@@ -1,4 +1,5 @@
-import { lstat, mkdir, open, readFile, rename, rm } from "node:fs/promises";
+import { AsyncLocalStorage } from "node:async_hooks";
+import { lstat, mkdir, open, readFile, realpath, rename, rm } from "node:fs/promises";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { resolvePaperclipInstanceRootForAdapter } from "@paperclipai/adapter-utils/server-utils";
@@ -334,6 +335,11 @@ export async function withCodexAccountHomePromotionLock(
* create) can still call into a secrets-service write that takes this lock
* without deadlocking on itself.
*/
+// An outer credential transaction acquires this lock before database row locks.
+// Nested secret-service writes must share that ownership, not acquire it again.
+// Expire ownership on return so detached work cannot inherit a released lock.
+const secretMutationOwnership = new AsyncLocalStorage
)}
{account.windows.map((window, index) => window.usedPercent == null ? (
-
-
{window.label}
-
{window.valueLabel ?? "Usage not reported"}
+
+
+ {window.label}
+ {window.valueLabel ?? "Usage not reported"}
+
+ {window.resetsAt &&
Resets {new Date(window.resetsAt).toLocaleString()}
}
) : (
({ health: vi.fn(), inspect: vi.fn(), repair: vi.fn(), retry: vi.fn(), invoices: vi.fn(), importInvoice: vi.fn(), reconcile: vi.fn(), adjust: vi.fn() }));
vi.mock("../api/accounting", () => ({ accountingApi: api }));
@@ -68,6 +69,42 @@ describe("operator accounting tools", () => {
expect(api.adjust).not.toHaveBeenCalled();
});
+ it("confirms an uncertain correction with the original payload after reconciliation changes", async () => {
+ api.invoices.mockResolvedValue([{ id: "first", biller: "openai", externalId: "invoice-one" }, { id: "second", biller: "openai", externalId: "invoice-two" }]);
+ api.reconcile.mockResolvedValue({ invoice: { externalId: "invoice-one", currency: "USD" }, lines: [{ id: "line", externalId: "charge", status: "difference", matchedEventId: "event", recordedCents: "1", amountCents: "2", differenceCents: "1" }] });
+ api.adjust.mockRejectedValueOnce(new Error("Response lost")).mockResolvedValue({});
+ await render(); await click("Open accounting tools"); await click("openai · invoice-one");
+ await input("Invoice correction reason", "Provider receipt"); await click("Apply reviewed correction");
+ const original = structuredClone(api.adjust.mock.calls[0]);
+ expect(original).toEqual(["one", "event", { idempotencyKey: "invoice-line:line", invoiceLineId: "line", expectedCents: "1", correctedCents: "2", reason: "Provider receipt", pricing: { source: "provider_invoice", evidence: "invoice-one" } }]);
+ expect(container.querySelector('[aria-label="Invoice correction reason"]')!.disabled).toBe(true);
+ expect(button("openai · invoice-two").disabled).toBe(true);
+ expect(button("Apply reviewed correction").disabled).toBe(true);
+ // A focus refresh may already show the saved adjustment. Confirmation must
+ // still be available and must not derive its payload from these new totals.
+ api.reconcile.mockResolvedValue({ invoice: { externalId: "invoice-one", currency: "USD" }, lines: [] });
+ await act(async () => { await client.invalidateQueries(); }); await flush();
+ await click("Hide accounting tools"); await click("Open accounting tools");
+ await click("Confirm original correction");
+ expect(api.adjust.mock.calls[1]).toEqual(original);
+ expect(container.textContent).toContain("Correction recorded");
+ expect(container.textContent).not.toContain("Confirm original correction");
+ expect(button("openai · invoice-two").disabled).toBe(false);
+ });
+
+ it("refreshes rejected corrections so the operator can review current evidence", async () => {
+ api.invoices.mockResolvedValue([{ id: "first", biller: "openai", externalId: "invoice-one" }]);
+ api.reconcile.mockResolvedValue({ invoice: { externalId: "invoice-one", currency: "USD" }, lines: [{ id: "line", externalId: "charge", status: "difference", matchedEventId: "event", recordedCents: "1", amountCents: "2", differenceCents: "1" }] });
+ api.adjust.mockRejectedValue(new ApiError("Evidence changed", 409, {}));
+ await render(); await click("Open accounting tools"); await click("openai · invoice-one");
+ await input("Invoice correction reason", "Provider receipt");
+ const reads = api.reconcile.mock.calls.length;
+ await click("Apply reviewed correction");
+ expect(api.reconcile.mock.calls.length).toBeGreaterThan(reads);
+ expect(container.querySelector('[aria-label="Invoice correction reason"]')!.disabled).toBe(false);
+ expect(container.textContent).not.toContain("Confirm original correction");
+ });
+
it("retries only ready receipts and keeps incomplete evidence visible", async () => {
api.health.mockResolvedValue({ companyId: "one", pendingRunCount: 2, unpricedEventCount: 0, pendingCancellationCount: 0, heldReservationCents: "0", items: [
{ runId: "ready", agentId: "a", state: "retryable", attempts: 2, since: "2026-09-28", lastError: "Database unavailable" },
diff --git a/ui/src/components/AccountingHealthPanel.tsx b/ui/src/components/AccountingHealthPanel.tsx
index 6917c6babc0..436efea39f8 100644
--- a/ui/src/components/AccountingHealthPanel.tsx
+++ b/ui/src/components/AccountingHealthPanel.tsx
@@ -2,6 +2,7 @@ import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { formatUsdExact, importBillingInvoiceSchema, type AccountingInspection } from "@paperclipai/shared";
import { accountingApi } from "../api/accounting";
+import { ApiError } from "../api/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
@@ -18,6 +19,7 @@ function AccountingPanel({ companyId }: { companyId: string }) {
const [inspection, setInspection] = useState(null);
const [repairReason, setRepairReason] = useState("");
const [correctionReason, setCorrectionReason] = useState("");
+ const [submittedCorrection, setSubmittedCorrection] = useState<{ eventId: string; input: Parameters[2] } | null>(null);
const [invoiceJson, setInvoiceJson] = useState("");
const [invoiceId, setInvoiceId] = useState("");
const [notice, setNotice] = useState("");
@@ -27,6 +29,23 @@ function AccountingPanel({ companyId }: { companyId: string }) {
const action = useMutation({ mutationFn: async (work: () => Promise) => { setNotice(""); await work(); },
onSuccess: async () => { await client.invalidateQueries(); } });
const run = (work: () => Promise) => action.mutate(work);
+ const correct = async (submission: NonNullable) => {
+ setSubmittedCorrection(submission);
+ try {
+ await accountingApi.adjust(companyId, submission.eventId, submission.input);
+ } catch (error) {
+ // A definite rejection can be reviewed again. An uncertain outcome must
+ // replay the original request, even if reconciliation has since changed.
+ if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
+ setSubmittedCorrection(null);
+ await client.invalidateQueries({ queryKey: ["accounting", companyId, "invoice", invoiceId] });
+ }
+ throw error;
+ }
+ setSubmittedCorrection(null);
+ setCorrectionReason("");
+ setNotice("Correction recorded. The original provider charge remains in the audit history.");
+ };
const error = action.error ?? health.error ?? invoices.error ?? report.error;
return
@@ -74,22 +93,26 @@ function AccountingPanel({ companyId }: { companyId: string }) {
Provider invoices
Import normalized invoice JSON with biller, externalId, currency, and lines. Each line needs externalId, amountCents, occurredAt, and a costEventId, runId, or providerRequestId for matching. Decimal amounts are strings in cents. Fees and credits remain separate from inference charges.
diff --git a/ui/src/pages/Costs.refresh.test.tsx b/ui/src/pages/Costs.refresh.test.tsx
index f8ab53a9fb8..9ed062676ca 100644
--- a/ui/src/pages/Costs.refresh.test.tsx
+++ b/ui/src/pages/Costs.refresh.test.tsx
@@ -116,6 +116,25 @@ describe.each([
expect(container.textContent).not.toContain("Showing the last loaded data");
});
+ it.each(["Last 7 Days", "Last 30 Days"])("retains all report cache entries for %s across midnight", async (period) => {
+ vi.setSystemTime(new Date(2026, 8, 29, 23, 59, 50));
+ await render(); await click(period);
+ await click("Providers"); await click("Billers"); await click("Overview");
+ const keys = client.getQueryCache().getAll().map(q => q.queryHash).sort();
+ const firstFrom = api.summary.mock.calls.at(-1)![1];
+ const row = container.querySelector('[title="Bender"]')!.closest(".border");
+ for (const method of ["summary", "financeEvents", "byProvider", "byBiller"]) api[method].mockRejectedValue(new Error("private failure"));
+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); await settle();
+ await act(async () => { await vi.advanceTimersByTimeAsync(31_000); }); await settle();
+ expect(api.summary.mock.calls.at(-1)![1]).not.toBe(firstFrom);
+ expect(container.textContent).toContain("$402.88");
+ expect(container.querySelector('[title="Bender"]')?.closest(".border")).toBe(row);
+ expect(container.textContent).toContain("Showing the last loaded data");
+ expect(container.textContent).not.toContain("private failure");
+ await click("Providers"); await click("Billers");
+ expect(client.getQueryCache().getAll().map(q => q.queryHash).sort()).toEqual(keys);
+ });
+
it("does not reuse another company's or selected period's data after a failed initial load", async () => {
await render();
api.summary.mockRejectedValue(new Error("database detail must stay private"));
diff --git a/ui/src/pages/Costs.test.tsx b/ui/src/pages/Costs.test.tsx
index 81f63841e00..7662422871c 100644
--- a/ui/src/pages/Costs.test.tsx
+++ b/ui/src/pages/Costs.test.tsx
@@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Costs } from "./Costs";
import { MemoryRouter } from "react-router-dom";
+const resolveIncidentMock = vi.hoisted(() => vi.fn());
const upsertPolicyMock = vi.hoisted(() => vi.fn());
const budgetOverviewMock = vi.hoisted(() => vi.fn());
const setBreadcrumbsMock = vi.hoisted(() => vi.fn());
@@ -30,7 +31,7 @@ vi.mock("../api/budgets", () => ({
budgetsApi: {
overview: (...args: unknown[]) => budgetOverviewMock(...args),
upsertPolicy: upsertPolicyMock,
- resolveIncident: vi.fn(),
+ resolveIncident: resolveIncidentMock,
},
}));
@@ -128,6 +129,25 @@ describe("Shared Costs surfaces", () => {
queryClient.clear();
});
+ it.each(surfaces)("shows failed budget actions on the %s Overview", async (_name, props) => {
+ for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
+ costsApiMocks.summary.mockResolvedValue({ spendCents: 200, budgetCents: 1000, pricingComplete: false });
+ costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
+ budgetOverviewMock.mockResolvedValue({ policies: [], activeIncidents: [{ id: "incident", scopeType: "agent", scopeName: "Codie", status: "open", thresholdType: "hard", amountObserved: 200, amountLimit: 1000 }], pausedAgentCount: 1, pausedProjectCount: 0 });
+ resolveIncidentMock.mockRejectedValue(new Error("private database error"));
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
+ root = createRoot(container);
+ await act(async () => root.render());
+ await act(async () => { await vi.waitFor(() => expect(container.textContent).toContain("Raise budget & resume")); });
+ await act(async () => [...container.querySelectorAll("button")].find(b => b.textContent === "Raise budget & resume")!.click());
+ await act(async () => { await vi.waitFor(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("Could not update the budget")); });
+ expect(resolveIncidentMock).toHaveBeenCalledWith("company-1", "incident", { incidentId: "incident", action: "raise_budget_and_resume", amount: 1200 });
+ expect(container.querySelector('[role="tab"][data-state="active"]')?.textContent).toBe("Overview");
+ expect(container.textContent).toContain("Review pending accounting and unpriced usage");
+ expect(container.textContent).not.toContain("private database error");
+ queryClient.clear();
+ });
+
it("compares monthly budgets only with month-to-date spend", async () => {
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
costsApiMocks.summary.mockResolvedValue({ spendCents: 200, budgetCents: 1000, utilizationPercent: 20, pricingComplete: true });
diff --git a/ui/src/pages/Costs.tsx b/ui/src/pages/Costs.tsx
index a1eda46eaf1..07e71f5c6e4 100644
--- a/ui/src/pages/Costs.tsx
+++ b/ui/src/pages/Costs.tsx
@@ -219,6 +219,7 @@ export function Costs({
// The clock advances the request bounds, not the identity of the report.
// Keep successful data visible during polling; a different company or selected
// period still gets its own cache entry and initial loading state.
+ const reportQueryFrom = preset === "custom" ? from || undefined : undefined;
const reportQueryTo = preset === "custom" ? to || undefined : preset;
const { data: budgetData, isLoading: budgetLoading, error: budgetError } = useQuery({
@@ -258,7 +259,7 @@ export function Costs({
});
const { data: spendData, isLoading: spendLoading, error: spendError } = useQuery({
- queryKey: queryKeys.costs(companyId, from || undefined, reportQueryTo),
+ queryKey: queryKeys.costs(companyId, reportQueryFrom, reportQueryTo),
queryFn: async () => {
const [summary, byAgent, byProject, byAgentModel] = await Promise.all([
costsApi.summary(companyId, from || undefined, to || undefined),
@@ -274,10 +275,10 @@ export function Costs({
const { data: financeData, isLoading: financeLoading, error: financeError } = useQuery({
queryKey: [
- queryKeys.financeSummary(companyId, from || undefined, reportQueryTo),
- queryKeys.financeByBiller(companyId, from || undefined, reportQueryTo),
- queryKeys.financeByKind(companyId, from || undefined, reportQueryTo),
- queryKeys.financeEvents(companyId, from || undefined, reportQueryTo, 18),
+ queryKeys.financeSummary(companyId, reportQueryFrom, reportQueryTo),
+ queryKeys.financeByBiller(companyId, reportQueryFrom, reportQueryTo),
+ queryKeys.financeByKind(companyId, reportQueryFrom, reportQueryTo),
+ queryKeys.financeEvents(companyId, reportQueryFrom, reportQueryTo, 18),
],
queryFn: async () => {
const [summary, byBiller, byKind, events] = await Promise.all([
@@ -320,7 +321,7 @@ export function Costs({
}, [spendData?.byAgentModel]);
const { data: providerData } = useQuery({
- queryKey: queryKeys.usageByProvider(companyId, from || undefined, reportQueryTo),
+ queryKey: queryKeys.usageByProvider(companyId, reportQueryFrom, reportQueryTo),
queryFn: () => costsApi.byProvider(companyId, from || undefined, to || undefined),
enabled: !!selectedCompanyId && customReady && (mainTab === "providers" || mainTab === "billers"),
refetchInterval: 30_000,
@@ -328,7 +329,7 @@ export function Costs({
});
const { data: billerData } = useQuery({
- queryKey: queryKeys.usageByBiller(companyId, from || undefined, reportQueryTo),
+ queryKey: queryKeys.usageByBiller(companyId, reportQueryFrom, reportQueryTo),
queryFn: () => costsApi.byBiller(companyId, from || undefined, to || undefined),
enabled: !!selectedCompanyId && customReady && mainTab === "billers",
refetchInterval: 30_000,
@@ -679,6 +680,7 @@ export function Costs({
) : null}
{!!spendData?.summary.estimatedEventCount && Includes {spendData.summary.estimatedEventCount} estimated run charges. Token estimates use published rates and recorded assumptions; provider bills may differ.
}
+ {incidentMutation.error && Could not update the budget. Review pending accounting and unpriced usage in Accounting tools, then try again.
}
setMainTab(value as typeof mainTab)}>
{!lockTab ? (
@@ -909,7 +911,7 @@ export function Costs({
- {(policyMutation.error || incidentMutation.error) && {(policyMutation.error ?? incidentMutation.error)?.message}
}
+ {policyMutation.error && {policyMutation.error.message}
}
{budgetLoading ? (
) : budgetError && !budgetData ? (