:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): show what each scout costs per day, per run, and per report (#97623)
posthog[bot]93c85b337423
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex dc9ee802b214..609bb7912ac7 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7888,6 +7888,18 @@ snapshots:hash: v1.k794b7964.e9a1cd20e5412b583cf614d164efd96d78087779d49fe6c8bb722ba6765102c6.sZivNSlRdhLYc8CY0SVelWu6swaLkvai_KCpasuN7tcscenes-app-inbox-scoutconfigform--weekly-schedule--light:hash: v1.k794b7964.b305519fa776432d2e8d1686d536e09782a66f217c75ce2b37038343e3b8cef8.Rug7RUaqdbIMdQ1ra_OhS6bzMQJ6f-AIjdbTEJCeHmo+ scenes-app-inbox-scoutdetailview--scout-page--dark:+ hash: v1.k794b7964.087c9f8e7270660c414e1ae443c032dac44817cb099ed93dd81aa341ff658a7b.t5vsjylrvrYr-03aEMNg8ePJ3cgF2ITKlZRf9ZoT1ic+ scenes-app-inbox-scoutdetailview--scout-page--light:+ hash: v1.k794b7964.506dbf875fb885f91c6bf58bfedc7e597d6513ad9a1c3d065e74716d96200fed.mpI8nafsVcoPRVDcXspuyKsZEIXq1Cb0dDtbYIRfuxw+ scenes-app-inbox-scoutdetailview--scout-page-no-reports--dark:+ hash: v1.k794b7964.0783344b02a68556a4980a0d38d19d4690f71a7ee93a0f0e153d1e6459e977bb.pe0x-ea0w_x8Lp3secczCeswShZOwDXyZPSNYIjeCL4+ scenes-app-inbox-scoutdetailview--scout-page-no-reports--light:+ hash: v1.k794b7964.d19235babe1cb01ad1220fa6db8859fad964d926b75ae345868de144aa67c580.VvPbd_hWIQ8wFmK-iolWBAeKY8jMA2hYumfW2Pz3jhA+ scenes-app-inbox-scoutdetailview--scout-page-non-staff--dark:+ hash: v1.k794b7964.a2ebecea102d059f7764bef59f9e2291f25414fe78a177a44675164e4abc5d92.j04rYU9j-J2Gdafk9wBtOv3Ly2Rc6Unq3nm8WIs4WtA+ scenes-app-inbox-scoutdetailview--scout-page-non-staff--light:+ hash: v1.k794b7964.b326031e884274e8a06cc11b86f919a6817d5af7f559c71ffff6e145924c44a0.2nWL--TkwE632GlU_8y7cuUdpkWp24zRzwNldGTtpkcscenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--dark:hash: v1.k794b7964.afe2203f4dd53373a3203fcfa611b5b65555341bdc2fc7fd73c15c2d83914600.O4kSRnOgICuQDkyD2HJCwBXdzE-KwsfzWT98nm43_5Ascenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--light:@@ -7912,6 +7924,18 @@ snapshots:hash: v1.k794b7964.cb947603948fda90cc6fda9efc2e78e240efb013149e44fee03b2a4cc03b0b41.sH5fGdFy2ImPKL1Rl4GF9TmxfCvLqMSXYFrF83PFw0Uscenes-app-inbox-scoutsroster--roster--light:hash: v1.k794b7964.b00bf7fe96c22218a5ad7fc62fba676d095899f0e9bc4a5f54cffe8cb212a799.xPUahRQgcuZMoUDEt8wbSdryvS7tj6VZSKMZLXDY7FQ+ scenes-app-inbox-scoutsroster--roster-costs--dark:+ hash: v1.k794b7964.631bfee2fc44cb760e4c6ca2194293aa4b3e2f74d70e861d33df83a8889eb97c.QewtE63qQ0MOFGw-XocsPA9on4EBS1XabnS_XJTYJ5g+ scenes-app-inbox-scoutsroster--roster-costs--light:+ hash: v1.k794b7964.84d575f8fd1994a847a88ad3d5721bf8d8c48757d4baa2aea3dc8bff08a6c106.msXWGAdSdgGkTxF3cHDRUoU_EQ8Up5Pp-Awwgw3Z6jM+ scenes-app-inbox-scoutsroster--roster-costs-non-staff--dark:+ hash: v1.k794b7964.6a104e1f11d3d44a190714666d7db789d8479d6e3d0686089ead4138646f8b9d.K--bqCt042LLnR6YRVsShm9WOsdBgAdfbXmYdrd5dBk+ scenes-app-inbox-scoutsroster--roster-costs-non-staff--light:+ hash: v1.k794b7964.c54727de9306e93a3c6a20bf0f41719bdcef495e0945134201c8ad05ac2f8204.BdUoCVAR19TDO85c03ROxlPwBwhFjveixvMcvdsZfwk+ scenes-app-inbox-scoutsroster--roster-costs-table--dark:+ hash: v1.k794b7964.e413457fe157fc4119197fc4cf8155ffcd44a38f9ef89ffa928555bc796dc674.JPlNpamhAWxFX_aWQ5BBG7tCN5pTYK3wc8sqnHB6XWs+ scenes-app-inbox-scoutsroster--roster-costs-table--light:+ hash: v1.k794b7964.49b466a57f2d708dc7038ff2fa235a5d1f6070bfaf7587372dfded6d77bfccae.tgynCIm3V7nqUVNgHAcdLmdoQzXNZDyGQ0QnCGoIT7Iscenes-app-inbox-scoutsroster--roster-legacy--dark:hash: v1.k794b7964.5339804f4cc136f9700b3329b0121ab62f3008197dcb4ff7c91d714e1fbdbbb5.peuyX_VFezfUR5E8LAdqk4e3GZWeYZ8qhq1Xp6HNLncscenes-app-inbox-scoutsroster--roster-legacy--light:diff --git a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts b/products/signals/frontend/inbox/__mocks__/scoutConfigs.tsindex 838c459bb88c..63b2a0d43706 100644--- a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts+++ b/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts@@ -1,4 +1,5 @@import type {+ ScoutCostsApi,ScoutSuggestionItemApi,ScoutSuggestionSetApi,SignalScoutConfigApi,@@ -244,3 +245,24 @@ export function mockScoutSuggestionSet(overrides: Partial<ScoutSuggestionSetApi>...overrides,}}++/**+ * A cost row per scout, cycling the three cases the surfaces have to tell apart: a scout that spent+ * and filed reports, one that spent and filed nothing, and one whose runs had no spend attributed.+ */+export function mockScoutCosts(configs: SignalScoutConfigApi[]): ScoutCostsApi {+ return {+ window_days: 7,+ available: true,+ scouts: configs.map((config, index) => {+ const unpriced = index % 3 === 2+ return {+ skill_name: config.skill_name,+ spend_usd: unpriced ? 0 : 1.68 + index * 4.2,+ run_count: 14 + index,+ priced_run_count: unpriced ? 0 : 14,+ reports_touched: index % 3 === 1 ? 0 : 11,+ }+ }),+ }+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCostCell.test.ts b/products/signals/frontend/inbox/components/config/scouts/ScoutCostCell.test.tsnew file mode 100644index 000000000000..6ab89f355d5c--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCostCell.test.ts@@ -0,0 +1,40 @@+import { getNextSorting } from 'lib/lemon-ui/LemonTable/sorting'++import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'++import { computeScoutCostRollups } from '../../../utils/scoutCosts'+import { ScoutRosterRow } from '../../../utils/scoutGroups'+import { scoutCostColumns } from './ScoutCostCell'++function row(skillName: string): ScoutRosterRow {+ return { config: { skill_name: skillName } as SignalScoutConfig, group: 'working' }+}++describe('scoutCostColumns', () => {+ // `unpriced` had runs but nothing attributed, so it gets no rollup and none of the three rates.+ const rollups = computeScoutCostRollups({+ window_days: 7,+ available: true,+ scouts: [+ { skill_name: 'cheap', spend_usd: 0.7, run_count: 7, priced_run_count: 7, reports_touched: 7 },+ { skill_name: 'unpriced', spend_usd: 0, run_count: 3, priced_run_count: 0, reports_touched: 0 },+ { skill_name: 'pricey', spend_usd: 7, run_count: 7, priced_run_count: 7, reports_touched: 7 },+ ],+ })+ const rows = [row('cheap'), row('unpriced'), row('pricey')]++ it.each(['cost-per-day', 'cost-per-run', 'cost-per-report'])(+ 'sorts the biggest spender first and the scout with no number last on a first click of %s',+ (key) => {+ const column = scoutCostColumns(rollups, 7).find((candidate) => candidate.key === key)!+ // The order the table itself lands on for an unsorted column, so a change to either+ // the column's default or the table's fails here.+ const { order } = getNextSorting(null, key, false, column.defaultSortOrder)!+ const sorter = column.sorter as (a: ScoutRosterRow, b: ScoutRosterRow) => number++ const sorted = rows.slice().sort((a, b) => order * sorter(a, b))++ expect(sorted.map((sortedRow) => sortedRow.config.skill_name)).toEqual(['pricey', 'cheap', 'unpriced'])+ }+ )+})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCostCell.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCostCell.tsxnew file mode 100644index 000000000000..be65141e445c--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCostCell.tsx@@ -0,0 +1,76 @@+import { Tooltip } from '@posthog/lemon-ui'++import { LemonTableColumn } from 'lib/lemon-ui/LemonTable'++import { ScoutCostRollup, scoutCostWindowLabel } from '../../../utils/scoutCosts'+import { ScoutRosterRow } from '../../../utils/scoutGroups'+import { formatRunCost } from '../../../utils/scoutRunsWindow'++type CostRate = { unit: 'day' | 'run' | 'report'; of: (rollup: ScoutCostRollup) => number | null; tooltip: string }++const COST_RATES: CostRate[] = [+ { unit: 'day', of: (rollup) => rollup.perDay, tooltip: 'Spend over the window, divided by its days.' },+ { unit: 'run', of: (rollup) => rollup.perRun, tooltip: 'Spend over the runs that had spend attributed.' },+ {+ unit: 'report',+ of: (rollup) => rollup.perReport,+ tooltip: 'Spend over the reports the scout filed or added to. Blank when it produced none.',+ },+]++function ScoutCostCell({ value }: { value: number | null }): JSX.Element {+ if (value === null) {+ // The scout spent, but produced no report to price. A dash says that without claiming $0.00.+ return <span className="text-xs text-muted">–</span>+ }+ // The header carries the unit, so the cell is the money alone.+ return <span className="text-xs text-secondary tabular-nums">{formatRunCost(value)}</span>+}++/**+ * The three cost columns for the roster table, staff only. Sorting by `$/day` answers which scouts+ * the spend is in, and by `$/report` which are expensive for what they produce. A scout with no+ * priced run in the window has no rollup, so its cells stay blank.+ */+export function scoutCostColumns(+ rollups: Map<string, ScoutCostRollup>,+ windowDays: number+): LemonTableColumn<ScoutRosterRow, keyof ScoutRosterRow | undefined>[] {+ return COST_RATES.map(({ unit, of, tooltip }) => ({+ title: (+ <Tooltip title={`${tooltip} Over the ${scoutCostWindowLabel(windowDays)}.`}>+ <span>{`$/${unit}`}</span>+ </Tooltip>+ ),+ key: `cost-per-${unit}`,+ width: '7%',+ align: 'right' as const,+ // Descending first, so one click answers the question the column exists for: the biggest+ // spenders on top, the scouts with no number out of the way at the bottom. Ascending would+ // open with a block of blank cells.+ defaultSortOrder: -1 as const,+ sorter: (a: ScoutRosterRow, b: ScoutRosterRow) => {+ const left = sortValue(rollups, a, of)+ const right = sortValue(rollups, b, of)+ // Two rows without a number are equal, and subtracting one infinity from the other+ // would hand the table a NaN.+ return left === right ? 0 : left - right+ },+ render: (_: any, row: ScoutRosterRow) => {+ const rollup = rollups.get(row.config.skill_name)+ return rollup ? <ScoutCostCell value={of(rollup)} /> : <span />+ },+ }))+}++// A scout without a number sorts below every scout that has one in the descending direction, which+// is the direction a first click takes. Sorting ascending asks for the cheapest first, and lifts+// the unpriced scouts with it.+function sortValue(+ rollups: Map<string, ScoutCostRollup>,+ row: ScoutRosterRow,+ of: (rollup: ScoutCostRollup) => number | null+): number {+ const rollup = rollups.get(row.config.skill_name)+ return (rollup ? of(rollup) : null) ?? Number.NEGATIVE_INFINITY+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCostLine.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCostLine.tsxnew file mode 100644index 000000000000..99351a52fc48--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCostLine.tsx@@ -0,0 +1,26 @@+import { Tooltip } from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'++import { ScoutCostRollup, scoutCostLineParts, scoutCostWindowLabel } from '../../../utils/scoutCosts'+import { formatRunCost } from '../../../utils/scoutRunsWindow'++/**+ * What a scout costs, on one line: per day, per run, and per report. Staff only, and rendered only+ * where a rollup exists, so a scout with no priced run in the window shows nothing rather than zero.+ */+export function ScoutCostLine({ rollup }: { rollup: ScoutCostRollup }): JSX.Element {+ const tooltip = [+ `${formatRunCost(rollup.spendUsd)} in the ${scoutCostWindowLabel(rollup.windowDays)}`,+ `${pluralize(rollup.pricedRunCount, 'priced run')}`,+ rollup.reportsTouched > 0+ ? `${pluralize(rollup.reportsTouched, 'report')} filed or added to`+ : 'no reports filed or added to',+ ].join(' · ')++ return (+ <Tooltip title={tooltip}>+ <span className="tabular-nums">{scoutCostLineParts(rollup).join(' · ')}</span>+ </Tooltip>+ )+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsxindex fa29836ad53a..cc15ed22a44c 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsx@@ -11,7 +11,8 @@ import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signalsimport { captureScoutAction } from '../../../inboxAnalytics'import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'-import { scoutDisplayName, SCOUT_RUNS_PER_SCOUT, ScoutRollup } from '../../../utils/scoutRunsWindow'+import { scoutCostWindowLabel } from '../../../utils/scoutCosts'+import { formatRunCost, scoutDisplayName, SCOUT_RUNS_PER_SCOUT, ScoutRollup } from '../../../utils/scoutRunsWindow'import { ScoutStatusTag } from './ScoutBadges'import { ScoutCadenceLabel } from './ScoutCadenceLabel'import { ScoutEnabledSwitch } from './ScoutConfigControls'@@ -157,11 +158,40 @@ export function ScoutDetailHeader({<Metric value={edited} label="Reports edited" /><Metric value={learnedCount} label="Learned" /><Metric value={noteCount} label="Told" />+ <ScoutCostMetrics skillName={config.skill_name} /></div></div>)}+/**+ * What the scout cost over the window, and what that buys per run and per report. Staff only, and+ * absent while it has no priced run in the window, the same way the per-run tooltip omits a cost it+ * cannot attribute.+ */+function ScoutCostMetrics({ skillName }: { skillName: string }): JSX.Element | null {+ const { scoutCostRollups } = useValues(scoutFleetLogic)+ const rollup = scoutCostRollups.get(skillName)++ if (!rollup) {+ return null+ }++ return (+ <>+ <Metric+ value={formatRunCost(rollup.spendUsd)}+ label={`Cost · ${scoutCostWindowLabel(rollup.windowDays)}`}+ />+ <Metric value={formatRunCost(rollup.perRun)} label="Cost per run" />+ <Metric+ value={rollup.perReport === null ? 'No reports' : formatRunCost(rollup.perReport)}+ label="Cost per report"+ />+ </>+ )+}+/*** The one thing to do about a scout the scheduler has flagged, stated in the words of the reason it* recorded. A paused or warned scout is the only case where a page should tell you what to do, sodiff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsxnew file mode 100644index 000000000000..e126cb04e237--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsx@@ -0,0 +1,60 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++import type { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'++import { mswDecorator } from '~/mocks/browser'++import { mockScoutConfigs, mockScoutCosts, mockScoutRuns } from '../../../__mocks__/scoutConfigs'+import { ScoutDetailView } from './ScoutDetailView'++// One scout's page. Use this to check the stat strip, including the staff-only cost tiles and the+// spend line under it.++const SKILL_NAME = mockScoutConfigs[0].skill_name++const meta: Meta<typeof ScoutDetailView> = {+ title: 'Scenes-App/Inbox/ScoutDetailView',+ component: ScoutDetailView,+ args: { skillName: SKILL_NAME },+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-06-11',+ featureFlags: { [FEATURE_FLAGS.PRODUCT_AUTONOMY]: true, [FEATURE_FLAGS.INBOX_REDESIGN]: true },+ testOptions: { waitForLoadersToDisappear: false },+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:id/signals/scout/configs/': () => [200, mockScoutConfigs],+ '/api/projects/:id/signals/scout/runs/recent-per-scout/': () => [200, mockScoutRuns(mockScoutConfigs)],+ '/api/projects/:id/signals/scout/runs/costs/': () => [200, mockScoutCosts(mockScoutConfigs)],+ '/api/projects/:id/signals/scout/runs/findings/summary/': () => [200, null],+ '/api/projects/:id/signals/scout/metadata/current/': () => [200, null],+ '/api/projects/:id/signals/scout/scratchpad/': () => [200, []],+ '/api/projects/:id/signals/scout/notes/': () => [200, []],+ },+ }),+ ],+}+export default meta++type Story = StoryObj<typeof ScoutDetailView>++export const ScoutPage: Story = {}++// The same scout for a non-staff reader: no cost tiles, no spend line, and no request for either.+export const ScoutPageNonStaff: Story = {+ decorators: [+ mswDecorator({+ get: { '/api/users/@me/': () => [200, { ...MOCK_DEFAULT_USER, is_staff: false }] },+ }),+ ],+}++// A scout that spent but filed nothing: the third tile says so rather than pricing zero reports.+export const ScoutPageNoReports: Story = {+ args: { skillName: mockScoutConfigs[1].skill_name },+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsxindex 2d6a7f59bac0..fd01d0484266 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx@@ -13,7 +13,8 @@ import { scoutDetailLogic } from '../../../logics/scoutDetailLogic'import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'import { scoutNotesLogic } from '../../../logics/scoutNotesLogic'import { entriesForSkill, scratchpadLogic } from '../../../logics/scratchpadLogic'-import { SCOUT_NO_RECENT_RUNS, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'+import { ScoutCostRollup, scoutCostWindowLabel } from '../../../utils/scoutCosts'+import { formatRunCost, SCOUT_NO_RECENT_RUNS, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'import { ScoutDetailHeader, ScoutAttentionBanner } from './ScoutDetailHeader'import { ScoutEmissionCard } from './ScoutEmissionCard'import { ScoutLearnedPanel } from './ScoutLearnedPanel'@@ -145,8 +146,9 @@ function BackToScouts(): JSX.Element {/** The window's totals in one line, so the sections below don't each restate the same window. */function ScoutActivitySummary({ skillName }: { skillName: string }): JSX.Element {- const { rollups } = useValues(scoutFleetLogic)+ const { rollups, scoutCostRollups } = useValues(scoutFleetLogic)const rollup = rollups.get(skillName)+ const costRollup = scoutCostRollups.get(skillName)if (!rollup || rollup.runCount === 0) {return <span className="text-sm text-secondary">{SCOUT_NO_RECENT_RUNS}</span>@@ -170,10 +172,30 @@ function ScoutActivitySummary({ skillName }: { skillName: string }): JSX.Element{SCOUT_RUNS_PER_SCOUT_LABEL}</span><span className="text-sm text-secondary">{parts.join(' · ')}</span>+ {costRollup && <span className="text-sm text-secondary tabular-nums">{scoutSpendSummary(costRollup)}</span>}</div>)}+/**+ * What the scout spent over the cost window and what it produced for it, e.g.+ * "$1.68 across 14 priced runs · 11 reports filed or added to · $0.15 per report". Staff only, and+ * on its own line because it describes the cost window rather than the run window above it.+ *+ * The count is the priced runs rather than every run started, because it is the divisor behind the+ * "Cost per run" tile. It keeps the qualifier so it does not read as the activity count that the+ * run summary above states over its own window.+ */+function scoutSpendSummary(rollup: ScoutCostRollup): string {+ return [+ `${formatRunCost(rollup.spendUsd)} across ${pluralize(rollup.pricedRunCount, 'priced run')} in the ${scoutCostWindowLabel(rollup.windowDays)}`,+ rollup.reportsTouched > 0+ ? `${pluralize(rollup.reportsTouched, 'report')} filed or added to`+ : 'no reports filed or added to',+ ...(rollup.perReport === null ? [] : [`${formatRunCost(rollup.perReport)} per report`]),+ ].join(' · ')+}+/*** The Reports section: the inbox reports this scout authored or edited directly via the report* channel (`emit_report` / `edit_report`) in the recent window, newest-updated first. Distinct fromdiff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsxindex f26743142059..1f82d296a1a5 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx@@ -13,6 +13,7 @@ import { inboxCardRowClassName } from '../../cards/inboxCardRowClassName'import { ScoutLifecycleBadge } from './ScoutBadges'import { ScoutCadenceLabel } from './ScoutCadenceLabel'import { ScoutEnabledSwitch } from './ScoutConfigControls'+import { ScoutCostLine } from './ScoutCostLine'import { ScoutNextRunLabel } from './ScoutNextRunLabel'import { ScoutRunBoxes } from './ScoutRunBoxes'import { ScoutStatusDot } from './ScoutStatusDot'@@ -36,12 +37,19 @@ function MetaSeparator(): JSX.Element {*/export function ScoutRosterCard({ row }: { row: ScoutRosterRow }): JSX.Element {const { config, group } = row- const { rollups, updatingScoutIds, scoutRunsLoadedOnce, scoutRunCosts, expensiveRunCostThreshold } =- useValues(scoutFleetLogic)+ const {+ rollups,+ updatingScoutIds,+ scoutRunsLoadedOnce,+ scoutRunCosts,+ scoutCostRollups,+ expensiveRunCostThreshold,+ } = useValues(scoutFleetLogic)const { updateScoutConfig } = useActions(scoutFleetLogic)const { currentTeam } = useValues(teamLogic)const now = new Date()const rollup = rollups.get(config.skill_name)+ const costRollup = scoutCostRollups.get(config.skill_name)const runs = rollup?.runs ?? []const subtitle = scoutSubtitle(config, rollup, now)// Only enabled scouts have a next run; a paused one would otherwise carry an empty dash.@@ -90,6 +98,11 @@ export function ScoutRosterCard({ row }: { row: ScoutRosterRow }): JSX.Element {</>)}</div>+ {costRollup && (+ <div className="flex flex-wrap items-center text-xs leading-none text-tertiary select-none">+ <ScoutCostLine rollup={costRollup} />+ </div>+ )}</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">diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.stories.tsxindex 86390ee26831..1a8494a67cbb 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.stories.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.stories.tsx@@ -1,10 +1,12 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'+import type { Meta, StoryObj } from '@storybook/react'import { FEATURE_FLAGS } from 'lib/constants'import { mswDecorator } from '~/mocks/browser'-import { mockLargeScoutFleet, mockScoutConfigs, mockScoutRuns } from '../../../__mocks__/scoutConfigs'+import { mockLargeScoutFleet, mockScoutConfigs, mockScoutCosts, mockScoutRuns } from '../../../__mocks__/scoutConfigs'import { ScoutsRoster } from './ScoutsRoster'import { ScoutsRosterLegacy } from './ScoutsRosterLegacy'@@ -98,3 +100,34 @@ export const Narrow: Story = {}),],}++// Cost, staff only. The fleet mixes the three cases: a scout that spent and filed reports, one that+// spent and filed nothing, and one whose runs had no spend attributed and so shows no numbers.+const COST_MOCKS = mswDecorator({+ get: {+ '/api/projects/:id/signals/scout/configs/': () => [200, mockLargeScoutFleet],+ '/api/projects/:id/signals/scout/runs/recent-per-scout/': () => [200, mockScoutRuns(mockLargeScoutFleet)],+ '/api/projects/:id/signals/scout/runs/costs/': () => [200, mockScoutCosts(mockLargeScoutFleet)],+ },+})++export const RosterCosts: Story = {+ decorators: [COST_MOCKS],+}++// The same fleet for a non-staff reader: no cost line on any card, and no request for one.+export const RosterCostsNonStaff: Story = {+ decorators: [+ COST_MOCKS,+ mswDecorator({+ get: { '/api/users/@me/': () => [200, { ...MOCK_DEFAULT_USER, is_staff: false }] },+ }),+ ],+}++// The table roster with the cost columns: `$/day`, `$/run`, and `$/report` before the run strip.+export const RosterCostsTable: Story = {+ parameters: { featureFlags: LEGACY_FLAGS },+ render: () => <ScoutsRosterLegacy />,+ decorators: [COST_MOCKS],+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsxindex 3f5570beb108..218077b9a6b8 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx@@ -9,8 +9,10 @@ import { urls } from 'scenes/urls'import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'import { compareScoutsByName, SCOUT_GROUP_LABEL, SCOUT_GROUP_ORDER, ScoutRosterRow } from '../../../utils/scoutGroups'import { showsScoutOwnership } from '../../../utils/scoutOwners'+import { SCOUT_ROSTER_WINDOW_DAYS } from '../../../utils/scoutRunsWindow'import { ScoutCadenceLabel } from './ScoutCadenceLabel'import { ScoutEnabledSwitch } from './ScoutConfigControls'+import { scoutCostColumns } from './ScoutCostCell'import { ScoutNameCell } from './ScoutNameCell'import { ScoutNextRunLabel } from './ScoutNextRunLabel'import { ScoutOwnersCell } from './ScoutOwnersCell'@@ -30,8 +32,15 @@ import { ScoutStatusDot } from './ScoutStatusDot'* nothing to say about a canonical one.*/export function ScoutsRosterTable({ compact }: { compact: boolean }): JSX.Element {- const { rosterScouts, rollups, updatingScoutIds, scoutRunsLoadedOnce, scoutRunCosts, expensiveRunCostThreshold } =- useValues(scoutFleetLogic)+ const {+ rosterScouts,+ rollups,+ updatingScoutIds,+ scoutRunsLoadedOnce,+ scoutRunCosts,+ scoutCostRollups,+ expensiveRunCostThreshold,+ } = useValues(scoutFleetLogic)const { updateScoutConfig } = useActions(scoutFleetLogic)if (rosterScouts.length === 0) {@@ -41,6 +50,9 @@ export function ScoutsRosterTable({ compact }: { compact: boolean }): JSX.Elemen// Only a custom scout can carry an owner, so a fleet of canonical scouts would get a header over// a column of blanks. It keeps the exact column set and widths it had before owners existed.const showOwners = !compact && rosterScouts.some((row) => showsScoutOwnership(row.config))+ // The cost response covers the whole team, so it can hold spend for a scout the filters hide+ // and for one whose config is gone. Ask the visible rows instead of counting the rollups.+ const showCosts = !compact && rosterScouts.some((row) => scoutCostRollups.has(row.config.skill_name))const width = compact? { scout: '40%', status: '26%', cadence: '12%', nextRun: '12%', runs: '20%', enabled: '14%' }: showOwners@@ -128,6 +140,10 @@ export function ScoutsRosterTable({ compact }: { compact: boolean }): JSX.Elemen</span>),},+ // Cost sits before the run strip, and drops out of the compact layout with the+ // other detail columns. Absent for everyone but staff, and while no scout on the+ // roster has a priced run in the window.+ ...(showCosts ? scoutCostColumns(scoutCostRollups, SCOUT_ROSTER_WINDOW_DAYS) : []),{// "Recent runs" doesn't fit the compact column, and a right-aligned header clips// from its left — it would read as "ent runs".diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.tsindex 6d199e75faf6..5615015ae41d 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts@@ -17,10 +17,11 @@ import {signalsScoutConfigList,signalsScoutConfigSync,signalsScoutConfigUpdate,+ signalsScoutRunsCosts,signalsScoutRunsRecentPerScout,signalsScoutRunsTokenCosts,} from 'products/signals/frontend/generated/api'-import type { SignalScoutConfigApi, UserBasicApi } from 'products/signals/frontend/generated/api.schemas'+import type { ScoutCostsApi, SignalScoutConfigApi, UserBasicApi } from 'products/signals/frontend/generated/api.schemas'import { SignalScoutRunSummary } from '../types'import { scoutFleetLogic } from './scoutFleetLogic'@@ -34,6 +35,7 @@ jest.mock('products/signals/frontend/generated/api', () => ({signalsScoutConfigUpdate: jest.fn(),signalsScoutRunsFindingsSummary: jest.fn(),signalsScoutRunsList: jest.fn(),+ signalsScoutRunsCosts: jest.fn(),signalsScoutRunsRecentPerScout: jest.fn(),signalsScoutRunsTokenCosts: jest.fn(),}))@@ -50,6 +52,7 @@ const mockSignalsScoutRunsRecentPerScout = signalsScoutRunsRecentPerScout as jesconst mockSignalsScoutRunsTokenCosts = signalsScoutRunsTokenCosts as jest.MockedFunction<typeof signalsScoutRunsTokenCosts>+const mockSignalsScoutRunsCosts = signalsScoutRunsCosts as jest.MockedFunction<typeof signalsScoutRunsCosts>const BASE_CONFIG: SignalScoutConfigApi = {id: 'config-1',@@ -132,6 +135,7 @@ describe('scoutFleetLogic', () => {mockSignalsScoutConfigUpdate.mockReset()mockSignalsScoutRunsRecentPerScout.mockReset().mockResolvedValue([])mockSignalsScoutRunsTokenCosts.mockReset().mockResolvedValue({ costs: [], available: true })+ mockSignalsScoutRunsCosts.mockReset().mockResolvedValue({ window_days: 7, scouts: [], available: true })logic = scoutFleetLogic()logic.mount()await expectLogic(logic).toFinishAllListeners()@@ -995,6 +999,99 @@ describe('scoutFleetLogic', () => {await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess']).toFinishAllListeners()expect(mockSignalsScoutRunsTokenCosts).not.toHaveBeenCalled()+ expect(mockSignalsScoutRunsCosts).not.toHaveBeenCalled()+ })++ it('asks for per-scout cost over the roster window and rolls it up per scout', async () => {+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])+ mockSignalsScoutRunsCosts.mockResolvedValue({+ window_days: 7,+ available: true,+ scouts: [+ {+ skill_name: 'signals-scout-errors',+ spend_usd: 1.68,+ run_count: 14,+ priced_run_count: 14,+ reports_touched: 11,+ },+ ],+ })+ await mountAsStaff(true)++ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])++ expect(mockSignalsScoutRunsCosts).toHaveBeenCalledWith(String(MOCK_TEAM_ID), { window_days: 7 })+ expect(logic.values.scoutCostRollups.get('signals-scout-errors')?.perDay).toBeCloseTo(0.24)+ })++ it('keeps the numbers it has when a later cost read fails', async () => {+ // The rollups feed a line on every roster card, so blanking them over one failed poll+ // is worse than showing the last numbers until the next one answers.+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])+ mockSignalsScoutRunsCosts.mockResolvedValue({+ window_days: 7,+ available: true,+ scouts: [+ {+ skill_name: 'signals-scout-errors',+ spend_usd: 1.68,+ run_count: 14,+ priced_run_count: 14,+ reports_touched: 11,+ },+ ],+ })+ await mountAsStaff(true)+ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])++ // Deploy skew: a bundle that has this feature can reach a backend without the endpoint.+ mockSignalsScoutRunsCosts.mockRejectedValue(new ApiError('nope', 404))+ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])++ expect(logic.values.scoutCostRollups.get('signals-scout-errors')?.perDay).toBeCloseTo(0.24)+ expect(jest.mocked(posthog.captureException)).not.toHaveBeenCalled()+ })++ it('reuses the rollup map when a poll returns the same costs, and rebuilds it when one moves', async () => {+ // The runs poll re-reads the fleet cost every 60s against a 15-minute server cache, so+ // identical numbers are the normal answer. Every roster card subscribes to this map.+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])+ const costsResponse = (spendUsd: number): ScoutCostsApi => ({+ window_days: 7,+ available: true,+ scouts: [+ {+ skill_name: 'signals-scout-errors',+ spend_usd: spendUsd,+ run_count: 14,+ priced_run_count: 14,+ reports_touched: 11,+ },+ ],+ })++ mockSignalsScoutRunsCosts.mockResolvedValue(costsResponse(1.68))+ await mountAsStaff(true)+ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])+ const firstRollups = logic.values.scoutCostRollups++ // A distinct object carrying the same numbers, the way the cached window answers.+ mockSignalsScoutRunsCosts.mockResolvedValue(costsResponse(1.68))+ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])+ expect(logic.values.scoutCostRollups).toBe(firstRollups)++ // A real change must still land, so the reuse cannot be unconditional.+ mockSignalsScoutRunsCosts.mockResolvedValue(costsResponse(3.36))+ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutCostsSuccess'])+ expect(logic.values.scoutCostRollups).not.toBe(firstRollups)+ expect(logic.values.scoutCostRollups.get('signals-scout-errors')?.perDay).toBeCloseTo(0.48)})})})diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.tsindex 3673a729bedb..33282c3b6d8b 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts@@ -35,12 +35,14 @@ import {signalsScoutMetadataGet,signalsScoutRunsFindingsSummary,signalsScoutRunsList,+ signalsScoutRunsCosts,signalsScoutRunsRecentPerScout,signalsScoutRunsTokenCosts,} from 'products/signals/frontend/generated/api'import type {FleetFindingsSummaryApi,PatchedSignalScoutConfigUpdateApi,+ ScoutCostsApi,ScoutMetadataApi,SignalScoutConfigApi,} from 'products/signals/frontend/generated/api.schemas'@@ -56,6 +58,7 @@ import {} from '../inboxAnalytics'import { SignalScoutRunSummary } from '../types'import { aiConsentDisabledReason } from '../utils/aiConsent'+import { computeScoutCostRollups, ScoutCostRollup } from '../utils/scoutCosts'import { compareScoutsByName, SCOUT_GROUP_ORDER, scoutGroup, ScoutGroupKey, ScoutRosterRow } from '../utils/scoutGroups'export type ScoutEnabledFilter = 'all' | 'enabled' | 'disabled'@@ -73,6 +76,7 @@ import {isSettledRun,rosterRunCosts,scoutDisplayName,+ SCOUT_ROSTER_WINDOW_DAYS,SCOUT_ROSTER_WINDOW_HOURS,SCOUT_RUNS_PER_SCOUT,SCOUT_RUNS_WINDOW_HOURS,@@ -241,6 +245,33 @@ function mergeCosts(previous: Map<string, number>, incoming: Map<string, number>return previous}+// Same idea for the fleet-wide cost response, which the runs poll re-reads every cycle. The window is+// cached server-side for 15 minutes, so an unchanged poll is the normal case, and `scoutCostRollups`+// builds the map every roster card subscribes to out of this object.+function reuseScoutCostsIfUnchanged(previous: ScoutCostsApi | null, next: ScoutCostsApi): ScoutCostsApi {+ if (+ !previous ||+ previous.window_days !== next.window_days ||+ previous.available !== next.available ||+ previous.scouts.length !== next.scouts.length+ ) {+ return next+ }+ // Rows arrive in the backend's skill-name order, so compare them pairwise. `skill_name` catches a+ // membership change that keeps the row count.+ const unchanged = next.scouts.every((scout, index) => {+ const before = previous.scouts[index]+ return (+ before.skill_name === scout.skill_name &&+ before.spend_usd === scout.spend_usd &&+ before.run_count === scout.run_count &&+ before.priced_run_count === scout.priced_run_count &&+ before.reports_touched === scout.reports_touched+ )+ })+ return unchanged ? previous : next+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scoutFleetLogicValues {dataProcessingAccepted: boolean // aiConsentLogic@@ -285,6 +316,9 @@ export interface scoutFleetLogicValues {scoutBannerMessage: string | nullscoutConfigs: SignalScoutConfig[] | nullscoutConfigsLoading: boolean+ scoutCostRollups: Map<string, ScoutCostRollup>+ scoutCosts: ScoutCostsApi | null+ scoutCostsLoading: booleanscoutEnabledFilter: ScoutEnabledFilterscoutFleetSyncOutcome: ScoutFleetSyncOutcomescoutFleetSyncRequested: boolean@@ -379,6 +413,21 @@ export interface scoutFleetLogicActions {scoutConfigs: SignalScoutConfigApi[] | nullpayload?: void}+ loadScoutCosts: (_: void) => void+ loadScoutCostsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadScoutCostsSuccess: (+ scoutCosts: ScoutCostsApi | null,+ payload?: void+ ) => {+ scoutCosts: ScoutCostsApi | null+ payload?: void+ }loadScoutMetadata: () => anyloadScoutMetadataFailure: (error: string,@@ -538,6 +587,7 @@ export interface scoutFleetLogicMeta {scoutRuns: SignalScoutRunSummary[],scoutRunCosts: Map<string, number>) => number | null+ scoutCostRollups: (scoutCosts: ScoutCostsApi | null) => Map<string, ScoutCostRollup>isStaff: (user: null | import('~/types').UserType) => booleanfleetSummary: (scoutConfigs: SignalScoutConfigApi[] | null,@@ -851,6 +901,38 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([},},],+ // What each scout spent over the roster's window, staff only. One request for the fleet,+ // answered from a 15-minute server cache, so it rides the runs load rather than a poll of+ // its own. The response is facts; `scoutCostRollups` turns them into the three rates.+ scoutCosts: [+ null as ScoutCostsApi | null,+ {+ loadScoutCosts: async (_: void, breakpoint) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId || !values.isStaff) {+ return values.scoutCosts+ }+ try {+ const costs = await signalsScoutRunsCosts(String(teamId), {+ window_days: SCOUT_ROSTER_WINDOW_DAYS,+ })+ breakpoint()+ return reuseScoutCostsIfUnchanged(values.scoutCosts, costs)+ } catch (error) {+ // Same posture as the per-run costs: a staff-only annotation degrades to no+ // number rather than reporting a failure the reader can do nothing about,+ // and the roster ships ahead of its endpoints.+ if (error instanceof ApiError) {+ if (shouldReportApiFailure(error) && !isUnavailableEndpointError(error)) {+ posthog.captureException(error)+ }+ return values.scoutCosts+ }+ throw error+ }+ },+ },+ ],runsWindow: [{ runs: [] as SignalScoutRunSummary[], complete: true } as {runs: SignalScoutRunSummary[]@@ -1087,6 +1169,10 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([(scoutRuns: SignalScoutRunSummary[], scoutRunCosts: Map<string, number>): number | null =>expensiveRunCostThreshold(rosterRunCosts(scoutRuns, scoutRunCosts)),],+ scoutCostRollups: [+ (s) => [s.scoutCosts],+ (scoutCosts: ScoutCostsApi | null): Map<string, ScoutCostRollup> => computeScoutCostRollups(scoutCosts),+ ],isStaff: [() => [userLogic.selectors.user],(user: null | import('~/types').UserType): boolean => user?.is_staff ?? false,@@ -1290,6 +1376,7 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([// never a cycle apart.if (values.isStaff) {actions.loadScoutRunCosts()+ actions.loadScoutCosts()}const evaluatedAt = new Date(values.rosterEvaluatedAt)const now = new Date()diff --git a/products/signals/frontend/inbox/utils/scoutCosts.test.ts b/products/signals/frontend/inbox/utils/scoutCosts.test.tsnew file mode 100644index 000000000000..92673a6c406f--- /dev/null+++ b/products/signals/frontend/inbox/utils/scoutCosts.test.ts@@ -0,0 +1,84 @@+import type { ScoutCostApi, ScoutCostsApi } from 'products/signals/frontend/generated/api.schemas'++import { computeScoutCostRollups, scoutCostLineParts } from './scoutCosts'++function costs(scouts: Partial<ScoutCostApi>[], overrides: Partial<ScoutCostsApi> = {}): ScoutCostsApi {+ return {+ window_days: 7,+ available: true,+ scouts: scouts.map((scout, index) => ({+ skill_name: `signals-scout-${index}`,+ spend_usd: 0,+ run_count: 0,+ priced_run_count: 0,+ reports_touched: 0,+ ...scout,+ })),+ ...overrides,+ }+}++describe('scoutCosts', () => {+ describe('computeScoutCostRollups', () => {+ it('divides spend by the window, by the priced runs, and by the reports touched', () => {+ const rollups = computeScoutCostRollups(+ costs([{ skill_name: 'a', spend_usd: 1.68, run_count: 14, priced_run_count: 12, reports_touched: 11 }])+ )++ const rollup = rollups.get('a')+ expect(rollup?.perDay).toBeCloseTo(0.24)+ // Runs with nothing attributed are not free runs, so they stay out of the divisor.+ expect(rollup?.perRun).toBeCloseTo(0.14)+ expect(rollup?.perReport).toBeCloseTo(0.1527)+ })++ it('leaves cost per report unset when the scout produced nothing, rather than pricing it at zero', () => {+ const rollups = computeScoutCostRollups(+ costs([{ skill_name: 'a', spend_usd: 13.02, run_count: 6, priced_run_count: 6, reports_touched: 0 }])+ )++ expect(rollups.get('a')?.perReport).toBeNull()+ expect(rollups.get('a')?.perDay).toBeCloseTo(1.86)+ })++ it.each<[string, Partial<ScoutCostApi>[], Partial<ScoutCostsApi>]>([+ // Nothing was attributed, so the spend is unknown, not zero: every surface omits it.+ ['no priced run in the window', [{ skill_name: 'a', run_count: 3, priced_run_count: 0 }], {}],+ [+ 'no internal project to read spend from',+ [{ skill_name: 'a', spend_usd: 1.5, run_count: 3, priced_run_count: 3 }],+ { available: false },+ ],+ ])('has no rollup when there is %s', (_name, scouts, overrides) => {+ expect(computeScoutCostRollups(costs(scouts, overrides)).size).toEqual(0)+ })++ it('has no rollup before the read lands', () => {+ expect(computeScoutCostRollups(null).size).toEqual(0)+ })+ })++ describe('scoutCostLineParts', () => {+ it.each<[string, Partial<ScoutCostApi>, string]>([+ [+ 'the three rates',+ { spend_usd: 1.68, run_count: 14, priced_run_count: 14, reports_touched: 11 },+ '$0.24/day · $0.12/run · $0.15/report',+ ],+ [+ 'the spend and no report to price',+ { spend_usd: 13.02, run_count: 6, priced_run_count: 6, reports_touched: 0 },+ '$1.86/day · $2.17/run · no reports',+ ],+ [+ // 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',+ { spend_usd: 0.014, run_count: 2, priced_run_count: 2, reports_touched: 2 },+ '$0.0020/day · $0.0070/run · $0.0070/report',+ ],+ ])('renders %s', (_name, scout, expected) => {+ const rollup = computeScoutCostRollups(costs([{ skill_name: 'a', ...scout }])).get('a')!+ expect(scoutCostLineParts(rollup).join(' · ')).toEqual(expected)+ })+ })+})diff --git a/products/signals/frontend/inbox/utils/scoutCosts.ts b/products/signals/frontend/inbox/utils/scoutCosts.tsnew file mode 100644index 000000000000..0da020c401fd--- /dev/null+++ b/products/signals/frontend/inbox/utils/scoutCosts.ts@@ -0,0 +1,70 @@+// Turns the cost endpoint's facts — spend, runs, priced runs, reports touched — into the three+// rates the roster and the scout page show. The API stays a fact table on purpose, so the+// definitions of cost per day, per run, and per report live here and nowhere else.++import type { ScoutCostsApi } from 'products/signals/frontend/generated/api.schemas'++import { formatRunCost } from './scoutRunsWindow'++export interface ScoutCostRollup {+ /** Spend attributed to the scout's runs in the window. */+ spendUsd: number+ windowDays: number+ /** Spend over the whole window, whatever part of it the scout was enabled for. */+ perDay: number+ /** Spend over the runs that had spend attributed, not over every run the scout started. */+ perRun: number+ /** Null when the scout filed or added to nothing, so there is no report to price. */+ perReport: number | null+ runCount: number+ pricedRunCount: number+ reportsTouched: number+}++/**+ * A rollup per scout that spent something in the window. A scout with no priced run gets no entry:+ * its spend is unknown rather than zero, the same way the per-run tooltip omits a cost it cannot+ * attribute, so every surface omits the line instead of printing `$0.00`.+ */+export function computeScoutCostRollups(costs: ScoutCostsApi | null): Map<string, ScoutCostRollup> {+ const rollups = new Map<string, ScoutCostRollup>()+ if (!costs?.available) {+ return rollups+ }+ for (const scout of costs.scouts) {+ if (scout.priced_run_count === 0) {+ continue+ }+ rollups.set(scout.skill_name, {+ spendUsd: scout.spend_usd,+ windowDays: costs.window_days,+ perDay: scout.spend_usd / costs.window_days,+ perRun: scout.spend_usd / scout.priced_run_count,+ perReport: scout.reports_touched > 0 ? scout.spend_usd / scout.reports_touched : null,+ runCount: scout.run_count,+ pricedRunCount: scout.priced_run_count,+ reportsTouched: scout.reports_touched,+ })+ }+ return rollups+}++/** A rate with its unit, e.g. "$0.24/day". Sub-cent rates keep four decimals, as run costs do. */+export function formatCostRate(value: number, unit: 'day' | 'run' | 'report'): string {+ return `${formatRunCost(value)}/${unit}`+}++/** The three rates as one line, e.g. "$0.24/day · $0.12/run · $0.15/report". */+export function scoutCostLineParts(rollup: ScoutCostRollup): string[] {+ return [+ formatCostRate(rollup.perDay, 'day'),+ formatCostRate(rollup.perRun, 'run'),+ // A scout that produced nothing still spent: say so, rather than pricing zero reports.+ rollup.perReport === null ? 'no reports' : formatCostRate(rollup.perReport, 'report'),+ ]+}++/** Window the numbers describe, for the labels and tooltips that name it. */+export function scoutCostWindowLabel(windowDays: number): string {+ return `last ${windowDays} days`+}