Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5191 fix(usage): price the Grok catalog + keep custom pricing editable (#5827)
Bohan Jiangfb9e1a8c722f
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.jsonindex 98efd382c9..142f553ec0 100644--- a/packages/views/locales/en/runtimes.json+++ b/packages/views/locales/en/runtimes.json@@ -413,6 +413,8 @@"unmapped_notice_other": "{{count}} models have no maintained price — their tokens are excluded from cost totals.","custom_pricing": {"open_button": "Set custom prices",+ "edit_button": "Edit custom prices",+ "active_notice": "Some models in this period are priced with your custom rates.","title": "Custom model prices","description": "Enter per-million-token rates so we can price models we don't ship a maintained rate for. Stored locally on this machine.","empty": "No models need a custom price right now.",diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.jsonindex 31ea58e953..a776ce19db 100644--- a/packages/views/locales/ja/runtimes.json+++ b/packages/views/locales/ja/runtimes.json@@ -400,6 +400,8 @@"unmapped_notice_other": "管理された価格がないモデルが {{count}} 個あり、そのトークンはコスト合計から除外されています。","custom_pricing": {"open_button": "カスタム価格を設定",+ "edit_button": "カスタム価格を編集",+ "active_notice": "この期間には、設定したカスタム価格で計算されているモデルがあります。","title": "カスタムモデル価格","description": "管理された単価を提供していないモデルの価格を計算できるよう、100 万トークンあたりの単価を入力してください。このマシンにローカルで保存されます。","empty": "今のところ、カスタム価格が必要なモデルはありません。",diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.jsonindex 37f848ce45..33754163e0 100644--- a/packages/views/locales/ko/runtimes.json+++ b/packages/views/locales/ko/runtimes.json@@ -400,6 +400,8 @@"unmapped_notice_other": "기본 가격이 등록되지 않은 모델 {{count}}개가 있어 해당 토큰은 비용 합계에서 제외됩니다.","custom_pricing": {"open_button": "사용자 지정 가격 설정",+ "edit_button": "사용자 지정 가격 편집",+ "active_notice": "이 기간에는 설정한 사용자 지정 가격으로 계산되는 모델이 있습니다.","title": "사용자 지정 모델 가격","description": "기본 단가가 등록되지 않은 모델의 가격을 계산할 수 있도록 백만 토큰당 요금을 입력하세요. 이 기기에 로컬로 저장됩니다.","empty": "지금은 사용자 지정 가격이 필요한 모델이 없습니다.",diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.jsonindex d9aee5efc5..abb940d37f 100644--- a/packages/views/locales/zh-Hans/runtimes.json+++ b/packages/views/locales/zh-Hans/runtimes.json@@ -400,6 +400,8 @@"unmapped_notice_other": "有 {{count}} 个模型没有维护价格,相关 token 未计入费用统计。","custom_pricing": {"open_button": "设置自定义价格",+ "edit_button": "编辑自定义价格",+ "active_notice": "当前时间范围内有模型按你设置的自定义价格计费。","title": "自定义模型价格","description": "为我们未维护官方价格的模型填入每百万 token 的费率。仅保存在本机。","empty": "目前没有需要设置价格的模型。",diff --git a/packages/views/runtimes/components/usage-section.test.tsx b/packages/views/runtimes/components/usage-section.test.tsxindex adb750e178..e35967dd8a 100644--- a/packages/views/runtimes/components/usage-section.test.tsx+++ b/packages/views/runtimes/components/usage-section.test.tsx@@ -41,16 +41,30 @@ vi.mock("@multica/core/hooks", () => ({// custom-pricing-store is consumed two ways: usage-section reads the store// hook, and runtimes/utils reads getCustomPricing(). The hook must be both-// callable and expose getState(), mirroring a real Zustand store.+// callable and expose getState(), mirroring a real Zustand store. Backed by+// a mutable holder so a test can seed saved overrides — with a hard-coded+// empty store, `collectUnmappedModels` can never see an override and the+// "saved rates stay editable" path below would be untestable.+const pricingState = vi.hoisted(() => ({+ pricings: {} as Record<string, unknown>,+}));+vi.mock("@multica/core/runtimes/custom-pricing-store", () => {- const state = { pricings: {} as Record<string, unknown> };const useCustomPricingStore = Object.assign(- (sel?: (s: typeof state) => unknown) => (sel ? sel(state) : state),- { getState: () => state },+ (sel?: (s: typeof pricingState) => unknown) =>+ sel ? sel(pricingState) : pricingState,+ { getState: () => pricingState },);- return { useCustomPricingStore, getCustomPricing: () => undefined };+ return {+ useCustomPricingStore,+ getCustomPricing: (model: string) => pricingState.pricings[model],+ };});+// Lets a test swap in its own usage rows (e.g. an unpriced model) without+// re-mocking the whole query layer. `null` keeps the default fixture.+const usageOverride = vi.hoisted(() => ({ rows: null as unknown[] | null }));+// useQuery is mocked so the component renders synchronously with canned// data — the `kind` tag on each query-options object routes the response.vi.mock("@tanstack/react-query", async () => {@@ -88,7 +102,7 @@ vi.mock("@tanstack/react-query", async () => {return {...actual,useQuery: (opts: { kind?: string }) => ({- data: opts?.kind === "usage" ? usageRows : [],+ data: opts?.kind === "usage" ? (usageOverride.rows ?? usageRows) : [],isLoading: false,}),};@@ -181,3 +195,67 @@ describe("UsageSection — Viewing timezone wiring", () => {expect(flows.at(-1)).toHaveAttribute("aria-label", "1K");});});++describe("UsageSection — custom-pricing entry point", () => {+ // A model that no maintained row prices, so it lands in the unmapped+ // diagnostic. `collectUnmappedModels` keys it by provider, so the saved+ // override below must use the same `acme/…` key the dialog would store.+ const UNPRICED_KEY = "acme/made-up-model-9";+ const unpricedRows = [+ {+ runtime_id: "r-1",+ date: new Date().toISOString().slice(0, 10),+ provider: "acme",+ model: "made-up-model-9",+ input_tokens: 1_000,+ output_tokens: 500,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ },+ ];++ beforeEach(() => {+ usageOverride.rows = null;+ pricingState.pricings = {};+ });++ it("stays hidden when every model resolves and nothing is overridden", () => {+ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });++ expect(+ screen.queryByRole("button", { name: "Set custom prices" }),+ ).toBeNull();+ expect(+ screen.queryByRole("button", { name: "Edit custom prices" }),+ ).toBeNull();+ });++ it("warns and offers the dialog while a model is unpriced", () => {+ usageOverride.rows = unpricedRows;++ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });++ expect(screen.getByRole("alert")).toHaveTextContent(UNPRICED_KEY);+ expect(+ screen.getByRole("button", { name: "Set custom prices" }),+ ).toBeInTheDocument();+ });++ it("keeps the dialog reachable after the last override is saved", () => {+ // Regression: a saved override makes the model resolve, so the window+ // has nothing unmapped left. Gating the bar on "something is unmapped"+ // used to remove the only entry point here, stranding the user with+ // rates they could no longer edit or delete.+ usageOverride.rows = unpricedRows;+ pricingState.pricings = {+ [UNPRICED_KEY]: { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 1 },+ };++ render(<UsageSection runtime={RUNTIME} />, { wrapper: Wrapper });++ expect(screen.queryByRole("alert")).toBeNull();+ expect(+ screen.getByRole("button", { name: "Edit custom prices" }),+ ).toBeInTheDocument();+ });+});diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsxindex f4bdb41e22..da28e7d2bc 100644--- a/packages/views/runtimes/components/usage-section.tsx+++ b/packages/views/runtimes/components/usage-section.tsx@@ -5,6 +5,7 @@ import { BarChart3, ChevronRight, AlertCircle } from "lucide-react";import { useQuery } from "@tanstack/react-query";import { Skeleton } from "@multica/ui/components/ui/skeleton";import { Button } from "@multica/ui/components/ui/button";+import { cn } from "@multica/ui/lib/utils";import {CompactNumberFlow,CurrencyNumberFlow,@@ -219,12 +220,13 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {</div></div>- {/* Pricing-gap banner. Sits above the KPI grid so a *partial* unmapping+ {/* Pricing bar. Sits above the KPI grid so a *partial* unmapping(some priced + some unpriced models in the same window) still hasa visible entry point into the manual-pricing dialog — otherwisethe chart would render normally and the unmapped tokens would silently- contribute $0 to totals. */}- <UnmappedPricingNotice usage={filtered} />+ contribute $0 to totals. Stays reachable once every model is priced+ if the user has saved overrides, so those rates remain editable. */}+ <CustomPricingBar usage={filtered} /><div className="grid grid-cols-3 divide-x rounded-lg border bg-card"><KpiCard@@ -539,39 +541,66 @@ function EmptyChartState({ usage }: { usage: RuntimeUsage[] }) {}// ----------------------------------------------------------------------------// UnmappedPricingNotice — always-visible banner shown above the KPI grid-// whenever the selected window contains any model that isn't priced. Covers-// the partial-unmapping case where the chart still renders (so EmptyChartState-// never fires) but some tokens are silently contributing $0 to totals.+// CustomPricingBar — the only entry point into the custom-pricing dialog,+// rendered above the KPI grid. Two states:+//+// 1. The window contains unpriced models → warning banner. Covers the+// partial-unmapping case where the chart still renders (so+// EmptyChartState never fires) but some tokens silently contribute $0.+// 2. Everything resolves, but the user has saved overrides → a quiet row+// that still offers the dialog. Gating the whole bar on "something is+// unmapped" used to hide it the moment the last override was saved:+// the override made the model resolve, the banner disappeared, and the+// saved rates could no longer be corrected or removed from the UI.+//+// Hidden entirely when nothing is unmapped and nothing is overridden.// ----------------------------------------------------------------------------function UnmappedPricingNotice({ usage }: { usage: RuntimeUsage[] }) {+function CustomPricingBar({ usage }: { usage: RuntimeUsage[] }) {const { t } = useT("runtimes");const [dialogOpen, setDialogOpen] = useState(false);+ // Boolean (not the object) so the selector stays referentially stable.+ const hasOverrides = useCustomPricingStore(+ (s) => Object.keys(s.pricings).length > 0,+ );const unmapped = collectUnmappedModels(usage);- if (unmapped.length === 0) return null;+ if (unmapped.length === 0 && !hasOverrides) return null;+ const hasGap = unmapped.length > 0;return (<div- role="alert"- className="flex flex-wrap items-center gap-3 rounded-lg border border-warning/30 bg-warning/10 px-3 py-2 text-xs"+ role={hasGap ? "alert" : undefined}+ className={cn(+ "flex flex-wrap items-center gap-3 rounded-lg border px-3 py-2 text-xs",+ hasGap ? "border-warning/30 bg-warning/10" : "bg-muted/20",+ )}>- <AlertCircle className="h-4 w-4 shrink-0 text-warning" />- <div className="min-w-0 flex-1 space-y-0.5">- <p className="text-foreground">- {t(($) => $.usage.unmapped_notice, { count: unmapped.length })}- </p>- <p className="truncate font-mono text-[11px] text-muted-foreground">- {unmapped.join(", ")}+ {hasGap ? (+ <>+ <AlertCircle className="h-4 w-4 shrink-0 text-warning" />+ <div className="min-w-0 flex-1 space-y-0.5">+ <p className="text-foreground">+ {t(($) => $.usage.unmapped_notice, { count: unmapped.length })}+ </p>+ <p className="truncate font-mono text-[11px] text-muted-foreground">+ {unmapped.join(", ")}+ </p>+ </div>+ </>+ ) : (+ <p className="min-w-0 flex-1 text-muted-foreground">+ {t(($) => $.usage.custom_pricing.active_notice)}</p>- </div>+ )}<Buttontype="button"variant="outline"size="sm"onClick={() => setDialogOpen(true)}>- {t(($) => $.usage.custom_pricing.open_button)}+ {hasGap+ ? t(($) => $.usage.custom_pricing.open_button)+ : t(($) => $.usage.custom_pricing.edit_button)}</Button><CustomPricingDialogopen={dialogOpen}diff --git a/packages/views/runtimes/utils.test.ts b/packages/views/runtimes/utils.test.tsindex f80cd63d1e..1bf16d1d5f 100644--- a/packages/views/runtimes/utils.test.ts+++ b/packages/views/runtimes/utils.test.ts@@ -461,6 +461,60 @@ describe("estimateCost", () => {).toBe(0);});+ it("prices grok-4.5 at xAI's short-context $2.00 / $6.00 tier", () => {+ // 1M input × $2.00 + 1M output × $6.00 + 1M cached-read × $0.30.+ // Short context on purpose: the long-context (≥200K prompt) tier is 2x,+ // but aggregated rows carry no per-request prompt sizes.+ expect(+ estimateCost({+ ...zeroUsage,+ provider: "xai",+ model: "grok-4.5",+ input_tokens: 1_000_000,+ output_tokens: 1_000_000,+ cache_read_tokens: 1_000_000,+ }),+ ).toBeCloseTo(8.3, 5);+ });++ it("prices the rest of the published Grok catalog", () => {+ // grok-4.3 and the 4.20 snapshots share one $1.25 / $2.50 tier;+ // grok-build-0.1 is its own $1.00 / $2.00 row.+ for (const model of [+ "grok-4.3",+ "grok-4.20-multi-agent-0309",+ "grok-4.20-0309-reasoning",+ "grok-4.20-0309-non-reasoning",+ ]) {+ expect(+ estimateCost({+ ...zeroUsage,+ provider: "xai",+ model,+ input_tokens: 1_000_000,+ output_tokens: 1_000_000,+ }),+ ).toBeCloseTo(3.75, 5);+ }+ expect(+ estimateCost({+ ...zeroUsage,+ provider: "xai",+ model: "grok-build-0.1",+ input_tokens: 1_000_000,+ output_tokens: 1_000_000,+ }),+ ).toBeCloseTo(3, 5);+ });++ it("leaves Grok SKUs that xAI does not publish a price for unmapped", () => {+ // No startsWith fallback: `grok-composer-2.5-fast` is in the Grok Build+ // catalog but absent from docs.x.ai/developers/pricing, so it must NOT+ // inherit grok-4.5's rate — it surfaces in the unmapped diagnostic+ // instead, where the user can supply their own rate.+ expect(isModelPriced("grok-composer-2.5-fast", "xai")).toBe(false);+ });+it("recognises the provider-prefixed forms emitted by OpenRouter-style runtimes", () => {// opencode + OpenRouter route IDs through as `<provider>/<model>`.// canonicalCandidates strips the prefix; without this the rows abovediff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.tsindex d1d90f87a9..954fe03193 100644--- a/packages/views/runtimes/utils.ts+++ b/packages/views/runtimes/utils.ts@@ -132,12 +132,13 @@ export function formatTokens(n: number): string {// DeepSeek: https://api-docs.deepseek.com/quick_start/pricing// Moonshot: https://www.kimi.com/resources/kimi-k2-6-pricing// Zhipu: https://docs.z.ai/guides/overview/pricing+// xAI: https://docs.x.ai/developers/pricing//// Anthropic's cacheWrite reflects the 5-minute cache TTL (1.25× input); the// daemon reports cache_creation_input_tokens without TTL metadata, so 5m is// the safest / cheapest assumption (matches the API default). DeepSeek,-// Moonshot and Zhipu do not bill cache writes separately (cached input is-// just discounted on subsequent reads), so cacheWrite mirrors input there.+// Moonshot, Zhipu and xAI do not bill cache writes separately (cached input+// is just discounted on subsequent reads), so cacheWrite mirrors input there.// OpenAI historically did the same, but its GPT-5.6+ generation bills cache// writes at 1.25× input (cache reads still get the 90% cached-input// discount), so those rows carry a distinct cacheWrite. Codex usage doesn't@@ -152,7 +153,8 @@ export function formatTokens(n: number): string {// `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+// (`claude-*`, `gpt-*`, `o3*`/`o4*`, `glm-*`, `deepseek-*`, `kimi-*`,+// `grok-*`) 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@@ -253,6 +255,26 @@ const MODEL_PRICING: Record<"glm-4.5-airx": { input: 1.1, output: 4.5, cacheRead: 0.22, cacheWrite: 1.1 },"glm-4.5-flash": { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ // -- xAI Grok (docs.x.ai/developers/pricing). Rates below are the+ // short-context tier. xAI bills a request at 2x ("long context") once+ // its prompt reaches 200K tokens, but aggregated usage rows carry no+ // per-request prompt sizes, so we price at the standard tier — the same+ // trade-off the Anthropic `[1m]` context tag takes (see `resolvePricing`).+ // `cacheRead` is xAI's published "Cached" input rate; there is no+ // separate cache-write rate on the page (writes bill as normal input),+ // so cacheWrite mirrors input per the header note. Grok ids are+ // vendor-prefixed, so these keys stay unqualified even though the+ // daemon tags the rows with provider `xai`.+ // `grok-composer-*` ships in the Grok Build catalog+ // (server/pkg/agent/models.go) but is absent from the price sheet; it+ // deliberately stays unmapped rather than inheriting a guessed rate. --+ "grok-4.5": { input: 2, output: 6, cacheRead: 0.30, cacheWrite: 2 },+ "grok-4.3": { input: 1.25, output: 2.50, cacheRead: 0.20, cacheWrite: 1.25 },+ "grok-build-0.1": { input: 1, output: 2, cacheRead: 0.20, cacheWrite: 1 },+ "grok-4.20-multi-agent-0309": { input: 1.25, output: 2.50, cacheRead: 0.20, cacheWrite: 1.25 },+ "grok-4.20-0309-reasoning": { input: 1.25, output: 2.50, cacheRead: 0.20, cacheWrite: 1.25 },+ "grok-4.20-0309-non-reasoning": { input: 1.25, output: 2.50, cacheRead: 0.20, cacheWrite: 1.25 },+// -- Cursor Composer / Auto (cursor.com/docs/models-and-pricing,// cursor.com/docs/models/cursor-composer-2,// cursor.com/docs/models/cursor-composer-2-5).