Files
PaperClipAI/ui/src/components/CostDataQualityNotice.test.tsx
T
1b4c803816 fix(costs): preserve usage attribution and explain unavailable run costs (#15948)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The cost ledger records usage and controls agent budgets.
> - Some runs lose the selected model or API billing category before
their usage reaches the ledger.
> - The dashboard reports missing costs but does not identify the
affected runs or the available actions.
> - This pull request preserves usage attribution and adds a compact
view of cost gaps grouped by agent.
> - Operators can inspect runs, open agent settings, and record saved
costs without starting new agent work.

## Linked Issues or Issue Description

Refs #15634, #11938, #15879.

This follows the merged subscription reporting in #15634. The older
proposal in #11938 addresses part of ACP model attribution. This change
also rejects conflicting models across a turn, fixes credential-backed
billing capture, and explains cost gaps in the existing dashboard. The
Pi receipt recovery work in #15879 covers a separate adapter recovery
path. This PR preserves unresolved receipts and does not recover
provider usage or reprice past entries.

**What happened?**

ACP results use the requested model even when the runtime selects a
model. Native and OpenCode API runs can report unknown billing despite a
matching API credential. The dashboard shows notices without links to
the affected runs. These gaps make API and subscription totals harder to
interpret.

**Expected behavior**

Record the model selected by the runtime. Identify API billing only from
a matching credential. Keep costs unresolved when reliable usage or
pricing is absent. Show the affected agents and runs. Offer an
accounting retry only when saved evidence is ready.

**Steps to reproduce**

1. Run an ACP agent with its model left unset, or use a matching API
credential with a native or OpenCode agent.
2. Inspect the recorded model and billing category for the run.
3. Open Costs Overview for a period with unpriced usage or terminal runs
awaiting receipts.
4. Inspect the notice and try to find the affected run or the relevant
agent settings.

**Paperclip version or commit**

Current master at `657e71584a0`. The patch is rebased on that commit.

**Deployment mode**

Self-hosted server and local development. The cost detail tests use a
disposable PostgreSQL database.

## What Changed

- Preserve the runtime-selected ACP model in checkpoints and final
results. Conflicting models across one turn remain unpriced.
- Share credential-backed API billing checks across native and OpenCode
results. Keep unknown billing when the provider and credential do not
match.
- Add company-scoped cost detail and accounting retry endpoints. Board
viewers can read details but cannot retry. Agents and foreign companies
are denied.
- Limit each detail category to 25 entries. Use one consistent database
snapshot and sparse indexes matching the filters and sort order. Add the
unknown-billing count to the existing summary query.
- Replace the notice with an expandable count line. Group entries
alphabetically by agent. Show the saved blob icon, link each name to
configuration, and put run and retry links beside the date.
- Preserve estimate and unavailable-price labels on Providers and
Billers; keep retry confirmation after the resolved notice disappears.
- Fetch details only while expanded. Retain the last loaded details
after a refresh error. Retry saved accounting only; do not rerun the
agent.
- Add capture, database, authorization, UI, and Storybook coverage.
Update the implementation contract and cost reporting guide.

## Verification

- `pnpm -r typecheck` passed after rebase.
- `pnpm build` and `pnpm build-storybook` passed after rebase.
- `pnpm check:token-gates` and `git diff --check` passed.
- 1,086 focused tests passed across 17 files. These cover ACP, native
and OpenCode capture, PostgreSQL reports, route authorization, OpenAPI,
Costs UI, and existing accounting regressions.
- Desktop and mobile browser checks passed during UI review. They cover
lazy expansion, alphabetical groups, loaded blob icons, configuration
and run links, keyboard retry, and layout overflow.
- `pnpm test:run` was attempted with command-scoped
`init.defaultBranch=master` for Git fixtures. It was stopped after a
native session recovery failure reproduced on unchanged base
`657e71584a0` (`archives a damaged prior epoch before completing guarded
same-task replacement with real runnerd`). An MCP upload case failed in
the broad run but passed in isolation on both the base and PR branch.
These local limitations do not affect the 1,086 passing focused tests.
- Current-head CI is green, including all unit test lanes, serialized
server suites, runner checks, typecheck, build, policy, and eight
browser shards. Apex re-review is 5/5 on `56de60effdb`; all four
original findings are addressed and every review thread is resolved.
- PostgreSQL applies migration `0333` in the integration fixtures.
EXPLAIN ANALYZE on the production detail statements uses the new sparse
indexes behind 5,000 healthy records in each table.
- Ten provider/biller card cases cover missing and estimated prices; the
retry test covers row removal and notice unmount. A live Storybook
browser check verifies the confirmation and updated count.
- Run `pnpm storybook`. Open **Costs / Subscriptions / Cost Data Quality
Details** to inspect the production page with representative fixtures.

## Risks

- Model and billing metadata change for future runs. Estimates still
require complete usage and a supported price. No past cost amount is
rewritten.
- A missing final receipt remains unresolved for budget checks. The
display changes after fifteen minutes; that time limit never authorizes
settlement.
- Accounting retry is a write action. It retains the existing company
checks, receipt fences, idempotency, and audit logging.
- Detail reads are bounded and run only after expansion. They poll every
30 seconds while open. No provider probe or new summary query is added.
- Migration `0333` adds two partial indexes; it changes no stored cost
amounts or table columns. Index creation scans the existing tables and
may briefly block writes during deployment. No lockfile or workflow
change is included.

## Model Used

OpenAI Codex, based on GPT-6, with repository inspection, code editing,
browser checks, and test execution. The exact serving model ID,
reasoning setting, and context window were not exposed to this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-11 22:48:29 -07:00

193 lines
13 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { MemoryRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { appearanceForPalette, agentAvatarUrl, type CostDataQualityItem, type CostDataQualityReason, type CostDataQualityReport } from "@paperclipai/shared";
import { ToastProvider, useToastState } from "../context/ToastContext";
import { CostDataQualityNotice } from "./CostDataQualityNotice";
const mocks = vi.hoisted(() => ({ dataQuality: vi.fn(), retryAccounting: vi.fn() }));
vi.mock("../api/costs", () => ({ costsApi: mocks }));
vi.mock("../context/CompanyContext", () => ({ useCompany: () => ({ selectedCompany: { issuePrefix: "PAP" } }) }));
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const key = ["costs", "company", "2026-10-01", "2026-10-09"];
function item(reason: CostDataQualityReason): CostDataQualityItem {
return { id: reason, runId: `${reason}-run`, agentId: "codie", agentName: "Codie", occurredAt: "2026-10-09T12:00:00Z", provider: "openai", model: "gpt-6-astra", reason };
}
function report(canRetry = true): CostDataQualityReport {
return { canRetry, events: [item("unknown_billing"), item("missing_model"), item("missing_price")],
runs: [item("waiting_for_receipt"), item("receipt_unavailable"), item("retryable")], hasMoreEvents: false, hasMoreRuns: false };
}
function ToastStatus() {
const toasts = useToastState();
return <div aria-label="Notifications">{toasts.map(toast => <p role="status" key={toast.id}>{toast.title} {toast.body}</p>)}</div>;
}
describe("actionable cost notices", () => {
let container: HTMLDivElement, root: ReturnType<typeof createRoot>, client: QueryClient;
beforeEach(() => {
vi.resetAllMocks(); mocks.dataQuality.mockResolvedValue(report()); mocks.retryAccounting.mockResolvedValue({ accounted: true });
container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container);
client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
});
afterEach(() => { act(() => root.unmount()); client.clear(); container.remove(); });
async function render(counts: { unpricedCount?: number; pendingCount?: number; unknownBillingCount?: number } = {}) {
await act(async () => root.render(<MemoryRouter initialEntries={["/PAP/activity/costs"]}><QueryClientProvider client={client}><ToastProvider><ToastStatus />
<CostDataQualityNotice companyId="company" from="2026-10-01" to="2026-10-09" reportKey={key} unpricedCount={12} pendingCount={4} unknownBillingCount={9} {...counts} />
</ToastProvider></QueryClientProvider></MemoryRouter>));
}
function button(text: string) { return [...container.querySelectorAll("button")].find(button => button.textContent === text)!; }
async function click(text: string) { await act(async () => button(text).click()); }
async function loaded() { await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Ready to record"))); }
it("loads bounded details only on demand using the displayed period", async () => {
await render(); expect(mocks.dataQuality).not.toHaveBeenCalled();
expect(button("16 run costs unavailable").getAttribute("aria-expanded")).toBe("false");
expect(container.textContent).toBe("16 run costs unavailable");
expect(container.querySelector('svg[aria-hidden="true"]')).not.toBeNull();
expect(container.querySelector('[role="alert"]')).toBeNull();
await click("16 run costs unavailable"); await loaded();
expect(mocks.dataQuality).toHaveBeenCalledExactlyOnceWith("company", "2026-10-01", "2026-10-09");
expect(button("16 run costs unavailable").getAttribute("aria-expanded")).toBe("true");
const details = document.getElementById(button("16 run costs unavailable").getAttribute("aria-controls")!)!;
expect(details.textContent).not.toContain("Totals include known charges only.");
expect(details.textContent).not.toContain("12 entries without prices · 4 runs without final cost data · 9 entries with unknown billing");
expect(details.textContent).not.toContain("Includes 12 estimated charges.");
await click("16 run costs unavailable");
expect(container.querySelector("ul")).toBeNull();
expect(container.textContent).toBe("16 run costs unavailable");
});
it("explains future configuration fixes and links to the affected runs in the active company", async () => {
await render(); await click("16 run costs unavailable"); await loaded();
const row = (label: string) => [...container.querySelectorAll('[data-slot="badge"]')].find(badge => badge.textContent === label)!.closest("li")!;
const billing = row("Billing category unknown");
expect(billing.textContent).toContain("Any recorded charges are included in the inference ledger.");
const configuration = container.querySelector('a[href="/PAP/agents/codie/configuration"]')!;
expect(configuration.textContent).toBe("Codie");
expect(configuration.closest("h3")!.textContent).toBe("Codie");
expect(container.querySelectorAll('a[href="/PAP/agents/codie/configuration"]')).toHaveLength(1);
expect(billing.querySelector('a[href="/PAP/agents/codie/configuration"]')).toBeNull();
expect(billing.querySelector('a[href="/PAP/agents/codie/runs/unknown_billing-run"]')).not.toBeNull();
for (const link of container.querySelectorAll("a")) expect(link.hasAttribute("data-slot")).toBe(false);
expect(container.querySelectorAll("h3")).toHaveLength(1);
expect(container.querySelectorAll('[data-slot="agent-avatar"]')).toHaveLength(1);
expect(container.textContent).toContain("Changing settings will not reprice this past run.");
const runs = [row("Receiving usage"), row("Final usage unavailable")];
expect(runs[0].textContent).toContain("You do not need to rerun the agent.");
expect(runs[1].textContent).toContain("Its cost remains unresolved for budget checks.");
expect(runs[1].textContent).toContain("rerunning the agent will not recover this usage.");
expect(runs[0].querySelector("button")).toBeNull();
expect(runs[1].querySelector("button")).toBeNull();
expect([...container.querySelectorAll("button")].filter(row => row.textContent === "Retry cost recording")).toHaveLength(1);
const actionLine = button("Retry cost recording").parentElement!;
expect(actionLine.children[0].tagName).toBe("TIME");
expect(actionLine.children[1].textContent).toBe("View run");
expect(actionLine.children[2].textContent).toBe("Retry cost recording");
expect(button("Retry cost recording").getAttribute("data-variant")).toBe("link");
});
it("groups all kinds of cost gaps by agent identity, alphabetizes names, and preserves appearances and newest-first entries", async () => {
const appearance = appearanceForPalette("deep-tide");
mocks.dataQuality.mockResolvedValue({ canRetry: true, hasMoreEvents: false, hasMoreRuns: false,
events: [
{ ...item("missing_model"), agentId: "fry", agentName: "fry" },
{ ...item("missing_price"), id: "shared-id", agentAppearance: appearance, occurredAt: "2026-10-08T12:00:00Z" },
{ ...item("unknown_billing"), agentId: null, agentName: null, runId: null },
{ ...item("missing_price"), id: "other-codie", agentId: "codie-2" },
],
runs: [
{ ...item("receipt_unavailable"), agentId: "leela", agentName: "Leela" },
{ ...item("retryable"), id: "shared-id", agentAppearance: appearance },
],
});
await render(); await click("16 run costs unavailable"); await loaded();
const groups = [...container.querySelectorAll('[aria-label="Cost details by agent"] > li')];
expect(groups.map(group => group.querySelector("h3")!.textContent)).toEqual(["Codie", "Codie", "fry", "Leela", "Paperclip services"]);
const codieItems = groups[0].querySelectorAll("li");
expect(codieItems).toHaveLength(2);
expect(codieItems[0].textContent).toContain("Ready to record");
expect(codieItems[1].textContent).toContain("Cost unavailable");
expect(groups[1].querySelectorAll("li")).toHaveLength(1);
expect(groups[0].querySelector("img")?.getAttribute("src")).toBe(agentAvatarUrl(appearance, 20));
expect(groups[4].querySelector("a")).toBeNull();
});
it("does not label priced unknown billing or estimates as unavailable costs", async () => {
await render({ unpricedCount: 0, pendingCount: 0, unknownBillingCount: 1 });
expect(container.textContent).toBe("1 billing type unknown");
await click("1 billing type unknown"); await loaded();
expect(container.textContent).toContain("Billing category unknown");
expect(container.textContent).not.toContain("Totals include known charges only.");
expect(container.textContent).not.toContain("Includes 12 estimated charges.");
});
it("records saved costs without rerunning work and refreshes every period for this company", async () => {
let finish!: (result: { accounted: boolean }) => void;
mocks.retryAccounting.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
await render(); await click("16 run costs unavailable"); await loaded();
const invalidate = vi.spyOn(client, "invalidateQueries");
await click("Retry cost recording");
await act(async () => vi.waitFor(() => expect(button("Retry cost recording").disabled).toBe(true)));
await click("Retry cost recording");
expect(mocks.retryAccounting).toHaveBeenCalledTimes(1);
await act(async () => finish({ accounted: true }));
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Costs recorded.")));
expect(mocks.retryAccounting).toHaveBeenCalledExactlyOnceWith("company", "retryable-run");
expect(invalidate).toHaveBeenCalledWith({ queryKey: ["costs", "company"] });
expect(invalidate).toHaveBeenCalledWith({ queryKey: ["cost-subscriptions", "company"] });
});
it("keeps retry confirmation after the refreshed report removes the run and the notice unmounts", async () => {
mocks.dataQuality.mockResolvedValueOnce({ ...report(), events: [], runs: [item("retryable")] })
.mockResolvedValue({ ...report(), events: [], runs: [] });
await render({ unpricedCount: 0, pendingCount: 1, unknownBillingCount: 0 });
await click("1 run cost unavailable"); await loaded();
await click("Retry cost recording");
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("No cost gaps remain")));
expect(container.textContent).not.toContain("Retry cost recording");
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={client}>
<ToastProvider><ToastStatus /></ToastProvider>
</QueryClientProvider></MemoryRouter>));
expect(container.textContent).toContain("Costs recorded. The agent was not rerun.");
});
it("makes stale retry results understandable and never renders raw provider errors", async () => {
mocks.retryAccounting.mockResolvedValueOnce({ accounted: false }).mockRejectedValueOnce(new Error("SECRET sh -c provider --token credential"));
await render(); await click("16 run costs unavailable"); await loaded();
await click("Retry cost recording");
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("No new cost data is available. The agent was not rerun.")));
await click("Retry cost recording");
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Cost recording failed. Try again shortly.")));
expect(container.textContent).not.toContain("SECRET");
expect(container.textContent).not.toContain("credential");
});
it("keeps viewer details readable without exposing the retry action", async () => {
mocks.dataQuality.mockResolvedValue(report(false));
await render(); await click("16 run costs unavailable"); await loaded();
expect(container.textContent).not.toContain("Retry cost recording");
expect(mocks.retryAccounting).not.toHaveBeenCalled();
});
it("retains the last successful details through a failed background refresh", async () => {
await render(); await click("16 run costs unavailable"); await loaded();
mocks.dataQuality.mockRejectedValue(new Error("SECRET backend exception"));
await act(async () => { await client.invalidateQueries({ queryKey: [...key, "data-quality"] }); });
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Showing the last loaded cost details.")));
expect(container.textContent).toContain("Ready to record");
expect(container.textContent).not.toContain("SECRET");
});
it("offers a safe first-load retry and explains truncated results", async () => {
mocks.dataQuality.mockRejectedValueOnce(new Error("SECRET command"));
await render(); await click("16 run costs unavailable");
await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Cost details could not be loaded.")));
expect(container.textContent).not.toContain("SECRET");
mocks.dataQuality.mockResolvedValue({ ...report(), hasMoreRuns: true });
await click("Retry loading"); await loaded();
expect(container.textContent).toContain("Select a shorter date range to inspect more.");
});
});