Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(costs): label spend by operation, record local runs at $0, add ROI framing (#925)

Raghav Chamadiyace70782308f5
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
index ebe707ffd..2e0ce847f 100644
--- a/docs/CLI_REFERENCE.md
+++ b/docs/CLI_REFERENCE.md
@@ -591,9 +591,11 @@ repowise expand a1b2c3d4e5f6 -q "FAILED"
### `repowise saved [PATH]`
-Report tokens (and estimated dollars) saved by `repowise distill`, direct
-invocations and hook rewrites. Covers the distill command/hook path only; MCP
-response truncation is not part of this ledger.
+Report tokens (and estimated dollars) saved for your coding agent. Combines
+`repowise distill` savings (direct invocations and hook rewrites) with MCP
+tool-response savings — each curated answer counted against the raw file
+exploration it replaced. Group `--by source` to split the `mcp:*` rows from the
+distill filters.
| Flag | Description |
|------|-------------|
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 8b2d302b6..3e4a5ee3e 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -910,9 +910,10 @@ repowise saved # per-filter rollup, totals, est. dollars
repowise saved --by day
```
-The Costs page in the web UI shows the same numbers on its *Cache & savings*
-tab. The ledger covers the distill command/hook path only, MCP response
-truncation is not counted.
+The Costs page in the web UI leads with the same results — total agent tokens
+and dollars saved, split across distill and the MCP tools — over the
+per-operation and per-provider spend breakdown. The ledger combines the distill
+command/hook path with MCP tool-response savings.
---
diff --git a/packages/api-client/src/costs.ts b/packages/api-client/src/costs.ts
index b301bc874..8b11eecf1 100644
--- a/packages/api-client/src/costs.ts
+++ b/packages/api-client/src/costs.ts
@@ -59,6 +59,9 @@ export interface DistillSavings {
missed_events: number;
missed_tokens_est: number;
missed_window_days: number;
+ /** Full re-reads of unchanged files a targeted get_symbol would have replaced. */
+ reread_events: number;
+ reread_tokens_est: number;
}
// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 8911cbaa5..7cf26cc84 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -882,9 +882,12 @@ def run_update(
graph=graph_builder.graph(),
git_meta_map=git_meta_map,
)
- new_decision_markers = run_async(
- extractor.scan_inline_markers(restrict_to_files=changed_paths)
- )
+ # Label these calls as decision extraction so the Costs page can
+ # tell them apart from page regeneration (both ride this provider).
+ with cost_tracker.record_as("decision_extraction"):
+ new_decision_markers = run_async(
+ extractor.scan_inline_markers(restrict_to_files=changed_paths)
+ )
if new_decision_markers and verbose:
console.print(
f"New decision markers found: [green]{len(new_decision_markers)}[/green]"
diff --git a/packages/core/src/repowise/core/analysis/decisions/extractor.py b/packages/core/src/repowise/core/analysis/decisions/extractor.py
index dc566098d..21030113c 100644
--- a/packages/core/src/repowise/core/analysis/decisions/extractor.py
+++ b/packages/core/src/repowise/core/analysis/decisions/extractor.py
@@ -28,6 +28,7 @@ All LLM calls are wrapped in try/except - failures never propagate.
from __future__ import annotations
import asyncio
+import contextlib
import json
import re
from collections.abc import Collection, Iterator
@@ -1411,6 +1412,20 @@ class DecisionExtractor:
# Main entry point
# ------------------------------------------------------------------
+ @contextlib.contextmanager
+ def _cost_operation(self, operation: str) -> Iterator[None]:
+ """Label this extractor's LLM spend as *operation* on the Costs page.
+
+ No-op when the provider has no cost tracker attached (server-side index
+ or cost tracking disabled), so extraction is never affected.
+ """
+ tracker = getattr(self._provider, "_cost_tracker", None)
+ if tracker is not None and hasattr(tracker, "record_as"):
+ with tracker.record_as(operation):
+ yield
+ else:
+ yield
+
async def extract_all(
self,
*,
@@ -1465,7 +1480,8 @@ class DecisionExtractor:
logger.info("decision_extractor.sources_disabled", sources=disabled)
logger.info("decision_extractor.extract_all_start")
- results = await asyncio.gather(*[_safe_source(name, fn) for name, fn in sources])
+ with self._cost_operation("decision_extraction"):
+ results = await asyncio.gather(*[_safe_source(name, fn) for name, fn in sources])
logger.info("decision_extractor.extract_all_done")
# Raw per-source pool, then the anti-hallucination gate.
@@ -1492,9 +1508,7 @@ class DecisionExtractor:
# Helpers
# ------------------------------------------------------------------
- def _iter_scan_targets(
- self, restrict_to_files: list[str] | None
- ) -> Iterator[tuple[str, str]]:
+ def _iter_scan_targets(self, restrict_to_files: list[str] | None) -> Iterator[tuple[str, str]]:
"""Yield ``(rel_path, text)`` for every file the marker scan covers.
Three sources, in priority order:
diff --git a/packages/core/src/repowise/core/generation/cost_tracker.py b/packages/core/src/repowise/core/generation/cost_tracker.py
index 5f5f344d6..23885cb3e 100644
--- a/packages/core/src/repowise/core/generation/cost_tracker.py
+++ b/packages/core/src/repowise/core/generation/cost_tracker.py
@@ -6,6 +6,8 @@ the ``llm_costs`` table for historical reporting via ``repowise costs``.
from __future__ import annotations
+import contextlib
+from collections.abc import Iterator
from datetime import datetime
from typing import Any
@@ -57,15 +59,40 @@ _PRICING: dict[str, dict[str, float]] = {
_FALLBACK_PRICING: dict[str, float] = {"input": 3.0, "output": 15.0}
+#: Model-name prefixes that identify a locally-served model (Ollama, LM Studio,
+#: llama.cpp, ...). Local inference has no per-token price, so anything under
+#: these prefixes is valued at $0 — for both indexing spend and agent-savings
+#: estimates. Prefix-based on purpose: a *hosted* ``meta-llama/*`` billed
+#: through OpenRouter must never be mistaken for a free local run.
+_LOCAL_MODEL_PREFIXES: tuple[str, ...] = (
+ "ollama/",
+ "ollama_chat/",
+ "local/",
+ "lmstudio/",
+ "llamacpp/",
+)
+
# Track which unknown models we've already warned about (per-process)
_warned_models: set[str] = set()
+def is_local_model(model: str) -> bool:
+ """True when *model* is served locally (or is the test ``mock`` model).
+
+ Both the cost ledger and the savings estimate price these at $0: no dollars
+ change hands per token. Covers Ollama/LM Studio/llama.cpp model strings and
+ the agent-CLI passthrough prefixes (``codex_cli/``, ``opencode/``).
+ """
+ return (
+ model == "mock"
+ or model.startswith(_LOCAL_MODEL_PREFIXES)
+ or model.startswith(("codex_cli/", "opencode/"))
+ )
+
+
def _get_pricing(model: str) -> dict[str, float]:
"""Return pricing for *model*, falling back and warning if unknown."""
- if model.startswith("codex_cli/"):
- return {"input": 0.0, "output": 0.0}
- if model.startswith("opencode/"):
+ if is_local_model(model):
return {"input": 0.0, "output": 0.0}
if model in _PRICING:
return _PRICING[model]
@@ -128,6 +155,11 @@ class CostTracker:
self._buffered = buffered
# Pending rows when buffered; flushed in one transaction by ``flush``.
self._pending: list[dict[str, Any]] = []
+ # Operation label attached to rows recorded right now. Providers read
+ # this at ``record()`` time instead of hardcoding ``"doc_generation"``,
+ # so a caller can scope a distinct phase (e.g. decision extraction) via
+ # ``record_as`` and have it show up as its own bucket on the Costs page.
+ self._operation = "doc_generation"
# ------------------------------------------------------------------
# Properties
@@ -143,6 +175,31 @@ class CostTracker:
"""Cumulative tokens (input + output) for this tracker instance."""
return self._session_tokens
+ @property
+ def operation(self) -> str:
+ """Operation label rows are currently recorded under.
+
+ Defaults to ``"doc_generation"``; a caller narrows it for a bounded
+ window with :meth:`record_as`.
+ """
+ return self._operation
+
+ @contextlib.contextmanager
+ def record_as(self, operation: str) -> Iterator[None]:
+ """Label every LLM call recorded inside this block as *operation*.
+
+ Restores the previous label on exit. Relies on the pipeline running
+ distinct LLM phases sequentially (decision extraction then page
+ regeneration, not interleaved on one tracker), so the label read at
+ ``record()`` time is the intended one.
+ """
+ prev = self._operation
+ self._operation = operation
+ try:
+ yield
+ finally:
+ self._operation = prev
+
# ------------------------------------------------------------------
# Recording
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/providers/llm/anthropic.py b/packages/core/src/repowise/core/providers/llm/anthropic.py
index 8b57482de..b07ced2a0 100644
--- a/packages/core/src/repowise/core/providers/llm/anthropic.py
+++ b/packages/core/src/repowise/core/providers/llm/anthropic.py
@@ -261,7 +261,7 @@ class AnthropicProvider(BaseProvider):
model=self._model,
input_tokens=result.input_tokens,
output_tokens=result.output_tokens,
- operation="doc_generation",
+ operation=self._cost_tracker.operation,
file_path=None,
)
diff --git a/packages/core/src/repowise/core/providers/llm/deepseek.py b/packages/core/src/repowise/core/providers/llm/deepseek.py
index 2e8fa0949..0460957f4 100644
--- a/packages/core/src/repowise/core/providers/llm/deepseek.py
+++ b/packages/core/src/repowise/core/providers/llm/deepseek.py
@@ -299,7 +299,7 @@ class DeepSeekProvider(BaseProvider):
model=self._model,
input_tokens=result.input_tokens,
output_tokens=result.output_tokens,
- operation="doc_generation",
+ operation=self._cost_tracker.operation,
file_path=None,
)
diff --git a/packages/core/src/repowise/core/providers/llm/gemini.py b/packages/core/src/repowise/core/providers/llm/gemini.py
index 5255b73c0..72412e982 100644
--- a/packages/core/src/repowise/core/providers/llm/gemini.py
+++ b/packages/core/src/repowise/core/providers/llm/gemini.py
@@ -415,7 +415,7 @@ class GeminiProvider(BaseProvider):
model=self._model,
input_tokens=result.input_tokens,
output_tokens=result.output_tokens,
- operation="doc_generation",
+ operation=self._cost_tracker.operation,
file_path=None,
)
diff --git a/packages/core/src/repowise/core/providers/llm/kimi.py b/packages/core/src/repowise/core/providers/llm/kimi.py
index 6ab38c589..478d7d4e3 100644
--- a/packages/core/src/repowise/core/providers/llm/kimi.py
+++ b/packages/core/src/repowise/core/providers/llm/kimi.py
@@ -310,7 +310,7 @@ class KimiProvider(BaseProvider):
model=self._model,
input_tokens=result.input_tokens,
output_tokens=result.output_tokens,
- operation="doc_generation",
+ operation=self._cost_tracker.operation,
file_path=None,
)
diff --git a/packages/core/src/repowise/core/providers/llm/litellm.py b/packages/core/src/repowise/core/providers/llm/litellm.py
index 2a25a1f86..aafad4e47 100644
--- a/packages/core/src/repowise/core/providers/llm/litellm.py
+++ b/packages/core/src/repowise/core/providers/llm/litellm.py
@@ -289,7 +289,7 @@ class LiteLLMProvider(BaseProvider):
model=self._model,
input_tokens=result.input_tokens,
output_tokens=result.output_tokens,
- operation="doc_generation",
+ operation=self._cost_tracker.operation,
file_path=None,
)
diff --git a/packages/core/src/repowise/core/providers/llm/ollama.py b/packages/core/src/repowise/core/providers/llm/ollama.py
index c9d2df15f..04340fdd3 100644
--- a/packages/core/src/repowise/core/providers/llm/ollama.py
+++ b/packages/core/src/repowise/core/providers/llm/ollama.py
@@ -20,6 +20,7 @@ Usage:
from __future__ import annotations
+import contextlib
import os
from collections.abc import AsyncIterator
from typing import Any
@@ -178,7 +179,7 @@ class OllamaProvider(BaseProvider):
)
try:
- return await self._generate_with_retry(
+ result = await self._generate_with_retry(
system_prompt=system_prompt,
user_prompt=user_prompt,
max_tokens=max_tokens,
@@ -191,6 +192,24 @@ class OllamaProvider(BaseProvider):
f"All {_MAX_RETRIES} retries exhausted: {exc}",
) from exc
+ # Record the call so a local index still shows accurate call/token
+ # counts on the Costs page — priced at $0, since the ``ollama/`` prefix
+ # marks it local (see ``is_local_model``). Recorded in the outer method
+ # (not the @retry-wrapped inner one) so a retry can never double-count.
+ # The tracker is attached externally by the orchestrator, so it may be
+ # absent.
+ tracker = getattr(self, "_cost_tracker", None)
+ if tracker is not None:
+ with contextlib.suppress(Exception):
+ await tracker.record(
+ model=f"ollama/{self._model}",
+ input_tokens=result.input_tokens,
+ output_tokens=result.output_tokens,
+ operation=tracker.operation,
+ file_path=None,
+ )
+ return result
+
@retry(
retry=retry_if_exception_type(ProviderError),
stop=stop_after_attempt(_MAX_RETRIES),
diff --git a/packages/core/src/repowise/core/providers/llm/openai.py b/packages/core/src/repowise/core/providers/llm/openai.py
index 483118ef1..07222f26a 100644
--- a/packages/core/src/repowise/core/providers/llm/openai.py
+++ b/packages/core/src/repowise/core/providers/llm/openai.py
@@ -362,7 +362,7 @@ class OpenAIProvider(BaseProvider):
model=self._model,
input_tokens=result.input_tokens,
output_tokens=result.output_tokens,
- operation="doc_generation",
+ operation=self._cost_tracker.operation,
file_path=None,
)
diff --git a/packages/core/src/repowise/core/providers/llm/openrouter.py b/packages/core/src/repowise/core/providers/llm/openrouter.py
index 689fd0488..3df3bf44b 100644
--- a/packages/core/src/repowise/core/providers/llm/openrouter.py
+++ b/packages/core/src/repowise/core/providers/llm/openrouter.py
@@ -13,6 +13,7 @@ Popular models:
from __future__ import annotations
+import contextlib
import os
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING, Any
@@ -278,7 +279,7 @@ class OpenRouterProvider(BaseProvider):
)
try:
- return await self._generate_with_retry(
+ result = await self._generate_with_retry(
system_prompt=system_prompt,
user_prompt=user_prompt,
max_tokens=max_tokens,
@@ -292,6 +293,23 @@ class OpenRouterProvider(BaseProvider):
f"All retries exhausted: {exc}",
) from exc
+ # Persist spend like the other providers do — without this, any repo
+ # generating docs through OpenRouter records zero cost and the Costs
+ # page shows $0. The tracker is attached externally by the orchestrator,
+ # so it may be absent (guard with getattr); record() swallows its own
+ # persistence errors, so generation is unaffected.
+ tracker = getattr(self, "_cost_tracker", None)
+ if tracker is not None:
+ with contextlib.suppress(Exception):
+ await tracker.record(
+ model=self._model,
+ input_tokens=result.input_tokens,
+ output_tokens=result.output_tokens,
+ operation=tracker.operation,
+ file_path=None,
+ )
+ return result
+
@retry(
retry=provider_should_retry,
stop=provider_retry_stop,
diff --git a/packages/server/src/repowise/server/mcp_server/_savings/counterfactual.py b/packages/server/src/repowise/server/mcp_server/_savings/counterfactual.py
index e9431257c..93ce2d3c3 100644
--- a/packages/server/src/repowise/server/mcp_server/_savings/counterfactual.py
+++ b/packages/server/src/repowise/server/mcp_server/_savings/counterfactual.py
@@ -76,6 +76,10 @@ ANSWER_READ_FLOOR_PER_FILE = 400
#: exploration the agent cannot cheaply reproduce (git log/blame spelunking,
#: ADR archaeology, README + entry-point skim) but whose size the result dict
#: cannot ground — so a flat, deliberately-low floor per successful call.
+#: ``get_dead_code`` stands in for the agent grepping every export for
+#: usages across the tree to prove it unreachable — an expensive manual sweep.
+#: Floored conservatively between a single-file health call and a full overview.
+DEAD_CODE_FLOOR = 800
RISK_FLOOR = 500
WHY_FLOOR = 400
HEALTH_FLOOR = 400
@@ -119,6 +123,7 @@ _ESTIMATORS: dict[str, Callable[[dict[str, Any]], int]] = {
"get_why": _fixed_floor(WHY_FLOOR),
"get_health": _fixed_floor(HEALTH_FLOOR),
"get_overview": _fixed_floor(OVERVIEW_FLOOR),
+ "get_dead_code": _fixed_floor(DEAD_CODE_FLOOR),
}
diff --git a/packages/ui/src/costs/distill-savings-card.tsx b/packages/ui/src/costs/distill-savings-card.tsx
index 67d076fc8..2d0d8ea79 100644
--- a/packages/ui/src/costs/distill-savings-card.tsx
+++ b/packages/ui/src/costs/distill-savings-card.tsx
@@ -262,8 +262,8 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {
<p className="mt-3 text-xs leading-snug text-[var(--color-text-tertiary)]">
Distill counts <code>repowise distill</code> command/hook savings; MCP counts the raw
file exploration each tool answer replaced (plus any over-budget content trimmed). Saved
- tokens are agent input, priced at the agent&apos;s input rate. Everything stays on this
- machine.
+ tokens are agent input, priced at the agent&apos;s input rate; counts are estimates
+ (~chars/4) and deliberately undersell. Everything stays on this machine.
</p>
</CardContent>
</Card>
diff --git a/packages/ui/src/costs/index.ts b/packages/ui/src/costs/index.ts
index 070e63f8e..2ea766559 100644
--- a/packages/ui/src/costs/index.ts
+++ b/packages/ui/src/costs/index.ts
@@ -13,3 +13,7 @@ export type {
DistillSavingsGroup,
McpDropGroup,
} from "./distill-savings-card";
+export { RoiCard } from "./roi-card";
+export type { RoiCardProps } from "./roi-card";
+export { SavingsTrendChart } from "./savings-trend-chart";
+export type { SavingsTrendChartProps } from "./savings-trend-chart";
diff --git a/packages/ui/src/costs/roi-card.tsx b/packages/ui/src/costs/roi-card.tsx
new file mode 100644
index 000000000..9aeb8c72c
--- /dev/null
+++ b/packages/ui/src/costs/roi-card.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+import { Scale, TrendingUp } from "lucide-react";
+import { Card, CardContent } from "../ui/card";
+import { formatCost, formatTokens } from "../lib/format";
+
+export interface RoiCardProps {
+ /** Estimated dollars saved for the coding agent (distill + MCP). */
+ savedUsd: number;
+ /** Real dollars spent generating/refreshing this repo's docs. */
+ spentUsd: number;
+ /** Total agent tokens saved, for the supporting caption. */
+ savedTokens: number;
+}
+
+/**
+ * Ties the two halves of the Costs page together: what repowise spent
+ * generating the docs against what it saved the coding agent. The page shows
+ * both numbers separately; this states the relationship the reader is doing in
+ * their head — return multiple and net position — in one line.
+ *
+ * Savings are an estimate (chars/4, priced at the agent's input rate); spend is
+ * metered. Shown only once there is real spend to compare against.
+ */
+export function RoiCard({ savedUsd, spentUsd, savedTokens }: RoiCardProps) {
+ if (spentUsd <= 0) return null;
+
+ const net = savedUsd - spentUsd;
+ const multiple = savedUsd / spentUsd;
+ const ahead = net >= 0;
+
+ return (
+ <Card>
+ <CardContent className="py-5">
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <div className="flex items-center gap-3">
+ <Scale className="h-5 w-5 shrink-0 text-[var(--color-accent-primary)]" />
+ <div>
+ <div className="text-xs font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Return on indexing
+ </div>
+ <p className="mt-0.5 text-sm text-[var(--color-text-secondary)]">
+ Spent{" "}
+ <span className="font-medium text-[var(--color-text-primary)]">
+ {formatCost(spentUsd)}
+ </span>{" "}
+ generating docs · saved your agent{" "}
+ <span className="font-medium text-[var(--color-success)]">
+ {formatCost(savedUsd)}
+ </span>{" "}
+ ({formatTokens(savedTokens)} tokens)
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-6 text-right">
+ <div>
+ <div className="flex items-center justify-end gap-1 text-2xl font-semibold tabular-nums text-[var(--color-text-primary)]">
+ <TrendingUp className="h-4 w-4 text-[var(--color-success)]" />
+ {multiple >= 10 ? multiple.toFixed(0) : multiple.toFixed(1)}×
+ </div>
+ <div className="text-xs text-[var(--color-text-tertiary)]">return</div>
+ </div>
+ <div>
+ <div
+ className={`text-2xl font-semibold tabular-nums ${
+ ahead ? "text-[var(--color-success)]" : "text-[var(--color-text-primary)]"
+ }`}
+ >
+ {ahead ? "+" : "−"}
+ {formatCost(Math.abs(net))}
+ </div>
+ <div className="text-xs text-[var(--color-text-tertiary)]">net</div>
+ </div>
+ </div>
+ </div>
+ <p className="mt-3 text-xs leading-snug text-[var(--color-text-tertiary)]">
+ Savings are estimated and priced at your agent&apos;s input rate; generation spend is
+ metered. A one-time indexing cost pays back across every agent session that reads these
+ docs.
+ </p>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/packages/ui/src/costs/savings-trend-chart.tsx b/packages/ui/src/costs/savings-trend-chart.tsx
new file mode 100644
index 000000000..e1abe79f2
--- /dev/null
+++ b/packages/ui/src/costs/savings-trend-chart.tsx
@@ -0,0 +1,73 @@
+"use client";
+
+import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from "recharts";
+import { formatTokens } from "../lib/format";
+
+export interface SavingsTrendChartProps {
+ /** Day-grouped savings rows ({ group: "YYYY-MM-DD", saved_tokens }). The
+ * `per_day` series from /distill-savings — total agent tokens saved per day
+ * (distill + MCP counterfactual). Caller fetches. */
+ groups: Array<{ group: string; saved_tokens: number }>;
+ height?: number;
+}
+
+/**
+ * Daily agent-savings bars — the token counterpart to DailySpendChart, so the
+ * Costs page can show savings accruing over time, not just a lifetime total.
+ * Renders the `per_day` array that the page already fetches.
+ */
+export function SavingsTrendChart({ groups, height = 220 }: SavingsTrendChartProps) {
+ const data = [...groups]
+ .filter((g) => g.saved_tokens > 0)
+ .sort((a, b) => a.group.localeCompare(b.group));
+
+ if (data.length === 0) {
+ return (
+ <p className="text-sm text-[var(--color-text-secondary)] py-8 text-center">
+ No savings recorded yet.
+ </p>
+ );
+ }
+
+ return (
+ <ResponsiveContainer width="100%" height={height}>
+ <BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>
+ <XAxis
+ dataKey="group"
+ tick={{ fill: "var(--color-text-tertiary)", fontSize: 11 }}
+ axisLine={false}
+ tickLine={false}
+ interval="preserveStartEnd"
+ minTickGap={24}
+ tickFormatter={(v: string) => {
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v);
+ return m ? `${Number(m[2])}/${Number(m[3])}` : v;
+ }}
+ />
+ <YAxis
+ tick={{ fill: "var(--color-text-tertiary)", fontSize: 10 }}
+ axisLine={false}
+ tickLine={false}
+ tickFormatter={(v: number) => formatTokens(v)}
+ />
+ <Tooltip
+ cursor={{ fill: "var(--color-bg-elevated)" }}
+ contentStyle={{
+ background: "var(--color-bg-overlay)",
+ border: "1px solid var(--color-border-default)",
+ borderRadius: "6px",
+ fontSize: "12px",
+ color: "var(--color-text-primary)",
+ }}
+ formatter={(value) => [`${formatTokens(Number(value))} tokens`, "Saved"]}
+ labelFormatter={(label) => `Date: ${String(label)}`}
+ />
+ <Bar
+ dataKey="saved_tokens"
+ fill="var(--color-savings-distill)"
+ radius={[4, 4, 0, 0]}
+ />
+ </BarChart>
+ </ResponsiveContainer>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/costs/page.tsx b/packages/web/src/app/repos/[id]/costs/page.tsx
index 73adfa123..66c55c796 100644
--- a/packages/web/src/app/repos/[id]/costs/page.tsx
+++ b/packages/web/src/app/repos/[id]/costs/page.tsx
@@ -15,6 +15,8 @@ import {
DistillSavingsCard,
ProviderComparison,
OperationBreakdown,
+ RoiCard,
+ SavingsTrendChart,
} from "@repowise-dev/ui/costs";
import { listCosts, getCostSummary, getDistillSavings } from "@/lib/api/costs";
import type { CostGroup, CostSummary, DistillSavings } from "@/lib/api/costs";
@@ -66,6 +68,29 @@ export default function CostsPage() {
coding agent, across distill (CLI + hook) and MCP tool responses. */}
<DistillSavingsCard data={distillSavings} />
+ {/* ROI: ties the saved dollars above to the generation spend below, so the
+ reader doesn't have to do the division themselves. */}
+ {distillSavings?.available && summary ? (
+ <RoiCard
+ savedUsd={distillSavings.estimated_usd_saved}
+ spentUsd={summary.total_cost_usd}
+ savedTokens={distillSavings.saved_tokens + distillSavings.mcp_tokens}
+ />
+ ) : null}
+
+ {/* Savings over time — renders the per_day series the page already
+ fetches (total agent tokens saved per day, distill + MCP). */}
+ {distillSavings?.available && (distillSavings.per_day?.length ?? 0) > 0 ? (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm">Agent tokens saved by day</CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <SavingsTrendChart groups={distillSavings.per_day} />
+ </CardContent>
+ </Card>
+ ) : null}
+
<Tabs value={tab} onValueChange={setTab} className="w-full">
<ScrollableTabsList>
<TabsTrigger value="daily">Daily</TabsTrigger>