: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
chore(signals): remove staff-only scout costs (#127622)
Andrew Maguireb291543cc7ed
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 42a50901269f..585cbf560cac 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -12759,25 +12759,21 @@ snapshots:scenes-app-inbox-scoutdetailview--scout-page--light:hash: v1.k794b7964.38853040ce8d5daacd23f3fa3705bc5b713f25b9a3c865bf1b77f94613813ca3.9SNuf8gxuxm3lJOHX2RHMgyU38143eiAkjS4skfXZQUscenes-app-inbox-scoutdetailview--scout-page-narrow-run-history--dark:- hash: v1.k794b7964.cd74619e7ed6b96f08e12783eafba48cf28478049f486b1c11c28e1e7d26d0e4.MxU1wyjdZ9w-r7aRp1KUsHNGNIwfzsJ6T30hBtLxHzw+ hash: v1.k794b7964.d052114d18a54dd39f59750f5ebe3dc6f711bfa643c8fc43b713faa66b5caa87.LDy2XTRTffyHIArmrfFrAzfuaxfXSl-UY2T85q-rkHIscenes-app-inbox-scoutdetailview--scout-page-narrow-run-history--light:- hash: v1.k794b7964.0630377060dbbcc5b0dfca8750b88df86088b4a26872b52683cd005d6e4d5ee4.4H9HNihF5kGdUubZZVkRmgcKzsm6pXwjP-bJ2Y7VqSA+ hash: v1.k794b7964.3e9ff173da114d82299b5b8dae70166707b38b48425134b88fdf8300f349c1a4.6T4Axb1KxkD8x7xM7vesudfneM8gfrsNtgNz4xrLd7Qscenes-app-inbox-scoutdetailview--scout-page-no-reports--dark:hash: v1.k794b7964.93ae979dddb80c5efc36b79b3f32520410b9e5aacb49190bd8bce892a5041ae7.ElR4R2uy_RK5YYbQBTMPRTWu_jWUc64DCGcRy_5gp9Ascenes-app-inbox-scoutdetailview--scout-page-no-reports--light:hash: v1.k794b7964.bf4ecca30f13c3c2b8cc36fa3019a19e22c42a88ee94f77f50599d19a99e648d.W6zbj9_SnRrz1TWBGotZLemo000iYsSJnE6m8mTsXsc- scenes-app-inbox-scoutdetailview--scout-page-non-staff--dark:- hash: v1.k794b7964.9b96e6f1be1795608a4291d7f7f96e9bc7ba3cfcb1808c42dd00808721a97ce7.dcePYQ9Ryjxs2sjbrs9VK2NusiiKEMxymfo9vfoQ_ZU- scenes-app-inbox-scoutdetailview--scout-page-non-staff--light:- hash: v1.k794b7964.99cb124c9205bf56dc3ee16ba35cebb6d0c3d32f22066c663ad1fe249ee65304.w6PLdtozCHRwebxj1qmc5qW-5olaXuIs8I4fV1Dp8r0scenes-app-inbox-scoutdetailview--scout-page-trials--dark:hash: v1.k794b7964.52eeb7b3afc8610d1694827cfcb426cda2020373837006e759eb5ec63e49747d.qCanqI0__u7ATyzZyHwBGdQfNGkf17tjOqupP8iUHdgscenes-app-inbox-scoutdetailview--scout-page-trials--light:hash: v1.k794b7964.5946d40e9188aa3aa83d55de1aacec69e9b14b1f129fdbf34fb88eeeec5d0e19.y8gMya_TLfhafRqmrhfK-0gjf6iku4w8RLJwYuay6csscenes-app-inbox-scoutdetailview--scout-page-trials-narrow--dark:- hash: v1.k794b7964.e87148d6e9c7bf4ab1eadd958d709fd0383e9ac603097166b73987cdfbbc6d16.fIJ-jRh34SvxC-IXvZs_CvLfqurWXQu5bErnZa0NsCc+ hash: v1.k794b7964.1d9847498bfc501597a079efa222f8008ed43223d0c259bf795be66275711f0d.hgLuSF6uOscZWYby-hqwLFSh3gZJgv2EYckEB6nmm3kscenes-app-inbox-scoutdetailview--scout-page-trials-narrow--light:- hash: v1.k794b7964.76a8f07bd0691c5c2358626e19a57ce4335186d3eb5ab2f03be6e46e7d5651fb.jREnparZoFM-Pp0MGzKuKmSH1rFoHtldUEYTNtzP9xE+ hash: v1.k794b7964.680f9e9012e6182841e21ddc4455017b02f92049c0e5c9532ca10164a7fe2149.FF6ATPeLRGmsb1HLiEOoIdWOCDDiZLoTsZq9KWmMqBYscenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--dark:hash: v1.k794b7964.afe2203f4dd53373a3203fcfa611b5b65555341bdc2fc7fd73c15c2d83914600.O4kSRnOgICuQDkyD2HJCwBXdzE-KwsfzWT98nm43_5Ascenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--light:@@ -12890,14 +12886,6 @@ snapshots:hash: v1.k794b7964.1fa499f9b82d53b5303ac9c1aad41ae71c3181773bfebff8484f9aac6a5d7ad5.c9CzmU_NYRff7RF85AjHkQMh2xHZSlQNuLU0fF3-Utoscenes-app-inbox-scoutsroster--roster--light:hash: v1.k794b7964.9641b33b8a0ebdb5f80a54278c0fb1328904398cf933ee06bfa4ccf58eb00415.2jp3o2jztnpwRlJ3x9o_KtVLLiGu42UoAmE71dud5go- scenes-app-inbox-scoutsroster--roster-costs--dark:- hash: v1.k794b7964.beeccb8195997c1c1877f549c6b6902b9b69cb1d9c720940ab7f5968f0335a71.1Jm1H94ElUbRIL-n5q9IJY-TmEDzSzxPqAms52-08F4- scenes-app-inbox-scoutsroster--roster-costs--light:- hash: v1.k794b7964.75d202bfe5d3ed9019278d4a9730bfd7e1c9ccda3b7358eb167472499b65445b.Hz5OA1f_5_lQmDuCNFUw-HWUbfnWNyN5qfnvGPevHcU- scenes-app-inbox-scoutsroster--roster-costs-non-staff--dark:- hash: v1.k794b7964.bc5496dd845ecda6f0ad12cfb26aef001eebb616144626a43170c8a67febd43b.JldNfdDLfUnEixxUwEc-HN7yzxRYqQesLQWPuf0gLrk- scenes-app-inbox-scoutsroster--roster-costs-non-staff--light:- hash: v1.k794b7964.ed67ad70f3fa88f0a8ec479cb91870ad1d9baab13bb4be71428c960c391bf0db.kS-qICwDGcauBM7y48IGpq2cxtE4M9qmalLa716nJN4scenes-app-inbox-scoutsuggestionsstrip--collapsed--dark:hash: v1.k794b7964.83c1649fea741bc937ef2be603c9bd7aabea26f78022b8accb37de85733e55d4.7qehj5PgTiUvxt50V7ALqkOG7HkNXYnaFg5yddoGaposcenes-app-inbox-scoutsuggestionsstrip--collapsed--light:diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 01a66ab79f4e..3cf75f2cb699 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -113,14 +113,6 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick eComputes 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`, `has_structured_output`, `has_not_in_use_closeout`). 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 both follow-up mechanisms: a report check the run's task created or recorded a verdict on, or the run window against the skill-namespaced `followup:` scratchpad keys, since working that queue means writing to it. Creating a check counts where creating a queue entry does not, because a check is the validation being scheduled rather than a note asking a future run to do it. The field name stays put while scouts move from the queue onto checks, so dashboards built on it keep meaning "a run that checked whether a past fix held".`has_not_in_use_closeout` cannot read the run window, because `not-in-use:` keys are not skill-namespaced and sibling scouts on one team run at the same time. The scratchpad `remember` view instead counts each `not-in-use:` write on the run its sandbox token is bound to (`metadata.not_in_use_writes`), never the body `run_id`, and finalize reads that counter plus the run's output columns.-- `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.-- `scout_costs.py`- What each scout spent during the roster's seven-day window. It groups run costs by the scout skill name on each run row. It also returns run counts, priced run counts, and recorded report counts. The staff-only `runs/costs` action caches this project-level result for 15 minutes.- `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.@@ -128,7 +120,6 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e`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`.Authored Monitoring scouts submit through `scout-monitoring-result-submit`, gated by a server-minted capability and the token-bound run. Assignment identifiers and the evidence window come from the persisted run brief. Validation errors permit correction within the same run; the ordinary close-out is prose and does not submit a verdict.- `SignalScoutRunViewSet` carries two staff-only cost actions. The `token-costs` action uses `run_costs.py`. The `costs` action uses `scout_costs.py`. Both actions sit in `tools.yaml` as `enabled: false`. Code generation registers each operation, but fleet spend stays outside the public MCP catalog.`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.pydeleted file mode 100644index 4b6d3b8f0e5f..000000000000--- a/products/signals/backend/scout_harness/run_costs.py+++ /dev/null@@ -1,161 +0,0 @@-"""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.value,- 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 costsdiff --git a/products/signals/backend/scout_harness/scout_costs.py b/products/signals/backend/scout_harness/scout_costs.pydeleted file mode 100644index 98a02aadaab7..000000000000--- a/products/signals/backend/scout_harness/scout_costs.py+++ /dev/null@@ -1,176 +0,0 @@-"""Model spend per scout over a window, for the staff-only cost readout on the roster.--`run_costs.py` prices a named set of runs, which answers "what did this run cost". This module-answers the question next to it: what a scout costs over a span, and what it produced for that-spend. Both numbers come from the same place — the run rows in Postgres, joined by `task_run_id` to-the `$ai_generation` sums in the internal AI observability project. The join has to happen here-rather than in the events, because a team-authored scout's generations all carry the same-`ai_stage`, so the events alone cannot name it.--The response is facts, not ratios: spend, how many runs, how many of those were priced, and how-many reports the scout touched. Cost per day, per run, and per report are derived from those four-numbers where they are rendered, so the definitions live in one place.-"""--from __future__ import annotations--from collections import defaultdict-from datetime import timedelta-from decimal import Decimal, InvalidOperation-from typing import Any--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.signals.backend.scout_harness.run_costs import RUN_COST_LOOKBACK_MARGIN-from products.tasks.backend.facade import api as tasks_facade-from products.tasks.backend.facade.billing import TaskTokenUsageUnavailable, get_local_task_run_token_costs--# The window the roster's fleet headline already spans, so every number on the page describes one-# span. It also bounds the per-team read on the largest fleets.-SCOUT_COST_WINDOW_DAYS = 7-# The window's trailing edge moves and the newest runs may still be settling, so this is a roughly-# current number, not a live one. Fifteen minutes keeps a page open on the roster off the events-# read while still tracking the day's spend.-SCOUT_COSTS_CACHE_TIMEOUT_SECONDS = 15 * 60---@frozen-class ScoutCost:- skill_name: str- # Sum over the scout's runs that had spend attributed. Zero when none did, which- # `priced_run_count` tells apart from a scout that really spent nothing.- spend_usd: Decimal- run_count: int- priced_run_count: int- # Distinct inbox reports the scout filed or added to. A report authored in one run and edited in- # three counts once.- reports_touched: int---@frozen-class ScoutCosts:- window_days: int- scouts: list[ScoutCost]- # False when this deployment has no internal AI observability project to read, so every spend is- # unknown rather than zero.- available: bool---def _serialize_scout_costs(costs: ScoutCosts) -> dict[str, Any]:- return {- "window_days": costs.window_days,- "available": costs.available,- "scouts": [- {- "skill_name": scout.skill_name,- "spend_usd": str(scout.spend_usd),- "run_count": scout.run_count,- "priced_run_count": scout.priced_run_count,- "reports_touched": scout.reports_touched,- }- for scout in costs.scouts- ],- }---def _deserialize_scout_costs(value: object) -> ScoutCosts | None:- if not isinstance(value, dict):- return None- window_days = value.get("window_days")- available = value.get("available")- scouts_value = value.get("scouts")- if type(window_days) is not int or type(available) is not bool or not isinstance(scouts_value, list):- return None-- scouts: list[ScoutCost] = []- try:- for scout_value in scouts_value:- if not isinstance(scout_value, dict):- return None- skill_name = scout_value["skill_name"]- spend_usd = Decimal(scout_value["spend_usd"])- counts = (- scout_value["run_count"],- scout_value["priced_run_count"],- scout_value["reports_touched"],- )- if (- not isinstance(skill_name, str)- or not spend_usd.is_finite()- or spend_usd < 0- or any(type(count) is not int or count < 0 for count in counts)- ):- return None- scouts.append(- ScoutCost(- skill_name=skill_name,- spend_usd=spend_usd,- run_count=counts[0],- priced_run_count=counts[1],- reports_touched=counts[2],- )- )- except (InvalidOperation, KeyError, TypeError, ValueError):- return None- return ScoutCosts(window_days=window_days, scouts=scouts, available=available)---def scout_costs(*, team_id: int, window_days: int) -> ScoutCosts:- """Sum this team's scout spend and output per scout over the last `window_days`."""- cache_key = f"scout_costs:v1:{team_id}:{window_days}"- cached = cache.get(cache_key)- if cached is not None:- cached_costs = _deserialize_scout_costs(cached)- if cached_costs is not None:- return cached_costs-- window_start = timezone.now() - timedelta(days=window_days)- task_run_ids_by_skill: dict[str, list[str]] = defaultdict(list)- report_ids_by_skill: dict[str, set[str]] = defaultdict(set)- for skill_name, task_run_id, emitted_report_ids, edited_report_ids in SignalScoutRun.objects.filter(- team_id=team_id, created_at__gte=window_start- ).values_list("skill_name", "task_run_id", "emitted_report_ids", "edited_report_ids"):- task_run_ids_by_skill[skill_name].append(str(task_run_id))- report_ids_by_skill[skill_name].update(- str(report_id) for report_id in [*(emitted_report_ids or []), *(edited_report_ids or [])]- )-- if not task_run_ids_by_skill:- return ScoutCosts(window_days=window_days, scouts=[], available=True)-- try:- spend_by_task_run_id = get_local_task_run_token_costs(- team_id=team_id,- origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT.value,- # No id list: the team filter and the window bound the read, and a per-team list would- # be tens of thousands of ids on the largest fleets. The margin absorbs clock skew- # between a run row and the generations stamped against it.- generated_after=window_start - RUN_COST_LOOKBACK_MARGIN,- product=Product.SIGNALS,- )- except TaskTokenUsageUnavailable:- return ScoutCosts(window_days=window_days, scouts=[], available=False)-- scouts = []- for skill_name, task_run_ids in sorted(task_run_ids_by_skill.items()):- priced = [- spend_by_task_run_id[task_run_id] for task_run_id in task_run_ids if task_run_id in spend_by_task_run_id- ]- scouts.append(- ScoutCost(- skill_name=skill_name,- spend_usd=sum(priced, Decimal(0)),- run_count=len(task_run_ids),- priced_run_count=len(priced),- reports_touched=len(report_ids_by_skill[skill_name]),- )- )-- costs = ScoutCosts(window_days=window_days, scouts=scouts, available=True)- cache.set(cache_key, _serialize_scout_costs(costs), timeout=SCOUT_COSTS_CACHE_TIMEOUT_SECONDS)- return costsdiff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 4e9999e4cab2..9790a99fd8d6 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -73,7 +73,6 @@ from products.signals.backend.scout_harness.precheck import (parse_precheck_query,resolve_effective_precheck,)-from products.signals.backend.scout_harness.scout_costs import SCOUT_COST_WINDOW_DAYSfrom products.signals.backend.scout_harness.skill_loader import reserved_scout_name_errorfrom products.signals.backend.scout_harness.slack_delivery import (MAX_SCOUT_SLACK_DM_TARGETS,@@ -437,99 +436,6 @@ 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 ScoutCostsQuerySerializer(serializers.Serializer):- """Query parameters for the `runs/costs` action."""-- window_days = serializers.IntegerField(- required=False,- # Bounded to the one supported window rather than left open, so a client that asks for 30- # gets a 400 instead of a number silently computed over 7 days.- min_value=SCOUT_COST_WINDOW_DAYS,- max_value=SCOUT_COST_WINDOW_DAYS,- help_text=(- f"Window in days over runs' `created_at` (default {SCOUT_COST_WINDOW_DAYS}). Only "- f"{SCOUT_COST_WINDOW_DAYS} is accepted today — it matches the window the roster's fleet "- "headline spans, so every number on the page describes one span."- ),- )---class ScoutCostSerializer(serializers.Serializer):- """What one scout spent in the window, and what it produced for that spend."""-- skill_name = serializers.CharField(help_text="Full skill name of the scout, e.g. `signals-scout-error-tracking`.")- spend_usd = serializers.FloatField(- help_text=(- "Model spend attributed to the scout's runs in the window, in US dollars. Zero when none "- "of its runs had spend attributed, which `priced_run_count` tells apart from a scout that "- "really spent nothing."- ),- )- run_count = serializers.IntegerField(help_text="Runs the scout started in the window.")- priced_run_count = serializers.IntegerField(- help_text=(- "Runs of the scout that had spend attributed. Lower than `run_count` where a run failed "- "before its first model call, or its generations haven't landed yet. Divide `spend_usd` by "- "this, not by `run_count`, for cost per run."- ),- )- reports_touched = serializers.IntegerField(- help_text=(- "Distinct inbox reports the scout filed or added to in the window. A report it authored in "- "one run and edited in three counts once. Zero means the scout produced no reports, so "- "cost per report has no value rather than a value of zero."- ),- )---class ScoutCostsSerializer(serializers.Serializer):- """Model spend and output per scout over a window."""-- window_days = serializers.IntegerField(help_text="Window the rows describe, in days.")- scouts = ScoutCostSerializer(- many=True,- help_text="One row per scout that started at least one run on this project in the window.",- )- available = serializers.BooleanField(- help_text=(- "False when this deployment has no internal AI observability project to read the "- "generations from, so `scouts` is empty and every spend 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.pyindex 48f101f8b942..766da32b289a 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -113,7 +113,6 @@ from products.signals.backend.scout_harness.precheck import (resolve_effective_precheck,scout_skill_is_canonical,)-from products.signals.backend.scout_harness.run_costs import scout_run_token_costsfrom products.signals.backend.scout_harness.run_gates import (ScoutRunRejection,ScoutRunRejectionKind,@@ -121,7 +120,6 @@ from products.signals.backend.scout_harness.run_gates import (check_run_in_flight,check_spend_gates,)-from products.signals.backend.scout_harness.scout_costs import SCOUT_COST_WINDOW_DAYS, scout_costsfrom products.signals.backend.scout_harness.scout_naming import SLUG_ALLOCATION_ATTEMPTS, allocate_scout_slugfrom products.signals.backend.scout_harness.serializers import (REPOSITORIES_REACHABILITY_CHECKED_CONTEXT_KEY,@@ -151,8 +149,6 @@ from products.signals.backend.scout_harness.serializers import (RecordStructuredOutputResponseSerializer,RememberRequestSerializer,ScoutCheckSummarySerializer,- ScoutCostsQuerySerializer,- ScoutCostsSerializer,ScoutEmissionReportLinkSerializer,ScoutFleetSyncQuerySerializer,ScoutMemberSerializer,@@ -163,7 +159,6 @@ from products.signals.backend.scout_harness.serializers import (ScoutNotesQuerySerializer,ScoutOrigin,ScoutRunIdsBatchRequestSerializer,- ScoutRunTokenCostsSerializer,ScoutToolCatalogueSerializer,ScratchpadEntrySerializer,SearchMemoryQuerySerializer,@@ -672,7 +667,6 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"edit_report","emissions_batch","emission_reports_batch",- "token_costs",}:with trial_state_errors():private.invalidate("The scout requested a write that private trials do not support.")@@ -1100,90 +1094,6 @@ 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",- )- # nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients- @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(- query_serializer=ScoutCostsQuerySerializer,- responses={- 200: OpenApiResponse(- response=ScoutCostsSerializer,- description="Model spend and output per scout over the window.",- ),- 403: OpenApiResponse(description="Caller is not PostHog staff."),- },- summary="Get what each scout spent over a window",- description=(- "Return what every scout on this project spent on model calls over the last `window_days`, "- "with how many runs it started, how many of those had spend attributed, and how many inbox "- "reports it filed or added to. Cost per day, per run, and per report are derived from those "- "numbers by the caller, so the endpoint stays a fact table and the definitions live in one "- "place. Spend is summed from the `$ai_generation` events the runs' sandboxes produced and "- "joined to the run rows by task run id, because a team-authored scout's generations all "- "carry the same stage tag and so cannot name it. Cached per project for 15 minutes: the "- "window's trailing edge moves and the newest runs may still be settling, so this is a "- "roughly current number, not a live one. `available` is false where the internal AI "- "observability project holding those events can't be read, so an unknown spend never reads "- "as zero. Staff-only, same gate as the per-run cost read. Strictly team-scoped."- ),- operation_id="signals_scout_runs_costs",- )- @action(- detail=False,- methods=["get"],- url_path="costs",- required_scopes=["signal_scout:read"],- pagination_class=None,- )- def costs(self, request: Request, **kwargs) -> Response:- if not cast(User, request.user).is_staff:- raise exceptions.PermissionDenied("Only PostHog staff can read scout costs.")- validated = getattr(request, "validated_query_data", {}) or {}- costs = scout_costs(- team_id=_canonical_team_id(self),- window_days=validated.get("window_days") or SCOUT_COST_WINDOW_DAYS,- )- return Response(ScoutCostsSerializer(dataclasses.asdict(costs)).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.pyindex 8db42c489da9..42933031dc1d 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -9,7 +9,6 @@ from collections.abc import AsyncIterator, Callablefrom contextlib import contextmanager, nullcontextfrom dataclasses import replacefrom datetime import UTC, datetime, timedelta-from decimal import Decimalfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import TYPE_CHECKING@@ -21,7 +20,6 @@ from posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.apps import apps-from django.core.cache import cachefrom django.db import OperationalErrorfrom django.test import SimpleTestCase, override_settingsfrom django.utils import timezone@@ -55,11 +53,7 @@ from products.signals.backend.report_metrics import (MAX_LIVE_METRIC_QUERY_SERIES,MAX_REPORT_METRICS,)-from products.signals.backend.scout_harness import (- prompt as scout_prompt,- run_costs,- scout_costs,-)+from products.signals.backend.scout_harness import prompt as scout_promptfrom products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEYfrom products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, _compute_row_hashfrom products.signals.backend.scout_harness.limits import (@@ -119,7 +113,6 @@ from products.signals.backend.temporal.agentic.scout_scheduler import (from products.skills.backend.models.skills import LLMSkill, LLMSkillFile, LLMSkillOwnerfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.agents import AgentTurnFailed, CustomPromptSandboxContext-from products.tasks.backend.facade.billing import TaskTokenUsageUnavailableif TYPE_CHECKING:from products.tasks.backend.models import TaskRun@@ -4265,263 +4258,6 @@ async def test_workflow_skips_only_scheduled_runs_the_precheck_rejects(triggeredassert result.skip_reason == "precheck_skipped"-class TestScoutCosts(BaseTest):- def setUp(self) -> None:- super().setUp()- cache.clear()-- def _run(- self,- *,- skill_name: str = "signals-scout-general",- team: Team | None = None,- created_days_ago: float = 1,- emitted_report_ids: list[str] | None = None,- edited_report_ids: list[str] | None = None,- ) -> SignalScoutRun:- team = team or self.team- config, _ = SignalScoutConfig.objects.get_or_create(team=team, skill_name=skill_name)- run = SignalScoutRun.objects.create(- team=team,- task_run=_make_task_run(team),- scout_config=config,- skill_name=skill_name,- skill_version=1,- emitted_report_ids=emitted_report_ids or [],- edited_report_ids=edited_report_ids or [],- )- SignalScoutRun.objects.filter(pk=run.pk).update(created_at=timezone.now() - timedelta(days=created_days_ago))- run.refresh_from_db()- return run-- def test_sums_spend_runs_and_distinct_reports_per_scout(self) -> None:- # A team-authored scout has to be named as itself: its generations all carry the same stage- # tag, so only the run rows can separate it from every other custom scout.- canonical_a = self._run(emitted_report_ids=["r-1"])- canonical_b = self._run(emitted_report_ids=["r-1"], edited_report_ids=["r-2"])- custom = self._run(skill_name="my-own-scout", edited_report_ids=["r-3"])- with patch.object(- scout_costs,- "get_local_task_run_token_costs",- return_value={- str(canonical_a.task_run_id): Decimal("1.2"),- str(canonical_b.task_run_id): Decimal("0.48"),- str(custom.task_run_id): Decimal("0.1"),- },- ) as query:- costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)-- assert costs.available- assert costs.window_days == 7- by_skill = {scout.skill_name: scout for scout in costs.scouts}- assert by_skill["signals-scout-general"] == scout_costs.ScoutCost(- skill_name="signals-scout-general",- spend_usd=Decimal("1.68"),- run_count=2,- priced_run_count=2,- # `r-1` was filed by one run and touched again by another, so it counts once.- reports_touched=2,- )- assert by_skill["my-own-scout"].spend_usd == Decimal("0.1")- assert by_skill["my-own-scout"].reports_touched == 1- # One window read for the whole team rather than a list of every run id, which would be tens- # of thousands of ids on the largest fleets.- assert query.call_args.kwargs.get("task_run_ids") is None- assert query.call_args.kwargs["generated_after"] < min(canonical_a.created_at, custom.created_at)-- def test_run_without_attributed_spend_is_left_out_of_the_priced_count(self) -> None:- # Cost per run divides by the runs that were priced, so a run that failed before its first- # model call must not pull the average down.- priced = self._run()- self._run()- with patch.object(- scout_costs, "get_local_task_run_token_costs", return_value={str(priced.task_run_id): Decimal("2")}- ):- costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)-- assert [(scout.run_count, scout.priced_run_count, scout.spend_usd) for scout in costs.scouts] == [- (2, 1, Decimal("2"))- ]-- def test_runs_outside_the_window_and_other_teams_runs_are_absent(self) -> None:- other_team = Team.objects.create(organization=self.organization, name="Other")- mine = self._run()- self._run(created_days_ago=9)- self._run(team=other_team, skill_name="signals-scout-general")- with patch.object(- scout_costs, "get_local_task_run_token_costs", return_value={str(mine.task_run_id): Decimal("3")}- ):- costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)-- assert [(scout.skill_name, scout.run_count) for scout in costs.scouts] == [("signals-scout-general", 1)]-- def test_second_read_is_served_from_the_cache(self) -> None:- # The window's trailing edge moves and the newest runs may still be settling, so the number- # is roughly current by design and every roster poll must not re-read the events.- run = self._run()- with patch.object(- scout_costs, "get_local_task_run_token_costs", return_value={str(run.task_run_id): Decimal("1")}- ) as query:- first = scout_costs.scout_costs(team_id=self.team.id, window_days=7)- second = scout_costs.scout_costs(team_id=self.team.id, window_days=7)-- assert second == first- query.assert_called_once()-- cached = cache.get(f"scout_costs:v1:{self.team.id}:7")- assert cached == {- "window_days": 7,- "available": True,- "scouts": [- {- "skill_name": "signals-scout-general",- "spend_usd": "1",- "run_count": 1,- "priced_run_count": 1,- "reports_touched": 0,- }- ],- }-- def test_unreadable_cost_project_is_reported_rather_than_priced_at_zero(self) -> None:- self._run()- with patch.object(scout_costs, "get_local_task_run_token_costs", side_effect=TaskTokenUsageUnavailable()):- costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)-- assert costs.available is False- assert costs.scouts == []-- def test_team_with_no_runs_in_the_window_reads_as_available_and_empty(self) -> None:- with patch.object(scout_costs, "get_local_task_run_token_costs") as query:- costs = scout_costs.scout_costs(team_id=self.team.id, window_days=7)-- assert costs.available- assert costs.scouts == []- query.assert_not_called()---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"- # The HogQL escaper dispatches on the exact class, so a `TextChoices` member in the constant- # raises before the query runs. Equality alone does not catch that.- assert type(called["origin_product"]) is str- 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]--@pytest.mark.parametrize("managed_by,backoff,level,expected",[diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex f471e5455906..78aac1b61813 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -12,7 +12,6 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.apps import apps-from django.core.cache import cachefrom django.test import SimpleTestCasefrom django.utils import timezone@@ -496,8 +495,6 @@ 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"-_SCOUT_COSTS_QUERY = "products.signals.backend.scout_harness.scout_costs.get_local_task_run_token_costs"class TestScoutHarnessEmissionReportsAPI(APIBaseTest):@@ -666,113 +663,6 @@ 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 TestScoutHarnessScoutCostsAPI(APIBaseTest):- def setUp(self) -> None:- super().setUp()- cache.clear()-- def _url(self, query: str = "") -> str:- return f"/api/projects/{self.team.id}/signals/scout/runs/costs/{query}"-- def _make_staff(self) -> None:- self.user.is_staff = True- self.user.save()-- def test_staff_reads_spend_counts_and_reports_per_scout(self) -> None:- self._make_staff()- priced = _make_run(self.team, emitted_report_ids=["r-1"], edited_report_ids=["r-1", "r-2"])- _make_run(self.team)- with patch(_SCOUT_COSTS_QUERY, return_value={str(priced.task_run_id): Decimal("1.68")}):- response = self.client.get(self._url())- assert response.status_code == status.HTTP_200_OK- body = response.json()- assert body["available"] is True- assert body["window_days"] == 7- assert body["scouts"] == [- {- "skill_name": "signals-scout-general",- "spend_usd": 1.68,- "run_count": 2,- # The run that spent nothing is out of the per-run divisor, not priced at zero.- "priced_run_count": 1,- # `r-1` was filed and then edited by the same run, so it counts once.- "reports_touched": 2,- }- ]-- 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. Same gate as the per-run cost read.- _make_run(self.team)- with patch(_SCOUT_COSTS_QUERY) as query:- response = self.client.get(self._url())- assert response.status_code == status.HTTP_403_FORBIDDEN- query.assert_not_called()-- @parameterized.expand(["signals/scout/runs/costs", "signals/spend"])- def test_child_scoped_api_key_cannot_read_parent_costs(self, endpoint: str) -> None:- self._make_staff()- child = Team.objects.create(organization=self.organization, parent_team=self.team, name="Child")- raw = generate_random_token_personal()- PersonalAPIKey.objects.create(- label="child-scoped",- user=self.user,- secure_value=hash_key_value(raw),- scopes=["signal_usage:read" if endpoint == "signals/spend" else "signal_scout:read"],- scoped_teams=[child.id],- )- self.client.logout()-- with patch(_SCOUT_COSTS_QUERY) as query:- response = self.client.get(- f"/api/projects/{child.id}/{endpoint}/",- HTTP_AUTHORIZATION=f"Bearer {raw}",- )-- assert response.status_code == status.HTTP_403_FORBIDDEN- query.assert_not_called()-- def test_unsupported_window_is_refused_rather_than_silently_widened(self) -> None:- # The parameter exists so a detail page can ask for 30 days later. Until it can, a request- # for 30 must not come back as a 7-day number labelled 30.- self._make_staff()- with patch(_SCOUT_COSTS_QUERY) as query:- response = self.client.get(self._url("?window_days=30"))- assert response.status_code == status.HTTP_400_BAD_REQUEST- query.assert_not_called()--class TestScoutHarnessRecentEmissionsAPI(APIBaseTest):def _url(self) -> str:return f"/api/projects/{self.team.id}/signals/scout/runs/emissions/recent/"@@ -6188,6 +6078,22 @@ class TestScoutSpendOverview(APIBaseTest):cached = SpendReporting(self.team).scouts()assert cached.scout_spend.total_spend == 200.375+ def test_child_scoped_api_key_cannot_read_parent_spend(self) -> None:+ child = Team.objects.create(organization=self.organization, parent_team=self.team, name="Child")+ raw = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="child-scoped",+ user=self.user,+ secure_value=hash_key_value(raw),+ scopes=["signal_usage:read"],+ scoped_teams=[child.id],+ )+ self.client.logout()++ response = self.client.get(f"/api/projects/{child.id}/signals/spend/", HTTP_AUTHORIZATION=f"Bearer {raw}")++ assert response.status_code == status.HTTP_403_FORBIDDEN+@parameterized.expand([("empty", False, 0), ("untracked", True, None)])def test_total_without_receipts(self, _name: str, has_run: bool, expected: float | None) -> None:if has_run:diff --git a/products/signals/backend/test/test_scout_trials_api.py b/products/signals/backend/test/test_scout_trials_api.pyindex 2b807cae0c40..d4830a9b667d 100644--- a/products/signals/backend/test/test_scout_trials_api.py+++ b/products/signals/backend/test/test_scout_trials_api.py@@ -167,13 +167,13 @@ class TestScoutTrialAPI(APIBaseTest):assert self.production.emitted_count == 0assert not SignalReportCheck.objects.for_team(self.team.id).exists()- @parameterized.expand(["emissions/batch", "emissions/reports/batch", "token-costs"])+ @parameterized.expand(["emissions/batch", "emissions/reports/batch"])def test_read_only_posts_do_not_invalidate_private_runs(self, action: str) -> None:self._as_trial()response = self.client.post(f"{self.trial_runs_url}{action}/", {"run_ids": [str(self.production.id)]}, format="json")- assert response.status_code == (403 if action == "token-costs" else 200), response.data+ assert response.status_code == 200, response.dataassert ScoutTrialStore(self.trial_run).invalid_reason() is None@parameterized.expand([("report_level", False), ("per_run", True)])diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex b76667ac5650..d304686a3e21 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -10538,34 +10538,6 @@ export interface CreateReportCheckRequestApi {report_id: string}-/**- * What one scout spent in the window, and what it produced for that spend.- */-export interface ScoutCostApi {- /** Full skill name of the scout, e.g. `signals-scout-error-tracking`. */- skill_name: string- /** Model spend attributed to the scout's runs in the window, in US dollars. Zero when none of its runs had spend attributed, which `priced_run_count` tells apart from a scout that really spent nothing. */- spend_usd: number- /** Runs the scout started in the window. */- run_count: number- /** Runs of the scout that had spend attributed. Lower than `run_count` where a run failed before its first model call, or its generations haven't landed yet. Divide `spend_usd` by this, not by `run_count`, for cost per run. */- priced_run_count: number- /** Distinct inbox reports the scout filed or added to in the window. A report it authored in one run and edited in three counts once. Zero means the scout produced no reports, so cost per report has no value rather than a value of zero. */- reports_touched: number-}--/**- * Model spend and output per scout over a window.- */-export interface ScoutCostsApi {- /** Window the rows describe, in days. */- window_days: number- /** One row per scout that started at least one run on this project in the window. */- scouts: ScoutCostApi[]- /** False when this deployment has no internal AI observability project to read the generations from, so `scouts` is empty and every spend is unknown rather than zero. */- available: boolean-}-/*** Request body for the batched emissions / emission-reports lookups: the set of run UUIDs to* resolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for the@@ -10602,29 +10574,6 @@ 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-}-/*** Request body for `remember`.*/@@ -11677,15 +11626,6 @@ export type SignalsScoutReportChecksListParams = {report_id: string}-export type SignalsScoutRunsCostsParams = {- /**- * Window in days over runs' `created_at` (default 7). Only 7 is accepted today — it matches the window the roster's fleet headline spans, so every number on the page describes one span.- * @minimum 7- * @maximum 7- */- window_days?: number-}-export type SignalsScoutRunsRecentEmissionsParams = {/*** ISO-8601 inclusive lower bound on `emitted_at`. Omit to skip the lower bound.diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 8e701b1a1bdd..38f6d113ce57 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -69,7 +69,6 @@ import type {ScoutChatTaskApi,ScoutChatTaskCreateApi,ScoutCheckSummaryApi,- ScoutCostsApi,ScoutEmissionReportLinkApi,ScoutMemberApi,ScoutMetadataApi,@@ -79,7 +78,6 @@ import type {ScoutRubricGenerateApi,ScoutRubricSaveApi,ScoutRunIdsBatchRequestApi,- ScoutRunTokenCostsApi,ScoutSuggestionItemApi,ScoutSuggestionRefreshApi,ScoutSuggestionSetApi,@@ -179,7 +177,6 @@ import type {SignalsScoutProjectProfileGetParams,SignalsScoutReportCheckListParams,SignalsScoutReportChecksListParams,- SignalsScoutRunsCostsParams,SignalsScoutRunsFindingsSummaryParams,SignalsScoutRunsListParams,SignalsScoutRunsRecentEmissionsParams,@@ -2961,37 +2958,6 @@ export const signalsScoutReportChecksList = async (})}-export const getSignalsScoutRunsCostsUrl = (projectId: string, params?: SignalsScoutRunsCostsParams) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/signals/scout/runs/costs/?${stringifiedParams}`- : `/api/projects/${projectId}/signals/scout/runs/costs/`-}--/**- * Return what every scout on this project spent on model calls over the last `window_days`, with how many runs it started, how many of those had spend attributed, and how many inbox reports it filed or added to. Cost per day, per run, and per report are derived from those numbers by the caller, so the endpoint stays a fact table and the definitions live in one place. Spend is summed from the `$ai_generation` events the runs' sandboxes produced and joined to the run rows by task run id, because a team-authored scout's generations all carry the same stage tag and so cannot name it. Cached per project for 15 minutes: the window's trailing edge moves and the newest runs may still be settling, so this is a roughly current number, not a live one. `available` is false where the internal AI observability project holding those events can't be read, so an unknown spend never reads as zero. Staff-only, same gate as the per-run cost read. Strictly team-scoped.- * @summary Get what each scout spent over a window- */-export const signalsScoutRunsCosts = async (- projectId: string,- params?: SignalsScoutRunsCostsParams,- options?: RequestInit-): Promise<ScoutCostsApi> => {- return apiMutator<ScoutCostsApi>(getSignalsScoutRunsCostsUrl(projectId, params), {- ...options,- method: 'GET',- })-}-export const getSignalsScoutRunsEmissionsBatchUrl = (projectId: string) => {return `/api/projects/${projectId}/signals/scout/runs/emissions/batch/`}@@ -3167,27 +3133,6 @@ export const signalsScoutReportCheckList = 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.tsindex 5646de819973..24cb0cab6e99 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -3915,25 +3915,6 @@ 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 entrydiff --git a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts b/products/signals/frontend/inbox/__mocks__/scoutConfigs.tsindex 51d1504268cf..54493d7c46d4 100644--- a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts+++ b/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts@@ -1,5 +1,4 @@import type {- ScoutCostsApi,ScoutSuggestionItemApi,ScoutSuggestionSetApi,SignalScoutConfigApi,@@ -299,24 +298,3 @@ export function mockScoutSuggestionSet(overrides: Partial<ScoutSuggestionSetApi>...overrides,}}--/**- * A cost row per scout, cycling the three cases the surfaces have to tell apart: a scout that spent- * and filed reports, one that spent and filed nothing, and one whose runs had no spend attributed.- */-export function mockScoutCosts(configs: SignalScoutConfigApi[]): ScoutCostsApi {- return {- window_days: 7,- available: true,- scouts: configs.map((config, index) => {- const unpriced = index % 3 === 2- return {- skill_name: config.skill_name,- spend_usd: unpriced ? 0 : 1.68 + index * 4.2,- run_count: 14 + index,- priced_run_count: unpriced ? 0 : 14,- reports_touched: index % 3 === 1 ? 0 : 11,- }- }),- }-}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCostLine.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCostLine.tsxdeleted file mode 100644index 99351a52fc48..000000000000--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCostLine.tsx+++ /dev/null@@ -1,26 +0,0 @@-import { Tooltip } from '@posthog/lemon-ui'--import { pluralize } from 'lib/utils/strings'--import { ScoutCostRollup, scoutCostLineParts, scoutCostWindowLabel } from '../../../utils/scoutCosts'-import { formatRunCost } from '../../../utils/scoutRunsWindow'--/**- * What a scout costs, on one line: per day, per run, and per report. Staff only, and rendered only- * where a rollup exists, so a scout with no priced run in the window shows nothing rather than zero.- */-export function ScoutCostLine({ rollup }: { rollup: ScoutCostRollup }): JSX.Element {- const tooltip = [- `${formatRunCost(rollup.spendUsd)} in the ${scoutCostWindowLabel(rollup.windowDays)}`,- `${pluralize(rollup.pricedRunCount, 'priced run')}`,- rollup.reportsTouched > 0- ? `${pluralize(rollup.reportsTouched, 'report')} filed or added to`- : 'no reports filed or added to',- ].join(' · ')-- return (- <Tooltip title={tooltip}>- <span className="tabular-nums">{scoutCostLineParts(rollup).join(' · ')}</span>- </Tooltip>- )-}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsxindex 90641a59d3f1..0eb0feae9b0c 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsx@@ -12,14 +12,13 @@ import { userLogic } from 'scenes/userLogic'import { mswDecorator } from '~/mocks/browser'-import { mockDailyQuietRuns, mockScoutConfigs, mockScoutCosts, mockScoutRuns } from '../../../__mocks__/scoutConfigs'+import { mockDailyQuietRuns, mockScoutConfigs, mockScoutRuns } from '../../../__mocks__/scoutConfigs'import { inboxSceneLogic } from '../../../inboxSceneLogic'import { ScoutDetailView } from './ScoutDetailView'import { trialFixtureConfig } from './trials/scoutTrialsFixtures'import { createScoutTrialsStoryMocks } from './trials/scoutTrialsStoryMocks'-// One scout's page. Use this to check the health strip, including the staff-only cost segment, and-// the Reports / Runs / Signals tabs below it.+// One scout's page. Use this to check the health strip and the Reports / Runs / Signals tabs below it.const SKILL_NAME = mockScoutConfigs[0].skill_name@@ -39,7 +38,6 @@ const meta: Meta<typeof ScoutDetailView> = {get: {'/api/projects/:id/signals/scout/configs/': () => [200, mockScoutConfigs],'/api/projects/:id/signals/scout/runs/recent-per-scout/': () => [200, mockScoutRuns(mockScoutConfigs)],- '/api/projects/:id/signals/scout/runs/costs/': () => [200, mockScoutCosts(mockScoutConfigs)],'/api/projects/:id/signals/scout/runs/findings/summary/': () => [200, null],'/api/projects/:id/signals/scout/metadata/current/': () => [200, null],'/api/projects/:id/signals/scout/scratchpad/': () => [200, []],@@ -54,16 +52,7 @@ type Story = StoryObj<typeof ScoutDetailView>export const ScoutPage: Story = {}-// The same scout for a non-staff reader: no cost segment, and no request for one.-export const ScoutPageNonStaff: Story = {- decorators: [- mswDecorator({- get: { '/api/users/@me/': () => [200, { ...MOCK_DEFAULT_USER, is_staff: false }] },- }),- ],-}--// A scout that spent but filed nothing: no reports segment, and Runs leads the tabs.+// A scout that filed nothing: no reports segment, and Runs leads the tabs.export const ScoutPageNoReports: Story = {args: { skillName: mockScoutConfigs[1].skill_name },}@@ -102,7 +91,6 @@ const trialsDecorators: Decorator[] = [...trialsMocks.mocks.get,'/api/projects/:id/signals/scout/configs/': () => [200, [trialFixtureConfig]],'/api/projects/:id/signals/scout/runs/recent-per-scout/': () => [200, []],- '/api/projects/:id/signals/scout/runs/costs/': () => [200, mockScoutCosts([trialFixtureConfig])],},}),]diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsxindex c79c9c732da5..54f8ef292dda 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx@@ -10,8 +10,6 @@ import { teamLogic } from 'scenes/teamLogic'import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'import { scoutDetailLogic } from '../../../logics/scoutDetailLogic'-import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'-import { scoutCostLineParts, scoutCostWindowLabel } from '../../../utils/scoutCosts'import { nextRunAt, SCOUT_GROUP_LABEL, ScoutGroupKey, scoutGroup } from '../../../utils/scoutGroups'import {filedOrAddedLabel,@@ -63,8 +61,6 @@ export function ScoutHealthStrip({noteCount: numberlearnedCount: number}): JSX.Element {- const { scoutCostRollups } = useValues(scoutFleetLogic)- const costRollup = scoutCostRollups.get(config.skill_name)const { scoutRunsLoadedOnce, scoutRunsCoverScout } = useValues(scoutDetailLogic({ skillName: config.skill_name }))const { currentTeam } = useValues(teamLogic)const now = new Date()@@ -139,22 +135,7 @@ export function ScoutHealthStrip({</Segment>)}- <FlaggedFeature- flag={FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY}- fallback={- <>- {costRollup && (- <Segment- tooltip={`Model usage for this scout in the ${scoutCostWindowLabel(costRollup.windowDays)}, with rates per run and per report.`}- >- <span className="whitespace-nowrap tabular-nums">- {scoutCostLineParts(costRollup).join(' · ')}- </span>- </Segment>- )}- </>- }- >+ <FlaggedFeature flag={FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY}><ScoutSpendLabel skillName={config.skill_name} /></FlaggedFeature>diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsxindex e6965b054ea6..5c353a1f44e5 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx@@ -17,7 +17,6 @@ import { ScoutSpendLabel } from '../../spend/ScoutSpendLabel'import { ScoutDeprecationBadge, ScoutExemptionBadge, ScoutLifecycleBadge } from './ScoutBadges'import { ScoutCadenceLabel } from './ScoutCadenceLabel'import { ScoutEnabledSwitch } from './ScoutConfigControls'-import { ScoutCostLine } from './ScoutCostLine'import { ScoutNextRunLabel } from './ScoutNextRunLabel'import { ScoutRosterRunBoxes } from './ScoutRosterRunBoxes'import { ScoutStatusDot } from './ScoutStatusDot'@@ -45,13 +44,11 @@ function MetaSeparator(): JSX.Element {*/export const ScoutRosterCard = memo(function ScoutRosterCard({ row }: { row: ScoutRosterRow }): JSX.Element {const { config, group } = row- const { rollups, updatingScoutIds, scoutRunsLoadedOnce, scoutRunsCoverFleet, scoutCostRollups } =- useValues(scoutFleetLogic)+ const { rollups, updatingScoutIds, scoutRunsLoadedOnce, scoutRunsCoverFleet } = useValues(scoutFleetLogic)const { updateScoutConfig } = useActions(scoutFleetLogic)const { currentTeam } = useValues(teamLogic)const now = new Date()const rollup = rollups.get(config.skill_name)- const costRollup = scoutCostRollups.get(config.skill_name)const runs = rollup?.runs ?? []const subtitle = scoutSubtitle(config, rollup, now)// Only enabled scouts have a next run; a paused one would otherwise carry an empty dash.@@ -98,18 +95,7 @@ export const ScoutRosterCard = memo(function ScoutRosterCard({ row }: { row: Sco</>)}</div>- <FlaggedFeature- flag={FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY}- fallback={- <>- {costRollup && (- <div className="flex flex-wrap items-center text-xs leading-none text-tertiary select-none">- <ScoutCostLine rollup={costRollup} />- </div>- )}- </>- }- >+ <FlaggedFeature flag={FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY}><ScoutSpendLabel skillName={config.skill_name} average /></FlaggedFeature></div>diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsxindex afbe8e3d8959..105f81743e18 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsx@@ -1,9 +1,7 @@-import { useValues } from 'kea'import { memo, useMemo } from 'react'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'import { SignalScoutRunSummary } from '../../../types'import { ScoutRunBoxes } from './ScoutRunBoxes'@@ -13,7 +11,6 @@ export const ScoutRosterRunBoxes = memo(function ScoutRosterRunBoxes({runs: SignalScoutRunSummary[]}): JSX.Element | null {const enabled = useFeatureFlag('SELF_DRIVING_USAGE_DISPLAY')- const { scoutRunCostsByScout, expensiveRunCostThreshold } = useValues(scoutFleetLogic)const costs = useMemo(() =>enabled@@ -25,11 +22,5 @@ export const ScoutRosterRunBoxes = memo(function ScoutRosterRunBoxes({: undefined,[runs, enabled])- return (- <ScoutRunBoxes- runs={runs}- costs={enabled ? costs : scoutRunCostsByScout.get(runs[0]?.skill_name ?? '')}- costThreshold={enabled ? undefined : expensiveRunCostThreshold}- />- )+ return <ScoutRunBoxes runs={runs} costs={costs} />})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsxindex 0fa88ca48979..c73d45f379b7 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.test.tsx@@ -47,52 +47,6 @@ describe('ScoutRunBoxes', () => {expect(labels.filter((label) => label.includes('$'))).toHaveLength(1)})- it('marks the runs at or over the fleet threshold, and leaves the cheap ones plain', () => {- // Cost only reached the tooltip, so finding an expensive run meant hovering box by box.- // The marker is the whole point of the change: without it every box looks the same.- const { container } = render(- <ScoutRunBoxes- runs={[- makeRun({ run_id: 'run-cheap' }),- makeRun({ run_id: 'run-at' }),- makeRun({ run_id: 'run-over' }),- ]}- costs={- new Map([- ['run-cheap', 0.05],- ['run-at', 0.49],- ['run-over', 3.19],- ])- }- costThreshold={0.49}- />- )-- expect(container.querySelectorAll('.bg-brand-yellow')).toHaveLength(2)- const labels = Array.from(container.querySelectorAll('[aria-label]')).map(- (node) => node.getAttribute('aria-label') ?? ''- )- expect(labels.filter((label) => label.includes('top 10% of runs by cost'))).toHaveLength(2)- })-- it('puts the marker inside the task link, so the whole column opens the task run', () => {- // The tooltip covers the column and offers to open the task run, and the column reserves- // height above the box for the marker. With the link around the box alone, a click on the- // marker does nothing on a roster card, and the roster table's row handler sends the- // reader to the scout page instead.- const { container } = render(- <ScoutRunBoxes- runs={[makeRun({ run_id: 'run-over', task_url: '/project/2/tasks/run-over' })]}- costs={new Map([['run-over', 3.19]])}- costThreshold={0.49}- />- )-- const link = container.querySelector('a')- expect(link).toHaveAttribute('href', '/project/2/tasks/run-over')- expect(link?.querySelector('.bg-brand-yellow')).not.toBeNull()- })-it('renders two elements per plain run, so a large fleet stays a small DOM', () => {// The roster renders one strip per scout. An extra node per box multiplies by every run on// every card, and a filter change discards the whole set at once.@@ -142,14 +96,6 @@ describe('ScoutRunBoxes', () => {}})- it('marks nothing while the fleet has too few priced runs to rank', () => {- const { container } = render(- <ScoutRunBoxes runs={[makeRun()]} costs={new Map([['run-1', 3.19]])} costThreshold={null} />- )-- expect(container.querySelector('.bg-brand-yellow')).toBeNull()- })-it('leaves every run unpriced when no costs are given', () => {const { container } = render(<ScoutRunBoxes runs={[makeRun()]} />)diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsxindex 91173b47f25b..9f3b0e6147c6 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx@@ -33,17 +33,9 @@ const OUTCOME_BOX_CLASS: Record<ScoutRunOutcome, string> = {const MAX_BOXES = 24const TOOLTIP_DELAY_MS = 400const BOX_CLASS = 'block h-3 w-2 shrink-0 rounded-[2px] transition-transform duration-100 hover:scale-y-125'-// A box column always keeps the marker's height, priced or not, so the strip does not jump a few-// pixels when the costs land a moment after the runs.-const COLUMN_CLASS = 'flex h-4 w-2 shrink-0 flex-col items-center justify-end gap-px'-const MARKER_CLASS = 'block h-[3px] w-2 rounded-[1px] bg-brand-yellow'+const COLUMN_CLASS = 'flex h-4 w-2 shrink-0 flex-col items-center justify-end'-function runDescription(- run: SignalScoutRunSummary,- now: Date,- costUsd: number | undefined,- expensive: boolean-): string {+function runDescription(run: SignalScoutRunSummary, now: Date, costUsd: number | undefined): string {const parts = [scoutRunOutcomeLabel(run, now)]const duration = formatRunDuration(runDurationSeconds(run, now))if (duration) {@@ -52,16 +44,10 @@ function runDescription(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.+ // Only runs with recorded usage carry a cost, so every other run's tooltip omits the segment.if (costUsd !== undefined) {parts.push(formatRunCost(costUsd))}- // The marker is a colored bar, so say the same thing in words for anyone reading the tooltip- // or the screen-reader label.- if (expensive) {- parts.push('top 10% of runs by cost')- }if (run.task_url) {parts.push('open task run')}@@ -108,25 +94,18 @@ function activeBoxOf(column: HTMLElement): ActiveBox {export const ScoutRunBoxes = memo(function ScoutRunBoxes({runs,costs,- costThreshold,}: {runs: SignalScoutRunSummary[]costs?: Map<string, number>- costThreshold?: number | null}): JSX.Element | null {const visible = useMemo(() => {const now = new Date()- return runs.slice(-MAX_BOXES).map((run) => {- const costUsd = costs?.get(run.run_id)- const expensive = costUsd !== undefined && costThreshold != null && costUsd >= costThreshold- return {- run,- outcome: deriveRunOutcome(run, now),- expensive,- description: runDescription(run, now, costUsd, expensive),- }- })- }, [runs, costs, costThreshold])+ return runs.slice(-MAX_BOXES).map((run) => ({+ run,+ outcome: deriveRunOutcome(run, now),+ description: runDescription(run, now, costs?.get(run.run_id)),+ }))+ }, [runs, costs])const [activeBox, setActiveBox] = useState<ActiveBox | null>(null)const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null)const pendingRunId = useRef<string | null>(null)@@ -215,21 +194,13 @@ export const ScoutRunBoxes = memo(function ScoutRunBoxes({onBlur={close}onClick={close}>- {newestFirst.map(({ run, outcome, expensive, description }) => {+ {newestFirst.map(({ run, outcome, description }) => {const boxClass = `${BOX_CLASS} ${OUTCOME_BOX_CLASS[outcome]}`// The label is an attribute, not an `sr-only` child: the roster renders a strip per// scout, so one more node per box adds thousands of nodes to a large fleet.- const column = (- <>- {expensive ? <span className={MARKER_CLASS} /> : null}- <span className={boxClass} role="img" aria-label={`Run ${description}`} />- </>- )+ const column = <span className={boxClass} role="img" aria-label={`Run ${description}`} />// The whole column links, not only the box, because the tooltip spans the column- // and offers to open the task run. A marker left outside the link would not- // navigate there: the roster card holds no handler above the box, and the roster- // table's row handler pushes the scout page for every click that is not inside an- // `a` or `button`.+ // and offers to open the task run.return run.task_url ? (<Link key={run.run_id} to={run.task_url} className={COLUMN_CLASS} data-run-id={run.run_id}>{column}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.stories.tsxindex 58eb31e16c56..4576073d80ac 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.stories.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.stories.tsx@@ -1,12 +1,10 @@-import { MOCK_DEFAULT_USER } from 'lib/api.mock'-import type { Meta, StoryObj } from '@storybook/react'import { FEATURE_FLAGS } from 'lib/constants'import { mswDecorator } from '~/mocks/browser'-import { mockLargeScoutFleet, mockScoutConfigs, mockScoutCosts, mockScoutRuns } from '../../../__mocks__/scoutConfigs'+import { mockLargeScoutFleet, mockScoutConfigs, mockScoutRuns } from '../../../__mocks__/scoutConfigs'import { ScoutsRoster } from './ScoutsRoster'// The roster: one column of scout cards under the search, filter, and sort toolbar. Use this to@@ -60,27 +58,3 @@ export const LargeFleet: Story = {}),],}--// Cost, staff only. The fleet mixes the three cases: a scout that spent and filed reports, one that-// spent and filed nothing, and one whose runs had no spend attributed and so shows no numbers.-const COST_MOCKS = mswDecorator({- get: {- '/api/projects/:id/signals/scout/configs/': () => [200, mockLargeScoutFleet],- '/api/projects/:id/signals/scout/runs/recent-per-scout/': () => [200, mockScoutRuns(mockLargeScoutFleet)],- '/api/projects/:id/signals/scout/runs/costs/': () => [200, mockScoutCosts(mockLargeScoutFleet)],- },-})--export const RosterCosts: Story = {- decorators: [COST_MOCKS],-}--// The same fleet for a non-staff reader: no cost line on any card, and no request for one.-export const RosterCostsNonStaff: Story = {- decorators: [- COST_MOCKS,- mswDecorator({- get: { '/api/users/@me/': () => [200, { ...MOCK_DEFAULT_USER, is_staff: false }] },- }),- ],-}diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.tsindex 2dfecbe6f1d1..ee00424a0465 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts@@ -5,8 +5,7 @@ import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'import { ApiError } from 'lib/api-error'-import { FEATURE_FLAGS, FIRST_REPORT_SCOUT_NAME } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { FIRST_REPORT_SCOUT_NAME } from 'lib/constants'import { organizationLogic } from 'scenes/organizationLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -20,11 +19,9 @@ import {signalsScoutConfigRun,signalsScoutConfigSync,signalsScoutConfigUpdate,- signalsScoutRunsCosts,signalsScoutRunsRecentPerScout,- signalsScoutRunsTokenCosts,} from 'products/signals/frontend/generated/api'-import type { ScoutCostsApi, SignalScoutConfigApi, UserBasicApi } from 'products/signals/frontend/generated/api.schemas'+import type { SignalScoutConfigApi, UserBasicApi } from 'products/signals/frontend/generated/api.schemas'import { llmSkillsNamePublishCommunityCreate } from 'products/skills/frontend/generated/api'import { SignalScoutRunSummary } from '../types'@@ -41,9 +38,7 @@ jest.mock('products/signals/frontend/generated/api', () => ({signalsScoutConfigUpdate: jest.fn(),signalsScoutRunsFindingsSummary: jest.fn(),signalsScoutRunsList: jest.fn(),- signalsScoutRunsCosts: jest.fn(),signalsScoutRunsRecentPerScout: jest.fn(),- signalsScoutRunsTokenCosts: jest.fn(),}))jest.mock('products/skills/frontend/generated/api', () => ({llmSkillsNameArchiveCreate: jest.fn(),@@ -60,10 +55,6 @@ const mockSignalsScoutConfigUpdate = signalsScoutConfigUpdate as jest.MockedFuncconst mockSignalsScoutRunsRecentPerScout = signalsScoutRunsRecentPerScout as jest.MockedFunction<typeof signalsScoutRunsRecentPerScout>-const mockSignalsScoutRunsTokenCosts = signalsScoutRunsTokenCosts as jest.MockedFunction<- typeof signalsScoutRunsTokenCosts->-const mockSignalsScoutRunsCosts = signalsScoutRunsCosts as jest.MockedFunction<typeof signalsScoutRunsCosts>const mockPublishCommunity = llmSkillsNamePublishCommunityCreate as jest.MockedFunction<typeof llmSkillsNamePublishCommunityCreate>@@ -167,8 +158,6 @@ describe('scoutFleetLogic', () => {mockSignalsScoutConfigSync.mockReset().mockResolvedValue([])mockSignalsScoutConfigUpdate.mockReset()mockSignalsScoutRunsRecentPerScout.mockReset().mockResolvedValue([])- mockSignalsScoutRunsTokenCosts.mockReset().mockResolvedValue({ costs: [], available: true })- mockSignalsScoutRunsCosts.mockReset().mockResolvedValue({ window_days: 7, scouts: [], available: true })mockPublishCommunity.mockReset().mockResolvedValue({pr_url: 'https://github.com/PostHog/community-skills/pull/1',pr_number: 1,@@ -1200,350 +1189,4 @@ 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.- // Each strip reads its own scout's slice, so a moved cost must replace only that- // scout's slice and leave every other strip's slice, and its render, alone.- // Both runs are live, so each poll asks for their costs again.- mockSignalsScoutRunsRecentPerScout.mockResolvedValue([- makeRun({ run_id: 'run-priced', status: 'in_progress', completed_at: null }),- makeRun({- run_id: 'run-other',- skill_name: 'signals-scout-other',- status: 'in_progress',- completed_at: null,- }),- ])- mockSignalsScoutRunsTokenCosts.mockResolvedValue({- costs: [- { run_id: 'run-priced', token_cost_usd: 4.03 },- { run_id: 'run-other', token_cost_usd: 0.5 },- ],- available: true,- })- await mountAsStaff(true)-- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])- const first = logic.values.scoutRunCosts- const firstSlices = logic.values.scoutRunCostsByScout- 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 },- { run_id: 'run-other', token_cost_usd: 0.5 },- ],- 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)- const slices = logic.values.scoutRunCostsByScout- expect(slices.get(BASE_CONFIG.skill_name)).not.toBe(firstSlices.get(BASE_CONFIG.skill_name))- expect(slices.get(BASE_CONFIG.skill_name)?.get('run-priced')).toBe(5.11)- expect(slices.get('signals-scout-other')).toBe(firstSlices.get('signals-scout-other'))- })-- it('asks for a settled run once, and keeps asking for a live or newly settled one', async () => {- const recentlySettled = new Date(Date.now() - 60_000).toISOString()- mockSignalsScoutRunsRecentPerScout.mockResolvedValue([- makeRun({ run_id: 'run-settled' }),- makeRun({ run_id: 'run-just-settled', completed_at: recentlySettled }),- makeRun({ run_id: 'run-live', status: 'in_progress', completed_at: null }),- ])- mockSignalsScoutRunsTokenCosts.mockResolvedValue({- costs: [- { run_id: 'run-settled', token_cost_usd: 4.03 },- { run_id: 'run-just-settled', token_cost_usd: 1 },- { run_id: 'run-live', token_cost_usd: 2 },- ],- available: true,- })- await mountAsStaff(true)-- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])-- expect(mockSignalsScoutRunsTokenCosts.mock.calls.map(([, body]) => body.run_ids)).toEqual([- ['run-settled', 'run-just-settled', 'run-live'],- ['run-just-settled', 'run-live'],- ])- expect(logic.values.scoutRunCosts.get('run-settled')).toBe(4.03)- })-- 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('shows a batch as soon as it lands, and sends the rest of the fleet together', async () => {- // Holding every batch back until the last one answers leaves the whole strip costless- // for the first seconds after load, which is the window a reader actually looks at.- const runIds = Array.from({ length: 401 }, (_, index) => `run-${index}`)- mockSignalsScoutRunsRecentPerScout.mockResolvedValue(runIds.map((run_id) => makeRun({ run_id })))- const held: Array<() => void> = []- // A tenth of each batch costs more, so the fleet has a top decile to mark.- mockSignalsScoutRunsTokenCosts.mockImplementation(async (_projectId, body) => {- const costs = body.run_ids.map((run_id, index) => ({- run_id,- token_cost_usd: index % 10 === 0 ? 5 : 1,- }))- if (!body.run_ids.includes('run-0')) {- await new Promise<void>((resolve) => held.push(resolve))- }- return { costs, available: true }- })- await mountAsStaff(true)-- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'mergeScoutRunCosts'])- await new Promise((resolve) => setTimeout(resolve, 0))-- expect(logic.values.scoutRunCosts.get('run-0')).toBe(5)- expect(logic.values.scoutRunCostsLoading).toBe(true)- expect(held).toHaveLength(2)- // The threshold ranks the whole fleet, so it waits for the load to finish rather than- // moving with each batch and re-rendering every strip on the roster.- expect(logic.values.expensiveRunCostThreshold).toBeNull()-- held.forEach((resolve) => resolve())- await expectLogic(logic).toDispatchActions(['loadScoutRunCostsSuccess'])-- expect(logic.values.scoutRunCosts.get('run-200')).toBe(5)- expect(logic.values.scoutRunCosts.get('run-400')).toBe(5)- expect(logic.values.expensiveRunCostThreshold).toBe(5)- })-- 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)- })-- it('asks again for a batch whose costs never reached the store because a sibling failed', async () => {- const runIds = Array.from({ length: 401 }, (_, index) => `run-${index}`)- mockSignalsScoutRunsRecentPerScout.mockResolvedValue(runIds.map((run_id) => makeRun({ run_id })))- mockSignalsScoutRunsTokenCosts.mockImplementation(async (_projectId, body) => {- if (body.run_ids.includes('run-200')) {- throw new ApiError('nope', 500)- }- if (body.run_ids.includes('run-400')) {- await new Promise((resolve) => setTimeout(resolve, 5))- }- return { costs: body.run_ids.map((run_id) => ({ run_id, token_cost_usd: 1 })), available: true }- })- await mountAsStaff(true)-- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])- await new Promise((resolve) => setTimeout(resolve, 20))- mockSignalsScoutRunsTokenCosts.mockClear().mockResolvedValue({ costs: [], available: true })- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])-- const askedAgain = mockSignalsScoutRunsTokenCosts.mock.calls.flatMap(([, body]) => body.run_ids)- expect(askedAgain).toContain('run-400')- expect(askedAgain).not.toContain('run-0')- })-- // 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],- // Deploy skew: a bundle that has the cost feature can reach a backend that does not- // have the endpoint yet, and DRF answers 405 when only the method is missing.- ['a method the backend does not serve yet, which does not', 405, false],- ['a path the backend does not serve yet, which does not', 404, 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.each([- [false, false],- [true, true],- ])('skips legacy costs for staff=%s and usage=%s', async (isStaff, usageEnabled) => {- mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])- featureFlagLogic.mount()- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY]: usageEnabled })- await mountAsStaff(isStaff)-- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess']).toFinishAllListeners()-- expect(mockSignalsScoutRunsTokenCosts).not.toHaveBeenCalled()- expect(mockSignalsScoutRunsCosts).not.toHaveBeenCalled()- featureFlagLogic.unmount()- })-- it('asks for per-scout cost over the roster window and rolls it up per scout', async () => {- mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])- mockSignalsScoutRunsCosts.mockResolvedValue({- window_days: 7,- available: true,- scouts: [- {- skill_name: 'signals-scout-errors',- spend_usd: 1.68,- run_count: 14,- priced_run_count: 14,- reports_touched: 11,- },- ],- })- await mountAsStaff(true)-- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])-- expect(mockSignalsScoutRunsCosts).toHaveBeenCalledWith(String(MOCK_TEAM_ID), { window_days: 7 })- expect(logic.values.scoutCostRollups.get('signals-scout-errors')?.perDay).toBeCloseTo(0.24)- })-- it('keeps the numbers it has when a later cost read fails', async () => {- // The rollups feed a line on every roster card, so blanking them over one failed poll- // is worse than showing the last numbers until the next one answers.- mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])- mockSignalsScoutRunsCosts.mockResolvedValue({- window_days: 7,- available: true,- scouts: [- {- skill_name: 'signals-scout-errors',- spend_usd: 1.68,- run_count: 14,- priced_run_count: 14,- reports_touched: 11,- },- ],- })- await mountAsStaff(true)- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])-- // Deploy skew: a bundle that has this feature can reach a backend without the endpoint.- mockSignalsScoutRunsCosts.mockRejectedValue(new ApiError('nope', 404))- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])-- expect(logic.values.scoutCostRollups.get('signals-scout-errors')?.perDay).toBeCloseTo(0.24)- expect(jest.mocked(posthog.captureException)).not.toHaveBeenCalled()- })-- it('reuses the rollup map when a poll returns the same costs, and rebuilds it when one moves', async () => {- // The runs poll re-reads the fleet cost every 60s against a 15-minute server cache, so- // identical numbers are the normal answer. Every roster card subscribes to this map.- mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])- const costsResponse = (spendUsd: number): ScoutCostsApi => ({- window_days: 7,- available: true,- scouts: [- {- skill_name: 'signals-scout-errors',- spend_usd: spendUsd,- run_count: 14,- priced_run_count: 14,- reports_touched: 11,- },- ],- })-- mockSignalsScoutRunsCosts.mockResolvedValue(costsResponse(1.68))- await mountAsStaff(true)- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])- const firstRollups = logic.values.scoutCostRollups-- // A distinct object carrying the same numbers, the way the cached window answers.- mockSignalsScoutRunsCosts.mockResolvedValue(costsResponse(1.68))- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])- expect(logic.values.scoutCostRollups).toBe(firstRollups)-- // A real change must still land, so the reuse cannot be unconditional.- mockSignalsScoutRunsCosts.mockResolvedValue(costsResponse(3.36))- logic.actions.loadScoutRuns()- await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])- expect(logic.values.scoutCostRollups).not.toBe(firstRollups)- expect(logic.values.scoutCostRollups.get('signals-scout-errors')?.perDay).toBeCloseTo(0.48)- })- })})diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.tsindex 6335c141d38c..f61dc245e077 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts@@ -12,15 +12,12 @@ 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, isUnavailableEndpointError, shouldReportApiFailure } from 'lib/api-error'-import { FEATURE_FLAGS, FIRST_REPORT_SCOUT_NAME } from 'lib/constants'+import { ApiError } from 'lib/api-error'+import { FIRST_REPORT_SCOUT_NAME } from 'lib/constants'import { dayjs } from 'lib/dayjs'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { chunk } from 'lib/utils/arrays'import { reconcileById } from 'lib/utils/objects'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -38,14 +35,11 @@ import {signalsScoutMetadataGet,signalsScoutRunsFindingsSummary,signalsScoutRunsList,- signalsScoutRunsCosts,signalsScoutRunsRecentPerScout,- signalsScoutRunsTokenCosts,} from 'products/signals/frontend/generated/api'import type {FleetFindingsSummaryApi,PatchedSignalScoutConfigUpdateApi,- ScoutCostsApi,ScoutMetadataApi,SignalScoutConfigApi,SignalsScoutConfigSyncSurface,@@ -64,7 +58,6 @@ import {} from '../inboxAnalytics'import { SignalScoutRunSummary } from '../types'import { aiConsentDisabledReason } from '../utils/aiConsent'-import { computeScoutCostRollups, ScoutCostRollup } from '../utils/scoutCosts'import { compareScoutsByName, SCOUT_GROUP_ORDER, scoutGroup, ScoutGroupKey, ScoutRosterRow } from '../utils/scoutGroups'import { selfDrivingSpendLogic } from './selfDrivingSpendLogic'@@ -77,14 +70,10 @@ import type { ScoutOwnerOption } from '../utils/scoutOwners'import {computeFleetSummary,computeScoutRollups,- expensiveRunCostThreshold,FleetSummary,isSettledRun,- rosterRunCosts,runResponseCoversFleet,- scoutRunCostSlices,scoutDisplayName,- SCOUT_ROSTER_WINDOW_DAYS,SCOUT_ROSTER_WINDOW_HOURS,SCOUT_RUNS_PER_SCOUT,SCOUT_RUNS_WINDOW_HOURS,@@ -204,17 +193,6 @@ const RUNS_REFETCH_INTERVAL_MS = 60_000// `loadScoutRuns` gets each scout's last N runs from one ranked query.const RUNS_PAGE_LIMIT = 100const 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-// How many batches are in flight together. Enough to hide the round trips of a materialized fleet,-// few enough that one poll cannot queue every other roster request behind its own burst.-const RUN_COST_BATCH_CONCURRENCY = 4-// The cost endpoint keeps a settled run's total open for 5 minutes after it settles, while its last-// generations cross ingestion, and it caches a total read in that grace for 60 seconds more. A run-// that settled before this answers with its final total. The rest covers clock skew.-const RUN_COST_FINAL_AFTER_MS = 10 * 60_000-// Orders the fleet runs read and the single-scout runs read, which both write `scoutRuns`.function nextRunsRequestSeq(cache: Record<string, any>): number {cache.runsRequestSeq = (cache.runsRequestSeq ?? 0) + 1@@ -307,67 +285,6 @@ 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 runCostIsFinal(run: SignalScoutRunSummary, now: number): boolean {- if (!isSettledRun(run)) {- return false- }- // The backend treats a settled run with no completion stamp as final too.- return !run.completed_at || now - new Date(run.completed_at).getTime() > RUN_COST_FINAL_AFTER_MS-}--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-}--// Fold a batch of costs into the map on screen, keeping the reference when the batch says nothing-// new. Only a poll that moved a number allocates.-function mergeCosts(previous: Map<string, number>, incoming: Map<string, number>): Map<string, number> {- for (const [runId, cost] of incoming) {- if (previous.get(runId) !== cost) {- return new Map([...previous, ...incoming])- }- }- return previous-}--// Same idea for the fleet-wide cost response, which the runs poll re-reads every cycle. The window is-// cached server-side for 15 minutes, so an unchanged poll is the normal case, and `scoutCostRollups`-// builds the map every roster card subscribes to out of this object.-function reuseScoutCostsIfUnchanged(previous: ScoutCostsApi | null, next: ScoutCostsApi): ScoutCostsApi {- if (- !previous ||- previous.window_days !== next.window_days ||- previous.available !== next.available ||- previous.scouts.length !== next.scouts.length- ) {- return next- }- // Rows arrive in the backend's skill-name order, so compare them pairwise. `skill_name` catches a- // membership change that keeps the row count.- const unchanged = next.scouts.every((scout, index) => {- const before = previous.scouts[index]- return (- before.skill_name === scout.skill_name &&- before.spend_usd === scout.spend_usd &&- before.run_count === scout.run_count &&- before.priced_run_count === scout.priced_run_count &&- before.reports_touched === scout.reports_touched- )- })- return unchanged ? previous : next-}-/** What the publisher fills in. The scout's own settings are read from its config, not typed. */export interface PublishScoutOptions {expected_skill_id: string@@ -419,7 +336,6 @@ export interface scoutFleetLogicValues {scoutCount: number}enabledCount: number- expensiveRunCostThreshold: number | nullfleetFindingsSummary: FleetFindingsSummaryApi | nullfleetFindingsSummaryLoadedOnce: booleanfleetFindingsSummaryLoading: boolean@@ -451,9 +367,6 @@ export interface scoutFleetLogicValues {scoutChatRetryAt: number | nullscoutConfigs: SignalScoutConfig[] | nullscoutConfigsLoading: boolean- scoutCostRollups: Map<string, ScoutCostRollup>- scoutCosts: ScoutCostsApi | null- scoutCostsLoading: booleanscoutEnabledFilter: ScoutEnabledFilterscoutFleetSyncOutcome: ScoutFleetSyncOutcomescoutFleetSyncRequested: boolean@@ -463,9 +376,6 @@ export interface scoutFleetLogicValues {scoutMetadataLoading: booleanscoutOwnerOptions: ScoutOwnerOption[]scoutRosterSort: ScoutRosterSort- scoutRunCosts: Map<string, number>- scoutRunCostsByScout: Map<string, Map<string, number>>- scoutRunCostsLoading: booleanscoutRuns: SignalScoutRunSummary[]scoutRunsCoverFleet: booleanscoutRunsLoadedOnce: boolean@@ -474,7 +384,6 @@ export interface scoutFleetLogicValues {scoutTagOptions: ScoutTagOption[]selectedScoutOwner: string | nullselectedScoutTags: string[]- settledScoutRunCosts: Map<string, number>updatingScoutIds: string[]}@@ -552,21 +461,6 @@ export interface scoutFleetLogicActions {scoutConfigs: SignalScoutConfigApi[] | nullpayload?: void}- loadScoutCosts: (_: void) => void- loadScoutCostsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadScoutCostsSuccess: (- scoutCosts: ScoutCostsApi | null,- payload?: void- ) => {- scoutCosts: ScoutCostsApi | null- payload?: void- }loadScoutMetadata: () => anyloadScoutMetadataFailure: (error: string,@@ -582,21 +476,6 @@ export interface scoutFleetLogicActions {scoutMetadata: ScoutMetadataApi | nullpayload?: 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) => voidloadScoutRunsFailure: (error: string,@@ -630,9 +509,6 @@ export interface scoutFleetLogicActions {materializeScoutFleet: (surface?: SignalsScoutConfigSyncSurface) => {surface: SignalsScoutConfigSyncSurface}- mergeScoutRunCosts: (costs: Map<string, number>) => {- costs: Map<string, number>- }patchScoutConfigLocally: (configId: string,updates: Partial<SignalScoutConfig> | SignalScoutConfigUpdate@@ -768,10 +644,6 @@ export interface scoutFleetLogicMeta {) => void | Promise<void>}__keaTypeGenInternalSelectorTypes: {- scoutRunCostsByScout: (- scoutRuns: SignalScoutRunSummary[],- scoutRunCosts: Map<string, number>- ) => Map<string, Map<string, number>>aiConsentDisabledReason: (dataProcessingAccepted: boolean,dataProcessingApprovalDisabledReason: string | null@@ -782,11 +654,6 @@ export interface scoutFleetLogicMeta {) => string | nullrollups: (scoutRuns: SignalScoutRunSummary[]) => Map<string, ScoutRollup>scoutRunsCoverFleet: (scoutConfigs: SignalScoutConfigApi[] | null) => boolean- expensiveRunCostThreshold: (- scoutRuns: SignalScoutRunSummary[],- settledScoutRunCosts: Map<string, number>- ) => number | null- scoutCostRollups: (scoutCosts: ScoutCostsApi | null) => Map<string, ScoutCostRollup>isStaff: (user: null | import('~/types').UserType) => booleanfleetSummary: (scoutConfigs: SignalScoutConfigApi[] | null,@@ -909,7 +776,6 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([startScoutChatTaskFailure: true,setScoutChatRetryAt: (retryAt: number | null) => ({ retryAt }),setScoutFleetSyncOutcome: (outcome: ScoutFleetSyncOutcome) => ({ outcome }),- mergeScoutRunCosts: (costs: Map<string, number>) => ({ costs }),}),loaders(({ actions, values, cache }) => ({@@ -1098,143 +964,6 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([},},],- // Per-run model spend, staff only. The roster's runs are the batch: one request per- // `RUN_COST_BATCH_LIMIT` ids. A run whose answer is final is asked once, so a poll over- // an unchanged fleet asks only for the live runs. 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 finalRunIds: Set<string> = (cache.finalRunCostIds ??= new Set<string>())- const now = Date.now()- const pending = values.scoutRuns.filter((run) => !finalRunIds.has(run.run_id))- const finalOnAnswer = new Set(- pending.filter((run) => runCostIsFinal(run, now)).map((run) => run.run_id)- )- const batches = chunk(- pending.map((run) => run.run_id),- RUN_COST_BATCH_LIMIT- )- const costs = new Map<string, number>()- for (const run of values.scoutRuns) {- const known = values.scoutRunCosts.get(run.run_id)- if (finalRunIds.has(run.run_id) && known !== undefined) {- costs.set(run.run_id, known)- }- }- const priceBatch = async (batch: string[]): Promise<Map<string, number> | null> => {- const response = await signalsScoutRunsTokenCosts(String(teamId), { run_ids: batch })- breakpoint()- // This deployment has no internal project to price runs against, so every- // batch answers the same way and each one costs the backend a run-row read- // and a traceback. Every cost stays unknown.- if (!response.available) {- return null- }- const priced = new Map<string, number>()- for (const cost of response.costs) {- if (cost.token_cost_usd !== null) {- priced.set(cost.run_id, cost.token_cost_usd)- }- }- for (const [runId, cost] of priced) {- costs.set(runId, cost)- }- return priced- }- // Only after the batch's costs reach the store, so a failed sibling cannot leave a- // run final with no cost on screen.- const markFinal = (batch: string[]): void => {- for (const runId of batch) {- if (finalOnAnswer.has(runId)) {- finalRunIds.add(runId)- }- }- }- try {- // The first batch also answers whether this deployment prices runs at all,- // so it goes on its own. The rest go a wave at a time: a materialized fleet- // is several batches, and holding them all back leaves the whole strip- // costless until the slowest one answers. Each wave lands as one merge,- // because every merge is a store update that the whole roster processes.- const first = batches.length > 0 ? await priceBatch(batches[0]) : null- if (first) {- actions.mergeScoutRunCosts(first)- markFinal(batches[0])- for (let start = 1; start < batches.length; start += RUN_COST_BATCH_CONCURRENCY) {- const wave = batches.slice(start, start + RUN_COST_BATCH_CONCURRENCY)- const priced = await Promise.all(wave.map(priceBatch))- actions.mergeScoutRunCosts(- new Map(priced.flatMap((batch) => (batch ? [...batch] : [])))- )- wave.forEach((batch, index) => priced[index] && markFinal(batch))- if (priced.includes(null)) {- break- }- }- }- } 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.- // A route the backend does not serve is expected too, because the- // roster ships ahead of its endpoints and shows no number until both- // sides are deployed.- if (shouldReportApiFailure(error) && !isUnavailableEndpointError(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 mergeCosts(values.scoutRunCosts, costs)- }- throw error- }- return reuseCostsIfUnchanged(values.scoutRunCosts, costs)- },- },- ],- // What each scout spent over the roster's window, staff only. One request for the fleet,- // answered from a 15-minute server cache, so it rides the runs load rather than a poll of- // its own. The response is facts; `scoutCostRollups` turns them into the three rates.- scoutCosts: [- null as ScoutCostsApi | null,- {- loadScoutCosts: async (_: void, breakpoint) => {- const teamId = teamLogic.values.currentTeamId- if (!teamId || !values.isStaff) {- return values.scoutCosts- }- try {- const costs = await signalsScoutRunsCosts(String(teamId), {- window_days: SCOUT_ROSTER_WINDOW_DAYS,- })- breakpoint()- return reuseScoutCostsIfUnchanged(values.scoutCosts, costs)- } catch (error) {- // Same posture as the per-run costs: a staff-only annotation degrades to no- // number rather than reporting a failure the reader can do nothing about,- // and the roster ships ahead of its endpoints.- if (error instanceof ApiError) {- if (shouldReportApiFailure(error) && !isUnavailableEndpointError(error)) {- posthog.captureException(error)- }- return values.scoutCosts- }- throw error- }- },- },- ],runsWindow: [{ runs: [] as SignalScoutRunSummary[], complete: true } as {runs: SignalScoutRunSummary[]@@ -1302,27 +1031,6 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([})),reducers({- // The loader owns this map's default and its end-of-load write; this half folds in a batch- // that landed while the rest of the load is still in flight.- scoutRunCosts: [- new Map<string, number>(),- {- mergeScoutRunCosts: (state: Map<string, number>, { costs }: { costs: Map<string, number> }) =>- mergeCosts(state, costs),- },- ],- // The cost map as of the last finished load. The expensive-run threshold ranks the whole- // fleet, so a half-priced fleet gives a wrong threshold, and a threshold that moves with each- // batch re-renders every strip on the roster.- settledScoutRunCosts: [- new Map<string, number>(),- {- loadScoutRunCostsSuccess: (- _: Map<string, number>,- { scoutRunCosts }: { scoutRunCosts: Map<string, number> }- ) => scoutRunCosts,- },- ],// Tracks which CTA's chat-task kickoff is mid-flight, keyed by its chat type, so only the// pressed chip spins (the others merely disable). A shared boolean spun all three at once.runningChatType: [@@ -1516,24 +1224,6 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([],}),- selectors(() => {- // Each logic instance keeps its last slices, so a scout whose costs did not move keeps its- // slice reference across cost batches and polls.- let previousCostSlices = new Map<string, Map<string, number>>()- return {- scoutRunCostsByScout: [- (s) => [s.scoutRuns, s.scoutRunCosts],- (- scoutRuns: SignalScoutRunSummary[],- scoutRunCosts: Map<string, number>- ): Map<string, Map<string, number>> => {- previousCostSlices = scoutRunCostSlices(scoutRuns, scoutRunCosts, previousCostSlices)- return previousCostSlices- },- ],- }- }),-selectors({aiConsentDisabledReason: [(s) => [s.dataProcessingAccepted, s.dataProcessingApprovalDisabledReason],@@ -1557,15 +1247,6 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([(s) => [s.scoutConfigs],(scoutConfigs: SignalScoutConfig[] | null): boolean => runResponseCoversFleet(scoutConfigs?.length ?? 0),],- expensiveRunCostThreshold: [- (s) => [s.scoutRuns, s.settledScoutRunCosts],- (scoutRuns: SignalScoutRunSummary[], settledScoutRunCosts: Map<string, number>): number | null =>- expensiveRunCostThreshold(rosterRunCosts(scoutRuns, settledScoutRunCosts)),- ],- scoutCostRollups: [- (s) => [s.scoutCosts],- (scoutCosts: ScoutCostsApi | null): Map<string, ScoutCostRollup> => computeScoutCostRollups(scoutCosts),- ],isStaff: [() => [userLogic.selectors.user],(user: null | import('~/types').UserType): boolean => user?.is_staff ?? false,@@ -1782,12 +1463,6 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([if (spendLogic.isMounted()) {spendLogic.actions.loadOverview()}- // 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 && !featureFlagLogic.values.featureFlags[FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY]) {- actions.loadScoutRunCosts()- actions.loadScoutCosts()- }const evaluatedAt = new Date(values.rosterEvaluatedAt)const now = new Date()const groupChanged = (values.scoutConfigs ?? []).some((config) => {diff --git a/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts b/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.tsindex 942d7f19921f..e52e56297085 100644--- a/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutSuggestionsLogic.test.ts@@ -15,7 +15,6 @@ import {signalsScoutConfigSync,signalsScoutConfigUpdate,signalsScoutRunsRecentPerScout,- signalsScoutRunsTokenCosts,signalsScoutSuggestionsDismiss,signalsScoutSuggestionsList,signalsScoutSuggestionsRefresh,@@ -46,7 +45,6 @@ jest.mock('products/signals/frontend/generated/api', () => ({signalsScoutRunsFindingsSummary: jest.fn(),signalsScoutRunsList: jest.fn(),signalsScoutRunsRecentPerScout: jest.fn(),- signalsScoutRunsTokenCosts: jest.fn(),signalsScoutSuggestionsDismiss: jest.fn(),signalsScoutSuggestionsList: jest.fn(),signalsScoutSuggestionsRefresh: jest.fn(),@@ -61,7 +59,6 @@ const mockConfigUpdate = signalsScoutConfigUpdate as jest.MockedFunction<typeofconst mockRunsRecentPerScout = signalsScoutRunsRecentPerScout as jest.MockedFunction<typeof signalsScoutRunsRecentPerScout>-const mockRunsTokenCosts = signalsScoutRunsTokenCosts as jest.MockedFunction<typeof signalsScoutRunsTokenCosts>const mockSkillRetrieve = llmSkillsNameRetrieve as jest.MockedFunction<typeof llmSkillsNameRetrieve>const CANONICAL_ITEM: ScoutSuggestionItemApi = {@@ -157,7 +154,6 @@ describe('scoutSuggestionsLogic', () => {mockConfigSync.mockReset().mockResolvedValue([CONFIG])mockConfigUpdate.mockReset().mockResolvedValue({ ...CONFIG, enabled: true })mockRunsRecentPerScout.mockReset().mockResolvedValue([])- mockRunsTokenCosts.mockReset().mockResolvedValue({ costs: [], available: true })mockSkillRetrieve.mockReset().mockResolvedValue({name: CANONICAL_ITEM.skill_name,description: 'Watches web vitals.',diff --git a/products/signals/frontend/inbox/utils/scoutCosts.test.ts b/products/signals/frontend/inbox/utils/scoutCosts.test.tsdeleted file mode 100644index 7b325a0c3e47..000000000000--- a/products/signals/frontend/inbox/utils/scoutCosts.test.ts+++ /dev/null@@ -1,83 +0,0 @@-import type { ScoutCostApi, ScoutCostsApi } from 'products/signals/frontend/generated/api.schemas'--import { computeScoutCostRollups, scoutCostLineParts } from './scoutCosts'--function costs(scouts: Partial<ScoutCostApi>[], overrides: Partial<ScoutCostsApi> = {}): ScoutCostsApi {- return {- window_days: 7,- available: true,- scouts: scouts.map((scout, index) => ({- skill_name: `signals-scout-${index}`,- spend_usd: 0,- run_count: 0,- priced_run_count: 0,- reports_touched: 0,- ...scout,- })),- ...overrides,- }-}--describe('scoutCosts', () => {- describe('computeScoutCostRollups', () => {- it('divides spend by the window, by the priced runs, and by the reports touched', () => {- const rollups = computeScoutCostRollups(- costs([{ skill_name: 'a', spend_usd: 1.68, run_count: 14, priced_run_count: 12, reports_touched: 11 }])- )-- const rollup = rollups.get('a')- expect(rollup?.perDay).toBeCloseTo(0.24)- // Runs with nothing attributed are not free runs, so they stay out of the divisor.- expect(rollup?.perRun).toBeCloseTo(0.14)- expect(rollup?.perReport).toBeCloseTo(0.1527)- })-- it('leaves cost per report unset when the scout produced nothing, rather than pricing it at zero', () => {- const rollups = computeScoutCostRollups(- costs([{ skill_name: 'a', spend_usd: 13.02, run_count: 6, priced_run_count: 6, reports_touched: 0 }])- )-- expect(rollups.get('a')?.perReport).toBeNull()- expect(rollups.get('a')?.perDay).toBeCloseTo(1.86)- })-- it.each<[string, Partial<ScoutCostApi>[], Partial<ScoutCostsApi>]>([- // Nothing was attributed, so the spend is unknown, not zero: every surface omits it.- ['no priced run in the window', [{ skill_name: 'a', run_count: 3, priced_run_count: 0 }], {}],- [- 'no internal project to read spend from',- [{ skill_name: 'a', spend_usd: 1.5, run_count: 3, priced_run_count: 3 }],- { available: false },- ],- ])('has no rollup when there is %s', (_name, scouts, overrides) => {- expect(computeScoutCostRollups(costs(scouts, overrides)).size).toEqual(0)- })-- it('has no rollup before the read lands', () => {- expect(computeScoutCostRollups(null).size).toEqual(0)- })- })-- describe('scoutCostLineParts', () => {- it.each<[string, Partial<ScoutCostApi>, string]>([- [- 'the three rates',- { spend_usd: 1.68, run_count: 14, priced_run_count: 14, reports_touched: 11 },- '$0.24/day · $0.12/run · $0.15/report',- ],- [- 'the spend and no report to price',- { spend_usd: 13.02, run_count: 6, priced_run_count: 6, reports_touched: 0 },- '$1.86/day · $2.17/run · no reports',- ],- [- 'two decimals on a sub-cent rate',- { spend_usd: 0.014, run_count: 2, priced_run_count: 2, reports_touched: 2 },- '$0.00/day · $0.01/run · $0.01/report',- ],- ])('renders %s', (_name, scout, expected) => {- const rollup = computeScoutCostRollups(costs([{ skill_name: 'a', ...scout }])).get('a')!- expect(scoutCostLineParts(rollup).join(' · ')).toEqual(expected)- })- })-})diff --git a/products/signals/frontend/inbox/utils/scoutCosts.ts b/products/signals/frontend/inbox/utils/scoutCosts.tsdeleted file mode 100644index 0da020c401fd..000000000000--- a/products/signals/frontend/inbox/utils/scoutCosts.ts+++ /dev/null@@ -1,70 +0,0 @@-// Turns the cost endpoint's facts — spend, runs, priced runs, reports touched — into the three-// rates the roster and the scout page show. The API stays a fact table on purpose, so the-// definitions of cost per day, per run, and per report live here and nowhere else.--import type { ScoutCostsApi } from 'products/signals/frontend/generated/api.schemas'--import { formatRunCost } from './scoutRunsWindow'--export interface ScoutCostRollup {- /** Spend attributed to the scout's runs in the window. */- spendUsd: number- windowDays: number- /** Spend over the whole window, whatever part of it the scout was enabled for. */- perDay: number- /** Spend over the runs that had spend attributed, not over every run the scout started. */- perRun: number- /** Null when the scout filed or added to nothing, so there is no report to price. */- perReport: number | null- runCount: number- pricedRunCount: number- reportsTouched: number-}--/**- * A rollup per scout that spent something in the window. A scout with no priced run gets no entry:- * its spend is unknown rather than zero, the same way the per-run tooltip omits a cost it cannot- * attribute, so every surface omits the line instead of printing `$0.00`.- */-export function computeScoutCostRollups(costs: ScoutCostsApi | null): Map<string, ScoutCostRollup> {- const rollups = new Map<string, ScoutCostRollup>()- if (!costs?.available) {- return rollups- }- for (const scout of costs.scouts) {- if (scout.priced_run_count === 0) {- continue- }- rollups.set(scout.skill_name, {- spendUsd: scout.spend_usd,- windowDays: costs.window_days,- perDay: scout.spend_usd / costs.window_days,- perRun: scout.spend_usd / scout.priced_run_count,- perReport: scout.reports_touched > 0 ? scout.spend_usd / scout.reports_touched : null,- runCount: scout.run_count,- pricedRunCount: scout.priced_run_count,- reportsTouched: scout.reports_touched,- })- }- return rollups-}--/** A rate with its unit, e.g. "$0.24/day". Sub-cent rates keep four decimals, as run costs do. */-export function formatCostRate(value: number, unit: 'day' | 'run' | 'report'): string {- return `${formatRunCost(value)}/${unit}`-}--/** The three rates as one line, e.g. "$0.24/day · $0.12/run · $0.15/report". */-export function scoutCostLineParts(rollup: ScoutCostRollup): string[] {- return [- formatCostRate(rollup.perDay, 'day'),- formatCostRate(rollup.perRun, 'run'),- // A scout that produced nothing still spent: say so, rather than pricing zero reports.- rollup.perReport === null ? 'no reports' : formatCostRate(rollup.perReport, 'report'),- ]-}--/** Window the numbers describe, for the labels and tooltips that name it. */-export function scoutCostWindowLabel(windowDays: number): string {- return `last ${windowDays} days`-}diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.tsindex d374a7bcba53..cf8857b6bd6b 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts@@ -5,12 +5,10 @@ import {computeFleetSummary,computeScoutRollups,deriveRunOutcome,- expensiveRunCostThreshold,formatRunCost,filedOrAddedLabel,groupScoutRuns,mostRecentEmittedRuns,- rosterRunCosts,runMatchesFilter,runResponseCoversFleet,runStripEmptyLabel,@@ -88,79 +86,6 @@ describe('scoutRunsWindow report channel', () => {})})- describe('expensiveRunCostThreshold', () => {- function costs(values: number[]): Map<string, number> {- return new Map(values.map((cost, index) => [`run-${index}`, cost]))- }-- const skewed = [...Array.from({ length: 27 }, (_, index) => 0.02 + index / 1000), 0.6, 0.9, 3.19]-- it('says nothing until enough runs are priced to rank them', () => {- // A decile over a handful of runs moves with every run that lands, so the marker would- // point at a different box each poll.- expect(expensiveRunCostThreshold(costs(skewed.slice(0, 19)))).toBeNull()- expect(expensiveRunCostThreshold(costs(skewed.slice(0, 20)))).not.toBeNull()- })-- it('says nothing when every run costs the same', () => {- // A flat fleet has no top decile to point at, and a marker over every box is noise.- expect(expensiveRunCostThreshold(costs(Array.from({ length: 30 }, () => 0.05)))).toBeNull()- })-- it('lands the line above the cheap majority when spend is skewed', () => {- // Scout spend is heavily skewed: the priciest run costs 50 times the median. The line- // has to leave that cheap median unmarked, or the marker points at the whole strip.- // A fleet of 30 runs has 3 runs in its priciest tenth, and the line marks those 3.- const threshold = expensiveRunCostThreshold(costs(skewed)) ?? 0-- expect(skewed.filter((cost) => cost >= threshold)).toEqual([0.6, 0.9, 3.19])- })-- // When most of the fleet shares one cheap price, that price sits on the decile boundary,- // and a line at the boundary would mark the whole strip. The priciest runs still have to- // carry the marker.- it.each<[string, number[], number[]]>([- ['two priciest runs', [...Array.from({ length: 18 }, () => 0.02), 1.5, 3.19], [1.5, 3.19]],- ['one priciest run', [...Array.from({ length: 19 }, () => 0.02), 3.19], [3.19]],- ])('marks the %s when the cheap majority shares one price', (_name, values, expected) => {- const threshold = expensiveRunCostThreshold(costs(values)) ?? 0-- expect(values.filter((cost) => cost >= threshold)).toEqual(expected)- })- })-- describe('rosterRunCosts', () => {- it('drops the cost of a run that has left the roster', () => {- const runs = [makeRun({ run_id: 'run-1' }), makeRun({ run_id: 'run-2' })]- const costs = new Map([- ['run-1', 0.02],- ['run-2', 0.03],- ['run-gone', 9.99],- ])-- expect(rosterRunCosts(runs, costs)).toEqual(- new Map([- ['run-1', 0.02],- ['run-2', 0.03],- ])- )- })-- it('keeps a run that has left the roster from turning the cost marker on', () => {- // A cost batch that fails keeps the previous poll's entries, so a run nobody can see- // could otherwise carry the map over the minimum and rank a line the strip has no- // runs for.- const runs = Array.from({ length: 19 }, (_, index) => makeRun({ run_id: `run-${index}` }))- const costs = new Map<string, number>([- ...runs.map((run, index): [string, number] => [run.run_id, 0.02 + index / 1000]),- ['run-gone', 9.99],- ])-- expect(expensiveRunCostThreshold(costs)).not.toBeNull()- expect(expensiveRunCostThreshold(rosterRunCosts(runs, costs))).toBeNull()- })- })-describe('runStripEmptyLabel', () => {it.each([[{ loadedOnce: false, coversFleet: true }, '…'],diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.tsindex 0245cea8ff5c..1d8bb2099ea1 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts@@ -198,93 +198,6 @@ export function formatRunCost(costUsd: number): string {return humanFriendlyCurrency(costUsd, 2)}-/**- * The costs of the runs the roster holds right now. A cost batch that fails keeps the previous- * poll's entries, so the cost map can outlive the runs it priced. A run that has left the roster is- * invisible on the strip, so it must not move the cost line or count toward the minimum that turns- * the line on.- */-export function rosterRunCosts(runs: SignalScoutRunSummary[], costs: Map<string, number>): Map<string, number> {- const onRoster = new Map<string, number>()- for (const run of runs) {- const cost = costs.get(run.run_id)- if (cost !== undefined) {- onRoster.set(run.run_id, cost)- }- }- return onRoster-}--function sameCosts(a: Map<string, number>, b: Map<string, number>): boolean {- if (a.size !== b.size) {- return false- }- for (const [runId, cost] of b) {- if (a.get(runId) !== cost) {- return false- }- }- return true-}--/**- * The roster's run costs split by scout, so each strip reads only its own runs. A scout whose- * costs did not change keeps its slice from `previous`. A cost batch prices runs of a few scouts,- * and a fresh slice for every scout would re-render every strip on the roster for each batch.- * A scout with no priced run has no slice.- */-export function scoutRunCostSlices(- runs: SignalScoutRunSummary[],- costs: Map<string, number>,- previous: Map<string, Map<string, number>>-): Map<string, Map<string, number>> {- const slices = new Map<string, Map<string, number>>()- for (const run of runs) {- const cost = costs.get(run.run_id)- if (cost === undefined) {- continue- }- let slice = slices.get(run.skill_name)- if (!slice) {- slice = new Map()- slices.set(run.skill_name, slice)- }- slice.set(run.run_id, cost)- }- for (const [skillName, slice] of slices) {- const prior = previous.get(skillName)- if (prior && sameCosts(prior, slice)) {- slices.set(skillName, prior)- }- }- return slices-}--// Below this many priced runs the top decile moves with every run that lands, so the marker would-// point at a different box each poll and mean nothing.-const MIN_PRICED_RUNS_FOR_COST_MARKER = 20--/**- * What the fleet's priciest tenth of runs starts at, or null while too few runs are priced to rank- * them. Scout spend is heavily skewed: most runs cost about a cent, so a top-decile line is what- * separates a run worth opening from the cheap majority.- */-export function expensiveRunCostThreshold(costs: Map<string, number>): number | null {- if (costs.size < MIN_PRICED_RUNS_FOR_COST_MARKER) {- return null- }- const sorted = [...costs.values()].sort((a, b) => a - b)- // The cheapest run inside the priciest tenth, so a line here marks that tenth and no more.- const decileStart = sorted[sorted.length - Math.ceil(sorted.length * 0.1)]- if (decileStart > sorted[0]) {- return decileStart- }- // More than nine tenths of the fleet costs the cheapest price, so a line at the decile would- // mark every box. Mark what costs more than that price instead, which is nothing at all when- // every run costs the same.- return sorted.find((cost) => cost > sorted[0]) ?? null-}-/*** 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 adiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex dda705360bff..44eba663f0e9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -110010,34 +110010,6 @@ export namespace Schemas {dispatched_at: string | null;}- /**- * What one scout spent in the window, and what it produced for that spend.- */- export interface ScoutCost {- /** Full skill name of the scout, e.g. `signals-scout-error-tracking`. */- skill_name: string;- /** Model spend attributed to the scout's runs in the window, in US dollars. Zero when none of its runs had spend attributed, which `priced_run_count` tells apart from a scout that really spent nothing. */- spend_usd: number;- /** Runs the scout started in the window. */- run_count: number;- /** Runs of the scout that had spend attributed. Lower than `run_count` where a run failed before its first model call, or its generations haven't landed yet. Divide `spend_usd` by this, not by `run_count`, for cost per run. */- priced_run_count: number;- /** Distinct inbox reports the scout filed or added to in the window. A report it authored in one run and edited in three counts once. Zero means the scout produced no reports, so cost per report has no value rather than a value of zero. */- reports_touched: number;- }-- /**- * Model spend and output per scout over a window.- */- export interface ScoutCosts {- /** Window the rows describe, in days. */- window_days: number;- /** One row per scout that started at least one run on this project in the window. */- scouts: ScoutCost[];- /** False when this deployment has no internal AI observability project to read the generations from, so `scouts` is empty and every spend is unknown rather than zero. */- available: boolean;- }-/*** One finding the run emitted, paired with the inbox report (if any) its signal grouped into.*@@ -110491,29 +110463,6 @@ 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;- }-/*** A scope preset a scout run can be dispatched with.*/@@ -143781,15 +143730,6 @@ export namespace Schemas {report_id: string;};- export type SignalsScoutRunsCostsParams = {- /**- * Window in days over runs' `created_at` (default 7). Only 7 is accepted today — it matches the window the roster's fleet headline spans, so every number on the page describes one span.- * @minimum 7- * @maximum 7- */- window_days?: number;- };-export type SignalsScoutRunsRecentEmissionsParams = {/*** ISO-8601 inclusive lower bound on `emitted_at`. Omit to skip the lower bound.