Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): show self-driving usage behind a feature flag (#126211)

Oliver Brownef6438a677c14
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index acdd395c237d..c5870bd64141 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -13242,6 +13242,14 @@ snapshots:
hash: v1.k794b7964.f72d1f5b1d052aa1ea44c14d139de7538c8f6fce028595c6e93e65fbbcd81cb6.BXH8wRO87CQipxqRHaFZBYjL2mFan6xvAaHTyOzCH2c
scenes-app-inbox-tabs--runs-loading--light:
hash: v1.k794b7964.4eb178f9e66f29a39f3228c992661409215bf5b173ae458978b3c9876f14bb49.miH6CsWRVa_TkVCM3QJMhPicboUncrDXfrEEWYaVb24
+ scenes-app-inbox-usage--by-source--dark:
+ hash: v1.k794b7964.2a700cb62bd78a4a58b72ba2a4fc06181706a42f952563c4ff96754faab5e2cb.N8D2k3TGoT7FE_Rho9LtGylno0TwiXfhOg4vMH-L6a8
+ scenes-app-inbox-usage--by-source--light:
+ hash: v1.k794b7964.0e848ecbab186f8c8d918ec52c69018c9c77ed2faf136cd8828e483101102bb0.KaWNPDso3qKDPk0-E9e6ZQ2xH2-9hDbvJoF-7uhZUB4
+ scenes-app-inbox-usage--overview--dark:
+ hash: v1.k794b7964.ed8a7c3ca8b23a5626a61558b40cdab7ae00c44154bb39b51ac049d63a5a44da.1kQ54pSck5gvEOUoPr_NZDHGuyjooPTjSfl7prW9xeM
+ scenes-app-inbox-usage--overview--light:
+ hash: v1.k794b7964.c0db5c21f0caa5c9db3734fff25875a16446503374e92c18865a2647f1f413a6.kksWeapIO84pQFzmTZ9iinPbHCmUgX9cDwiUiXr9SMM
scenes-app-inbox-usagewidget--approaching-limit--dark:
hash: v1.k794b7964.9569cc5327e5d7c1e60d9a0281681a6e8a2a56c0fb7656553b528ad7ea0d4fdf.MNU43hs83kTG4wrx8PNTS0SOX5iy02OpAWIGp_ABY6c
scenes-app-inbox-usagewidget--approaching-limit--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 1bfd52bad4d3..eb478e28e07b 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -225,6 +225,7 @@ export const FEATURE_FLAGS = {
SELF_DRIVING_GITHUB_OPTIONAL: 'self-driving-github-optional',
SELF_DRIVING_QUOTA_ENFORCEMENT: 'self-driving-quota-enforcement', // owner: #team-self-driving, gates self-driving PR-limit enforcement (also checked server-side)
SELF_DRIVING_UBP: 'self-driving-ubp', // owner: #team-self-driving
+ SELF_DRIVING_USAGE_DISPLAY: 'self-driving-usage-display', // owner: #team-self-driving, gates monetary usage in the Self-driving UI
SESSION_REPLAY_BACKEND_LOGS: 'session-replay-backend-logs', // owner: #team-replay
SESSION_REPLAY_DOCTOR: 'session-replay-doctor', // owner: #team-replay
SETTINGS_BOUNCE_RATE_PAGE_VIEW_MODE: 'settings-bounce-rate-page-view-mode', // owner: #team-web-analytics
diff --git a/frontend/src/lib/oauthScopes.generated.ts b/frontend/src/lib/oauthScopes.generated.ts
index 253e1d3bb63b..961c6ac7ee4b 100644
--- a/frontend/src/lib/oauthScopes.generated.ts
+++ b/frontend/src/lib/oauthScopes.generated.ts
@@ -190,6 +190,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'sharing_configuration:write',
'signal_scout:read',
'signal_scout:write',
+ 'signal_usage:read',
+ 'signal_usage:write',
'stamphog:read',
'stamphog:write',
'streamlit_app:read',
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index d651a19124ce..36439d4ea5f5 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -331,6 +331,12 @@ export const API_SCOPES: APIScope[] = [
},
},
{ key: 'signal_scout', objectName: 'Signals agent', objectPlural: 'signals agents' },
+ {
+ key: 'signal_usage',
+ objectName: 'Self-driving usage',
+ objectPlural: 'self-driving usage',
+ disabledActions: ['write'],
+ },
{ key: 'review_hog', objectName: 'PostHog Review', objectPlural: 'PostHog Review reviews' },
{ key: 'stamphog', objectName: 'Stamphog', objectPlural: 'stamphog' },
{ key: 'streamlit_app', objectName: 'Streamlit app', objectPlural: 'Streamlit apps' },
@@ -617,6 +623,7 @@ export const API_SCOPE_GROUPS: APIScopeGroup[] = [
'today',
'loop',
'signal_scout',
+ 'signal_usage',
'review_hog',
'approvals',
'autoresearch',
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 806d308086be..6a53ce15039c 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -124,6 +124,7 @@ APIScopeObject = Literal[
"signal_scout_monitoring",
"signal_scout_report",
"signal_scratchpad_internal",
+ "signal_usage",
"slack_run",
"stamphog",
"streamlit_app",
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index 721c4f68ac2b..c0c050837035 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -255,6 +255,10 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {
"products.signals.backend.presentation.onboarding.InboxOnboardingViewSet",
# Lists only the requesting member's own exclusions, a short list, so `pagination_class` is None.
"products.signals.backend.presentation.reviewer_exclusions.SignalReviewerExclusionViewSet",
+ # Returns one usage overview document, not a page of rows.
+ "products.signals.backend.presentation.spend.SignalSpendViewSet",
+ # Returns one rollup per signal source type; Settings needs the complete breakdown to total usage.
+ "products.signals.backend.presentation.spend.SignalSourceSpendViewSet",
"products.signals.backend.scout_harness.views.SignalScoutConfigViewSet",
"products.signals.backend.scout_harness.views.SignalScoutMembersViewSet",
"products.signals.backend.scout_harness.views.SignalScoutNoteViewSet",
diff --git a/products/access_control/frontend/generated/api.schemas.ts b/products/access_control/frontend/generated/api.schemas.ts
index 5ec513017b4d..8033d106c750 100644
--- a/products/access_control/frontend/generated/api.schemas.ts
+++ b/products/access_control/frontend/generated/api.schemas.ts
@@ -136,6 +136,7 @@ export const ResolvedAccessSourceSubjectEnumApi = {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
@@ -257,6 +258,7 @@ export const ScopeObjectEnumApi = {
SessionRecordingPlaylist: 'session_recording_playlist',
SharingConfiguration: 'sharing_configuration',
SignalScout: 'signal_scout',
+ SignalUsage: 'signal_usage',
Stamphog: 'stamphog',
StreamlitApp: 'streamlit_app',
Subscription: 'subscription',
@@ -401,6 +403,7 @@ export interface ProjectAccessSourceApi {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
@@ -565,6 +568,7 @@ export interface AccessControlObjectRuleApi {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
@@ -954,6 +958,7 @@ export interface AccessControlObjectRuleResourceApi {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
@@ -1240,6 +1245,7 @@ export interface ResolvedAccessApi {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
diff --git a/products/signals/backend/facade/spend.py b/products/signals/backend/facade/spend.py
index 1822884d2042..d5b57fc112f1 100644
--- a/products/signals/backend/facade/spend.py
+++ b/products/signals/backend/facade/spend.py
@@ -1,4 +1,20 @@
+from typing import TYPE_CHECKING
+
from products.signals.backend.spend import (
complete_task_spend as complete_task_spend,
register_report_task_spend as register_report_task_spend,
)
+from products.signals.backend.spend_reporting import SpendReporting
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+ from products.signals.backend.spend_reporting import SourceSpend, SpendOverview
+
+
+def scout_spend_overview(*, team: "Team") -> "SpendOverview":
+ return SpendReporting(team).scouts()
+
+
+def source_spend_overview(*, team: "Team") -> list["SourceSpend"]:
+ return SpendReporting(team).sources()
diff --git a/products/signals/backend/presentation/spend.py b/products/signals/backend/presentation/spend.py
new file mode 100644
index 000000000000..4e7066cfa912
--- /dev/null
+++ b/products/signals/backend/presentation/spend.py
@@ -0,0 +1,82 @@
+from dataclasses import asdict
+
+from drf_spectacular.utils import extend_schema, extend_schema_serializer
+from rest_framework import serializers, viewsets
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.permissions import APIScopePermission
+
+from products.signals.backend.facade.spend import scout_spend_overview, source_spend_overview
+from products.signals.backend.presentation.scout_permissions import ScoutCanonicalTeamAccessPermission
+
+
+class SpendAmountSerializer(serializers.Serializer):
+ total_spend = serializers.FloatField(
+ allow_null=True,
+ help_text="Recorded usage in USD cents, before billing exemptions; null when untracked.",
+ )
+ incomplete = serializers.BooleanField(help_text="Whether usage is still settling or accounting is incomplete.")
+
+
+class ScoutSpendSerializer(serializers.Serializer):
+ skill_name = serializers.CharField(help_text="Name of the scout skill.")
+ spend = SpendAmountSerializer(help_text="Accumulated usage for this scout's runs in the period.")
+ average_spend = serializers.FloatField(
+ allow_null=True,
+ help_text="Average recorded usage per tracked scout run in USD cents; null when no runs were tracked.",
+ )
+
+
+@extend_schema_serializer(many=False)
+class SpendOverviewSerializer(serializers.Serializer):
+ period_start = serializers.DateTimeField(help_text="Inclusive start of the rolling 30-day run window.")
+ period_end = serializers.DateTimeField(help_text="Exclusive end of the rolling 30-day run window.")
+ scouts = ScoutSpendSerializer(many=True, help_text="Usage for each scout with runs in the period.")
+ scout_spend = SpendAmountSerializer(help_text="Total scout run usage in the period.")
+
+
+class SourceSpendSerializer(serializers.Serializer):
+ source_product = serializers.CharField(help_text="Product that emitted the signals.")
+ source_type = serializers.CharField(help_text="Type of signals emitted by the source.")
+ signal_count = serializers.IntegerField(help_text="Number of signals received in the last 30 days.")
+ spend = SpendAmountSerializer(
+ help_text="Accumulated processing usage on these signals, including later processing."
+ )
+
+
+class ReportSpendSerializer(serializers.Serializer):
+ generation = SpendAmountSerializer(
+ help_text="Usage for the report's backing signals, research and repository selection."
+ )
+ implementation = SpendAmountSerializer(help_text="Usage for implementation tasks owned by the report.")
+ shared_scout_runs = SpendAmountSerializer(
+ help_text="Full usage of scout runs that authored this report. Shared with all other output of those runs."
+ )
+
+
+class SignalSpendViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ serializer_class = SpendOverviewSerializer
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [IsAuthenticated, APIScopePermission, ScoutCanonicalTeamAccessPermission]
+ scope_object = "signal_usage"
+ pagination_class = None
+
+ @extend_schema(responses=SpendOverviewSerializer, operation_id="signals_spend_overview")
+ def list(self, request: Request, **kwargs: object) -> Response:
+ return Response(SpendOverviewSerializer(asdict(scout_spend_overview(team=self.team))).data)
+
+
+class SignalSourceSpendViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ serializer_class = SourceSpendSerializer
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ permission_classes = [IsAuthenticated, APIScopePermission]
+ scope_object = "signal_usage"
+ pagination_class = None
+
+ @extend_schema(responses=SourceSpendSerializer(many=True), operation_id="signals_source_spend")
+ def list(self, request: Request, **kwargs: object) -> Response:
+ return Response(SourceSpendSerializer(source_spend_overview(team=self.team), many=True).data)
diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.py
index 68c16fa6bdf1..640b92c969cc 100644
--- a/products/signals/backend/routes.py
+++ b/products/signals/backend/routes.py
@@ -7,6 +7,7 @@ from products.signals.backend.presentation.inbox_summary import InboxSummaryView
from products.signals.backend.presentation.onboarding import InboxOnboardingViewSet
from products.signals.backend.presentation.reviewer_exclusions import SignalReviewerExclusionViewSet
from products.signals.backend.presentation.scout_rubrics import SignalScoutRubricViewSet
+from products.signals.backend.presentation.spend import SignalSourceSpendViewSet, SignalSpendViewSet
from products.signals.backend.scout_chat import SignalScoutChatTaskViewSet
from products.signals.backend.scout_harness.views import (
SignalProjectProfileViewSet,
@@ -23,6 +24,10 @@ from products.signals.backend.views import SignalViewSet
def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(r"signals/spend", SignalSpendViewSet, "project_signals_spend", ["team_id"])
+ routers.projects.register(
+ r"signals/source_spend", SignalSourceSpendViewSet, "project_signals_source_spend", ["team_id"]
+ )
routers.projects.register(r"signals/onboarding", InboxOnboardingViewSet, "project_signals_onboarding", ["team_id"])
routers.projects.register(
r"signals/inbox_summary", InboxSummaryViewSet, "project_signals_inbox_summary", ["team_id"]
diff --git a/products/signals/backend/spend_reporting.py b/products/signals/backend/spend_reporting.py
new file mode 100644
index 000000000000..fe763fc2ed45
--- /dev/null
+++ b/products/signals/backend/spend_reporting.py
@@ -0,0 +1,211 @@
+from datetime import datetime, timedelta
+from typing import cast
+from uuid import UUID
+
+from django.core.cache import cache
+from django.db.models import Count, Q, QuerySet, Sum
+from django.utils import timezone
+
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.clickhouse.workload import Workload
+from posthog.dataclasses import frozen
+from posthog.models import Team
+
+from products.signals.backend.enums import SignalSourceProduct, SignalSourceType
+from products.signals.backend.models import SignalReport, SignalScoutRun, SignalSpend
+from products.signals.backend.signal_metadata import EMBEDDING_MODEL, _deduped_signals_subquery, _signals_query_context
+
+
+@frozen
+class SpendAmount:
+ total_spend: float | None
+ incomplete: bool
+
+
+@frozen
+class ScoutSpend:
+ skill_name: str
+ spend: SpendAmount
+ average_spend: float | None
+
+
+@frozen
+class SpendOverview:
+ period_start: datetime
+ period_end: datetime
+ scouts: list[ScoutSpend]
+ scout_spend: SpendAmount
+
+
+@frozen
+class SourceSpend:
+ source_product: str
+ source_type: str
+ signal_count: int
+ spend: SpendAmount
+
+
+@frozen
+class ReportSpend:
+ generation: SpendAmount
+ implementation: SpendAmount
+ shared_scout_runs: SpendAmount
+
+
+class SpendReporting:
+ def __init__(self, team: Team) -> None:
+ self.team = team
+ self.team_id = self.team.id
+
+ def _amount(self, receipts: QuerySet[SignalSpend]) -> SpendAmount:
+ totals = receipts.aggregate(
+ total=Sum("spend"),
+ incomplete=Count("id", filter=Q(accounting_failed=True) | Q(finalized_at__isnull=True)),
+ )
+ return SpendAmount(
+ total_spend=float(totals["total"]) if totals["total"] is not None else None,
+ incomplete=bool(totals["incomplete"]),
+ )
+
+ def _scouts(self, team: Team) -> SpendOverview:
+ end = timezone.now()
+ start = end - timedelta(days=30)
+ runs = (
+ SignalScoutRun.objects.for_team(team.id)
+ .filter(created_at__gte=start, created_at__lt=end)
+ .exclude(metadata__has_key="scout_trial")
+ )
+ run_counts = dict(runs.values("skill_name").annotate(count=Count("id")).values_list("skill_name", "count"))
+ receipts = SignalSpend.objects.for_team(team.id).filter(
+ kind=SignalSpend.Kind.SCOUT_RUN, scout_run_id__in=runs.values("id")
+ )
+ totals = list(
+ receipts.values("scout_run__skill_name").annotate(
+ total=Sum("spend"),
+ tracked=Count("scout_run_id", distinct=True),
+ incomplete=Count("id", filter=Q(accounting_failed=True) | Q(finalized_at__isnull=True)),
+ )
+ )
+ by_skill = {
+ row["scout_run__skill_name"]: SpendAmount(
+ total_spend=float(row["total"]),
+ incomplete=bool(row["incomplete"]) or row["tracked"] < run_counts[row["scout_run__skill_name"]],
+ )
+ for row in totals
+ }
+ average_by_skill = {row["scout_run__skill_name"]: float(row["total"] / row["tracked"]) for row in totals}
+ scouts = [
+ ScoutSpend(
+ skill_name=name,
+ spend=by_skill.get(name, SpendAmount(total_spend=None, incomplete=False)),
+ average_spend=average_by_skill.get(name),
+ )
+ for name in sorted(run_counts)
+ ]
+ total_spend = float(sum(row["total"] for row in totals)) if totals else None
+ return SpendOverview(
+ period_start=start,
+ period_end=end,
+ scouts=scouts,
+ scout_spend=SpendAmount(
+ total_spend=total_spend if run_counts else 0,
+ incomplete=any(scout.spend.incomplete or scout.spend.total_spend is None for scout in scouts),
+ ),
+ )
+
+ def scouts(self) -> SpendOverview:
+ team = self.team.parent_team or self.team
+ return cast(
+ SpendOverview,
+ cache.get_or_set(f"signals:usage:scouts:v1:{team.id}", lambda: self._scouts(team), timeout=60),
+ )
+
+ def _sources(self) -> list[SourceSpend]:
+ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)
+ # Signal timestamps do not change when spend metadata is republished, so this bounds all
+ # versions of a signal without losing its latest receipt or counting it more than once.
+ query = f"""
+ SELECT
+ JSONExtractString(metadata, 'source_product') AS source_product,
+ JSONExtractString(metadata, 'source_type') AS source_type,
+ count() AS signal_count,
+ countIf(isNotNull(toFloat64OrNull(JSONExtractRaw(metadata, 'total_spend')))) AS tracked_count,
+ sum(toFloat64OrNull(JSONExtractRaw(metadata, 'total_spend'))) AS total_spend,
+ countIf(length(JSONExtractArrayRaw(metadata, 'spend_accounting_failed_stages')) > 0) AS failed_count
+ FROM ({_deduped_signals_subquery(include_content=False, extra_where="timestamp >= {period_start} AND timestamp < {period_end} AND rendering = 'plain'")})
+ GROUP BY source_product, source_type
+ ORDER BY total_spend DESC, source_product, source_type
+ LIMIT {{source_group_limit}}
+ """
+ end = timezone.now()
+ response = execute_hogql_query(
+ query=query,
+ team=self.team,
+ context=_signals_query_context(self.team),
+ ch_user=ClickHouseUser.SIGNALS,
+ workload=Workload.ONLINE,
+ query_type="SignalsSourceSpend",
+ placeholders={
+ "model_name": ast.Constant(value=EMBEDDING_MODEL.value),
+ "period_start": ast.Constant(value=end - timedelta(days=30)),
+ "period_end": ast.Constant(value=end),
+ "source_group_limit": ast.Constant(value=len(SignalSourceProduct) * len(SignalSourceType)),
+ },
+ )
+ return [
+ SourceSpend(
+ source_product=product,
+ source_type=source_type,
+ signal_count=count,
+ spend=SpendAmount(
+ total_spend=float(total) if tracked else None, incomplete=tracked < count or failed > 0
+ ),
+ )
+ for product, source_type, count, tracked, total, failed in response.results or []
+ ]
+
+ def sources(self) -> list[SourceSpend]:
+ return cast(
+ list[SourceSpend], cache.get_or_set(f"signals:usage:sources:v1:{self.team_id}", self._sources, timeout=60)
+ )
+
+ def report(self, report: SignalReport) -> ReportSpend:
+ # Task polling stops after completion, so caching here could leave the final amount stale.
+ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)
+ query = f"""
+ SELECT groupArray(document_id)
+ FROM ({_deduped_signals_subquery(include_content=False, candidate_document_filter="JSONExtractString(metadata, 'report_id') = {report_id}")})
+ WHERE JSONExtractString(metadata, 'report_id') = {{report_id}}
+ """
+ response = execute_hogql_query(
+ query=query,
+ team=self.team,
+ context=_signals_query_context(self.team),
+ ch_user=ClickHouseUser.SIGNALS,
+ workload=Workload.ONLINE,
+ query_type="SignalsReportSpend",
+ placeholders={
+ "model_name": ast.Constant(value=EMBEDDING_MODEL.value),
+ "report_id": ast.Constant(value=str(report.id)),
+ },
+ )
+ signal_ids = {UUID(signal_id) for row in response.results or [] for signal_id in row[0]}
+ if report.triggering_signal_id:
+ signal_ids.add(report.triggering_signal_id)
+ if report.pending_triggering_signal_id:
+ signal_ids.add(report.pending_triggering_signal_id)
+ receipts = SignalSpend.objects.for_team(self.team_id).filter(kind__isnull=False)
+ shared_runs = (
+ SignalScoutRun.objects.for_team(self.team_id)
+ .filter(emitted_report_ids__contains=[str(report.id)])
+ .exclude(metadata__has_key="scout_trial")
+ )
+ return ReportSpend(
+ generation=self._amount(receipts.filter(signal_id__in=signal_ids)),
+ implementation=self._amount(receipts.filter(report_id=report.id)),
+ shared_scout_runs=self._amount(receipts.filter(scout_run_id__in=shared_runs.values("id"))),
+ )
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index c8dc8a2574c4..f471e5455906 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -56,6 +56,7 @@ from products.signals.backend.models import (
SignalScoutNote,
SignalScoutRun,
SignalScratchpad,
+ SignalSpend,
)
from products.signals.backend.pipeline_identity import AI_STAGE_RESEARCH
from products.signals.backend.quota import SelfDrivingQuotaGate
@@ -88,6 +89,7 @@ from products.signals.backend.scout_harness.tools.profile import compute_project
from products.signals.backend.scout_harness.tools.scratchpad import NOT_IN_USE_WRITES_KEY
from products.signals.backend.scout_harness.tools.structured_output import STRUCTURED_OUTPUT_COUNT_KEY
from products.signals.backend.scout_harness.trial_state import initial_trial_state
+from products.signals.backend.spend_reporting import SpendReporting
from products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_ids
from products.skills.backend.models.skills import LLMSkill, LLMSkillOwner
@@ -738,10 +740,8 @@ class TestScoutHarnessScoutCostsAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
query.assert_not_called()
- def test_child_scoped_api_key_cannot_read_parent_costs(self) -> None:
- from posthog.models.personal_api_key import PersonalAPIKey
- from posthog.models.utils import generate_random_token_personal, hash_key_value
-
+ @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()
@@ -749,14 +749,14 @@ class TestScoutHarnessScoutCostsAPI(APIBaseTest):
label="child-scoped",
user=self.user,
secure_value=hash_key_value(raw),
- scopes=["signal_scout:read"],
+ 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}/signals/scout/runs/costs/",
+ f"/api/projects/{child.id}/{endpoint}/",
HTTP_AUTHORIZATION=f"Bearer {raw}",
)
@@ -6099,3 +6099,99 @@ class TestScoutHarnessLighthouseAPI(APIBaseTest):
assert refused.status_code == status.HTTP_404_NOT_FOUND
browserless_for_sibling.assert_not_called()
assert self._spent(sibling_run) == 0
+
+
+class TestScoutSpendOverview(APIBaseTest):
+ @parameterized.expand(
+ [
+ (endpoint, scope, report_status)
+ for endpoint in ("scouts", "sources", "report")
+ for scope in ("signal_usage", "signal_scout", "task")
+ for report_status in (
+ [SignalReport.Status.POTENTIAL, SignalReport.Status.SUPPRESSED]
+ if endpoint == "report"
+ else [SignalReport.Status.POTENTIAL]
+ )
+ ]
+ )
+ def test_usage_requires_its_own_scope(self, endpoint: str, scope: str, report_status: str) -> None:
+ report = SignalReport.objects.create(team=self.team, title="Synthetic report", status=report_status)
+ path = {
+ "scouts": "signals/spend/",
+ "sources": "signals/source_spend/",
+ "report": f"signals/reports/{report.id}/spend/",
+ }[endpoint]
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="usage-read",
+ user=self.user,
+ secure_value=hash_key_value(raw),
+ scopes=[f"{scope}:read"],
+ scoped_teams=[self.team.id],
+ )
+ self.client.logout()
+ with patch("products.signals.backend.spend_reporting.execute_hogql_query") as query:
+ query.return_value.results = []
+ response = self.client.get(f"/api/projects/{self.team.id}/{path}", HTTP_AUTHORIZATION=f"Bearer {raw}")
+ assert response.status_code == (200 if scope == "signal_usage" else 403), response.content
+
+ @parameterized.expand([False, True])
+ def test_spend_is_team_scoped_and_excludes_private_and_old_runs(self, child_environment: bool) -> None:
+ run = _make_run(self.team)
+ _make_run(self.team)
+ second_tracked = _make_run(self.team)
+ another_scout = _make_run(self.team, skill_name="signals-scout-errors")
+ private = _make_run(self.team, metadata={"scout_trial": {"version": 1}})
+ old = _make_run(self.team)
+ SignalScoutRun.objects.for_team(self.team.id).filter(id=old.id).update(
+ created_at=timezone.now() - timedelta(days=40)
+ )
+ other_team = Team.objects.create(organization=self.organization)
+ other = _make_run(other_team)
+ for row, amount in [
+ (run, 125.25),
+ (second_tracked, 74.75),
+ (another_scout, 0.375),
+ (private, 999),
+ (old, 999),
+ (other, 999),
+ ]:
+ SignalSpend.objects.for_team(row.team_id).create(
+ team_id=row.team_id,
+ scout_run=row,
+ task_run_id=row.task_run_id,
+ kind="scout_run",
+ spend=amount,
+ finalized_at=timezone.now(),
+ )
+ url_team = (
+ Team.objects.create(organization=self.organization, parent_team=self.team)
+ if child_environment
+ else self.team
+ )
+ response = self.client.get(f"/api/projects/{url_team.id}/signals/spend/")
+ assert response.status_code == 200, response.content
+ assert response.json()["scout_spend"] == {"total_spend": 200.375, "incomplete": True}
+ assert response.json()["scouts"] == [
+ {
+ "skill_name": "signals-scout-errors",
+ "spend": {"total_spend": 0.375, "incomplete": False},
+ "average_spend": 0.375,
+ },
+ {
+ "skill_name": "signals-scout-general",
+ "spend": {"total_spend": 200, "incomplete": True},
+ "average_spend": 100,
+ },
+ ]
+ with self.assertNumQueries(0):
+ cached = SpendReporting(self.team).scouts()
+ assert cached.scout_spend.total_spend == 200.375
+
+ @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:
+ _make_run(self.team)
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/spend/")
+ assert response.status_code == 200, response.content
+ assert response.json()["scout_spend"] == {"total_spend": expected, "incomplete": has_run}
diff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.py
index 4beea3423c0f..fe2650322e28 100644
--- a/products/signals/backend/test/test_signal_queries.py
+++ b/products/signals/backend/test/test_signal_queries.py
@@ -3,11 +3,14 @@ from __future__ import annotations
import json
import uuid
from datetime import UTC, datetime, timedelta
+from itertools import islice, product
import time_machine
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, FuzzyInt
from unittest.mock import AsyncMock, MagicMock, patch
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
from parameterized import parameterized
@@ -18,7 +21,9 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.models import Team
+from products.signals.backend.enums import SignalSourceProduct, SignalSourceType
from products.signals.backend.facade.api import (
SignalSourceSlicePullRequest,
get_outcomes_for_signal_source_slice,
@@ -29,6 +34,7 @@ from products.signals.backend.models import (
SignalReport,
SignalReportArtefact,
SignalReportPullRequest,
+ SignalSpend,
)
from products.signals.backend.signal_metadata import (
EMBEDDING_MODEL,
@@ -790,3 +796,130 @@ class TestRetractSourceSignals(_SignalEmbeddingsTestBase):
call.kwargs["start_signal_args"] == [SignalMetadataChange(deleted=True, clear_content=True)]
for call in calls
)
+
+
+class TestSpendReportingQueries(_SignalEmbeddingsTestBase):
+ def test_source_usage_includes_groups_beyond_the_default_query_limit(self) -> None:
+ groups = list(islice(product(SignalSourceProduct, SignalSourceType), 101))
+ for index, (source_product, source_type) in enumerate(groups):
+ self._emit_version(
+ document_id=f"usage-group-{index}",
+ report_id="report",
+ source_product=source_product,
+ source_type=source_type,
+ inserted_at=self.base,
+ spend_metadata={"total_spend": index + 1},
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/source_spend/")
+ assert response.status_code == 200, response.content
+ rows = response.json()
+ assert len(rows) == 101
+ assert {(row["source_product"], row["source_type"]) for row in rows} == set(groups)
+ assert sum(row["spend"]["total_spend"] for row in rows) == sum(range(1, 102))
+
+ @parameterized.expand([False, True])
+ def test_sources_use_latest_receipt_and_distinguish_missing_spend(self, child_environment: bool) -> None:
+ if child_environment:
+ self.team = Team.objects.create(organization=self.organization, parent_team=self.team)
+ for inserted_at, amount in [(self.base, 2.5), (self.base + timedelta(hours=1), 17.125)]:
+ self._emit_version(
+ document_id="source-spend",
+ report_id="report",
+ source_product="github",
+ inserted_at=inserted_at,
+ spend_metadata={"total_spend": amount},
+ )
+ self._emit_version(
+ document_id="untracked",
+ report_id="report",
+ source_product="github",
+ inserted_at=self.base,
+ spend_metadata={"total_spend": None},
+ )
+ self._emit_version(
+ document_id="old",
+ report_id="report",
+ source_product="linear",
+ inserted_at=self.base - timedelta(days=40),
+ spend_metadata={"total_spend": 999},
+ )
+ self._emit_version(
+ document_id="other-model",
+ report_id="report",
+ source_product="linear",
+ inserted_at=self.base,
+ model=EmbeddingModelName.TEXT_EMBEDDING_3_LARGE_3072,
+ spend_metadata={"total_spend": 999},
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/source_spend/")
+ assert response.status_code == 200, response.content
+ with patch("products.signals.backend.spend_reporting.execute_hogql_query") as query:
+ cached = self.client.get(f"/api/projects/{self.team.id}/signals/source_spend/")
+ query.assert_not_called()
+ assert cached.json() == response.json()
+ assert response.json() == [
+ {
+ "source_product": "github",
+ "source_type": "some_type",
+ "signal_count": 2,
+ "spend": {"total_spend": 17.125, "incomplete": True},
+ }
+ ]
+
+ @parameterized.expand([False, True])
+ def test_report_prices_only_current_signals_and_own_implementation(self, child_environment: bool) -> None:
+ if child_environment:
+ self.team = Team.objects.create(organization=self.organization, parent_team=self.team)
+ report = SignalReport.objects.create(team=self.team)
+ other_report = SignalReport.objects.create(team=self.team)
+ signal_id, moved_id = str(uuid.uuid4()), str(uuid.uuid4())
+ for signal, owner, inserted_at in [
+ (signal_id, report.id, self.base),
+ (moved_id, report.id, self.base),
+ (moved_id, other_report.id, self.base + timedelta(hours=1)),
+ ]:
+ self._emit_version(
+ document_id=signal, report_id=str(owner), source_product="github", inserted_at=inserted_at
+ )
+ amounts = [(signal_id, 12.125), (moved_id, 999)]
+ for _ in range(100):
+ extra_id = str(uuid.uuid4())
+ self._emit_version(
+ document_id=extra_id, report_id=str(report.id), source_product="github", inserted_at=self.base
+ )
+ amounts.append((extra_id, 1))
+ receipt_team = self.team.parent_team or self.team
+ SignalSpend.objects.for_team(self.team.id).bulk_create(
+ [
+ SignalSpend(
+ team=receipt_team, kind="ad-hoc", signal_id=signal, spend=amount, finalized_at=timezone.now()
+ )
+ for signal, amount in amounts
+ ]
+ )
+ SignalSpend.objects.for_team(self.team.id).create(
+ team=self.team,
+ kind="research",
+ signal_id=signal_id,
+ task_run_id=uuid.uuid4(),
+ spend=20,
+ accounting_failed=True,
+ )
+ SignalSpend.objects.for_team(self.team.id).create(
+ team=self.team,
+ kind="reviewer_triggered_implementation",
+ report=report,
+ task_run_id=uuid.uuid4(),
+ spend=50,
+ finalized_at=timezone.now(),
+ )
+ with CaptureQueriesContext(connection) as queries:
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/spend/")
+ assert response.status_code == 200, response.content
+ assert all(SignalReportArtefact._meta.db_table not in query["sql"] for query in queries.captured_queries)
+ assert response.json() == {
+ "generation": {"total_spend": 132.125, "incomplete": True},
+ "implementation": {"total_spend": 50, "incomplete": False},
+ "shared_scout_runs": {"total_spend": None, "incomplete": False},
+ }
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 44d26367e74c..c52b065789a9 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -158,6 +158,7 @@ from products.signals.backend.personal_ranking.config import PERSONAL_INBOX_RANK
from products.signals.backend.personal_ranking.serve import serve_personal_ranking
from products.signals.backend.pr_ci_status import pr_ci_statuses_for_references, rollup_ci_status
from products.signals.backend.presentation.scout_permissions import ScoutCanonicalTeamAccessPermission
+from products.signals.backend.presentation.spend import ReportSpendSerializer
from products.signals.backend.pull_requests import import_report_pull_requests
from products.signals.backend.quota import self_driving_quota_enforcement_enabled, self_driving_quota_gate
from products.signals.backend.ranking.access import can_view_inbox_ranking, user_flag_enabled
@@ -303,6 +304,7 @@ from products.signals.backend.slack_notification_targets import (
validate_slack_notification_target,
)
from products.signals.backend.source_suggestions import current_source_suggestion
+from products.signals.backend.spend_reporting import SpendReporting
from products.signals.backend.suggested_reviewer_index import report_ids_naming_reviewers
from products.signals.backend.task_attribution import TASK_ID_HEADER, resolve_request_attribution
from products.signals.backend.task_run_artefacts import ReportTaskCapExceeded
@@ -1846,7 +1848,7 @@ class SignalReportViewSet(
def safely_get_queryset(self, queryset):
if self.action == "read_state":
return queryset.filter(team=self.team).exclude(status=SignalReport.Status.DELETED)
- if self.action in {"viewed", "feedback_state", "feedback", "pr_ci_statuses", "refresh_metrics"}:
+ if self.action in {"viewed", "feedback_state", "feedback", "pr_ci_statuses", "refresh_metrics", "spend"}:
# None of these actions renders a report, so they skip the rendering annotations and
# prefetches every other action's serializer needs. `viewed` is passive telemetry fired
# right after the detail request that already rendered the report, `pr_ci_statuses` only
@@ -2002,6 +2004,7 @@ class SignalReportViewSet(
"bulk_claim",
"retrieve",
"signals",
+ "spend",
"refund",
"feedback",
"feedback_state",
@@ -2789,6 +2792,12 @@ class SignalReportViewSet(
"report_plans_map": {str(report.id): plan},
}
+ @extend_schema(responses=ReportSpendSerializer, operation_id="signals_report_spend")
+ @action(detail=True, methods=["get"], required_scopes=["signal_usage:read"])
+ def spend(self, request: Request, **kwargs: object) -> Response:
+ report = self.get_object()
+ return Response(ReportSpendSerializer(SpendReporting(self.team).report(report)).data)
+
def retrieve(self, request, *args, **kwargs):
with trial_state_errors():
store = trial_store_for_request(request, self.team_id)
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 62d4da530391..c521aa5f0ada 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -5175,6 +5175,25 @@ export interface ReportSignalsResponseApi {
signals: SignalNodeApi[]
}
+export interface SpendAmountApi {
+ /**
+ * Recorded usage in USD cents, before billing exemptions; null when untracked.
+ * @nullable
+ */
+ total_spend: number | null
+ /** Whether usage is still settling or accounting is incomplete. */
+ incomplete: boolean
+}
+
+export interface ReportSpendApi {
+ /** Usage for the report's backing signals, research and repository selection. */
+ generation: SpendAmountApi
+ /** Usage for implementation tasks owned by the report. */
+ implementation: SpendAmountApi
+ /** Full usage of scout runs that authored this report. Shared with all other output of those runs. */
+ shared_scout_runs: SpendAmountApi
+}
+
/**
* * `suppressed` - suppressed
* * `potential` - potential
@@ -10673,6 +10692,40 @@ export interface PatchedSignalSourceConfigApi {
readonly status?: SignalSourceSyncStatusEnumApi | null
}
+export interface SourceSpendApi {
+ /** Product that emitted the signals. */
+ source_product: string
+ /** Type of signals emitted by the source. */
+ source_type: string
+ /** Number of signals received in the last 30 days. */
+ signal_count: number
+ /** Accumulated processing usage on these signals, including later processing. */
+ spend: SpendAmountApi
+}
+
+export interface ScoutSpendApi {
+ /** Name of the scout skill. */
+ skill_name: string
+ /** Accumulated usage for this scout's runs in the period. */
+ spend: SpendAmountApi
+ /**
+ * Average recorded usage per tracked scout run in USD cents; null when no runs were tracked.
+ * @nullable
+ */
+ average_spend: number | null
+}
+
+export interface SpendOverviewApi {
+ /** Inclusive start of the rolling 30-day run window. */
+ period_start: string
+ /** Exclusive end of the rolling 30-day run window. */
+ period_end: string
+ /** Usage for each scout with runs in the period. */
+ scouts: ScoutSpendApi[]
+ /** Total scout run usage in the period. */
+ scout_spend: SpendAmountApi
+}
+
export interface SignalUserAutonomyConfigApi {
readonly id: string
readonly user: _UserApi
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 1a9346ac527a..4ec5b635f5cf 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -61,6 +61,7 @@ import type {
ReportReadStateRequestApi,
ReportReadStateResponseApi,
ReportSignalsResponseApi,
+ ReportSpendApi,
ReviewerExclusionApi,
ReviewerExclusionCreateApi,
ReviewerExclusionCreateResultApi,
@@ -183,6 +184,8 @@ import type {
SignalsScoutRunsRecentPerScoutParams,
SignalsScoutScratchpadSearchParams,
SignalsSourceConfigsListParams,
+ SourceSpendApi,
+ SpendOverviewApi,
SubmitMonitoringResultRequestApi,
SubmitMonitoringResultResponseApi,
} from './api.schemas'
@@ -1126,6 +1129,21 @@ export const signalsReportsSignalsRetrieve = async (
})
}
+export const getSignalsReportSpendUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${id}/spend/`
+}
+
+export const signalsReportSpend = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ReportSpendApi> => {
+ return apiMutator<ReportSpendApi>(getSignalsReportSpendUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getSignalsReportsStateCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/signals/reports/${id}/state/`
}
@@ -3372,6 +3390,28 @@ export const signalsSourceConfigsDestroy = async (
})
}
+export const getSignalsSourceSpendUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/signals/source_spend/`
+}
+
+export const signalsSourceSpend = async (projectId: string, options?: RequestInit): Promise<SourceSpendApi[]> => {
+ return apiMutator<SourceSpendApi[]>(getSignalsSourceSpendUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSignalsSpendOverviewUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/signals/spend/`
+}
+
+export const signalsSpendOverview = async (projectId: string, options?: RequestInit): Promise<SpendOverviewApi> => {
+ return apiMutator<SpendOverviewApi>(getSignalsSpendOverviewUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getUsersSignalAutonomyRetrieveUrl = (userId: string) => {
return `/api/users/${userId}/signal_autonomy/`
}
diff --git a/products/signals/frontend/inbox/components/cards/SignalRunCard.tsx b/products/signals/frontend/inbox/components/cards/SignalRunCard.tsx
index 6a50677cf12d..a3deb8e369ed 100644
--- a/products/signals/frontend/inbox/components/cards/SignalRunCard.tsx
+++ b/products/signals/frontend/inbox/components/cards/SignalRunCard.tsx
@@ -9,6 +9,7 @@ import { urls } from 'scenes/urls'
import { captureInboxRunOpened } from '../../inboxAnalytics'
import { SignalRun } from '../../types'
import { stripScoutPrefix } from '../../utils/scoutRunsWindow'
+import { RecordedSpend } from '../spend/RecordedSpend'
import { inboxCardRowClassName } from './inboxCardRowClassName'
import { resolveRunVariant, RunStatusIndicator } from './runStatusVariant'
@@ -51,6 +52,11 @@ export function SignalRunCard({ run }: { run: SignalRun }): JSX.Element {
<span>
Started <TZLabel time={run.created_at} className="tabular-nums align-baseline" />
</span>
+ {isScout && (
+ <span className="text-[11px] text-muted">
+ <RecordedSpend amount={run.total_spend} />
+ </span>
+ )}
</div>
</div>
</Link>
diff --git a/products/signals/frontend/inbox/components/config/AgentsRoster.test.tsx b/products/signals/frontend/inbox/components/config/AgentsRoster.test.tsx
index b182f2fc718d..917e2dde316a 100644
--- a/products/signals/frontend/inbox/components/config/AgentsRoster.test.tsx
+++ b/products/signals/frontend/inbox/components/config/AgentsRoster.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -48,6 +48,7 @@ describe('AgentsRoster', () => {
initKeaTests()
useMocks({
get: {
+ '/api/projects/:team_id/signals/source_spend/': () => [200, []],
'/api/projects/:team_id/signals/source_configs/': () => [200, { results: [] }],
'/api/projects/:team_id/vision/scanners/': () => [
200,
@@ -67,6 +68,69 @@ describe('AgentsRoster', () => {
})
afterEach(cleanup)
+ it.each([
+ { enabled: true, armed: true },
+ { enabled: true, armed: false },
+ { enabled: false, armed: true },
+ ])('gates source usage when enabled=$enabled and armed=$armed', async ({ enabled, armed }) => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PRODUCT_AUTONOMY], {
+ [FEATURE_FLAGS.PRODUCT_AUTONOMY]: true,
+ [FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY]: enabled,
+ })
+ const usageRequests = jest.fn()
+ useMocks({
+ get: {
+ '/api/projects/:team_id/signals/source_configs/': {
+ results: ['issue_created', 'issue_reopened', 'issue_spiking'].map((source_type) => ({
+ id: source_type,
+ source_product: 'error_tracking',
+ source_type,
+ enabled: armed,
+ config: {},
+ })),
+ },
+ '/api/projects/:team_id/signals/source_spend/': () => {
+ usageRequests()
+ return [
+ 200,
+ [
+ {
+ source_product: 'error_tracking',
+ source_type: 'issue_created',
+ signal_count: 1,
+ spend: { total_spend: 125, incomplete: false },
+ },
+ {
+ source_product: 'error_tracking',
+ source_type: 'issue_spiking',
+ signal_count: 1,
+ spend: { total_spend: 25, incomplete: false },
+ },
+ {
+ source_product: 'conversations',
+ source_type: 'ticket',
+ signal_count: 1,
+ spend: { total_spend: null, incomplete: true },
+ },
+ ],
+ ]
+ },
+ },
+ })
+ render(<AgentsRoster />)
+ const errorTracking = document.querySelector('[data-source="error_tracking"]') as HTMLElement
+ expect(await within(errorTracking).findByLabelText('Arm Error tracking')).toBeInTheDocument()
+ if (enabled && armed) {
+ expect(await within(errorTracking).findByText('$1.50')).toBeInTheDocument()
+ const support = document.querySelector('[data-source="conversations"]') as HTMLElement
+ expect(within(support).queryByText('Not tracked')).not.toBeInTheDocument()
+ expect(usageRequests).toHaveBeenCalledTimes(1)
+ } else {
+ expect(document.querySelector('[data-attr="source-spend"]')).toBeNull()
+ expect(usageRequests).not.toHaveBeenCalled()
+ }
+ })
+
it('keeps connected sources in the roster and connects from the inline catalog without losing the search', async () => {
useMocks({
get: {
diff --git a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
index 7350cc5167b0..033ff6ab009f 100644
--- a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
+++ b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
@@ -13,6 +13,8 @@ import {
Spinner,
} from '@posthog/lemon-ui'
+import { FlaggedFeature } from 'lib/components/FlaggedFeature'
+import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTagType } from 'lib/lemon-ui/LemonTag/LemonTag'
import type { CISignalsSyncStatusEnumApi } from 'products/engineering_analytics/frontend/generated/api.schemas'
@@ -22,6 +24,7 @@ import { sourceSteeringIsSet } from '../../logics/sourceSteeringModalLogic'
import { signalSourcesLogic } from '../../signalSourcesLogic'
import type { SourceProductDataStatus, SourceProductStatus } from '../../signalSourcesLogic'
import { SignalSourceConfig, SignalSourceConfigStatus, SignalSourceType, linearTeamIdsFromConfig } from '../../types'
+import { SourceSpendLabel } from '../spend/SourceSpendLabel'
import { AGENT_ROSTER_GROUPS, AgentRosterDefinition, AgentRosterGroup, AgentRosterSource } from './agentRosterMeta'
import { DataSourceSetupModal } from './DataSourceSetupModal'
import { LinearTeamsModal } from './LinearTeamsModal'
@@ -541,6 +544,11 @@ const AgentRow = memo(function AgentRow({
{enabledCount} of {entities.length} {agent.entityNoun} on
</span>
)}
+ {armed && !productOff && (
+ <FlaggedFeature flag={FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY}>
+ <SourceSpendLabel sourceProduct={agent.sourceProduct} />
+ </FlaggedFeature>
+ )}
{(loading || requiresSetup || hasMasterSwitch) && (
<div className={`flex shrink-0 justify-end ${warehouseSource ? 'w-20' : 'w-13'}`}>
{loading ? (
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx
index e6d78296d653..c79c9c732da5 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx
@@ -2,6 +2,8 @@ import { useValues } from 'kea'
import { Tooltip } from '@posthog/lemon-ui'
+import { FlaggedFeature } from 'lib/components/FlaggedFeature'
+import { FEATURE_FLAGS } from 'lib/constants'
import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
@@ -17,6 +19,7 @@ import {
ScoutRollup,
SCOUT_RUNS_PER_SCOUT_LABEL,
} from '../../../utils/scoutRunsWindow'
+import { ScoutSpendLabel } from '../../spend/ScoutSpendLabel'
import { ScoutStatusTag } from './ScoutBadges'
import { ScoutCadenceLabel } from './ScoutCadenceLabel'
import { ScoutNextRunLabel } from './ScoutNextRunLabel'
@@ -61,13 +64,13 @@ export function ScoutHealthStrip({
learnedCount: 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()
const runs = rollup?.runs ?? []
const failed = rollup?.failedCount ?? 0
- const costRollup = scoutCostRollups.get(config.skill_name)
// Shared with the run rows, so the strip cannot word the same report activity differently.
const reportLabel = filedOrAddedLabel(rollup?.authoredReportIds ?? [], rollup?.editedReportIds ?? [])
// Only an enabled scout has a next run; a paused one would otherwise carry an empty dash.
@@ -104,7 +107,7 @@ export function ScoutHealthStrip({
<Segment tooltip={`Runs this scout made in the ${SCOUT_RUNS_PER_SCOUT_LABEL}, quiet ones included.`}>
{runs.length > 0 ? (
<>
- <ScoutRosterRunBoxes skillName={config.skill_name} runs={runs} />
+ <ScoutRosterRunBoxes runs={runs} />
<span className="whitespace-nowrap tabular-nums">{pluralize(runs.length, 'run')}</span>
{/* The counts here and below change while the page is open, so each number
gets its own element — see "Rule 7" in frontend/src/AGENTS.md for what a
@@ -136,13 +139,24 @@ export function ScoutHealthStrip({
</Segment>
)}
- {costRollup && (
- <Segment
- tooltip={`What this scout spent on model calls in the ${scoutCostWindowLabel(costRollup.windowDays)}, and what that buys per run and per report.`}
- >
- <span className="whitespace-nowrap tabular-nums">{scoutCostLineParts(costRollup).join(' · ')}</span>
- </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>
+ )}
+ </>
+ }
+ >
+ <ScoutSpendLabel skillName={config.skill_name} />
+ </FlaggedFeature>
<Segment tooltip="Notes the team has left this scout, and entries it has written for itself.">
<span className="whitespace-nowrap tabular-nums">
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx
index 8dcdcaee82c7..e6965b054ea6 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx
@@ -3,6 +3,8 @@ import { memo } from 'react'
import { Link } from '@posthog/lemon-ui'
+import { FlaggedFeature } from 'lib/components/FlaggedFeature'
+import { FEATURE_FLAGS } from 'lib/constants'
import { cn } from 'lib/utils/css-classes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -11,6 +13,7 @@ import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
import { nextRunAt, SCOUT_GROUP_LABEL, ScoutRosterRow, scoutSubtitle } from '../../../utils/scoutGroups'
import { runStripEmptyLabel, scoutDisplayName } from '../../../utils/scoutRunsWindow'
import { inboxCardRowClassName } from '../../cards/inboxCardRowClassName'
+import { ScoutSpendLabel } from '../../spend/ScoutSpendLabel'
import { ScoutDeprecationBadge, ScoutExemptionBadge, ScoutLifecycleBadge } from './ScoutBadges'
import { ScoutCadenceLabel } from './ScoutCadenceLabel'
import { ScoutEnabledSwitch } from './ScoutConfigControls'
@@ -95,18 +98,27 @@ export const ScoutRosterCard = memo(function ScoutRosterCard({ row }: { row: Sco
</>
)}
</div>
- {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}
+ fallback={
+ <>
+ {costRollup && (
+ <div className="flex flex-wrap items-center text-xs leading-none text-tertiary select-none">
+ <ScoutCostLine rollup={costRollup} />
+ </div>
+ )}
+ </>
+ }
+ >
+ <ScoutSpendLabel skillName={config.skill_name} average />
+ </FlaggedFeature>
</div>
</Link>
<div className="flex shrink-0 items-center justify-between gap-4 @lg:justify-end @lg:self-stretch @lg:border-l @lg:border-primary @lg:pl-3">
{/* A fixed strip width on wide rows keeps every row's newest run on one vertical line. */}
<div className="flex min-w-0 justify-end @lg:w-52">
{runs.length > 0 ? (
- <ScoutRosterRunBoxes skillName={config.skill_name} runs={runs} />
+ <ScoutRosterRunBoxes runs={runs} />
) : (
// Until the runs request has landed once, an empty rollup means "not
// loaded", not "never ran"; the poll retries a failed load on its own. Past
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsx
index 4c17661f6883..afbe8e3d8959 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsx
@@ -1,28 +1,35 @@
import { useValues } from 'kea'
-import { memo } from 'react'
+import { memo, useMemo } from 'react'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
import { SignalScoutRunSummary } from '../../../types'
import { ScoutRunBoxes } from './ScoutRunBoxes'
-/**
- * A scout's run strip with that scout's costs. The cost subscription lives here, not in the card or
- * table that holds the strip, so a cost batch re-renders this small component and not the whole row.
- * `ScoutRunBoxes` then skips its render when the scout's cost slice kept its reference.
- */
export const ScoutRosterRunBoxes = memo(function ScoutRosterRunBoxes({
- skillName,
runs,
}: {
- skillName: string
runs: SignalScoutRunSummary[]
}): JSX.Element | null {
+ const enabled = useFeatureFlag('SELF_DRIVING_USAGE_DISPLAY')
const { scoutRunCostsByScout, expensiveRunCostThreshold } = useValues(scoutFleetLogic)
+ const costs = useMemo(
+ () =>
+ enabled
+ ? new Map(
+ runs.flatMap((run) =>
+ run.total_spend == null ? [] : [[run.run_id, run.total_spend / 100] as const]
+ )
+ )
+ : undefined,
+ [runs, enabled]
+ )
return (
<ScoutRunBoxes
runs={runs}
- costs={scoutRunCostsByScout.get(skillName)}
- costThreshold={expensiveRunCostThreshold}
+ costs={enabled ? costs : scoutRunCostsByScout.get(runs[0]?.skill_name ?? '')}
+ costThreshold={enabled ? undefined : expensiveRunCostThreshold}
/>
)
})
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx
index eed7047b7c94..5c497daf81b3 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx
@@ -30,6 +30,7 @@ import {
SCOUT_RUN_HISTORY_UNAVAILABLE,
SCOUT_RUNS_PER_SCOUT_LABEL,
} from '../../../utils/scoutRunsWindow'
+import { RecordedSpend } from '../../spend/RecordedSpend'
import { ScoutTimestamp } from './ScoutTimestamp'
// This pill matches any run that produced output, either a signal finding or report activity, so its
@@ -198,6 +199,9 @@ function FailedRunGroup({ runs, skillName }: { runs: SignalScoutRunSummary[]; sk
<span className="whitespace-nowrap text-[11px] text-warning">· timed out</span>
)}
<span className="min-w-0 flex-1 text-secondary">{scoutRunFailureLine(run, now)}</span>
+ <span className="text-[11px] text-muted">
+ <RecordedSpend amount={run.total_spend} />
+ </span>
<RunOutputTag run={run} />
{run.task_url && (
<Link
@@ -265,6 +269,9 @@ const ScoutRunRow = memo(function ScoutRunRow({
<RunGlyph run={run} />
<ScoutTimestamp time={run.started_at} />
{duration && <span className="whitespace-nowrap text-[11px] text-muted">· {duration}</span>}
+ <span className="text-[11px] text-muted">
+ <RecordedSpend amount={run.total_spend} />
+ </span>
{/* One colour per failure kind, matching the glyph — a red glyph next to amber text
read as two different states of the same run. */}
{failureKind && (
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx
index 08604f6f8a8e..3bc9f868fc7a 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx
@@ -3,6 +3,8 @@ import { useEffect, useRef } from 'react'
import { LemonButton, Link } from '@posthog/lemon-ui'
+import { FlaggedFeature } from 'lib/components/FlaggedFeature'
+import { FEATURE_FLAGS } from 'lib/constants'
import { urls } from 'scenes/urls'
import { captureScoutFleetViewed, captureScratchpadLinkClicked } from '../../../inboxAnalytics'
@@ -114,9 +116,17 @@ export function ScoutsRoster(): JSX.Element {
<ScoutsRosterList />
<div className="flex flex-col gap-1 pt-1">
<span className="text-xs text-muted">
- The totals above cover the {SCOUT_ROSTER_WINDOW_LABEL}. Each scout's run strip shows its{' '}
- {SCOUT_RUNS_PER_SCOUT_LABEL}, so scouts on different schedules stay comparable. New scouts are
- created as skills in your PostHog project, under the name you give them.{' '}
+ <FlaggedFeature
+ flag={FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY}
+ fallback={<span>The totals above cover the {SCOUT_ROSTER_WINDOW_LABEL}. </span>}
+ >
+ <span>
+ Run and report totals cover the {SCOUT_ROSTER_WINDOW_LABEL}. Usage covers the last 30
+ days.{' '}
+ </span>
+ </FlaggedFeature>
+ Each scout's run strip shows its {SCOUT_RUNS_PER_SCOUT_LABEL}, so scouts on different schedules stay
+ comparable. New scouts are created as skills in your PostHog project, under the name you give them.{' '}
<Link to={urls.inboxRuns()} data-attr="inbox-open-runs">
See every recent run
</Link>{' '}
diff --git a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx b/products/signals/frontend/inbox/components/detail/ReportDetail.tsx
index c373d1f2fbf9..efbe7d24c790 100644
--- a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx
+++ b/products/signals/frontend/inbox/components/detail/ReportDetail.tsx
@@ -13,7 +13,9 @@ import {
} from '@posthog/icons'
import { LemonBanner, LemonButton, LemonTabs, LemonSelect, Link } from '@posthog/lemon-ui'
+import { FlaggedFeature } from 'lib/components/FlaggedFeature'
import { TZLabel } from 'lib/components/TZLabel'
+import { FEATURE_FLAGS } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonMenu, LemonMenuItem } from 'lib/lemon-ui/LemonMenu'
import { addProjectIdIfMissing } from 'lib/utils/kea-router'
@@ -35,6 +37,7 @@ import { SignalReportActionabilityBadge } from '../badges/SignalReportActionabil
import { SignalReportBillingBadge } from '../badges/SignalReportBillingBadge'
import { SignalReportPriorityBadge } from '../badges/SignalReportPriorityBadge'
import { isStatusRedundantWithActionability, SignalReportStatusBadge } from '../badges/SignalReportStatusBadge'
+import { ReportSpendSection } from '../spend/ReportSpendSection'
import { CommitContent } from './artefactTypes'
import { DetailSection } from './DetailSection'
import { DiscussReportButton } from './DiscussReportButton'
@@ -517,6 +520,9 @@ export function InboxDetailFrame({
{/* The pull request picker (when present), then reviewers, runs, and activity. */}
{children}
<SuggestedReviewersSection report={report} />
+ <FlaggedFeature flag={FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY}>
+ <ReportSpendSection reportId={report.id} />
+ </FlaggedFeature>
<ReportTasksSection report={report} />
<ReportChecksSection report={report} />
<ReportActivitySection report={report} />
diff --git a/products/signals/frontend/inbox/components/spend/RecordedSpend.tsx b/products/signals/frontend/inbox/components/spend/RecordedSpend.tsx
new file mode 100644
index 000000000000..a5727a90720a
--- /dev/null
+++ b/products/signals/frontend/inbox/components/spend/RecordedSpend.tsx
@@ -0,0 +1,39 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
+const currency = new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+})
+
+export function RecordedSpend({
+ amount,
+ description,
+}: {
+ amount: number | null | undefined
+ description?: string
+}): JSX.Element | null {
+ const enabled = useFeatureFlag('SELF_DRIVING_USAGE_DISPLAY')
+ if (!enabled) {
+ return null
+ }
+ return (
+ <Tooltip
+ title={[
+ description,
+ amount == null
+ ? 'Usage was not recorded for this activity.'
+ : 'Recorded usage in USD, before credits and billing exemptions.',
+ ]
+ .filter(Boolean)
+ .join(' ')}
+ >
+ <span className="tabular-nums" translate="no">
+ {amount == null ? 'Not tracked' : currency.format(amount / 100)}
+ </span>
+ </Tooltip>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/spend/ReportSpendSection.tsx b/products/signals/frontend/inbox/components/spend/ReportSpendSection.tsx
new file mode 100644
index 000000000000..b03db29e754c
--- /dev/null
+++ b/products/signals/frontend/inbox/components/spend/ReportSpendSection.tsx
@@ -0,0 +1,58 @@
+import { useActions, useValues } from 'kea'
+
+import { IconReceipt } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { reportSpendLogic } from '../../logics/reportSpendLogic'
+import { DetailSection } from '../detail/DetailSection'
+import { RecordedSpend } from './RecordedSpend'
+
+export function ReportSpendSection({ reportId }: { reportId: string }): JSX.Element {
+ const { currentTeamId } = useValues(teamLogic)
+ const logic = reportSpendLogic({ teamId: currentTeamId ?? 0, reportId })
+ const { spend, spendLoading, failed } = useValues(logic)
+ const { refreshSpend } = useActions(logic)
+
+ return (
+ <DetailSection title="Usage" icon={<IconReceipt />}>
+ {failed ? (
+ <LemonBanner
+ type="error"
+ action={
+ <LemonButton onClick={() => refreshSpend()} loading={spendLoading}>
+ Retry
+ </LemonButton>
+ }
+ >
+ Couldn't load usage.
+ </LemonBanner>
+ ) : !spend ? (
+ <LemonSkeleton className="h-8 w-full" />
+ ) : (
+ <div className="flex flex-col gap-2 text-xs" data-attr="report-spend">
+ <div className="flex flex-wrap justify-between gap-2">
+ <span>Report generation</span>
+ <RecordedSpend amount={spend.generation.total_spend} />
+ </div>
+ {spend.implementation.total_spend !== null && (
+ <div className="flex flex-wrap justify-between gap-2">
+ <span>Implementation</span>
+ <RecordedSpend amount={spend.implementation.total_spend} />
+ </div>
+ )}
+ {spend.shared_scout_runs.total_spend !== null && (
+ <div className="flex flex-col gap-1">
+ <div className="flex flex-wrap justify-between gap-2">
+ <span>Authoring scout runs</span>
+ <RecordedSpend amount={spend.shared_scout_runs.total_spend} />
+ </div>
+ <span className="text-muted">Shared across all output of these runs.</span>
+ </div>
+ )}
+ </div>
+ )}
+ </DetailSection>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/spend/ScoutSpendLabel.tsx b/products/signals/frontend/inbox/components/spend/ScoutSpendLabel.tsx
new file mode 100644
index 000000000000..629b20379f87
--- /dev/null
+++ b/products/signals/frontend/inbox/components/spend/ScoutSpendLabel.tsx
@@ -0,0 +1,46 @@
+import { useValues } from 'kea'
+
+import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { selfDrivingSpendLogic } from '../../logics/selfDrivingSpendLogic'
+import { RecordedSpend } from './RecordedSpend'
+
+export function ScoutSpendLabel({
+ skillName,
+ average = false,
+}: {
+ skillName: string
+ average?: boolean
+}): JSX.Element | null {
+ const { currentTeamId } = useValues(teamLogic)
+ const logic = selfDrivingSpendLogic({ teamId: currentTeamId ?? 0 })
+ const { overview, spendByScout, averageSpendByScout, failed } = useValues(logic)
+
+ if (failed) {
+ return (
+ <Tooltip title="Couldn't load usage. Refresh the page to try again.">
+ <span className="text-xs text-muted">Usage unavailable</span>
+ </Tooltip>
+ )
+ }
+ if (!overview) {
+ return <LemonSkeleton className="h-3 w-32" />
+ }
+ if (average && !averageSpendByScout.has(skillName)) {
+ return null
+ }
+ const amount = (average ? averageSpendByScout : spendByScout).get(skillName)
+ return (
+ <span className="inline-flex flex-wrap items-center gap-x-1 text-xs text-secondary" data-attr="scout-spend">
+ <RecordedSpend
+ amount={amount === undefined ? (average ? null : 0) : amount}
+ description={
+ average ? 'Average usage across runs with recorded amounts in the last 30 days.' : undefined
+ }
+ />
+ <span>{average ? 'avg per run · last 30 days' : 'usage · last 30 days'}</span>
+ </span>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/spend/SourceSpendLabel.tsx b/products/signals/frontend/inbox/components/spend/SourceSpendLabel.tsx
new file mode 100644
index 000000000000..41f8cc67c889
--- /dev/null
+++ b/products/signals/frontend/inbox/components/spend/SourceSpendLabel.tsx
@@ -0,0 +1,33 @@
+import { useValues } from 'kea'
+
+import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { sourceSpendLogic } from '../../logics/sourceSpendLogic'
+import { RecordedSpend } from './RecordedSpend'
+
+export function SourceSpendLabel({ sourceProduct }: { sourceProduct: string }): JSX.Element {
+ const { currentTeamId } = useValues(teamLogic)
+ const { sources, failed, spendByProduct } = useValues(sourceSpendLogic({ teamId: currentTeamId ?? 0 }))
+
+ if (failed) {
+ return (
+ <Tooltip title="Couldn't load source usage. Refresh the page to try again.">
+ <span className="text-xs text-muted">Unavailable</span>
+ </Tooltip>
+ )
+ }
+ if (sources === null) {
+ return <LemonSkeleton className="h-3 w-10" />
+ }
+ const amount = spendByProduct.get(sourceProduct)
+ return (
+ <span className="shrink-0 whitespace-nowrap text-xs text-muted" data-attr="source-spend">
+ <RecordedSpend
+ amount={amount === undefined ? 0 : amount}
+ description="Accumulated processing usage for signals received in the last 30 days, including later research."
+ />
+ </span>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/spend/Spend.stories.tsx b/products/signals/frontend/inbox/components/spend/Spend.stories.tsx
new file mode 100644
index 000000000000..96b80ba9c2fb
--- /dev/null
+++ b/products/signals/frontend/inbox/components/spend/Spend.stories.tsx
@@ -0,0 +1,101 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { RecordedSpend } from './RecordedSpend'
+import { ReportSpendSection } from './ReportSpendSection'
+import { ScoutSpendLabel } from './ScoutSpendLabel'
+import { SourceSpendLabel } from './SourceSpendLabel'
+import { UsageOverview } from './UsageOverview'
+
+const meta: Meta = {
+ title: 'Scenes-App/Inbox/Usage',
+ parameters: {
+ mockDate: '2026-06-11',
+ featureFlags: [FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY],
+ testOptions: { waitForSelector: '[data-attr="report-spend"]' },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:id/signals/spend/': {
+ period_start: '2026-05-12T00:00:00Z',
+ period_end: '2026-06-11T00:00:00Z',
+ scout_spend: { total_spend: 131.625, incomplete: true },
+ scouts: [
+ {
+ skill_name: 'signals-scout-general',
+ spend: { total_spend: 131.625, incomplete: true },
+ average_spend: 32.90625,
+ },
+ ],
+ },
+ '/api/projects/:id/signals/source_spend/': [
+ {
+ source_product: 'error_tracking',
+ source_type: 'issue_created',
+ signal_count: 4,
+ spend: { total_spend: 162.75, incomplete: false },
+ },
+ {
+ source_product: 'github',
+ source_type: 'issue',
+ signal_count: 1,
+ spend: { total_spend: 0.125, incomplete: false },
+ },
+ {
+ source_product: 'linear',
+ source_type: 'issue',
+ signal_count: 1,
+ spend: { total_spend: null, incomplete: true },
+ },
+ ],
+ '/api/projects/:id/signals/reports/:reportId/spend/': {
+ generation: { total_spend: 162.75, incomplete: false },
+ implementation: { total_spend: 490, incomplete: true },
+ shared_scout_runs: { total_spend: 46.25, incomplete: false },
+ },
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj
+
+export const Overview: Story = {
+ render: () => (
+ <div className="flex max-w-2xl flex-col gap-6 p-4">
+ <ReportSpendSection reportId="example-report" />
+ <ScoutSpendLabel skillName="signals-scout-general" />
+ <ScoutSpendLabel skillName="signals-scout-general" average />
+ <div className="flex items-center justify-between gap-2">
+ <span>Error tracking</span>
+ <SourceSpendLabel sourceProduct="error_tracking" />
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <span>GitHub</span>
+ <SourceSpendLabel sourceProduct="github" />
+ </div>
+ <div className="flex items-center justify-between gap-2">
+ <span>Linear</span>
+ <SourceSpendLabel sourceProduct="linear" />
+ </div>
+ <div className="flex flex-wrap gap-4">
+ <RecordedSpend amount={0} />
+ <RecordedSpend amount={0.0001} />
+ </div>
+ </div>
+ ),
+}
+
+export const BySource: Story = {
+ parameters: { testOptions: { waitForSelector: '[data-attr="usage-overview"]' } },
+ render: () => (
+ <div className="max-w-xl p-4">
+ <UsageOverview />
+ </div>
+ ),
+}
diff --git a/products/signals/frontend/inbox/components/spend/UsageOverview.tsx b/products/signals/frontend/inbox/components/spend/UsageOverview.tsx
new file mode 100644
index 000000000000..a57149a08a4a
--- /dev/null
+++ b/products/signals/frontend/inbox/components/spend/UsageOverview.tsx
@@ -0,0 +1,62 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonSkeleton, LemonTable } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { UsageBucket, usageOverviewLogic } from '../../logics/usageOverviewLogic'
+import { SignalSourceProduct } from '../../types'
+import { getSourceProductMeta } from '../badges/sourceProductIcons'
+import { RecordedSpend } from './RecordedSpend'
+
+export function UsageOverview(): JSX.Element {
+ const { currentTeamId } = useValues(teamLogic)
+ const logic = usageOverviewLogic({ teamId: currentTeamId ?? 0 })
+ const { buckets, loading, failed } = useValues(logic)
+ const { loadUsage } = useActions(logic)
+
+ if (failed) {
+ return (
+ <LemonBanner type="error" action={<LemonButton onClick={loadUsage}>Retry</LemonButton>}>
+ Couldn't load usage.
+ </LemonBanner>
+ )
+ }
+ if (loading) {
+ return <LemonSkeleton className="h-32 w-full" />
+ }
+ return (
+ <div data-attr="usage-overview">
+ <LemonTable<UsageBucket>
+ dataSource={buckets}
+ rowKey="sourceProduct"
+ size="small"
+ columns={[
+ {
+ title: 'Source',
+ key: 'source',
+ render: (_, { sourceProduct }) =>
+ sourceProduct === SignalSourceProduct.SignalsScout
+ ? 'Scouts'
+ : (getSourceProductMeta(sourceProduct)?.label ?? sourceProduct),
+ },
+ {
+ title: 'Usage',
+ key: 'usage',
+ align: 'right',
+ render: (_, { sourceProduct, amount }) => (
+ <RecordedSpend
+ amount={amount}
+ description={
+ sourceProduct === SignalSourceProduct.SignalsScout
+ ? 'Usage for scout runs started and scout signals received in the last 30 days, including later research.'
+ : 'Accumulated processing usage for signals received in the last 30 days, including later research.'
+ }
+ />
+ ),
+ },
+ ]}
+ />
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx
index 7921402ac2a7..2b0edda42c99 100644
--- a/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx
+++ b/products/signals/frontend/inbox/components/tabs/SettingsTab.tsx
@@ -1,5 +1,6 @@
import { useMountedLogic, useValues } from 'kea'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { GithubIntegration } from 'scenes/integrations/components/GithubIntegration'
import { urls } from 'scenes/urls'
@@ -11,9 +12,11 @@ import { SelfDrivingSection } from '../config/SelfDrivingSection'
import { SlackNotificationsSection } from '../config/SlackNotificationsSection'
import { InboxUsageWidget } from '../shell/InboxUsageWidget'
import { InstallationSetupSection } from '../shell/InstallationSetupSection'
+import { UsageOverview } from '../spend/UsageOverview'
import { SettingsSection } from './SettingsSection'
export function SettingsTab(): JSX.Element {
+ const usageEnabled = useFeatureFlag('SELF_DRIVING_USAGE_DISPLAY')
useMountedLogic(integrationsLogic)
// The usage widget renders nothing without the billing product, so the section title
// must hide with it rather than sit over an empty area.
@@ -28,6 +31,14 @@ export function SettingsTab(): JSX.Element {
>
<SelfDrivingSection />
</SettingsSection>
+ {usageEnabled && (
+ <SettingsSection
+ title="Usage"
+ description="Recorded usage for scout runs started and signals received in the last 30 days."
+ >
+ <UsageOverview />
+ </SettingsSection>
+ )}
<AgentSteeringSection />
<SettingsSection
title="Code access"
@@ -44,7 +55,10 @@ export function SettingsTab(): JSX.Element {
<SlackNotificationsSection />
</SettingsSection>
{(inboxUsageProduct != null || inboxUsageLoading) && (
- <SettingsSection title="Usage" description="Pull requests agents opened this billing period.">
+ <SettingsSection
+ title={usageEnabled ? 'Pull request usage' : 'Usage'}
+ description="Pull requests agents opened this billing period."
+ >
<InboxUsageWidget />
</SettingsSection>
)}
diff --git a/products/signals/frontend/inbox/inboxSceneLogic.test.ts b/products/signals/frontend/inbox/inboxSceneLogic.test.ts
index 7660d1e703c0..c888fc89b6ae 100644
--- a/products/signals/frontend/inbox/inboxSceneLogic.test.ts
+++ b/products/signals/frontend/inbox/inboxSceneLogic.test.ts
@@ -101,10 +101,23 @@ describe('mergeSignalRuns', () => {
it('tags kind and title per source (scout → skill_name, signal → report title)', () => {
const [scoutRow, signalRow] = mergeSignalRuns(
- [scoutRun({ task_id: 'scout', skill_name: 'signals-scout-surveys', created_at: '2026-06-11T11:00:00Z' })],
+ [
+ scoutRun({
+ task_id: 'scout',
+ skill_name: 'signals-scout-surveys',
+ created_at: '2026-06-11T11:00:00Z',
+ total_spend: 125.25,
+ status: 'in_progress',
+ }),
+ ],
[signalTask({ id: 'signal', title: 'Slow query', created_at: '2026-06-11T08:00:00Z' })]
)
- expect(scoutRow).toMatchObject({ kind: 'scout', title: 'signals-scout-surveys', report_id: null })
+ expect(scoutRow).toMatchObject({
+ kind: 'scout',
+ title: 'signals-scout-surveys',
+ report_id: null,
+ total_spend: 125.25,
+ })
expect(signalRow).toMatchObject({ kind: 'signal', title: 'Slow query', report_id: 'report-1' })
})
diff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.ts
index 17eefee53c5c..a39621fe90f7 100644
--- a/products/signals/frontend/inbox/inboxSceneLogic.ts
+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts
@@ -121,6 +121,7 @@ export function mergeSignalRuns(scoutRuns: SignalScoutRunSummary[], signalTasks:
(run): SignalRun => ({
task_id: run.task_id,
kind: 'scout',
+ total_spend: run.total_spend,
title: run.skill_name,
status: run.status,
report_id: null,
diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts
index d308bf769667..61975c0a5aa1 100644
--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts
@@ -27,6 +27,7 @@ import { REPORT_AI_PANEL_ID, inboxTaskKickoffLogic } from '../inboxTaskKickoffLo
import { EnrichedReviewer, SignalReport, SignalReportStatus } from '../types'
import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'
import { ReportTaskEntry, implementationSlotClaim, inboxReportDetailLogic } from './inboxReportDetailLogic'
+import { reportSpendLogic } from './reportSpendLogic'
const REPORT = { id: 'report-1', status: 'ready', title: 'Checkout errors spiked' } as unknown as SignalReport
@@ -39,6 +40,148 @@ const linkedTask = (purpose: ReportTaskPurpose, status: TaskRunStatus | null, pr
}) as unknown as ReportTaskEntry
describe('inboxReportDetailLogic', () => {
+ it.each([
+ { purpose: 'research', slowUsage: false },
+ { purpose: 'implementation', slowUsage: false },
+ { purpose: 'implementation', slowUsage: true },
+ ])(
+ 'loads usage once and refreshes while $purpose runs and settles (slow usage: $slowUsage)',
+ async ({ purpose, slowUsage }) => {
+ jest.useFakeTimers({
+ doNotFake: [
+ 'Date',
+ 'performance',
+ 'queueMicrotask',
+ 'setTimeout',
+ 'clearTimeout',
+ 'setImmediate',
+ 'clearImmediate',
+ 'nextTick',
+ ],
+ })
+ let status = TaskRunStatus.IN_PROGRESS
+ let amount = 125
+ let releaseSignals!: () => void
+ const pendingSignals = new Promise<void>((resolve) => {
+ releaseSignals = resolve
+ })
+ let pendingUsage: Promise<void> | undefined
+ let releaseUsage: (() => void) | undefined
+ let notifyUsageStarted = (): void => {}
+ const usageRequest = jest.fn(async () => {
+ const requestedAmount = amount
+ notifyUsageStarted()
+ await pendingUsage
+ return {
+ generation: { total_spend: purpose === 'research' ? requestedAmount : 0, incomplete: false },
+ implementation: {
+ total_spend: purpose === 'implementation' ? requestedAmount : null,
+ incomplete: false,
+ },
+ shared_scout_runs: { total_spend: null, incomplete: false },
+ }
+ })
+ useMocks({
+ get: {
+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },
+ '/api/projects/:team_id/signals/reports/:id/artefacts/': {
+ results: [
+ {
+ id: 'task-run',
+ type: 'task_run',
+ content: { task_id: 'active-task', product: 'signals', type: purpose },
+ created_at: '2026-01-01T00:00:00Z',
+ },
+ ],
+ },
+ '/api/projects/:team_id/tasks/:id/': () => ({
+ id: 'active-task',
+ latest_run: { id: 'active-run', status },
+ }),
+ '/api/projects/:team_id/signals/reports/:id/checks/': { results: [] },
+ '/api/projects/:team_id/signals/reports/:id/signals/': async () => {
+ await pendingSignals
+ return { signals: [] }
+ },
+ '/api/projects/:team_id/signals/reports/:id/spend/': usageRequest,
+ '/api/projects/:team_id/signals/reports/available_reviewers/': [],
+ },
+ })
+ initKeaTests()
+ const usage = reportSpendLogic({ teamId: MOCK_DEFAULT_TEAM.id, reportId: REPORT.id })
+ const logic = inboxReportDetailLogic({ reportId: REPORT.id, report: REPORT })
+ usage.mount()
+ logic.mount()
+ try {
+ await expectLogic(usage).toDispatchActions(['loadSpendSuccess'])
+ expect(usageRequest).toHaveBeenCalledTimes(1)
+ releaseSignals()
+ await expectLogic(logic).toDispatchActions(['loadReportSignalsSuccess']).toFinishAllListeners()
+ await expectLogic(usage).toFinishAllListeners()
+ expect(usageRequest).toHaveBeenCalledTimes(1)
+
+ expect(logic.values.shouldPollReportTasks).toBe(true)
+ amount = 250
+ let usageStarted: Promise<void> | undefined
+ if (slowUsage) {
+ usageStarted = new Promise<void>((resolve) => {
+ notifyUsageStarted = resolve
+ })
+ pendingUsage = new Promise<void>((resolve) => {
+ releaseUsage = resolve
+ })
+ }
+ await expectLogic(logic, () => jest.advanceTimersByTime(5000)).toDispatchActions([
+ 'loadReportArtefacts',
+ 'loadReportTasksSuccess',
+ ])
+ if (slowUsage) {
+ await usageStarted
+ for (let poll = 0; poll < 2; poll++) {
+ await expectLogic(logic, () => jest.advanceTimersByTime(5000)).toDispatchActions([
+ 'loadReportArtefacts',
+ 'loadReportTasksSuccess',
+ ])
+ }
+ expect(usage.values.spendLoading).toBe(true)
+ } else {
+ await expectLogic(usage).toFinishAllListeners()
+ }
+ expect(usageRequest).toHaveBeenCalledTimes(2)
+ expect(usage.values.spend?.[purpose === 'research' ? 'generation' : 'implementation'].total_spend).toBe(
+ slowUsage ? 125 : 250
+ )
+
+ status = TaskRunStatus.COMPLETED
+ amount = 375
+ await expectLogic(logic, () => jest.advanceTimersByTime(5000)).toDispatchActions([
+ 'loadReportArtefacts',
+ 'loadReportTasksSuccess',
+ ])
+ if (slowUsage) {
+ expect(usageRequest).toHaveBeenCalledTimes(2)
+ pendingUsage = undefined
+ releaseUsage?.()
+ }
+ await expectLogic(usage).toFinishAllListeners()
+ expect(usageRequest).toHaveBeenCalledTimes(3)
+ expect(usage.values.spend?.[purpose === 'research' ? 'generation' : 'implementation'].total_spend).toBe(
+ 375
+ )
+ expect(logic.values.shouldPollReportTasks).toBe(false)
+ jest.advanceTimersByTime(10000)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(usageRequest).toHaveBeenCalledTimes(3)
+ } finally {
+ releaseSignals()
+ releaseUsage?.()
+ logic.unmount()
+ usage.unmount()
+ jest.useRealTimers()
+ }
+ }
+ )
+
it.each([SignalReportStatus.READY, SignalReportStatus.MONITORING])(
'orders report runs and refreshes settled tasks appropriately in %s',
async (status) => {
diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts
index 5a762a829776..a485e4bcaff9 100644
--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts
+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts
@@ -93,6 +93,7 @@ import { isReportClaimable, reportClaimant, requestReportClaim } from '../utils/
import { reportPullRequests, primaryReportPullRequest, type ReportPullRequest } from '../utils/reportPullRequests'
import { withInboxWriteTimeout } from '../utils/writeTimeout'
import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'
+import { reportSpendLogic } from './reportSpendLogic'
/** Run statuses that count as terminal. Mirrors desktop `isTerminalStatus` / `ReportTasksSection`. */
const TERMINAL_RUN_STATUSES: TaskRunStatus[] = [TaskRunStatus.COMPLETED, TaskRunStatus.FAILED, TaskRunStatus.CANCELLED]
@@ -2197,6 +2198,14 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
cache.sidebarAlignmentPending = false
},
loadReportTasksSuccess: (_, __, ___, previousState) => {
+ const previousTasks = selectors.reportTasks(previousState)
+ const spendLogic = reportSpendLogic({
+ teamId: teamLogic.values.currentTeamId ?? 0,
+ reportId: props.reportId,
+ })
+ if (previousTasks !== null && spendLogic.isMounted()) {
+ spendLogic.actions.refreshSpend()
+ }
if (
cache.sidebarAlignmentPending &&
values.selectedTab === SidePanelTab.Max &&
@@ -2216,7 +2225,7 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
actions.warmReportDiscussion(values.report)
}
}
- const before = selectors.reportTasks(previousState) ?? []
+ const before = previousTasks ?? []
const settled = (values.reportTasks ?? []).some((entry) => {
const run = entry.task.latest_run
const prior = before.find((row) => row.task.id === entry.task.id)?.task.latest_run
diff --git a/products/signals/frontend/inbox/logics/reportSpendLogic.test.ts b/products/signals/frontend/inbox/logics/reportSpendLogic.test.ts
new file mode 100644
index 000000000000..4f32327676cd
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/reportSpendLogic.test.ts
@@ -0,0 +1,73 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import * as api from 'products/signals/frontend/generated/api'
+import type { ReportSpendApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { reportSpendLogic } from './reportSpendLogic'
+
+describe('reportSpendLogic', () => {
+ const receipt = (incomplete: boolean, amount = 125): ReportSpendApi => ({
+ generation: { total_spend: amount, incomplete },
+ implementation: { total_spend: null, incomplete: false },
+ shared_scout_runs: { total_spend: null, incomplete: false },
+ })
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ jest.useRealTimers()
+ })
+
+ it('refreshes unfinished receipts without task polling and stops when finalized', async () => {
+ const request = jest
+ .spyOn(api, 'signalsReportSpend')
+ .mockResolvedValueOnce(receipt(true))
+ .mockResolvedValue(receipt(false, 375))
+ const logic = reportSpendLogic({ teamId: 1, reportId: 'report-1' })
+ logic.mount()
+ try {
+ await expectLogic(logic).toDispatchActions(['loadSpendSuccess'])
+ expect(logic.values.spend?.generation.total_spend).toBe(125)
+
+ await jest.advanceTimersByTimeAsync(5000)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.spend?.generation.total_spend).toBe(375)
+
+ await jest.advanceTimersByTimeAsync(300000)
+ expect(request).toHaveBeenCalledTimes(2)
+ } finally {
+ logic.unmount()
+ }
+ })
+
+ it('backs off and caps retries for receipts that never finalize', async () => {
+ const request = jest.spyOn(api, 'signalsReportSpend').mockResolvedValue(receipt(true))
+ const logic = reportSpendLogic({ teamId: 1, reportId: 'report-1' })
+ logic.mount()
+ try {
+ await expectLogic(logic).toDispatchActions(['loadSpendSuccess'])
+ for (const [index, delay] of [5000, 10000, 20000, 30000, 30000, 30000].entries()) {
+ await jest.advanceTimersByTimeAsync(delay - 1)
+ expect(request).toHaveBeenCalledTimes(index + 1)
+ await jest.advanceTimersByTimeAsync(1)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(request).toHaveBeenCalledTimes(index + 2)
+ }
+ await jest.advanceTimersByTimeAsync(300000)
+ expect(request).toHaveBeenCalledTimes(7)
+
+ await expectLogic(logic, () => logic.actions.refreshSpend()).toDispatchActions(['loadSpendSuccess'])
+ expect(request).toHaveBeenCalledTimes(8)
+ } finally {
+ logic.unmount()
+ }
+ await jest.advanceTimersByTimeAsync(300000)
+ expect(request).toHaveBeenCalledTimes(8)
+ })
+})
diff --git a/products/signals/frontend/inbox/logics/reportSpendLogic.ts b/products/signals/frontend/inbox/logics/reportSpendLogic.ts
new file mode 100644
index 000000000000..e73e2b7f3c7a
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/reportSpendLogic.ts
@@ -0,0 +1,108 @@
+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { signalsReportSpend } from 'products/signals/frontend/generated/api'
+import type { ReportSpendApi } from 'products/signals/frontend/generated/api.schemas'
+
+const USAGE_RETRY_DELAY_MS = 5000
+const USAGE_RETRY_MAX_DELAY_MS = 30000
+const USAGE_RETRY_LIMIT = 6
+
+export interface ReportSpendLogicProps {
+ teamId: number
+ reportId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface reportSpendLogicValues {
+ failed: boolean
+ spend: ReportSpendApi | null
+ spendLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface reportSpendLogicActions {
+ loadSpend: () => any
+ loadSpendFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSpendSuccess: (
+ spend: ReportSpendApi,
+ payload?: any
+ ) => {
+ spend: ReportSpendApi
+ payload?: any
+ }
+ refreshSpend: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface reportSpendLogicMeta {
+ key: string
+}
+
+export type reportSpendLogicType = MakeLogicType<
+ reportSpendLogicValues,
+ reportSpendLogicActions,
+ ReportSpendLogicProps,
+ reportSpendLogicMeta
+>
+
+export const reportSpendLogic = kea<reportSpendLogicType>([
+ props({} as ReportSpendLogicProps),
+ key((props) => `${props.teamId}:${props.reportId}`),
+ path((key) => ['products', 'signals', 'reportSpendLogic', key]),
+ actions({ refreshSpend: true }),
+ loaders(({ props }) => ({
+ spend: [
+ null as ReportSpendApi | null,
+ { loadSpend: async () => signalsReportSpend(String(props.teamId), props.reportId) },
+ ],
+ })),
+ reducers({
+ failed: [false, { loadSpend: () => false, loadSpendSuccess: () => false, loadSpendFailure: () => true }],
+ }),
+ listeners(({ actions, cache, values }) => {
+ const refreshOrRetry = (): void => {
+ cache.disposables.dispose('unsettledSpendRetry')
+ if (cache.refreshPending) {
+ actions.refreshSpend()
+ return
+ }
+ const attempt = cache.retryAttempt ?? 0
+ if (
+ !Object.values(values.spend ?? {}).some((amount) => amount.incomplete) ||
+ attempt >= USAGE_RETRY_LIMIT
+ ) {
+ return
+ }
+ const delay = Math.min(USAGE_RETRY_DELAY_MS * 2 ** attempt, USAGE_RETRY_MAX_DELAY_MS)
+ cache.disposables.add(() => {
+ const timer = setTimeout(() => {
+ cache.retryAttempt = attempt + 1
+ actions.loadSpend()
+ }, delay)
+ return () => clearTimeout(timer)
+ }, 'unsettledSpendRetry')
+ }
+ return {
+ refreshSpend: () => {
+ cache.retryAttempt = 0
+ cache.disposables.dispose('unsettledSpendRetry')
+ cache.refreshPending = values.spendLoading
+ if (!values.spendLoading) {
+ actions.loadSpend()
+ }
+ },
+ loadSpendSuccess: refreshOrRetry,
+ loadSpendFailure: refreshOrRetry,
+ }
+ }),
+ afterMount(({ actions }) => actions.refreshSpend()),
+])
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
index 01093152f9e5..2dfecbe6f1d1 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
@@ -5,7 +5,8 @@ import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
import { ApiError } from 'lib/api-error'
-import { FIRST_REPORT_SCOUT_NAME } from 'lib/constants'
+import { FEATURE_FLAGS, FIRST_REPORT_SCOUT_NAME } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -1436,15 +1437,21 @@ describe('scoutFleetLogic', () => {
expect(jest.mocked(posthog.captureException).mock.calls.length > 0).toBe(reported)
})
- it('never asks for costs on behalf of a non-staff user', async () => {
+ 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' })])
- await mountAsStaff(false)
+ 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 () => {
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
index 3dd6c3480978..6335c141d38c 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
@@ -17,8 +17,9 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import { ApiError, isUnavailableEndpointError, shouldReportApiFailure } from 'lib/api-error'
-import { FIRST_REPORT_SCOUT_NAME } from 'lib/constants'
+import { FEATURE_FLAGS, 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'
@@ -65,6 +66,7 @@ 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'
export type ScoutEnabledFilter = 'all' | 'enabled' | 'disabled'
export type ScoutRosterSort = 'name' | 'status' | 'created' | 'updated' | 'last_run'
@@ -1776,9 +1778,13 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
listeners(({ actions, values, cache, sharedListeners }) => ({
loadScoutRunsSuccess: () => {
+ const spendLogic = selfDrivingSpendLogic({ teamId: teamLogic.values.currentTeamId ?? 0 })
+ 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) {
+ if (values.isStaff && !featureFlagLogic.values.featureFlags[FEATURE_FLAGS.SELF_DRIVING_USAGE_DISPLAY]) {
actions.loadScoutRunCosts()
actions.loadScoutCosts()
}
diff --git a/products/signals/frontend/inbox/logics/selfDrivingSpendLogic.ts b/products/signals/frontend/inbox/logics/selfDrivingSpendLogic.ts
new file mode 100644
index 000000000000..3255ecf57134
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/selfDrivingSpendLogic.ts
@@ -0,0 +1,84 @@
+import { MakeLogicType, afterMount, kea, key, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { signalsSpendOverview } from 'products/signals/frontend/generated/api'
+import type { SpendOverviewApi } from 'products/signals/frontend/generated/api.schemas'
+
+export interface SelfDrivingSpendLogicProps {
+ teamId: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface selfDrivingSpendLogicValues {
+ averageSpendByScout: Map<string, number | null>
+ failed: boolean
+ overview: SpendOverviewApi | null
+ overviewLoading: boolean
+ spendByScout: Map<string, number | null>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface selfDrivingSpendLogicActions {
+ loadOverview: () => any
+ loadOverviewFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadOverviewSuccess: (
+ overview: SpendOverviewApi,
+ payload?: any
+ ) => {
+ overview: SpendOverviewApi
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface selfDrivingSpendLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ averageSpendByScout: (overview: SpendOverviewApi | null) => Map<string, number | null>
+ spendByScout: (overview: SpendOverviewApi | null) => Map<string, number | null>
+ }
+}
+
+export type selfDrivingSpendLogicType = MakeLogicType<
+ selfDrivingSpendLogicValues,
+ selfDrivingSpendLogicActions,
+ SelfDrivingSpendLogicProps,
+ selfDrivingSpendLogicMeta
+>
+
+export const selfDrivingSpendLogic = kea<selfDrivingSpendLogicType>([
+ props({} as SelfDrivingSpendLogicProps),
+ key((props) => props.teamId),
+ path((key) => ['products', 'signals', 'selfDrivingSpendLogic', key]),
+ loaders(({ props }) => ({
+ overview: [
+ null as SpendOverviewApi | null,
+ { loadOverview: async () => signalsSpendOverview(String(props.teamId)) },
+ ],
+ })),
+ reducers({
+ failed: [
+ false,
+ { loadOverview: () => false, loadOverviewSuccess: () => false, loadOverviewFailure: () => true },
+ ],
+ }),
+ selectors({
+ averageSpendByScout: [
+ (s) => [s.overview],
+ (overview: SpendOverviewApi | null): Map<string, number | null> =>
+ new Map(overview?.scouts.map((scout) => [scout.skill_name, scout.average_spend])),
+ ],
+ spendByScout: [
+ (s) => [s.overview],
+ (overview: SpendOverviewApi | null) =>
+ new Map(overview?.scouts.map((scout) => [scout.skill_name, scout.spend.total_spend])),
+ ],
+ }),
+ afterMount(({ actions }) => actions.loadOverview()),
+])
diff --git a/products/signals/frontend/inbox/logics/sourceSpendLogic.ts b/products/signals/frontend/inbox/logics/sourceSpendLogic.ts
new file mode 100644
index 000000000000..991961d70dbf
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/sourceSpendLogic.ts
@@ -0,0 +1,84 @@
+import { MakeLogicType, afterMount, kea, key, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { signalsSourceSpend } from 'products/signals/frontend/generated/api'
+import type { SourceSpendApi } from 'products/signals/frontend/generated/api.schemas'
+
+export interface SourceSpendLogicProps {
+ teamId: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface sourceSpendLogicValues {
+ failed: boolean
+ sources: SourceSpendApi[] | null
+ sourcesLoading: boolean
+ spendByProduct: Map<string, number | null>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface sourceSpendLogicActions {
+ loadSources: () => any
+ loadSourcesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSourcesSuccess: (
+ sources: SourceSpendApi[],
+ payload?: any
+ ) => {
+ sources: SourceSpendApi[]
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface sourceSpendLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ spendByProduct: (sources: SourceSpendApi[] | null) => Map<string, number | null>
+ }
+}
+
+export type sourceSpendLogicType = MakeLogicType<
+ sourceSpendLogicValues,
+ sourceSpendLogicActions,
+ SourceSpendLogicProps,
+ sourceSpendLogicMeta
+>
+
+export const sourceSpendLogic = kea<sourceSpendLogicType>([
+ props({} as SourceSpendLogicProps),
+ key((props) => props.teamId),
+ path((key) => ['products', 'signals', 'sourceSpendLogic', key]),
+ loaders(({ props }) => ({
+ sources: [
+ null as SourceSpendApi[] | null,
+ { loadSources: async () => signalsSourceSpend(String(props.teamId)) },
+ ],
+ })),
+ reducers({
+ failed: [false, { loadSources: () => false, loadSourcesSuccess: () => false, loadSourcesFailure: () => true }],
+ }),
+ selectors({
+ spendByProduct: [
+ (s) => [s.sources],
+ (sources: SourceSpendApi[] | null): Map<string, number | null> => {
+ const totals = new Map<string, number | null>()
+ for (const source of sources ?? []) {
+ const previous = totals.get(source.source_product)
+ const amount = source.spend.total_spend
+ totals.set(
+ source.source_product,
+ previous == null && amount == null ? null : (previous ?? 0) + (amount ?? 0)
+ )
+ }
+ return totals
+ },
+ ],
+ }),
+ afterMount(({ actions }) => actions.loadSources()),
+])
diff --git a/products/signals/frontend/inbox/logics/usageOverviewLogic.test.ts b/products/signals/frontend/inbox/logics/usageOverviewLogic.test.ts
new file mode 100644
index 000000000000..23f44e7386e5
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/usageOverviewLogic.test.ts
@@ -0,0 +1,72 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { SourceSpendApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { usageOverviewLogic } from './usageOverviewLogic'
+
+describe('usageOverviewLogic', () => {
+ it.each([
+ {
+ name: 'groups source subtypes and combines scout signals with scout runs once',
+ sources: [
+ { source_product: 'error_tracking', source_type: 'issue_created', amount: 125 },
+ { source_product: 'error_tracking', source_type: 'issue_spiking', amount: 25 },
+ { source_product: 'signals_scout', source_type: 'cross_source_issue', amount: 13 },
+ { source_product: 'llm_analytics', source_type: 'evaluation_report', amount: 0 },
+ { source_product: 'linear', source_type: 'issue', amount: null },
+ ],
+ scoutAmount: 100,
+ expected: [
+ { sourceProduct: 'error_tracking', amount: 150 },
+ { sourceProduct: 'signals_scout', amount: 113 },
+ { sourceProduct: 'llm_analytics', amount: 0 },
+ { sourceProduct: 'linear', amount: null },
+ ],
+ },
+ {
+ name: 'shows zero scout usage when there is no activity',
+ sources: [],
+ scoutAmount: 0,
+ expected: [{ sourceProduct: 'signals_scout', amount: 0 }],
+ },
+ {
+ name: 'preserves untracked scout usage',
+ sources: [{ source_product: 'signals_scout', source_type: 'cross_source_issue', amount: null }],
+ scoutAmount: null,
+ expected: [{ sourceProduct: 'signals_scout', amount: null }],
+ },
+ ])('$name', async ({ sources, scoutAmount, expected }) => {
+ initKeaTests()
+ useMocks({
+ get: {
+ '/api/projects/:id/signals/source_spend/': sources.map(
+ ({ source_product, source_type, amount }): SourceSpendApi => ({
+ source_product,
+ source_type,
+ signal_count: 1,
+ spend: { total_spend: amount, incomplete: amount === null },
+ })
+ ),
+ '/api/projects/:id/signals/spend/': {
+ period_start: '2026-06-01T00:00:00Z',
+ period_end: '2026-07-01T00:00:00Z',
+ scout_spend: { total_spend: scoutAmount, incomplete: scoutAmount === null },
+ scouts: [],
+ },
+ },
+ })
+ const logic = usageOverviewLogic({ teamId: MOCK_DEFAULT_TEAM.id })
+ logic.mount()
+ try {
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.buckets).toEqual(expected)
+ } finally {
+ logic.unmount()
+ }
+ })
+})
diff --git a/products/signals/frontend/inbox/logics/usageOverviewLogic.ts b/products/signals/frontend/inbox/logics/usageOverviewLogic.ts
new file mode 100644
index 000000000000..2b235f35091d
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/usageOverviewLogic.ts
@@ -0,0 +1,101 @@
+import { LogicWrapper, MakeLogicType, actions, connect, kea, key, listeners, path, props, selectors } from 'kea'
+
+import type { SourceSpendApi, SpendOverviewApi } from '../../generated/api.schemas'
+import { SignalSourceProduct } from '../types'
+import { selfDrivingSpendLogic } from './selfDrivingSpendLogic'
+import { sourceSpendLogic } from './sourceSpendLogic'
+
+export interface UsageBucket {
+ sourceProduct: string
+ amount: number | null
+}
+
+export interface UsageOverviewLogicProps {
+ teamId: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface usageOverviewLogicValues {
+ overview: SpendOverviewApi | null // selfDrivingSpendLogic
+ scoutsFailed: boolean // selfDrivingSpendLogic
+ sources: SourceSpendApi[] | null // sourceSpendLogic
+ sourcesFailed: boolean // sourceSpendLogic
+ spendByProduct: Map<string, number | null> // sourceSpendLogic
+ buckets: UsageBucket[]
+ failed: boolean
+ loading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface usageOverviewLogicActions {
+ loadOverview: () => any // selfDrivingSpendLogic
+ loadSources: () => any // sourceSpendLogic
+ loadUsage: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface usageOverviewLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ loading: (sources: SourceSpendApi[] | null, overview: SpendOverviewApi | null) => boolean
+ failed: (sourcesFailed: boolean, scoutsFailed: boolean) => boolean
+ buckets: (spendByProduct: Map<string, number | null>, overview: SpendOverviewApi | null) => UsageBucket[]
+ }
+}
+
+export type usageOverviewLogicType = MakeLogicType<
+ usageOverviewLogicValues,
+ usageOverviewLogicActions,
+ UsageOverviewLogicProps,
+ usageOverviewLogicMeta
+>
+
+export const usageOverviewLogic: LogicWrapper<usageOverviewLogicType> = kea<usageOverviewLogicType>([
+ props({} as UsageOverviewLogicProps),
+ key((props: UsageOverviewLogicProps) => props.teamId),
+ path((key) => ['products', 'signals', 'usageOverviewLogic', key]),
+ connect((props: UsageOverviewLogicProps) => ({
+ values: [
+ sourceSpendLogic(props),
+ ['sources', 'spendByProduct', 'failed as sourcesFailed'],
+ selfDrivingSpendLogic(props),
+ ['overview', 'failed as scoutsFailed'],
+ ],
+ actions: [sourceSpendLogic(props), ['loadSources'], selfDrivingSpendLogic(props), ['loadOverview']],
+ })),
+ actions({ loadUsage: true }),
+ selectors({
+ loading: [
+ (s) => [s.sources, s.overview],
+ (sources: SourceSpendApi[] | null, overview: SpendOverviewApi | null): boolean =>
+ sources === null || overview === null,
+ ],
+ failed: [
+ (s) => [s.sourcesFailed, s.scoutsFailed],
+ (sourcesFailed: boolean, scoutsFailed: boolean): boolean => sourcesFailed || scoutsFailed,
+ ],
+ buckets: [
+ (s) => [s.spendByProduct, s.overview],
+ (spendByProduct: Map<string, number | null>, overview: SpendOverviewApi | null): UsageBucket[] => {
+ const amounts = new Map<string, number | null>(spendByProduct)
+ const scoutSignals = amounts.get(SignalSourceProduct.SignalsScout)
+ const scoutRuns = overview?.scout_spend.total_spend
+ amounts.set(
+ SignalSourceProduct.SignalsScout,
+ scoutSignals == null && scoutRuns == null ? null : (scoutSignals ?? 0) + (scoutRuns ?? 0)
+ )
+ return Array.from(amounts, ([sourceProduct, amount]) => ({ sourceProduct, amount })).sort(
+ (a, b) => (b.amount ?? -1) - (a.amount ?? -1) || a.sourceProduct.localeCompare(b.sourceProduct)
+ )
+ },
+ ],
+ }),
+ listeners(({ actions }) => ({
+ loadUsage: () => {
+ actions.loadSources()
+ actions.loadOverview()
+ },
+ })),
+])
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index a7a6c1a89490..92cff1769460 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -445,6 +445,7 @@ export type SignalRunKind = 'scout' | 'signal'
* standalone Tasks scene (`/tasks/{task_id}`).
*/
export interface SignalRun {
+ total_spend?: number | null
task_id: string
kind: SignalRunKind
/** Scout: the `signals-scout-*` skill code name (shown verbatim). Signal: the report title. */
diff --git a/products/signals/frontend/inbox/utils/scoutCosts.test.ts b/products/signals/frontend/inbox/utils/scoutCosts.test.ts
index 92673a6c406f..7b325a0c3e47 100644
--- a/products/signals/frontend/inbox/utils/scoutCosts.test.ts
+++ b/products/signals/frontend/inbox/utils/scoutCosts.test.ts
@@ -71,10 +71,9 @@ describe('scoutCosts', () => {
'$1.86/day · $2.17/run · no reports',
],
[
- // A sub-cent rate at two decimals would read as "$0.00", which says the scout is free.
- 'four decimals on a sub-cent rate',
+ 'two decimals on a sub-cent rate',
{ spend_usd: 0.014, run_count: 2, priced_run_count: 2, reports_touched: 2 },
- '$0.0020/day · $0.0070/run · $0.0070/report',
+ '$0.00/day · $0.01/run · $0.01/report',
],
])('renders %s', (_name, scout, expected) => {
const rollup = computeScoutCostRollups(costs([{ skill_name: 'a', ...scout }])).get('a')!
diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts
index ca217d243d8f..d374a7bcba53 100644
--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts
+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts
@@ -79,11 +79,9 @@ describe('scoutRunsWindow report channel', () => {
})
describe('formatRunCost', () => {
- // A cheap run still cost something, and "$0.00" is exactly the number this readout exists
- // to replace, so anything under a cent gets the digits to show it.
it.each<[number, string]>([
[4.0327, '$4.03'],
- [0.0042, '$0.0042'],
+ [0.0042, '$0.00'],
[0, '$0.00'],
])('%s → %s', (cost, expected) => {
expect(formatRunCost(cost)).toEqual(expected)
diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
index 3fe9f157674a..0245cea8ff5c 100644
--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
@@ -195,7 +195,7 @@ export function formatRunDuration(seconds: number | null): string {
* decimals it would read as "$0.00", which says the run was free.
*/
export function formatRunCost(costUsd: number): string {
- return humanFriendlyCurrency(costUsd, costUsd > 0 && costUsd < 0.01 ? 4 : 2)
+ return humanFriendlyCurrency(costUsd, 2)
}
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 23866188e946..27aec3391d5a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -688,6 +688,7 @@ export namespace Schemas {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
@@ -810,6 +811,7 @@ export namespace Schemas {
SessionRecordingPlaylist: 'session_recording_playlist',
SharingConfiguration: 'sharing_configuration',
SignalScout: 'signal_scout',
+ SignalUsage: 'signal_usage',
Stamphog: 'stamphog',
StreamlitApp: 'streamlit_app',
Subscription: 'subscription',
@@ -932,6 +934,7 @@ export namespace Schemas {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
@@ -1177,6 +1180,7 @@ export namespace Schemas {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
@@ -1585,6 +1589,7 @@ export namespace Schemas {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
@@ -72959,6 +72964,7 @@ export namespace Schemas {
* * `session_recording_playlist` - session_recording_playlist
* * `sharing_configuration` - sharing_configuration
* * `signal_scout` - signal_scout
+ * * `signal_usage` - signal_usage
* * `stamphog` - stamphog
* * `streamlit_app` - streamlit_app
* * `subscription` - subscription
@@ -105924,6 +105930,25 @@ export namespace Schemas {
signals: SignalNode[];
}
+ export interface SpendAmount {
+ /**
+ * Recorded usage in USD cents, before billing exemptions; null when untracked.
+ * @nullable
+ */
+ total_spend: number | null;
+ /** Whether usage is still settling or accounting is incomplete. */
+ incomplete: boolean;
+ }
+
+ export interface ReportSpend {
+ /** Usage for the report's backing signals, research and repository selection. */
+ generation: SpendAmount;
+ /** Usage for implementation tasks owned by the report. */
+ implementation: SpendAmount;
+ /** Full usage of scout runs that authored this report. Shared with all other output of those runs. */
+ shared_scout_runs: SpendAmount;
+ }
+
/**
* * `get_it_merged` - Get it merged
* * `make_it_green` - Make it green
@@ -110166,6 +110191,18 @@ export namespace Schemas {
scopes: string[];
}
+ export interface ScoutSpend {
+ /** Name of the scout skill. */
+ skill_name: string;
+ /** Accumulated usage for this scout's runs in the period. */
+ spend: SpendAmount;
+ /**
+ * Average recorded usage per tracked scout run in USD cents; null when no runs were tracked.
+ * @nullable
+ */
+ average_spend: number | null;
+ }
+
export interface ScoutSuggestionRefresh {
/** The dispatched refresh workflow id. */
workflow_id: string;
@@ -118265,6 +118302,17 @@ export namespace Schemas {
webhook?: SourceSetupWebhook;
}
+ export interface SourceSpend {
+ /** Product that emitted the signals. */
+ source_product: string;
+ /** Type of signals emitted by the source. */
+ source_type: string;
+ /** Number of signals received in the last 30 days. */
+ signal_count: number;
+ /** Accumulated processing usage on these signals, including later processing. */
+ spend: SpendAmount;
+ }
+
/**
* Validation errors keyed by the source or mapped table ID. Valid sources are omitted.
*/
@@ -118320,6 +118368,17 @@ export namespace Schemas {
Bytes: 'bytes',
} as const;
+ export interface SpendOverview {
+ /** Inclusive start of the rolling 30-day run window. */
+ period_start: string;
+ /** Exclusive end of the rolling 30-day run window. */
+ period_end: string;
+ /** Usage for each scout with runs in the period. */
+ scouts: ScoutSpend[];
+ /** Total scout run usage in the period. */
+ scout_spend: SpendAmount;
+ }
+
/**
* Raw cached payload as stored in Redis, or null on a miss.
* @nullable
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index 253e1d3bb63b..961c6ac7ee4b 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -190,6 +190,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'sharing_configuration:write',
'signal_scout:read',
'signal_scout:write',
+ 'signal_usage:read',
+ 'signal_usage:write',
'stamphog:read',
'stamphog:write',
'streamlit_app:read',