Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(usage): disambiguate model pricing by provider (MUL-3346)
YYClawda4f278330fb
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 2d79b25c53..95042ea565 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -279,6 +279,20 @@ describe("dashboard + runtime usage schema drift", () => {expect(RuntimeUsageByHourListSchema.parse([{ hour: 9 }])[0]?.model).toBe("");});+ it("defaults a missing provider to \"\" so an older server's rows still price by bare model", () => {+ // provider was added for cross-provider model disambiguation; a server+ // predating it omits the field. The schema must fill "" (→ bare-model+ // pricing lookup) rather than drop the row.+ expect(+ DashboardUsageDailyListSchema.parse([{ date: "2026-05-19", model: "claude-opus-4-7" }])[0]+ ?.provider,+ ).toBe("");+ expect(+ DashboardUsageByAgentListSchema.parse([{ model: "claude-opus-4-7" }])[0]?.provider,+ ).toBe("");+ expect(RuntimeUsageByAgentListSchema.parse([{ model: "x" }])[0]?.provider).toBe("");+ });+it("rejects a non-array body so parseWithFallback can return its fallback", () => {expect(DashboardUsageDailyListSchema.safeParse(null).success).toBe(false);expect(RuntimeUsageListSchema.safeParse({ rows: [] }).success).toBe(false);diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex c49f3c3766..52bf28f96b 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -339,6 +339,7 @@ export const EMPTY_CLOUD_RUNTIME_NODE: CloudRuntimeNode = {const DashboardUsageDailySchema = z.object({date: z.string().default(""),+ provider: z.string().default(""),model: z.string().default(""),input_tokens: z.number().default(0),output_tokens: z.number().default(0),@@ -351,6 +352,7 @@ export const DashboardUsageDailyListSchema = z.array(DashboardUsageDailySchema);const DashboardUsageByAgentSchema = z.object({agent_id: z.string().default(""),+ provider: z.string().default(""),model: z.string().default(""),input_tokens: z.number().default(0),output_tokens: z.number().default(0),@@ -408,6 +410,7 @@ export const RuntimeHourlyActivityListSchema = z.array(RuntimeHourlyActivityScheconst RuntimeUsageByAgentSchema = z.object({agent_id: z.string().default(""),+ provider: z.string().default(""),model: z.string().default(""),input_tokens: z.number().default(0),output_tokens: z.number().default(0),diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 62fba76487..1700aa593e 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -542,12 +542,14 @@ export interface RuntimeHourlyActivity {count: number;}-// One (agent, model) row of the "Cost by agent" tab on the runtime detail-// page. Model stays on the wire because cost is computed client-side from-// a per-model pricing table — the client groups these rows by agent_id and-// sums cost per agent across models.+// One (agent, provider, model) row of the "Cost by agent" tab on the runtime+// detail page. provider + model stay on the wire because cost is computed+// client-side from a per-model pricing table (provider disambiguates bare+// model ids that collide across providers) — the client groups these rows by+// agent_id and sums cost per agent across models.export interface RuntimeUsageByAgent {agent_id: string;+ provider: string;model: string;input_tokens: number;output_tokens: number;@@ -569,12 +571,15 @@ export interface RuntimeUsageByHour {task_count: number;}-// One (date, model) bucket of token usage for the workspace dashboard.-// Same shape as RuntimeUsage but workspace-scoped (no runtime_id, no-// provider field on the wire) and optionally narrowed to a single project-// on the server side. Cost stays client-side via the model pricing table.+// One (date, provider, model) bucket of token usage for the workspace+// dashboard. Workspace-scoped (no runtime_id) and optionally narrowed to a+// single project on the server side. `provider` is kept on the wire so the+// client can disambiguate bare model ids that collide across providers+// (e.g. Cursor's `auto` vs another provider's `auto`) when pricing. Cost+// stays client-side via the model pricing table.export interface DashboardUsageDaily {date: string;+ provider: string;model: string;input_tokens: number;output_tokens: number;@@ -588,6 +593,7 @@ export interface DashboardUsageDaily {// sums cost.export interface DashboardUsageByAgent {agent_id: string;+ provider: string;model: string;input_tokens: number;output_tokens: number;diff --git a/packages/views/dashboard/utils.test.ts b/packages/views/dashboard/utils.test.tsindex 6aac9de0bd..f9ca6b2afa 100644--- a/packages/views/dashboard/utils.test.ts+++ b/packages/views/dashboard/utils.test.ts@@ -14,6 +14,7 @@ describe("aggregateDailyCost", () => {const result = aggregateDailyCost([{date: "2026-05-10",+ provider: "claude",model: "claude-sonnet-4-6",input_tokens: 1_000_000,output_tokens: 500_000,@@ -23,6 +24,7 @@ describe("aggregateDailyCost", () => {},{date: "2026-05-09",+ provider: "claude",model: "claude-sonnet-4-6",input_tokens: 1_000_000,output_tokens: 0,@@ -45,6 +47,7 @@ describe("aggregateDailyCost", () => {const result = aggregateDailyCost([{date: "2026-05-10",+ provider: "claude",model: "made-up-model",input_tokens: 999_999_999,output_tokens: 0,@@ -62,6 +65,7 @@ describe("aggregateAgentTokens", () => {const rows = aggregateAgentTokens([{agent_id: "small-spender",+ provider: "claude",model: "claude-sonnet-4-6",input_tokens: 100_000,output_tokens: 0,@@ -71,6 +75,7 @@ describe("aggregateAgentTokens", () => {},{agent_id: "big-spender",+ provider: "claude",model: "claude-sonnet-4-6",input_tokens: 5_000_000,output_tokens: 0,@@ -80,6 +85,7 @@ describe("aggregateAgentTokens", () => {},{agent_id: "big-spender",+ provider: "claude",model: "claude-haiku-4-5",input_tokens: 1_000_000,output_tokens: 0,@@ -101,6 +107,7 @@ describe("computeDailyTotals", () => {const totals = computeDailyTotals([{date: "2026-05-10",+ provider: "claude",model: "claude-sonnet-4-6",input_tokens: 1_000_000,output_tokens: 0,@@ -110,6 +117,7 @@ describe("computeDailyTotals", () => {},{date: "2026-05-09",+ provider: "claude",model: "claude-sonnet-4-6",input_tokens: 2_000_000,output_tokens: 0,diff --git a/packages/views/runtimes/components/custom-pricing-dialog.tsx b/packages/views/runtimes/components/custom-pricing-dialog.tsxindex b2dd8200dc..5cd6b8debb 100644--- a/packages/views/runtimes/components/custom-pricing-dialog.tsx+++ b/packages/views/runtimes/components/custom-pricing-dialog.tsx@@ -86,8 +86,8 @@ export function CustomPricingDialog({ open, onOpenChange, unmappedModels }: PropuseEffect(() => {if (!open) return;const fresh: Record<string, DraftRow> = {};- for (const model of rows) {- fresh[model] = toDraft(pricings[model]);+ for (const key of rows) {+ fresh[key] = toDraft(pricings[key]);}setDrafts(fresh);// We intentionally don't depend on `rows` (a new array each render) —@@ -96,16 +96,16 @@ export function CustomPricingDialog({ open, onOpenChange, unmappedModels }: Prop// eslint-disable-next-line react-hooks/exhaustive-deps}, [open, rows.join("\n")]);- const updateField = (model: string, field: keyof DraftRow, value: string) => {+ const updateField = (key: string, field: keyof DraftRow, value: string) => {setDrafts((d) => ({...d,- [model]: { ...(d[model] ?? EMPTY_DRAFT), [field]: value },+ [key]: { ...(d[key] ?? EMPTY_DRAFT), [field]: value },}));};const handleSave = () => {- for (const model of rows) {- const draft = drafts[model] ?? EMPTY_DRAFT;+ for (const key of rows) {+ const draft = drafts[key] ?? EMPTY_DRAFT;const parsed = parseRow(draft);const allEmpty =draft.input.trim() === "" &&@@ -114,10 +114,10 @@ export function CustomPricingDialog({ open, onOpenChange, unmappedModels }: Propdraft.cacheWrite.trim() === "";if (allEmpty) {// Treat clearing every field as "remove this override".- if (pricings[model]) removeCustomPricing(model);+ if (pricings[key]) removeCustomPricing(key);continue;}- if (parsed) setCustomPricing(model, parsed);+ if (parsed) setCustomPricing(key, parsed);}onOpenChange(false);};@@ -138,19 +138,19 @@ export function CustomPricingDialog({ open, onOpenChange, unmappedModels }: Prop{t(($) => $.usage.custom_pricing.empty)}</p>) : (- rows.map((model) => {- const draft = drafts[model] ?? EMPTY_DRAFT;- const hasOverride = Boolean(pricings[model]);+ rows.map((key) => {+ const draft = drafts[key] ?? EMPTY_DRAFT;+ const hasOverride = Boolean(pricings[key]);return (- <div key={model} className="space-y-2 rounded-md border p-3">+ <div key={key} className="space-y-2 rounded-md border p-3"><div className="flex items-center justify-between gap-2">- <code className="truncate font-mono text-xs">{model}</code>+ <code className="truncate font-mono text-xs">{key}</code>{hasOverride && (<Buttontype="button"variant="ghost"size="icon-xs"- onClick={() => removeCustomPricing(model)}+ onClick={() => removeCustomPricing(key)}aria-label={t(($) => $.usage.custom_pricing.remove_aria)}title={t(($) => $.usage.custom_pricing.remove_aria)}>@@ -162,22 +162,22 @@ export function CustomPricingDialog({ open, onOpenChange, unmappedModels }: Prop<PriceFieldlabel={t(($) => $.usage.custom_pricing.field_input)}value={draft.input}- onChange={(v) => updateField(model, "input", v)}+ onChange={(v) => updateField(key, "input", v)}/><PriceFieldlabel={t(($) => $.usage.custom_pricing.field_output)}value={draft.output}- onChange={(v) => updateField(model, "output", v)}+ onChange={(v) => updateField(key, "output", v)}/><PriceFieldlabel={t(($) => $.usage.custom_pricing.field_cache_read)}value={draft.cacheRead}- onChange={(v) => updateField(model, "cacheRead", v)}+ onChange={(v) => updateField(key, "cacheRead", v)}/><PriceFieldlabel={t(($) => $.usage.custom_pricing.field_cache_write)}value={draft.cacheWrite}- onChange={(v) => updateField(model, "cacheWrite", v)}+ onChange={(v) => updateField(key, "cacheWrite", v)}/></div></div>diff --git a/packages/views/runtimes/utils.test.ts b/packages/views/runtimes/utils.test.tsindex f9140fb158..37fae3c472 100644--- a/packages/views/runtimes/utils.test.ts+++ b/packages/views/runtimes/utils.test.ts@@ -264,9 +264,12 @@ describe("estimateCost", () => {});it("prices Cursor Composer rows at the published rates without cache-write spend", () => {+ // Cursor's ids are unprefixed generic names, so they're provider-qualified+ // (`cursor/auto`) and only resolve when the row carries provider "cursor".const costWithAllTokenTypes = (model: string) =>estimateCost({...zeroUsage,+ provider: "cursor",model,input_tokens: 1_000_000,output_tokens: 1_000_000,@@ -293,9 +296,34 @@ describe("estimateCost", () => {1.25 + 10 + 0.125,5,);+ // The legacy `cursor` fallback equals the provider name, so it stays+ // unqualified and resolves regardless of the row's provider.expect(costWithAllTokenTypes("cursor")).toBeCloseTo(3 + 15 + 0.5, 5);});+ it("scopes the generic `auto` id by provider so collisions don't borrow a price", () => {+ const auto = (provider?: string) =>+ estimateCost({ ...zeroUsage, provider, model: "auto", input_tokens: 1_000_000 });++ // Cursor's `auto` is priced via the `cursor/auto` row.+ expect(auto("cursor")).toBeCloseTo(1.25, 5);+ // A different provider reporting `auto` has no row+ // yet — it must NOT inherit Cursor's price; it stays unmapped ($0).+ expect(auto("acme")).toBe(0);+ // No provider at all → also unmapped, never silently Cursor's price.+ expect(auto(undefined)).toBe(0);+ });++ it("reports provider-qualified keys for unmapped generic model ids", () => {+ const unmapped = collectUnmappedModels([+ { ...zeroUsage, provider: "acme", model: "auto" },+ { ...zeroUsage, provider: "cursor", model: "auto" },+ ]);+ // Same bare id, two providers → two distinct, priceable-by-key entries.+ // `cursor/auto` is priced, so only the genuinely-unmapped one surfaces.+ expect(unmapped).toEqual(["acme/auto"]);+ });+// The Chinese-model rates below are spot-checked against the literal// numbers on the three official price sheets cited in MODEL_PRICING's// header comment. Pinning them in tests is what catches a future edit@@ -494,6 +522,23 @@ describe("user-supplied custom pricing", () => {).toBeCloseTo(2, 5);});+ it("resolves a provider-qualified override only for the matching provider", () => {+ // The dialog stores the override under the provider-qualified key that+ // `collectUnmappedModels` surfaced, so it must price a provider-scoped+ // `auto` row without leaking onto another provider's `auto`.+ useCustomPricingStore.getState().setCustomPricing("acme/auto", {+ input: 2,+ output: 8,+ cacheRead: 0.2,+ cacheWrite: 2,+ });+ expect(+ estimateCost({ ...zeroUsage, provider: "acme", model: "auto", input_tokens: 1_000_000 }),+ ).toBeCloseTo(2, 5);+ // A row with no provider must not pick up the provider-scoped override.+ expect(isModelPriced("auto")).toBe(false);+ });+it("removeCustomPricing clears the override", () => {const store = useCustomPricingStore.getState();store.setCustomPricing("gpt-5.5-mini", {@@ -532,12 +577,31 @@ describe("user-supplied custom pricing", () => {];// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst byModel = aggregateCostByModel(rows as any);+ // Priced vendor-prefixed id stays bare; the unmapped generic id is+ // provider-qualified so it matches the unmapped notice / pricing dialog.const sonnet = byModel.find((r) => r.key === "claude-sonnet-4-6");- const fictional = byModel.find((r) => r.key === "fictional-model-x");+ const fictional = byModel.find((r) => r.key === "fictional/fictional-model-x");expect(sonnet?.cost).toBeCloseTo(3, 5);expect(fictional?.cost).toBe(0);+ // The unmapped key is provider-qualified so a user can price this exact+ // (provider, model) pair without affecting another provider's same id.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ expect(collectUnmappedModels(rows as any)).toEqual(["fictional/fictional-model-x"]);+ });++ it("keeps the same generic model id from two providers as distinct by-model rows", () => {+ // Two providers reporting the bare id `auto` must not collapse into one+ // mislabelled `auto` row — each is provider-qualified so the priced+ // (cursor) and unpriced (other) sides stay separable.+ const rows = [+ { ...zeroUsage, model: "auto", provider: "cursor", input_tokens: 1_000_000, date: "2026-01-01" },+ { ...zeroUsage, model: "auto", provider: "acme", input_tokens: 1_000_000, date: "2026-01-01" },+ ];// eslint-disable-next-line @typescript-eslint/no-explicit-any- expect(collectUnmappedModels(rows as any)).toEqual(["fictional-model-x"]);+ const byModel = aggregateCostByModel(rows as any);+ expect(byModel.map((r) => r.key).toSorted()).toEqual(["acme/auto", "cursor/auto"]);+ expect(byModel.find((r) => r.key === "cursor/auto")?.cost).toBeCloseTo(1.25, 5);+ expect(byModel.find((r) => r.key === "acme/auto")?.cost).toBe(0);});it("aggregateCostByModel reflects a newly-saved custom price on re-call with the same input", () => {diff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.tsindex 8ba30376c9..6ccae37519 100644--- a/packages/views/runtimes/utils.ts+++ b/packages/views/runtimes/utils.ts@@ -147,6 +147,14 @@ export function formatTokens(n: number): string {// inheriting the price of a near-named relative; they surface in the// unmapped diagnostic instead. Mirror new entries in// `server/pkg/agent/models.go` so the catalog and pricing stay in sync.+//+// Provider-qualified keys: a model id that is NOT vendor-prefixed+// (`claude-*`, `gpt-*`, `o3*`/`o4*`, `glm-*`, `deepseek-*`, `kimi-*`) and is+// not the provider name itself can collide across providers — more than one+// provider may report the same generic id like `auto`. Such generic ids MUST be keyed as+// `${provider}/${model}` (e.g. `cursor/auto`). `resolvePricing` tries the+// `${provider}/…` form first, then the bare form, so vendor-prefixed SKUs+// stay unqualified and still resolve.const MODEL_PRICING: Record<string,{ input: number; output: number; cacheRead: number; cacheWrite: number }@@ -232,20 +240,26 @@ const MODEL_PRICING: Record<// -- Cursor Composer / Auto (cursor.com/docs/models-and-pricing,// cursor.com/docs/models/cursor-composer-2,// cursor.com/docs/models/cursor-composer-2-5).- // Cursor result events often omit `model`, so the daemon falls back to- // the configured runtime model or the legacy key `cursor`.- // Cursor does not publish a cache-write rate for these rows; keep it at- // 0 so reported cache_write_tokens don't invent spend from input pricing.- "auto": { input: 1.25, output: 6, cacheRead: 0.25, cacheWrite: 0 },- "composer-2.5-fast": { input: 3, output: 15, cacheRead: 0.5, cacheWrite: 0 },- "composer-2.5": { input: 0.5, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },- "composer-2-fast": { input: 1.5, output: 7.5, cacheRead: 0.35, cacheWrite: 0 },- "composer-2": { input: 0.5, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },- "composer-1.5": { input: 3.5, output: 17.5, cacheRead: 0.35, cacheWrite: 0 },- "composer-1": { input: 1.25, output: 10, cacheRead: 0.125, cacheWrite: 0 },+ // Cursor's model ids are all unprefixed generic names (`auto`,+ // `composer-*`) that collide with other providers (another provider+ // could also report `auto`), so they are provider-qualified under `cursor/`.+ // See the `provider-qualified keys` note above. Cursor result events+ // often omit `model`, so the daemon falls back to the configured+ // runtime model or the legacy key `cursor`. Cursor does not publish a+ // cache-write rate for these rows; keep it at 0 so reported+ // cache_write_tokens don't invent spend from input pricing.+ "cursor/auto": { input: 1.25, output: 6, cacheRead: 0.25, cacheWrite: 0 },+ "cursor/composer-2.5-fast": { input: 3, output: 15, cacheRead: 0.5, cacheWrite: 0 },+ "cursor/composer-2.5": { input: 0.5, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },+ "cursor/composer-2-fast": { input: 1.5, output: 7.5, cacheRead: 0.35, cacheWrite: 0 },+ "cursor/composer-2": { input: 0.5, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },+ "cursor/composer-1.5": { input: 3.5, output: 17.5, cacheRead: 0.35, cacheWrite: 0 },+ "cursor/composer-1": { input: 1.25, output: 10, cacheRead: 0.125, cacheWrite: 0 },// Legacy fallback bucket when neither the result event nor the runtime- // model is known — price at the current Composer 2.5 Fast default.- "cursor": { input: 3, output: 15, cacheRead: 0.5, cacheWrite: 0 },+ // model is known — the daemon emits the literal `cursor`. This key equals+ // the provider name itself, so it can't collide across providers and stays+ // unqualified. Price at the current Composer 2.5 Fast default.+ "cursor": { input: 3, output: 15, cacheRead: 0.5, cacheWrite: 0 },};// Resolve a model string to its pricing tier. Exact match, with four@@ -272,24 +286,99 @@ const MODEL_PRICING: Record<// Anything still unmapped falls back to the user-supplied custom pricing// store. No startsWith fallback: variants like `gpt-5.5-mini` must have// their own row to be priced (otherwise they'd inherit `gpt-5.5`).-function resolvePricing(model: string) {+//+// `provider` disambiguates unprefixed generic ids (see the header note):+// every candidate is tried `${provider}/…`-qualified first, then bare, so a+// `cursor/auto` row wins for a Cursor row while an unqualified `auto` (no+// provider) stays unmapped instead of silently borrowing Cursor's price.+function resolvePricing(model: string, provider?: string) {if (!model) return undefined;- for (const candidate of canonicalCandidates(model)) {+ const candidates = pricingCandidates(model, provider);+ for (const candidate of candidates) {const hit = MODEL_PRICING[candidate];if (hit) return hit;}- for (const candidate of canonicalCandidates(model)) {+ for (const candidate of candidates) {const hit = getCustomPricing(candidate);if (hit) return hit;}return undefined;}+// Canonical provider token for keying: trimmed + lowercased so lookup keys,+// storage keys, and grouping labels all tolerate case drift in the stored+// value. Returns "" when no provider is known.+function normalizeProvider(provider?: string): string {+ return provider?.trim().toLowerCase() ?? "";+}++// Provider-qualify a key, skipping the prefix when the key already carries+// this provider (an upstream-qualified `cursor/auto` must not become+// `cursor/cursor/auto`). `provider` must already be normalized.+function qualify(provider: string, key: string): string {+ return key.startsWith(`${provider}/`) ? key : `${provider}/${key}`;+}++// Lookup keys for a (model, provider) pair: every canonical candidate+// `${provider}/`-qualified first (when a provider is known), then the bare+// candidates. Qualified-first means a provider-scoped row/override always+// beats an unqualified one.+function pricingCandidates(model: string, provider?: string): string[] {+ const base = canonicalCandidates(model);+ const p = normalizeProvider(provider);+ if (!p) return base;+ return [...base.map((c) => qualify(p, c)), ...base];+}++// The canonical storage/diagnostic key for a (model, provider) pair: the+// provider-qualified form when a provider is known, else the bare model.+// `collectUnmappedModels` returns these, and the custom-pricing dialog keys+// overrides by them, so a user-entered rate for `cursor/auto` resolves only+// for Cursor rows — not for another provider that also reports `auto`.+// Provider is lowercased so lookups tolerate case drift in the stored value.+export function pricingKey(model: string, provider?: string): string {+ const p = normalizeProvider(provider);+ return p ? qualify(p, model) : model;+}++// Display/grouping key for a usage row's model. Self-resolving ids+// (vendor-prefixed SKUs like `claude-opus-4-7`, and the legacy `cursor`+// fallback whose key equals the provider name) stay bare; a generic id that+// only prices under a provider (`auto`, `composer-*`) is provider-qualified+// so two providers reporting the same bare id don't merge into one mislabelled+// row, and the label matches what `collectUnmappedModels` / the pricing dialog+// surface.+export function modelGroupingKey(model: string, provider?: string): string {+ if (!model) return normalizeProvider(provider) || "unknown";+ return isSelfResolvingId(model) ? model : pricingKey(model, provider);+}++// Whether a model id prices on its own without a provider qualifier (a+// vendor-prefixed SKU, or the legacy `cursor` fallback). Such ids keep a bare+// grouping key; generic ids (`auto`, `composer-*`) stay provider-qualified.+//+// Probes the BARE model on purpose: forwarding a provider would let a+// qualified row report as self-resolving and collapse back to a bare key,+// re-merging the cross-provider collision this scheme prevents. Keep the+// argument list provider-free so that stays true.+function isSelfResolvingId(model: string): boolean {+ return isModelPriced(model);+}+// Generate the lookup candidates for a model string, in priority order:// the raw string first (preserves explicit user / catalog spellings),// then the canonicalized forms. Deduped so we don't repeat lookups.+//+// Pure in `model`, and the aggregation loops call it 3-4x per row, so the+// result is memoized — the model-string set is small and bounded. Callers+// only read the array (pricingCandidates maps/spreads into a fresh one), so+// sharing the cached reference is safe.+// Intentionally process-lifetime: never evicted (bounded key set, see above).+const canonicalCandidatesCache = new Map<string, string[]>();function canonicalCandidates(model: string): string[] {+ const cached = canonicalCandidatesCache.get(model);+ if (cached) return cached;const seen = new Set<string>();const out: string[] = [];const push = (s: string) => {@@ -325,23 +414,28 @@ function canonicalCandidates(model: string): string[] {push(stripDate(noProvider));push(stripDate(dashed));push(stripDate(noTag));+ canonicalCandidatesCache.set(model, out);return out;}// Cheap predicate for the empty-state diagnostic: which model strings in a// usage batch failed pricing resolution. Useful when the user is staring at// "$0.00 / 2M tokens" and wants to know why.-export function isModelPriced(model: string): boolean {- return resolvePricing(model) !== undefined;+export function isModelPriced(model: string, provider?: string): boolean {+ return resolvePricing(model, provider) !== undefined;}-// Returns the unique, sorted list of model strings present in `rows` that-// don't resolve to a price. Empty when everything's priced or there are no-// rows.+// Returns the unique, sorted list of pricing keys present in `rows` that+// don't resolve to a price. Keys are provider-qualified (`cursor/auto`) when+// the row carries a provider, so the same bare model id reported by two+// providers surfaces as two distinct entries the user can price separately.+// Empty when everything's priced or there are no rows.export function collectUnmappedModels(rows: readonly Priceable[]): string[] {const set = new Set<string>();for (const r of rows) {- if (r.model && !isModelPriced(r.model)) set.add(r.model);+ if (r.model && !isModelPriced(r.model, r.provider)) {+ set.add(pricingKey(r.model, r.provider));+ }}return Array.from(set).toSorted();}@@ -350,13 +444,17 @@ export function collectUnmappedModels(rows: readonly Priceable[]): string[] {// RuntimeUsageByAgent, RuntimeUsageByHour all share this shape on purpose// (the back-end keeps the model dimension specifically so the client can// run this calculation for any aggregation axis).+// `provider` is optional so callers with provider-less rows (and existing+// test fixtures) still type-check; when present it disambiguates generic+// model ids during pricing. RuntimeUsage / RuntimeUsageByAgent /+// DashboardUsageDaily / DashboardUsageByAgent all carry it on the wire.type Priceable = Pick<RuntimeUsage,"model" | "input_tokens" | "output_tokens" | "cache_read_tokens" | "cache_write_tokens"->;+> & { provider?: string };export function estimateCost(usage: Priceable): number {- const pricing = resolvePricing(usage.model);+ const pricing = resolvePricing(usage.model, usage.provider);if (!pricing) return 0;return ((usage.input_tokens * pricing.input +@@ -375,7 +473,7 @@ export interface CostBreakdown {}export function estimateCostBreakdown(usage: Priceable): CostBreakdown {- const pricing = resolvePricing(usage.model);+ const pricing = resolvePricing(usage.model, usage.provider);if (!pricing) {return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };}@@ -391,7 +489,7 @@ export function estimateCostBreakdown(usage: Priceable): CostBreakdown {// minus what they actually cost at the discounted cache-hit rate. This is a// reconstruction of "money the cache saved you", not real-world spend.export function estimateCacheSavings(usage: Priceable): number {- const pricing = resolvePricing(usage.model);+ const pricing = resolvePricing(usage.model, usage.provider);if (!pricing) return 0;const wouldHaveCost = (usage.cache_read_tokens * pricing.input) / 1_000_000;const actualCost = (usage.cache_read_tokens * pricing.cacheRead) / 1_000_000;@@ -508,7 +606,7 @@ export function aggregateByDate(usage: RuntimeUsage[]): {stack.cacheWrite += breakdown.cacheWrite;stackMap.set(u.date, stack);- const modelName = u.model || u.provider;+ const modelName = modelGroupingKey(u.model, u.provider);const m = modelMap.get(modelName) ?? { tokens: 0, cost: 0 };m.tokens +=u.input_tokens + u.output_tokens + u.cache_read_tokens + u.cache_write_tokens;@@ -582,7 +680,7 @@ type WeeklyAggregable = Pick<| "output_tokens"| "cache_read_tokens"| "cache_write_tokens"->;+> & { provider?: string };export function aggregateByWeek(usage: readonly WeeklyAggregable[],@@ -803,7 +901,7 @@ export function aggregateCostByAgent(rows: RuntimeUsageByAgent[]): CostByKey[] {export function aggregateCostByModel(rows: RuntimeUsage[]): CostByKey[] {const map = new Map<string, CostByKey>();for (const r of rows) {- const key = r.model || r.provider || "unknown";+ const key = modelGroupingKey(r.model, r.provider);const entry = map.get(key) ?? { key, tokens: 0, cost: 0, taskCount: 0 };entry.tokens +=r.input_tokens + r.output_tokens + r.cache_read_tokens + r.cache_write_tokens;diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex abea25ad45..23ccf78b26 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -255,6 +255,13 @@ func workspaceReposResponse(workspaceID string, raw []byte, settingsRaw []byte)return resp}+// normalizeProvider canonicalizes a provider string for storage: trimmed and+// lowercased so client-side pricing lookups tolerate case drift. Returns "" for+// a blank input.+func normalizeProvider(s string) string {+ return strings.ToLower(strings.TrimSpace(s))+}+func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {var req DaemonRegisterRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {@@ -311,7 +318,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {resp := make([]AgentRuntimeResponse, 0, len(req.Runtimes))for _, runtime := range req.Runtimes {- provider := strings.TrimSpace(runtime.Type)+ provider := normalizeProvider(runtime.Type)if provider == "" {provider = "unknown"}@@ -2071,10 +2078,29 @@ func (h *Handler) ReportTaskUsage(w http.ResponseWriter, r *http.Request) {return}+ // Provider is lowercased on write so client-side pricing lookups tolerate+ // case drift. An empty provider (an older daemon that omits the field) is+ // stamped from the task's runtime, so generic model ids like `auto` still+ // resolve to a provider instead of landing as '' and pricing $0.+ var runtimeProvider string+ runtimeProviderLoaded := falsefor _, u := range req.Usage {+ provider := normalizeProvider(u.Provider)+ if provider == "" {+ if !runtimeProviderLoaded {+ if rt, err := h.Queries.GetAgentRuntime(r.Context(), task.RuntimeID); err == nil {+ runtimeProvider = normalizeProvider(rt.Provider)+ } else {+ slog.Warn("load runtime provider for usage backfill failed",+ "task_id", taskID, "runtime_id", uuidToString(task.RuntimeID), "error", err)+ }+ runtimeProviderLoaded = true+ }+ provider = runtimeProvider+ }if err := h.Queries.UpsertTaskUsage(r.Context(), db.UpsertTaskUsageParams{TaskID: parseUUID(taskID),- Provider: u.Provider,+ Provider: provider,Model: u.Model,InputTokens: u.InputTokens,OutputTokens: u.OutputTokens,@@ -2084,7 +2110,7 @@ func (h *Handler) ReportTaskUsage(w http.ResponseWriter, r *http.Request) {slog.Warn("upsert task usage failed", "task_id", taskID, "model", u.Model, "error", err)continue}- h.TaskService.CaptureTaskUsage(r.Context(), task, u.Provider, u.Model, u.InputTokens, u.OutputTokens, u.CacheReadTokens, u.CacheWriteTokens)+ h.TaskService.CaptureTaskUsage(r.Context(), task, provider, u.Model, u.InputTokens, u.OutputTokens, u.CacheReadTokens, u.CacheWriteTokens)}writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})diff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.goindex 679c5a310d..d3f44af875 100644--- a/server/internal/handler/dashboard.go+++ b/server/internal/handler/dashboard.go@@ -51,11 +51,13 @@ func parseProjectIDParam(w http.ResponseWriter, r *http.Request) (pgtype.UUID, breturn u, true}-// DashboardUsageDailyResponse is one (date, model) bucket. Cost-side math-// happens on the client from a per-model pricing table; model stays on the-// wire for that reason.+// DashboardUsageDailyResponse is one (date, provider, model) bucket. Cost-side+// math happens on the client from a per-model pricing table; provider + model+// stay on the wire so the client can disambiguate bare model ids that collide+// across providers (e.g. Cursor's `auto`).type DashboardUsageDailyResponse struct {Date string `json:"date"`+ Provider string `json:"provider"`Model string `json:"model"`InputTokens int64 `json:"input_tokens"`OutputTokens int64 `json:"output_tokens"`@@ -107,6 +109,7 @@ func (h *Handler) listDashboardUsageDaily(for i, row := range rows {resp[i] = DashboardUsageDailyResponse{Date: row.Date.Time.Format("2006-01-02"),+ Provider: row.Provider,Model: row.Model,InputTokens: row.InputTokens,OutputTokens: row.OutputTokens,@@ -118,9 +121,12 @@ func (h *Handler) listDashboardUsageDaily(return resp, nil}-// DashboardUsageByAgentResponse is one (agent, model) row.+// DashboardUsageByAgentResponse is one (agent, provider, model) row. provider+// rides along for the same cross-provider pricing disambiguation as the daily+// response; the client folds by agent_id and sums cost.type DashboardUsageByAgentResponse struct {AgentID string `json:"agent_id"`+ Provider string `json:"provider"`Model string `json:"model"`InputTokens int64 `json:"input_tokens"`OutputTokens int64 `json:"output_tokens"`@@ -172,6 +178,7 @@ func (h *Handler) listDashboardUsageByAgent(for i, row := range rows {resp[i] = DashboardUsageByAgentResponse{AgentID: uuidToString(row.AgentID),+ Provider: row.Provider,Model: row.Model,InputTokens: row.InputTokens,OutputTokens: row.OutputTokens,diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 6ed4a16dad..2b08ddcd69 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -188,12 +188,14 @@ func (h *Handler) GetRuntimeTaskActivity(w http.ResponseWriter, r *http.Request)writeJSON(w, http.StatusOK, resp)}-// RuntimeUsageByAgentResponse is one (agent, model) row of "Cost by agent".-// Model stays on the wire because cost is computed client-side from a model-// pricing table, intentionally not stored server-side so pricing changes-// don't require a back-fill. The client groups by agent_id and sums.+// RuntimeUsageByAgentResponse is one (agent, provider, model) row of "Cost by+// agent". provider + model stay on the wire because cost is computed+// client-side from a model pricing table (intentionally not stored server-side+// so pricing changes don't require a back-fill); provider disambiguates bare+// model ids that collide across providers. The client groups by agent_id and sums.type RuntimeUsageByAgentResponse struct {AgentID string `json:"agent_id"`+ Provider string `json:"provider"`Model string `json:"model"`InputTokens int64 `json:"input_tokens"`OutputTokens int64 `json:"output_tokens"`@@ -239,6 +241,7 @@ func (h *Handler) GetRuntimeUsageByAgent(w http.ResponseWriter, r *http.Request)for i, row := range rows {resp[i] = RuntimeUsageByAgentResponse{AgentID: uuidToString(row.AgentID),+ Provider: row.Provider,Model: row.Model,InputTokens: row.InputTokens,OutputTokens: row.OutputTokens,diff --git a/server/internal/handler/runtime_test.go b/server/internal/handler/runtime_test.goindex 30ff3af4ee..3cc063f321 100644--- a/server/internal/handler/runtime_test.go+++ b/server/internal/handler/runtime_test.go@@ -9,6 +9,7 @@ import ("time""github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated")func TestRuntimeHandlersRejectMalformedRuntimeID(t *testing.T) {@@ -202,6 +203,86 @@ func TestGetRuntimeUsage_BucketsByUsageTime(t *testing.T) {}}+// TestListRuntimeUsageByAgent_MergesMixedCaseProvider proves the by-agent+// query folds historical mixed-case provider rows (written before the handler+// lowercased provider on write) into a single lowercased bucket via the+// query's LOWER(provider) normalization, instead of splitting them.+func TestListRuntimeUsageByAgent_MergesMixedCaseProvider(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var runtimeID, agentID string+ if err := testPool.QueryRow(ctx, `+ SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1+ `, testWorkspaceID).Scan(&runtimeID); err != nil {+ t.Fatalf("fetch runtime: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1+ `, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("fetch agent: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, creator_id, creator_type)+ VALUES ($1, 'mixed-case provider test', $2, 'member')+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })++ now := time.Now().UTC()+ // Two tasks for the same agent/model under this runtime, reporting the+ // same provider in different casing — 'Cursor' (legacy) and 'cursor' (new).+ insert := func(provider string, input int64) {+ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)+ VALUES ($1, $2, $3, 'completed', $4)+ RETURNING id+ `, agentID, issueID, runtimeID, now).Scan(&taskID); err != nil {+ t.Fatalf("insert task: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)+ VALUES ($1, $2, 'mixed-case-model', $3, 0, $4)+ `, taskID, provider, input, now); err != nil {+ t.Fatalf("insert task_usage: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ }+ insert("Cursor", 1000)+ insert("cursor", 500)++ rows, err := testHandler.Queries.ListRuntimeUsageByAgent(ctx, db.ListRuntimeUsageByAgentParams{+ RuntimeID: parseUUID(runtimeID),+ Since: pgtype.Timestamptz{Time: now.Add(-time.Hour), Valid: true},+ })+ if err != nil {+ t.Fatalf("ListRuntimeUsageByAgent: %v", err)+ }++ var got []db.ListRuntimeUsageByAgentRow+ for _, r := range rows {+ if r.Model == "mixed-case-model" {+ got = append(got, r)+ }+ }+ if len(got) != 1 {+ t.Fatalf("expected mixed-case providers to merge into 1 row, got %d: %+v", len(got), got)+ }+ if got[0].Provider != "cursor" {+ t.Errorf("expected merged provider 'cursor', got %q", got[0].Provider)+ }+ if got[0].InputTokens != 1500 {+ t.Errorf("expected merged input_tokens 1500, got %d", got[0].InputTokens)+ }+}+// TestListRuntimeUsageBucketsByViewerTimezone proves the runtime trend reads// bucket the day boundary in the VIEWER's tz (the argument passed to// listRuntimeUsage). The viewer tz is Asia/Shanghai; assertions only pass ifdiff --git a/server/pkg/db/generated/runtime_usage.sql.go b/server/pkg/db/generated/runtime_usage.sql.goindex 41b5ce7a34..43bd185c58 100644--- a/server/pkg/db/generated/runtime_usage.sql.go+++ b/server/pkg/db/generated/runtime_usage.sql.go@@ -125,7 +125,7 @@ func (q *Queries) GetRuntimeUsageByHour(ctx context.Context, arg GetRuntimeUsageconst listRuntimeUsage = `-- name: ListRuntimeUsage :manySELECTDATE(bucket_hour AT TIME ZONE $2::text) AS date,- provider,+ LOWER(provider) AS provider,model,SUM(input_tokens)::bigint AS input_tokens,SUM(output_tokens)::bigint AS output_tokens,@@ -134,8 +134,8 @@ SELECTFROM task_usage_hourlyWHERE runtime_id = $1AND bucket_hour >= $3::timestamptz-GROUP BY DATE(bucket_hour AT TIME ZONE $2::text), provider, model-ORDER BY DATE(bucket_hour AT TIME ZONE $2::text) DESC, provider, model+GROUP BY DATE(bucket_hour AT TIME ZONE $2::text), LOWER(provider), model+ORDER BY DATE(bucket_hour AT TIME ZONE $2::text) DESC, LOWER(provider), model`type ListRuntimeUsageParams struct {@@ -162,6 +162,9 @@ type ListRuntimeUsageRow struct {// @tz is required, even if the caller intends "UTC", so the bucket// cast is unambiguous — `bucket_hour` is UTC and the caller picks the// calendar boundary per request.+//+// provider is LOWER()-normalized so mixed-case historical rows merge+// (same reason as ListRuntimeUsageByAgent below).func (q *Queries) ListRuntimeUsage(ctx context.Context, arg ListRuntimeUsageParams) ([]ListRuntimeUsageRow, error) {rows, err := q.db.Query(ctx, listRuntimeUsage, arg.RuntimeID, arg.Tz, arg.Since)if err != nil {@@ -193,6 +196,7 @@ func (q *Queries) ListRuntimeUsage(ctx context.Context, arg ListRuntimeUsageParaconst listRuntimeUsageByAgent = `-- name: ListRuntimeUsageByAgent :manySELECTatq.agent_id,+ LOWER(tu.provider) AS provider,tu.model,SUM(tu.input_tokens)::bigint AS input_tokens,SUM(tu.output_tokens)::bigint AS output_tokens,@@ -203,8 +207,8 @@ FROM task_usage tuJOIN agent_task_queue atq ON atq.id = tu.task_idWHERE atq.runtime_id = $1AND tu.created_at >= $2::timestamptz-GROUP BY atq.agent_id, tu.model-ORDER BY atq.agent_id, tu.model+GROUP BY atq.agent_id, LOWER(tu.provider), tu.model+ORDER BY atq.agent_id, LOWER(tu.provider), tu.model`type ListRuntimeUsageByAgentParams struct {@@ -214,6 +218,7 @@ type ListRuntimeUsageByAgentParams struct {type ListRuntimeUsageByAgentRow struct {AgentID pgtype.UUID `json:"agent_id"`+ Provider string `json:"provider"`Model string `json:"model"`InputTokens int64 `json:"input_tokens"`OutputTokens int64 `json:"output_tokens"`@@ -222,7 +227,7 @@ type ListRuntimeUsageByAgentRow struct {TaskCount int32 `json:"task_count"`}-// Per-(agent, model) token aggregates for a runtime since a cutoff. Powers+// Per-(agent, provider, model) token aggregates for a runtime since a cutoff. Powers// the runtime-detail "Cost by agent" tab. task_usage only carries task_id,// so we join the queue to expose agent_id. The model dimension is kept on// purpose: cost is computed client-side from a per-model pricing table, so@@ -231,6 +236,8 @@ type ListRuntimeUsageByAgentRow struct {//// This view doesn't bucket by date, so it doesn't need @tz; only the// @since cutoff is provided in runtime-local terms (computed in Go).+// provider is LOWER()-normalized so mixed-case historical rows merge with+// new rows (see ListDashboardUsageDaily in task_usage.sql).func (q *Queries) ListRuntimeUsageByAgent(ctx context.Context, arg ListRuntimeUsageByAgentParams) ([]ListRuntimeUsageByAgentRow, error) {rows, err := q.db.Query(ctx, listRuntimeUsageByAgent, arg.RuntimeID, arg.Since)if err != nil {@@ -242,6 +249,7 @@ func (q *Queries) ListRuntimeUsageByAgent(ctx context.Context, arg ListRuntimeUsvar i ListRuntimeUsageByAgentRowif err := rows.Scan(&i.AgentID,+ &i.Provider,&i.Model,&i.InputTokens,&i.OutputTokens,diff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.goindex 4dddfa7923..7072831914 100644--- a/server/pkg/db/generated/task_usage.sql.go+++ b/server/pkg/db/generated/task_usage.sql.go@@ -231,6 +231,7 @@ func (q *Queries) ListDashboardRunTimeDaily(ctx context.Context, arg ListDashboaconst listDashboardUsageByAgent = `-- name: ListDashboardUsageByAgent :manySELECTagent_id,+ LOWER(provider) AS provider,model,SUM(input_tokens)::bigint AS input_tokens,SUM(output_tokens)::bigint AS output_tokens,@@ -241,8 +242,8 @@ FROM task_usage_hourlyWHERE workspace_id = $1AND bucket_hour >= $2::timestamptzAND ($3::uuid IS NULL OR project_id = $3)-GROUP BY agent_id, model-ORDER BY agent_id, model+GROUP BY agent_id, LOWER(provider), model+ORDER BY agent_id, LOWER(provider), model`type ListDashboardUsageByAgentParams struct {@@ -253,6 +254,7 @@ type ListDashboardUsageByAgentParams struct {type ListDashboardUsageByAgentRow struct {AgentID pgtype.UUID `json:"agent_id"`+ Provider string `json:"provider"`Model string `json:"model"`InputTokens int64 `json:"input_tokens"`OutputTokens int64 `json:"output_tokens"`@@ -261,7 +263,7 @@ type ListDashboardUsageByAgentRow struct {TaskCount int32 `json:"task_count"`}-// Per-(agent, model) token aggregates from `task_usage_hourly`. No+// Per-(agent, provider, model) token aggregates from `task_usage_hourly`. No// date grouping in the result, so this query takes no `@tz` — the// @since cutoff is a raw timestamptz the Go layer has already computed// in the viewer's tz. Model dimension is preserved so the client can@@ -273,6 +275,8 @@ type ListDashboardUsageByAgentRow struct {// hour the same way the daily version over-counted by day. The// frontend prefers `ListDashboardAgentRunTime` for the user-facing// "tasks" column, so this stays informational only.+// provider is LOWER()-normalized so mixed-case historical rows merge with+// new rows (see ListDashboardUsageDaily).func (q *Queries) ListDashboardUsageByAgent(ctx context.Context, arg ListDashboardUsageByAgentParams) ([]ListDashboardUsageByAgentRow, error) {rows, err := q.db.Query(ctx, listDashboardUsageByAgent, arg.WorkspaceID, arg.Since, arg.ProjectID)if err != nil {@@ -284,6 +288,7 @@ func (q *Queries) ListDashboardUsageByAgent(ctx context.Context, arg ListDashboavar i ListDashboardUsageByAgentRowif err := rows.Scan(&i.AgentID,+ &i.Provider,&i.Model,&i.InputTokens,&i.OutputTokens,@@ -304,6 +309,7 @@ func (q *Queries) ListDashboardUsageByAgent(ctx context.Context, arg ListDashboaconst listDashboardUsageDaily = `-- name: ListDashboardUsageDaily :manySELECTDATE(bucket_hour AT TIME ZONE $2::text) AS date,+ LOWER(provider) AS provider,model,SUM(input_tokens)::bigint AS input_tokens,SUM(output_tokens)::bigint AS output_tokens,@@ -314,8 +320,8 @@ FROM task_usage_hourlyWHERE workspace_id = $1AND bucket_hour >= $3::timestamptzAND ($4::uuid IS NULL OR project_id = $4)-GROUP BY DATE(bucket_hour AT TIME ZONE $2::text), model-ORDER BY DATE(bucket_hour AT TIME ZONE $2::text) DESC, model+GROUP BY DATE(bucket_hour AT TIME ZONE $2::text), LOWER(provider), model+ORDER BY DATE(bucket_hour AT TIME ZONE $2::text) DESC, LOWER(provider), model`type ListDashboardUsageDailyParams struct {@@ -327,6 +333,7 @@ type ListDashboardUsageDailyParams struct {type ListDashboardUsageDailyRow struct {Date pgtype.Date `json:"date"`+ Provider string `json:"provider"`Model string `json:"model"`InputTokens int64 `json:"input_tokens"`OutputTokens int64 `json:"output_tokens"`@@ -335,7 +342,7 @@ type ListDashboardUsageDailyRow struct {TaskCount int32 `json:"task_count"`}-// Daily per-(date, model) token aggregates for the workspace, served+// Daily per-(date, provider, model) token aggregates for the workspace, served// from the UTC-bucketed `task_usage_hourly` table and// sliced to calendar days under the caller-supplied @tz. Optionally// scoped to a single project via sqlc.narg('project_id'). Powers the@@ -349,6 +356,9 @@ type ListDashboardUsageDailyRow struct {// with DATE_TRUNC here — DATE_TRUNC operates in the session tz and would// snap the cutoff back to UTC midnight, dragging in an extra partial// local day for any non-UTC viewer.+// provider is LOWER()-normalized so mixed-case historical rows (written+// before the handler lowercased provider on write) merge with new rows+// instead of forming a separate case-variant bucket.func (q *Queries) ListDashboardUsageDaily(ctx context.Context, arg ListDashboardUsageDailyParams) ([]ListDashboardUsageDailyRow, error) {rows, err := q.db.Query(ctx, listDashboardUsageDaily,arg.WorkspaceID,@@ -365,6 +375,7 @@ func (q *Queries) ListDashboardUsageDaily(ctx context.Context, arg ListDashboardvar i ListDashboardUsageDailyRowif err := rows.Scan(&i.Date,+ &i.Provider,&i.Model,&i.InputTokens,&i.OutputTokens,diff --git a/server/pkg/db/queries/runtime_usage.sql b/server/pkg/db/queries/runtime_usage.sqlindex 70d81c37cc..ea5550eb3d 100644--- a/server/pkg/db/queries/runtime_usage.sql+++ b/server/pkg/db/queries/runtime_usage.sql@@ -7,9 +7,12 @@-- @tz is required, even if the caller intends "UTC", so the bucket-- cast is unambiguous — `bucket_hour` is UTC and the caller picks the-- calendar boundary per request.+--+-- provider is LOWER()-normalized so mixed-case historical rows merge+-- (same reason as ListRuntimeUsageByAgent below).SELECTDATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) AS date,- provider,+ LOWER(provider) AS provider,model,SUM(input_tokens)::bigint AS input_tokens,SUM(output_tokens)::bigint AS output_tokens,@@ -18,8 +21,8 @@ SELECTFROM task_usage_hourlyWHERE runtime_id = $1AND bucket_hour >= sqlc.arg('since')::timestamptz-GROUP BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text), provider, model-ORDER BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) DESC, provider, model;+GROUP BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text), LOWER(provider), model+ORDER BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) DESC, LOWER(provider), model;-- name: GetRuntimeTaskHourlyActivity :many-- Hour-of-day distribution for queue starts. Bucketed in the viewer's@@ -33,7 +36,7 @@ GROUP BY hourORDER BY hour;-- name: ListRuntimeUsageByAgent :many--- Per-(agent, model) token aggregates for a runtime since a cutoff. Powers+-- Per-(agent, provider, model) token aggregates for a runtime since a cutoff. Powers-- the runtime-detail "Cost by agent" tab. task_usage only carries task_id,-- so we join the queue to expose agent_id. The model dimension is kept on-- purpose: cost is computed client-side from a per-model pricing table, so@@ -42,8 +45,11 @@ ORDER BY hour;---- This view doesn't bucket by date, so it doesn't need @tz; only the-- @since cutoff is provided in runtime-local terms (computed in Go).+-- provider is LOWER()-normalized so mixed-case historical rows merge with+-- new rows (see ListDashboardUsageDaily in task_usage.sql).SELECTatq.agent_id,+ LOWER(tu.provider) AS provider,tu.model,SUM(tu.input_tokens)::bigint AS input_tokens,SUM(tu.output_tokens)::bigint AS output_tokens,@@ -54,8 +60,8 @@ FROM task_usage tuJOIN agent_task_queue atq ON atq.id = tu.task_idWHERE atq.runtime_id = $1AND tu.created_at >= @since::timestamptz-GROUP BY atq.agent_id, tu.model-ORDER BY atq.agent_id, tu.model;+GROUP BY atq.agent_id, LOWER(tu.provider), tu.model+ORDER BY atq.agent_id, LOWER(tu.provider), tu.model;-- name: GetRuntimeUsageByHour :many-- Per-(hour, model) token aggregates (hour ∈ 0..23) for a runtime since adiff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sqlindex 43c6d1e6e7..f697deff79 100644--- a/server/pkg/db/queries/task_usage.sql+++ b/server/pkg/db/queries/task_usage.sql@@ -30,7 +30,7 @@ JOIN agent_task_queue atq ON atq.id = tu.task_idWHERE atq.issue_id = $1;-- name: ListDashboardUsageDaily :many--- Daily per-(date, model) token aggregates for the workspace, served+-- Daily per-(date, provider, model) token aggregates for the workspace, served-- from the UTC-bucketed `task_usage_hourly` table and-- sliced to calendar days under the caller-supplied @tz. Optionally-- scoped to a single project via sqlc.narg('project_id'). Powers the@@ -44,8 +44,12 @@ WHERE atq.issue_id = $1;-- with DATE_TRUNC here — DATE_TRUNC operates in the session tz and would-- snap the cutoff back to UTC midnight, dragging in an extra partial-- local day for any non-UTC viewer.+-- provider is LOWER()-normalized so mixed-case historical rows (written+-- before the handler lowercased provider on write) merge with new rows+-- instead of forming a separate case-variant bucket.SELECTDATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) AS date,+ LOWER(provider) AS provider,model,SUM(input_tokens)::bigint AS input_tokens,SUM(output_tokens)::bigint AS output_tokens,@@ -56,11 +60,11 @@ FROM task_usage_hourlyWHERE workspace_id = $1AND bucket_hour >= sqlc.arg('since')::timestamptzAND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'))-GROUP BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text), model-ORDER BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) DESC, model;+GROUP BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text), LOWER(provider), model+ORDER BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) DESC, LOWER(provider), model;-- name: ListDashboardUsageByAgent :many--- Per-(agent, model) token aggregates from `task_usage_hourly`. No+-- Per-(agent, provider, model) token aggregates from `task_usage_hourly`. No-- date grouping in the result, so this query takes no `@tz` — the-- @since cutoff is a raw timestamptz the Go layer has already computed-- in the viewer's tz. Model dimension is preserved so the client can@@ -72,8 +76,11 @@ ORDER BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) DESC, model;-- hour the same way the daily version over-counted by day. The-- frontend prefers `ListDashboardAgentRunTime` for the user-facing-- "tasks" column, so this stays informational only.+-- provider is LOWER()-normalized so mixed-case historical rows merge with+-- new rows (see ListDashboardUsageDaily).SELECTagent_id,+ LOWER(provider) AS provider,model,SUM(input_tokens)::bigint AS input_tokens,SUM(output_tokens)::bigint AS output_tokens,@@ -84,8 +91,8 @@ FROM task_usage_hourlyWHERE workspace_id = $1AND bucket_hour >= @since::timestamptzAND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'))-GROUP BY agent_id, model-ORDER BY agent_id, model;+GROUP BY agent_id, LOWER(provider), model+ORDER BY agent_id, LOWER(provider), model;-- name: ListDashboardRunTimeDaily :many-- Daily per-date run time + task counts for the workspace, optionally