Skip to content

The open-source app everyone uses to manage agents at work

fix(costs): preserve usage attribution and explain unavailable run costs (#15948)

Devin Foley1b4c803816e8
diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md
index 54be98db81..02f459214c 100644
--- a/doc/SPEC-implementation.md
+++ b/doc/SPEC-implementation.md
@@ -1601,6 +1601,26 @@ Validation:
Read-time aggregate queries are acceptable for V1.
Materialized rollups can be added later if query latency exceeds targets.
+The Costs overview distinguishes unknown billing categories, missing model/price
+data, and terminal runs awaiting final receipts. Bounded, company-scoped details
+load on demand at `GET /companies/:companyId/costs/data-quality`. Entries link to
+the run and, where applicable, agent configuration for future usage. Normal
+credits and fixed billing are not unknown billing warnings. Unavailable historic
+prices require no cleanup and must not be presented as zero-cost receipts.
+
+`POST /companies/:companyId/costs/retry-accounting` accepts a run ID, requires a
+board cost reader with a non-viewer membership, and uses the existing audited,
+idempotent accounting service. It never executes an agent. The UI offers retry
+only when the saved run is eligible to record costs. Missing final usage changes
+its display label after fifteen minutes; elapsed time never settles the debt or
+discards a late receipt. Raw provider errors and credentials are excluded from
+cost details. ACP usage retains the runtime-selected model, including defaults;
+conflicting before/after model IDs do not authorize a single-model estimate.
+Remote OpenCode billing uses only credentials forwarded to the execution target.
+Cost detail reads use company-scoped partial indexes matching their filters and
+sort order. Provider and biller cards retain estimate and missing-price labels;
+an accounting retry confirmation survives removal of the resolved cost gap.
+
## 14. UI Requirements (Board App)
V1 UI routes:
diff --git a/docs/guides/agent-developer/cost-reporting.md b/docs/guides/agent-developer/cost-reporting.md
index 6f8c81541e..0c3f247ac1 100644
--- a/docs/guides/agent-developer/cost-reporting.md
+++ b/docs/guides/agent-developer/cost-reporting.md
@@ -17,6 +17,51 @@ Cost reporting happens automatically through adapters. When an agent heartbeat c
The server records this as a cost event for budget tracking.
+Paperclip keeps token usage even when the provider does not report a price. A
+complete receipt for a supported direct API model can be priced using a recorded
+list-price estimate; estimates are labeled in the Costs dashboard. Missing costs
+are never treated as proof of free usage.
+
+## Understanding incomplete cost data
+
+The Costs overview shows a compact line such as **12 run costs unavailable** when
+usage is missing a price or final receipt. Expand it with the arrow to see the
+affected entries, grouped alphabetically by agent with links to
+each run. Unknown billing types use their own label rather than counting as
+unavailable costs. Estimates remain labeled on spend cards and tables.
+Select an agent's name to open its configuration.
+Provider and biller cards also label estimates and unavailable prices. A total
+with only unpriced entries shows a dash instead of $0.00. Successful recording
+shows a confirmation even when it resolves the last gap.
+
+- **Billing category unknown:** select an AI connection in the agent's
+ configuration for future runs. Recorded charges remain in the inference ledger.
+- **Model not reported:** select an explicit model for future runs. ACP adapters
+ also retain the provider-selected model when the runtime reports it, including
+ its default model. A model change during a turn is not priced as one model.
+- **Cost unavailable:** the past entry has no reliable price. No cleanup is
+ required; totals include known charges only.
+- **Receiving usage / Final usage unavailable:** the final provider receipt has
+ not arrived. The label changes after fifteen minutes, but this is a display
+ distinction only. Paperclip still accepts late receipts and preserves the
+ accounting debt. Rerunning an agent does not recover its previous receipt.
+- **Ready to record:** Paperclip can retry saved accounting data. **Retry cost
+ recording** records costs only and never starts agent work. Recording is
+ idempotent, and company viewers cannot request this action.
+
+Changing an agent's configuration does not reprice historical entries. Normal
+credits and fixed billing are listed as other billing usage, without an unknown
+billing warning. OpenCode API billing can be identified from a nonempty API key
+for its selected provider; the provider name alone is insufficient evidence.
+Remote OpenCode runs use only keys forwarded to the remote process. Keys present
+on the Paperclip server do not establish a remote run's billing category.
+
+Board cost readers can inspect bounded details at
+`GET /api/companies/{companyId}/costs/data-quality`, with the same date bounds as
+other cost reports. Details contain no provider errors or credentials and load
+only when expanded in the UI. Authorized board members can request recording at
+`POST /api/companies/{companyId}/costs/retry-accounting` with `{ "runId": "uuid" }`.
+
## Cost Events API
Cost events can also be reported directly:
diff --git a/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts b/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts
new file mode 100644
index 0000000000..e7bc77e698
--- /dev/null
+++ b/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { acpxAccountingModel } from "./accounting-model.js";
+
+const selected = (id: string) => ({ models: { currentModelId: id, availableModelIds: [id] } });
+describe("ACP accounting model", () => {
+ it("retains the runtime's default and effective model instead of the requested label", () => {
+ expect(acpxAccountingModel("", selected("gpt-6.1-sol"), selected("gpt-6.1-sol"))).toBe("gpt-6.1-sol");
+ expect(acpxAccountingModel("default", null, selected("gpt-6-astra"))).toBe("gpt-6-astra");
+ expect(acpxAccountingModel("", selected("gpt-6-astra"), null)).toBe("gpt-6-astra");
+ });
+ it("uses explicit configuration only when no selected model was reported", () => {
+ expect(acpxAccountingModel("gpt-6.1-sol", null, null)).toBe("gpt-6.1-sol");
+ expect(acpxAccountingModel("", { models: { availableModelIds: ["gpt-6.1-sol"] } }, null)).toBeNull();
+ });
+ it("does not price a turn that changed models as one model", () => {
+ expect(acpxAccountingModel("gpt-6.1-sol", selected("gpt-6.1-sol"), selected("gpt-6-astra"))).toBeNull();
+ });
+});
diff --git a/packages/adapter-utils/src/acpx-engine/accounting-model.ts b/packages/adapter-utils/src/acpx-engine/accounting-model.ts
new file mode 100644
index 0000000000..df181bc6bc
--- /dev/null
+++ b/packages/adapter-utils/src/acpx-engine/accounting-model.ts
@@ -0,0 +1,10 @@
+import type { AcpRuntimeStatus } from "acpx/runtime";
+
+/** Use provider-selected IDs, including its default. A mid-turn model change
+ * cannot be priced as a single-model receipt; never guess from a display name. */
+export function acpxAccountingModel(requested: string, before: AcpRuntimeStatus | null, after: AcpRuntimeStatus | null): string | null {
+ const pre = before?.models?.currentModelId?.trim();
+ const post = after?.models?.currentModelId?.trim();
+ if (pre && post && pre !== post) return null;
+ return post || pre || requested.trim() || null;
+}
diff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.ts
index b78e91122c..704e0643cd 100644
--- a/packages/adapter-utils/src/acpx-engine/execute.test.ts
+++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts
@@ -1403,6 +1403,7 @@ describe("shared ACPX engine runtime behavior", () => {
const stateDir = path.join(root, "state");
const logs: Array<{ stream: string; text: string }> = [];
let statusCalls = 0;
+ const onUsage = vi.fn();
const execute = createAcpxEngineExecutor({
createRuntime: () => ({
ensureSession: async () => ({
@@ -1413,8 +1414,9 @@ describe("shared ACPX engine runtime behavior", () => {
getStatus: async () => {
statusCalls += 1;
return statusCalls === 1
- ? { usage: { cost: { amount: 0.4, currency: "USD" } } }
+ ? { models: { currentModelId: "claude-observed-default", availableModelIds: [] }, usage: { cost: { amount: 0.4, currency: "USD" } } }
: {
+ models: { currentModelId: "claude-observed-default", availableModelIds: [] },
usage: {
cumulative: {
inputTokens: 120,
@@ -1448,6 +1450,7 @@ describe("shared ACPX engine runtime behavior", () => {
const result = await execute({
runId: "run-usage-capture",
+ onUsage,
agent: {
id: "agent-1",
companyId: "company-1",
@@ -1471,6 +1474,8 @@ describe("shared ACPX engine runtime behavior", () => {
expect(result.provider).toBe("anthropic");
expect(result.biller).toBe("anthropic");
expect(result.billingType).toBe("api");
+ expect(result.model).toBe("claude-observed-default");
+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ model: "claude-observed-default", complete: true }));
expect((result.resultJson as Record<string, unknown>)?.cumulativeCostUsd).toBeCloseTo(1.15);
expect((result.resultJson as Record<string, unknown>)?.usage).toEqual({
inputTokens: 120,
diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.ts
index 135126363f..e84c601499 100644
--- a/packages/adapter-utils/src/acpx-engine/execute.ts
+++ b/packages/adapter-utils/src/acpx-engine/execute.ts
@@ -129,6 +129,7 @@ import type {
TurnCompletion,
} from "./run-contracts.js";
import { createRunResourceLedger } from "./run-resource-ledger.js";
+import { acpxAccountingModel } from "./accounting-model.js";
import { settleAcpRun, type SettlementSteps } from "./settlement-sequence.js";
import {
runAttempt,
@@ -4765,6 +4766,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
// scoped hoisted local, so the settlement `endSession` step can cancel it.
let runPrompt = "";
let preTurnStatus: AcpRuntimeStatus | null = null;
+ let accountingModel: string | null = prepared.requestedModel || null;
// Phase-timing markers for the prepare_turn and turn phases. The prepare
// phase covers the prompt build and the pre-turn usage snapshot; the turn
// phase covers the started turn and the event relay.
@@ -4836,6 +4838,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
// Snapshot pre-turn usage so cumulative agent-reported cost can be
// attributed to this run alone.
preTurnStatus = await readRuntimeStatus(runtime, sessionHandle);
+ accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, null);
// The prepare phase (prompt build + usage snapshot) finished; the turn
// phase starts next.
await emitPhase("prepare_turn", preparePhaseStart, "ok");
@@ -4965,7 +4968,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
const checkpoint = summarizeAcpxTurnUsage({ preStatus: preTurnStatus, postStatus: null, eventBreakdown, eventCostUsd });
observedUsage = { usage: checkpoint.usage ?? undefined, costUsd: checkpoint.costUsd, usageBasis: "per_run", usageComplete: false };
await ctx.onUsage?.({ ...billingFields, usage: checkpoint.usage ?? undefined, costUsd: checkpoint.costUsd,
- model: prepared.requestedModel, usageBasis: "per_run", complete: false });
+ model: accountingModel, usageBasis: "per_run", complete: false });
}
await emitRuntimeEvent(ctx, event, toolTitles, prepared.coalescePlaceholderToolUpdates);
}
@@ -5046,6 +5049,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
const turnSucceeded = terminal.status === "completed" && !timedOut && !channelLost;
// Read usage before the settlement can discard runtime state.
const postTurnStatus = await readRuntimeStatus(runtime, sessionHandle);
+ accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, postTurnStatus);
const turnUsage = summarizeAcpxTurnUsage({
preStatus: preTurnStatus,
postStatus: postTurnStatus,
@@ -5057,7 +5061,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
const usageComplete = !channelLost && (turnSucceeded || postTurnStatus?.usage != null);
observedUsage = { usage: turnUsage.usage ?? undefined, costUsd: turnUsage.costUsd, usageBasis: "per_run", usageComplete };
await ctx.onUsage?.({ ...billingFields, usage: turnUsage.usage ?? undefined, costUsd: turnUsage.costUsd,
- model: prepared.requestedModel, usageBasis: "per_run", complete: usageComplete });
+ model: accountingModel, usageBasis: "per_run", complete: usageComplete });
const failedTurn = terminal.status === "failed" || terminal.status === "cancelled" || timedOut;
// ACPX can defer session/load until runTurn. Forget an unavailable
// session so the next bounded turn receives the full task conversation.
@@ -5140,7 +5144,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
sessionDisplayId: sessionHandle.agentSessionId ?? sessionHandle.backendSessionId ?? sessionHandle.runtimeSessionName,
...billingFields,
...referencedProjectStagingFailuresField,
- model: prepared.requestedModel || null,
+ model: accountingModel,
...(turnUsage.usage ? { usage: turnUsage.usage, usageBasis: "per_run" as const } : {}),
costUsd: turnUsage.costUsd,
usageComplete,
@@ -5281,7 +5285,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
...(!turnDispatchAttempted ? { executionRecovery: { kind: "bootstrap" as const, providerWorkStarted: false as const } } : {}),
...billingFields,
...referencedProjectStagingFailuresField,
- model: prepared.requestedModel || null,
+ model: accountingModel,
clearSession: clearSession || timedOut,
resultJson: { phase, ...activityDiagnostics },
summary: message,
diff --git a/packages/adapter-utils/src/api-billing-type.test.ts b/packages/adapter-utils/src/api-billing-type.test.ts
new file mode 100644
index 0000000000..5804093cce
--- /dev/null
+++ b/packages/adapter-utils/src/api-billing-type.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+import { apiKeyBillingType } from "./api-billing-type.js";
+
+describe("verified API billing", () => {
+ it.each([
+ ["openrouter", "OPENROUTER_API_KEY"], ["openai", "OPENAI_API_KEY"],
+ ["anthropic", "ANTHROPIC_API_KEY"], ["deepseek", "DEEPSEEK_API_KEY"],
+ ])("classifies %s with its matching credential", (provider, key) => {
+ expect(apiKeyBillingType(provider, { [key]: "fixture-key" })).toBe("metered_api");
+ });
+ it("recognizes Codex's key alias only for the Codex runtime", () => {
+ const env = { CODEX_API_KEY: "fixture" };
+ expect(apiKeyBillingType("openai", env, "codex")).toBe("metered_api");
+ expect(apiKeyBillingType("openai", env)).toBe("unknown");
+ expect(apiKeyBillingType("openrouter", env, "codex")).toBe("unknown");
+ });
+ it.each(["openrouter", "openai", "constructor", "toString", null, "unsupported"]) ("does not infer billing for %s", provider => {
+ expect(apiKeyBillingType(provider, { ANTHROPIC_API_KEY: "unrelated-key", OPENAI_API_KEY: " " })).toBe("unknown");
+ });
+});
diff --git a/packages/adapter-utils/src/api-billing-type.ts b/packages/adapter-utils/src/api-billing-type.ts
new file mode 100644
index 0000000000..28402cc4f4
--- /dev/null
+++ b/packages/adapter-utils/src/api-billing-type.ts
@@ -0,0 +1,17 @@
+import type { AdapterBillingType } from "./types.js";
+
+const API_KEY_NAMES: Readonly<Record<string, readonly string[]>> = {
+ openai: ["OPENAI_API_KEY"],
+ openrouter: ["OPENROUTER_API_KEY"],
+ anthropic: ["ANTHROPIC_API_KEY"],
+ deepseek: ["DEEPSEEK_API_KEY"],
+};
+
+/** A model/provider name alone does not prove billing. Only a matching API
+ * credential establishes API use; ambient auth files remain unclassified. */
+export function apiKeyBillingType(provider: string | null, env: Record<string, string | undefined>, runtime?: "codex"): AdapterBillingType {
+ // Codex's credential alias is not accepted by other OpenAI clients.
+ if (provider === "openai" && runtime === "codex" && env.CODEX_API_KEY?.trim()) return "metered_api";
+ const keys = provider && Object.hasOwn(API_KEY_NAMES, provider) ? API_KEY_NAMES[provider] : undefined;
+ return keys?.some(key => Boolean(env[key]?.trim())) ? "metered_api" : "unknown";
+}
diff --git a/packages/adapters/opencode-local/src/server/execute.remote.test.ts b/packages/adapters/opencode-local/src/server/execute.remote.test.ts
index 2271749e33..13335c0be6 100644
--- a/packages/adapters/opencode-local/src/server/execute.remote.test.ts
+++ b/packages/adapters/opencode-local/src/server/execute.remote.test.ts
@@ -13,11 +13,11 @@ const {
syncDirectoryToSsh,
startAdapterExecutionTargetPaperclipBridge,
} = vi.hoisted(() => ({
- runChildProcess: vi.fn(async (_runId: string, _command: string, args: string[]) => {
+ runChildProcess: vi.fn(async (_runId: string, _command: string, args: string[], _options?: { onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void> }) => {
if (args.includes("models")) {
return {
exitCode: 0,
- signal: null,
+ signal: null as string | null,
timedOut: false,
stdout: "opencode/gpt-5-nano\nopenai/gpt-4.1\n",
stderr: "",
@@ -27,7 +27,7 @@ const {
}
return {
exitCode: 0,
- signal: null,
+ signal: null as string | null,
timedOut: false,
stdout: [
JSON.stringify({ type: "step_start", sessionID: "session_123" }),
@@ -126,6 +126,37 @@ describe("opencode remote execution", () => {
}
});
+ it.each([[false, false], [false, true], [true, false], [true, true]])(
+ "uses only forwarded credentials for remote billing (forwarded=%s, timeout=%s)", async (forwarded, timedOut) => {
+ vi.stubEnv("OPENROUTER_API_KEY", "host-only-api-key");
+ const workspace = await mkdtemp(path.join(os.tmpdir(), "opencode-remote-billing-"));
+ cleanupDirs.push(workspace);
+ const usageLine = JSON.stringify({ type: "step_finish", sessionID: "session-billing",
+ part: { cost: 0.001, tokens: { input: 10, output: 2, cache: { read: 1, write: 0 } } } });
+ runChildProcess.mockImplementationOnce(async (_runId, _command, _args, options) => {
+ await options?.onLog?.("stdout", `${usageLine}\n`);
+ return { stdout: usageLine, stderr: "", exitCode: timedOut ? 143 : 0,
+ signal: timedOut ? "SIGTERM" : null, timedOut, pid: 123, startedAt: new Date().toISOString() };
+ });
+ const onUsage = vi.fn();
+ const result = await execute({
+ runId: "remote-billing", agent: { id: "agent", companyId: "company", name: "OpenCode", adapterType: "opencode_local", adapterConfig: {} },
+ runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
+ config: { command: "opencode", cwd: workspace, model: "openrouter/anthropic/claude-sonnet-4.5",
+ env: { OPENCODE_ALLOW_ALL_MODELS: "1", ...(forwarded ? { OPENROUTER_API_KEY: "forwarded-api-key" } : {}) } },
+ context: {}, executionTransport: { remoteExecution: { host: "127.0.0.1", port: 2222, username: "fixture", remoteCwd: "/remote/workspace", remoteWorkspacePath: "/remote/workspace" } },
+ onLog: async () => {}, onUsage,
+ });
+ const expected = forwarded ? "metered_api" : "unknown";
+ expect(result.billingType).toBe(expected);
+ expect(result.timedOut).toBe(timedOut);
+ expect(onUsage).toHaveBeenCalledWith(expect.objectContaining({ billingType: expected, complete: false }));
+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ billingType: expected, complete: !timedOut }));
+ const runCall = runChildProcess.mock.calls.find(call => call[2].includes("run"))!;
+ expect((runCall[3] as { env: Record<string, string> }).env.OPENROUTER_API_KEY).toBe(forwarded ? "forwarded-api-key" : undefined);
+ },
+ );
+
it.each([false, true])("prepares the workspace, syncs OpenCode skills, and restores workspace changes for remote SSH execution (managed=%s)", async (managed) => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-remote-"));
cleanupDirs.push(rootDir);
diff --git a/packages/adapters/opencode-local/src/server/execute.test.ts b/packages/adapters/opencode-local/src/server/execute.test.ts
index a754b9d4b9..8307883e5f 100644
--- a/packages/adapters/opencode-local/src/server/execute.test.ts
+++ b/packages/adapters/opencode-local/src/server/execute.test.ts
@@ -177,7 +177,7 @@ describe("OpenCode local skill injection", () => {
}
});
- it("passes an OpenRouter key and complete model to OpenCode without logging the key", async () => {
+ it.each([false, true])("preserves API billing in streamed usage and final results without leaking keys (timedOut=%s)", async (timedOut) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-openrouter-"));
const workspace = path.join(root, "workspace");
const commandPath = path.join(root, "opencode");
@@ -187,15 +187,15 @@ describe("OpenCode local skill injection", () => {
await fs.writeFile(commandPath, "#!/bin/sh\nexit 0\n", "utf8");
await fs.chmod(commandPath, 0o755);
runProcessMock.mockReset();
- runProcessMock.mockResolvedValueOnce(probeResult({
- stdout: JSON.stringify({
- type: "text",
- sessionID: "session-openrouter",
- part: { text: "done" },
- }),
- }));
+ const usageLine = JSON.stringify({ type: "step_finish", sessionID: "session-openrouter",
+ part: { cost: 0.0025, tokens: { input: 10, output: 2, cache: { read: 100, write: 0 } } } });
+ runProcessMock.mockImplementationOnce(async (...args) => {
+ await args[4].onLog("stdout", `${usageLine}\n`);
+ return probeResult({ stdout: usageLine, timedOut, exitCode: timedOut ? 143 : 0, signal: timedOut ? "SIGTERM" : null });
+ });
const logs: string[] = [];
const metadata: unknown[] = [];
+ const onUsage = vi.fn();
try {
const result = await execute({
@@ -225,6 +225,7 @@ describe("OpenCode local skill injection", () => {
},
context: {},
authToken: "run-jwt-token",
+ onUsage,
onLog: async (_stream, chunk) => {
logs.push(chunk);
},
@@ -233,8 +234,13 @@ describe("OpenCode local skill injection", () => {
},
});
- expect(result.exitCode).toBe(0);
+ expect(result.exitCode).toBe(timedOut ? 143 : 0);
+ expect(result.usageComplete).toBe(!timedOut);
expect(result.model).toBe(model);
+ expect(result.billingType).toBe("metered_api");
+ expect(result.biller).toBe("openrouter");
+ expect(onUsage).toHaveBeenCalledWith(expect.objectContaining({ billingType: "metered_api", biller: "openrouter", model, complete: false }));
+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ billingType: "metered_api", biller: "openrouter", model, complete: !timedOut }));
const executionCall = runProcessMock.mock.calls.at(-1)!;
expect(executionCall[3]).toContain("--model");
expect(executionCall[3]).toContain(model);
diff --git a/packages/adapters/opencode-local/src/server/execute.ts b/packages/adapters/opencode-local/src/server/execute.ts
index bc643aef8e..e9cbac6461 100644
--- a/packages/adapters/opencode-local/src/server/execute.ts
+++ b/packages/adapters/opencode-local/src/server/execute.ts
@@ -61,6 +61,7 @@ import {
requireOpenCodeModelId,
} from "./models.js";
import { removeMaintainerOnlySkillSymlinks } from "@paperclipai/adapter-utils/server-utils";
+import { apiKeyBillingType } from "@paperclipai/adapter-utils/api-billing-type";
import { prepareOpenCodeRuntimeConfig, prepareManagedOpenCodeRemoteHomes } from "./runtime-config.js";
import { SANDBOX_INSTALL_COMMAND } from "../index.js";
import { resolveOpenCodeSkillsHome } from "./skills.js";
@@ -632,6 +633,8 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
return args;
};
+ // Remote targets receive only the prepared environment, never host keys.
+ const accountingEnv = executionTargetIsRemote ? preparedRuntimeConfig.env : runtimeEnv;
const runAttempt = async (resumeSessionId: string | null) => {
await hydrateFreshSessionHandoff(ctx, { resumedSession: Boolean(resumeSessionId) });
const { basePrompt, promptMetrics } = buildPrompt(Boolean(resumeSessionId));
@@ -662,7 +665,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const provider = parseModelProvider(model || null);
return { usage: parsed.usageReported ? parsed.usage : undefined, costUsd: parsed.costUsd,
costStatus: parsed.usageComplete || parsed.costUsd != null ? undefined : "unpriced",
- usageBasis: "per_run", provider, biller: resolveOpenCodeBiller(runtimeEnv, provider), billingType: "unknown", model, complete: false };
+ usageBasis: "per_run", provider, biller: resolveOpenCodeBiller(accountingEnv, provider), billingType: apiKeyBillingType(provider, accountingEnv), model, complete: false };
});
const proc = await runAdapterExecutionTargetProcess(runId, runtimeExecutionTarget, command, args, {
onProcessStopped: providerStop.beginInvocation(),
@@ -717,9 +720,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
usage: attempt.parsed.usageReported ? attempt.parsed.usage : undefined,
usageBasis: "per_run",
provider: parseModelProvider(model || null),
- biller: resolveOpenCodeBiller(runtimeEnv, parseModelProvider(model || null)),
+ biller: resolveOpenCodeBiller(accountingEnv, parseModelProvider(model || null)),
model,
- billingType: "unknown",
+ billingType: apiKeyBillingType(parseModelProvider(model || null), accountingEnv),
costUsd: attempt.parsed.costUsd,
costStatus: attempt.parsed.usageComplete || attempt.parsed.costUsd != null ? undefined : "unpriced",
// A provider or output-observation timeout can arrive before the
@@ -776,9 +779,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
sessionParams: resolvedSessionParams,
sessionDisplayId: resolvedSessionId,
provider: parseModelProvider(modelId),
- biller: resolveOpenCodeBiller(runtimeEnv, parseModelProvider(modelId)),
+ biller: resolveOpenCodeBiller(accountingEnv, parseModelProvider(modelId)),
model: modelId,
- billingType: "unknown",
+ billingType: apiKeyBillingType(parseModelProvider(modelId), accountingEnv),
costUsd: attempt.parsed.costUsd,
costStatus: attempt.parsed.usageComplete || attempt.parsed.costUsd != null ? undefined : "unpriced",
resultJson: {
diff --git a/packages/db/src/migrations/0333_normal_wild_pack.sql b/packages/db/src/migrations/0333_normal_wild_pack.sql
new file mode 100644
index 0000000000..0748f036eb
--- /dev/null
+++ b/packages/db/src/migrations/0333_normal_wild_pack.sql
@@ -0,0 +1,2 @@
+CREATE INDEX "cost_events_data_quality_idx" ON "cost_events" USING btree ("company_id","occurred_at" DESC NULLS LAST,"id") WHERE "cost_events"."billing_type" = 'unknown' or ("cost_events"."cost_status" = 'unpriced' and "cost_events"."billing_type" <> 'subscription_included');--> statement-breakpoint
+CREATE INDEX "heartbeat_runs_cost_data_quality_idx" ON "heartbeat_runs" USING btree ("company_id",coalesce("finished_at", "created_at") desc,"id") WHERE "heartbeat_runs"."cost_accounting_pending" = true and "heartbeat_runs"."status" in ('succeeded','failed','timed_out','cancelled','interrupted');
\ No newline at end of file
diff --git a/packages/db/src/migrations/meta/0322_snapshot.json b/packages/db/src/migrations/meta/0333_snapshot.json
similarity index 96%
rename from packages/db/src/migrations/meta/0322_snapshot.json
rename to packages/db/src/migrations/meta/0333_snapshot.json
index 7bae34318a..2a2b1f5f3f 100644
--- a/packages/db/src/migrations/meta/0322_snapshot.json
+++ b/packages/db/src/migrations/meta/0333_snapshot.json
@@ -1,6 +1,6 @@
{
- "id": "677c8c43-8767-4e2b-9cc4-35a76061e6df",
- "prevId": "3a76c99a-51c4-41d7-b7e2-12b55d8c7d08",
+ "id": "fb1a65b0-7eff-4e5a-a023-fecec51f938c",
+ "prevId": "8dadd21e-8c02-4ada-b99a-55ba133e7f70",
"version": "7",
"dialect": "postgresql",
"tables": {
@@ -416,6 +416,12 @@
"primaryKey": false,
"notNull": false
},
+ "fast_response_request_id": {
+ "name": "fast_response_request_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
"agent_id": {
"name": "agent_id",
"type": "uuid",
@@ -462,6 +468,27 @@
}
},
"indexes": {
+ "budget_reservations_fast_response_idx": {
+ "name": "budget_reservations_fast_response_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "fast_response_request_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
"budget_reservations_decision_idx": {
"name": "budget_reservations_decision_idx",
"columns": [
@@ -580,7 +607,7 @@
"checkConstraints": {
"budget_reservations_source_check": {
"name": "budget_reservations_source_check",
- "value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int = 1"
+ "value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int + (\"budget_reservations\".\"fast_response_request_id\" is not null)::int = 1"
},
"budget_reservations_state_check": {
"name": "budget_reservations_state_check",
@@ -3737,6 +3764,28 @@
"method": "btree",
"with": {}
},
+ "agent_wakeup_requests_question_response_history_idx": {
+ "name": "agent_wakeup_requests_question_response_history_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "idempotency_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'question-response:%'",
+ "concurrently": true,
+ "method": "btree",
+ "with": {}
+ },
"agent_wakeup_requests_connection_intent_delivery_idempotency_uq": {
"name": "agent_wakeup_requests_connection_intent_delivery_idempotency_uq",
"columns": [
@@ -10455,7 +10504,7 @@
},
"chat_endpoints_provider_check": {
"name": "chat_endpoints_provider_check",
- "value": "\"chat_endpoints\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')"
+ "value": "\"chat_endpoints\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'speko', 'agentmail', 'imessage-photon')"
},
"chat_endpoints_status_check": {
"name": "chat_endpoints_status_check",
@@ -10640,7 +10689,7 @@
"checkConstraints": {
"chat_external_principals_provider_check": {
"name": "chat_external_principals_provider_check",
- "value": "\"chat_external_principals\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')"
+ "value": "\"chat_external_principals\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'speko', 'agentmail', 'imessage-photon')"
},
"chat_external_principals_kind_check": {
"name": "chat_external_principals_kind_check",
@@ -11966,6 +12015,31 @@
"primaryKey": false,
"notNull": true
},
+ "owner_type": {
+ "name": "owner_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'personal'"
+ },
+ "owner_login": {
+ "name": "owner_login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "app_name": {
+ "name": "app_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "handoff": {
+ "name": "handoff",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
"status": {
"name": "status",
"type": "text",
@@ -12521,184 +12595,1246 @@
"primaryKey": false,
"notNull": true
},
- "publication_id": {
- "name": "publication_id",
- "type": "uuid",
- "primaryKey": false,
- "notNull": true
- },
+ "publication_id": {
+ "name": "publication_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "comment_id": {
+ "name": "comment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "attachment_id": {
+ "name": "attachment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "principal_id": {
+ "name": "principal_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "authorized_user_id": {
+ "name": "authorized_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "runtime_generation": {
+ "name": "runtime_generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_fingerprint": {
+ "name": "credential_fingerprint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "conversation_generation": {
+ "name": "conversation_generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_digest": {
+ "name": "source_digest",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "authority_digest": {
+ "name": "authority_digest",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tenant_id": {
+ "name": "tenant_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "bot_app_id": {
+ "name": "bot_app_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "aad_object_id": {
+ "name": "aad_object_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_conversation_id": {
+ "name": "provider_conversation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_user_id": {
+ "name": "provider_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sha256": {
+ "name": "sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "byte_size": {
+ "name": "byte_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "filename": {
+ "name": "filename",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token_sha256": {
+ "name": "token_sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "phase": {
+ "name": "phase",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'consent_pending'"
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "attempt_id": {
+ "name": "attempt_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempt_expires_at": {
+ "name": "attempt_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "consent_message_id": {
+ "name": "consent_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_info_message_id": {
+ "name": "file_info_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "response_activity_id": {
+ "name": "response_activity_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "response_digest": {
+ "name": "response_digest",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "private_state": {
+ "name": "private_state",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chat_teams_file_transfers_publication_uq": {
+ "name": "chat_teams_file_transfers_publication_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "publication_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_teams_file_transfers_token_uq": {
+ "name": "chat_teams_file_transfers_token_uq",
+ "columns": [
+ {
+ "expression": "endpoint_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "token_sha256",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_teams_file_transfers_work_idx": {
+ "name": "chat_teams_file_transfers_work_idx",
+ "columns": [
+ {
+ "expression": "phase",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "attempt_expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chat_teams_file_transfers_company_id_companies_id_fk": {
+ "name": "chat_teams_file_transfers_company_id_companies_id_fk",
+ "tableFrom": "chat_teams_file_transfers",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_teams_file_transfers_issue_id_issues_id_fk": {
+ "name": "chat_teams_file_transfers_issue_id_issues_id_fk",
+ "tableFrom": "chat_teams_file_transfers",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ },
+ "chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {
+ "name": "chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk",
+ "tableFrom": "chat_teams_file_transfers",
+ "tableTo": "chat_endpoints",
+ "columnsFrom": [
+ "company_id",
+ "endpoint_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk": {
+ "name": "chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk",
+ "tableFrom": "chat_teams_file_transfers",
+ "tableTo": "chat_publications",
+ "columnsFrom": [
+ "company_id",
+ "publication_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk": {
+ "name": "chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk",
+ "tableFrom": "chat_teams_file_transfers",
+ "tableTo": "chat_conversations",
+ "columnsFrom": [
+ "company_id",
+ "conversation_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk": {
+ "name": "chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk",
+ "tableFrom": "chat_teams_file_transfers",
+ "tableTo": "chat_external_principals",
+ "columnsFrom": [
+ "company_id",
+ "principal_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "chat_teams_file_transfers_phase_check": {
+ "name": "chat_teams_file_transfers_phase_check",
+ "value": "\"chat_teams_file_transfers\".\"phase\" in ('consent_pending','consent_sending','consent_unknown','awaiting_consent','upload_pending','uploading','upload_unknown','file_info_pending','file_info_sending','file_info_unknown','delivered','declined','expired','cancelled','conflict')"
+ },
+ "chat_teams_file_transfers_bounds_check": {
+ "name": "chat_teams_file_transfers_bounds_check",
+ "value": "\"chat_teams_file_transfers\".\"version\" > 0 and \"chat_teams_file_transfers\".\"runtime_generation\" >= 0 and \"chat_teams_file_transfers\".\"conversation_generation\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" < 62914560"
+ },
+ "chat_teams_file_transfers_hash_check": {
+ "name": "chat_teams_file_transfers_hash_check",
+ "value": "\"chat_teams_file_transfers\".\"source_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"authority_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"sha256\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"token_sha256\" ~ '^[a-f0-9]{64}$'"
+ },
+ "chat_teams_file_transfers_attempt_check": {
+ "name": "chat_teams_file_transfers_attempt_check",
+ "value": "(\"chat_teams_file_transfers\".\"attempt_id\" is null) = (\"chat_teams_file_transfers\".\"attempt_expires_at\" is null)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.chat_voice_callbacks": {
+ "name": "chat_voice_callbacks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "endpoint_id": {
+ "name": "endpoint_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "phone_number": {
+ "name": "phone_number",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chat_voice_callbacks_owner_uq": {
+ "name": "chat_voice_callbacks_owner_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "endpoint_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chat_voice_callbacks_endpoint_fk": {
+ "name": "chat_voice_callbacks_endpoint_fk",
+ "tableFrom": "chat_voice_callbacks",
+ "tableTo": "chat_endpoints",
+ "columnsFrom": [
+ "company_id",
+ "endpoint_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "chat_voice_callbacks_phone_check": {
+ "name": "chat_voice_callbacks_phone_check",
+ "value": "\"chat_voice_callbacks\".\"phone_number\" ~ '^\\+[1-9][0-9]{6,14}$'"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.chat_voice_inbound_calls": {
+ "name": "chat_voice_inbound_calls",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "endpoint_id": {
+ "name": "endpoint_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_session_id": {
+ "name": "provider_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'awaiting_approval'"
+ },
+ "approval_code": {
+ "name": "approval_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_fingerprint": {
+ "name": "credential_fingerprint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_token_hash": {
+ "name": "tool_token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "request_fingerprint": {
+ "name": "request_fingerprint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "approved_by_user_id": {
+ "name": "approved_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "caller_authority": {
+ "name": "caller_authority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "intake_issue_id": {
+ "name": "intake_issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requested_issue_id": {
+ "name": "requested_issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chat_voice_inbound_expiry_idx": {
+ "name": "chat_voice_inbound_expiry_idx",
+ "columns": [
+ {
+ "expression": "state",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chat_voice_inbound_endpoint_fk": {
+ "name": "chat_voice_inbound_endpoint_fk",
+ "tableFrom": "chat_voice_inbound_calls",
+ "tableTo": "chat_endpoints",
+ "columnsFrom": [
+ "company_id",
+ "endpoint_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_voice_inbound_session_fk": {
+ "name": "chat_voice_inbound_session_fk",
+ "tableFrom": "chat_voice_inbound_calls",
+ "tableTo": "chat_voice_sessions",
+ "columnsFrom": [
+ "company_id",
+ "session_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "chat_voice_inbound_intake_fk": {
+ "name": "chat_voice_inbound_intake_fk",
+ "tableFrom": "chat_voice_inbound_calls",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "company_id",
+ "intake_issue_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "chat_voice_inbound_requested_issue_fk": {
+ "name": "chat_voice_inbound_requested_issue_fk",
+ "tableFrom": "chat_voice_inbound_calls",
+ "tableTo": "issues",
+ "columnsFrom": [
+ "company_id",
+ "requested_issue_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "chat_voice_inbound_provider_uq": {
+ "name": "chat_voice_inbound_provider_uq",
+ "nullsNotDistinct": false,
+ "columns": [
+ "provider_session_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "chat_voice_inbound_state_check": {
+ "name": "chat_voice_inbound_state_check",
+ "value": "\"chat_voice_inbound_calls\".\"state\" in ('guest_intake', 'awaiting_approval', 'approving', 'approved', 'denied', 'expired', 'ended')"
+ },
+ "chat_voice_inbound_token_check": {
+ "name": "chat_voice_inbound_token_check",
+ "value": "\"chat_voice_inbound_calls\".\"tool_token_hash\" ~ '^[a-f0-9]{64}$'"
+ },
+ "chat_voice_inbound_code_check": {
+ "name": "chat_voice_inbound_code_check",
+ "value": "\"chat_voice_inbound_calls\".\"approval_code\" ~ '^[0-9]{6}$'"
+ },
+ "chat_voice_inbound_generation_check": {
+ "name": "chat_voice_inbound_generation_check",
+ "value": "\"chat_voice_inbound_calls\".\"generation\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.chat_voice_phone_lines": {
+ "name": "chat_voice_phone_lines",
+ "schema": "",
+ "columns": {
+ "endpoint_id": {
+ "name": "endpoint_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_number_id": {
+ "name": "provider_number_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "phone_number": {
+ "name": "phone_number",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "guest_intake": {
+ "name": "guest_intake",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "low_trust_environment_id": {
+ "name": "low_trust_environment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "chat_voice_phone_lines_low_trust_environment_id_environments_id_fk": {
+ "name": "chat_voice_phone_lines_low_trust_environment_id_environments_id_fk",
+ "tableFrom": "chat_voice_phone_lines",
+ "tableTo": "environments",
+ "columnsFrom": [
+ "low_trust_environment_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "chat_voice_phone_lines_endpoint_fk": {
+ "name": "chat_voice_phone_lines_endpoint_fk",
+ "tableFrom": "chat_voice_phone_lines",
+ "tableTo": "chat_endpoints",
+ "columnsFrom": [
+ "company_id",
+ "endpoint_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "chat_voice_phone_lines_number_uq": {
+ "name": "chat_voice_phone_lines_number_uq",
+ "nullsNotDistinct": false,
+ "columns": [
+ "provider_number_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "chat_voice_phone_lines_number_check": {
+ "name": "chat_voice_phone_lines_number_check",
+ "value": "\"chat_voice_phone_lines\".\"phone_number\" ~ '^\\+[1-9][0-9]{6,14}$'"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.chat_voice_reports": {
+ "name": "chat_voice_reports",
+ "schema": "",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "transcript": {
+ "name": "transcript",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "cost_micro_usd": {
+ "name": "cost_micro_usd",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "duration_seconds": {
+ "name": "duration_seconds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_updated_at": {
+ "name": "provider_updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "next_check_at": {
+ "name": "next_check_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chat_voice_reports_pending_idx": {
+ "name": "chat_voice_reports_pending_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "next_check_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chat_voice_reports_session_fk": {
+ "name": "chat_voice_reports_session_fk",
+ "tableFrom": "chat_voice_reports",
+ "tableTo": "chat_voice_sessions",
+ "columnsFrom": [
+ "company_id",
+ "session_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "chat_voice_reports_status_check": {
+ "name": "chat_voice_reports_status_check",
+ "value": "\"chat_voice_reports\".\"status\" in ('pending', 'available', 'unavailable')"
+ },
+ "chat_voice_reports_cost_check": {
+ "name": "chat_voice_reports_cost_check",
+ "value": "\"chat_voice_reports\".\"cost_micro_usd\" is null or \"chat_voice_reports\".\"cost_micro_usd\" ~ '^[0-9]{1,30}$'"
+ },
+ "chat_voice_reports_duration_check": {
+ "name": "chat_voice_reports_duration_check",
+ "value": "\"chat_voice_reports\".\"duration_seconds\" is null or \"chat_voice_reports\".\"duration_seconds\" >= 0"
+ },
+ "chat_voice_reports_attempts_check": {
+ "name": "chat_voice_reports_attempts_check",
+ "value": "\"chat_voice_reports\".\"attempts\" >= 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.chat_voice_replies": {
+ "name": "chat_voice_replies",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "publication_id": {
+ "name": "publication_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cursor": {
+ "name": "cursor",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "delivered_at": {
+ "name": "delivered_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spoken_at": {
+ "name": "spoken_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chat_voice_replies_publication_uq": {
+ "name": "chat_voice_replies_publication_uq",
+ "columns": [
+ {
+ "expression": "session_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "publication_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_voice_replies_cursor_uq": {
+ "name": "chat_voice_replies_cursor_uq",
+ "columns": [
+ {
+ "expression": "session_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "cursor",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chat_voice_replies_company_id_companies_id_fk": {
+ "name": "chat_voice_replies_company_id_companies_id_fk",
+ "tableFrom": "chat_voice_replies",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_voice_replies_session_fk": {
+ "name": "chat_voice_replies_session_fk",
+ "tableFrom": "chat_voice_replies",
+ "tableTo": "chat_voice_sessions",
+ "columnsFrom": [
+ "company_id",
+ "session_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "chat_voice_replies_publication_fk": {
+ "name": "chat_voice_replies_publication_fk",
+ "tableFrom": "chat_voice_replies",
+ "tableTo": "chat_publications",
+ "columnsFrom": [
+ "company_id",
+ "publication_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "chat_voice_replies_cursor_check": {
+ "name": "chat_voice_replies_cursor_check",
+ "value": "\"chat_voice_replies\".\"cursor\" > 0"
+ },
+ "chat_voice_replies_spoken_check": {
+ "name": "chat_voice_replies_spoken_check",
+ "value": "\"chat_voice_replies\".\"spoken_at\" is null or \"chat_voice_replies\".\"delivered_at\" is not null"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.chat_voice_sessions": {
+ "name": "chat_voice_sessions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "endpoint_id": {
+ "name": "endpoint_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
"issue_id": {
"name": "issue_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
- "comment_id": {
- "name": "comment_id",
- "type": "uuid",
- "primaryKey": false,
- "notNull": true
- },
- "attachment_id": {
- "name": "attachment_id",
- "type": "uuid",
- "primaryKey": false,
- "notNull": true
- },
- "principal_id": {
- "name": "principal_id",
+ "assigned_agent_id": {
+ "name": "assigned_agent_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
- "authorized_user_id": {
- "name": "authorized_user_id",
+ "caller_id": {
+ "name": "caller_id",
"type": "text",
"primaryKey": false,
- "notNull": false
- },
- "runtime_generation": {
- "name": "runtime_generation",
- "type": "integer",
- "primaryKey": false,
"notNull": true
},
- "credential_fingerprint": {
- "name": "credential_fingerprint",
+ "caller_authority": {
+ "name": "caller_authority",
"type": "text",
"primaryKey": false,
"notNull": true
},
- "conversation_generation": {
- "name": "conversation_generation",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "source_digest": {
- "name": "source_digest",
+ "approved_by_user_id": {
+ "name": "approved_by_user_id",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": false
},
- "authority_digest": {
- "name": "authority_digest",
+ "mode": {
+ "name": "mode",
"type": "text",
"primaryKey": false,
"notNull": true
},
- "tenant_id": {
- "name": "tenant_id",
- "type": "uuid",
- "primaryKey": false,
- "notNull": true
- },
- "bot_app_id": {
- "name": "bot_app_id",
- "type": "uuid",
+ "state": {
+ "name": "state",
+ "type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": true,
+ "default": "'reserved'"
},
- "aad_object_id": {
- "name": "aad_object_id",
- "type": "uuid",
+ "generation": {
+ "name": "generation",
+ "type": "integer",
"primaryKey": false,
"notNull": true
},
- "provider_conversation_id": {
- "name": "provider_conversation_id",
+ "credential_fingerprint": {
+ "name": "credential_fingerprint",
"type": "text",
"primaryKey": false,
"notNull": true
},
- "provider_user_id": {
- "name": "provider_user_id",
+ "provider_session_id": {
+ "name": "provider_session_id",
"type": "text",
"primaryKey": false,
- "notNull": true
+ "notNull": false
},
- "sha256": {
- "name": "sha256",
+ "tool_token_hash": {
+ "name": "tool_token_hash",
"type": "text",
"primaryKey": false,
"notNull": true
},
- "byte_size": {
- "name": "byte_size",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "filename": {
- "name": "filename",
+ "idempotency_key": {
+ "name": "idempotency_key",
"type": "text",
"primaryKey": false,
"notNull": true
},
- "token_sha256": {
- "name": "token_sha256",
+ "request_fingerprint": {
+ "name": "request_fingerprint",
"type": "text",
"primaryKey": false,
"notNull": true
},
- "phase": {
- "name": "phase",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "default": "'consent_pending'"
- },
- "version": {
- "name": "version",
+ "reply_cursor": {
+ "name": "reply_cursor",
"type": "integer",
"primaryKey": false,
"notNull": true,
- "default": 1
- },
- "attempt_id": {
- "name": "attempt_id",
- "type": "uuid",
- "primaryKey": false,
- "notNull": false
- },
- "attempt_expires_at": {
- "name": "attempt_expires_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": false
- },
- "consent_message_id": {
- "name": "consent_message_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "file_info_message_id": {
- "name": "file_info_message_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "response_activity_id": {
- "name": "response_activity_id",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "response_digest": {
- "name": "response_digest",
- "type": "text",
- "primaryKey": false,
- "notNull": false
- },
- "private_state": {
- "name": "private_state",
- "type": "jsonb",
- "primaryKey": false,
- "notNull": true
+ "default": 0
},
- "reason": {
- "name": "reason",
+ "error_code": {
+ "name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false
@@ -12709,6 +13845,12 @@
"primaryKey": false,
"notNull": true
},
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
@@ -12725,8 +13867,23 @@
}
},
"indexes": {
- "chat_teams_file_transfers_publication_uq": {
- "name": "chat_teams_file_transfers_publication_uq",
+ "chat_voice_sessions_provider_uq": {
+ "name": "chat_voice_sessions_provider_uq",
+ "columns": [
+ {
+ "expression": "provider_session_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_voice_sessions_request_uq": {
+ "name": "chat_voice_sessions_request_uq",
"columns": [
{
"expression": "company_id",
@@ -12735,7 +13892,13 @@
"nulls": "last"
},
{
- "expression": "publication_id",
+ "expression": "caller_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "idempotency_key",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -12746,38 +13909,39 @@
"method": "btree",
"with": {}
},
- "chat_teams_file_transfers_token_uq": {
- "name": "chat_teams_file_transfers_token_uq",
+ "chat_voice_sessions_live_caller_task_uq": {
+ "name": "chat_voice_sessions_live_caller_task_uq",
"columns": [
{
- "expression": "endpoint_id",
+ "expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
- "expression": "token_sha256",
+ "expression": "caller_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "issue_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
+ "where": "\"chat_voice_sessions\".\"state\" not in ('ended', 'failed', 'expired')",
"concurrently": false,
"method": "btree",
"with": {}
},
- "chat_teams_file_transfers_work_idx": {
- "name": "chat_teams_file_transfers_work_idx",
+ "chat_voice_sessions_expiry_idx": {
+ "name": "chat_voice_sessions_expiry_idx",
"columns": [
{
- "expression": "phase",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "attempt_expires_at",
+ "expression": "state",
"isExpression": false,
"asc": true,
"nulls": "last"
@@ -12796,9 +13960,9 @@
}
},
"foreignKeys": {
- "chat_teams_file_transfers_company_id_companies_id_fk": {
- "name": "chat_teams_file_transfers_company_id_companies_id_fk",
- "tableFrom": "chat_teams_file_transfers",
+ "chat_voice_sessions_company_id_companies_id_fk": {
+ "name": "chat_voice_sessions_company_id_companies_id_fk",
+ "tableFrom": "chat_voice_sessions",
"tableTo": "companies",
"columnsFrom": [
"company_id"
@@ -12809,71 +13973,254 @@
"onDelete": "cascade",
"onUpdate": "no action"
},
- "chat_teams_file_transfers_issue_id_issues_id_fk": {
- "name": "chat_teams_file_transfers_issue_id_issues_id_fk",
- "tableFrom": "chat_teams_file_transfers",
- "tableTo": "issues",
+ "chat_voice_sessions_endpoint_fk": {
+ "name": "chat_voice_sessions_endpoint_fk",
+ "tableFrom": "chat_voice_sessions",
+ "tableTo": "chat_endpoints",
"columnsFrom": [
- "issue_id"
+ "company_id",
+ "endpoint_id"
],
"columnsTo": [
+ "company_id",
"id"
],
- "onDelete": "restrict",
+ "onDelete": "no action",
"onUpdate": "no action"
},
- "chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {
- "name": "chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk",
- "tableFrom": "chat_teams_file_transfers",
- "tableTo": "chat_endpoints",
+ "chat_voice_sessions_conversation_fk": {
+ "name": "chat_voice_sessions_conversation_fk",
+ "tableFrom": "chat_voice_sessions",
+ "tableTo": "chat_conversations",
"columnsFrom": [
"company_id",
- "endpoint_id"
+ "conversation_id"
],
"columnsTo": [
"company_id",
"id"
],
- "onDelete": "cascade",
+ "onDelete": "no action",
"onUpdate": "no action"
},
- "chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk": {
- "name": "chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk",
- "tableFrom": "chat_teams_file_transfers",
- "tableTo": "chat_publications",
+ "chat_voice_sessions_issue_fk": {
+ "name": "chat_voice_sessions_issue_fk",
+ "tableFrom": "chat_voice_sessions",
+ "tableTo": "issues",
"columnsFrom": [
"company_id",
- "publication_id"
+ "issue_id"
],
"columnsTo": [
"company_id",
"id"
],
- "onDelete": "cascade",
+ "onDelete": "no action",
"onUpdate": "no action"
},
- "chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk": {
- "name": "chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk",
- "tableFrom": "chat_teams_file_transfers",
- "tableTo": "chat_conversations",
+ "chat_voice_sessions_agent_fk": {
+ "name": "chat_voice_sessions_agent_fk",
+ "tableFrom": "chat_voice_sessions",
+ "tableTo": "agents",
"columnsFrom": [
"company_id",
- "conversation_id"
+ "assigned_agent_id"
],
"columnsTo": [
"company_id",
"id"
],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "chat_voice_sessions_company_id_uq": {
+ "name": "chat_voice_sessions_company_id_uq",
+ "nullsNotDistinct": false,
+ "columns": [
+ "company_id",
+ "id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "chat_voice_sessions_state_check": {
+ "name": "chat_voice_sessions_state_check",
+ "value": "\"chat_voice_sessions\".\"state\" in ('reserved', 'creating', 'creation_unknown', 'connecting', 'active', 'awaiting_approval', 'ending', 'ended', 'failed', 'expired')"
+ },
+ "chat_voice_sessions_mode_check": {
+ "name": "chat_voice_sessions_mode_check",
+ "value": "\"chat_voice_sessions\".\"mode\" in ('browser', 'inbound_phone', 'outbound_phone')"
+ },
+ "chat_voice_sessions_authority_check": {
+ "name": "chat_voice_sessions_authority_check",
+ "value": "\"chat_voice_sessions\".\"caller_authority\" in ('member', 'instance_admin', 'local_board', 'guest_intake', 'pending_approval')"
+ },
+ "chat_voice_sessions_counters_check": {
+ "name": "chat_voice_sessions_counters_check",
+ "value": "\"chat_voice_sessions\".\"generation\" >= 1 and \"chat_voice_sessions\".\"reply_cursor\" >= 0"
+ },
+ "chat_voice_sessions_token_check": {
+ "name": "chat_voice_sessions_token_check",
+ "value": "\"chat_voice_sessions\".\"tool_token_hash\" ~ '^[a-f0-9]{64}$'"
+ },
+ "chat_voice_sessions_expiry_check": {
+ "name": "chat_voice_sessions_expiry_check",
+ "value": "\"chat_voice_sessions\".\"expires_at\" > \"chat_voice_sessions\".\"created_at\""
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.chat_voice_tool_calls": {
+ "name": "chat_voice_tool_calls",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_tool_call_id": {
+ "name": "provider_tool_call_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "webhook_id": {
+ "name": "webhook_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "fingerprint": {
+ "name": "fingerprint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool": {
+ "name": "tool",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "delivery_id": {
+ "name": "delivery_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "response": {
+ "name": "response",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "chat_voice_tool_calls_tool_uq": {
+ "name": "chat_voice_tool_calls_tool_uq",
+ "columns": [
+ {
+ "expression": "session_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "provider_tool_call_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chat_voice_tool_calls_webhook_uq": {
+ "name": "chat_voice_tool_calls_webhook_uq",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "webhook_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "chat_voice_tool_calls_company_id_companies_id_fk": {
+ "name": "chat_voice_tool_calls_company_id_companies_id_fk",
+ "tableFrom": "chat_voice_tool_calls",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
"onDelete": "cascade",
"onUpdate": "no action"
},
- "chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk": {
- "name": "chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk",
- "tableFrom": "chat_teams_file_transfers",
- "tableTo": "chat_external_principals",
+ "chat_voice_tool_calls_session_fk": {
+ "name": "chat_voice_tool_calls_session_fk",
+ "tableFrom": "chat_voice_tool_calls",
+ "tableTo": "chat_voice_sessions",
"columnsFrom": [
"company_id",
- "principal_id"
+ "session_id"
+ ],
+ "columnsTo": [
+ "company_id",
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "chat_voice_tool_calls_delivery_fk": {
+ "name": "chat_voice_tool_calls_delivery_fk",
+ "tableFrom": "chat_voice_tool_calls",
+ "tableTo": "chat_deliveries",
+ "columnsFrom": [
+ "company_id",
+ "delivery_id"
],
"columnsTo": [
"company_id",
@@ -12887,21 +14234,9 @@
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {
- "chat_teams_file_transfers_phase_check": {
- "name": "chat_teams_file_transfers_phase_check",
- "value": "\"chat_teams_file_transfers\".\"phase\" in ('consent_pending','consent_sending','consent_unknown','awaiting_consent','upload_pending','uploading','upload_unknown','file_info_pending','file_info_sending','file_info_unknown','delivered','declined','expired','cancelled','conflict')"
- },
- "chat_teams_file_transfers_bounds_check": {
- "name": "chat_teams_file_transfers_bounds_check",
- "value": "\"chat_teams_file_transfers\".\"version\" > 0 and \"chat_teams_file_transfers\".\"runtime_generation\" >= 0 and \"chat_teams_file_transfers\".\"conversation_generation\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" < 62914560"
- },
- "chat_teams_file_transfers_hash_check": {
- "name": "chat_teams_file_transfers_hash_check",
- "value": "\"chat_teams_file_transfers\".\"source_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"authority_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"sha256\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"token_sha256\" ~ '^[a-f0-9]{64}$'"
- },
- "chat_teams_file_transfers_attempt_check": {
- "name": "chat_teams_file_transfers_attempt_check",
- "value": "(\"chat_teams_file_transfers\".\"attempt_id\" is null) = (\"chat_teams_file_transfers\".\"attempt_expires_at\" is null)"
+ "chat_voice_tool_calls_tool_check": {
+ "name": "chat_voice_tool_calls_tool_check",
+ "value": "\"chat_voice_tool_calls\".\"tool\" in ('submit_request', 'get_updates', 'answer_question')"
}
},
"isRLSEnabled": false
@@ -18290,6 +19625,34 @@
"method": "btree",
"with": {}
},
+ "cost_events_data_quality_idx": {
+ "name": "cost_events_data_quality_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurred_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"cost_events\".\"billing_type\" = 'unknown' or (\"cost_events\".\"cost_status\" = 'unpriced' and \"cost_events\".\"billing_type\" <> 'subscription_included')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
"cost_events_company_occurred_idx": {
"name": "cost_events_company_occurred_idx",
"columns": [
@@ -18540,7 +19903,7 @@
"checkConstraints": {
"cost_events_usage_kind_check": {
"name": "cost_events_usage_kind_check",
- "value": "\"cost_events\".\"usage_kind\" = 'decision' or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)"
+ "value": "\"cost_events\".\"usage_kind\" in ('decision', 'fast_response') or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)"
},
"cost_events_nonnegative_amounts": {
"name": "cost_events_nonnegative_amounts",
@@ -26205,6 +27568,378 @@
"checkConstraints": {},
"isRLSEnabled": false
},
+ "public.company_fast_responses": {
+ "name": "company_fast_responses",
+ "schema": "",
+ "columns": {
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "connection_id": {
+ "name": "connection_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "grant_id": {
+ "name": "grant_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "allow_sponsored": {
+ "name": "allow_sponsored",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "company_fast_responses_company_id_companies_id_fk": {
+ "name": "company_fast_responses_company_id_companies_id_fk",
+ "tableFrom": "company_fast_responses",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "company_fast_responses_configured": {
+ "name": "company_fast_responses_configured",
+ "value": "(\"company_fast_responses\".\"connection_id\" is null) = (\"company_fast_responses\".\"grant_id\" is null) and (not \"company_fast_responses\".\"enabled\" or (\"company_fast_responses\".\"connection_id\" is not null and \"company_fast_responses\".\"model\" is not null))"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.fast_response_requests": {
+ "name": "fast_response_requests",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "company_id": {
+ "name": "company_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_key": {
+ "name": "source_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_comment_id": {
+ "name": "source_comment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "responsible_user_id": {
+ "name": "responsible_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sponsored": {
+ "name": "sponsored",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "endpoint_id": {
+ "name": "endpoint_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "delivery_id": {
+ "name": "delivery_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_generation": {
+ "name": "session_generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "publication_status": {
+ "name": "publication_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "connection_id": {
+ "name": "connection_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "grant_id": {
+ "name": "grant_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_request_id": {
+ "name": "provider_request_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost_event_id": {
+ "name": "cost_event_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_code": {
+ "name": "error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "comment_id": {
+ "name": "comment_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "fast_response_requests_source_idx": {
+ "name": "fast_response_requests_source_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "source_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "fast_response_requests_history_idx": {
+ "name": "fast_response_requests_history_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "accepted_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "fast_response_requests_work_idx": {
+ "name": "fast_response_requests_work_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"fast_response_requests\".\"status\" in ('pending', 'running')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "fast_response_requests_company_id_companies_id_fk": {
+ "name": "fast_response_requests_company_id_companies_id_fk",
+ "tableFrom": "fast_response_requests",
+ "tableTo": "companies",
+ "columnsFrom": [
+ "company_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "fast_response_requests_cost_event_id_cost_events_id_fk": {
+ "name": "fast_response_requests_cost_event_id_cost_events_id_fk",
+ "tableFrom": "fast_response_requests",
+ "tableTo": "cost_events",
+ "columnsFrom": [
+ "cost_event_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "fast_response_requests_status_check": {
+ "name": "fast_response_requests_status_check",
+ "value": "\"fast_response_requests\".\"status\" in ('pending', 'running', 'succeeded', 'failed', 'unknown', 'skipped')"
+ }
+ },
+ "isRLSEnabled": false
+ },
"public.feedback_exports": {
"name": "feedback_exports",
"schema": "",
@@ -28652,6 +30387,34 @@
"method": "btree",
"with": {}
},
+ "heartbeat_runs_cost_data_quality_idx": {
+ "name": "heartbeat_runs_cost_data_quality_idx",
+ "columns": [
+ {
+ "expression": "company_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "coalesce(\"finished_at\", \"created_at\") desc",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"heartbeat_runs\".\"cost_accounting_pending\" = true and \"heartbeat_runs\".\"status\" in ('succeeded','failed','timed_out','cancelled','interrupted')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
"heartbeat_runs_execution_status_delivery_idx": {
"name": "heartbeat_runs_execution_status_delivery_idx",
"columns": [
@@ -31106,6 +32869,19 @@
"primaryKey": false,
"notNull": false
},
+ "origin": {
+ "name": "origin",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'comment'"
+ },
+ "fast_response_request_id": {
+ "name": "fast_response_request_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
"body": {
"name": "body",
"type": "text",
@@ -49927,7 +51703,7 @@
},
"tool_connections_transport_check": {
"name": "tool_connections_transport_check",
- "value": "\"tool_connections\".\"transport\" in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'runtime_auth')"
+ "value": "\"tool_connections\".\"transport\" in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'voice', 'runtime_auth')"
},
"tool_connections_purpose_check": {
"name": "tool_connections_purpose_check",
@@ -49935,7 +51711,7 @@
},
"tool_connections_channel_transport_check": {
"name": "tool_connections_channel_transport_check",
- "value": "(\n (\"tool_connections\".\"connection_purpose\" = 'tool' and \"tool_connections\".\"transport\" not in ('chat_sdk', 'runtime_auth'))\n or\n (\"tool_connections\".\"connection_purpose\" = 'channel' and (\"tool_connections\".\"transport\" = 'chat_sdk' or (\"tool_connections\".\"transport\" = 'rest_api' and \"tool_connections\".\"config\"->>'provider' = 'agentmail')))\n or\n (\"tool_connections\".\"connection_purpose\" = 'ai' and \"tool_connections\".\"transport\" = 'runtime_auth')\n )"
+ "value": "(\n (\"tool_connections\".\"connection_purpose\" = 'tool' and \"tool_connections\".\"transport\" not in ('chat_sdk', 'voice', 'runtime_auth'))\n or\n (\"tool_connections\".\"connection_purpose\" = 'channel' and (\"tool_connections\".\"transport\" in ('chat_sdk', 'voice') or (\"tool_connections\".\"transport\" = 'rest_api' and \"tool_connections\".\"config\"->>'provider' = 'agentmail')))\n or\n (\"tool_connections\".\"connection_purpose\" = 'ai' and \"tool_connections\".\"transport\" = 'runtime_auth')\n )"
},
"tool_connections_auth_kind_check": {
"name": "tool_connections_auth_kind_check",
diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json
index 412ba94d17..ddd1f7d814 100644
--- a/packages/db/src/migrations/meta/_journal.json
+++ b/packages/db/src/migrations/meta/_journal.json
@@ -2318,6 +2318,13 @@
"when": 1791693159075,
"tag": "0332_little_night_nurse",
"breakpoints": true
+ },
+ {
+ "idx": 333,
+ "version": "7",
+ "when": 1791781882729,
+ "tag": "0333_normal_wild_pack",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema/cost_events.ts b/packages/db/src/schema/cost_events.ts
index f6639b6c30..a6d6e784f1 100644
--- a/packages/db/src/schema/cost_events.ts
+++ b/packages/db/src/schema/cost_events.ts
@@ -46,6 +46,8 @@ export const costEvents = pgTable(
nonnegativeAmounts: check("cost_events_nonnegative_amounts", sql`${table.costCents} >= 0 and ${table.inputTokens} >= 0 and ${table.cachedInputTokens} >= 0 and ${table.outputTokens} >= 0`),
companyProjectOccurredIdx: index("cost_events_company_project_occurred_idx").on(table.companyId, table.projectId, table.occurredAt),
unpricedIdx: index("cost_events_unpriced_idx").on(table.companyId, table.occurredAt, table.id).where(sql`${table.costStatus} = 'unpriced' and ${table.billingType} <> 'subscription_included'`),
+ dataQualityIdx: index("cost_events_data_quality_idx").on(table.companyId, table.occurredAt.desc(), table.id)
+ .where(sql`${table.billingType} = 'unknown' or (${table.costStatus} = 'unpriced' and ${table.billingType} <> 'subscription_included')`),
companyOccurredIdx: index("cost_events_company_occurred_idx").on(table.companyId, table.occurredAt),
companySubscriptionOccurredIdx: index("cost_events_company_subscription_occurred_idx").on(table.companyId, table.subscriptionId, table.occurredAt),
companyAgentOccurredIdx: index("cost_events_company_agent_occurred_idx").on(
diff --git a/packages/db/src/schema/heartbeat_runs.ts b/packages/db/src/schema/heartbeat_runs.ts
index 6b7ac23f49..8d0ac21e6e 100644
--- a/packages/db/src/schema/heartbeat_runs.ts
+++ b/packages/db/src/schema/heartbeat_runs.ts
@@ -117,6 +117,9 @@ export const heartbeatRuns = pgTable(
OR ${table.scopeKind} = 'issue'`,
),
costAccountingPendingIdx: index("heartbeat_runs_cost_accounting_pending_idx").on(table.updatedAt, table.id).where(sql`${table.costAccountingPending} = true`),
+ costDataQualityIdx: index("heartbeat_runs_cost_data_quality_idx")
+ .on(table.companyId, sql`coalesce(${table.finishedAt}, ${table.createdAt}) desc`, table.id)
+ .where(sql`${table.costAccountingPending} = true and ${table.status} in ('succeeded','failed','timed_out','cancelled','interrupted')`),
executionStatusDeliveryIdx: index("heartbeat_runs_execution_status_delivery_idx")
.on(table.executionStatusDeliveryId).where(sql`${table.executionStatusDeliveryId} is not null`),
executionControlDeadlineIdx: index("heartbeat_runs_execution_control_deadline_idx")
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 2ffdbc39e8..b41b34b074 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1268,6 +1268,9 @@ export type {
BudgetIncidentResolutionInput,
CostEvent,
CostSummary,
+ CostDataQualityItem,
+ CostDataQualityReport,
+ CostDataQualityReason,
IssueCostSummary,
CostByAgent,
CostByUser,
diff --git a/packages/shared/src/types/cost.ts b/packages/shared/src/types/cost.ts
index 6c54bcad26..b0fc8ee386 100644
--- a/packages/shared/src/types/cost.ts
+++ b/packages/shared/src/types/cost.ts
@@ -33,6 +33,8 @@ export interface CostSummary {
pendingRunCount: number;
unpricedEventCount: number;
estimatedEventCount?: number;
+ /** Receipts whose API/subscription billing identity was not established. */
+ unknownBillingEventCount?: number;
pricingComplete: boolean;
companyId: string;
spendCents: number;
@@ -41,6 +43,30 @@ export interface CostSummary {
utilizationPercent: number;
}
+export type CostDataQualityReason = "unknown_billing" | "missing_model" | "missing_price"
+ | "waiting_for_receipt" | "receipt_unavailable" | "retryable";
+
+export interface CostDataQualityItem {
+ id: string;
+ runId: string | null;
+ agentId: string | null;
+ agentName: string | null;
+ agentAppearance?: AgentAppearance | null;
+ occurredAt: string;
+ provider: string | null;
+ model: string | null;
+ reason: CostDataQualityReason;
+}
+
+export interface CostDataQualityReport {
+ canRetry: boolean;
+ /** Each category is bounded independently so one cannot hide another. */
+ events: CostDataQualityItem[];
+ runs: CostDataQualityItem[];
+ hasMoreEvents: boolean;
+ hasMoreRuns: boolean;
+}
+
export interface IssueCostSummary {
issueId: string;
issueCount: number;
@@ -110,6 +136,9 @@ export interface CostByProviderModel {
model: string;
costCents: number;
costCentsExact?: string;
+ eventCount?: number;
+ estimatedEventCount?: number;
+ unpricedEventCount?: number;
inputTokens: number;
cachedInputTokens: number;
outputTokens: number;
@@ -124,6 +153,9 @@ export interface CostByBiller {
biller: string;
costCents: number;
costCentsExact?: string;
+ eventCount?: number;
+ estimatedEventCount?: number;
+ unpricedEventCount?: number;
inputTokens: number;
cachedInputTokens: number;
outputTokens: number;
diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts
index be561795fd..754fc0252c 100644
--- a/packages/shared/src/types/index.ts
+++ b/packages/shared/src/types/index.ts
@@ -900,7 +900,7 @@ export type {
RoutineExecutionIssueOrigin,
RoutineListItem,
} from "./routine.js";
-export type { CostEvent, CostSummary, IssueCostSummary, CostByUser, CostByUserReport, CostByAgent, CostByProviderModel, CostByBiller, CostByAgentModel, CostWindowSpendRow, CostByProject } from "./cost.js";
+export type { CostEvent, CostSummary, CostDataQualityItem, CostDataQualityReport, CostDataQualityReason, IssueCostSummary, CostByUser, CostByUserReport, CostByAgent, CostByProviderModel, CostByBiller, CostByAgentModel, CostWindowSpendRow, CostByProject } from "./cost.js";
export type { FinanceEvent, FinanceSummary, FinanceByBiller, FinanceByKind } from "./finance.js";
export type {
AgentWakeupResponse,
diff --git a/server/src/__tests__/cost-data-quality-routes.test.ts b/server/src/__tests__/cost-data-quality-routes.test.ts
new file mode 100644
index 0000000000..5099cb8a24
--- /dev/null
+++ b/server/src/__tests__/cost-data-quality-routes.test.ts
@@ -0,0 +1,64 @@
+import express from "express";
+import request from "supertest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Db } from "@paperclipai/db";
+import { costRoutes } from "../routes/costs.js";
+import { errorHandler } from "../middleware/error-handler.js";
+
+const mocks = vi.hoisted(() => ({ report: vi.fn(), retry: vi.fn(), decide: vi.fn(), canManage: vi.fn() }));
+vi.mock("../services/cost-data-quality.js", () => ({ costDataQualityReport: mocks.report }));
+vi.mock("../routes/ai-connections.js", () => ({ canManageAiConnections: mocks.canManage }));
+vi.mock("../services/index.js", () => ({
+ heartbeatService: () => ({}), costService: () => ({}), financeService: () => ({}), budgetService: () => ({}),
+ companyService: () => ({}), agentService: () => ({}), issueService: () => ({}), accessService: () => ({ decide: mocks.decide }),
+}));
+vi.mock("../services/accounting-integrity.js", () => ({ accountingIntegrityService: () => ({ retry: mocks.retry }) }));
+vi.mock("../services/billing-reconciliation.js", () => ({ billingReconciliationService: () => ({}) }));
+const companyId = "11111111-1111-4111-8111-111111111111";
+const runId = "22222222-2222-4222-8222-222222222222";
+const path = `/api/companies/${companyId}/costs`;
+function app(type: "board" | "agent" = "board", role = "member") {
+ const instance = express(); instance.use(express.json());
+ instance.use((req, _res, next) => {
+ req.actor = type === "board" ? { type: "board", source: "session", userId: "alice", companyIds: [companyId], memberships: [{ companyId, status: "active", membershipRole: role }] } as typeof req.actor : { type: "agent", agentId: "agent", companyId } as typeof req.actor;
+ next();
+ });
+ instance.use("/api", costRoutes({} as Db)); instance.use(errorHandler); return instance;
+}
+beforeEach(() => {
+ vi.clearAllMocks(); mocks.decide.mockResolvedValue({ allowed: true });
+ mocks.report.mockResolvedValue({ events: [], runs: [] }); mocks.retry.mockResolvedValue({ accounted: false });
+});
+describe("cost details and accounting retry authorization", () => {
+ it("allows cost readers, makes viewers read-only, and does not query connection-management permissions", async () => {
+ expect((await request(app()).get(`${path}/data-quality?period=all`)).status).toBe(200);
+ expect(mocks.report).toHaveBeenLastCalledWith(expect.anything(), companyId, true, { allTime: true });
+ expect((await request(app("board", "viewer")).get(`${path}/data-quality`)).status).toBe(200);
+ expect(mocks.report).toHaveBeenLastCalledWith(expect.anything(), companyId, false, undefined);
+ expect(mocks.canManage).not.toHaveBeenCalled();
+ });
+ it("rejects agents, foreign companies, invalid date bounds and denied cost visibility before reading details", async () => {
+ expect((await request(app("agent")).get(`${path}/data-quality`)).status).toBe(403);
+ expect((await request(app()).get("/api/companies/other/costs/data-quality")).status).toBe(403);
+ for (const query of ["from=invalid", "from=2026-10-09&to=2026-10-01", "period=all&from=2026-10-01"]) {
+ expect((await request(app()).get(`${path}/data-quality?${query}`)).status).toBe(400);
+ }
+ mocks.decide.mockResolvedValue({ allowed: false });
+ expect((await request(app()).get(`${path}/data-quality`)).status).toBe(403);
+ expect(mocks.report).not.toHaveBeenCalled();
+ });
+ it("passes authorized retry to the existing audited accounting service without executing agents", async () => {
+ const response = await request(app()).post(`${path}/retry-accounting`).send({ runId });
+ expect(response.status).toBe(200); expect(response.body).toEqual({ accounted: false });
+ expect(mocks.retry).toHaveBeenCalledExactlyOnceWith(companyId, runId, "alice");
+ });
+ it("rejects viewers, agents, cross-company requests, malformed IDs and denied cost visibility before retrying", async () => {
+ expect((await request(app("board", "viewer")).post(`${path}/retry-accounting`).send({ runId })).status).toBe(403);
+ expect((await request(app("agent")).post(`${path}/retry-accounting`).send({ runId })).status).toBe(403);
+ expect((await request(app()).post("/api/companies/other/costs/retry-accounting").send({ runId })).status).toBe(403);
+ expect((await request(app()).post(`${path}/retry-accounting`).send({ runId: "bad" })).status).toBe(400);
+ mocks.decide.mockResolvedValue({ allowed: false });
+ expect((await request(app()).post(`${path}/retry-accounting`).send({ runId })).status).toBe(403);
+ expect(mocks.retry).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/__tests__/cost-data-quality.test.ts b/server/src/__tests__/cost-data-quality.test.ts
new file mode 100644
index 0000000000..376b05ad0b
--- /dev/null
+++ b/server/src/__tests__/cost-data-quality.test.ts
@@ -0,0 +1,216 @@
+import { randomUUID } from "node:crypto";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { eq, sql } from "drizzle-orm";
+import { appearanceForPalette } from "@paperclipai/shared";
+import { agents, companies, costEvents, createDb, heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db";
+import { costDataQualityReport, RECEIPT_WAIT_MS } from "../services/cost-data-quality.js";
+import { accountingIntegrityService } from "../services/accounting-integrity.js";
+import { costService } from "../services/costs.js";
+import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+
+const now = new Date("2026-10-09T13:00:00Z");
+describe("actionable cost data quality", () => {
+ let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
+ let db: ReturnType<typeof createDb>;
+ beforeAll(async () => {
+ database = await startEmbeddedPostgresTestDatabase("paperclip-cost-quality-");
+ db = createDb(database.connectionString);
+ }, 90_000);
+ afterAll(async () => { await database?.cleanup(); });
+
+ async function company() {
+ const companyId = randomUUID(), agentId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Costs", issuePrefix: `Q${companyId.slice(0, 6)}` });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Codie", role: "engineer", adapterType: "codex_local" });
+ return { companyId, agentId };
+ }
+ async function event(owner: Awaited<ReturnType<typeof company>>, overrides: Partial<typeof costEvents.$inferInsert> = {}) {
+ const [row] = await db.insert(costEvents).values({ ...owner, provider: "openai", model: "gpt-6-astra", billingType: "metered_api", costStatus: "unpriced", costCents: 0, occurredAt: now, ...overrides }).returning();
+ return row;
+ }
+ async function run(owner: Awaited<ReturnType<typeof company>>, overrides: Partial<typeof heartbeatRuns.$inferInsert> = {}) {
+ const [row] = await db.insert(heartbeatRuns).values({ ...owner, status: "failed", costAccountingPending: true, createdAt: now, finishedAt: now, usageJson: { accountingReceiptReady: false }, ...overrides }).returning();
+ return row;
+ }
+
+ it("distinguishes billing, model and price gaps, excluding normal subscription/credit/fixed usage", async () => {
+ const owner = await company();
+ const unknown = await event(owner, { billingType: "unknown", costStatus: "reported", costCents: 21 });
+ const missingModel = await event(owner, { model: "unknown" });
+ const missingPrice = await event(owner);
+ await event(owner, { billingType: "subscription_included" });
+ await event(owner, { billingType: "credits", costStatus: "reported" });
+ await event(owner, { billingType: "fixed", costStatus: "reported" });
+ await event(owner, { costStatus: "estimated", costCents: 3 });
+ const report = await costDataQualityReport(db, owner.companyId, true, undefined, now);
+ expect(report.events).toHaveLength(3);
+ expect(report.events.every(row => row.occurredAt === now.toISOString())).toBe(true);
+ expect(report.events).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: unknown.id, reason: "unknown_billing", agentName: "Codie" }),
+ expect.objectContaining({ id: missingModel.id, reason: "missing_model" }),
+ expect.objectContaining({ id: missingPrice.id, reason: "missing_price" }),
+ ]));
+ const summary = await costService(db).summary(owner.companyId, { allTime: true });
+ expect(summary.unknownBillingEventCount).toBe(1);
+ expect(summary.spendCents).toBe(24); // Unknown billing retains its reported dollars.
+ expect(summary.unpricedEventCount).toBe(2); // Included subscription usage is not a price gap.
+ const providerRows = await costService(db).byProvider(owner.companyId, { allTime: true });
+ expect(providerRows.reduce((count, row) => count + row.eventCount!, 0)).toBe(7);
+ expect(providerRows.reduce((count, row) => count + row.estimatedEventCount!, 0)).toBe(1);
+ expect(providerRows.reduce((count, row) => count + row.unpricedEventCount!, 0)).toBe(2);
+ expect(await costService(db).byBiller(owner.companyId, { allTime: true })).toEqual([
+ expect.objectContaining({ eventCount: 7, estimatedEventCount: 1, unpricedEventCount: 2, costCents: 24 }),
+ ]);
+ });
+
+ it("uses sparse ordered indexes for old gaps behind thousands of healthy records", async () => {
+ const owner = await company();
+ await db.execute(sql`insert into cost_events (company_id,agent_id,provider,model,billing_type,cost_status,cost_cents,occurred_at)
+ select ${owner.companyId}::uuid,${owner.agentId}::uuid,'openai','gpt-6-astra','metered_api','reported',1,
+ ${now.toISOString()}::timestamptz - n * interval '1 second' from generate_series(1,5000) n`);
+ await db.execute(sql`insert into heartbeat_runs (company_id,agent_id,status,created_at,finished_at,cost_accounting_pending)
+ select ${owner.companyId}::uuid,${owner.agentId}::uuid,'succeeded',${now.toISOString()}::timestamptz,
+ ${now.toISOString()}::timestamptz - n * interval '1 second',false from generate_series(1,5000) n`);
+ const old = new Date(now.getTime() - 10_000_000);
+ await event(owner, { occurredAt: old });
+ await event(owner, { occurredAt: old, billingType: "unknown", costStatus: "reported" });
+ await run(owner, { finishedAt: old });
+ await db.execute(sql`analyze cost_events`);
+ await db.execute(sql`analyze heartbeat_runs`);
+ const plans: string[] = [];
+ // Explain the actual production statements, with the normal planner enabled.
+ const explainingDb = new Proxy(db, {
+ get(target, key) {
+ if (key === "transaction") return (work: (tx: typeof db) => Promise<unknown>, options: Parameters<typeof db.transaction>[1]) =>
+ target.transaction(tx => work(new Proxy(tx, {
+ get(transaction, property) {
+ if (property === "execute") return async (query: Parameters<typeof tx.execute>[0]) => {
+ plans.push(JSON.stringify(await transaction.execute(sql`explain (analyze, buffers, format json) ${query}`)));
+ return transaction.execute(query);
+ };
+ const value = Reflect.get(transaction, property);
+ return typeof value === "function" ? value.bind(transaction) : value;
+ },
+ }) as unknown as typeof db), options);
+ const value = Reflect.get(target, key);
+ return typeof value === "function" ? value.bind(target) : value;
+ },
+ });
+ const report = await costDataQualityReport(explainingDb, owner.companyId, false, { allTime: true }, now);
+ expect(report.events).toHaveLength(2);
+ expect(report.runs).toHaveLength(1);
+ expect(plans).toHaveLength(2);
+ expect(plans[0]).toContain("cost_events_data_quality_idx");
+ expect(plans[1]).toContain("heartbeat_runs_cost_data_quality_idx");
+ expect(plans.join(" ")).not.toContain("Rows Removed by Filter\":5000");
+ });
+
+ it("enforces company and period boundaries, including month-to-date and inclusive endpoints", async () => {
+ const owner = await company(), other = await company();
+ const start = new Date("2026-10-01T00:00:00Z");
+ const first = await event(owner, { occurredAt: start });
+ const last = await event(owner);
+ const past = await event(owner, { occurredAt: new Date(start.getTime() - 1) });
+ await event(owner, { occurredAt: new Date(now.getTime() + 1) });
+ await event(other);
+ await run(other);
+ expect((await costDataQualityReport(db, owner.companyId, false, undefined, now)).events.map(row => row.id)).toEqual([last.id, first.id]);
+ expect((await costDataQualityReport(db, owner.companyId, true, { from: start, to: now }, now)).events).toHaveLength(2);
+ expect((await costDataQualityReport(db, owner.companyId, true, { from: new Date(past.occurredAt), to: new Date(past.occurredAt) }, now)).events.map(row => row.id)).toEqual([past.id]);
+ const all = await costDataQualityReport(db, owner.companyId, false, { allTime: true }, now);
+ expect(all.events).toHaveLength(4);
+ expect(all.runs).toEqual([]);
+ expect(all.canRetry).toBe(false);
+ await expect(costDataQualityReport(db, randomUUID(), true)).rejects.toThrow("Company not found");
+ });
+
+ it("includes the agent's saved appearance for both pricing and receipt gaps", async () => {
+ const owner = await company();
+ const appearance = appearanceForPalette("deep-tide");
+ await db.update(agents).set({ appearance }).where(eq(agents.id, owner.agentId));
+ await event(owner);
+ await run(owner);
+ const report = await costDataQualityReport(db, owner.companyId, true, undefined, now);
+ expect(report.events[0].agentAppearance).toEqual(appearance);
+ expect(report.runs[0].agentAppearance).toEqual(appearance);
+ });
+
+ it("changes waiting copy at fifteen minutes without settling or mutating the run", async () => {
+ const owner = await company();
+ const pending = await run(owner, { accountingLastError: "SECRET provider command", resultJson: { credential: "SECRET" } });
+ expect((await costDataQualityReport(db, owner.companyId, true, undefined, now)).runs[0].reason).toBe("waiting_for_receipt");
+ const report = await costDataQualityReport(db, owner.companyId, true, undefined, new Date(now.getTime() + RECEIPT_WAIT_MS));
+ expect(report.runs[0].reason).toBe("receipt_unavailable");
+ expect(Object.keys(report.runs[0]).sort()).toEqual(["agentId", "agentName", "agentAppearance", "id", "model", "occurredAt", "provider", "reason", "runId"].sort());
+ expect(JSON.stringify(report)).not.toContain("SECRET");
+ const [saved] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, pending.id));
+ expect(saved.costAccountingPending).toBe(true);
+ expect(saved.costAccountedAt).toBeNull();
+ expect(saved.accountingAttemptCount).toBe(0);
+ });
+
+ it("offers retry only at the writer's proven receipt boundary", async () => {
+ const owner = await company();
+ const ready = await run(owner, { usageJson: { accountingReceiptReady: true } });
+ const noWork = await run(owner, { usageJson: { accountingReceiptReady: false, accountingProviderWorkStarted: false } });
+ const resultProof = await run(owner, { resultJson: { executionRecovery: { providerWorkStarted: false } } });
+ const captureFailed = await run(owner, { usageJson: { accountingReceiptReady: true, accountingCaptureFailed: true, accountingProviderWorkStarted: false } });
+ const invalidProof = await run(owner, { usageJson: { accountingReceiptReady: false, accountingProviderWorkStarted: "false" } });
+ const acknowledged = await run(owner, { costAccountedAt: now });
+ await run(owner, { status: "running" });
+ await run(owner, { status: "queued" });
+ await run(owner, { costAccountingPending: false });
+ const report = await costDataQualityReport(db, owner.companyId, true, undefined, now);
+ expect(report.runs).toHaveLength(6);
+ for (const row of [ready, noWork, resultProof, acknowledged]) expect(report.runs.find(item => item.id === row.id)?.reason).toBe("retryable");
+ expect(report.runs.find(item => item.id === captureFailed.id)?.reason).toBe("waiting_for_receipt");
+ expect(report.runs.find(item => item.id === invalidProof.id)?.reason).toBe("waiting_for_receipt");
+ const integrity = accountingIntegrityService(db);
+ expect(await integrity.retry(owner.companyId, captureFailed.id, "board")).toEqual({ accounted: false });
+ expect(await integrity.retry(owner.companyId, noWork.id, "board")).toEqual({ accounted: true });
+ expect(await db.select().from(costEvents).where(eq(costEvents.companyId, owner.companyId))).toEqual([]);
+ });
+
+ it("does not offer retry while a native coordinator can still resume provider work", async () => {
+ const owner = await company();
+ const [issue] = await db.insert(issues).values({ companyId: owner.companyId, title: "Native task" }).returning();
+ const pending = await run(owner, { nativeIssueId: issue.id, runtimeMode: "native", usageJson: { accountingReceiptReady: true } });
+ await db.insert(nativeRunFinalizations).values({ companyId: owner.companyId, runId: pending.id, issueId: issue.id, phase: "recovering" });
+ expect((await costDataQualityReport(db, owner.companyId, true, undefined, now)).runs[0].reason).toBe("waiting_for_receipt");
+ expect(await accountingIntegrityService(db).retry(owner.companyId, pending.id, "board")).toEqual({ accounted: false });
+ await db.update(nativeRunFinalizations).set({ phase: "terminal_failure" }).where(eq(nativeRunFinalizations.runId, pending.id));
+ expect((await costDataQualityReport(db, owner.companyId, true, undefined, now)).runs[0].reason).toBe("retryable");
+ });
+
+ it("bounds each category independently and reports truncation", async () => {
+ const owner = await company();
+ for (let i = 0; i < 26; i++) {
+ await event(owner, { occurredAt: new Date(now.getTime() - i * 1000) });
+ await run(owner, { finishedAt: new Date(now.getTime() - i * 1000) });
+ }
+ const report = await costDataQualityReport(db, owner.companyId, true, undefined, now);
+ expect(report.events).toHaveLength(25);
+ expect(report.runs).toHaveLength(25);
+ expect(report.hasMoreEvents).toBe(true);
+ expect(report.hasMoreRuns).toBe(true);
+ expect(new Date(report.events[24].occurredAt).getTime()).toBe(now.getTime() - 24_000);
+ });
+
+ it("retry cannot invent a missing receipt; a late receipt is recorded exactly once", async () => {
+ const owner = await company();
+ const pending = await run(owner);
+ const integrity = accountingIntegrityService(db);
+ expect(await integrity.retry(owner.companyId, pending.id, "board")).toEqual({ accounted: false });
+ expect((await db.select().from(costEvents).where(eq(costEvents.companyId, owner.companyId)))).toEqual([]);
+ await db.update(heartbeatRuns).set({ usageJson: { accountingReceiptReady: true, provider: "openai", biller: "openai", billingType: "metered_api", model: "gpt-6-astra", costUsd: 0.21, inputTokens: 10, outputTokens: 2 } }).where(eq(heartbeatRuns.id, pending.id));
+ expect((await costDataQualityReport(db, owner.companyId, true, { allTime: true }, now)).runs[0].reason).toBe("retryable");
+ expect(await integrity.retry(owner.companyId, pending.id, "board")).toEqual({ accounted: true });
+ expect(await integrity.retry(owner.companyId, pending.id, "board")).toEqual({ accounted: false });
+ const charges = await db.select().from(costEvents).where(eq(costEvents.companyId, owner.companyId));
+ expect(charges).toHaveLength(1);
+ expect(charges[0].costCents).toBe(21);
+ expect((await costDataQualityReport(db, owner.companyId, true, { allTime: true }, now)).runs).toEqual([]);
+ const other = await company();
+ await expect(integrity.retry(other.companyId, pending.id, "board")).rejects.toThrow("Accounting run not found");
+ });
+});
diff --git a/server/src/routes/costs.ts b/server/src/routes/costs.ts
index 0a0eb45cfd..d599e008a9 100644
--- a/server/src/routes/costs.ts
+++ b/server/src/routes/costs.ts
@@ -6,6 +6,7 @@ import { refreshCompanySubscriptions } from "../services/subscription-refresh.js
import { canManageAiConnections } from "./ai-connections.js";
import { importProviderCostsSchema } from "@paperclipai/shared";
import { accountingIntegrityService } from "../services/accounting-integrity.js";
+import { costDataQualityReport } from "../services/cost-data-quality.js";
import { billingReconciliationService } from "../services/billing-reconciliation.js";
import { adjustCostSchema, importBillingInvoiceSchema, repairAccountingSchema, retryAccountingSchema } from "@paperclipai/shared";
import { Router } from "express";
@@ -84,13 +85,31 @@ export function costRoutes(
const issues = issueService(db);
const access = accessService(db);
- async function subscriptionActor(req: Parameters<typeof assertCompanyAccess>[0], companyId: string) {
+ function costReaderActor(req: Parameters<typeof assertCompanyAccess>[0], companyId: string) {
assertBoard(req);
assertCompanyAccess(req, companyId);
- return { userId: getActorInfo(req).actorId, canManage: await canManageAiConnections(db, req, companyId),
+ return { userId: getActorInfo(req).actorId,
readOnly: req.actor.memberships?.some(member => member.companyId === companyId && member.membershipRole === "viewer") ?? false };
}
+ async function subscriptionActor(req: Parameters<typeof assertCompanyAccess>[0], companyId: string) {
+ return { ...costReaderActor(req, companyId), canManage: await canManageAiConnections(db, req, companyId) };
+ }
+
+ router.get("/companies/:companyId/costs/data-quality", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const actor = costReaderActor(req, companyId);
+ if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
+ res.json(await costDataQualityReport(db, companyId, !actor.readOnly, parseCostDateRange(req.query)));
+ });
+ router.post("/companies/:companyId/costs/retry-accounting", validate(retryAccountingSchema), async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const actor = costReaderActor(req, companyId);
+ if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
+ if (actor.readOnly) throw forbidden("Viewers cannot retry cost recording");
+ res.json(await accountingIntegrityService(db, budgetHooks).retry(companyId, req.body.runId, actor.userId));
+ });
+
router.get("/companies/:companyId/costs/subscriptions", async (req, res) => {
const companyId = req.params.companyId as string;
const actor = await subscriptionActor(req, companyId);
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index dd2d117cc7..f39cd53431 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -5620,6 +5620,7 @@ const costSummaryPaths = [
"window-spend",
"quota-windows",
"subscriptions",
+ "data-quality",
] as const;
for (const segment of costSummaryPaths) {
@@ -5638,6 +5639,13 @@ for (const segment of costSummaryPaths) {
});
}
+registry.registerPath({ method: "post", path: "/api/companies/{companyId}/costs/retry-accounting", tags: ["costs"],
+ summary: "Retry recording a run's saved cost data",
+ description: "Requires company cost-read and board write access. Viewers and agents cannot retry. Replays accounting evidence only; never starts provider work or invents missing usage.",
+ request: { params: z.object({ companyId: z.string() }), body: jsonBody(retryAccountingSchema) },
+ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
+});
+
registry.registerPath({ method: "post", path: "/api/companies/{companyId}/costs/subscriptions/refresh", tags: ["costs"],
summary: "Refresh connected subscription estimates in the background",
description: "Board members only. Probes only credentials the caller can use. Successful observations are cached for six hours; provider failures retain prior estimates. No inference requests, invoices, or budget charges are created.",
diff --git a/server/src/services/cost-data-quality.ts b/server/src/services/cost-data-quality.ts
new file mode 100644
index 0000000000..9db7bcf12a
--- /dev/null
+++ b/server/src/services/cost-data-quality.ts
@@ -0,0 +1,57 @@
+import { sql } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import type { CostDataQualityItem, CostDataQualityReport } from "@paperclipai/shared";
+import { resolveCostDateRange, type CostDateRange } from "./cost-date-range.js";
+import { withAccountingReadSnapshot } from "./accounting-transaction.js";
+
+const PAGE_SIZE = 25;
+// A display distinction, never authority to acknowledge missing usage as zero.
+export const RECEIPT_WAIT_MS = 15 * 60 * 1000;
+
+/** Safe explanations for cost readers: bounded metadata only, never raw errors,
+ * credential identities, prompts, environments, or untrusted provider payloads. */
+export async function costDataQualityReport(db: Db, companyId: string, canRetry: boolean, range?: CostDateRange, now = new Date()): Promise<CostDataQualityReport> {
+ return withAccountingReadSnapshot(db, companyId, async tx => {
+ const period = resolveCostDateRange(range, now);
+ const eventFrom = period.from ? sql`and e.occurred_at >= ${period.from.toISOString()}::timestamptz` : sql``;
+ const eventTo = period.to ? sql`and e.occurred_at <= ${period.to.toISOString()}::timestamptz` : sql``;
+ const runFrom = period.from ? sql`and coalesce(r.finished_at,r.created_at) >= ${period.from.toISOString()}::timestamptz` : sql``;
+ const runTo = period.to ? sql`and coalesce(r.finished_at,r.created_at) <= ${period.to.toISOString()}::timestamptz` : sql``;
+ const [events, runs] = await Promise.all([
+ tx.execute<CostDataQualityItem & Record<string, unknown>>(sql`
+ select e.id, e.heartbeat_run_id as "runId", e.agent_id as "agentId", a.name as "agentName", a.appearance as "agentAppearance",
+ e.occurred_at::text as "occurredAt", e.provider, e.model,
+ case when e.billing_type = 'unknown' then 'unknown_billing'
+ when e.model in ('unknown','') then 'missing_model' else 'missing_price' end as reason
+ from cost_events e left join agents a on a.id = e.agent_id and a.company_id = e.company_id
+ where e.company_id = ${companyId} ${eventFrom} ${eventTo}
+ and (e.billing_type = 'unknown' or (e.cost_status = 'unpriced' and e.billing_type <> 'subscription_included'))
+ order by e.occurred_at desc,e.id limit ${PAGE_SIZE + 1}`),
+ tx.execute<CostDataQualityItem & Record<string, unknown>>(sql`
+ select r.id, r.id as "runId", r.agent_id as "agentId", a.name as "agentName", a.appearance as "agentAppearance",
+ coalesce(r.finished_at,r.created_at)::text as "occurredAt",
+ r.usage_json->>'provider' as provider,r.usage_json->>'model' as model,
+ case when r.cost_accounted_at is not null then 'retryable'
+ when r.usage_json->'accountingCaptureFailed' is distinct from 'true'::jsonb
+ and (r.usage_json->'accountingProviderWorkStarted' = 'false'::jsonb
+ or r.result_json->'executionRecovery'->'providerWorkStarted' = 'false'::jsonb) then 'retryable'
+ when r.usage_json->'accountingCaptureFailed' = 'true'::jsonb
+ or r.usage_json->'accountingReceiptReady' = 'false'::jsonb
+ or (r.runtime_mode = 'native' and exists (select 1 from native_run_finalizations f
+ where f.run_id = r.id and f.company_id = r.company_id and f.result_id is null and f.phase <> 'terminal_failure'))
+ then case when coalesce(r.finished_at,r.created_at) <= ${new Date(now.getTime() - RECEIPT_WAIT_MS).toISOString()}::timestamptz
+ then 'receipt_unavailable' else 'waiting_for_receipt' end
+ else 'retryable' end as reason
+ from heartbeat_runs r left join agents a on a.id = r.agent_id and a.company_id = r.company_id
+ where r.company_id = ${companyId} and r.cost_accounting_pending
+ and r.status in ('succeeded','failed','timed_out','cancelled','interrupted') ${runFrom} ${runTo}
+ order by coalesce(r.finished_at,r.created_at) desc,r.id limit ${PAGE_SIZE + 1}`),
+ ]);
+ // PostgreSQL's text timestamp is not portable to every browser's Date parser.
+ const items = (rows: readonly CostDataQualityItem[]) => rows.slice(0, PAGE_SIZE).map(row => ({
+ ...row, occurredAt: new Date(row.occurredAt).toISOString(),
+ }));
+ return { canRetry, events: items(Array.from(events)), runs: items(Array.from(runs)),
+ hasMoreEvents: events.length > PAGE_SIZE, hasMoreRuns: runs.length > PAGE_SIZE };
+ });
+}
diff --git a/server/src/services/costs.ts b/server/src/services/costs.ts
index 76b8380e62..fd2976dd91 100644
--- a/server/src/services/costs.ts
+++ b/server/src/services/costs.ts
@@ -186,10 +186,11 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));
if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));
- const [{ total, totalExact, eventCount, unpricedEventCount, estimatedEventCount }] = await db
+ const [{ total, totalExact, eventCount, unpricedEventCount, estimatedEventCount, unknownBillingEventCount }] = await db
.select({
eventCount: sql<number>`count(*)::int`,
estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,
+ unknownBillingEventCount: sql<number>`count(*) filter (where ${costEvents.billingType} = 'unknown')::int`,
unpricedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'unpriced' and ${costEvents.billingType} <> 'subscription_included')::int`,
total: sumAsNumber(costEvents.costCents),
totalExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,
@@ -213,6 +214,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
companyId,
eventCount,
unpricedEventCount,
+ unknownBillingEventCount,
estimatedEventCount,
pendingRunCount,
pricingComplete: unpricedEventCount === 0 && pendingRunCount === 0,
@@ -492,6 +494,9 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
model: costEvents.model,
costCents: sumAsNumber(costEvents.costCents),
costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,
+ eventCount: sql<number>`count(*)::int`,
+ estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,
+ unpricedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'unpriced' and ${costEvents.billingType} <> 'subscription_included')::int`,
inputTokens: sumAsNumber(ordinaryInputTokens),
cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),
outputTokens: sumAsNumber(costEvents.outputTokens),
@@ -523,6 +528,9 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
biller: costEvents.biller,
costCents: sumAsNumber(costEvents.costCents),
costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,
+ eventCount: sql<number>`count(*)::int`,
+ estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,
+ unpricedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'unpriced' and ${costEvents.billingType} <> 'subscription_included')::int`,
inputTokens: sumAsNumber(ordinaryInputTokens),
cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),
outputTokens: sumAsNumber(costEvents.outputTokens),
diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts
index 6ae27897a9..375cbf61cc 100644
--- a/server/src/services/native-runtime/native-session-executor.test.ts
+++ b/server/src/services/native-runtime/native-session-executor.test.ts
@@ -1049,6 +1049,10 @@ describe("native provider usage normalization", () => {
it("reports the actual runtime billing identity", () => {
expect(resolveNativeBilling({ kind: "opencode", model: "openrouter/deepseek/test", permissionMode: "allow" }))
.toEqual({ provider: "deepseek", biller: "openrouter", billingType: "unknown" });
+ expect(resolveNativeBilling({ kind: "opencode", model: "openrouter/deepseek/test", permissionMode: "allow" }, { OPENROUTER_API_KEY: "fixture" }))
+ .toEqual({ provider: "deepseek", biller: "openrouter", billingType: "metered_api" });
+ expect(resolveNativeBilling({ kind: "codex", model: "gpt-6.1-sol" } as NativeExecutionInput["provider"], { CODEX_API_KEY: "fixture" }))
+ .toEqual({ provider: "openai", biller: "openai", billingType: "metered_api" });
expect(resolveNativeBilling({ kind: "acpx", agent: "claude", model: "claude-test", permissionMode: "approve-all",
profile: { driverKind: "acpx_runtime", protocolVersion: 1, acpxVersion: "0.13.1", agent: "claude", agentProfileVersion: 1,
agentServerPackage: "@zed-industries/claude-agent-acp", agentServerVersion: "1", agentRuntimePackage: null,
@@ -1063,6 +1067,8 @@ describe("native provider usage normalization", () => {
it.each(["OPENAI_BASE_URL", "OPENAI_API_BASE", "OPENAI_API_BASE_URL"])("does not price native or managed proxy traffic as direct OpenAI using %s", key => {
const provider = { kind: "codex", model: "gpt-6-astra" } as Parameters<typeof resolveNativeBilling>[0];
expect(resolveNativeBilling(provider, { OPENAI_API_KEY: "fixture", [key]: "https://proxy.example/v1" }).biller).toBe("unknown");
+ expect(resolveNativeBilling({ kind: "opencode", model: "openai/gpt-6-astra", permissionMode: "allow" }, { OPENAI_API_KEY: "fixture", [key]: "https://proxy.example/v1" }))
+ .toMatchObject({ provider: "openai", biller: "unknown", billingType: "metered_api" });
expect(resolveNativeBilling(provider, { [key]: "https://proxy.example/v1" }, { provider: "openai", biller: "openai", billingType: "metered_api" }).biller).toBe("unknown");
expect(resolveNativeBilling(provider, {}, { provider: "openai", biller: "openai", billingType: "metered_api" })).toMatchObject({ biller: "openai", billingType: "metered_api" });
});
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index 6b5275fc9d..9a823b4e95 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -1,4 +1,5 @@
import { configuredEnvironment } from "../../vendor/paperclip-runner/index.js";
+import { apiKeyBillingType } from "@paperclipai/adapter-utils/api-billing-type";
import { agents } from "@paperclipai/db";
import { isCloudManagedInstance } from "../cloud-instance.js";
import { dotRunnerBroker } from "../dot-runner-broker.js";
@@ -9798,11 +9799,15 @@ export function resolveNativeBilling(provider: NativeExecutionInput["provider"],
const parts = (provider.model ?? "").split("/");
const biller = parts.length > 1 ? parts[0] : provider.kind === "acpx" ? nativeUsageBiller(provider) : "unknown";
const modelProvider = biller === "openrouter" && parts.length > 2 ? parts[1] : biller;
- return { provider: modelProvider, biller, billingType: "unknown" };
+ const billingType = apiKeyBillingType(biller, env);
+ const effectiveBiller = biller === "openai" && billingType === "metered_api"
+ ? inferOpenAiCompatibleBiller(env, "openai") ?? "unknown" : biller;
+ return { provider: modelProvider, biller: effectiveBiller, billingType };
}
if (provider.kind !== "codex" && !(provider.kind === "acpx" && provider.agent === "codex"))
return { provider: "unknown", biller: "unknown", billingType: "unknown" };
- return { provider: "openai", biller: env.OPENAI_API_KEY ? inferOpenAiCompatibleBiller(env, "openai") : "unknown", billingType: env.OPENAI_API_KEY ? "metered_api" : "unknown" };
+ const billingType = apiKeyBillingType("openai", env, "codex");
+ return { provider: "openai", biller: billingType === "metered_api" ? inferOpenAiCompatibleBiller(env, "openai") : "unknown", billingType };
}
export function normalizeNativeUsage(usage: Record<string, unknown> | null, options: { inputIncludesCacheReads?: boolean } = {}) {
diff --git a/ui/src/api/costs.ts b/ui/src/api/costs.ts
index 637ff175dc..33106bbaab 100644
--- a/ui/src/api/costs.ts
+++ b/ui/src/api/costs.ts
@@ -1,5 +1,6 @@
import type {
CostSummary,
+ CostDataQualityReport,
CostByAgent,
CostByUserReport,
CostByProviderModel,
@@ -25,6 +26,10 @@ function dateParams(from?: string, to?: string): string {
}
export const costsApi = {
+ dataQuality: (companyId: string, from?: string, to?: string) =>
+ api.get<CostDataQualityReport>(`/companies/${companyId}/costs/data-quality${dateParams(from, to)}`),
+ retryAccounting: (companyId: string, runId: string) =>
+ api.post<{ accounted: boolean }>(`/companies/${companyId}/costs/retry-accounting`, { runId }),
summary: (companyId: string, from?: string, to?: string) =>
api.get<CostSummary>(`/companies/${companyId}/costs/summary${dateParams(from, to)}`),
byUser: (companyId: string, from?: string, to?: string) =>
diff --git a/ui/src/components/BillerSpendCard.tsx b/ui/src/components/BillerSpendCard.tsx
index db6aa467c9..1ad711d420 100644
--- a/ui/src/components/BillerSpendCard.tsx
+++ b/ui/src/components/BillerSpendCard.tsx
@@ -2,6 +2,7 @@ import { useMemo } from "react";
import type { CostByBiller, CostByProviderModel } from "@paperclipai/shared";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { QuotaBar } from "./QuotaBar";
+import { CostAmount } from "./CostAmount";
import { billingTypeDisplayName, formatCents, formatTokens, providerDisplayName } from "@/lib/utils";
interface BillerSpendCardProps {
@@ -71,9 +72,10 @@ export function BillerSpendCard({
{row.modelCount} model{row.modelCount === 1 ? "" : "s"}
</CardDescription>
</div>
- <span className="text-xl font-bold tabular-nums shrink-0">
- {formatCents(row.costCents)}
- </span>
+ <div className="text-xl shrink-0">
+ <CostAmount costCents={row.costCents} eventCount={row.eventCount}
+ estimatedEventCount={row.estimatedEventCount} unpricedEventCount={row.unpricedEventCount} showUnavailableCount />
+ </div>
</div>
</CardHeader>
diff --git a/ui/src/components/CostAmount.tsx b/ui/src/components/CostAmount.tsx
index 48c09caaaf..bffebcbad9 100644
--- a/ui/src/components/CostAmount.tsx
+++ b/ui/src/components/CostAmount.tsx
@@ -2,15 +2,18 @@ import type { ReactNode } from "react";
import type { CostByAgent } from "@paperclipai/shared";
import { formatCents } from "../lib/utils";
import { CostEstimateLabel } from "./CostEstimateLabel";
+import { Badge } from "./ui/badge";
export function CostAmount({
costCents,
eventCount,
estimatedEventCount,
unpricedEventCount,
+ showUnavailableCount = false,
suffix,
}: Pick<CostByAgent, "costCents"> & Partial<Pick<CostByAgent, "eventCount" | "estimatedEventCount">> & {
unpricedEventCount?: number;
+ showUnavailableCount?: boolean;
suffix?: ReactNode;
}) {
const entirelyUnpriced = costCents === 0 && (eventCount ?? 0) > 0 && unpricedEventCount === eventCount;
@@ -21,6 +24,9 @@ export function CostAmount({
{suffix}
</div>
<CostEstimateLabel eventCount={eventCount} estimatedEventCount={estimatedEventCount} />
+ {showUnavailableCount && !!unpricedEventCount && <Badge variant="outline" className="font-normal text-muted-foreground">
+ {unpricedEventCount} {unpricedEventCount === 1 ? "cost" : "costs"} unavailable
+ </Badge>}
</div>
);
}
diff --git a/ui/src/components/CostDataQualityNotice.test.tsx b/ui/src/components/CostDataQualityNotice.test.tsx
new file mode 100644
index 0000000000..6cf8c15e9f
--- /dev/null
+++ b/ui/src/components/CostDataQualityNotice.test.tsx
@@ -0,0 +1,192 @@
+// @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.");
+ });
+});
diff --git a/ui/src/components/CostDataQualityNotice.tsx b/ui/src/components/CostDataQualityNotice.tsx
new file mode 100644
index 0000000000..75e1d51edc
--- /dev/null
+++ b/ui/src/components/CostDataQualityNotice.tsx
@@ -0,0 +1,137 @@
+import { useId, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { ChevronDown, ChevronRight } from "lucide-react";
+import { Link } from "../lib/router";
+import type { CostDataQualityItem, CostDataQualityReason } from "@paperclipai/shared";
+import { costsApi } from "../api/costs";
+import { formatDateTime } from "../lib/utils";
+import { Button } from "./ui/button";
+import { Badge } from "./ui/badge";
+import { AgentAvatar } from "./AgentAvatar";
+import { useToastActions } from "../context/ToastContext";
+
+const explanations: Record<CostDataQualityReason, { label: string; description: string }> = {
+ unknown_billing: {
+ label: "Billing category unknown",
+ description: "This run did not identify API or subscription billing. Any recorded charges are included in the inference ledger. For future runs, select an AI connection in the agent’s configuration so Paperclip can identify its billing.",
+ },
+ missing_model: {
+ label: "Model not reported",
+ description: "Token usage was recorded without a model, so Paperclip cannot estimate its cost. Select an explicit model in the agent’s configuration for future runs. Changing settings will not reprice this past run.",
+ },
+ missing_price: {
+ label: "Cost unavailable",
+ description: "The provider did not supply a reliable price for this usage. There is no action required for this past entry. New API runs with complete usage and a supported model are estimated automatically.",
+ },
+ waiting_for_receipt: {
+ label: "Receiving usage",
+ description: "This run has stopped. Paperclip is waiting for its final usage data and will record it automatically. You do not need to rerun the agent.",
+ },
+ receipt_unavailable: {
+ label: "Final usage unavailable",
+ description: "This run stopped without final usage data. Its cost remains unresolved for budget checks. Paperclip will record a late receipt if one arrives; rerunning the agent will not recover this usage.",
+ },
+ retryable: {
+ label: "Ready to record",
+ description: "Saved usage data is ready to be recorded. Paperclip retries automatically, or you can retry now. This records costs only; it does not rerun the agent.",
+ },
+};
+
+export function CostDataQualityNotice({ companyId, from, to, reportKey, unpricedCount, pendingCount, unknownBillingCount }: {
+ companyId: string; from?: string; to?: string; reportKey: readonly unknown[];
+ unpricedCount: number; pendingCount: number; unknownBillingCount: number;
+}) {
+ const [open, setOpen] = useState(false);
+ const unavailableCount = unpricedCount + pendingCount;
+ const hasCostGaps = unavailableCount > 0 || unknownBillingCount > 0;
+ const detailsId = useId();
+ const client = useQueryClient();
+ const { pushToast } = useToastActions();
+ const key = [...reportKey, "data-quality"];
+ const { data, error, isPending, refetch } = useQuery({
+ queryKey: key,
+ queryFn: () => costsApi.dataQuality(companyId, from, to),
+ enabled: open && hasCostGaps,
+ refetchInterval: open && hasCostGaps ? 30_000 : false,
+ });
+ const retry = useMutation({
+ mutationFn: (runId: string) => costsApi.retryAccounting(companyId, runId),
+ onSuccess: result => {
+ pushToast({
+ title: result.accounted ? "Costs recorded." : "No new cost data is available.",
+ body: "The agent was not rerun.",
+ tone: result.accounted ? "success" : "info",
+ });
+ client.invalidateQueries({ queryKey: ["costs", companyId] });
+ client.invalidateQueries({ queryKey: key });
+ client.invalidateQueries({ queryKey: ["cost-subscriptions", companyId] });
+ },
+ });
+ const label = unavailableCount > 0
+ ? `${unavailableCount} run ${unavailableCount === 1 ? "cost" : "costs"} unavailable`
+ : `${unknownBillingCount} billing ${unknownBillingCount === 1 ? "type" : "types"} unknown`;
+
+ const groups = new Map<string | null, {
+ agent: { id?: string; name: string; appearance?: CostDataQualityItem["agentAppearance"] };
+ items: { item: CostDataQualityItem; source: "event" | "run" }[];
+ }>();
+ for (const [source, items] of [["event", data?.events ?? []], ["run", data?.runs ?? []]] as const) {
+ for (const item of items) {
+ let group = groups.get(item.agentId);
+ if (!group) {
+ group = { agent: { id: item.agentId ?? undefined, name: item.agentName ?? (item.agentId ? "Unknown agent" : "Paperclip services"), appearance: item.agentAppearance }, items: [] };
+ groups.set(item.agentId, group);
+ }
+ group.items.push({ item, source });
+ }
+ }
+ const sortedGroups = [...groups.values()].sort((a, b) =>
+ a.agent.name.localeCompare(b.agent.name, "en", { sensitivity: "base", numeric: true })
+ || (a.agent.id ?? "").localeCompare(b.agent.id ?? ""));
+ for (const group of sortedGroups) group.items.sort((a, b) =>
+ Date.parse(b.item.occurredAt) - Date.parse(a.item.occurredAt)
+ || `${a.source}:${a.item.id}`.localeCompare(`${b.source}:${b.item.id}`));
+
+ function itemRow(item: CostDataQualityItem, source: "event" | "run") {
+ const explanation = explanations[item.reason];
+ return <li key={`${source}:${item.id}`} className="space-y-2 border-b border-border py-3 last:border-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <Badge variant="outline" className="font-normal text-muted-foreground">{explanation.label}</Badge>
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <time dateTime={item.occurredAt}>{formatDateTime(item.occurredAt)}</time>
+ {item.runId && item.agentId && <Link className="text-primary underline underline-offset-4 hover:text-primary/80" to={`/agents/${item.agentId}/runs/${item.runId}`}>View run</Link>}
+ {item.reason === "retryable" && item.runId && data?.canRetry && <Button type="button" variant="link" size="sm" className="h-auto p-0 text-xs font-normal underline hover:text-primary/80" disabled={retry.isPending}
+ onClick={() => { retry.reset(); retry.mutate(item.runId!); }}>Retry cost recording</Button>}
+ </div>
+ </div>
+ <p>{explanation.description}</p>
+ {retry.variables === item.runId && retry.isPending && <p role="status">Recording saved costs…</p>}
+ {retry.variables === item.runId && retry.error && <p role="status">Cost recording failed. Try again shortly.</p>}
+ </li>;
+ }
+
+ return <div className="space-y-2 text-sm text-muted-foreground">
+ <Button type="button" variant="ghost" size="sm" className="h-auto justify-start gap-1 px-0 py-1 font-normal has-[>svg]:px-0" aria-expanded={open} aria-controls={detailsId} onClick={() => setOpen(value => !value)}>
+ {open ? <ChevronDown className="size-3" aria-hidden="true" /> : <ChevronRight className="size-3" aria-hidden="true" />}
+ {label}
+ </Button>
+ {open && <div id={detailsId} className="space-y-2">
+ {hasCostGaps && isPending && <p role="status">Loading affected runs…</p>}
+ {hasCostGaps && error && !data && <div className="flex flex-wrap items-center gap-2"><p role="status">Cost details could not be loaded.</p><Button variant="outline" size="sm" onClick={() => refetch()}>Retry loading</Button></div>}
+ {hasCostGaps && data && <>
+ {error && <p role="status">Showing the last loaded cost details. Updates will resume automatically.</p>}
+ {data.events.length === 0 && data.runs.length === 0 && <p role="status">No cost gaps remain in this period.</p>}
+ <ul aria-label="Cost details by agent" className="space-y-4">
+ {sortedGroups.map(group => <li key={group.agent.id ?? "services"}>
+ <h3 className="flex items-center gap-2 font-medium text-foreground">
+ <AgentAvatar agent={group.agent} size={20} />
+ {group.agent.id ? <Link className="text-primary underline underline-offset-4 hover:text-primary/80" to={`/agents/${group.agent.id}/configuration`}>{group.agent.name}</Link> : group.agent.name}
+ </h3>
+ <ul aria-label={`${group.agent.name} cost details`}>{group.items.map(({ item, source }) => itemRow(item, source))}</ul>
+ </li>)}
+ </ul>
+ {(data.hasMoreEvents || data.hasMoreRuns) && <p className="text-xs">Showing the 25 most recent entries in each category. Select a shorter date range to inspect more.</p>}
+ </>}
+ </div>}
+ </div>;
+}
diff --git a/ui/src/components/ProviderCostStatus.test.tsx b/ui/src/components/ProviderCostStatus.test.tsx
new file mode 100644
index 0000000000..e4dbcba106
--- /dev/null
+++ b/ui/src/components/ProviderCostStatus.test.tsx
@@ -0,0 +1,36 @@
+// @vitest-environment jsdom
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { ProviderQuotaCard } from "./ProviderQuotaCard";
+import { BillerSpendCard } from "./BillerSpendCard";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const base = { provider: "openai", biller: "openai", billingType: "metered_api" as const, model: "gpt-6-astra",
+ inputTokens: 10, cachedInputTokens: 0, outputTokens: 2, apiRunCount: 1, subscriptionRunCount: 0,
+ subscriptionInputTokens: 0, subscriptionCachedInputTokens: 0, subscriptionOutputTokens: 0,
+ providerCount: 1, modelCount: 1 };
+const cases = [
+ { name: "unpriced", costCents: 0, eventCount: 2, estimatedEventCount: 0, unpricedEventCount: 2, amount: "—", estimate: null, unavailable: "2 costs unavailable" },
+ { name: "mixed", costCents: 125, eventCount: 3, estimatedEventCount: 1, unpricedEventCount: 1, amount: "$1.25", estimate: "Partially estimated", unavailable: "1 cost unavailable" },
+ { name: "estimated", costCents: 125, eventCount: 2, estimatedEventCount: 2, unpricedEventCount: 0, amount: "$1.25", estimate: "Estimated", unavailable: null },
+ { name: "included subscription", costCents: 0, eventCount: 2, estimatedEventCount: 0, unpricedEventCount: 0, amount: "$0.00", estimate: null, unavailable: null },
+ { name: "older response", costCents: 125, amount: "$1.25", estimate: null, unavailable: null },
+];
+describe.each(["provider", "biller"] as const)("%s price status", kind => {
+ let container: HTMLDivElement, root: ReturnType<typeof createRoot>;
+ beforeEach(() => { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); });
+ afterEach(() => { act(() => root.unmount()); container.remove(); });
+ it.each(cases)("labels $name totals without implying missing costs are free", async example => {
+ const row = { ...base, ...example };
+ const props = { budgetMonthlyCents: 0, totalCompanySpendCents: row.costCents, weekSpendCents: 0 };
+ await act(async () => root.render(kind === "provider"
+ ? <ProviderQuotaCard {...props} provider="openai" rows={[row]} windowRows={[]} showDeficitNotch={false} />
+ : <BillerSpendCard {...props} row={row} providerRows={[row]} />));
+ const header = container.querySelector('[data-slot="card-header"]')!;
+ expect(header.textContent).toContain(example.amount);
+ if (example.amount === "—") expect(header.textContent).not.toContain("$0.00");
+ const badges = [...header.querySelectorAll('[data-slot="badge"]')].map(badge => badge.textContent);
+ expect(badges).toEqual([example.estimate, example.unavailable].filter(Boolean));
+ });
+});
diff --git a/ui/src/components/ProviderQuotaCard.tsx b/ui/src/components/ProviderQuotaCard.tsx
index aa5ee70e3b..1ec93514f8 100644
--- a/ui/src/components/ProviderQuotaCard.tsx
+++ b/ui/src/components/ProviderQuotaCard.tsx
@@ -5,6 +5,7 @@ import type { CostByProviderModel, CostWindowSpendRow, QuotaWindow, ProviderQuot
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { QuotaBar } from "./QuotaBar";
+import { CostAmount } from "./CostAmount";
import { ClaudeSubscriptionPanel } from "./ClaudeSubscriptionPanel";
import { CodexSubscriptionPanel } from "./CodexSubscriptionPanel";
import {
@@ -63,10 +64,14 @@ export function ProviderQuotaCard({
const totals = useMemo(() => {
let inputTokens = 0, outputTokens = 0, costCents = 0;
let apiRunCount = 0, subRunCount = 0, subInputTokens = 0, subOutputTokens = 0;
+ let eventCount = 0, estimatedEventCount = 0, unpricedEventCount = 0;
for (const r of rows) {
inputTokens += r.inputTokens + r.cachedInputTokens;
outputTokens += r.outputTokens;
costCents += r.costCents;
+ eventCount += r.eventCount ?? 0;
+ estimatedEventCount += r.estimatedEventCount ?? 0;
+ unpricedEventCount += r.unpricedEventCount ?? 0;
apiRunCount += r.apiRunCount;
subRunCount += r.subscriptionRunCount;
subInputTokens += r.subscriptionInputTokens + r.subscriptionCachedInputTokens;
@@ -81,6 +86,7 @@ export function ProviderQuotaCard({
totalOutputTokens: outputTokens,
totalTokens,
totalCostCents: costCents,
+ eventCount, estimatedEventCount, unpricedEventCount,
totalApiRuns: apiRunCount,
totalSubRuns: subRunCount,
totalSubInputTokens: subInputTokens,
@@ -156,9 +162,10 @@ export function ProviderQuotaCard({
)}
</CardDescription>
</div>
- <span className="text-xl font-bold tabular-nums shrink-0">
- {formatCents(totalCostCents)}
- </span>
+ <div className="text-xl shrink-0">
+ <CostAmount costCents={totalCostCents} eventCount={totals.eventCount}
+ estimatedEventCount={totals.estimatedEventCount} unpricedEventCount={totals.unpricedEventCount} showUnavailableCount />
+ </div>
</div>
</CardHeader>
diff --git a/ui/src/pages/Costs.test.tsx b/ui/src/pages/Costs.test.tsx
index 14e0591fb0..35c54ddef6 100644
--- a/ui/src/pages/Costs.test.tsx
+++ b/ui/src/pages/Costs.test.tsx
@@ -27,6 +27,8 @@ const costsApiMocks = vi.hoisted(() => ({
byBiller: vi.fn(),
windowSpend: vi.fn(),
quotaWindows: vi.fn(),
+ dataQuality: vi.fn(),
+ retryAccounting: vi.fn(),
}));
const subscriptionsMocks = vi.hoisted(() => ({ report: vi.fn(), refresh: vi.fn(), update: vi.fn(), link: vi.fn() }));
vi.mock("../api/subscriptions", () => ({ subscriptionsApi: subscriptionsMocks }));
@@ -50,6 +52,8 @@ vi.mock("../context/BreadcrumbContext", () => ({
useBreadcrumbs: () => ({ setBreadcrumbs: setBreadcrumbsMock }),
}));
+vi.mock("../context/ToastContext", () => ({ useToastActions: () => ({ pushToast: vi.fn() }) }));
+
vi.mock("../context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false }) }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -109,7 +113,7 @@ describe("Shared Costs surfaces", () => {
root = createRoot(container);
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>));
await act(async () => vi.waitFor(() => expect(container.textContent).toContain(
- "150 tokens have other or unknown billing types, with $6.00 in recorded charges. They remain in the inference ledger.",
+ "Other billing usage: 150 tokens · $6.00 in recorded charges, included in the inference ledger.",
)));
expect(container.textContent).not.toContain("tokens have an unknown billing type");
});
@@ -138,6 +142,37 @@ describe("Shared Costs surfaces", () => {
for (const mock of Object.values(costsApiMocks)) expect(mock).not.toHaveBeenCalled();
});
+ it.each(surfaces)("shows unknown billing separately from complete prices only on the %s Overview", async (_name, props) => {
+ for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
+ costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
+ costsApiMocks.summary.mockResolvedValue({ spendCents: 21, budgetCents: 0, pricingComplete: true, unknownBillingEventCount: 1, unpricedEventCount: 0, pendingRunCount: 0 });
+ costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });
+ costsApiMocks.dataQuality.mockResolvedValue({ canRetry: true, events: [{ id: "event", runId: "run", agentId: "agent", agentName: "Codie", reason: "unknown_billing", occurredAt: "2026-10-09T12:00:00Z" }], runs: [], hasMoreEvents: false, hasMoreRuns: false });
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ root = createRoot(container);
+ await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>));
+ await act(async () => vi.waitFor(() => expect(container.textContent).toContain("1 billing type unknown")));
+ expect(container.textContent).not.toContain("Totals include known charges only.");
+ expect(costsApiMocks.dataQuality).not.toHaveBeenCalled();
+ const button = (label: string) => [...container.querySelectorAll("button")].find(row => row.textContent === label)!;
+ await act(async () => button("1 billing type unknown").click());
+ await act(async () => vi.waitFor(() => expect(container.textContent).toContain("Billing category unknown")));
+ const [, from, to] = costsApiMocks.dataQuality.mock.lastCall!;
+ expect(Number.isFinite(Date.parse(from))).toBe(true);
+ expect(Number.isFinite(Date.parse(to))).toBe(true);
+ await act(async () => button("Providers").dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 })));
+ expect(container.querySelector('[role="tab"][data-state="active"]')?.textContent).toBe("Providers");
+ expect(container.textContent).not.toContain("1 billing type unknown");
+ expect(container.textContent).not.toContain("Billing category unknown");
+ await act(async () => button("Overview").dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 })));
+ expect(button("1 billing type unknown")).toBeDefined();
+ await act(async () => button("All Time").click());
+ await act(async () => vi.waitFor(() => expect(button("1 billing type unknown")).toBeDefined()));
+ await act(async () => button("1 billing type unknown").click());
+ await act(async () => vi.waitFor(() => expect(costsApiMocks.dataQuality).toHaveBeenLastCalledWith("company-1", undefined, undefined)));
+ queryClient.clear();
+ });
+
it("opens linked decision history with real date bounds instead of report cache labels", async () => {
for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);
costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });
@@ -348,23 +383,23 @@ describe("Shared Costs surfaces", () => {
root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>);
});
await act(async () => {
- await vi.waitFor(() => expect(container.textContent).toContain("Costs are unavailable for 2 usage entries in this period. Totals include known costs only."));
+ await vi.waitFor(() => expect(container.textContent).toContain("3 run costs unavailable"));
});
- const notice = [...container.querySelectorAll('[role="status"]')].find(element => element.textContent?.includes("Costs are unavailable"))!;
+ const notice = [...container.querySelectorAll("button")].find(button => button.textContent === "3 run costs unavailable")!.parentElement!;
expect(notice.classList.contains("text-muted-foreground")).toBe(true);
expect(notice.querySelector(".text-destructive")).toBeNull();
expect(notice.classList.contains("text-destructive")).toBe(false);
- expect(notice.textContent).toContain("1 run is awaiting cost data.");
- expect(notice.previousElementSibling?.textContent).toContain("API spend");
+ expect(notice.textContent).toBe("3 run costs unavailable");
+ expect(costsApiMocks.dataQuality).not.toHaveBeenCalled();
expect(container.textContent).toContain("Finance headline totals are USD only");
costsApiMocks.summary.mockResolvedValue({ spendCents: 12.4, budgetCents: 0, pricingComplete: false, unpricedEventCount: 10, pendingRunCount: 0 });
await act(async () => { await queryClient.invalidateQueries(); });
- await vi.waitFor(() => expect(notice.textContent).toContain("Costs are unavailable for 10 usage entries"));
+ await vi.waitFor(() => expect(notice.textContent).toBe("10 run costs unavailable"));
expect(notice.textContent).not.toContain("awaiting cost data");
expect(notice.textContent).not.toContain("0 runs");
costsApiMocks.summary.mockResolvedValue({ spendCents: 12.4, budgetCents: 0, pricingComplete: false, unpricedEventCount: 0, pendingRunCount: 1 });
await act(async () => { await queryClient.invalidateQueries(); });
- await vi.waitFor(() => expect(notice.textContent).toBe("1 run is awaiting cost data."));
+ await vi.waitFor(() => expect(notice.textContent).toBe("1 run cost unavailable"));
costsApiMocks.summary.mockResolvedValue({ spendCents: 12.4, budgetCents: 0, pricingComplete: true, unpricedEventCount: 0, pendingRunCount: 0 });
await act(async () => { await queryClient.invalidateQueries(); });
await vi.waitFor(() => expect(container.contains(notice)).toBe(false));
@@ -410,6 +445,9 @@ describe("Shared Costs surfaces", () => {
expect(projectBadge("Estimated project")?.textContent).toBe("Estimated");
expect(projectBadge("Mixed project")?.textContent).toBe("Partially estimated");
expect(projectBadge("Reported project")).toBeNull();
+ expect(container.textContent).not.toContain("Includes 3 estimated charges.");
+ expect(container.querySelector('button[aria-expanded]')).toBeNull();
+ expect(costsApiMocks.dataQuality).not.toHaveBeenCalled();
await act(async () => card("Mixed").querySelector<HTMLElement>(".cursor-pointer")!.click());
const breakdown = card("Mixed").querySelector(".border-l")!;
expect(breakdown.textContent).toContain("gpt-6-astra");
diff --git a/ui/src/pages/Costs.tsx b/ui/src/pages/Costs.tsx
index 30b5ba0e0a..4bee302312 100644
--- a/ui/src/pages/Costs.tsx
+++ b/ui/src/pages/Costs.tsx
@@ -6,6 +6,7 @@ import { useSearchParams } from "@/lib/router";
import { CostEstimateLabel } from "../components/CostEstimateLabel";
import { CostAmount } from "../components/CostAmount";
import { CostByUserTable } from "../components/CostByUserTable";
+import { CostDataQualityNotice } from "../components/CostDataQualityNotice";
import { AgentIdentity } from "@/components/AgentIdentity";
import { useEffect, useMemo, useRef, useState, type ComponentType, type ReactNode } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
@@ -692,26 +693,18 @@ export function Costs({
/>
</div>
{subscriptions && Number(subscriptions.subscription.costCents) > 0 && <p className="text-sm text-muted-foreground">Subscription accounts also have {formatCents(Number(subscriptions.subscription.costCents))} in recorded usage charges for this period, separate from monthly fees.</p>}
- {subscriptions && subscriptions.unknown.eventCount > 0 && <p className="text-sm text-muted-foreground">{formatTokens(subscriptions.unknown.inputTokens + subscriptions.unknown.cachedInputTokens + subscriptions.unknown.outputTokens)} tokens have other or unknown billing types{Number(subscriptions.unknown.costCents) > 0 ? `, with ${formatCents(Number(subscriptions.unknown.costCents))} in recorded charges` : ""}. They remain in the inference ledger.</p>}
+ {subscriptions && subscriptions.unknown.eventCount > 0 && <p className="text-sm text-muted-foreground">Other billing usage: {formatTokens(subscriptions.unknown.inputTokens + subscriptions.unknown.cachedInputTokens + subscriptions.unknown.outputTokens)} tokens{Number(subscriptions.unknown.costCents) > 0 ? ` · ${formatCents(Number(subscriptions.unknown.costCents))} in recorded charges` : ""}, included in the inference ledger.</p>}
{subscriptionError && subscriptions && <p role="status" className="text-sm text-muted-foreground">Showing the last loaded API and subscription usage. Updates will resume automatically.</p>}
{discoverSubscriptions.error && <div role="status" className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
<p>Connected accounts could not be checked. Existing subscription estimates are still shown.</p>
{subscriptions?.canRefresh && <Button variant="outline" size="sm" disabled={discoverSubscriptions.isPending}
onClick={() => discoverSubscriptions.mutate(companyId)}>Retry account check</Button>}
</div>}
- {spendData?.summary.pricingComplete === false && (
- <div role="status" className="space-y-1 text-sm text-muted-foreground">
- {spendData.summary.unpricedEventCount > 0 && (
- <p>
- Costs are unavailable for {spendData.summary.unpricedEventCount} usage {spendData.summary.unpricedEventCount === 1 ? "entry" : "entries"} in this period. Totals include known costs only.
- </p>
- )}
- {spendData.summary.pendingRunCount > 0 && (
- <p>
- {spendData.summary.pendingRunCount} {spendData.summary.pendingRunCount === 1 ? "run is" : "runs are"} awaiting cost data.
- </p>
- )}
- </div>
+ {mainTab === "overview" && spendData && (spendData.summary.unpricedEventCount > 0 || spendData.summary.pendingRunCount > 0 || (spendData.summary.unknownBillingEventCount ?? 0) > 0) && (
+ <CostDataQualityNotice key={`${companyId}:${reportQueryFrom}:${reportQueryTo}`} companyId={companyId}
+ from={from || undefined} to={to || undefined} reportKey={queryKeys.costs(companyId, reportQueryFrom, reportQueryTo)}
+ unpricedCount={spendData.summary.unpricedEventCount} pendingCount={spendData.summary.pendingRunCount}
+ unknownBillingCount={spendData.summary.unknownBillingEventCount ?? 0} />
)}
</div>
) : null}
@@ -727,7 +720,6 @@ export function Costs({
</p>
) : null}
- {!!spendData?.summary.estimatedEventCount && <p role="status" className="text-sm text-muted-foreground">Includes {spendData.summary.estimatedEventCount} estimated {spendData.summary.estimatedEventCount === 1 ? "charge" : "charges"}. Token estimates use published rates and recorded assumptions; provider bills may differ.</p>}
{incidentMutation.error && <p role="alert" className="text-sm text-destructive">Could not update the budget. Check any pending runs or unpriced usage shown on this page, then try again.</p>}
<Tabs value={mainTab} onValueChange={(value) => { setMainTab(value as typeof mainTab); setSearchParams(current => { const next = new URLSearchParams(current); next.set("tab", value); return next; }, { replace: true }); }}>
{!lockTab ? (
diff --git a/ui/storybook/stories/costs/subscriptions.stories.tsx b/ui/storybook/stories/costs/subscriptions.stories.tsx
index 7736017064..3173cb6259 100644
--- a/ui/storybook/stories/costs/subscriptions.stories.tsx
+++ b/ui/storybook/stories/costs/subscriptions.stories.tsx
@@ -2,8 +2,9 @@ import { useLayoutEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, userEvent, within } from "storybook/test";
-import { monthlySubscriptionCents, type SubscriptionCostReport } from "@paperclipai/shared";
+import { monthlySubscriptionCents, type SubscriptionCostReport, type CostDataQualityReport } from "@paperclipai/shared";
import { Costs } from "@/pages/Costs";
+import { ToastViewport } from "@/components/ToastViewport";
function fixture(): SubscriptionCostReport {
const zero = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 };
@@ -26,12 +27,24 @@ function fixture(): SubscriptionCostReport {
}
/** Production Costs page; only API responses are fixtures. Edits persist in the story. */
-function SubscriptionCostsStory({ unknownPrice = false, stale = false }: { unknownPrice?: boolean; stale?: boolean }) {
+function SubscriptionCostsStory({ unknownPrice = false, stale = false, costGaps = false }: { unknownPrice?: boolean; stale?: boolean; costGaps?: boolean }) {
const [ready, setReady] = useState(false);
const client = useQueryClient();
useLayoutEffect(() => {
const original = window.fetch;
const report = fixture();
+ const details: CostDataQualityReport = { canRetry: true, hasMoreEvents: false, hasMoreRuns: false,
+ events: [
+ { id: "unknown-billing", runId: "run-openrouter", agentId: "codie", agentName: "Codie", occurredAt: "2026-10-09T10:00:00Z", provider: "openrouter", model: "deepseek-v4", reason: "unknown_billing" },
+ { id: "missing-model", runId: "run-default-model", agentId: "fry", agentName: "Fry", occurredAt: "2026-10-09T09:00:00Z", provider: "openai", model: "unknown", reason: "missing_model" },
+ { id: "missing-price", runId: "run-old-receipt", agentId: "leela", agentName: "Leela", occurredAt: "2026-10-02T09:00:00Z", provider: "openai", model: "gpt-6-astra", reason: "missing_price" },
+ ],
+ runs: [
+ { id: "receiving", runId: "receiving", agentId: "codie", agentName: "Codie", occurredAt: new Date().toISOString(), provider: "openai", model: "gpt-6-astra", reason: "waiting_for_receipt" },
+ { id: "unavailable", runId: "unavailable", agentId: "leela", agentName: "Leela", occurredAt: "2026-10-08T12:00:00Z", provider: "anthropic", model: "claude-opus-4-6", reason: "receipt_unavailable" },
+ { id: "ready", runId: "ready", agentId: "fry", agentName: "Fry", occurredAt: "2026-10-09T12:00:00Z", provider: "openai", model: "gpt-6-astra", reason: "retryable" },
+ ],
+ };
if (unknownPrice) {
report.accounts[1].price = { ...report.accounts[1].price, plan: "Claude Max", amountCents: null, monthlyCents: null, source: "unknown", sourceUrl: null };
report.accounts[1].detectedPlan = "max";
@@ -44,6 +57,12 @@ function SubscriptionCostsStory({ unknownPrice = false, stale = false }: { unkno
const path = url.pathname.startsWith(base) ? url.pathname.slice(base.length) : "";
if (path === "costs/subscriptions/refresh") return Response.json({ status: "accepted" }, { status: 202 });
if (path === "costs/subscriptions") return Response.json(report);
+ if (path === "costs/data-quality") return Response.json(details);
+ if (path === "costs/retry-accounting" && init?.method === "POST") {
+ const { runId } = JSON.parse(String(init.body));
+ details.runs = details.runs.filter(row => row.runId !== runId);
+ return Response.json({ accounted: true });
+ }
if (path.startsWith("costs/subscriptions/") && init?.method === "PATCH") {
const account = report.accounts.find(row => row.id === path.split("/")[2])!;
const patch = JSON.parse(String(init.body));
@@ -63,7 +82,7 @@ function SubscriptionCostsStory({ unknownPrice = false, stale = false }: { unkno
return Response.json({ id: account.id });
}
if (path === "budgets/overview") return Response.json({ policies: [], activeIncidents: [], pausedAgentCount: 0, pausedProjectCount: 0, pendingApprovalCount: 0 });
- if (path === "costs/summary") return Response.json({ spendCents: 4217, budgetCents: 20000, utilizationPercent: 21, pricingComplete: true, eventCount: 74, estimatedEventCount: 12, unpricedEventCount: 0, pendingRunCount: 0 });
+ if (path === "costs/summary") return Response.json({ spendCents: 4217, budgetCents: 20000, utilizationPercent: 21, pricingComplete: !costGaps, eventCount: 74, estimatedEventCount: 12, unpricedEventCount: costGaps ? 2 : 0, pendingRunCount: costGaps ? details.runs.length : 0, unknownBillingEventCount: costGaps ? 1 : 0 });
if (path === "costs/by-agent") return Response.json([
{ agentId: "codie", agentName: "Codie", agentStatus: "active", costCents: 4217, inputTokens: 12000000, cachedInputTokens: 56200000, outputTokens: 1000000, eventCount: 54, estimatedEventCount: 12, apiRunCount: 24, subscriptionRunCount: 30 },
{ agentId: "fry", agentName: "Fry", agentStatus: "active", costCents: 0, inputTokens: 2000000, cachedInputTokens: 10000000, outputTokens: 200000, eventCount: 10, estimatedEventCount: 0, apiRunCount: 0, subscriptionRunCount: 10 },
@@ -75,10 +94,10 @@ function SubscriptionCostsStory({ unknownPrice = false, stale = false }: { unkno
if (path.startsWith("costs/")) return Response.json([]);
return original(input, init);
};
- client.removeQueries({ queryKey: ["cost-subscriptions"] }); setReady(true);
- return () => { window.fetch = original; client.removeQueries({ queryKey: ["cost-subscriptions"] }); };
- }, [client, unknownPrice, stale]);
- return ready ? <Costs embedded hideBudgetsTab /> : null;
+ client.removeQueries({ queryKey: ["cost-subscriptions"] }); client.removeQueries({ queryKey: ["costs"] }); setReady(true);
+ return () => { window.fetch = original; client.removeQueries({ queryKey: ["cost-subscriptions"] }); client.removeQueries({ queryKey: ["costs"] }); };
+ }, [client, unknownPrice, stale, costGaps]);
+ return ready ? <><Costs embedded hideBudgetsTab /><ToastViewport /></> : null;
}
const meta = { title: "Costs/Subscriptions", component: SubscriptionCostsStory, parameters: {
@@ -90,6 +109,8 @@ export const Overview: Story = { play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(await canvas.findByText("API spend")).toBeVisible();
await expect(await canvas.findByText("$120.00")).toBeVisible();
+ await expect(canvas.queryByRole("button", { name: "12 estimated charges" })).not.toBeInTheDocument();
+ await expect(canvas.queryByText(/Includes 12 estimated charges/)).not.toBeInTheDocument();
} };
export const AccountDetails: Story = { play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
@@ -101,3 +122,21 @@ export const AccountDetails: Story = { play: async ({ canvasElement }) => {
export const UnknownPrice: Story = { args: { unknownPrice: true } };
export const ProviderUnavailable: Story = { args: { stale: true } };
export const Mobile: Story = { globals: { viewport: { value: "mobile1", isRotated: false } } };
+export const CostDataQuality: Story = { args: { costGaps: true }, play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(await canvas.findByRole("button", { name: "5 run costs unavailable" })).toHaveAttribute("aria-expanded", "false");
+ await expect(canvas.queryByText(/Includes 12 estimated charges/)).not.toBeInTheDocument();
+} };
+export const CostDataQualityDetails: Story = { args: { costGaps: true }, play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(await canvas.findByRole("button", { name: "5 run costs unavailable" }));
+ await expect(await canvas.findByText("Model not reported")).toBeVisible();
+ await expect(await canvas.findByRole("button", { name: "Retry cost recording" })).toBeVisible();
+ const groups = canvas.getByRole("list", { name: "Cost details by agent" });
+ await expect(within(groups).getAllByRole("heading").map(heading => heading.textContent)).toEqual(["Codie", "Fry", "Leela"]);
+ await expect(canvas.getAllByRole("link", { name: "View run" })).toHaveLength(6);
+ await expect(within(groups).getAllByRole("link", { name: /^(Codie|Fry|Leela)$/ })).toHaveLength(3);
+ await expect(canvas.queryByRole("link", { name: "Configuration" })).not.toBeInTheDocument();
+ await expect(canvas.queryByText("Totals include known charges only.")).not.toBeInTheDocument();
+ await expect(canvas.queryByText(/Includes 12 estimated charges/)).not.toBeInTheDocument();
+} };