Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
90.6 KB
Raw Blame
// @vitest-environment node
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";
import type { AgentRuntime, RuntimeUsage } from "@multica/core/types";

import {
  addDaysIso,
  aggregateByDate,
  aggregateByWeek,
  aggregateCostByModel,
  cacheHitRatePercent,
  collectUnmappedModels,
  computeCostInWindow,
  estimateCost,
  estimateCostBreakdown,
  formatCredits,
  formatSpend,
  formatTokens,
  hasTokenFigure,
  isModelPriced,
  isSelfHealingRuntime,
  sliceWindow,
  summarizeTaskUsage,
  summarizeTaskUsageAcross,
  todayIso,
  weekStartIso,
} from "./utils";

afterEach(() => {
  // Reset overrides so tests don't bleed pricing state into one another.
  useCustomPricingStore.setState({ pricings: {} });
});

const zeroUsage = {
  input_tokens: 0,
  output_tokens: 0,
  cache_read_tokens: 0,
  cache_write_tokens: 0,
};

describe("cacheHitRatePercent", () => {
  it("includes cache writes in the input-side denominator", () => {
    expect(cacheHitRatePercent(0, 72, 28)).toBe(72);
  });

  it("does not round an incomplete hit rate up to 100%", () => {
    expect(cacheHitRatePercent(45, 9_955, 0)).toBe(99);
    expect(cacheHitRatePercent(0, 10_000, 0)).toBe(100);
  });

  it("returns null when there are no input-side tokens", () => {
    expect(cacheHitRatePercent(0, 0, 0)).toBeNull();
  });
});

describe("isSelfHealingRuntime", () => {
  function makeRuntime(overrides: Partial<AgentRuntime>): AgentRuntime {
    return {
      id: "rt-1",
      workspace_id: "ws-1",
      daemon_id: null,
      name: "rt",
      runtime_mode: "local",
      provider: "claude",
      launch_header: "",
      status: "online",
      device_info: "",
      metadata: {},
      owner_id: null,
      visibility: "private",
      last_seen_at: null,
      created_at: "2026-01-01T00:00:00Z",
      updated_at: "2026-01-01T00:00:00Z",
      ...overrides,
    };
  }

  it("flags an online local runtime as self-healing", () => {
    expect(
      isSelfHealingRuntime(
        makeRuntime({ runtime_mode: "local", status: "online" }),
      ),
    ).toBe(true);
  });

  it("treats an offline local runtime as safe to delete", () => {
    // Daemon isn't running, so the server-side delete is final — no
    // re-registration race to worry about.
    expect(
      isSelfHealingRuntime(
        makeRuntime({ runtime_mode: "local", status: "offline" }),
      ),
    ).toBe(false);
  });

  it("treats cloud runtimes as safe to delete regardless of status", () => {
    // Cloud workers are managed by Fleet, not a self-restarting local daemon.
    expect(
      isSelfHealingRuntime(
        makeRuntime({ runtime_mode: "cloud", status: "online" }),
      ),
    ).toBe(false);
    expect(
      isSelfHealingRuntime(
        makeRuntime({ runtime_mode: "cloud", status: "offline" }),
      ),
    ).toBe(false);
  });
});

describe("estimateCost", () => {
  it("prices the canonical Anthropic Sonnet 4.6 SKU", () => {
    const cost = estimateCost({
      ...zeroUsage,
      model: "claude-sonnet-4-6",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
    });
    // 1M × $3 input + 1M × $15 output = $18.
    expect(cost).toBeCloseTo(18, 5);
  });

  it("prices a Codex CLI session reporting gpt-5-codex", () => {
    const cost = estimateCost({
      ...zeroUsage,
      model: "gpt-5-codex",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
      cache_read_tokens: 2_000_000,
    });
    // 1M × $1.25 + 1M × $10 + 2M × $0.125 = $11.50.
    expect(cost).toBeCloseTo(11.5, 5);
  });

  it("strips dated snapshots before resolving (gpt-5-2025-08-07 → gpt-5)", () => {
    const cost = estimateCost({
      ...zeroUsage,
      model: "gpt-5-2025-08-07",
      input_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(1.25, 5);
  });

  it("prices a Copilot session reporting claude-opus-4.7 at the official Opus rate", () => {
    // Copilot's `meta.agentMeta.model` is `claude-opus-4.7` (dotted). We
    // canonicalize to the dashed catalog key so it hits the maintained $5/$25
    // tier instead of falling through to the custom-pricing dialog.
    const cost = estimateCost({
      ...zeroUsage,
      model: "claude-opus-4.7",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(5 + 25, 5);
  });

  it("prices Claude Fable 5 at the Mythos-class tier", () => {
    const cost = estimateCost({
      ...zeroUsage,
      model: "claude-fable-5",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
      cache_read_tokens: 1_000_000,
      cache_write_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(10 + 50 + 1 + 12.5, 5);
  });

  it("prices Claude Fable 5.1 at the Mythos-class tier with quarter-rate cache reads", () => {
    // Same $10 / $50 and $12.50 cache write as Fable 5, but cache reads are
    // 0.025x input ($0.25) rather than the usual 0.1x.
    const cost = estimateCost({
      ...zeroUsage,
      model: "claude-fable-5-1",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
      cache_read_tokens: 1_000_000,
      cache_write_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(10 + 50 + 0.25 + 12.5, 5);
  });

  // Fable 5.2 has its own, cheaper Anthropic row.
  it.each(["claude-fable-5-2", "claude-fable-5.2", "claude-fable-5-2[1m]"])(
    "prices Claude %s at its own 8 / 40 tier",
    (model) => {
      const cost = estimateCost({
        ...zeroUsage,
        model,
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
        cache_read_tokens: 1_000_000,
        cache_write_tokens: 1_000_000,
      });
      expect(cost).toBeCloseTo(8 + 40 + 0.2 + 10, 5);
    },
  );

  it.each([
    {
      model: "claude-sonnet-5-5",
      dotted: "claude-sonnet-5.5",
      expected: { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 2.5 },
    },
    {
      model: "claude-haiku-5-5",
      dotted: "claude-haiku-5.5",
      expected: { input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite: 0.125 },
    },
  ])("prices $model across transport spellings", ({ model, dotted, expected }) => {
    for (const alias of [
      model,
      dotted,
      `anthropic/${model}`,
      `anthropic:${dotted}`,
      `${model}[1m]`,
      `${model}-20261001`,
      `${model}-2026-10-01[1m]`,
      `${model}-latest`,
    ]) {
      // Aggregate totals do not identify a single request's context tier.
      const usage = {
        model: alias,
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
        cache_read_tokens: 1_000_000,
        cache_write_tokens: 1_000_000,
      };
      expect(estimateCostBreakdown(usage)).toEqual(expected);
      expect(estimateCost(usage)).toBeCloseTo(
        expected.input + expected.output + expected.cacheRead + expected.cacheWrite,
        5,
      );
      expect(collectUnmappedModels([usage])).toEqual([]);
    }
  });

  it("keeps unknown Sonnet and Haiku variants unmapped", () => {
    for (const model of [
      "claude-sonnet-5-6",
      "claude-sonnet-5.6",
      "claude-sonnet-5-55",
      "claude-haiku-5-6",
      "claude-haiku-5.6",
      "claude-haiku-5-55",
      ...["claude-sonnet-5", "claude-sonnet-5-5", "claude-haiku-5-5"].flatMap(
        (base) => ["x", "-preview", "-latest-preview", "-20261001x", "[1m]junk", "[1m][2m]", "[]"].map(
          (suffix) => base + suffix,
        ),
      ),
    ]) {
      expect(isModelPriced(model)).toBe(false);
      expect(estimateCost({ ...zeroUsage, model, input_tokens: 1_000_000 })).toBe(0);
    }
  });

  it("prices Claude Sonnet 5 at Anthropic's intro $2 / $10 tier", () => {
    const cost = estimateCost({
      ...zeroUsage,
      model: "claude-sonnet-5",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
      cache_read_tokens: 1_000_000,
      cache_write_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(2 + 10 + 0.2 + 2.5, 5);
  });

  it("prices the provider-prefixed Anthropic form (anthropic/claude-sonnet-4.6)", () => {
    // openclaw / opencode emit `<provider>/<model>`. Same SKU as the
    // bare form, must hit the same rate.
    const cost = estimateCost({
      ...zeroUsage,
      model: "anthropic/claude-sonnet-4.6",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(3 + 15, 5);
  });

  it("prices the dated dotted Anthropic form (claude-haiku-4.5-20251001)", () => {
    // Belt-and-braces: combine all three tolerances (provider prefix not
    // present, but dot→dash + date strip both apply).
    const cost = estimateCost({
      ...zeroUsage,
      model: "claude-haiku-4.5-20251001",
      input_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(1, 5);
  });

  it("prices the full provider+dotted+dated form (anthropic/claude-opus-4.7-20251001)", () => {
    // All three normalization steps must compose: strip `anthropic/`,
    // dot→dash on the Claude ID, and trim the date stamp. Pins the
    // combined path so a future change to candidate ordering can't
    // silently drop one tolerance.
    const cost = estimateCost({
      ...zeroUsage,
      model: "anthropic/claude-opus-4.7-20251001",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(5 + 25, 5);
  });

  it("prices the 1M-context Anthropic tag form (claude-opus-4-7[1m]) at the standard Opus tier", () => {
    // Claude Code reports the 1M-context beta as `claude-opus-4-7[1m]`.
    // Anthropic prices it at the standard Opus rate for prompts ≤200K
    // input tokens (with a 2× surcharge above that, which we can't see
    // from aggregated daily totals). Strip the bracketed context tag so
    // the tokens still land in the cost total at standard pricing —
    // mild under-estimate, but the alternative was excluding them
    // entirely (the bug this fixes).
    const cost = estimateCost({
      ...zeroUsage,
      model: "claude-opus-4-7[1m]",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(5 + 25, 5);
    expect(isModelPriced("claude-opus-4-7[1m]")).toBe(true);
  });

  it("prices Opus 5 on the standard Opus tier across its transport spellings", () => {
    // Opus 5 is a 5/25 SKU like Opus 4.5-4.8. Claude Code reports the
    // 1M-context window with a bracketed suffix and openclaw/opencode prefix
    // the id with the provider, so all three spellings reach the cost
    // estimator and must land on the same row.
    for (const model of [
      "claude-opus-5",
      "claude-opus-5[1m]",
      "anthropic/claude-opus-5",
    ]) {
      expect(
        estimateCost({
          ...zeroUsage,
          model,
          input_tokens: 1_000_000,
          output_tokens: 1_000_000,
        }),
      ).toBeCloseTo(5 + 25, 5);
      expect(isModelPriced(model)).toBe(true);
    }
  });

  it("prices Opus 5.5 at its own 4/20 tier with 0.05x cache reads, not Opus 5's", () => {
    // Opus 5.5 is cheaper than Opus 5 ($4 / $20, $5 cache write) and prices
    // cache reads at 0.05x input ($0.20) instead of the usual 0.1x. Copilot
    // reports it dotted, so every spelling must reach the 5.5 row.
    for (const model of [
      "claude-opus-5-5",
      "claude-opus-5-5[1m]",
      "claude-opus-5.5",
      "anthropic/claude-opus-5-5",
    ]) {
      expect(
        estimateCost({
          ...zeroUsage,
          model,
          input_tokens: 1_000_000,
          output_tokens: 1_000_000,
          cache_read_tokens: 1_000_000,
          cache_write_tokens: 1_000_000,
        }),
      ).toBeCloseTo(4 + 20 + 0.2 + 5, 5);
      expect(isModelPriced(model)).toBe(true);
    }
  });

  it("prices each dotted Codex catalog SKU at its own tier, not gpt-5", () => {
    // Every dotted minor version is priced independently. The resolver does
    // exact-match-after-date-strip (no startsWith fallback), so each row
    // must exist on its own.
    expect(
      estimateCost({ ...zeroUsage, model: "gpt-5.5", input_tokens: 1_000_000 }),
    ).toBeCloseTo(5, 5);
    expect(
      estimateCost({ ...zeroUsage, model: "gpt-5.4", output_tokens: 1_000_000 }),
    ).toBeCloseTo(15, 5);
    expect(
      estimateCost({
        ...zeroUsage,
        model: "gpt-5.4-mini",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBeCloseTo(0.75 + 4.5, 5);
    expect(
      estimateCost({
        ...zeroUsage,
        model: "gpt-5.3-codex",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBeCloseTo(1.75 + 14, 5);
  });

  it("prices current Codex models per OpenAI's official cache-aware rates", () => {
    // OpenAI's standard short-context rates. 5.6 is the first OpenAI generation to bill
    // cache writes separately: cacheRead generally = 0.1x input (GPT-6.1
    // Sol and Terra use 0.05x), cacheWrite = 1.25x
    // input. Cover every model x every token category so a wrong cache rate
    // can't hide behind an input-only assertion. `total` is 1M of each of the
    // four categories priced at its own rate.
    const cases = [
      { model: "gpt-6-astra", input: 10, cacheRead: 1, cacheWrite: 12.5, output: 50, total: 73.5 },
      { model: "gpt-6.1-sol", input: 2, cacheRead: 0.1, cacheWrite: 2.5, output: 10, total: 14.6 },
      { model: "gpt-6.1-terra", input: 1, cacheRead: 0.05, cacheWrite: 1.25, output: 5, total: 7.3 },
      { model: "gpt-6-sol", input: 2, cacheRead: 0.2, cacheWrite: 2.5, output: 10, total: 14.7 },
      { model: "gpt-6-luna", input: 0.1, cacheRead: 0.01, cacheWrite: 0.125, output: 0.5, total: 0.735 },
      { model: "gpt-5.6-sol", input: 5, cacheRead: 0.5, cacheWrite: 6.25, output: 30, total: 41.75 },
      { model: "gpt-5.6-terra", input: 2, cacheRead: 0.2, cacheWrite: 2.5, output: 12, total: 16.7 },
      { model: "gpt-5.6-luna", input: 0.2, cacheRead: 0.02, cacheWrite: 0.25, output: 1.2, total: 1.67 },
    ];
    for (const c of cases) {
      const breakdown = estimateCostBreakdown({
        ...zeroUsage,
        model: c.model,
        input_tokens: 1_000_000,
        cache_read_tokens: 1_000_000,
        cache_write_tokens: 1_000_000,
        output_tokens: 1_000_000,
      });
      expect(breakdown.input).toBeCloseTo(c.input, 5);
      expect(breakdown.cacheRead).toBeCloseTo(c.cacheRead, 5);
      expect(breakdown.cacheWrite).toBeCloseTo(c.cacheWrite, 5);
      expect(breakdown.output).toBeCloseTo(c.output, 5);
      expect(
        estimateCost({
          ...zeroUsage,
          model: c.model,
          input_tokens: 1_000_000,
          cache_read_tokens: 1_000_000,
          cache_write_tokens: 1_000_000,
          output_tokens: 1_000_000,
        }),
      ).toBeCloseTo(c.total, 5);
    }
  });

  it("prices published Gemini token SKUs at standard rates in every bucket", () => {
    const cases = [
      { model: "gemini-4-neon", input: 3, output: 15, cacheRead: 0.15, cacheWrite: 3 },
      { model: "gemini-4-hydrogen", input: 1.5, output: 7.5, cacheRead: 0.075, cacheWrite: 1.5 },
      { model: "gemini-4-argon", input: 2, output: 10, cacheRead: 0.1, cacheWrite: 2 },
      { model: "gemini-4-carbon", input: 2, output: 10, cacheRead: 0.1, cacheWrite: 2 },
      { model: "gemini-3.8-flash", input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 },
      { model: "gemini-3.7-flash", input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 },
      { model: "gemini-3.6-flash", input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 },
      { model: "gemini-3.5-flash", input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 },
      { model: "gemini-3.5-flash-lite", input: 0.3, output: 2.5, cacheRead: 0.03, cacheWrite: 0.3 },
      { model: "gemini-3.1-flash-lite", input: 0.25, output: 1.5, cacheRead: 0.025, cacheWrite: 0.25 },
      { model: "gemini-3.1-pro", input: 2, output: 12, cacheRead: 0.2, cacheWrite: 2 },
      { model: "gemini-3.1-pro-preview", input: 2, output: 12, cacheRead: 0.2, cacheWrite: 2 },
      { model: "gemini-3.1-pro-preview-customtools", input: 2, output: 12, cacheRead: 0.2, cacheWrite: 2 },
      { model: "gemini-3-flash", input: 0.5, output: 3, cacheRead: 0.05, cacheWrite: 0.5 },
      { model: "gemini-3-flash-preview", input: 0.5, output: 3, cacheRead: 0.05, cacheWrite: 0.5 },
      { model: "gemini-2.5-pro", input: 1.25, output: 10, cacheRead: 0.125, cacheWrite: 1.25 },
      { model: "gemini-2.5-flash", input: 0.3, output: 2.5, cacheRead: 0.03, cacheWrite: 0.3 },
      { model: "gemini-2.5-flash-lite", input: 0.1, output: 0.4, cacheRead: 0.01, cacheWrite: 0.1 },
      { model: "gemini-robotics-er-2-preview", input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1 },
      { model: "gemini-robotics-er-2-streaming-preview", input: 1, output: 5, cacheRead: 0, cacheWrite: 0 },
      { model: "gemini-3.8-flash-tts", input: 0.5, output: 9, cacheRead: 0, cacheWrite: 0 },
      { model: "gemini-3.8-flash-lite-tts", input: 0.5, output: 6, cacheRead: 0, cacheWrite: 0 },
      { model: "gemini-3.1-flash-tts-preview", input: 1, output: 20, cacheRead: 0, cacheWrite: 0 },
      { model: "gemini-2.5-flash-preview-tts", input: 0.5, output: 10, cacheRead: 0, cacheWrite: 0 },
      { model: "gemini-2.5-pro-preview-tts", input: 1, output: 20, cacheRead: 0, cacheWrite: 0 },
      { model: "gemini-3.5-transcribe", input: 2, output: 12, cacheRead: 0, cacheWrite: 0 },
      { model: "gemini-3.5-transcribe-live", input: 3.5, output: 21, cacheRead: 0, cacheWrite: 0 },
      { model: "gemini-3.5-live-translate-preview", input: 3.5, output: 21, cacheRead: 0, cacheWrite: 0 },
    ];
    for (const c of cases) {
      for (const model of [c.model, `google/${c.model}`, `custom:google/${c.model}[1m]`]) {
        const row = {
          provider: "antigravity", model,
          input_tokens: 1_000_000, output_tokens: 1_000_000,
          cache_read_tokens: 1_000_000, cache_write_tokens: 1_000_000,
        };
        expect(isModelPriced(model, row.provider), model).toBe(true);
        expect(collectUnmappedModels([row]), model).toEqual([]);
        expect(estimateCostBreakdown(row), model).toEqual({
          input: c.input, output: c.output, cacheRead: c.cacheRead, cacheWrite: c.cacheWrite,
        });
        expect(estimateCost(row), model).toBeCloseTo(c.input + c.output + c.cacheRead + c.cacheWrite, 5);
      }
    }
  });

  it("resolves Antigravity display names and reasoning suffixes without changing rates", () => {
    for (const [label, id, price] of [
      ["Gemini 3.8 Flash", "gemini-3.8-flash", 0.75],
      ["Gemini 3.5 Flash", "gemini-3.5-flash", 0.75],
      ["Gemini 3.5 Flash-Lite", "gemini-3.5-flash-lite", 0.3],
      ["Gemini 3.1 Pro", "gemini-3.1-pro", 2],
      ["Gemini 4 Argon", "gemini-4-argon", 2],
      ["Gemini 4 Carbon", "gemini-4-carbon", 2],
      ["Gemini 4 Neon", "gemini-4-neon", 3],
      ["Gemini 4 Hydrogen", "gemini-4-hydrogen", 1.5],
    ] as const) {
      for (const model of [label, `${label} (High)`, `google/${label} (Low)`, `${label} (Extra)`,
        `${id}-minimal`, `${id}-xhigh`, `antigravity:${id}-high`, `custom:google/${id}-low[1m]`]) {
        expect(isModelPriced(model, "antigravity"), model).toBe(true);
        expect(estimateCost({ ...zeroUsage, provider: "antigravity", model, input_tokens: 1_000_000 }), model).toBeCloseTo(price, 5);
      }
    }
  });

  it("resolves Antigravity Claude effort suffixes and display labels at the base tier", () => {
    // Antigravity appends the reasoning effort or Thinking mode to Claude ids
    // (`claude-opus-5-5-high`) or reports the display label. Both are a
    // reasoning dial, not a different SKU, so they price at the base model's
    // tier — but only under the antigravity provider (the scoping stays
    // pinned by "keeps Cursor variant stripping scoped to Cursor rows"),
    // mirroring priceForAntigravityModel in server/internal/metrics/pricing.go.
    const cost = (model: string) =>
      estimateCost({
        ...zeroUsage, provider: "antigravity", model,
        input_tokens: 1_000_000, output_tokens: 1_000_000,
        cache_read_tokens: 1_000_000, cache_write_tokens: 1_000_000,
      });
    const opus55 = 4 + 20 + 0.2 + 5;
    const sonnet55 = 2 + 10 + 0.1 + 2.5;
    const opus46 = 5 + 25 + 0.5 + 6.25;
    const sonnet46 = 3 + 15 + 0.3 + 3.75;
    for (const [model, want] of [
      ["claude-opus-5-5-high", opus55],
      ["claude-opus-5-5-medium", opus55],
      ["claude-sonnet-5-5-low", sonnet55],
      ["claude-haiku-5-5-minimal", 0.1 + 0.5 + 0.01 + 0.125],
      ["claude-opus-5-5-high[1m]", opus55],
      ["claude-opus-5.5-high", opus55],
      ["Claude-Opus-5.5-High", opus55],
      ["antigravity:claude-opus-5-5-high", opus55],
      ["Claude Opus 5.5 (High)", opus55],
      ["Claude Opus 5.5", opus55],
      ["claude-opus-5-5-thinking", opus55],
      ["Claude Opus 5.5 (Thinking)", opus55],
      ["Claude Sonnet 5.5 (Thinking)", sonnet55],
      ["claude-sonnet-5-5-thinking", sonnet55],
      ["Claude Opus 4.6 (Thinking)", opus46],
      ["claude-opus-4-6-thinking", opus46],
      ["Claude Sonnet 4.6 (Thinking)", sonnet46],
    ] as const) {
      expect(isModelPriced(model, "antigravity"), model).toBe(true);
      expect(cost(model), model).toBeCloseTo(want, 5);
    }
    expect(collectUnmappedModels([
      { ...zeroUsage, provider: "antigravity", model: "claude-opus-5-5-high", input_tokens: 1 },
      { ...zeroUsage, provider: "antigravity", model: "Claude Sonnet 5.5 (Medium)", input_tokens: 1 },
      { ...zeroUsage, provider: "antigravity", model: "Claude Opus 5.5 (Thinking)", input_tokens: 1 },
    ])).toEqual([]);
    // Only the levels Antigravity offers for Claude are stripped, the
    // version is a major or major.minor number, and one context tag at most;
    // everything else stays unmapped.
    for (const model of [
      "claude-opus-5-5-fast", "claude-opus-5-5-max", "claude-opus-5-5-xhigh",
      "claude-opus-5-5-thinking-high", "Claude Opus 5.5 (Extra)", "claude-opus-5-5-preview",
      "claude-opus-5-5-99-high", "claude-opus-5-5-20261001-high",
      "claude-opus-5-5-high-latest", "/claude-opus-5-5-high",
      "claude-opus-5-5[]", "claude-opus-5-5-high[1m][2m]",
    ]) {
      expect(isModelPriced(model, "antigravity"), model).toBe(false);
      expect(cost(model), model).toBe(0);
    }
  });

  it("prices Antigravity GPT-OSS 120B at Vertex AI's rate, scoped to Antigravity", () => {
    const cost = (model: string, provider?: string) =>
      estimateCost({
        ...zeroUsage, provider, model,
        input_tokens: 1_000_000, output_tokens: 1_000_000,
        cache_read_tokens: 1_000_000, cache_write_tokens: 1_000_000,
      });
    for (const model of [
      "GPT-OSS 120B (Medium)", "GPT-OSS 120B", "gpt-oss-120b", "gpt-oss-120b-medium",
      "gpt-oss-120b-high[1m]", "openai/gpt-oss-120b",
    ]) {
      expect(isModelPriced(model, "antigravity"), model).toBe(true);
      expect(cost(model, "antigravity"), model).toBeCloseTo(0.09 + 0.36 + 0.09 + 0.09, 5);
    }
    expect(collectUnmappedModels([
      { ...zeroUsage, provider: "antigravity", model: "GPT-OSS 120B (Medium)", input_tokens: 1 },
    ])).toEqual([]);
    // Orchestrator splits a turn between a planner and an executor model, so
    // no single rate fits; other gpt-oss sizes and variants are not guessed.
    for (const model of [
      "gpt-oss-20b", "GPT-OSS 20B (Medium)", "gpt-oss-120b-xhigh", "gpt-oss-120b-preview",
      "GPT-OSS 120B (Turbo)", "gpt-oss-120b[1m][2m]",
      "Orchestrator (Neon)", "Orchestrator (Carbon)", "gemini-pro-orchestrator",
    ]) {
      expect(isModelPriced(model, "antigravity"), model).toBe(false);
      expect(cost(model, "antigravity"), model).toBe(0);
    }
    // Other runtimes reach gpt-oss through hosts with their own rates.
    for (const provider of [undefined, "opencode", "cursor"]) {
      expect(isModelPriced("gpt-oss-120b", provider), String(provider)).toBe(false);
    }
  });

  it("does not guess Gemini variant or multimodal generation prices", () => {
    for (const model of [
      "gemini-3.8-flash-lite",
      "gemini-3.8-flash-live",
      "gemini-3.8-flash-preview",
      "gemini-3.8-flash-ultra",
      "gemini-3-8-flash",
      "Gemini 3.8 Flash (Ultra)",
      "Gemini 3.9 Flash (High)",
      "gemini-3.8-flash[1m][2m]",
      "gemini-3.1-pro-preview-extra",
      "gemini-3.1-pro-image",
      "gemini-2.5-pro-preview-05-06",
      "gemini-2.5-flash-lite-preview-09-2025",
      "gemini-2.5-flash-image",
      "gemini-3-pro-image",
      "gemini-nano-banana-2.1",
      "gemini-3.1-flash-image",
      "gemini-3.1-flash-lite-image",
      "gemini-3.8-live",
      "gemini-3.8-live-extended-thinking",
      "gemini-3.1-flash-live-preview",
      "gemini-2.5-flash-native-audio-preview-12-2025",
      "gemini-omni-1.1-flash",
      "gemini-omni-flash-preview",
      "gemini-embedding-2",
      "gemini-4-argon-fast",
      "gemini-4-carbon-fast",
      "gemini-4-carbon[1m][2m]",
      "gemini-4-argon[1m][2m]",
      "gemini-4-neon-fast",
      "gemini-4-neon-max",
      "gemini-4-neon-extra",
      "gemini-4-neon[1m][2m]",
      "gemini-4-hydrogen-fast",
      "Gemini 4 Neon (Ultra)",
      "Gemini 4 Hydrogen (Xhigh)",
      "Gemini 4 Neon Medium",
    ]) {
      expect(isModelPriced(model, "antigravity"), model).toBe(false);
      expect(estimateCost({ ...zeroUsage, provider: "antigravity", model, input_tokens: 1_000_000 }), model).toBe(0);
    }
  });

  it("prices Cursor's 3.5 and 3.6 Flash at Cursor's sheet, not Google's routed rate", () => {
    const cost = (model: string) =>
      estimateCost({ ...zeroUsage, provider: "cursor", model,
        input_tokens: 1_000_000, output_tokens: 1_000_000, cache_read_tokens: 1_000_000,
      });
    expect(cost("gemini-3.5-flash")).toBeCloseTo(1.5 + 9 + 0.15, 5);
    expect(cost("gemini-3.6-flash-high")).toBeCloseTo(1.5 + 7.5 + 0.15, 5);
    expect(cost("gemini-3.7-flash-high")).toBeCloseTo(0.75 + 3.75 + 0.075, 5);
  });

  it("resolves current Codex routing prefixes and context tags", () => {
    for (const model of ["openai:gpt-6.1-sol", "openai/gpt-6.1-sol", "gpt-6.1-sol[1m]"]) {
      expect(isModelPriced(model, "codex")).toBe(true);
      expect(estimateCost({ ...zeroUsage, provider: "codex", model, cache_read_tokens: 1_000_000 })).toBeCloseTo(0.1, 5);
    }
    for (const model of ["openai:gpt-6.1-terra", "openai/gpt-6.1-terra", "gpt-6.1-terra[1m]"]) {
      expect(isModelPriced(model, "codex")).toBe(true);
      expect(estimateCost({ ...zeroUsage, provider: "codex", model, cache_read_tokens: 1_000_000 })).toBeCloseTo(0.05, 5);
    }
  });

  it("flags catalog SKUs without a published price (gpt-5.5-mini) as unmapped", () => {
    // `gpt-5.5-mini` is in the Codex catalog but OpenAI hasn't published a
    // public rate. We refuse to absorb it into `gpt-5.5` — the diagnostic
    // surfaces it instead so the team knows to add an explicit row.
    expect(isModelPriced("gpt-5.5-mini")).toBe(false);
    expect(
      estimateCost({
        ...zeroUsage,
        model: "gpt-5.5-mini",
        input_tokens: 1_000_000,
      }),
    ).toBe(0);
  });

  it("flags hypothetical future variants as unmapped instead of inheriting a relative's price", () => {
    // No exact match → unmapped. Covers both dotted families (`gpt-5.99-codex`)
    // and unknown sub-variants (`gpt-5-foo`); both must miss rather than
    // silently inherit `gpt-5` pricing.
    expect(isModelPriced("gpt-5.99-codex")).toBe(false);
    expect(isModelPriced("gpt-5-foo")).toBe(false);
    // Dash-normalized 5.6 ids must also miss: the real Codex slug is dotted
    // (`gpt-5.6-luna`) and this resolver does NOT dash-normalize non-claude
    // ids, so a dashed variant surfaces as unmapped — matching the backend's
    // literal-dot alias in server/internal/metrics/pricing.go (MUL-4347).
    expect(isModelPriced("gpt-5-6-luna")).toBe(false);
    expect(isModelPriced("gpt-5-6-sol")).toBe(false);
    expect(isModelPriced("gpt-6-astra")).toBe(true);
    expect(isModelPriced("gpt-6-astra-pro")).toBe(false);
    expect(isModelPriced("gpt-6.1-sol-pro")).toBe(false);
    expect(isModelPriced("gpt-6-1-sol")).toBe(false);
    expect(isModelPriced("gpt-6.1-terra-pro")).toBe(false);
    expect(isModelPriced("gpt-6-1-terra")).toBe(false);
    expect(isModelPriced("gpt-6-sol-high")).toBe(false);
    expect(isModelPriced("gpt-6-luna-pro")).toBe(false);
    expect(
      estimateCost({
        ...zeroUsage,
        model: "gpt-5.99-codex",
        input_tokens: 1_000_000,
      }),
    ).toBe(0);
  });

  it("strips `provider:model` routing prefixes (Hermes custom providers) before resolving", () => {
    // Regression: canonicalCandidates only stripped `/` prefixes, so Hermes
    // ids like `alibaba-coding-plan:qwen3.8-max` and `custom:ark-code-latest`
    // never resolved and stayed uncosted. `:` must be stripped like `/`.
    const cost = estimateCost({
      ...zeroUsage,
      provider: "hermes",
      model: "alibaba-coding-plan:qwen3.8-max",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
      cache_read_tokens: 1_000_000,
      cache_write_tokens: 1_000_000,
    });
    // 1M × $2 + 1M × $6 + 1M × $0.17 + 1M × $2.50 = $10.67.
    expect(cost).toBeCloseTo(10.67, 5);
    // `ark-code-latest` is a rolling Volcengine alias, not a stable model
    // identity, so it is deliberately unmapped after the prefix strip.
    expect(isModelPriced("custom:ark-code-latest", "hermes")).toBe(false);
    expect(isModelPriced("kimi-coding:kimi-k3", "hermes")).toBe(true);
  });

  it("prices the Qwen / Kimi models added from models.dev", () => {
    expect(
      estimateCost({
        ...zeroUsage,
        model: "qwen3.7-plus",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBeCloseTo(2.0, 5); // $0.40 + $1.60 (International ≤256K tier)
    expect(
      estimateCost({
        ...zeroUsage,
        model: "kimi-code/k3",
        provider: "kimi",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBeCloseTo(18, 5); // kimi/k3 → $3 + $15
    expect(
      estimateCost({
        ...zeroUsage,
        model: "qwen3.6-flash",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBeCloseTo(1.75, 5); // $0.25 + $1.50 (International ≤256K tier)
    // `ark-code-latest` is a rolling Volcengine alias (target switched in
    // the console, possibly across model families), not a stable model
    // identity — it stays unmapped like grok-composer-*.
    expect(isModelPriced("ark-code-latest")).toBe(false);
  });

  it("keeps subscription-only and preview SKUs distinct from their GA siblings", () => {
    // qwen3.8-max-preview is subscription-priced at 0; it must NOT inherit
    // qwen3.8-max's $2/$6 tier, and `qwen3.8-max-preview[1m]` must resolve
    // to the preview row after the context-tag strip.
    expect(
      estimateCost({
        ...zeroUsage,
        model: "qwen3.8-max-preview[1m]",
        input_tokens: 1_000_000,
      }),
    ).toBe(0);
    expect(
      estimateCost({
        ...zeroUsage,
        model: "qwen3.8-max",
        input_tokens: 1_000_000,
      }),
    ).toBeCloseTo(2, 5);
  });

  it("iteratively strips nested routing prefixes (custom:anthropic/claude-opus-4.7)", () => {
    // Regression for the review blocker: stripProvider used to peel a single
    // `/` or `:` layer, so a Hermes-style `custom:anthropic/claude-opus-4.7`
    // stopped at `anthropic/claude-opus-4.7` and missed the table while the
    // backend substring rules matched it. Iterative peeling must resolve it
    // to the Opus tier: 1M × $5 + 1M × $25 = $30.
    const cost = estimateCost({
      ...zeroUsage,
      provider: "hermes",
      model: "custom:anthropic/claude-opus-4.7",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(30, 5);
    expect(isModelPriced("custom:anthropic/claude-opus-4.7", "hermes")).toBe(true);
  });

  it("keeps unknown suffixed Qwen variants unmapped (anchored aliases)", () => {
    // Regression for the review blocker: the backend alias regexes were
    // unanchored substrings, so `qwen3.7-plus-extra` / `qwen3.8-max-preview-extra`
    // silently borrowed a tier. The frontend exact matcher must agree and
    // leave them unmapped so both sides surface the same diagnostics.
    expect(isModelPriced("qwen3.7-plus-extra")).toBe(false);
    expect(isModelPriced("qwen3.6-flash-extra")).toBe(false);
    expect(isModelPriced("qwen3.8-max-preview-extra")).toBe(false);
  });

  it("returns 0 for a genuinely unknown model so the UI can flag it", () => {
    expect(
      estimateCost({
        ...zeroUsage,
        model: "totally-made-up-model",
        input_tokens: 1_000_000,
      }),
    ).toBe(0);
  });

  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,
        cache_read_tokens: 1_000_000,
        cache_write_tokens: 1_000_000,
      });

    expect(costWithAllTokenTypes("auto")).toBeCloseTo(1.25 + 6 + 0.25, 5);
    expect(costWithAllTokenTypes("composer-2.5-fast")).toBeCloseTo(
      3 + 15 + 0.5,
      5,
    );
    expect(costWithAllTokenTypes("composer-2.5")).toBeCloseTo(0.5 + 2.5 + 0.2, 5);
    expect(costWithAllTokenTypes("composer-2-fast")).toBeCloseTo(
      1.5 + 7.5 + 0.35,
      5,
    );
    expect(costWithAllTokenTypes("composer-2")).toBeCloseTo(0.5 + 2.5 + 0.2, 5);
    expect(costWithAllTokenTypes("composer-1.5")).toBeCloseTo(
      3.5 + 17.5 + 0.35,
      5,
    );
    expect(costWithAllTokenTypes("composer-1")).toBeCloseTo(
      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("prices Cursor catalog variants at their base model's Cursor rate", () => {
    // Cursor ids carry effort / thinking parts the rate doesn't depend on.
    // 1M each of input, output, cache read, cache write.
    const cost = (model: string) =>
      estimateCost({
        ...zeroUsage,
        provider: "cursor",
        model,
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
        cache_read_tokens: 1_000_000,
        cache_write_tokens: 1_000_000,
      });

    const opus55 = 4 + 20 + 0.2 + 5;
    expect(cost("claude-opus-5-5-high")).toBeCloseTo(opus55, 5);
    expect(cost("claude-opus-5-5-max")).toBeCloseTo(opus55, 5);
    expect(cost("claude-fable-5-1-thinking-high")).toBeCloseTo(10 + 50 + 0.25 + 12.5, 5);
    expect(cost("claude-fable-5-2-xhigh")).toBeCloseTo(8 + 40 + 0.2 + 10, 5);
    // Thinking after the effort level, and the older `claude-4.6-sonnet` naming.
    expect(cost("claude-4.6-sonnet-medium-thinking")).toBeCloseTo(3 + 15 + 0.3 + 3.75, 5);
    expect(cost("gpt-5.5-extra-high")).toBeCloseTo(5 + 30 + 0.5, 5);
    expect(cost("gpt-5.6-sol-none")).toBeCloseTo(5 + 30 + 0.5 + 6.25, 5);
    expect(cost("cursor-grok-4.6-high")).toBeCloseTo(2 + 6 + 0.5, 5);
    expect(cost("grok-4.7-medium")).toBeCloseTo(2 + 6 + 0.5, 5);
    expect(cost("gemini-4-argon-medium")).toBeCloseTo(2 + 10 + 0.1, 5);
    expect(cost("gemini-4-hydrogen-high")).toBeCloseTo(1.5 + 7.5 + 0.075, 5);
    expect(cost("gemini-4-hydrogen-xhigh")).toBeCloseTo(1.5 + 7.5 + 0.075, 5);
    // Cursor's post-intro Carbon rate, not the bare row's $2 / $10 intro rate.
    expect(cost("gemini-4-carbon-medium")).toBeCloseTo(4 + 20 + 0.2, 5);
    expect(cost("muse-wonder-1.0-minimal")).toBeCloseTo(4 + 20 + 0.2, 5);
    expect(cost("kimi-k3-max")).toBeCloseTo(3 + 15 + 0.3, 5);
    expect(cost("claude-opus-4-8[context=1m,effort=high,fast=false]")).toBeCloseTo(
      5 + 25 + 0.5 + 6.25,
      5,
    );
  });

  it("prices Cursor Fast variants only where a Fast rate is published", () => {
    const cost = (model: string) =>
      estimateCost({
        ...zeroUsage,
        provider: "cursor",
        model,
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      });

    expect(cost("gpt-5.6-sol-medium-fast")).toBeCloseTo(10 + 60, 5);
    expect(cost("cursor-grok-4.5-high-fast")).toBeCloseTo(4 + 18, 5);
    expect(cost("claude-opus-4-7-thinking-high-fast")).toBeCloseTo(30 + 150, 5);
    expect(cost("claude-opus-4-8[effort=high,fast=true]")).toBeCloseTo(10 + 50, 5);
    // Cursor's sheet doesn't price these Fast variants; the vendor sheet does.
    expect(cost("claude-opus-5-5-xhigh-fast")).toBeCloseTo(8 + 40, 5);
    expect(cost("claude-opus-5-5[fast=true]")).toBeCloseTo(8 + 40, 5);
    expect(cost("claude-opus-5-thinking-high-fast")).toBeCloseTo(10 + 50, 5);
    expect(cost("gpt-5.5-extra-high-fast")).toBeCloseTo(12.5 + 75, 5);
    expect(cost("gpt-5.3-codex-xhigh-fast")).toBeCloseTo(3.5 + 28, 5);
    expect(cost("gpt-5.2-fast")).toBeCloseTo(3.5 + 28, 5);
    // No published Fast rate: unmapped, never the cheaper standard rate.
    expect(isModelPriced("claude-sonnet-5-5-high-fast", "cursor")).toBe(false);
    expect(isModelPriced("kimi-k3-fast", "cursor")).toBe(false);
    expect(isModelPriced("claude-sonnet-5[fast=true]", "cursor")).toBe(false);
    expect(collectUnmappedModels([
      { ...zeroUsage, provider: "cursor", model: "claude-sonnet-5-5-high-fast", input_tokens: 1 },
    ])).toEqual(["cursor/claude-sonnet-5-5-high-fast"]);
  });

  it("prices Cursor catalog ids missing from the base table", () => {
    const cost = (model: string) =>
      estimateCost({
        ...zeroUsage,
        provider: "cursor",
        model,
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
        cache_read_tokens: 1_000_000,
      });
    expect(cost("gpt-5.1-high")).toBeCloseTo(1.25 + 10 + 0.125, 5);
    expect(cost("deepseek-v41-flash-1017-max")).toBeCloseTo(0.3 + 1.2 + 0.006, 5);
  });

  it("keeps Cursor variant stripping scoped to Cursor rows", () => {
    expect(isModelPriced("claude-opus-5-5-high")).toBe(false);
    expect(isModelPriced("claude-opus-5-5-high", "claude")).toBe(false);
    expect(isModelPriced("claude-opus-5-5-high", "cursor")).toBe(true);
  });

  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
  // that copies a price from a near-named neighbour by accident — the
  // mistake the previous attempt (PR #3170, closed) made.
  it("prices the retired deepseek-v4-flash alias at the current Flash peak rate", () => {
    const cost = estimateCost({
      ...zeroUsage,
      model: "deepseek-v4-flash",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
      cache_read_tokens: 1_000_000,
    });
    expect(cost).toBeCloseTo(0.30 + 1.20 + 0.006, 5);
  });

  it("prices the deepseek-chat / deepseek-reasoner aliases at the same rate as deepseek-v4-flash", () => {
    // Preserve the existing Flash routing for these historical aliases.
    const flash = estimateCost({
      ...zeroUsage,
      model: "deepseek-v4-flash",
      input_tokens: 1_000_000,
    });
    expect(
      estimateCost({
        ...zeroUsage,
        model: "deepseek-chat",
        input_tokens: 1_000_000,
      }),
    ).toBeCloseTo(flash, 5);
    expect(
      estimateCost({
        ...zeroUsage,
        model: "deepseek-reasoner",
        input_tokens: 1_000_000,
      }),
    ).toBeCloseTo(flash, 5);
  });

  it("prices documented Flash aliases and the 1017 snapshot at the official peak rate", () => {
    const want = { input: 0.30, output: 1.20, cacheRead: 0.006, cacheWrite: 0.30 };
    for (const model of [
      "deepseek-flash",
      "deepseek/deepseek-flash",
      "custom:deepseek/deepseek-flash[1m]",
      "deepseek-v4-flash",
      "deepseek-v4-flash-vision-exp",
      "deepseek/deepseek-v4-flash-vision-exp",
      "deepseek-chat",
      "deepseek-reasoner",
      "deepseek-v4.1-flash",
      "deepseek/deepseek-v4.1-flash",
      "deepseek/deepseek-v4.1-flash-1017",
      "deepseek-v4.1-flash-1017",
    ]) {
      const usage = {
        ...zeroUsage,
        model,
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
        cache_read_tokens: 1_000_000,
        cache_write_tokens: 1_000_000,
      };
      expect(estimateCostBreakdown(usage), model).toEqual(want);
      expect(estimateCost(usage), model).toBeCloseTo(1.806, 5);
      expect(collectUnmappedModels([usage]), model).toEqual([]);
    }
  });

  it("leaves unknown Flash variants unpriced", () => {
    for (const model of [
      "deepseek-v4.1-pro", "deepseek-v4.1-flash-preview",
      "deepseek-v4-1-flash", "deepseek-v4.1-flash-1020",
      "deepseek-v4.1-flash-1017-preview", "deepseek-flash-preview",
      "deepseek-v4-flash-preview", "deepseek-v4-flash-vision-exp-extra",
    ]) {
      expect(isModelPriced(model), model).toBe(false);
      expect(estimateCost({ ...zeroUsage, model, input_tokens: 1_000_000 }), model).toBe(0);
    }
  });

  it("prices Bedrock-served Anthropic ids like their bare catalog SKUs", () => {
    // Bedrock reports `us.anthropic.<id>` (region family + vendor prefix) and
    // appends the inference-profile version to snapshots. Before the prefix
    // strip none of these matched a table key, so a Bedrock runtime showed
    // $0.00 for every turn while the tokens were still counted.
    const tokens = {
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
      cache_read_tokens: 1_000_000,
      cache_write_tokens: 1_000_000,
    };
    const bareSonnet5 = estimateCost({
      ...zeroUsage,
      model: "claude-sonnet-5",
      ...tokens,
    });
    for (const model of [
      "us.anthropic.claude-sonnet-5",
      "eu.anthropic.claude-sonnet-5",
      "global.anthropic.claude-sonnet-5",
      "anthropic.claude-sonnet-5",
      "custom:bedrock/us.anthropic.claude-sonnet-5-v1:0[1m]",
    ]) {
      expect(estimateCost({ ...zeroUsage, provider: "claude", model, ...tokens })).toBeCloseTo(
        bareSonnet5,
        5,
      );
    }
    // Snapshot + profile version suffix resolves to the same family tier.
    expect(
      estimateCost({
        ...zeroUsage,
        provider: "claude",
        model: "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        input_tokens: 1_000_000,
      }),
    ).toBeCloseTo(3, 5);
    // A non-Anthropic Bedrock model must stay unmapped instead of borrowing a
    // Claude rate.
    expect(isModelPriced("us.amazon.nova-pro-v1:0", "amazon")).toBe(false);
  });

  it("only strips Bedrock versions from recognized Anthropic model ids", () => {
    for (const model of [
      "us.anthropic.claude-sonnet-6",
      "us.anthropic.claude-sonnet-5-preview",
      "global.anthropic.claude-opus-5-mini",
      "us.anthropic.claude-sonnet-5-preview-v1:0",
      "us.anthropic.claude-sonnet-5-v1:0junk",
      "us.anthropic.claude-sonnet-5-v1:0[1m][2m]",
      "gpt-6.1-sol-v1:0",
      "claude-sonnet-5-v1:0",
      "us.anthropic.gpt-6.1-sol-v1:0",
    ]) {
      expect(isModelPriced(model), model).toBe(false);
    }
  });

  it("prices kimi-k2.6 at the official $0.95 / $4.00 tier (not the K2 tier)", () => {
    // Moonshot's K2.6 page is the only authoritative source today; K2.6 is
    // explicitly NOT priced like K2. 1M input × $0.95 + 1M output × $4.00 = $4.95.
    expect(
      estimateCost({
        ...zeroUsage,
        model: "kimi-k2.6",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBeCloseTo(4.95, 5);
  });

  it("prices glm-5.1 at the official $1.4 / $4.4 tier", () => {
    expect(
      estimateCost({
        ...zeroUsage,
        model: "glm-5.1",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBeCloseTo(1.4 + 4.4, 5);
  });

  it("prices glm-4.5-flash at the official Free tier ($0)", () => {
    // z.ai currently ships Free tiers for the *-flash family; $0 is the
    // literal price on the page, not a placeholder. Anything non-zero
    // here would mean we mis-copied a paid SKU's number into the row.
    expect(isModelPriced("glm-4.5-flash")).toBe(true);
    expect(isModelPriced("glm-4.7-flash")).toBe(true);
    expect(
      estimateCost({
        ...zeroUsage,
        model: "glm-4.5-flash",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBe(0);
  });

  it("prices GLM-5.3 and its paid Flash tier at the official z.ai rates", () => {
    // docs.z.ai/guides/overview/pricing (2026-11-11): GLM-5.3 $1.4 / $4.4
    // with $0.26 cached input; GLM-5.3-Flash is the PAID $0.15 / $0.50 tier,
    // unlike the free 4.x flash tiers above.
    for (const c of [
      { model: "glm-5.3", input: 1.4, output: 4.4, cacheRead: 0.26, cacheWrite: 1.4 },
      { model: "glm-5.3-flash", input: 0.15, output: 0.5, cacheRead: 0.03, cacheWrite: 0.15 },
    ]) {
      for (const model of [c.model, `zhipuai/${c.model}`]) {
        const breakdown = estimateCostBreakdown({
          ...zeroUsage, model,
          input_tokens: 1_000_000, output_tokens: 1_000_000,
          cache_read_tokens: 1_000_000, cache_write_tokens: 1_000_000,
        });
        expect(breakdown.input, model).toBeCloseTo(c.input, 5);
        expect(breakdown.output, model).toBeCloseTo(c.output, 5);
        expect(breakdown.cacheRead, model).toBeCloseTo(c.cacheRead, 5);
        expect(breakdown.cacheWrite, model).toBeCloseTo(c.cacheWrite, 5);
      }
    }
    // A Hermes custom provider carries a `custom:` routing prefix.
    expect(collectUnmappedModels([
      { ...zeroUsage, model: "glm-5.3", input_tokens: 1 },
      { ...zeroUsage, provider: "hermes", model: "custom:glm-5.3", input_tokens: 1 },
      { ...zeroUsage, provider: "claude", model: "glm-5.3-flash", input_tokens: 1 },
    ])).toEqual([]);
    // Unknown suffixed variants stay unmapped, matching the anchored
    // backend rules in server/internal/metrics/pricing.go.
    for (const model of ["glm-5.3-flashx", "glm-5.3-fast", "glm-5.3-extra"]) {
      expect(isModelPriced(model), model).toBe(false);
    }
  });

  it("prices Kimi K3.1 Pro under its vendor and provider-qualified keys", () => {
    // platform.kimi.ai/docs/pricing/chat (2026-11-11): $2 / $10 / $0.20
    // cached input, no separate cache write. `k3.1-pro` is a generic id, so
    // it prices only under the provider-qualified `kimi/k3.1-pro` key — a
    // bare `k3.1-pro` from an unknown provider stays unmapped like
    // `cursor/auto`.
    const k311 = 2 + 10 + 0.2 + 2;
    for (const [model, provider] of [
      ["kimi-code/k3.1-pro", "kimi"],
      ["kimi-k3.1-pro", undefined],
      ["kimi-k3.1-pro", "kimi"],
    ] as const) {
      expect(isModelPriced(model, provider), `${provider}/${model}`).toBe(true);
      expect(
        estimateCost({
          ...zeroUsage, provider, model,
          input_tokens: 1_000_000, output_tokens: 1_000_000,
          cache_read_tokens: 1_000_000, cache_write_tokens: 1_000_000,
        }),
        `${provider}/${model}`,
      ).toBeCloseTo(k311, 5);
    }
    // The subscription coding-route alias, the CodeBuddy SKU, the
    // double-price highspeed variant, and the bare id under an unknown or
    // absent provider all stay unmapped.
    for (const [model, provider] of [
      ["kimi-for-coding", "kimi"],
      ["kimi-code/kimi-for-coding", "kimi"],
      ["kimi-k3-1", undefined],
      ["kimi-k3.1-pro-highspeed", undefined],
      ["kimi-code/k3.1-pro-highspeed", "kimi"],
      ["k3.1-pro-highspeed", "kimi"],
      ["k3.1-pro", "acme"],
      ["k3.1-pro", undefined],
    ] as const) {
      expect(isModelPriced(model, provider), `${provider ?? "no-provider"}/${model}`).toBe(false);
    }
  });

  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 grok-4.6 at xAI's short-context $2.00 / $6.00 tier with $0.50 cached input", () => {
    // grok-4.6 cached input is $0.50/1M, not grok-4.5's $0.30.
    // 1M input × $2.00 + 1M output × $6.00 + 1M cached-read × $0.50.
    expect(
      estimateCost({
        ...zeroUsage,
        provider: "xai",
        model: "grok-4.6",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
        cache_read_tokens: 1_000_000,
      }),
    ).toBeCloseTo(8.5, 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);
  });

  // -------------------------------------------------------------------------
  // Provider-reported cost. `cost_usd_ticks` is what the provider actually
  // charged (1e-10 USD) for the rows behind an aggregate; `uncosted_*` are the
  // tokens it did not price and which therefore still need the rate table.
  // -------------------------------------------------------------------------

  it("uses the provider's own cost instead of the rate table when it reports one", () => {
    // Real grok 0.2.106 turn: 2049 uncached input + 10880 cache read + 29
    // output, costUsdTicks 75360000 = $0.007536. Here the rate table would
    // agree, which is what makes it a clean check that the authoritative
    // number is the one being used rather than added to an estimate.
    expect(
      estimateCost({
        ...zeroUsage,
        provider: "grok",
        model: "grok-4.5",
        input_tokens: 2049,
        cache_read_tokens: 10880,
        output_tokens: 29,
        cost_usd_ticks: 75_360_000,
        uncosted_input_tokens: 0,
        uncosted_output_tokens: 0,
        uncosted_cache_read_tokens: 0,
        uncosted_cache_write_tokens: 0,
      }),
    ).toBeCloseTo(0.007536, 10);
  });

  it("keeps the long-context surcharge the rate table cannot express", () => {
    // xAI bills a request at 2x once its prompt reaches 200K tokens. The same
    // tokens priced from the table give the short-context figure; the
    // provider's own number carries the surcharge, and must not be quietly
    // replaced by the cheaper local estimate.
    const tokens = {
      ...zeroUsage,
      provider: "grok",
      model: "grok-4.5",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
    };
    const shortContext = estimateCost(tokens);
    expect(shortContext).toBeCloseTo(8, 5);

    const longContext = estimateCost({
      ...tokens,
      cost_usd_ticks: 16 * 10_000_000_000, // $16 — the 2x tier
      uncosted_input_tokens: 0,
      uncosted_output_tokens: 0,
      uncosted_cache_read_tokens: 0,
      uncosted_cache_write_tokens: 0,
    });
    expect(longContext).toBeCloseTo(16, 5);
  });

  it("adds an estimate for the tokens the provider did not price", () => {
    // A bucket can mix rows that carry a provider cost with rows that don't —
    // two providers in one aggregate, or Grok either side of a CLI upgrade.
    // Reporting only the authoritative half would under-report the bucket.
    expect(
      estimateCost({
        ...zeroUsage,
        provider: "grok",
        model: "grok-4.5",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
        cost_usd_ticks: 4 * 10_000_000_000, // $4 for the priced half
        uncosted_input_tokens: 1_000_000, // $2 at the table rate
        uncosted_output_tokens: 1_000_000, // $6 at the table rate
        uncosted_cache_read_tokens: 0,
        uncosted_cache_write_tokens: 0,
      }),
    ).toBeCloseTo(12, 5);
  });

  it("falls back to estimating the full row when the backend omits the split", () => {
    // A backend older than the cost split sends no `uncosted_*` fields.
    // Treating that as "nothing left to estimate" would report $0 for every
    // row, so an absent split must estimate the full token counts.
    expect(
      estimateCost({
        ...zeroUsage,
        provider: "grok",
        model: "grok-4.5",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBeCloseTo(8, 5);
  });

  it("does not double-charge a cost that arrives without its token split", () => {
    // Defensive: an authoritative cost with no `uncosted_*` must not also get
    // a full-row estimate stacked on top.
    expect(
      estimateCost({
        ...zeroUsage,
        provider: "grok",
        model: "grok-4.5",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
        cost_usd_ticks: 16 * 10_000_000_000,
      }),
    ).toBeCloseTo(16, 5);
  });

  it("reports provider cost even for a model with no rate-table row", () => {
    // `grok-composer-*` has no published rate, but a turn the provider priced
    // itself needs no rate — the money is known exactly.
    expect(
      estimateCost({
        ...zeroUsage,
        provider: "grok",
        model: "grok-composer-2.5-fast",
        input_tokens: 500,
        output_tokens: 100,
        cost_usd_ticks: 12_345_678_900,
        uncosted_input_tokens: 0,
        uncosted_output_tokens: 0,
        uncosted_cache_read_tokens: 0,
        uncosted_cache_write_tokens: 0,
      }),
    ).toBeCloseTo(1.23456789, 8);
  });

  it("keeps the breakdown and the headline agreeing on an unpriced model", () => {
    // `grok-composer-*` has no rate row, so there is nothing to split by — but
    // the provider priced the turn. If the breakdown returned zeros here the
    // stacked chart would read $0 while the headline read the real cost, and
    // the unmapped banner (correctly) would not be shown to explain it.
    const usage = {
      ...zeroUsage,
      provider: "grok",
      model: "grok-composer-2.5-fast",
      input_tokens: 500,
      output_tokens: 100,
      cost_usd_ticks: 12_345_678_900,
      uncosted_input_tokens: 0,
      uncosted_output_tokens: 0,
      uncosted_cache_read_tokens: 0,
      uncosted_cache_write_tokens: 0,
    };
    const b = estimateCostBreakdown(usage);
    expect(b.input + b.output + b.cacheRead + b.cacheWrite).toBeCloseTo(
      estimateCost(usage),
      8,
    );
    expect(b.input).toBeCloseTo(1.23456789, 8);
  });

  it("reports no cost for an unpriced model the provider did not price either", () => {
    // The control for the case above: no rates and no provider cost must stay
    // at zero rather than inventing a figure.
    const usage = {
      ...zeroUsage,
      provider: "grok",
      model: "grok-composer-2.5-fast",
      input_tokens: 500,
      output_tokens: 100,
    };
    expect(estimateCost(usage)).toBe(0);
    const b = estimateCostBreakdown(usage);
    expect(b.input + b.output + b.cacheRead + b.cacheWrite).toBe(0);
    // ...and it still asks the user for a rate, because one would help here.
    expect(collectUnmappedModels([usage])).toEqual(["grok/grok-composer-2.5-fast"]);
  });

  it("keeps the cost breakdown summing to the total on provider-priced rows", () => {
    // The stacked chart is drawn from the breakdown while the headline uses
    // estimateCost; if the authoritative charge were dropped from the split
    // the two would silently disagree on every Grok row.
    const usage = {
      ...zeroUsage,
      provider: "grok",
      model: "grok-4.5",
      input_tokens: 1_000_000,
      output_tokens: 1_000_000,
      cost_usd_ticks: 16 * 10_000_000_000,
      uncosted_input_tokens: 0,
      uncosted_output_tokens: 0,
      uncosted_cache_read_tokens: 0,
      uncosted_cache_write_tokens: 0,
    };
    const b = estimateCostBreakdown(usage);
    expect(b.input + b.output + b.cacheRead + b.cacheWrite).toBeCloseTo(
      estimateCost(usage),
      5,
    );
    // Split follows the rate table's own proportions ($2 input : $6 output).
    expect(b.input).toBeCloseTo(4, 5);
    expect(b.output).toBeCloseTo(12, 5);
  });

  it("drops a fully provider-priced model from the unmapped diagnostic", () => {
    // The banner asks the user to supply a missing rate. A row the provider
    // priced in full needs no rate, so prompting for one would invite
    // overriding a real bill with a guess.
    const row = {
      ...zeroUsage,
      provider: "grok",
      model: "grok-composer-2.5-fast",
      input_tokens: 500,
      cost_usd_ticks: 12_345_678_900,
      uncosted_input_tokens: 0,
      uncosted_output_tokens: 0,
      uncosted_cache_read_tokens: 0,
      uncosted_cache_write_tokens: 0,
    };
    expect(collectUnmappedModels([row])).toEqual([]);
    // ...but the same model still surfaces while any of its tokens are
    // unpriced, because those genuinely need a rate.
    expect(
      collectUnmappedModels([{ ...row, uncosted_input_tokens: 500 }]),
    ).toEqual(["grok/grok-composer-2.5-fast"]);
  });

  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 above
    // would only fire on bare IDs and the dashboard would still show
    // $0.00 for the runtime that actually triggered this work.
    expect(isModelPriced("deepseek/deepseek-v4-flash")).toBe(true);
    expect(isModelPriced("moonshotai/kimi-k2.6")).toBe(true);
    expect(isModelPriced("zhipuai/glm-5.1")).toBe(true);
    expect(isModelPriced("zhipuai/glm-4.5-air")).toBe(true);
  });
});

describe("isModelPriced", () => {
  it("recognises both Claude and Codex/GPT families", () => {
    expect(isModelPriced("claude-sonnet-5")).toBe(true);
    expect(isModelPriced("claude-fable-5")).toBe(true);
    expect(isModelPriced("claude-fable-5-1")).toBe(true);
    expect(isModelPriced("claude-fable-5-2")).toBe(true);
    expect(isModelPriced("claude-sonnet-4-6")).toBe(true);
    expect(isModelPriced("gpt-5-codex")).toBe(true);
    expect(isModelPriced("gpt-5-mini")).toBe(true);
    expect(isModelPriced("o3")).toBe(true);
    expect(isModelPriced("totally-made-up-model")).toBe(false);
  });

  it("recognises dotted Anthropic IDs as the same SKU as their dashed canonical form", () => {
    // GitHub Copilot reports Claude models with dots (`claude-opus-4.7`)
    // while Anthropic's own CLIs use dashes (`claude-opus-4-7`). Both must
    // hit the same catalog row, otherwise Copilot-routed usage gets bucketed
    // as "unmapped" and the user has to type the price in by hand.
    expect(isModelPriced("claude-sonnet-5")).toBe(true);
    expect(isModelPriced("claude-fable-5.1")).toBe(true);
    expect(isModelPriced("claude-haiku-4.5")).toBe(true);
    expect(isModelPriced("claude-sonnet-4.5")).toBe(true);
    expect(isModelPriced("claude-sonnet-4.6")).toBe(true);
    expect(isModelPriced("claude-opus-4.5")).toBe(true);
    expect(isModelPriced("claude-opus-4.6")).toBe(true);
    expect(isModelPriced("claude-opus-4.7")).toBe(true);
  });

  it("recognises provider-prefixed Anthropic IDs (openclaw / opencode form)", () => {
    // openclaw / opencode emit `<provider>/<model>` in `meta.agentMeta.model`.
    // The provider prefix is routing metadata, not part of the SKU.
    expect(isModelPriced("anthropic/claude-sonnet-5")).toBe(true);
    expect(isModelPriced("anthropic/claude-fable-5")).toBe(true);
    expect(isModelPriced("anthropic/claude-fable-5-1")).toBe(true);
    expect(isModelPriced("anthropic/claude-opus-4.7")).toBe(true);
    expect(isModelPriced("anthropic/claude-sonnet-4-6")).toBe(true);
  });

  it("still rejects OpenAI dotted variants that don't have their own row", () => {
    // The Anthropic dot→dash normalization is scoped to `claude-*` IDs.
    // For OpenAI the separator is semantic — `gpt-5.4` is a different SKU
    // from a hypothetical `gpt-5-4` — and `gpt-5.5-mini` must still surface
    // as unmapped because OpenAI hasn't published its rate.
    expect(isModelPriced("gpt-5.5-mini")).toBe(false);
  });
});

describe("collectUnmappedModels", () => {
  it("only surfaces names that miss every pricing tier", () => {
    const rows = [
      { ...zeroUsage, model: "claude-sonnet-4-6" },
      { ...zeroUsage, model: "gpt-5-codex" },
      { ...zeroUsage, model: "fictional-model-x" },
    ];
    expect(collectUnmappedModels(rows)).toEqual(["fictional-model-x"]);
  });
});

describe("user-supplied custom pricing", () => {
  it("prices a model the maintained catalog doesn't ship", () => {
    useCustomPricingStore.getState().setCustomPricing("gpt-5.5-mini", {
      input: 1,
      output: 4,
      cacheRead: 0.1,
      cacheWrite: 1,
    });
    expect(isModelPriced("gpt-5.5-mini")).toBe(true);
    expect(
      estimateCost({
        ...zeroUsage,
        model: "gpt-5.5-mini",
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      }),
    ).toBeCloseTo(5, 5);
  });

  it("does NOT shadow the maintained catalog when both define the same model", () => {
    // Catalog wins so a user can't accidentally over-charge themselves for
    // a model we already track (and so a stale local override doesn't
    // silently disagree with what the dashboard shows everyone else).
    useCustomPricingStore.getState().setCustomPricing("claude-sonnet-4-6", {
      input: 999,
      output: 999,
      cacheRead: 999,
      cacheWrite: 999,
    });
    expect(
      estimateCost({
        ...zeroUsage,
        model: "claude-sonnet-4-6",
        input_tokens: 1_000_000,
      }),
    ).toBeCloseTo(3, 5); // maintained input rate, not the 999 override
  });

  it("falls back to a stripped dated snapshot in the custom store", () => {
    useCustomPricingStore.getState().setCustomPricing("brand-new-model", {
      input: 2,
      output: 8,
      cacheRead: 0.2,
      cacheWrite: 2,
    });
    expect(
      estimateCost({
        ...zeroUsage,
        model: "brand-new-model-2026-04-01",
        input_tokens: 1_000_000,
      }),
    ).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", {
      input: 1,
      output: 4,
      cacheRead: 0.1,
      cacheWrite: 1,
    });
    expect(isModelPriced("gpt-5.5-mini")).toBe(true);
    useCustomPricingStore.getState().removeCustomPricing("gpt-5.5-mini");
    expect(isModelPriced("gpt-5.5-mini")).toBe(false);
  });

  it("priced + unpriced models in the same window produce a mixed-cost aggregate", () => {
    // The partial-unmapping case: chart renders normally because some
    // models are priced, but the unmapped ones silently contribute $0 if
    // we don't surface them. Confirm aggregateCostByModel exposes both
    // sides so the UI can show a notice for the gap.
    const rows = [
      {
        ...zeroUsage,
        model: "claude-sonnet-4-6",
        input_tokens: 1_000_000,
        date: "2026-01-01",
        provider: "anthropic",
        agent_count: 1,
      },
      {
        ...zeroUsage,
        model: "fictional-model-x",
        input_tokens: 1_000_000,
        date: "2026-01-01",
        provider: "fictional",
        agent_count: 1,
      },
    ];
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const 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/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
    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", () => {
    // Regression for the memo-dependency bug GPT-Boy flagged: aggregate
    // helpers must give different answers before vs after a price save,
    // otherwise child components (WhenChart / CostByBlock / ActivityHeatmap)
    // that memo on query data alone keep showing pre-save totals.
    const rows = [
      {
        ...zeroUsage,
        model: "fictional-model-x",
        input_tokens: 1_000_000,
        date: "2026-01-01",
        provider: "fictional",
        agent_count: 1,
      },
    ];
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const before = aggregateCostByModel(rows as any);
    expect(before[0]?.cost).toBe(0);

    useCustomPricingStore.getState().setCustomPricing("fictional-model-x", {
      input: 2,
      output: 8,
      cacheRead: 0.2,
      cacheWrite: 2,
    });
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const after = aggregateCostByModel(rows as any);
    expect(after[0]?.cost).toBeCloseTo(2, 5);
  });
});

// ---------------------------------------------------------------------------
// Calendar helpers + weekly aggregation. All of these run on YYYY-MM-DD
// strings (the wire shape of RuntimeUsage.date) and on a runtime-supplied
// IANA timezone — the host browser's tz should never affect the result.
// ---------------------------------------------------------------------------

describe("weekStartIso", () => {
  it("returns the Monday of the same ISO week", () => {
    // 2026-05-19 is a Tuesday → Monday is 2026-05-18.
    expect(weekStartIso("2026-05-19")).toBe("2026-05-18");
  });

  it("treats Monday as the start of its own week (idempotent)", () => {
    expect(weekStartIso("2026-05-18")).toBe("2026-05-18");
  });

  it("rolls Sunday back to the previous Monday", () => {
    // 2026-05-17 is a Sunday → Monday is 2026-05-11.
    expect(weekStartIso("2026-05-17")).toBe("2026-05-11");
  });

  it("crosses month and year boundaries", () => {
    // 2026-01-03 is a Saturday → Monday is 2025-12-29.
    expect(weekStartIso("2026-01-03")).toBe("2025-12-29");
  });
});

describe("addDaysIso", () => {
  it("adds across month boundary", () => {
    expect(addDaysIso("2026-05-30", 3)).toBe("2026-06-02");
  });

  it("subtracts across year boundary", () => {
    expect(addDaysIso("2026-01-02", -5)).toBe("2025-12-28");
  });
});

describe("todayIso", () => {
  beforeEach(() => {
    vi.useFakeTimers();
  });
  afterEach(() => {
    vi.useRealTimers();
  });

  it("uses the runtime's timezone, not the host's, to decide today", () => {
    // 2026-05-19 16:00 UTC. In Asia/Shanghai (UTC+8) it's already 2026-05-20.
    // In America/Los_Angeles (UTC-7 on this date) it's still 2026-05-19.
    vi.setSystemTime(new Date("2026-05-19T16:00:00Z"));
    expect(todayIso("Asia/Shanghai")).toBe("2026-05-20");
    expect(todayIso("America/Los_Angeles")).toBe("2026-05-19");
    expect(todayIso("UTC")).toBe("2026-05-19");
  });
});

describe("sliceWindow (timezone-aware)", () => {
  beforeEach(() => {
    vi.useFakeTimers();
  });
  afterEach(() => {
    vi.useRealTimers();
  });

  function makeUsage(date: string): RuntimeUsage {
    return {
      runtime_id: "r",
      date,
      provider: "anthropic",
      model: "claude-sonnet-4-6",
      input_tokens: 0,
      output_tokens: 0,
      cache_read_tokens: 0,
      cache_write_tokens: 0,
    };
  }

  it("cuts the current window at today-in-tz, not today-in-host-utc", () => {
    // Host clock is 2026-05-19 23:00 UTC → still May 19 in UTC, May 20 in Shanghai.
    // A daily-usage row dated 2026-05-20 (the runtime's "today" in Shanghai)
    // should be included in the current window when tz=Asia/Shanghai.
    vi.setSystemTime(new Date("2026-05-19T23:00:00Z"));
    const usage = [
      makeUsage("2026-05-13"),
      makeUsage("2026-05-19"),
      makeUsage("2026-05-20"),
    ];
    // The Shanghai window is 05-14..05-20, so 05-13 falls out; a cutoff read
    // from the host clock (today 05-19) would have kept it.
    const { filtered } = sliceWindow(usage, 7, "Asia/Shanghai");
    expect(filtered.map((u) => u.date)).toEqual([
      "2026-05-19",
      "2026-05-20",
    ]);
  });

  it("returns the immediately prior window of equal length", () => {
    vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));
    const usage = [
      makeUsage("2026-05-01"),
      makeUsage("2026-05-08"),
      makeUsage("2026-05-15"),
      makeUsage("2026-05-19"),
    ];
    const { filtered, prevFiltered } = sliceWindow(usage, 7, "UTC");
    expect(filtered.map((u) => u.date)).toEqual(["2026-05-15", "2026-05-19"]);
    expect(prevFiltered.map((u) => u.date)).toEqual(["2026-05-08"]);
  });

  it("covers exactly `days` calendar days, today included, in both windows", () => {
    vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));
    const usage = [
      makeUsage("2026-05-05"),
      makeUsage("2026-05-06"),
      makeUsage("2026-05-12"),
      makeUsage("2026-05-13"),
      makeUsage("2026-05-19"),
    ];
    const { filtered, prevFiltered } = sliceWindow(usage, 7, "UTC");
    expect(filtered.map((u) => u.date)).toEqual(["2026-05-13", "2026-05-19"]);
    expect(prevFiltered.map((u) => u.date)).toEqual(["2026-05-06", "2026-05-12"]);
  });
});

describe("aggregateByDate", () => {
  // MUL-6334: the daily cost stack computed `estimateCostBreakdown` and then
  // summed only three of its four components, silently dropping cache-read
  // spend from every bar and from the tooltip Total that sums them.
  function makeUsage(
    date: string,
    tokens: Partial<{
      input: number;
      output: number;
      cacheRead: number;
      cacheWrite: number;
    }>,
    model = "gpt-5.6-sol",
  ): RuntimeUsage {
    return {
      runtime_id: "r",
      date,
      provider: "openai",
      model,
      input_tokens: tokens.input ?? 0,
      output_tokens: tokens.output ?? 0,
      cache_read_tokens: tokens.cacheRead ?? 0,
      cache_write_tokens: tokens.cacheWrite ?? 0,
    };
  }

  it("bills cache reads in the daily stack and its total", () => {
    // gpt-5.6-sol: input $5/M, output $30/M, cacheRead $0.50/M.
    const rows = [
      makeUsage("2026-05-11", { input: 1_000_000, cacheRead: 10_000_000 }),
    ];
    const { dailyCostStack } = aggregateByDate(rows);
    const day = dailyCostStack[0];
    expect(day?.cacheRead).toBeCloseTo(5, 2);
    expect(day?.total).toBeCloseTo(10, 2);
  });

  it("keeps every daily bucket's total equal to the sum of estimateCost", () => {
    // The invariant the reporter asked for. A cache-read-dominated workload is
    // the only shape that catches the regression: with zero cache reads the
    // broken and fixed totals are identical.
    const rows = [
      makeUsage("2026-05-11", {
        input: 4_300_000,
        output: 456_400,
        cacheRead: 79_300_000,
      }),
      makeUsage("2026-05-11", { input: 1_000, output: 500 }),
      makeUsage("2026-05-12", { cacheRead: 50_000_000 }),
      // Anthropic rows exercise the cache-write segment too.
      makeUsage(
        "2026-05-12",
        { input: 200_000, output: 20_000, cacheRead: 8_000_000, cacheWrite: 400_000 },
        "claude-sonnet-4-6",
      ),
    ];
    const { dailyCostStack } = aggregateByDate(rows);
    expect(dailyCostStack).toHaveLength(2);
    for (const day of dailyCostStack) {
      const expected = rows
        .filter((r) => r.date === day.date)
        .reduce((sum, r) => sum + estimateCost(r), 0);
      // Each of the four segments is rounded to cents before being summed —
      // that is what keeps the tooltip footer equal to the bars above it — so
      // the bucket can sit up to half a cent per segment off the exact figure.
      // The tolerance is the rounding, not slack for a dropped category: a
      // missing segment shows up as dollars, not cents.
      expect(Math.abs(day.total - expected)).toBeLessThanOrEqual(0.02);
      // Total is what the tooltip footer prints; the segments are what it
      // sums to get there. They have to be exactly the same number.
      expect(day.input + day.output + day.cacheRead + day.cacheWrite).toBeCloseTo(
        day.total,
        10,
      );
    }
  });

  it("reproduces the reported gpt-5.6-sol undercount", () => {
    // The exact workload from the bug report: the chart showed $35.19 against
    // a true $74.84, hiding $39.65 (53%) of spend.
    const rows = [
      makeUsage("2026-05-11", {
        input: 4_300_000,
        output: 456_400,
        cacheRead: 79_300_000,
      }),
    ];
    const { dailyCostStack, dailyCost } = aggregateByDate(rows);
    expect(dailyCostStack[0]?.total).toBeCloseTo(74.84, 2);
    // The non-stacked series always included cache reads; the stack now agrees
    // with it, which is what makes the chart agree with the Cost KPI.
    expect(dailyCostStack[0]?.total).toBeCloseTo(dailyCost[0]?.cost ?? 0, 2);
  });

  it("still reports a non-zero total when spend is entirely cache reads", () => {
    // `total` gates the chart's empty state, which blames an unmapped model
    // when it reads 0. A cache-read-only bucket used to trip that.
    const rows = [makeUsage("2026-05-11", { cacheRead: 20_000_000 })];
    const { dailyCostStack } = aggregateByDate(rows);
    expect(dailyCostStack[0]?.total).toBeCloseTo(10, 2);
  });
});

describe("aggregateByWeek", () => {
  beforeEach(() => {
    vi.useFakeTimers();
  });
  afterEach(() => {
    vi.useRealTimers();
  });

  function makeUsage(
    date: string,
    input: number,
    output: number,
    cacheRead = 0,
    cacheWrite = 0,
  ): RuntimeUsage {
    return {
      runtime_id: "r",
      date,
      provider: "anthropic",
      model: "claude-sonnet-4-6",
      input_tokens: input,
      output_tokens: output,
      cache_read_tokens: cacheRead,
      cache_write_tokens: cacheWrite,
    };
  }

  it("groups daily rows into Mon-anchored ISO weeks", () => {
    // 2026-05-24 is Sunday, so the calendar week containing "today" is
    // Mon=05-18..Sun=05-24. With weekCount=2 the window covers weeks
    // 2026-05-11 and 2026-05-18 — exactly the two weeks the rows fall in.
    vi.setSystemTime(new Date("2026-05-24T12:00:00Z"));
    // 2026-05-11 is Mon; 2026-05-17 is Sun (same week).
    // 2026-05-18 is Mon (next week).
    const rows = [
      makeUsage("2026-05-11", 1_000_000, 0),
      makeUsage("2026-05-17", 0, 1_000_000),
      makeUsage("2026-05-18", 2_000_000, 0),
    ];
    const { weeklyTokens } = aggregateByWeek(rows, "UTC", 2);
    expect(weeklyTokens).toHaveLength(2);
    expect(weeklyTokens[0]).toMatchObject({
      weekStart: "2026-05-11",
      weekEnd: "2026-05-17",
      input: 1_000_000,
      output: 1_000_000,
      partial: false,
      daysCovered: 7,
    });
    expect(weeklyTokens[1]).toMatchObject({
      weekStart: "2026-05-18",
      weekEnd: "2026-05-24",
      input: 2_000_000,
      partial: false,
      daysCovered: 7,
    });
  });

  it("flags the in-progress week as partial with days-elapsed count", () => {
    // 2026-05-20 is a Wednesday (Mon=05-18, Sun=05-24).
    vi.setSystemTime(new Date("2026-05-20T08:00:00Z"));
    const rows = [makeUsage("2026-05-18", 1_000_000, 0)];
    const { weeklyTokens } = aggregateByWeek(rows, "UTC", 1);
    expect(weeklyTokens[0]).toMatchObject({
      weekStart: "2026-05-18",
      weekEnd: "2026-05-24",
      partial: true,
      daysCovered: 3, // Mon, Tue, Wed
    });
  });

  it("sums costs per week using the model pricing table", () => {
    // 2026-05-17 sits in the calendar week of 2026-05-11..2026-05-17, so
    // weekCount=1 anchors the window on that same week.
    vi.setSystemTime(new Date("2026-05-17T12:00:00Z"));
    // 1M input × $3 + 1M output × $15 = $18 per row. Two rows in the same
    // week (Mon + Wed) → $36 weekly total.
    const rows = [
      makeUsage("2026-05-11", 1_000_000, 1_000_000),
      makeUsage("2026-05-13", 1_000_000, 1_000_000),
    ];
    const { weeklyCostStack } = aggregateByWeek(rows, "UTC", 1);
    expect(weeklyCostStack).toHaveLength(1);
    expect(weeklyCostStack[0]?.total).toBeCloseTo(36, 2);
  });

  it("bills cache reads in the weekly stack and its total (MUL-6334)", () => {
    vi.setSystemTime(new Date("2026-05-17T12:00:00Z"));
    // claude-sonnet-4-6: input $3/M, output $15/M, cacheRead $0.30/M,
    // cacheWrite $3.75/M. Row: $3 + $15 + $6 (20M cache reads) + $3.75 = $27.75.
    const rows = [
      makeUsage("2026-05-11", 1_000_000, 1_000_000, 20_000_000, 1_000_000),
    ];
    const { weeklyCostStack } = aggregateByWeek(rows, "UTC", 1);
    const week = weeklyCostStack[0];
    expect(week?.cacheRead).toBeCloseTo(6, 2);
    expect(week?.total).toBeCloseTo(27.75, 2);
    // Same invariant the daily stack holds: bucket total === sum of estimateCost.
    expect(week?.total).toBeCloseTo(
      rows.reduce((sum, r) => sum + estimateCost(r), 0),
      2,
    );
  });

  it("emits trailing calendar weeks pinned to today, dropping older populated weeks", () => {
    // Regression for MUL-2382 weekly window scoping:
    // before the fix, aggregateByWeek built buckets only for weeks that had
    // data and the caller did `.slice(-weekCount)`. With sparse data (an old
    // populated week far outside the selected window plus an empty stretch
    // closer to today), that slice would surface the OLD populated week
    // instead of the trailing in-window weeks. The chart should now show
    // exactly the trailing calendar weeks, with the empty in-range weeks
    // present as zero-valued buckets rather than disappearing.
    vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));
    // 30-day window @ 2026-05-19 → 5 trailing weeks (Mon=04-20, 04-27,
    // 05-04, 05-11, 05-18). 2026-04-13 (Mon) is one week earlier — outside
    // the window. No data in any of the 5 in-range weeks.
    const rows = [makeUsage("2026-04-13", 1_000_000, 1_000_000)];
    const { weeklyTokens, weeklyCostStack } = aggregateByWeek(rows, "UTC", 5);

    expect(weeklyTokens.map((w) => w.weekStart)).toEqual([
      "2026-04-20",
      "2026-04-27",
      "2026-05-04",
      "2026-05-11",
      "2026-05-18",
    ]);
    // Every in-range week is empty — the old populated week was dropped.
    for (const w of weeklyTokens) {
      expect(w.input).toBe(0);
      expect(w.output).toBe(0);
      expect(w.cacheRead).toBe(0);
      expect(w.cacheWrite).toBe(0);
    }
    for (const w of weeklyCostStack) {
      expect(w.total).toBe(0);
    }
  });

  it("keeps in-window weeks empty when nearby data sits inside the window", () => {
    // Sparse-but-in-range case: only the oldest in-window week has data;
    // the remaining trailing weeks must render as empty buckets, not be
    // collapsed to a single populated bar.
    vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));
    const rows = [makeUsage("2026-04-22", 1_000_000, 1_000_000)]; // week of 04-20
    const { weeklyTokens } = aggregateByWeek(rows, "UTC", 5);
    expect(weeklyTokens).toHaveLength(5);
    expect(weeklyTokens[0]).toMatchObject({
      weekStart: "2026-04-20",
      input: 1_000_000,
      output: 1_000_000,
    });
    for (const w of weeklyTokens.slice(1)) {
      expect(w.input).toBe(0);
      expect(w.output).toBe(0);
    }
  });
});

// computeCostInWindow drives the runtime-list cost cell and its ↑/↓ delta.
// The `tz` argument was inserted as the THIRD positional parameter (before
// `offsetDays`) in the timezone-architecture RFC — a positional-arg slip
// here is otherwise silent, so the window math, the end-exclusive boundary,
// the offset shift, and the tz-of-"today" all need explicit coverage.
describe("computeCostInWindow", () => {
  beforeEach(() => {
    vi.useFakeTimers();
  });
  afterEach(() => {
    vi.useRealTimers();
  });

  // claude-sonnet-4-6 is priced at $3 / 1M input tokens, so a row with
  // 1M input tokens contributes exactly $3.
  function priced(date: string, inputTokens: number): RuntimeUsage {
    return {
      runtime_id: "r",
      date,
      provider: "anthropic",
      model: "claude-sonnet-4-6",
      input_tokens: inputTokens,
      output_tokens: 0,
      cache_read_tokens: 0,
      cache_write_tokens: 0,
    };
  }

  it("sums cost over the trailing daysBack window, end-exclusive of today", () => {
    // 2026-05-19 23:00 UTC is already 2026-05-20 in Asia/Shanghai, so
    // "today" is 2026-05-20 and the 7-day window is [2026-05-13, 2026-05-20).
    vi.setSystemTime(new Date("2026-05-19T23:00:00Z"));
    const rows = [
      priced("2026-05-12", 1_000_000), // before window — excluded
      priced("2026-05-13", 1_000_000), // window start — included
      priced("2026-05-19", 1_000_000), // included
      priced("2026-05-20", 1_000_000), // today — excluded (end-exclusive)
    ];
    expect(computeCostInWindow(rows, 7, "Asia/Shanghai")).toBeCloseTo(6, 5);
  });

  it("offsetDays shifts the window back to the prior period", () => {
    // today = 2026-05-20; offsetDays=7, daysBack=7 → window [05-06, 05-13).
    vi.setSystemTime(new Date("2026-05-20T12:00:00Z"));
    const rows = [
      priced("2026-05-05", 1_000_000), // before prior window — excluded
      priced("2026-05-06", 1_000_000), // prior window start — included
      priced("2026-05-12", 1_000_000), // included
      priced("2026-05-13", 1_000_000), // in the current window, not prior — excluded
    ];
    expect(computeCostInWindow(rows, 7, "UTC", 7)).toBeCloseTo(6, 5);
  });

  it("reads 'today' in the supplied tz, not the host clock", () => {
    // Host clock is 2026-05-19 in UTC but already 2026-05-20 in Shanghai.
    // A row dated 2026-05-19 falls inside the 1-day window only when the
    // tz pushes "today" forward to 2026-05-20.
    vi.setSystemTime(new Date("2026-05-19T20:00:00Z"));
    const rows = [priced("2026-05-19", 1_000_000)];
    expect(computeCostInWindow(rows, 1, "UTC")).toBe(0); // today=05-19, window [05-18,05-19)
    expect(computeCostInWindow(rows, 1, "Asia/Shanghai")).toBeCloseTo(3, 5);
  });

  it("returns 0 for an unpriced model rather than NaN", () => {
    vi.setSystemTime(new Date("2026-05-20T12:00:00Z"));
    const rows: RuntimeUsage[] = [
      { ...priced("2026-05-19", 1_000_000), model: "totally-made-up-model" },
    ];
    expect(computeCostInWindow(rows, 7, "UTC")).toBe(0);
  });

  it("returns 0 for an empty row set", () => {
    vi.setSystemTime(new Date("2026-05-20T12:00:00Z"));
    expect(computeCostInWindow([], 7, "UTC")).toBe(0);
  });
});

describe("summarizeTaskUsage", () => {
  // claude-opus-5: 5 / 25 / 0.50 / 6.25 per million.
  const opus = {
    provider: "anthropic",
    model: "claude-opus-5",
    input_tokens: 96_000,
    output_tokens: 34_000,
    cache_read_tokens: 712_000,
    cache_write_tokens: 50_000,
  };
  // gpt-5.6-terra: 2 / 12 / 0.20 / 2.50 per million.
  const terra = {
    provider: "openai",
    model: "gpt-5.6-terra",
    input_tokens: 31_000,
    output_tokens: 12_000,
    cache_read_tokens: 158_000,
    cache_write_tokens: 11_000,
  };

  it("sums every token bucket into the headline figure", () => {
    const s = summarizeTaskUsage([opus]);
    expect(s?.tokens).toBe(96_000 + 34_000 + 712_000 + 50_000);
    expect(s?.input).toBe(96_000);
    expect(s?.cacheWrite).toBe(50_000);
    expect(s?.models).toEqual(["claude-opus-5"]);
  });

  it("prices each model slice at its own rate, not the combined total", () => {
    // Priced separately: 1.9985 (opus) + 0.2651 (terra).
    // Priced as one blob at either rate, the answer would be wrong.
    const s = summarizeTaskUsage([opus, terra]);
    expect(s?.cost).toBeCloseTo(1.9985 + 0.2651, 5);
    expect(s?.models).toEqual(["claude-opus-5", "gpt-5.6-terra"]);
  });

  it("prefers the provider's own cost over the rate table", () => {
    // 3e10 ticks = $3.00, well above what the rate table would charge, so a
    // rate-table result would be visibly different.
    const s = summarizeTaskUsage([{ ...opus, cost_usd_ticks: 30_000_000_000 }]);
    expect(s?.cost).toBeCloseTo(3, 5);
  });

  it("returns null for no usage rather than a zeroed summary", () => {
    // Both must be null: a run with no recorded usage was not free, and a
    // 0 here would render as "$0.00" and assert that it was.
    expect(summarizeTaskUsage(undefined)).toBeNull();
    expect(summarizeTaskUsage([])).toBeNull();
  });

  it("counts tokens for an unpriced model but leaves its cost at 0", () => {
    const s = summarizeTaskUsage([{ ...opus, model: "totally-made-up-model" }]);
    expect(s?.tokens).toBe(892_000);
    expect(s?.cost).toBe(0);
  });

  it("reports cache savings against full input pricing", () => {
    // 712K cache reads at opus: would have cost 5/M, actually cost 0.50/M.
    const s = summarizeTaskUsage([opus]);
    expect(s?.cacheSavings).toBeCloseTo((712_000 * (5 - 0.5)) / 1_000_000, 5);
  });
});

describe("summarizeTaskUsageAcross", () => {
  const slice = {
    model: "claude-opus-5",
    input_tokens: 1_000_000,
    output_tokens: 0,
    cache_read_tokens: 0,
    cache_write_tokens: 0,
  };

  it("skips runs with no usage instead of nulling the whole total", () => {
    const total = summarizeTaskUsageAcross([[slice], undefined, [], [slice]]);
    expect(total?.tokens).toBe(2_000_000);
    expect(total?.cost).toBeCloseTo(10, 5);
  });

  it("is null only when no run has any usage", () => {
    expect(summarizeTaskUsageAcross([undefined, [], undefined])).toBeNull();
    expect(summarizeTaskUsageAcross([])).toBeNull();
  });
});

describe("formatTokens", () => {
  it("uses a compact unit ladder for large token counts", () => {
    expect(formatTokens(999)).toBe("999");
    expect(formatTokens(1_000)).toBe("1K");
    expect(formatTokens(1_050)).toBe("1.1K");
    expect(formatTokens(1_000_000)).toBe("1M");
    expect(formatTokens(2_200_000_000)).toBe("2.2B");
    expect(formatTokens(29_513_100_000)).toBe("29.5B");
    expect(formatTokens(1_000_000_000_000)).toBe("1T");
  });

  it("promotes values that round across a unit boundary", () => {
    expect(formatTokens(999_949)).toBe("999.9K");
    expect(formatTokens(999_950)).toBe("1M");
    expect(formatTokens(999_999_999)).toBe("1B");
  });
});

describe("credits usage", () => {
  const qoder = {
    provider: "qoder_cloud",
    model: "",
    input_tokens: 0,
    output_tokens: 0,
    cache_read_tokens: 0,
    cache_write_tokens: 0,
    credits_micros: 1_250_000,
  };
  const label = (credits: string, provider: string) => `${credits} ${provider} credits`;

  it("sums credits across slices and leaves token cost at zero", () => {
    const s = summarizeTaskUsage([qoder, { ...qoder, credits_micros: 500_000 }]);
    expect(s?.credits).toEqual(new Map([["qoder_cloud", 1.75]]));
    expect(s?.cost).toBe(0);
    expect(s?.models).toEqual([]);
  });

  it("reports no credits when no slice was billed in credits", () => {
    const { credits_micros: _, ...tokensOnly } = qoder;
    expect(summarizeTaskUsage([tokensOnly])?.credits.size).toBe(0);
  });

  it("keeps different providers' credit units separate", () => {
    const s = summarizeTaskUsage([qoder, { ...qoder, provider: "other", credits_micros: 500_000 }]);
    expect(s?.credits).toEqual(new Map([["qoder_cloud", 1.25], ["other", 0.5]]));
    expect(formatSpend(s!, label)).toBe("1.25 qoder_cloud credits + 0.5 other credits");
  });

  it("shows credits alone, USD alone, or both", () => {
    expect(formatSpend({ cost: 0, credits: new Map([["qoder_cloud", 1.75]]) }, label)).toBe("1.75 qoder_cloud credits");
    expect(formatSpend({ cost: 1.5, credits: new Map() }, label)).toBe("$1.50");
    expect(formatSpend({ cost: 1.5, credits: new Map([["qoder_cloud", 2]]) }, label)).toBe("$1.50 + 2 qoder_cloud credits");
    expect(formatSpend({ cost: 0, credits: new Map([["qoder_cloud", 0]]) }, label)).toBe("0 qoder_cloud credits");
  });

  it("formats credits by magnitude", () => {
    expect(formatCredits(0.125)).toBe("0.13");
    expect(formatCredits(250.4)).toBe("250");
    expect(formatCredits(12_500)).toBe(formatTokens(12_500));
  });

  it("hides the token figure only for credits-only usage", () => {
    expect(hasTokenFigure({ tokens: 0, credits: new Map([["qoder_cloud", 1]]) })).toBe(false);
    expect(hasTokenFigure({ tokens: 10, credits: new Map([["qoder_cloud", 1]]) })).toBe(true);
    expect(hasTokenFigure({ tokens: 0, credits: new Map() })).toBe(true);
  });
});