:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): show daily model spend details (#79211)
Matt Pua6e2e45b55b27
diff --git a/products/ai_observability/backend/api/personal_spend.py b/products/ai_observability/backend/api/personal_spend.pyindex 49b6417210ec..62d5f66c6ae1 100644--- a/products/ai_observability/backend/api/personal_spend.py+++ b/products/ai_observability/backend/api/personal_spend.py@@ -63,6 +63,8 @@ DEFAULT_DATE_FROM = "-30d"MAX_WINDOW_DAYS = 90# The most calendar days a MAX_WINDOW_DAYS window can touch: partial days at both edges.BY_DAY_MAX_ROWS = MAX_WINDOW_DAYS + 1+BY_DAY_MODEL_TOP_MODELS = 6+BY_DAY_MODEL_MAX_ROWS = BY_DAY_MAX_ROWS * (BY_DAY_MODEL_TOP_MODELS + 1)# Sub-day series are only useful (and cheap) over short windows; a "last 24h"# view is the intended consumer. The cap bounds the series length regardless of# bucket size: 600 buckets is 50 hours at 5-minute buckets and 25 days hourly.@@ -75,6 +77,7 @@ MAX_LIMIT = 200DEFAULT_LIMIT = 50CACHE_TIMEOUT_SECONDS = 300+CACHE_VERSION = "v2"UTC = ZoneInfo("UTC")@@ -89,7 +92,7 @@ def _cache_key(to_slot = date_to or "_now"# Suffix only when set, so bucketless requests keep their pre-bucket_minutes cache keys.bucket_slot = f":{bucket_minutes}" if bucket_minutes else ""- return f"personal_spend:{email}:{date_from}:{to_slot}:{product}:{limit}{bucket_slot}"+ return f"personal_spend:{CACHE_VERSION}:{email}:{date_from}:{to_slot}:{product}:{limit}{bucket_slot}"def _parse_date_param(value: str, field: str, now: datetime.datetime) -> datetime.datetime:@@ -282,6 +285,25 @@ class _DayBreakdownRowSerializer(serializers.Serializer):help_text="Number of $ai_generation + $ai_embedding events on this day for the scoped product.")cost_usd = serializers.FloatField(help_text="Total cost in USD on this day for the scoped product.")+ input_tokens = serializers.IntegerField(help_text="Sum of `$ai_input_tokens` on this day for the scoped product.")+ output_tokens = serializers.IntegerField(help_text="Sum of `$ai_output_tokens` on this day for the scoped product.")+++class _DayModelBreakdownRowSerializer(serializers.Serializer):+ day = serializers.DateField(help_text="UTC calendar day the events fall on (`toDate(timestamp)`).")+ model = serializers.CharField(+ allow_null=True,+ help_text=(+ "Model name for one of the highest-cost models in the selected window. Null is the aggregate "+ "of all remaining models, including events without a model."+ ),+ )+ cost_usd = serializers.FloatField(help_text="Total cost in USD for this model on this day.")+ input_tokens = serializers.IntegerField(help_text="Sum of `$ai_input_tokens` for this model on this day.")+ output_tokens = serializers.IntegerField(help_text="Sum of `$ai_output_tokens` for this model on this day.")+ generation_count = serializers.IntegerField(+ help_text="Number of $ai_generation + $ai_embedding events for this model on this day."+ )class _BucketBreakdownRowSerializer(serializers.Serializer):@@ -456,6 +478,13 @@ class PersonalSpendAnalysisResponseSerializer(serializers.Serializer):by_day = _DayBreakdownSerializer(help_text="Spend grouped by UTC day, ordered ascending. Scoped to `product`. Not subject to `limit`.")+ by_day_model = _DayModelBreakdownRowSerializer(+ many=True,+ help_text=(+ "Daily model spend for the scoped product, ordered by day and cost. Includes the six highest-cost "+ "models in the selected window plus a null-model row for the remaining models."+ ),+ )by_bucket = _BucketBreakdownSerializer(required=False,help_text=(@@ -718,7 +747,9 @@ def _fetch_by_day(SELECTtoDate(timestamp) AS day,count() AS event_count,- round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS cost_usd+ round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS cost_usd,+ sum(toFloat(properties.$ai_input_tokens)) AS input_tokens,+ sum(toFloat(properties.$ai_output_tokens)) AS output_tokensFROM eventsWHERE {event_in}AND {product_filter}@@ -751,12 +782,101 @@ def _fetch_by_day("day": row[0],"event_count": int(row[1] or 0),"cost_usd": float(row[2] or 0.0),+ "input_tokens": int(row[3] or 0),+ "output_tokens": int(row[4] or 0),}for row in (result.results or [])]return _truncate(rows, BY_DAY_MAX_ROWS)+def _fetch_by_day_model(+ team: Team,+ email: str,+ from_dt: datetime.datetime,+ to_dt: datetime.datetime,+ product: str,+) -> list[dict[str, Any]]:+ top_models_query = parse_select(+ f"""+ SELECT properties.$ai_model AS model+ FROM events+ WHERE {{event_in}}+ AND {{product_filter}}+ AND {{email_filter}}+ AND {{timestamp_filter}}+ AND isNotNull(properties.$ai_model)+ GROUP BY model+ ORDER BY sum(toFloat(properties.$ai_total_cost_usd)) DESC, model ASC+ LIMIT {{limit}}+ """+ )+ top_models_result = execute_hogql_query(+ query=top_models_query,+ placeholders={+ "event_in": _event_in(["$ai_generation", "$ai_embedding"]),+ "product_filter": _product_filter(product),+ "email_filter": _email_filter(email),+ "timestamp_filter": _timestamp_filter(from_dt, to_dt),+ "limit": ast.Constant(value=BY_DAY_MODEL_TOP_MODELS),+ },+ team=team,+ query_type="PersonalSpendByDayModelTopModels",+ )+ top_models = [row[0] for row in (top_models_result.results or []) if row[0] is not None]+ model_expression = "NULL"+ if top_models:+ model_expression = "if(properties.$ai_model IN {top_models}, properties.$ai_model, NULL)"++ query = parse_select(+ f"""+ SELECT+ toDate(timestamp) AS day,+ {model_expression} AS model,+ round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS cost_usd,+ sum(toFloat(properties.$ai_input_tokens)) AS input_tokens,+ sum(toFloat(properties.$ai_output_tokens)) AS output_tokens,+ count() AS generation_count+ FROM events+ WHERE {{event_in}}+ AND {{product_filter}}+ AND {{email_filter}}+ AND {{timestamp_filter}}+ GROUP BY day, model+ ORDER BY day ASC, cost_usd DESC, model ASC+ LIMIT {{limit}}+ """+ )+ placeholders: dict[str, ast.Expr] = {+ "event_in": _event_in(["$ai_generation", "$ai_embedding"]),+ "product_filter": _product_filter(product),+ "email_filter": _email_filter(email),+ "timestamp_filter": _timestamp_filter(from_dt, to_dt),+ "limit": ast.Constant(value=BY_DAY_MODEL_MAX_ROWS),+ }+ if top_models:+ placeholders["top_models"] = ast.Tuple(exprs=[ast.Constant(value=model) for model in top_models])++ result = execute_hogql_query(+ query=query,+ placeholders=placeholders,+ team=team,+ modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),+ query_type="PersonalSpendByDayModel",+ )+ return [+ {+ "day": row[0],+ "model": str(row[1]) if row[1] is not None else None,+ "cost_usd": float(row[2] or 0.0),+ "input_tokens": int(row[3] or 0),+ "output_tokens": int(row[4] or 0),+ "generation_count": int(row[5] or 0),+ }+ for row in (result.results or [])+ ]++def _fetch_by_bucket(team: Team,email: str,@@ -888,6 +1008,7 @@ def _compute_spend_analysis("by_tool": by_tool,"by_model": _fetch_by_model(team, email, from_dt, to_dt, product, limit),"by_day": _fetch_by_day(team, email, from_dt, to_dt, product),+ "by_day_model": _fetch_by_day_model(team, email, from_dt, to_dt, product),**({"by_bucket": _fetch_by_bucket(team, email, from_dt, to_dt, product, bucket_minutes)}if bucket_minutes is not Nonediff --git a/products/ai_observability/backend/api/test/__snapshots__/test_personal_spend.ambr b/products/ai_observability/backend/api/test/__snapshots__/test_personal_spend.ambrindex 4606a957cfbf..5e8d1114d7ab 100644--- a/products/ai_observability/backend/api/test/__snapshots__/test_personal_spend.ambr+++ b/products/ai_observability/backend/api/test/__snapshots__/test_personal_spend.ambr@@ -170,7 +170,9 @@/* user_id:0 request:_snapshot_@me_spend_ */SELECT toDate(events.timestamp) AS day,count() AS event_count,- round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd,+ sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')) AS input_tokens,+ sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')) AS output_tokensFROM eventsLEFT OUTER JOIN(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,@@ -206,3 +208,88 @@use_hive_partitioning=0'''# ---+# name: TestPersonalSpendQueries.test_empty_result_when_no_events.5+ '''+ /* user_id:0 request:_snapshot_@me_spend_ */+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_model'), ''), 'null'), '^"|"$', '') AS model+ FROM events+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_model'), ''), 'null'), '^"|"$', '')))+ GROUP BY model+ ORDER BY sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')) DESC, model ASC+ LIMIT 6 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPersonalSpendQueries.test_empty_result_when_no_events.6+ '''+ /* user_id:0 request:_snapshot_@me_spend_ */+ SELECT toDate(events.timestamp) AS day,+ NULL AS model,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd,+ sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')) AS input_tokens,+ sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')) AS output_tokens,+ count() AS generation_count+ FROM events+ LEFT OUTER JOIN+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(person.created_at, person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))+ GROUP BY day,+ model+ ORDER BY day ASC, cost_usd DESC,+ model ASC+ LIMIT 637 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---diff --git a/products/ai_observability/backend/api/test/test_personal_spend.py b/products/ai_observability/backend/api/test/test_personal_spend.pyindex 6431c915f89a..32bf4002044f 100644--- a/products/ai_observability/backend/api/test/test_personal_spend.py+++ b/products/ai_observability/backend/api/test/test_personal_spend.py@@ -25,6 +25,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIRequestFactory, force_authenticate+from posthog.models import Teamfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value@@ -231,7 +232,7 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):self,*,ai_product: str = "posthog_code",- model: str = "claude-opus-4-8",+ model: str | None = "claude-opus-4-8",tool: str | None = "Bash",trace_id: str = "trace-1",cost: float | None = 1.5,@@ -278,6 +279,7 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):assert body["by_tool"] == {"items": [], "truncated": False}assert body["by_model"] == {"items": [], "truncated": False}assert body["by_day"] == {"items": [], "truncated": False}+ assert body["by_day_model"] == []assert body["top_traces"] == {"items": [], "truncated": False}def test_summary_reports_cross_product_totals_alongside_scoped(self) -> None:@@ -394,9 +396,10 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=-7d")assert response.status_code == status.HTTP_200_OK- # 5 fetchers run once (summary, by_product, by_tool, by_model, by_day). top_traces+ # 7 fetchers run once (summary, by_product, by_tool, by_model, by_day, and the two+ # by_day_model queries). top_traces# is deprecated and returned empty without a query.- assert mock_exec.call_count == 5+ assert mock_exec.call_count == 7def test_second_call_serves_from_cache(self) -> None:with patch("products.ai_observability.backend.api.personal_spend.execute_hogql_query") as mock_exec:@@ -455,14 +458,28 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):assert rows["Bash"]["share_of_scoped"] == 0.5assert rows["Read"]["share_of_scoped"] == 0.5- def test_by_day_groups_spend_per_utc_day_scoped_to_product(self) -> None:+ def test_by_day_includes_tokens_and_by_day_model_scopes_product(self) -> None:earlier = datetime(2026, 6, 13, 9, 0, tzinfo=UTC)later = datetime(2026, 6, 15, 20, 0, tzinfo=UTC)- self._create_generation(cost=1.0, trace_id="old-1", timestamp=earlier)- self._create_generation(cost=0.5, trace_id="old-2", timestamp=earlier)- self._create_generation(cost=2.0, trace_id="new", timestamp=later)+ self._create_generation(cost=1.0, input_tokens=100, output_tokens=10, trace_id="old-1", timestamp=earlier)+ self._create_generation(cost=0.5, input_tokens=50, output_tokens=5, trace_id="old-2", timestamp=earlier)+ self._create_generation(+ cost=2.0,+ input_tokens=200,+ output_tokens=20,+ model="gpt-5",+ trace_id="new",+ timestamp=later,+ )# Same day as `earlier` but another product: must not leak into the scoped series.- self._create_generation(ai_product="background_agents", cost=99.0, timestamp=earlier)+ self._create_generation(+ ai_product="background_agents",+ cost=99.0,+ input_tokens=9900,+ output_tokens=990,+ model="leaked-model",+ timestamp=earlier,+ )flush_persons_and_events()response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=2026-06-10&date_to=2026-06-16")@@ -470,10 +487,135 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):assert by_day["truncated"] is False# Ordered by day ascending, not by cost.assert by_day["items"] == [- {"day": "2026-06-13", "event_count": 2, "cost_usd": 1.5},- {"day": "2026-06-15", "event_count": 1, "cost_usd": 2.0},+ {"day": "2026-06-13", "event_count": 2, "cost_usd": 1.5, "input_tokens": 150, "output_tokens": 15},+ {"day": "2026-06-15", "event_count": 1, "cost_usd": 2.0, "input_tokens": 200, "output_tokens": 20},+ ]+ assert response.json()["by_day_model"] == [+ {+ "day": "2026-06-13",+ "model": "claude-opus-4-8",+ "cost_usd": 1.5,+ "input_tokens": 150,+ "output_tokens": 15,+ "generation_count": 2,+ },+ {+ "day": "2026-06-15",+ "model": "gpt-5",+ "cost_usd": 2.0,+ "input_tokens": 200,+ "output_tokens": 20,+ "generation_count": 1,+ },]+ def test_by_day_model_does_not_include_another_team(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ _create_person(+ distinct_ids=["other-team-distinct"],+ team=other_team,+ properties={"email": self.user.email},+ )+ _create_event(+ event="$ai_generation",+ team=other_team,+ distinct_id="other-team-distinct",+ properties={+ "$ai_input_tokens": 999,+ "$ai_output_tokens": 99,+ "$ai_total_cost_usd": 99.0,+ "$ai_model": "other-team-model",+ "ai_product": "posthog_code",+ },+ )+ self._create_generation(cost=1.0, input_tokens=10, output_tokens=1, model="visible-model")+ flush_persons_and_events()++ response = self.client.get(ENDPOINT_OK)++ assert response.json()["by_day_model"][0]["model"] == "visible-model"+ assert response.json()["by_day_model"][0]["cost_usd"] == 1.0++ def test_by_day_model_aggregates_long_tail_models_as_other(self) -> None:+ timestamp = datetime(2026, 6, 15, 12, 0, tzinfo=UTC)+ for index in range(11):+ self._create_generation(+ cost=float(11 - index),+ model=f"model-{index}",+ timestamp=timestamp,+ trace_id=f"trace-{index}",+ )+ flush_persons_and_events()++ response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=2026-06-15&date_to=2026-06-16")+ rows = {row["model"]: row for row in response.json()["by_day_model"]}++ assert len(rows) == 7+ assert rows[None]["generation_count"] == 5++ def test_by_day_model_keeps_a_model_named_other_separate_from_the_aggregate(self) -> None:+ timestamp = datetime(2026, 6, 15, 12, 0, tzinfo=UTC)+ self._create_generation(cost=100.0, model="Other", timestamp=timestamp, trace_id="named-other")+ for index in range(7):+ self._create_generation(+ cost=float(7 - index),+ model=f"model-{index}",+ timestamp=timestamp,+ trace_id=f"trace-{index}",+ )+ flush_persons_and_events()++ response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=2026-06-15&date_to=2026-06-16")+ rows = {row["model"]: row for row in response.json()["by_day_model"]}++ assert rows["Other"]["cost_usd"] == 100.0+ assert rows[None]["cost_usd"] == 3.0++ def test_by_day_model_selects_top_models_by_cost_not_generation_count(self) -> None:+ timestamp = datetime(2026, 6, 15, 12, 0, tzinfo=UTC)+ self._create_generation(cost=100.0, model="rare-expensive", timestamp=timestamp, trace_id="rare")+ for occurrence in range(7):+ self._create_generation(+ cost=1.0,+ model="frequent-cheap",+ timestamp=timestamp,+ trace_id=f"frequent-{occurrence}",+ )+ for index in range(6):+ self._create_generation(+ cost=10.0,+ model=f"medium-{index}",+ timestamp=timestamp,+ trace_id=f"medium-{index}",+ )+ flush_persons_and_events()++ response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=2026-06-15&date_to=2026-06-16")+ rows = {row["model"]: row for row in response.json()["by_day_model"]}++ assert "rare-expensive" in rows+ assert "frequent-cheap" not in rows+ assert rows[None]["cost_usd"] == 17.0++ def test_by_day_model_keeps_named_top_models_when_unmodeled_events_exist(self) -> None:+ timestamp = datetime(2026, 6, 15, 12, 0, tzinfo=UTC)+ for index in range(6):+ for occurrence in range(2):+ self._create_generation(+ cost=1.0,+ model=f"model-{index}",+ timestamp=timestamp,+ trace_id=f"model-{index}-{occurrence}",+ )+ self._create_generation(cost=100.0, model=None, timestamp=timestamp, trace_id="unmodeled")+ flush_persons_and_events()++ response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=2026-06-15&date_to=2026-06-16")+ rows = {row["model"]: row for row in response.json()["by_day_model"]}++ assert {f"model-{index}" for index in range(6)} <= rows.keys()+ assert rows[None]["cost_usd"] == 100.0+def test_by_day_ignores_request_limit(self) -> None:self._create_generation(cost=1.0, trace_id="a", timestamp=datetime(2026, 6, 12, 12, 0, tzinfo=UTC))self._create_generation(cost=2.0, trace_id="b", timestamp=datetime(2026, 6, 13, 12, 0, tzinfo=UTC))@@ -625,8 +767,20 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=2026-06-10&date_to=2026-06-16")assert response.json()["by_day"]["items"] == [- {"day": "2026-06-13", "event_count": 2, "cost_usd": 1.5},- {"day": "2026-06-15", "event_count": 1, "cost_usd": 0.0},+ {+ "day": "2026-06-13",+ "event_count": 2,+ "cost_usd": 1.5,+ "input_tokens": 200000,+ "output_tokens": 1000,+ },+ {+ "day": "2026-06-15",+ "event_count": 1,+ "cost_usd": 0.0,+ "input_tokens": 100000,+ "output_tokens": 500,+ },]diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 6c4b5187a563..90144a0d3bae 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -96,6 +96,10 @@ export interface _DayBreakdownRowApi {event_count: number/** Total cost in USD on this day for the scoped product. */cost_usd: number+ /** Sum of `$ai_input_tokens` on this day for the scoped product. */+ input_tokens: number+ /** Sum of `$ai_output_tokens` on this day for the scoped product. */+ output_tokens: number}export interface _DayBreakdownApi {@@ -105,6 +109,24 @@ export interface _DayBreakdownApi {truncated: boolean}+export interface _DayModelBreakdownRowApi {+ /** UTC calendar day the events fall on (`toDate(timestamp)`). */+ day: string+ /**+ * Model name for one of the highest-cost models in the selected window. Null is the aggregate of all remaining models, including events without a model.+ * @nullable+ */+ model: string | null+ /** Total cost in USD for this model on this day. */+ cost_usd: number+ /** Sum of `$ai_input_tokens` for this model on this day. */+ input_tokens: number+ /** Sum of `$ai_output_tokens` for this model on this day. */+ output_tokens: number+ /** Number of $ai_generation + $ai_embedding events for this model on this day. */+ generation_count: number+}+export interface _BucketBreakdownRowApi {/** UTC start of the time bucket the events fall in (`toStartOfInterval(timestamp, ...)`). */bucket_start: string@@ -177,6 +199,8 @@ export interface PersonalSpendAnalysisResponseApi {by_model: _ModelBreakdownApi/** Spend grouped by UTC day, ordered ascending. Scoped to `product`. Not subject to `limit`. */by_day: _DayBreakdownApi+ /** Daily model spend for the scoped product, ordered by day and cost. Includes the six highest-cost models in the selected window plus a null-model row for the remaining models. */+ by_day_model: _DayModelBreakdownRowApi[]/** Spend grouped by UTC time bucket with per-bucket cost/token components, ordered ascending. Scoped to `product`. Only present when the request set `bucket_minutes`. */by_bucket?: _BucketBreakdownApi/** Deprecated — always returns `{items: [], truncated: false}`. Trace IDs are opaque strings that aren't actionable in the UI. Kept in the response shape so existing consumers don't crash; remove your rendering of this field and we'll drop it from the response entirely in a follow-up. */diff --git a/products/desktop/packages/api-client/src/spend-analysis.ts b/products/desktop/packages/api-client/src/spend-analysis.tsindex a289ca389d9c..28354088597e 100644--- a/products/desktop/packages/api-client/src/spend-analysis.ts+++ b/products/desktop/packages/api-client/src/spend-analysis.ts@@ -34,6 +34,17 @@ export interface SpendAnalysisDayRow {day: string;event_count: number;cost_usd: number;+ input_tokens: number;+ output_tokens: number;+}++export interface SpendAnalysisDayModelRow {+ day: string;+ model: string | null;+ cost_usd: number;+ input_tokens: number;+ output_tokens: number;+ generation_count: number;}export interface SpendAnalysisBreakdown<TRow> {@@ -48,6 +59,7 @@ export interface SpendAnalysisResponse {by_model: SpendAnalysisBreakdown<SpendAnalysisModelRow>;// Optional until the backend by_day rollout reaches every deployment.by_day?: SpendAnalysisBreakdown<SpendAnalysisDayRow>;+ by_day_model?: SpendAnalysisDayModelRow[];// `top_traces` is still in the backend response shape (always empty) per// posthog/posthog#59796. Renderer code does not consume it; left out of the// TS type so future readers see only what we actually use.diff --git a/products/desktop/packages/core/src/billing/spendAnalysisFormat.test.ts b/products/desktop/packages/core/src/billing/spendAnalysisFormat.test.tsindex c4891949ceeb..9133e0d7ce62 100644--- a/products/desktop/packages/core/src/billing/spendAnalysisFormat.test.ts+++ b/products/desktop/packages/core/src/billing/spendAnalysisFormat.test.ts@@ -46,17 +46,76 @@ describe("fillSpendDays", () => {it("zero-fills days without rows across the window", () => {const filled = fillSpendDays([- { day: "2026-07-01", event_count: 3, cost_usd: 1.5 },- { day: "2026-07-03", event_count: 1, cost_usd: 0.25 },+ {+ day: "2026-07-01",+ event_count: 3,+ cost_usd: 1.5,+ input_tokens: 100,+ output_tokens: 10,+ },+ {+ day: "2026-07-03",+ event_count: 1,+ cost_usd: 0.25,+ input_tokens: 20,+ output_tokens: 2,+ },],"2026-07-01T00:00:00Z","2026-07-04T12:00:00Z",+ [+ {+ day: "2026-07-01",+ model: "model-a",+ cost_usd: 1.5,+ input_tokens: 100,+ output_tokens: 10,+ generation_count: 3,+ },+ ],);expect(filled).toEqual([- { day: "2026-07-01", event_count: 3, cost_usd: 1.5 },- { day: "2026-07-02", event_count: 0, cost_usd: 0 },- { day: "2026-07-03", event_count: 1, cost_usd: 0.25 },- { day: "2026-07-04", event_count: 0, cost_usd: 0 },+ {+ day: "2026-07-01",+ event_count: 3,+ cost_usd: 1.5,+ input_tokens: 100,+ output_tokens: 10,+ models: [+ {+ day: "2026-07-01",+ model: "model-a",+ cost_usd: 1.5,+ input_tokens: 100,+ output_tokens: 10,+ generation_count: 3,+ },+ ],+ },+ {+ day: "2026-07-02",+ event_count: 0,+ cost_usd: 0,+ input_tokens: 0,+ output_tokens: 0,+ models: [],+ },+ {+ day: "2026-07-03",+ event_count: 1,+ cost_usd: 0.25,+ input_tokens: 20,+ output_tokens: 2,+ models: [],+ },+ {+ day: "2026-07-04",+ event_count: 0,+ cost_usd: 0,+ input_tokens: 0,+ output_tokens: 0,+ models: [],+ },]);});diff --git a/products/desktop/packages/core/src/billing/spendAnalysisFormat.ts b/products/desktop/packages/core/src/billing/spendAnalysisFormat.tsindex 14dff94430e4..330e52e3e3f4 100644--- a/products/desktop/packages/core/src/billing/spendAnalysisFormat.ts+++ b/products/desktop/packages/core/src/billing/spendAnalysisFormat.ts@@ -1,4 +1,8 @@-import type { SpendAnalysisDayRow } from "./spendAnalysisTypes";+import type {+ SpendAnalysisDayModelRow,+ SpendAnalysisDayRow,+ SpendAnalysisFilledDay,+} from "./spendAnalysisTypes";export function formatUsd(amount: number): string {if (amount === 0) return "$0";@@ -40,18 +44,19 @@ export function formatWindow(fromIso: string, toIso: string): string {const DAY_MS = 86_400_000;const MAX_FILLED_DAYS = 100;-export interface SpendAnalysisFilledDay {- day: string;- event_count: number;- cost_usd: number;-}-export function fillSpendDays(items: SpendAnalysisDayRow[],fromIso: string,toIso: string,+ byDayModel: SpendAnalysisDayModelRow[] = [],): SpendAnalysisFilledDay[] {const byDay = new Map(items.map((row) => [row.day, row]));+ const modelsByDay = new Map<string, SpendAnalysisDayModelRow[]>();+ for (const row of byDayModel) {+ const rows = modelsByDay.get(row.day) ?? [];+ rows.push(row);+ modelsByDay.set(row.day, rows);+ }const from = new Date(fromIso);const start = Date.UTC(from.getUTCFullYear(),@@ -71,6 +76,9 @@ export function fillSpendDays(day,event_count: row?.event_count ?? 0,cost_usd: row?.cost_usd ?? 0,+ input_tokens: row?.input_tokens ?? 0,+ output_tokens: row?.output_tokens ?? 0,+ models: modelsByDay.get(day) ?? [],});}return filled;diff --git a/products/desktop/packages/core/src/billing/spendAnalysisTypes.ts b/products/desktop/packages/core/src/billing/spendAnalysisTypes.tsindex 36ae6698122d..7d88a87b6f9a 100644--- a/products/desktop/packages/core/src/billing/spendAnalysisTypes.ts+++ b/products/desktop/packages/core/src/billing/spendAnalysisTypes.ts@@ -22,18 +22,32 @@ export interface SpendAnalysisToolRow {avg_input_tokens: number;}-export interface SpendAnalysisModelRow {- model: string | null;- generation_count: number;+export interface SpendAnalysisTokenRow {cost_usd: number;input_tokens: number;output_tokens: number;}-export interface SpendAnalysisDayRow {+export interface SpendAnalysisGenerationRow extends SpendAnalysisTokenRow {+ generation_count: number;+}++export interface SpendAnalysisModelRow extends SpendAnalysisGenerationRow {+ model: string | null;+}++export interface SpendAnalysisDayRow extends SpendAnalysisTokenRow {day: string;event_count: number;- cost_usd: number;+}++export interface SpendAnalysisDayModelRow extends SpendAnalysisGenerationRow {+ day: string;+ model: string | null;+}++export interface SpendAnalysisFilledDay extends SpendAnalysisDayRow {+ models: SpendAnalysisDayModelRow[];}export interface SpendAnalysisBreakdown<TRow> {@@ -48,4 +62,5 @@ export interface SpendAnalysisResponse {by_model: SpendAnalysisBreakdown<SpendAnalysisModelRow>;// Optional until the backend by_day rollout reaches every deployment.by_day?: SpendAnalysisBreakdown<SpendAnalysisDayRow>;+ by_day_model?: SpendAnalysisDayModelRow[];}diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendAnalysisSection.tsx b/products/desktop/packages/ui/src/features/usage/components/SpendAnalysisSection.tsxindex 304c72e66eb0..b2f88104711e 100644--- a/products/desktop/packages/ui/src/features/usage/components/SpendAnalysisSection.tsx+++ b/products/desktop/packages/ui/src/features/usage/components/SpendAnalysisSection.tsx@@ -7,6 +7,7 @@ import { Button, Callout, Flex, Spinner, Text } from "@radix-ui/themes";import { useMemo, useState } from "react";import { useSpendAnalysis } from "../useSpendAnalysis";import { ModelBreakdownCards } from "./ModelBreakdownCards";+import { SpendAnalysisSkeleton } from "./SpendAnalysisSkeleton";import {ProductBreakdownCard,ToolBreakdownCard,@@ -31,6 +32,7 @@ export function SpendAnalysisSection() {data.by_day.items,data.summary.date_from,data.summary.date_to,+ data.by_day_model,);}, [data]);@@ -72,14 +74,7 @@ export function SpendAnalysisSection() {</Callout.Text></Callout.Root>) : isLoading ? (- <Flex- align="center"- justify="center"- p="6"- className="rounded-(--radius-3) border border-(--gray-5)"- >- <Spinner size="2" />- </Flex>+ <SpendAnalysisSkeleton />) : data ? (<><SpendKpiStrip data={data} filledDays={filledDays} />diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendAnalysisSkeleton.tsx b/products/desktop/packages/ui/src/features/usage/components/SpendAnalysisSkeleton.tsxnew file mode 100644index 000000000000..6e2d4981a09f--- /dev/null+++ b/products/desktop/packages/ui/src/features/usage/components/SpendAnalysisSkeleton.tsx@@ -0,0 +1,132 @@+import { Skeleton } from "@posthog/quill";+import { Text } from "@radix-ui/themes";+import type { ReactNode } from "react";++const SKELETON_ROWS = ["first", "second", "third", "fourth", "fifth"];+const SKELETON_MODELS = [+ "first",+ "second",+ "third",+ "fourth",+ "fifth",+ "sixth",+];+const SKELETON_CHART_BARS = [28, 45, 62, 36, 70, 52, 84, 41, 58, 74];++function SpendKpiSkeleton() {+ return (+ <div className="grid grid-cols-4 overflow-hidden rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid)">+ {SKELETON_ROWS.slice(0, 4).map((key, index) => (+ <div+ key={key}+ className={`flex min-w-0 flex-col gap-3 px-4 py-3 ${index === 3 ? "" : "border-(--gray-5) border-r"}`}+ >+ <Skeleton className="h-3 w-20" />+ <Skeleton className="h-6 w-16" />+ <Skeleton className="h-3 w-24" />+ </div>+ ))}+ </div>+ );+}++function SpendTableSkeleton() {+ return (+ <div className="flex flex-col gap-3">+ <div className="grid grid-cols-4 gap-4">+ <Skeleton className="h-3 w-12" />+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-full" />+ </div>+ {SKELETON_ROWS.map((key) => (+ <div key={key} className="grid grid-cols-4 gap-4">+ <Skeleton className="h-3 w-4/5" />+ <Skeleton className="h-3 w-3/5" />+ <Skeleton className="h-3 w-3/5" />+ <Skeleton className="h-3 w-2/3" />+ </div>+ ))}+ </div>+ );+}++export function SpendAnalysisSkeleton() {+ return (+ <>+ <SpendKpiSkeleton />+ <SpendOverTimeCardSkeleton />+ <UsageCardSkeleton title="Cost by model">+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">+ {SKELETON_MODELS.map((key) => (+ <div+ key={key}+ className="flex flex-col gap-3 rounded-(--radius-2) border border-(--gray-5) bg-(--gray-2) p-3"+ >+ <div className="flex items-center justify-between gap-4">+ <Skeleton className="h-4 w-3/5" />+ <Skeleton className="h-4 w-10" />+ </div>+ <Skeleton className="h-3 w-full" />+ <div className="grid grid-cols-2 gap-x-4 gap-y-2">+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-full" />+ </div>+ </div>+ ))}+ </div>+ </UsageCardSkeleton>+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <UsageCardSkeleton title="By tool">+ <SpendTableSkeleton />+ </UsageCardSkeleton>+ <UsageCardSkeleton title="By product">+ <SpendTableSkeleton />+ </UsageCardSkeleton>+ </div>+ <UsageCardSkeleton title="Where to look">+ <div className="flex flex-col gap-3">+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-4/5" />+ <Skeleton className="h-3 w-3/5" />+ <div className="border-(--gray-5) border-t pt-3">+ <Skeleton className="h-7 w-64" />+ </div>+ </div>+ </UsageCardSkeleton>+ </>+ );+}++function SpendOverTimeCardSkeleton() {+ return (+ <UsageCardSkeleton title="Daily spend and total">+ <div className="flex h-56 items-end gap-2 px-3 pt-6">+ {SKELETON_CHART_BARS.map((height) => (+ <Skeleton+ key={height}+ className="flex-1"+ style={{ height: `${height}%` }}+ />+ ))}+ </div>+ </UsageCardSkeleton>+ );+}++function UsageCardSkeleton({+ title,+ children,+}: {+ title: string;+ children: ReactNode;+}) {+ return (+ <div className="flex flex-col gap-3 rounded-(--radius-3) border border-(--gray-5) p-4">+ <Text className="font-medium text-sm">{title}</Text>+ {children}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendKpiStrip.tsx b/products/desktop/packages/ui/src/features/usage/components/SpendKpiStrip.tsxindex d28373fa6a76..eec472a0fec8 100644--- a/products/desktop/packages/ui/src/features/usage/components/SpendKpiStrip.tsx+++ b/products/desktop/packages/ui/src/features/usage/components/SpendKpiStrip.tsx@@ -1,10 +1,12 @@import {formatUsd,formatWindow,- type SpendAnalysisFilledDay,windowDays,} from "@posthog/core/billing/spendAnalysisFormat";-import type { SpendAnalysisResponse } from "@posthog/core/billing/spendAnalysisTypes";+import type {+ SpendAnalysisFilledDay,+ SpendAnalysisResponse,+} from "@posthog/core/billing/spendAnalysisTypes";import { MetricCard, useChartTheme } from "@posthog/quill-charts";import type { ReactNode } from "react";import { spendDayLabel } from "./spendDayLabel";diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.ts b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.tsindex e553bb69fb2a..c08444ebf851 100644--- a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.ts+++ b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.test.ts@@ -1,4 +1,4 @@-import type { SpendAnalysisFilledDay } from "@posthog/core/billing/spendAnalysisFormat";+import type { SpendAnalysisFilledDay } from "@posthog/core/billing/spendAnalysisTypes";import { describe, expect, it, vi } from "vitest";vi.mock("@posthog/quill-charts", () => ({@@ -7,19 +7,82 @@ vi.mock("@posthog/quill-charts", () => ({useChartTheme: () => ({}),}));-import { spendSeriesForDays } from "./SpendOverTimeCard";+import {+ modelColorsForDays,+ spendSeriesForDays,+ tokenTotalsForDay,+} from "./SpendOverTimeCard";describe("spendSeriesForDays", () => {it("keeps daily spend separate from the cumulative total", () => {const days: SpendAnalysisFilledDay[] = [- { day: "2026-08-01", cost_usd: 1.25, event_count: 1 },- { day: "2026-08-02", cost_usd: -0.5, event_count: 2 },- { day: "2026-08-03", cost_usd: 2.75, event_count: 3 },+ {+ day: "2026-08-01",+ cost_usd: 1.25,+ event_count: 1,+ input_tokens: 100,+ output_tokens: 200,+ models: [],+ },+ {+ day: "2026-08-02",+ cost_usd: -0.5,+ event_count: 2,+ input_tokens: 300,+ output_tokens: 400,+ models: [],+ },+ {+ day: "2026-08-03",+ cost_usd: 2.75,+ event_count: 3,+ input_tokens: 500,+ output_tokens: 600,+ models: [],+ },];expect(spendSeriesForDays(days)).toMatchObject([{ key: "daily-spend", type: "bar", data: [1.25, 0, 2.75] },{ key: "cumulative-spend", type: "line", data: [1.25, 1.25, 4] },]);+ expect(tokenTotalsForDay(days, 1)).toEqual({+ daily: 700,+ cumulative: 1000,+ });+ });++ it("assigns distinct colors to each model", () => {+ const days: SpendAnalysisFilledDay[] = [+ {+ day: "2026-08-01",+ cost_usd: 0,+ event_count: 0,+ input_tokens: 0,+ output_tokens: 0,+ models: [+ {+ day: "2026-08-01",+ model: "gpt-5",+ cost_usd: 1,+ input_tokens: 1,+ output_tokens: 1,+ generation_count: 1,+ },+ {+ day: "2026-08-01",+ model: "claude-opus-4-8",+ cost_usd: 1,+ input_tokens: 1,+ output_tokens: 1,+ generation_count: 1,+ },+ ],+ },+ ];++ const colors = modelColorsForDays(days);++ expect(colors.get("gpt-5")).not.toBe(colors.get("claude-opus-4-8"));});});diff --git a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsxindex 9098252cf3a8..2299e38e58ad 100644--- a/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx+++ b/products/desktop/packages/ui/src/features/usage/components/SpendOverTimeCard.tsx@@ -1,13 +1,16 @@import { ChartBar } from "@phosphor-icons/react";import {+ formatTokens,formatUsd,- type SpendAnalysisFilledDay,} from "@posthog/core/billing/spendAnalysisFormat";+import type { SpendAnalysisFilledDay } from "@posthog/core/billing/spendAnalysisTypes";import {- DefaultTooltip,type Series,TimeSeriesComboChart,type TimeSeriesComboChartConfig,+ type TooltipContext,+ TooltipSurface,+ TooltipSwatch,useChartTheme,} from "@posthog/quill-charts";import { UsageCard } from "./UsageCard";@@ -16,6 +19,10 @@ interface SpendOverTimeCardProps {filledDays: SpendAnalysisFilledDay[];}+function modelLabel(model: string | null): string {+ return model ?? "Other models";+}+export function spendSeriesForDays(filledDays: SpendAnalysisFilledDay[],): Series[] {@@ -44,9 +51,119 @@ export function spendSeriesForDays(];}+export function tokenTotalsForDay(+ filledDays: SpendAnalysisFilledDay[],+ dayIndex: number,+): { daily: number; cumulative: number } {+ const daysThroughSelectedDay = filledDays.slice(0, dayIndex + 1);+ const daily = daysThroughSelectedDay.at(-1);++ return {+ daily: (daily?.input_tokens ?? 0) + (daily?.output_tokens ?? 0),+ cumulative: daysThroughSelectedDay.reduce(+ (total, day) => total + day.input_tokens + day.output_tokens,+ 0,+ ),+ };+}++function SpendTooltip({+ context,+ day,+ filledDays,+ modelColors,+}: {+ context: TooltipContext;+ day: SpendAnalysisFilledDay | undefined;+ filledDays: SpendAnalysisFilledDay[];+ modelColors: ReadonlyMap<string | null, string>;+}) {+ const dailySpend = context.seriesData.find(+ (series) => series.series.key === "daily-spend",+ )?.value;+ const cumulativeSpend = context.seriesData.find(+ (series) => series.series.key === "cumulative-spend",+ )?.value;+ const tokenTotals = tokenTotalsForDay(filledDays, context.dataIndex);+ return (+ <TooltipSurface>+ <div className="mb-2">+ <div className="font-semibold">+ {new Intl.DateTimeFormat("en-US", {+ day: "numeric",+ month: "short",+ timeZone: "UTC",+ year: "numeric",+ }).format(new Date(`${context.label}T00:00:00Z`))}+ </div>+ <div className="opacity-60">Daily breakdown</div>+ </div>+ {day?.models.length ? (+ <div className="flex items-center gap-2 px-1.5 pb-0.5 text-xs opacity-60">+ <span className="flex-1">Model</span>+ <span className="w-10 text-right">Cost</span>+ <span className="w-12 text-right">Tokens</span>+ </div>+ ) : null}+ {day?.models.map((model) => (+ <div+ key={model.model}+ className="flex min-w-0 items-center gap-2 px-1.5 py-0.5"+ >+ <TooltipSwatch+ color={modelColors.get(model.model) ?? "var(--data-color-1)"}+ />+ <span className="flex-1 truncate">{modelLabel(model.model)}</span>+ <strong className="w-10 text-right tabular-nums">+ {formatUsd(model.cost_usd)}+ </strong>+ <span className="w-12 text-right tabular-nums opacity-60">+ {formatTokens(model.input_tokens + model.output_tokens)}+ </span>+ </div>+ ))}+ <div className="mt-2 border-current/25 border-t pt-2">+ <div className="flex items-center gap-3 px-1.5 py-0.5">+ <strong className="flex-1">Daily total</strong>+ <strong className="w-10 text-right tabular-nums">+ {formatUsd(dailySpend ?? 0)}+ </strong>+ <strong className="w-12 text-right tabular-nums opacity-60">+ {formatTokens(tokenTotals.daily)}+ </strong>+ </div>+ <div className="flex items-center gap-3 px-1.5 py-0.5">+ <strong className="flex-1">Cumulative total</strong>+ <strong className="w-10 text-right tabular-nums">+ {formatUsd(cumulativeSpend ?? 0)}+ </strong>+ <strong className="w-12 text-right tabular-nums opacity-60">+ {formatTokens(tokenTotals.cumulative)}+ </strong>+ </div>+ </div>+ </TooltipSurface>+ );+}++export function modelColorsForDays(+ filledDays: SpendAnalysisFilledDay[],+): ReadonlyMap<string | null, string> {+ const models = [+ ...new Set(+ filledDays.flatMap((day) => day.models.map((model) => model.model)),+ ),+ ].sort((a, b) => modelLabel(a).localeCompare(modelLabel(b)));++ return new Map(+ models.map((model, index) => [model, `var(--data-color-${index + 1})`]),+ );+}+export function SpendOverTimeCard({ filledDays }: SpendOverTimeCardProps) {const theme = useChartTheme();const series = spendSeriesForDays(filledDays);+ const modelColors = modelColorsForDays(filledDays);return (<UsageCard@@ -54,29 +171,55 @@ export function SpendOverTimeCard({ filledDays }: SpendOverTimeCardProps) {title="Daily spend and total"><div className="flex h-56 w-full flex-col">- <TimeSeriesComboChart- series={series}- labels={filledDays.map((d) => d.day)}- config={{- xAxis: { timezone: "UTC", interval: "day" },- yAxis: [- { id: "daily", position: "left", tickFormatter: formatUsd },- {- id: "cumulative",- position: "right",- tickFormatter: formatUsd,- },- ] as unknown as TimeSeriesComboChartConfig["yAxis"],- barLayout: "grouped",- barCornerRadius: 2,- showCrosshair: true,- tooltip: { placement: "cursor", showTotal: false },- }}- theme={theme}- tooltip={(context) => (- <DefaultTooltip {...context} valueFormatter={formatUsd} />- )}- />+ <div className="flex items-center justify-between px-2 text-(--gray-11) text-xs">+ <span className="flex items-center gap-1.5">+ <span className="size-2 rounded-sm bg-(--data-color-1)" />+ Daily spend (USD)+ </span>+ <span className="flex items-center gap-1.5">+ <span className="size-2 rounded-full bg-(--data-color-2)" />+ Cumulative spend (USD)+ </span>+ </div>+ <div className="min-h-0 flex-1">+ <TimeSeriesComboChart+ className="h-full"+ series={series}+ labels={filledDays.map((d) => d.day)}+ config={{+ xAxis: { timezone: "UTC", interval: "day" },+ yAxis: [+ {+ id: "daily",+ position: "left",+ label: "Daily spend (USD)",+ format: "currency",+ currency: "USD",+ },+ {+ id: "cumulative",+ position: "right",+ label: "Cumulative spend (USD)",+ format: "currency",+ currency: "USD",+ },+ ] as unknown as TimeSeriesComboChartConfig["yAxis"],+ barLayout: "grouped",+ barCornerRadius: 2,+ showCrosshair: true,+ tooltip: { placement: "cursor", showTotal: false },+ }}+ theme={theme}+ tooltip={(context) => (+ <SpendTooltip+ context={context}+ day={filledDays[context.dataIndex]}+ filledDays={filledDays}+ modelColors={modelColors}+ />+ )}+ />+ </div></div></UsageCard>);diff --git a/products/desktop/packages/ui/src/features/usage/components/modelBreakdownSort.test.ts b/products/desktop/packages/ui/src/features/usage/components/modelBreakdownSort.test.tsdeleted file mode 100644index 4c96436d2eec..000000000000--- a/products/desktop/packages/ui/src/features/usage/components/modelBreakdownSort.test.ts+++ /dev/null@@ -1,35 +0,0 @@-import type { SpendAnalysisModelRow } from "@posthog/core/billing/spendAnalysisTypes";-import { describe, expect, it } from "vitest";-import { sortModelBreakdownRows } from "./ModelBreakdownCards";--describe("sortModelBreakdownRows", () => {- const rows: SpendAnalysisModelRow[] = [- {- model: "highest-cost",- cost_usd: 10,- input_tokens: 100,- output_tokens: 50,- generation_count: 1,- },- {- model: "most-tokens",- cost_usd: 2,- input_tokens: 900,- output_tokens: 100,- generation_count: 1,- },- ];-- it("orders models by the selected metric without changing the input rows", () => {- expect(- sortModelBreakdownRows(rows, "cost").map((row) => row.model),- ).toEqual(["highest-cost", "most-tokens"]);- expect(- sortModelBreakdownRows(rows, "tokens").map((row) => row.model),- ).toEqual(["most-tokens", "highest-cost"]);- expect(rows.map((row) => row.model)).toEqual([- "highest-cost",- "most-tokens",- ]);- });-});diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e5237e9baa84..a5f163882a4c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -60282,6 +60282,10 @@ export namespace Schemas {event_count: number;/** Total cost in USD on this day for the scoped product. */cost_usd: number;+ /** Sum of `$ai_input_tokens` on this day for the scoped product. */+ input_tokens: number;+ /** Sum of `$ai_output_tokens` on this day for the scoped product. */+ output_tokens: number;}export interface _DayBreakdown {@@ -60291,6 +60295,24 @@ export namespace Schemas {truncated: boolean;}+ export interface _DayModelBreakdownRow {+ /** UTC calendar day the events fall on (`toDate(timestamp)`). */+ day: string;+ /**+ * Model name for one of the highest-cost models in the selected window. Null is the aggregate of all remaining models, including events without a model.+ * @nullable+ */+ model: string | null;+ /** Total cost in USD for this model on this day. */+ cost_usd: number;+ /** Sum of `$ai_input_tokens` for this model on this day. */+ input_tokens: number;+ /** Sum of `$ai_output_tokens` for this model on this day. */+ output_tokens: number;+ /** Number of $ai_generation + $ai_embedding events for this model on this day. */+ generation_count: number;+ }+export interface _BucketBreakdownRow {/** UTC start of the time bucket the events fall in (`toStartOfInterval(timestamp, ...)`). */bucket_start: string;@@ -60363,6 +60385,8 @@ export namespace Schemas {by_model: _ModelBreakdown;/** Spend grouped by UTC day, ordered ascending. Scoped to `product`. Not subject to `limit`. */by_day: _DayBreakdown;+ /** Daily model spend for the scoped product, ordered by day and cost. Includes the six highest-cost models in the selected window plus a null-model row for the remaining models. */+ by_day_model: _DayModelBreakdownRow[];/** Spend grouped by UTC time bucket with per-bucket cost/token components, ordered ascending. Scoped to `product`. Only present when the request set `bucket_minutes`. */by_bucket?: _BucketBreakdown;/** Deprecated — always returns `{items: [], truncated: false}`. Trace IDs are opaque strings that aren't actionable in the UI. Kept in the response shape so existing consumers don't crash; remove your rendering of this field and we'll drop it from the response entirely in a follow-up. */