Skip to content

: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.

feat(signals): show staff what a scout run cost in the roster (#94376)

posthog[bot]4f1320f5690b
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 0d4634b6e10b..2b05114b5a7e 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -70,12 +70,19 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
- `derived_metadata.py`
Computes the `metadata["derived"]` region on the run row at finalize: booleans the harness reads back off the run's own settled output (`has_emit_report`, `has_edit_report`, `has_self_improvement`, `has_chart`, `has_self_validation`). Deliberately server-derived rather than scout-reported, so a flag can't be omitted or contradicted by the model, and computed in one place at finalize rather than stamped incrementally at each emit/edit site.
`has_self_improvement` classifies authored report titles through `tools/report.is_self_improvement_title`, the same predicate the lifecycle events use, so the run row and the event stream can never disagree. `has_self_validation` reads the run window against the skill-namespaced `followup:` scratchpad keys, since working that queue means writing to it.
+- `run_costs.py`
+ What a run spent on model calls, for the staff-only cost readout in the roster's run tooltips.
+ A scout run is a Tasks run, so its `$ai_generation` events land in the internal AI observability project stamped with `task_origin_product = 'signals_scout'` and the run's `task_run_id`; the sum per run comes from `tasks.facade.billing.get_local_task_run_token_costs`, which is keyed on the origin product rather than on `ai_product` — scout runs report `ai_product = 'signals_scout'`, so the desktop read's `posthog_code` filter priced every one of them at zero, and a report's pipeline stages report a different value per stage again.
+ A batch of runs costs one query, and each run's answer is cached: an hour once the total is final, and a minute while it can still move.
+ A total can still move for three reasons — the run is still generating, the run settled inside `RUN_COST_INGESTION_GRACE` so its last generations may not have reached ClickHouse yet, or nothing is attributed to the run at all and the answer is not yet a number.
+ Two things it will not do. It never reports a run with no attributed generation as `$0.00`, since a free run and an unattributed one are not the same thing — such a run carries no cost at all. And it never reports zero where there is no internal project to read: the batch comes back `available=false` instead. The read is region-local (`INTERNAL_LLM_ANALYTICS_TEAM_ID_BY_REGION` in `task_usage.py`), so both clouds price their own runs and neither needs the cross-region proxy the per-task desktop read uses.
- `serializers.py`
DRF serializers for the harness HTTP surface (runs, scratchpad, project profile).
Annotated for drf-spectacular so the generated MCP tools have informative schemas.
- `views.py`
`SignalScoutRunViewSet`, `SignalScoutConfigViewSet`, `SignalScratchpadViewSet`, `SignalScoutNoteViewSet`, `SignalProjectProfileViewSet`, `SignalScoutMetadataViewSet`, `SignalScoutMembersViewSet`, `SignalScoutViewSet`.
Routed under `project_signals_scout_*` basenames in `products/signals/backend/routes.py` and exposed as `scout-*` MCP tools via `products/signals/mcp/tools.yaml`.
+ `SignalScoutRunViewSet` also carries the staff-only `token-costs` batch action (`run_costs.py`), which sits in `tools.yaml` as `enabled: false` — codegen registers every operation, and this one stays off, because fleet spend is an internal operating number and the events it sums sit in a project other than the one in the path.
`SignalScoutViewSet` backs `scout-create`: it creates a custom `signals-scout-*` skill and its runnable config atomically, grants the report-channel tools server-side, and treats an identical definition as a retry while rejecting conflicting definitions.
`SignalScoutMembersViewSet` (`scout-members-list`) is the reviewer-routing roster:
it returns the project's members (those with access to the team) with `user_uuid` / `email` / `github_login` so a report-channel scout can populate `suggested_reviewers` at cold start. The roster is member PII the scout needs to route, gated on the internal `signal_scout_internal` scope object (`scope_object = "signal_scout_internal"`, default `list` → `signal_scout_internal:read`, satisfied by the sandbox token's `…:write`) — so, like `emit-signal`, it is reachable only inside a scout run and never enters a customer's public MCP catalog. (The narrower `signal_scout_report` scope was considered but is transient — kept only while emit-signal and emit-report coexist — so the durable tool stays on `signal_scout_internal`.) Membership is resolved server-side via `report_generation/resolve_reviewers.list_project_members` (through `Team.all_users_with_access()`, so private-project access control is honored), the project-nested path that the org-nested `org-members-list` tool (stripped + 403'd for a scoped-team token) can't provide.
diff --git a/products/signals/backend/scout_harness/run_costs.py b/products/signals/backend/scout_harness/run_costs.py
new file mode 100644
index 000000000000..69db17d408d7
--- /dev/null
+++ b/products/signals/backend/scout_harness/run_costs.py
@@ -0,0 +1,161 @@
+"""Model spend per scout run, for the staff-only cost readout on the roster.
+
+A scout run is a Tasks run, so the `$ai_generation` events it makes land in the internal AI
+observability project stamped with `task_origin_product = 'signals_scout'` and the run's
+`task_run_id`. That makes cost per run one grouped sum, which is what
+`get_local_task_run_token_costs` does; this module batches a set of runs into one such sum,
+caches each run's answer, and keeps "not attributed" distinct from "$0.00".
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from datetime import datetime, timedelta
+from decimal import Decimal
+from uuid import UUID
+
+from django.core.cache import cache
+from django.utils import timezone
+
+from posthog.clickhouse.query_tagging import Product
+from posthog.dataclasses import frozen
+
+from products.signals.backend.models import SignalScoutRun
+from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.billing import TaskTokenUsageUnavailable, get_local_task_run_token_costs
+
+# A settled run's spend is final, so it outlives the roster's 60s poll — otherwise every poll
+# re-sums runs whose answer cannot change. A live run keeps generating, so it is cached only long
+# enough to absorb a burst of polls, and its number stays a lower bound until the run finishes.
+# An unknown cost takes the short timeout whatever the run's status. "Nothing attributed" is not a
+# final answer: the run's generations may still be crossing capture, or its model may not be in the
+# price map yet. Both resolve on their own, so pinning the gap for an hour hides a readable cost.
+SETTLED_RUN_COST_CACHE_TIMEOUT_SECONDS = 60 * 60
+LIVE_RUN_COST_CACHE_TIMEOUT_SECONDS = 60
+# Generations are stamped while the run works, so the read window opens at the earliest run in the
+# batch. The margin absorbs clock skew between the run row and the generation events.
+RUN_COST_LOOKBACK_MARGIN = timedelta(hours=1)
+# A run's status flips terminal the moment the agent stops, but its last `$ai_generation` events are
+# captured fire-and-forget and still have to cross capture, Kafka, and ClickHouse before the sum can
+# see them. So a total read right after a run settles can be short, and pinning that for an hour
+# hides spend that is about to be readable. The window is cheap: the roster spans days of runs, and
+# only the handful that settled in the last few minutes stay on the short timeout.
+RUN_COST_INGESTION_GRACE = timedelta(minutes=5)
+# A run whose status says it can still generate, so its cost is a running total, not a final one.
+LIVE_RUN_STATUSES = frozenset(
+ {
+ tasks_facade.TaskRunStatus.NOT_STARTED,
+ tasks_facade.TaskRunStatus.QUEUED,
+ tasks_facade.TaskRunStatus.IN_PROGRESS,
+ }
+)
+
+
+@frozen
+class ScoutRunTokenCost:
+ run_id: str
+ # None when no generation is attributed to the run — a run that failed before its first model
+ # call, or one whose events haven't landed yet. Deliberately not 0, which would read as "this
+ # run was free".
+ token_cost_usd: Decimal | None
+
+
+@frozen
+class ScoutRunTokenCosts:
+ costs: list[ScoutRunTokenCost]
+ # False when this deployment has no internal AI observability project to read, so every cost
+ # is unknown rather than zero.
+ available: bool
+
+
+@frozen
+class _RunToPrice:
+ """What pricing a run needs: which run, which generations, when to look, and whether it's done."""
+
+ run_id: str
+ task_run_id: str
+ created_at: datetime
+ # True while the run can still generate, and for a grace period after it settles while its last
+ # generations may still be landing. Either way the sum read now is not the final one.
+ cost_may_still_move: bool
+
+
+def _cost_may_still_move(*, status: str, completed_at: datetime | None, now: datetime) -> bool:
+ if status in LIVE_RUN_STATUSES:
+ return True
+ # A terminal run with no stamp took a path that does not write one, so there is no settle time
+ # to measure the grace against. Treat it as final rather than re-querying it on every poll.
+ if completed_at is None:
+ return False
+ return now - completed_at < RUN_COST_INGESTION_GRACE
+
+
+def scout_run_token_costs(*, team_id: int, run_ids: Sequence[UUID]) -> ScoutRunTokenCosts:
+ """Sum the model spend attributed to each of this team's scout runs.
+
+ Runs belonging to another team, and run ids that don't exist, contribute nothing — the team
+ filter is the tenant guard, so one stale id never fails the batch.
+ """
+ now = timezone.now()
+ runs = [
+ _RunToPrice(
+ run_id=str(run_id),
+ # `task_run` is a non-null 1:1, so every run has exactly one id to attribute against.
+ task_run_id=str(task_run_id),
+ created_at=created_at,
+ cost_may_still_move=_cost_may_still_move(status=status, completed_at=completed_at, now=now),
+ )
+ for run_id, created_at, task_run_id, status, completed_at in SignalScoutRun.objects.filter(
+ team_id=team_id, id__in=run_ids
+ ).values_list("id", "created_at", "task_run_id", "task_run__status", "task_run__completed_at")
+ ]
+ if not runs:
+ return ScoutRunTokenCosts(costs=[], available=True)
+
+ costs: dict[str, Decimal | None] = {}
+ pending: list[_RunToPrice] = []
+ for run in runs:
+ cached = cache.get(_cache_key(team_id=team_id, task_run_id=run.task_run_id))
+ if cached is None:
+ pending.append(run)
+ continue
+ # An empty string holds a cached "nothing attributed": the cache can't tell a stored
+ # `None` from a miss.
+ costs[run.run_id] = Decimal(cached) if cached else None
+
+ if pending:
+ try:
+ costs.update(_query_pending_costs(team_id=team_id, pending=pending))
+ except TaskTokenUsageUnavailable:
+ return ScoutRunTokenCosts(costs=[], available=False)
+
+ return ScoutRunTokenCosts(
+ costs=[ScoutRunTokenCost(run_id=run_id, token_cost_usd=cost) for run_id, cost in costs.items()],
+ available=True,
+ )
+
+
+def _cache_key(*, team_id: int, task_run_id: str) -> str:
+ return f"scout_run_token_cost:v1:{team_id}:{task_run_id}"
+
+
+def _query_pending_costs(*, team_id: int, pending: list[_RunToPrice]) -> dict[str, Decimal | None]:
+ by_task_run_id = get_local_task_run_token_costs(
+ team_id=team_id,
+ origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT,
+ task_run_ids=[UUID(run.task_run_id) for run in pending],
+ generated_after=min(run.created_at for run in pending) - RUN_COST_LOOKBACK_MARGIN,
+ product=Product.SIGNALS,
+ )
+ costs: dict[str, Decimal | None] = {}
+ for run in pending:
+ cost = by_task_run_id.get(run.task_run_id)
+ costs[run.run_id] = cost
+ cache.set(
+ _cache_key(team_id=team_id, task_run_id=run.task_run_id),
+ str(cost) if cost is not None else "",
+ timeout=SETTLED_RUN_COST_CACHE_TIMEOUT_SECONDS
+ if cost is not None and not run.cost_may_still_move
+ else LIVE_RUN_COST_CACHE_TIMEOUT_SECONDS,
+ )
+ return costs
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index fe8f07715124..96d867115784 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -380,6 +380,38 @@ class ScoutRunIdsBatchRequestSerializer(serializers.Serializer):
)
+class ScoutRunTokenCostSerializer(serializers.Serializer):
+ """What one scout run spent on model calls."""
+
+ run_id = serializers.CharField(help_text="UUID of the `SignalScoutRun` this cost belongs to.")
+ token_cost_usd = serializers.FloatField(
+ allow_null=True,
+ help_text=(
+ "Model spend attributed to the run in US dollars, summed from its `$ai_generation` events. "
+ "Null when no generation is attributed to the run — it failed before its first model call, "
+ "or its events haven't landed yet. A run still in progress reports what it has spent so far."
+ ),
+ )
+
+
+class ScoutRunTokenCostsSerializer(serializers.Serializer):
+ """Model spend for a batch of scout runs."""
+
+ costs = ScoutRunTokenCostSerializer(
+ many=True,
+ help_text=(
+ "One entry per requested run that exists on this project. Runs from another project, and "
+ "ids that match no run, are absent."
+ ),
+ )
+ available = serializers.BooleanField(
+ help_text=(
+ "False when this deployment has no internal AI observability project to read the "
+ "generations from, so `costs` is empty and every cost is unknown rather than zero."
+ ),
+ )
+
+
class RecentEmissionsQuerySerializer(serializers.Serializer):
"""Query parameters for `recent-emissions` — recent findings across every run on the team.
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 9893d52049af..d7cefb616110 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -67,6 +67,7 @@ from products.signals.backend.scout_harness.config_registry import enabled_scout
from products.signals.backend.scout_harness.fleet_sync import materialize_scout_fleet
from products.signals.backend.scout_harness.lazy_seed import scout_skill_origin
from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM
+from products.signals.backend.scout_harness.run_costs import scout_run_token_costs
from products.signals.backend.scout_harness.run_gates import (
ScoutRunRejection,
ScoutRunRejectionKind,
@@ -102,6 +103,7 @@ from products.signals.backend.scout_harness.serializers import (
ScoutNoteSerializer,
ScoutNotesQuerySerializer,
ScoutRunIdsBatchRequestSerializer,
+ ScoutRunTokenCostsSerializer,
ScratchpadEntrySerializer,
SearchMemoryQuerySerializer,
SearchRecentRunsQuerySerializer,
@@ -787,6 +789,47 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
return Response(ScoutEmissionReportLinkSerializer(links, many=True).data)
+ @validated_request(
+ request_serializer=ScoutRunIdsBatchRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=ScoutRunTokenCostsSerializer,
+ description="Model spend for each requested run that exists on this project.",
+ ),
+ 403: OpenApiResponse(description="Caller is not PostHog staff."),
+ },
+ summary="Get the model spend of many runs at once",
+ description=(
+ "Return what each requested `SignalScoutRun` spent on model calls, summed from the "
+ "`$ai_generation` events its sandbox produced. One query for the whole batch, cached per run: "
+ "a settled run's total is final, a run still in progress reports what it has spent so far. "
+ "`available` is false where the internal AI observability project holding those events can't "
+ "be read, so an unknown cost never reads as zero. Staff-only — fleet spend is an internal "
+ "operating number, and the events sit outside the project in the path. Strictly team-scoped — "
+ "run ids belonging to another project contribute no rows."
+ ),
+ operation_id="signals_scout_runs_token_costs",
+ )
+ @action(
+ detail=False,
+ methods=["post"],
+ url_path="token-costs",
+ required_scopes=["signal_scout:read"],
+ pagination_class=None,
+ )
+ def token_costs(self, request: Request, **kwargs) -> Response:
+ if not cast(User, request.user).is_staff:
+ raise exceptions.PermissionDenied("Only PostHog staff can read scout run costs.")
+ costs = scout_run_token_costs(team_id=_canonical_team_id(self), run_ids=request.validated_data["run_ids"])
+ return Response(
+ ScoutRunTokenCostsSerializer(
+ {
+ "costs": [dataclasses.asdict(cost) for cost in costs.costs],
+ "available": costs.available,
+ }
+ ).data
+ )
+
@validated_request(
request_serializer=EmitFindingRequestSerializer,
parameters=[_RUN_ID_PATH_PARAMETER],
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index 34227c4c8005..727a1a983691 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -7,6 +7,7 @@ import asyncio
from contextlib import contextmanager
from dataclasses import replace
from datetime import UTC, datetime, timedelta
+from decimal import Decimal
from typing import TYPE_CHECKING
import pytest
@@ -14,8 +15,10 @@ from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
from django.apps import apps
+from django.core.cache import cache
from django.db import OperationalError
from django.test import SimpleTestCase
+from django.utils import timezone
import pytest_asyncio
from asgiref.sync import sync_to_async
@@ -31,6 +34,7 @@ from products.signals.backend.agent_runtime import AgentRuntime
from products.signals.backend.daily_limit import DailyReportLimitGate
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.report_charts import ReportChart
+from products.signals.backend.scout_harness import run_costs
from products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEY
from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, _compute_row_hash
from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_S, failure_streak_pause_threshold
@@ -63,6 +67,7 @@ from products.signals.backend.scout_harness.tools.runs import _build_task_url, _
from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, run_signals_scout_activity
from products.skills.backend.models.skills import LLMSkill, LLMSkillFile, LLMSkillOwner
from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.billing import TaskTokenUsageUnavailable
if TYPE_CHECKING:
from products.tasks.backend.models import TaskRun
@@ -2472,3 +2477,122 @@ class TestRunRowProvenanceStamps(BaseTest):
business_knowledge_maintained=True,
)
assert (run.metadata or {})["business_knowledge_maintained"] is True
+
+
+class TestScoutRunTokenCosts(BaseTest):
+ """The staff-only per-run cost read behind the roster's run tooltips."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def _run(
+ self,
+ *,
+ team: Team | None = None,
+ task_run_status: str | None = None,
+ settled_seconds_ago: int | None = None,
+ ) -> SignalScoutRun:
+ team = team or self.team
+ task_run = _make_task_run(team)
+ if task_run_status is not None:
+ task_run.status = task_run_status
+ task_run.save(update_fields=["status"])
+ if settled_seconds_ago is not None:
+ task_run.completed_at = timezone.now() - timedelta(seconds=settled_seconds_ago)
+ task_run.save(update_fields=["completed_at"])
+ config, _ = SignalScoutConfig.objects.get_or_create(team=team, skill_name="signals-scout-general")
+ return SignalScoutRun.objects.create(
+ team=team,
+ task_run=task_run,
+ scout_config=config,
+ skill_name="signals-scout-general",
+ skill_version=1,
+ )
+
+ def test_prices_each_run_and_serves_a_settled_run_from_cache(self) -> None:
+ run = self._run(task_run_status="completed")
+ with patch.object(
+ run_costs, "get_local_task_run_token_costs", return_value={str(run.task_run_id): Decimal("1.5")}
+ ) as query:
+ first = run_costs.scout_run_token_costs(team_id=self.team.id, run_ids=[run.id])
+ second = run_costs.scout_run_token_costs(team_id=self.team.id, run_ids=[run.id])
+
+ assert first.available
+ assert first.costs == [run_costs.ScoutRunTokenCost(run_id=str(run.id), token_cost_usd=Decimal("1.5"))]
+ assert second.costs == first.costs
+ # The roster polls every 60s and a settled run's spend is final, so the second read must not
+ # re-run the query.
+ query.assert_called_once()
+ called = query.call_args.kwargs
+ assert called["origin_product"] == "signals_scout"
+ assert called["task_run_ids"] == [run.task_run_id]
+ # The window has to open before the run did, or the sum finds none of its generations.
+ assert called["generated_after"] < run.created_at
+
+ def test_run_with_no_attributed_generations_reads_as_unknown(self) -> None:
+ # A run that failed before its first model call must not read as "$0.00 spent".
+ run = self._run(task_run_status="failed")
+ with patch.object(run_costs, "get_local_task_run_token_costs", return_value={}):
+ costs = run_costs.scout_run_token_costs(team_id=self.team.id, run_ids=[run.id])
+
+ assert costs.available
+ assert costs.costs == [run_costs.ScoutRunTokenCost(run_id=str(run.id), token_cost_usd=None)]
+
+ @parameterized.expand(
+ [
+ ("in_progress", "in_progress", None, Decimal("1"), run_costs.LIVE_RUN_COST_CACHE_TIMEOUT_SECONDS),
+ ("completed", "completed", None, Decimal("1"), run_costs.SETTLED_RUN_COST_CACHE_TIMEOUT_SECONDS),
+ ("completed but unpriced", "completed", None, None, run_costs.LIVE_RUN_COST_CACHE_TIMEOUT_SECONDS),
+ ("settled seconds ago", "completed", 5, Decimal("1"), run_costs.LIVE_RUN_COST_CACHE_TIMEOUT_SECONDS),
+ ("settled long ago", "completed", 60 * 60, Decimal("1"), run_costs.SETTLED_RUN_COST_CACHE_TIMEOUT_SECONDS),
+ ]
+ )
+ def test_only_a_known_total_on_a_settled_run_is_cached_for_long(
+ self,
+ _name: str,
+ task_run_status: str,
+ settled_seconds_ago: int | None,
+ cost: Decimal | None,
+ expected_timeout: int,
+ ) -> None:
+ # A run still generating keeps spending, so caching its partial total for as long as a
+ # finished run's would leave the roster showing a number that stopped moving. A settled run
+ # with nothing attributed is the other unfinished answer: its generations may still be
+ # crossing capture, or its model may not be priced yet, and both resolve within the hour.
+ # A run that settled seconds ago is the same case with a number attached: the total can be
+ # short of its last generations until they land.
+ run = self._run(task_run_status=task_run_status, settled_seconds_ago=settled_seconds_ago)
+ with (
+ patch.object(
+ run_costs,
+ "get_local_task_run_token_costs",
+ return_value={str(run.task_run_id): cost} if cost is not None else {},
+ ),
+ patch.object(run_costs.cache, "set") as cache_set,
+ ):
+ run_costs.scout_run_token_costs(team_id=self.team.id, run_ids=[run.id])
+
+ assert cache_set.call_args.kwargs["timeout"] == expected_timeout
+
+ def test_unreadable_cost_project_is_reported_rather_than_priced_at_zero(self) -> None:
+ # The generations live in one region's internal project, so a deployment that can't read it
+ # has to say the cost is unknown.
+ run = self._run(task_run_status="completed")
+ with patch.object(run_costs, "get_local_task_run_token_costs", side_effect=TaskTokenUsageUnavailable()):
+ costs = run_costs.scout_run_token_costs(team_id=self.team.id, run_ids=[run.id])
+
+ assert costs.available is False
+ assert costs.costs == []
+
+ def test_another_teams_run_is_not_priced(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ mine = self._run(task_run_status="completed")
+ theirs = self._run(team=other_team, task_run_status="completed")
+ with patch.object(
+ run_costs, "get_local_task_run_token_costs", return_value={str(mine.task_run_id): Decimal("1")}
+ ) as query:
+ costs = run_costs.scout_run_token_costs(team_id=self.team.id, run_ids=[mine.id, theirs.id])
+
+ assert [cost.run_id for cost in costs.costs] == [str(mine.id)]
+ assert query.call_args.kwargs["task_run_ids"] == [mine.task_run_id]
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index f16227cd417c..21c29c655c33 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from datetime import datetime, timedelta
+from decimal import Decimal
from typing import TYPE_CHECKING
from uuid import UUID, uuid4
@@ -327,6 +328,7 @@ class TestScoutHarnessRunEmissionsAPI(APIBaseTest):
# Patch target: the helper is hot-imported into the view module, so patch it there, not at source.
_FETCH_REPORT_IDS = "products.signals.backend.temporal.signal_queries.fetch_report_ids_for_source_ids"
+_RUN_TOKEN_COSTS_QUERY = "products.signals.backend.scout_harness.run_costs.get_local_task_run_token_costs"
class TestScoutHarnessEmissionReportsAPI(APIBaseTest):
@@ -495,6 +497,37 @@ class TestScoutHarnessEmissionReportsBatchAPI(APIBaseTest):
assert [row["finding_id"] for row in response.json()] == ["mine"]
+class TestScoutHarnessRunTokenCostsAPI(APIBaseTest):
+ def _url(self) -> str:
+ return f"/api/projects/{self.team.id}/signals/scout/runs/token-costs/"
+
+ def test_staff_reads_the_cost_of_every_requested_run(self) -> None:
+ self.user.is_staff = True
+ self.user.save()
+ priced = _make_run(self.team)
+ unpriced = _make_run(self.team)
+ with patch(_RUN_TOKEN_COSTS_QUERY, return_value={str(priced.task_run_id): Decimal("1.25")}):
+ response = self.client.post(
+ self._url(), data={"run_ids": [str(priced.id), str(unpriced.id)]}, format="json"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["available"] is True
+ costs = {row["run_id"]: row["token_cost_usd"] for row in body["costs"]}
+ # A run with no generations attributed reports null, not 0 — the number the roster showed
+ # for every scout run while the read was keyed on the desktop `ai_product`.
+ assert costs == {str(priced.id): 1.25, str(unpriced.id): None}
+
+ def test_non_staff_is_refused(self) -> None:
+ # Fleet spend is an internal operating number, and the generations sit in a project other
+ # than the one in the path.
+ run = _make_run(self.team)
+ with patch(_RUN_TOKEN_COSTS_QUERY) as query:
+ response = self.client.post(self._url(), data={"run_ids": [str(run.id)]}, format="json")
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ query.assert_not_called()
+
+
class TestScoutHarnessRecentEmissionsAPI(APIBaseTest):
def _url(self) -> str:
return f"/api/projects/{self.team.id}/signals/scout/runs/emissions/recent/"
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index cfea38f6821b..6db4a8611e48 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3828,6 +3828,29 @@ export interface FleetFindingsSummaryApi {
latest_at: string | null
}
+/**
+ * What one scout run spent on model calls.
+ */
+export interface ScoutRunTokenCostApi {
+ /** UUID of the `SignalScoutRun` this cost belongs to. */
+ run_id: string
+ /**
+ * Model spend attributed to the run in US dollars, summed from its `$ai_generation` events. Null when no generation is attributed to the run — it failed before its first model call, or its events haven't landed yet. A run still in progress reports what it has spent so far.
+ * @nullable
+ */
+ token_cost_usd: number | null
+}
+
+/**
+ * Model spend for a batch of scout runs.
+ */
+export interface ScoutRunTokenCostsApi {
+ /** One entry per requested run that exists on this project. Runs from another project, and ids that match no run, are absent. */
+ costs: ScoutRunTokenCostApi[]
+ /** False when this deployment has no internal AI observability project to read the generations from, so `costs` is empty and every cost is unknown rather than zero. */
+ available: boolean
+}
+
/**
* `SignalScratchpad` projection used by `search-memory` and `remember`.
*/
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 1352cfc8f91d..64c4d2fa20e3 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -49,6 +49,7 @@ import type {
ScoutNoteApi,
ScoutNoteCreateRequestApi,
ScoutRunIdsBatchRequestApi,
+ ScoutRunTokenCostsApi,
ScoutSuggestionItemApi,
ScoutSuggestionRefreshApi,
ScoutSuggestionSetApi,
@@ -1359,6 +1360,27 @@ export const signalsScoutRunsRecentPerScout = async (
})
}
+export const getSignalsScoutRunsTokenCostsUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/signals/scout/runs/token-costs/`
+}
+
+/**
+ * Return what each requested `SignalScoutRun` spent on model calls, summed from the `$ai_generation` events its sandbox produced. One query for the whole batch, cached per run: a settled run's total is final, a run still in progress reports what it has spent so far. `available` is false where the internal AI observability project holding those events can't be read, so an unknown cost never reads as zero. Staff-only — fleet spend is an internal operating number, and the events sit outside the project in the path. Strictly team-scoped — run ids belonging to another project contribute no rows.
+ * @summary Get the model spend of many runs at once
+ */
+export const signalsScoutRunsTokenCosts = async (
+ projectId: string,
+ scoutRunIdsBatchRequestApi: ScoutRunIdsBatchRequestApi,
+ options?: RequestInit
+): Promise<ScoutRunTokenCostsApi> => {
+ return apiMutator<ScoutRunTokenCostsApi>(getSignalsScoutRunsTokenCostsUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(scoutRunIdsBatchRequestApi),
+ })
+}
+
export const getSignalsScoutScratchpadSearchUrl = (projectId: string, params?: SignalsScoutScratchpadSearchParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index e23aa37e621e..1b2ac55a33ea 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1427,6 +1427,25 @@ export const SignalsScoutRunsEmissionReportsBatchBody = /* @__PURE__ */ zod
"Request body for the batched emissions \/ emission-reports lookups: the set of run UUIDs to\nresolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for the\nreports lookup, one ClickHouse round-trip — per emitted run) into a single request."
)
+/**
+ * Return what each requested `SignalScoutRun` spent on model calls, summed from the `$ai_generation` events its sandbox produced. One query for the whole batch, cached per run: a settled run's total is final, a run still in progress reports what it has spent so far. `available` is false where the internal AI observability project holding those events can't be read, so an unknown cost never reads as zero. Staff-only — fleet spend is an internal operating number, and the events sit outside the project in the path. Strictly team-scoped — run ids belonging to another project contribute no rows.
+ * @summary Get the model spend of many runs at once
+ */
+export const signalsScoutRunsTokenCostsBodyRunIdsMax = 200
+
+export const SignalsScoutRunsTokenCostsBody = /* @__PURE__ */ zod
+ .object({
+ run_ids: zod
+ .array(zod.uuid())
+ .max(signalsScoutRunsTokenCostsBodyRunIdsMax)
+ .describe(
+ 'UUIDs of the `SignalScoutRun` rows to resolve in one batch. Run ids belonging to another team are silently ignored (they contribute no rows) rather than failing the whole request. Capped at 200 ids per call.'
+ ),
+ })
+ .describe(
+ "Request body for the batched emissions \/ emission-reports lookups: the set of run UUIDs to\nresolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for the\nreports lookup, one ClickHouse round-trip — per emitted run) into a single request."
+ )
+
/**
* Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place. A write carries the entry's whole state, so `expires_at` is set when passed and cleared when omitted.
* @summary Remember a scratchpad entry
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx
index 28e1a02f25d5..98a30f4add65 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx
@@ -40,7 +40,7 @@ function MetaSeparator(): JSX.Element {
*/
export function ScoutRosterCard({ row }: { row: ScoutRosterRow }): JSX.Element {
const { config, group } = row
- const { rollups, updatingScoutIds, scoutRunsLoadedOnce } = useValues(scoutFleetLogic)
+ const { rollups, updatingScoutIds, scoutRunsLoadedOnce, scoutRunCosts } = useValues(scoutFleetLogic)
const { updateScoutConfig } = useActions(scoutFleetLogic)
const { currentTeam } = useValues(teamLogic)
const now = new Date()
@@ -96,7 +96,7 @@ export function ScoutRosterCard({ row }: { row: ScoutRosterRow }): JSX.Element {
{/* A fixed strip width on wide rows keeps every row's newest run on one vertical line. */}
<div className="flex min-w-0 justify-end @lg:w-52">
{runs.length > 0 ? (
- <ScoutRunBoxes runs={runs} />
+ <ScoutRunBoxes runs={runs} costs={scoutRunCosts} />
) : (
// Until the runs request has landed once, an empty rollup means "not
// loaded", not "never ran"; the poll retries a failed load on its own.
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsx
new file mode 100644
index 000000000000..c387d241aa9f
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsx
@@ -0,0 +1,52 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render } from '@testing-library/react'
+
+import { SignalScoutRunSummary } from '../../../types'
+import { ScoutRunBoxes } from './ScoutRunBoxes'
+
+function makeRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {
+ return {
+ run_id: 'run-1',
+ skill_name: 'signals-scout-general',
+ skill_version: 1,
+ status: 'completed',
+ metadata: {},
+ created_at: '2026-07-22T01:00:00Z',
+ started_at: '2026-07-22T01:00:00Z',
+ completed_at: '2026-07-22T01:02:00Z',
+ summary: '',
+ emitted_count: 0,
+ emitted_finding_ids: [],
+ emitted_report_ids: [],
+ edited_report_ids: [],
+ ...overrides,
+ }
+}
+
+describe('ScoutRunBoxes', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('states what a run cost, and stays silent about runs with no cost', () => {
+ // The strip is the only place a person can see what one scout run spent, so a cost that
+ // reaches the logic but not the box says nothing to anyone.
+ const { container } = render(
+ <ScoutRunBoxes
+ runs={[makeRun({ run_id: 'run-priced' }), makeRun({ run_id: 'run-unpriced' })]}
+ costs={new Map([['run-priced', 4.03]])}
+ />
+ )
+
+ const labels = Array.from(container.querySelectorAll('.sr-only')).map((node) => node.textContent ?? '')
+ expect(labels.filter((label) => label.includes('$4.03'))).toHaveLength(1)
+ expect(labels.filter((label) => label.includes('$'))).toHaveLength(1)
+ })
+
+ it('leaves every run unpriced when no costs are given', () => {
+ const { container } = render(<ScoutRunBoxes runs={[makeRun()]} />)
+
+ expect(container.querySelector('.sr-only')?.textContent).not.toContain('$')
+ })
+})
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx
index f72db342c674..5c649b230aa3 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx
@@ -7,6 +7,7 @@ import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { SignalScoutRunSummary } from '../../../types'
import {
deriveRunOutcome,
+ formatRunCost,
formatRunDuration,
runDurationSeconds,
ScoutRunOutcome,
@@ -32,7 +33,7 @@ const OUTCOME_BOX_CLASS: Record<ScoutRunOutcome, string> = {
const MAX_BOXES = 24
const BOX_CLASS = 'block h-3 w-2 shrink-0 rounded-[2px] transition-transform duration-100 hover:scale-y-125'
-function runTooltip(run: SignalScoutRunSummary, now: Date): string {
+function runTooltip(run: SignalScoutRunSummary, now: Date, costUsd: number | undefined): string {
const parts = [scoutRunOutcomeLabel(run, now)]
const duration = formatRunDuration(runDurationSeconds(run, now))
if (duration) {
@@ -41,6 +42,11 @@ function runTooltip(run: SignalScoutRunSummary, now: Date): string {
if (run.started_at) {
parts.push(humanFriendlyDetailedTime(run.started_at))
}
+ // Only staff are given costs, and only for runs with model spend attributed to them, so the
+ // rest of the tooltip reads the same as before.
+ if (costUsd !== undefined) {
+ parts.push(formatRunCost(costUsd))
+ }
return parts.join(' · ')
}
@@ -58,15 +64,21 @@ function runTooltip(run: SignalScoutRunSummary, now: Date): string {
* vertical line. Left-aligning instead scatters the newest run across the column by run count,
* which is the one box a reader is scanning for.
*/
-export function ScoutRunBoxes({ runs }: { runs: SignalScoutRunSummary[] }): JSX.Element | null {
+export function ScoutRunBoxes({
+ runs,
+ costs,
+}: {
+ runs: SignalScoutRunSummary[]
+ costs?: Map<string, number>
+}): JSX.Element | null {
const visible = useMemo(() => {
const now = new Date()
return runs.slice(-MAX_BOXES).map((run) => ({
run,
outcome: deriveRunOutcome(run, now),
- tooltip: runTooltip(run, now),
+ tooltip: runTooltip(run, now, costs?.get(run.run_id)),
}))
- }, [runs])
+ }, [runs, costs])
if (runs.length === 0) {
return null
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx
index 08f2810f380a..f9db00ff03de 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx
@@ -35,7 +35,7 @@ import { ScoutStatusDot } from './ScoutStatusDot'
* nothing to say about a canonical one.
*/
export function ScoutsRosterTable({ compact }: { compact: boolean }): JSX.Element {
- const { rosterScouts, rollups, updatingScoutIds, scoutRunsLoadedOnce } = useValues(scoutFleetLogic)
+ const { rosterScouts, rollups, updatingScoutIds, scoutRunsLoadedOnce, scoutRunCosts } = useValues(scoutFleetLogic)
const { updateScoutConfig } = useActions(scoutFleetLogic)
if (rosterScouts.length === 0) {
@@ -141,7 +141,7 @@ export function ScoutsRosterTable({ compact }: { compact: boolean }): JSX.Elemen
render: (_, row: ScoutRosterRow) => {
const runs = rollups.get(row.config.skill_name)?.runs ?? []
if (runs.length) {
- return <ScoutRunBoxes runs={runs} />
+ return <ScoutRunBoxes runs={runs} costs={scoutRunCosts} />
}
// Until the runs request has landed once, an empty rollup means "not
// loaded", not "never ran"; the poll retries a failed load on its own.
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
index 966045b8033c..ab25ddabdf9c 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
@@ -1,4 +1,4 @@
-import { MOCK_DEFAULT_ORGANIZATION, MOCK_TEAM_ID } from 'lib/api.mock'
+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
@@ -8,6 +8,7 @@ import { ApiError } from 'lib/api-error'
import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
import { initKeaTests } from '~/test/init'
@@ -17,6 +18,7 @@ import {
signalsScoutConfigSync,
signalsScoutConfigUpdate,
signalsScoutRunsRecentPerScout,
+ signalsScoutRunsTokenCosts,
} from 'products/signals/frontend/generated/api'
import type { SignalScoutConfigApi, UserBasicApi } from 'products/signals/frontend/generated/api.schemas'
@@ -33,6 +35,7 @@ jest.mock('products/signals/frontend/generated/api', () => ({
signalsScoutRunsFindingsSummary: jest.fn(),
signalsScoutRunsList: jest.fn(),
signalsScoutRunsRecentPerScout: jest.fn(),
+ signalsScoutRunsTokenCosts: jest.fn(),
}))
const mockSignalsScoutChatTasksCreate = signalsScoutChatTasksCreate as jest.MockedFunction<
@@ -44,6 +47,9 @@ const mockSignalsScoutConfigUpdate = signalsScoutConfigUpdate as jest.MockedFunc
const mockSignalsScoutRunsRecentPerScout = signalsScoutRunsRecentPerScout as jest.MockedFunction<
typeof signalsScoutRunsRecentPerScout
>
+const mockSignalsScoutRunsTokenCosts = signalsScoutRunsTokenCosts as jest.MockedFunction<
+ typeof signalsScoutRunsTokenCosts
+>
const BASE_CONFIG: SignalScoutConfigApi = {
id: 'config-1',
@@ -124,6 +130,7 @@ describe('scoutFleetLogic', () => {
mockSignalsScoutConfigSync.mockReset().mockResolvedValue([])
mockSignalsScoutConfigUpdate.mockReset()
mockSignalsScoutRunsRecentPerScout.mockReset().mockResolvedValue([])
+ mockSignalsScoutRunsTokenCosts.mockReset().mockResolvedValue({ costs: [], available: true })
logic = scoutFleetLogic()
logic.mount()
await expectLogic(logic).toFinishAllListeners()
@@ -824,4 +831,132 @@ describe('scoutFleetLogic', () => {
)
})
})
+ describe('staff-only run costs', () => {
+ const mountAsStaff = async (isStaff: boolean): Promise<void> => {
+ logic.unmount()
+ userLogic.mount()
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_staff: isStaff })
+ logic = scoutFleetLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ it('annotates staff runs with the cost of the runs that have spend attributed', async () => {
+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue([
+ makeRun({ run_id: 'run-priced' }),
+ makeRun({ run_id: 'run-unpriced' }),
+ ])
+ mockSignalsScoutRunsTokenCosts.mockResolvedValue({
+ costs: [
+ { run_id: 'run-priced', token_cost_usd: 4.03 },
+ // A run with nothing attributed is dropped, so its tooltip says nothing about
+ // cost rather than claiming the run was free.
+ { run_id: 'run-unpriced', token_cost_usd: null },
+ ],
+ available: true,
+ })
+ await mountAsStaff(true)
+
+ logic.actions.loadScoutRuns()
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])
+
+ expect(mockSignalsScoutRunsTokenCosts).toHaveBeenCalledWith(String(MOCK_TEAM_ID), {
+ run_ids: ['run-priced', 'run-unpriced'],
+ })
+ expect(logic.values.scoutRunCosts.get('run-priced')).toBe(4.03)
+ expect(logic.values.scoutRunCosts.has('run-unpriced')).toBe(false)
+ })
+
+ it('keeps the cost map when a poll re-derives the same numbers, and replaces it when one moves', async () => {
+ // Every roster card subscribes to this map and ScoutRunBoxes keys its tooltip memo on it,
+ // so a fresh map each poll re-renders the whole roster for nothing. Reusing it too
+ // eagerly is the worse failure though: the roster would show a frozen cost forever.
+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])
+ mockSignalsScoutRunsTokenCosts.mockResolvedValue({
+ costs: [{ run_id: 'run-priced', token_cost_usd: 4.03 }],
+ available: true,
+ })
+ await mountAsStaff(true)
+
+ logic.actions.loadScoutRuns()
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])
+ const first = logic.values.scoutRunCosts
+ expect(first.get('run-priced')).toBe(4.03)
+
+ logic.actions.loadScoutRuns()
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])
+ expect(logic.values.scoutRunCosts).toBe(first)
+
+ mockSignalsScoutRunsTokenCosts.mockResolvedValue({
+ costs: [{ run_id: 'run-priced', token_cost_usd: 5.11 }],
+ available: true,
+ })
+ logic.actions.loadScoutRuns()
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])
+ expect(logic.values.scoutRunCosts).not.toBe(first)
+ expect(logic.values.scoutRunCosts.get('run-priced')).toBe(5.11)
+ })
+
+ it('sends no further batches once the deployment reports it cannot price runs', async () => {
+ // `available: false` is the same answer for every batch, and each one costs the backend
+ // a run-row read and a traceback, so asking again buys nothing.
+ const runIds = Array.from({ length: 201 }, (_, index) => `run-${index}`)
+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue(runIds.map((run_id) => makeRun({ run_id })))
+ mockSignalsScoutRunsTokenCosts.mockResolvedValue({ costs: [], available: false })
+ await mountAsStaff(true)
+
+ logic.actions.loadScoutRuns()
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])
+
+ expect(mockSignalsScoutRunsTokenCosts).toHaveBeenCalledTimes(1)
+ expect(logic.values.scoutRunCosts.size).toBe(0)
+ })
+
+ it('keeps the batches that answered when a later batch fails', async () => {
+ // A materialized fleet is more run ids than one request carries, so the loader sends
+ // several. Discarding the whole load over one failed batch blanks every tooltip in the
+ // roster instead of only the runs that batch was pricing.
+ const runIds = Array.from({ length: 201 }, (_, index) => `run-${index}`)
+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue(runIds.map((run_id) => makeRun({ run_id })))
+ mockSignalsScoutRunsTokenCosts.mockImplementation(async (_projectId, body) => {
+ if (!body.run_ids.includes('run-0')) {
+ throw new ApiError('nope', 500)
+ }
+ return { costs: [{ run_id: 'run-0', token_cost_usd: 4.03 }], available: true }
+ })
+ await mountAsStaff(true)
+
+ logic.actions.loadScoutRuns()
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])
+
+ expect(logic.values.scoutRunCosts.get('run-0')).toBe(4.03)
+ })
+
+ // Recovering in the loader skips the gate `initKea` applies to loader failures, so the
+ // loader reapplies it. A backend fault must still leave a client-side exception behind, and
+ // a gateway blip must not, since filing those buries the crashes worth seeing.
+ it.each([
+ ['a backend fault, which reaches error tracking', 500, true],
+ ['a gateway blip, which does not', 503, false],
+ ])('recovers from %s', async (_name: string, status: number, reported: boolean) => {
+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])
+ mockSignalsScoutRunsTokenCosts.mockRejectedValue(new ApiError('nope', status))
+ await mountAsStaff(true)
+
+ logic.actions.loadScoutRuns()
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])
+
+ expect(jest.mocked(posthog.captureException).mock.calls.length > 0).toBe(reported)
+ })
+
+ it('never asks for costs on behalf of a non-staff user', async () => {
+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])
+ await mountAsStaff(false)
+
+ logic.actions.loadScoutRuns()
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess']).toFinishAllListeners()
+
+ expect(mockSignalsScoutRunsTokenCosts).not.toHaveBeenCalled()
+ })
+ })
})
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
index 015913face58..06badf0fed5a 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
@@ -12,15 +12,17 @@ import {
} from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
-import { ApiError } from 'lib/api-error'
+import { ApiError, shouldReportApiFailure } from 'lib/api-error'
import { dayjs } from 'lib/dayjs'
import { reconcileById } from 'lib/utils/objects'
import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
import {
signalsScoutChatTasksCreate,
@@ -33,6 +35,7 @@ import {
signalsScoutRunsFindingsSummary,
signalsScoutRunsList,
signalsScoutRunsRecentPerScout,
+ signalsScoutRunsTokenCosts,
} from 'products/signals/frontend/generated/api'
import type {
FleetFindingsSummaryApi,
@@ -120,6 +123,9 @@ const RUNS_REFETCH_INTERVAL_MS = 60_000
// `loadScoutRuns` gets each scout's last N runs from one ranked query.
const RUNS_PAGE_LIMIT = 100
const MAX_RUNS_PAGES = 15
+// The cost endpoint takes run ids in batches (`SCOUT_RUNS_BATCH_LIMIT` server-side), and a fleet
+// holds more runs than one batch, so the roster's runs are sent a batch at a time.
+const RUN_COST_BATCH_LIMIT = 200
// Roster filter state also lives in the URL so a filtered view survives a refresh and is shareable.
// The search param is written on this debounce, so typing does not rewrite the URL per keystroke.
@@ -203,6 +209,21 @@ function sameTags(a: string[], b: string[]): boolean {
return a.length === b.length && a.every((tag, index) => tag === b[index])
}
+// Keep the cost map reference-stable when a poll re-derives the same numbers, the way
+// `reconcileById` does for the polled lists. A settled run's total is cached for an hour, so an
+// unchanged poll is the normal case, and every roster card subscribes to this map.
+function reuseCostsIfUnchanged(previous: Map<string, number>, next: Map<string, number>): Map<string, number> {
+ if (previous.size !== next.size) {
+ return next
+ }
+ for (const [runId, cost] of next) {
+ if (previous.get(runId) !== cost) {
+ return next
+ }
+ }
+ return previous
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutFleetLogicValues {
dataProcessingAccepted: boolean // aiConsentLogic
@@ -225,6 +246,7 @@ export interface scoutFleetLogicValues {
fleetFindingsSummaryLoadedOnce: boolean
fleetFindingsSummaryLoading: boolean
fleetSummary: FleetSummary | null
+ isStaff: boolean
lastRunAt: string | null
manualRunScoutIds: string[]
pauseAttentionCounts: {
@@ -253,6 +275,8 @@ export interface scoutFleetLogicValues {
scoutMetadataLoading: boolean
scoutOwnerOptions: ScoutOwnerOption[]
scoutRosterSort: ScoutRosterSort
+ scoutRunCosts: Map<string, number>
+ scoutRunCostsLoading: boolean
scoutRuns: SignalScoutRunSummary[]
scoutRunsLoadedOnce: boolean
scoutRunsLoading: boolean
@@ -352,6 +376,21 @@ export interface scoutFleetLogicActions {
scoutMetadata: ScoutMetadataApi | null
payload?: any
}
+ loadScoutRunCosts: (_: void) => void
+ loadScoutRunCostsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadScoutRunCostsSuccess: (
+ scoutRunCosts: Map<string, number>,
+ payload?: void
+ ) => {
+ scoutRunCosts: Map<string, number>
+ payload?: void
+ }
loadScoutRuns: (_: void) => void
loadScoutRunsFailure: (
error: string,
@@ -472,6 +511,7 @@ export interface scoutFleetLogicMeta {
dataProcessingApprovalDisabledReason: string | null
) => string | null
rollups: (scoutRuns: SignalScoutRunSummary[]) => Map<string, ScoutRollup>
+ isStaff: (user: null | import('~/types').UserType) => boolean
fleetSummary: (
scoutConfigs: SignalScoutConfigApi[] | null,
rollups: Map<string, ScoutRollup>
@@ -706,6 +746,63 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
},
},
],
+ // Per-run model spend, staff only. The roster's own runs are the batch: one request per
+ // `RUN_COST_BATCH_LIMIT` ids, and the endpoint caches a settled run's total, so a poll over
+ // an unchanged fleet costs cache reads rather than a query per run. Runs with nothing
+ // attributed are dropped rather than stored as 0 — the tooltip then says nothing about
+ // cost, instead of claiming the run was free.
+ scoutRunCosts: [
+ new Map<string, number>(),
+ {
+ loadScoutRunCosts: async (_: void, breakpoint) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId || !values.isStaff || values.scoutRuns.length === 0) {
+ return values.scoutRunCosts
+ }
+ const runIds = values.scoutRuns.map((run) => run.run_id)
+ const costs = new Map<string, number>()
+ try {
+ for (let start = 0; start < runIds.length; start += RUN_COST_BATCH_LIMIT) {
+ const response = await signalsScoutRunsTokenCosts(String(teamId), {
+ run_ids: runIds.slice(start, start + RUN_COST_BATCH_LIMIT),
+ })
+ breakpoint()
+ // This deployment has no internal project to price runs against, so the
+ // remaining batches would answer the same way and each one costs the
+ // backend a run-row read and a traceback. Every cost stays unknown.
+ if (!response.available) {
+ break
+ }
+ for (const cost of response.costs) {
+ if (cost.token_cost_usd !== null) {
+ costs.set(cost.run_id, cost.token_cost_usd)
+ }
+ }
+ }
+ } catch (error) {
+ // Cost is a staff-only annotation on a tooltip, so a blip degrades to no
+ // number rather than reporting a failure the reader can do nothing about.
+ if (error instanceof ApiError) {
+ // Recovering here skips the gate `initKea` applies to loader failures, so
+ // reapply it: a refused or unreachable read is expected, but a backend
+ // fault must still reach error tracking instead of reading as success.
+ if (shouldReportApiFailure(error)) {
+ posthog.captureException(error)
+ }
+ // A full fleet spans several batches, so keep the ones that answered and
+ // leave the rest on their last known number. Dropping the whole load
+ // would blank every tooltip over one failed batch.
+ return reuseCostsIfUnchanged(
+ values.scoutRunCosts,
+ new Map([...values.scoutRunCosts, ...costs])
+ )
+ }
+ throw error
+ }
+ return reuseCostsIfUnchanged(values.scoutRunCosts, costs)
+ },
+ },
+ ],
runsWindow: [
{ runs: [] as SignalScoutRunSummary[], complete: true } as {
runs: SignalScoutRunSummary[]
@@ -928,6 +1025,10 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
(s) => [s.scoutRuns],
(scoutRuns: SignalScoutRunSummary[]): Map<string, ScoutRollup> => computeScoutRollups(scoutRuns),
],
+ isStaff: [
+ () => [userLogic.selectors.user],
+ (user: null | import('~/types').UserType): boolean => user?.is_staff ?? false,
+ ],
fleetSummary: [
(s) => [s.scoutConfigs, s.rollups],
(scoutConfigs: SignalScoutConfig[] | null, rollups: Map<string, ScoutRollup>): FleetSummary | null =>
@@ -1123,6 +1224,11 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
listeners(({ actions, values, cache, sharedListeners }) => ({
loadScoutRunsSuccess: () => {
+ // Costs follow the runs rather than a poll of their own, so a run and its cost are
+ // never a cycle apart.
+ if (values.isStaff) {
+ actions.loadScoutRunCosts()
+ }
const evaluatedAt = new Date(values.rosterEvaluatedAt)
const now = new Date()
const groupChanged = (values.scoutConfigs ?? []).some((config) => {
diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts
index f934064eab04..36c4f37736da 100644
--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts
+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts
@@ -5,6 +5,7 @@ import {
computeFleetSummary,
computeScoutRollups,
deriveRunOutcome,
+ formatRunCost,
mostRecentEmittedRuns,
runMatchesFilter,
dayTimeToWeeklyCron,
@@ -57,6 +58,18 @@ describe('scoutRunsWindow report channel', () => {
})
})
+ describe('formatRunCost', () => {
+ // A cheap run still cost something, and "$0.00" is exactly the number this readout exists
+ // to replace, so anything under a cent gets the digits to show it.
+ it.each<[number, string]>([
+ [4.0327, '$4.03'],
+ [0.0042, '$0.0042'],
+ [0, '$0.00'],
+ ])('%s → %s', (cost, expected) => {
+ expect(formatRunCost(cost)).toEqual(expected)
+ })
+ })
+
describe('runMatchesFilter', () => {
it('keeps a report-authoring run out of Quiet and inside Emitted', () => {
const run = makeRun({ emitted_report_ids: ['r-1'] })
diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
index cece1e9de228..97e277a7d34a 100644
--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
@@ -6,6 +6,7 @@
// the runs endpoint's `date_to` cursor past its 100-row page cap).
import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
import { pluralize } from 'lib/utils/strings'
import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
@@ -145,6 +146,14 @@ export function formatRunDuration(seconds: number | null): string {
return humanFriendlyDuration(seconds, { maxUnits: 2 })
}
+/**
+ * What a run spent on model calls. A run costing less than a cent gets more digits, since at two
+ * decimals it would read as "$0.00", which says the run was free.
+ */
+export function formatRunCost(costUsd: number): string {
+ return humanFriendlyCurrency(costUsd, costUsd > 0 && costUsd < 0.01 ? 4 : 2)
+}
+
/**
* Scout runs are hard-killed at the ~31-minute Temporal activity deadline and
* surface as bare "failed" with no error field. Until the serializer carries a
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 81b225670aeb..e07ab6acf845 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -1165,6 +1165,9 @@ tools:
description:
'DEPRECATED: renamed to scout-runs-retrieve. This alias forwards to the same endpoint and will be removed.
Call scout-runs-retrieve directly with the same arguments.'
+ signals-scout-runs-token-costs:
+ operation: signals_scout_runs_token_costs
+ enabled: false
signals-scout-scratchpad-forget:
operation: signals_scout_scratchpad_forget
enabled: true
diff --git a/products/tasks/backend/facade/billing.py b/products/tasks/backend/facade/billing.py
index 2ad4cad813e1..e12f40d827e3 100644
--- a/products/tasks/backend/facade/billing.py
+++ b/products/tasks/backend/facade/billing.py
@@ -16,6 +16,7 @@ from products.tasks.backend.logic.services.task_usage import (
TASK_USAGE_TIMESTAMP_HEADER,
TaskTokenUsageUnavailable,
TaskUsage,
+ get_local_task_run_token_costs,
get_local_task_token_cost,
get_task_usage,
)
@@ -29,6 +30,7 @@ __all__ = [
"TASK_USAGE_SIGNATURE_HEADER",
"TASK_USAGE_TIMESTAMP_HEADER",
"get_billable_sandbox_compute_usage_by_team",
+ "get_local_task_run_token_costs",
"get_local_task_token_cost",
"get_task_sandbox_usage_by_team",
"get_task_usage",
diff --git a/products/tasks/backend/logic/services/task_usage.py b/products/tasks/backend/logic/services/task_usage.py
index a1c663d0dee5..c4a6f580f6c6 100644
--- a/products/tasks/backend/logic/services/task_usage.py
+++ b/products/tasks/backend/logic/services/task_usage.py
@@ -2,6 +2,7 @@ import hmac
import json
import time
import hashlib
+from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
@@ -122,6 +123,30 @@ def _get_cross_region_task_token_cost(*, team_id: int, task_id: UUID, task_creat
raise TaskTokenUsageUnavailable("Cross-region task usage is unavailable") from error
+# The internal project the gateways capture `$ai_generation` into is region-local: each region's
+# generations land in that region's own project. Same mapping AI credit billing reads
+# (`CLOUD_REGION_TO_TEAM_ID` in `posthog/tasks/usage_report.py`), kept separately because that
+# module imports this product's facade. `LLM_ANALYTICS_INTERNAL_TEAM_ID` is 2 in every region, so
+# it can't answer this on its own — it stays the fallback for a deployment that isn't US or EU.
+INTERNAL_LLM_ANALYTICS_TEAM_ID_BY_REGION = {"EU": 1, "US": 2}
+
+
+def _internal_llm_analytics_team() -> Team:
+ """The project this region's `$ai_generation` events are captured into.
+
+ A deployment with no such project has nothing to read, and callers must surface that as
+ unknown rather than as zero spend.
+ """
+ team_id = INTERNAL_LLM_ANALYTICS_TEAM_ID_BY_REGION.get(
+ settings.CLOUD_DEPLOYMENT or "", settings.LLM_ANALYTICS_INTERNAL_TEAM_ID
+ )
+ try:
+ return Team.objects.get(pk=team_id)
+ except Team.DoesNotExist as error:
+ logger.exception("task_usage.internal_llm_analytics_team_missing", team_id=team_id)
+ raise TaskTokenUsageUnavailable("The internal AI observability project is not readable here") from error
+
+
def get_local_task_token_cost(*, team_id: int, task_id: UUID, task_created_at: datetime) -> Decimal:
query = parse_select(
"""
@@ -145,13 +170,68 @@ def get_local_task_token_cost(*, team_id: int, task_id: UUID, task_created_at: d
"team_id": ast.Constant(value=str(team_id)),
"task_id": ast.Constant(value=str(task_id)),
},
- team=Team.objects.get(pk=settings.LLM_ANALYTICS_INTERNAL_TEAM_ID),
+ team=_internal_llm_analytics_team(),
query_type="TaskUsageTokenCost",
)
value = (result.results or [(0,)])[0][0]
return Decimal(str(value or 0))
+def get_local_task_run_token_costs(
+ *,
+ team_id: int,
+ origin_product: str,
+ task_run_ids: Sequence[UUID],
+ generated_after: datetime,
+ product: Product,
+) -> dict[str, Decimal]:
+ """Model spend per task run, for every run in `task_run_ids` that has any attributed to it.
+
+ Keyed on `task_origin_product` rather than `ai_product`, because `ai_product` names the agent
+ that made the generation, not the product the run belongs to: one origin product spans several
+ `ai_product` values (a signal report reports a different one per pipeline stage), and one
+ `ai_product` spans several origin products. A run with no attributed generation is absent from
+ the result rather than priced at zero, so a caller can tell it from a run that really spent
+ nothing. A run whose generations all lack `$ai_total_cost_usd` is absent for the same reason:
+ the property is written only where a cost could be calculated, so the sum is null and the spend
+ is unknown, not zero. A run priced in part still reports the sum of what was priced, which is a
+ lower bound.
+ """
+ if not task_run_ids:
+ return {}
+
+ query = parse_select(
+ """
+ SELECT toString(properties.task_run_id) AS task_run_id,
+ round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS token_cost_usd
+ FROM events
+ WHERE equals(event, '$ai_generation')
+ AND greaterOrEquals(timestamp, {generated_after})
+ AND equals(properties.task_origin_product, {origin_product})
+ AND equals(toString(properties.team_id), {team_id})
+ AND in(toString(properties.task_run_id), {task_run_ids})
+ GROUP BY task_run_id
+ LIMIT {row_limit}
+ """
+ )
+ with tags_context(product=product, feature=Feature.QUERY):
+ result = execute_hogql_query(
+ query=query,
+ placeholders={
+ "generated_after": ast.Constant(value=generated_after),
+ "origin_product": ast.Constant(value=origin_product),
+ "team_id": ast.Constant(value=str(team_id)),
+ "task_run_ids": ast.Constant(value=[str(task_run_id) for task_run_id in task_run_ids]),
+ # The group-by yields at most one row per requested run, but a limit-less select
+ # is capped at 100 rows, and a caller may ask about more runs than that.
+ "row_limit": ast.Constant(value=len(task_run_ids)),
+ },
+ team=_internal_llm_analytics_team(),
+ query_type="TaskRunUsageTokenCost",
+ )
+ return {str(row[0]): Decimal(str(row[1])) for row in (result.results or []) if row[0] and row[1] is not None}
+
+
def _get_task_compute_cost(*, team_id: int, task_id: UUID) -> Decimal:
if not COMPUTE_RATE_CARDS:
return Decimal(0)
diff --git a/products/tasks/backend/logic/services/tests/test_task_usage.py b/products/tasks/backend/logic/services/tests/test_task_usage.py
index b2cc4a5e1c7d..6fe877a5201e 100644
--- a/products/tasks/backend/logic/services/tests/test_task_usage.py
+++ b/products/tasks/backend/logic/services/tests/test_task_usage.py
@@ -10,6 +10,8 @@ from unittest.mock import patch
from django.core.cache import cache
from django.test import SimpleTestCase
+from parameterized import parameterized
+
from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags
from products.tasks.backend.logic.services import task_usage
@@ -40,6 +42,26 @@ class TestTaskUsageQueryTagging(SimpleTestCase):
assert captured_tags == {"product": Product.POSTHOG_CODE, "feature": Feature.QUERY}
+ @parameterized.expand([("US", 2), ("EU", 1)])
+ def test_costs_are_read_from_the_regions_own_internal_project(self, region: str, expected_team_id: int) -> None:
+ # A region's generations are captured into the internal project in that same region, and
+ # `LLM_ANALYTICS_INTERNAL_TEAM_ID` is 2 in both — reading it in the EU would price every EU
+ # run at zero.
+ with (
+ self.settings(CLOUD_DEPLOYMENT=region, LLM_ANALYTICS_INTERNAL_TEAM_ID=2),
+ patch.object(task_usage.Team.objects, "get", return_value=object()) as team_get,
+ patch.object(task_usage, "execute_hogql_query", return_value=SimpleNamespace(results=[])),
+ ):
+ task_usage.get_local_task_run_token_costs(
+ team_id=1,
+ origin_product="signals_scout",
+ task_run_ids=[UUID("00000000-0000-0000-0000-000000000001")],
+ generated_after=datetime(2026, 8, 1, tzinfo=UTC),
+ product=Product.SIGNALS,
+ )
+
+ assert team_get.call_args.kwargs["pk"] == expected_team_id
+
class TestTaskUsage(ClickhouseTestMixin, APIBaseTest):
def setUp(self) -> None:
@@ -86,6 +108,112 @@ class TestTaskUsage(ClickhouseTestMixin, APIBaseTest):
assert usage.compute_cost_usd == 0
assert usage.total_cost_usd == Decimal("2.5")
+ def test_run_token_costs_group_by_run_and_key_on_the_origin_product(self) -> None:
+ # `ai_product` can't stand in for `task_origin_product`: a scout run reports
+ # `ai_product = 'signals_scout'`, so the desktop read's `posthog_code` filter matched none
+ # of them and priced every scout run at zero. Group by run, filter on the origin, and keep
+ # another product's, another team's, and another run's generations out of the total.
+ priced_run = "11111111-1111-1111-1111-111111111111"
+ second_run = "22222222-2222-2222-2222-222222222222"
+ unattributed_run = "33333333-3333-3333-3333-333333333333"
+ for team_id, task_run_id, origin_product, cost in (
+ (self.team.id, priced_run, "signals_scout", 2.5),
+ (self.team.id, priced_run, "signals_scout", 1),
+ (self.team.id, second_run, "signals_scout", 4),
+ (self.team.id, priced_run, "user_created", 10),
+ (self.team.id + 1, priced_run, "signals_scout", 40),
+ ):
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id=str(self.user.distinct_id),
+ timestamp=self.task.created_at + timedelta(seconds=1),
+ properties={
+ "team_id": team_id,
+ "task_run_id": task_run_id,
+ "task_origin_product": origin_product,
+ "$ai_total_cost_usd": cost,
+ },
+ )
+ flush_persons_and_events()
+
+ with self.settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id):
+ costs = task_usage.get_local_task_run_token_costs(
+ team_id=self.team.id,
+ origin_product="signals_scout",
+ task_run_ids=[UUID(priced_run), UUID(second_run), UUID(unattributed_run)],
+ generated_after=self.task.created_at,
+ product=Product.SIGNALS,
+ )
+
+ # The run with no generations of its own is absent rather than priced at zero, so a caller
+ # can tell it from a run that really spent nothing.
+ assert costs == {priced_run: Decimal("3.5"), second_run: Decimal("4")}
+
+ def test_run_token_costs_price_a_full_batch_rather_than_the_default_row_limit(self) -> None:
+ # `execute_hogql_query` caps a limit-less select at 100 rows, but the endpoint takes 200 run
+ # ids per call. Without an explicit limit the runs past the hundredth read as unattributed.
+ run_ids = [UUID(int=index + 1) for index in range(101)]
+ for run_id in run_ids:
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id=str(self.user.distinct_id),
+ timestamp=self.task.created_at + timedelta(seconds=1),
+ properties={
+ "team_id": self.team.id,
+ "task_run_id": str(run_id),
+ "task_origin_product": "signals_scout",
+ "$ai_total_cost_usd": 1,
+ },
+ )
+ flush_persons_and_events()
+
+ with self.settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id):
+ costs = task_usage.get_local_task_run_token_costs(
+ team_id=self.team.id,
+ origin_product="signals_scout",
+ task_run_ids=run_ids,
+ generated_after=self.task.created_at,
+ product=Product.SIGNALS,
+ )
+
+ assert len(costs) == len(run_ids)
+
+ def test_run_token_costs_omit_a_run_whose_generations_carry_no_cost(self) -> None:
+ # `$ai_total_cost_usd` is only written where a cost could be calculated, so a run made
+ # entirely of unpriced generations sums to null. Reporting that as 0 would tell staff the
+ # run was free, which is the one thing the caller must be able to rule out.
+ priced_run = "44444444-4444-4444-4444-444444444444"
+ unpriced_run = "55555555-5555-5555-5555-555555555555"
+ for task_run_id, cost in ((priced_run, 1.25), (unpriced_run, None), (unpriced_run, None)):
+ properties: dict[str, object] = {
+ "team_id": self.team.id,
+ "task_run_id": task_run_id,
+ "task_origin_product": "signals_scout",
+ }
+ if cost is not None:
+ properties["$ai_total_cost_usd"] = cost
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id=str(self.user.distinct_id),
+ timestamp=self.task.created_at + timedelta(seconds=1),
+ properties=properties,
+ )
+ flush_persons_and_events()
+
+ with self.settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id):
+ costs = task_usage.get_local_task_run_token_costs(
+ team_id=self.team.id,
+ origin_product="signals_scout",
+ task_run_ids=[UUID(priced_run), UUID(unpriced_run)],
+ generated_after=self.task.created_at,
+ product=Product.SIGNALS,
+ )
+
+ assert costs == {priced_run: Decimal("1.25")}
+
def test_compute_cost_only_includes_billable_desktop_sessions(self) -> None:
rate_start = datetime(2026, 8, 1, tzinfo=UTC)
rate_card = ComputeRateCard(
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2f38033d4816..7e0ba56c9b14 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -77021,6 +77021,29 @@ export namespace Schemas {
run_ids: string[];
}
+ /**
+ * What one scout run spent on model calls.
+ */
+ export interface ScoutRunTokenCost {
+ /** UUID of the `SignalScoutRun` this cost belongs to. */
+ run_id: string;
+ /**
+ * Model spend attributed to the run in US dollars, summed from its `$ai_generation` events. Null when no generation is attributed to the run — it failed before its first model call, or its events haven't landed yet. A run still in progress reports what it has spent so far.
+ * @nullable
+ */
+ token_cost_usd: number | null;
+ }
+
+ /**
+ * Model spend for a batch of scout runs.
+ */
+ export interface ScoutRunTokenCosts {
+ /** One entry per requested run that exists on this project. Runs from another project, and ids that match no run, are absent. */
+ costs: ScoutRunTokenCost[];
+ /** False when this deployment has no internal AI observability project to read the generations from, so `costs` is empty and every cost is unknown rather than zero. */
+ available: boolean;
+ }
+
export interface ScoutSuggestionProposedConfig {
/**
* Suggested five-field cron schedule in the project timezone, or null for an interval.