: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
import { pluralize } from 'lib/utils/strings'
import { SignalScoutRunSummary } from '../types'
import {
computeFleetSummary,
computeScoutRollups,
deriveRunOutcome,
formatRunCost,
filedOrAddedLabel,
groupScoutRuns,
mostRecentEmittedRuns,
runMatchesFilter,
runResponseCoversFleet,
runStripEmptyLabel,
SCOUT_RUNS_FLEET_COVERAGE_LIMIT,
dayTimeToWeeklyCron,
getScoutScheduleMode,
SCOUT_CUSTOM_CRON_SCHEDULE_MODE,
SCOUT_DAILY_AT_SCHEDULE_MODE,
SCOUT_WEEKLY_ON_SCHEDULE_MODE,
ScoutRunOutcome,
scoutCronScheduleError,
scoutDisplayName,
scoutReportActivityLabel,
scoutRunFailureLine,
scoutRunGroupKey,
scoutRunReportLabel,
weeklyCronToDayTime,
} from './scoutRunsWindow'
const NOW = new Date('2026-06-27T22:00:00Z')
function makeRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {
return {
run_id: 'run-1',
total_spend: null,
skill_name: 'signals-scout-dev-report-probe',
skill_version: 1,
status: 'completed',
metadata: {},
created_at: '2026-06-27T21:00:00Z',
started_at: '2026-06-27T21:00:00Z',
completed_at: '2026-06-27T21:02:00Z',
summary: '',
emitted_count: 0,
emitted_finding_ids: [],
emitted_report_ids: [],
edited_report_ids: [],
...overrides,
}
}
describe('scoutRunsWindow report channel', () => {
it.each([
['Checkout / daily digest', 'Checkout / daily digest'],
['', 'Daily digest'],
[undefined, 'Daily digest'],
])('uses the display name %s with a default for existing scouts', (display_name, expected) => {
expect(scoutDisplayName({ skill_name: 'signals-scout-daily-digest', display_name })).toBe(expected)
})
// The report channel (emit_report/edit_report) is invisible to emitted_count, so a report-authoring
// run used to read as "quiet / 0 signals emitted". These lock in that report activity counts as output.
describe('deriveRunOutcome', () => {
it.each<[string, Partial<SignalScoutRunSummary>, ScoutRunOutcome]>([
['authored a report, no findings → reported', { emitted_report_ids: ['r-1'] }, 'reported'],
['only edited a report, no findings → reported', { edited_report_ids: ['r-2'] }, 'reported'],
['no findings and no reports → quiet', {}, 'quiet'],
[
'findings win over report activity → emitted',
{ emitted_count: 2, emitted_finding_ids: ['f-1', 'f-2'], emitted_report_ids: ['r-1'] },
'emitted',
],
])('%s', (_name, overrides, expected) => {
expect(deriveRunOutcome(makeRun(overrides), NOW)).toEqual(expected)
})
})
describe('formatRunCost', () => {
it.each<[number, string]>([
[4.0327, '$4.03'],
[0.0042, '$0.00'],
[0, '$0.00'],
])('%s → %s', (cost, expected) => {
expect(formatRunCost(cost)).toEqual(expected)
})
})
describe('runStripEmptyLabel', () => {
it.each([
[{ loadedOnce: false, coversFleet: true }, '…'],
[{ loadedOnce: true, coversFleet: true }, 'No runs yet'],
// A fleet the response stops short of leaves this scout unread, so "No runs yet" would
// report lost history as a scout that never worked.
[{ loadedOnce: true, coversFleet: false }, 'History unavailable'],
])('reads %j as %s', (state, expected) => {
expect(runStripEmptyLabel(state)).toBe(expected)
})
it('treats a fleet past the covered count as uncovered', () => {
expect(runResponseCoversFleet(SCOUT_RUNS_FLEET_COVERAGE_LIMIT)).toBe(true)
expect(runResponseCoversFleet(SCOUT_RUNS_FLEET_COVERAGE_LIMIT + 1)).toBe(false)
})
})
describe('runMatchesFilter', () => {
it('keeps a report-authoring run out of Quiet and inside Emitted', () => {
const run = makeRun({ emitted_report_ids: ['r-1'] })
expect(runMatchesFilter(run, 'quiet')).toBe(false)
expect(runMatchesFilter(run, 'emitted')).toBe(true)
})
it('keeps a genuinely quiet run inside Quiet and out of Emitted', () => {
const run = makeRun()
expect(runMatchesFilter(run, 'quiet')).toBe(true)
expect(runMatchesFilter(run, 'emitted')).toBe(false)
})
})
describe('scoutReportActivityLabel', () => {
// Expected built via `pluralize` so the count↔word non-breaking space matches without hardcoding
// an invisible character in the literal. The ` · ` separator uses normal spaces.
it.each<[string, Partial<SignalScoutRunSummary>, string | null]>([
['authored only', { emitted_report_ids: ['r-1'] }, `${pluralize(1, 'report')} authored`],
['edited only (pluralized)', { edited_report_ids: ['r-1', 'r-2'] }, `${pluralize(2, 'report')} edited`],
[
'both authored and edited',
{ emitted_report_ids: ['r-1'], edited_report_ids: ['r-2'] },
`${pluralize(1, 'report')} authored · ${pluralize(1, 'report')} edited`,
],
['no report activity', {}, null],
])('%s', (_name, overrides, expected) => {
expect(scoutReportActivityLabel(makeRun(overrides))).toEqual(expected)
})
})
// The row tags read in the report channel's words, and a report both filed and later edited is
// one report — the header strip derives it the same way, so the two must not disagree.
describe('scoutRunReportLabel', () => {
it.each<[string, Partial<SignalScoutRunSummary>, string | null]>([
['filed only', { emitted_report_ids: ['r-1'] }, `Filed ${pluralize(1, 'report')}`],
['added to only', { edited_report_ids: ['r-1', 'r-2'] }, `Added to ${pluralize(2, 'report')}`],
[
'filed one and added to another',
{ emitted_report_ids: ['r-1'], edited_report_ids: ['r-2'] },
'Filed 1 · added to 1',
],
[
'filed then edited the same report counts once',
{ emitted_report_ids: ['r-1'], edited_report_ids: ['r-1'] },
`Filed ${pluralize(1, 'report')}`,
],
['no report activity', {}, null],
])('%s', (_name, overrides, expected) => {
expect(scoutRunReportLabel(makeRun(overrides))).toEqual(expected)
})
// The header strip shares this label, and hands it the rollup's deduped id sets rather
// than one run's arrays.
it('takes id sets, and drops a filed report from the added-to count', () => {
expect(filedOrAddedLabel(new Set(['r-1']), new Set(['r-1', 'r-2']))).toEqual('Filed 1 · added to 1')
})
})
describe('scoutRunFailureLine', () => {
// The close-out is agent prose, so its first line can open with any markdown marker. Each
// has to go before the sentence split, or the split stops on the marker's own punctuation.
it.each<[string, string, string]>([
['a heading', '## Stopped mid-plan\nEligibility is healthy. More.', 'Stopped mid-plan'],
['a bullet', '- Stopped mid-plan. More.', 'Stopped mid-plan.'],
['an ordered item', '1. Stopped mid-plan. More.', 'Stopped mid-plan.'],
['an ordered item in brackets', '1) Stopped mid-plan. More.', 'Stopped mid-plan.'],
['a decimal that is not a marker', '1.5s of runtime. More.', '1.5s of runtime.'],
])('takes the first sentence of a close-out opening with %s', (_name, summary, expected) => {
expect(scoutRunFailureLine(makeRun({ status: 'failed', summary }), NOW)).toBe(expected)
})
// The serializer sends the first line of the task's error message as `failure_reason`, so a
// failure that never got to its close-out still says what went wrong.
it.each<[string, Partial<SignalScoutRunSummary>, string]>([
[
'the recorded reason when the run wrote no close-out',
{
summary: '',
error: 'ToolError: the sandbox closed the connection\n at step 3',
failure_reason: 'ToolError: the sandbox closed the connection',
},
'ToolError: the sandbox closed the connection',
],
[
'the close-out ahead of the reason',
{
summary: 'Stopped mid-plan. More.',
error: 'ToolError: the sandbox closed the connection',
failure_reason: 'ToolError: the sandbox closed the connection',
},
'Stopped mid-plan.',
],
])('takes %s', (_name, overrides, expected) => {
expect(scoutRunFailureLine(makeRun({ status: 'failed', ...overrides }), NOW)).toBe(expected)
})
// A run killed at the deadline records no message, so the serializer derives a placeholder
// reason with a null `error`. The elapsed time says more than the placeholder does.
it('names the duration when the run never wrote a close-out', () => {
const run = makeRun({
status: 'failed',
summary: '',
error: null,
failure_reason: 'failed (no error message recorded)',
started_at: '2026-06-27T21:00:00Z',
completed_at: '2026-06-27T21:00:37Z',
})
expect(scoutRunFailureLine(run, NOW)).toBe('Ended after 37s without a close-out.')
})
})
// A scout's history is mostly quiet, so a flat list buries the failures anyone opened it for.
describe('groupScoutRuns', () => {
const quiet = (id: string): SignalScoutRunSummary => makeRun({ run_id: id })
const failed = (id: string): SignalScoutRunSummary => makeRun({ run_id: id, status: 'failed' })
const filed = (id: string): SignalScoutRunSummary => makeRun({ run_id: id, emitted_report_ids: ['r-1'] })
it('folds a run of quiet runs into one group and keeps them in order', () => {
const groups = groupScoutRuns([quiet('a'), quiet('b'), quiet('c')])
expect(groups).toHaveLength(1)
expect(groups[0]).toMatchObject({ kind: 'quiet' })
expect(groups[0].kind === 'quiet' && groups[0].runs.map((run) => run.run_id)).toEqual(['a', 'b', 'c'])
})
it('folds consecutive failures into one group', () => {
const groups = groupScoutRuns([failed('a'), failed('b'), failed('c')])
expect(groups).toHaveLength(1)
expect(groups[0].kind === 'failed' && groups[0].runs).toHaveLength(3)
})
it('never merges across a productive run, so a group only spans what it says it does', () => {
const groups = groupScoutRuns([quiet('a'), filed('b'), quiet('c'), failed('d'), quiet('e')])
expect(groups.map((group) => group.kind)).toEqual(['quiet', 'run', 'quiet', 'failed', 'quiet'])
})
it('never merges a failure into a quiet group', () => {
const groups = groupScoutRuns([quiet('a'), failed('b')])
expect(groups.map((group) => group.kind)).toEqual(['quiet', 'failed'])
})
it('keeps a lone quiet run as a group of one, so the list does not switch grammar', () => {
const groups = groupScoutRuns([quiet('a')])
expect(groups[0].kind === 'quiet' && groups[0].runs).toHaveLength(1)
})
// The detail view polls and prepends, so a group's key has to survive a newer run joining
// it. Otherwise React remounts the group and the reader's open rows close.
it('keys a folded group the same way once a newer run joins it', () => {
const [before] = groupScoutRuns([quiet('b'), quiet('c')])
const [after] = groupScoutRuns([quiet('a'), quiet('b'), quiet('c')])
expect(scoutRunGroupKey(after)).toEqual(scoutRunGroupKey(before))
})
})
describe('computeScoutRollups', () => {
it('dedupes report ids across runs into the authored/edited sets', () => {
const skill = 'signals-scout-dev-report-probe'
const runs = [
makeRun({ run_id: 'run-1', skill_name: skill, emitted_report_ids: ['r-1'] }),
// The same report is edited by a later run — must not double-count, and stays distinct
// from the authored set.
makeRun({ run_id: 'run-2', skill_name: skill, edited_report_ids: ['r-1'] }),
makeRun({ run_id: 'run-3', skill_name: skill, edited_report_ids: ['r-2'] }),
]
const rollup = computeScoutRollups(runs).get(skill)!
expect([...rollup.authoredReportIds]).toEqual(['r-1'])
expect([...rollup.editedReportIds].sort()).toEqual(['r-1', 'r-2'])
})
})
describe('mostRecentEmittedRuns', () => {
it('includes report-channel-only runs alongside emitted runs, excluding quiet ones', () => {
// The fleet findings page fetches this set — narrowing it back to `emitted_count > 0`
// would silently drop report-authoring runs, so their reports never get listed.
const runs = [
makeRun({ run_id: 'run-findings', emitted_count: 1, emitted_finding_ids: ['f-1'] }),
makeRun({ run_id: 'run-authored', emitted_report_ids: ['r-1'] }),
makeRun({ run_id: 'run-edited', edited_report_ids: ['r-2'] }),
makeRun({ run_id: 'run-quiet' }),
]
expect(mostRecentEmittedRuns(runs).map((run) => run.run_id)).toEqual([
'run-findings',
'run-authored',
'run-edited',
])
})
})
describe('computeFleetSummary', () => {
it('counts a report-only run toward emit rate, matching the Emitted filter', () => {
// Guards the divergence where the fleet emit rate counted only `emitted_count > 0` while the
// per-scout "Emitted" chip counts report-channel output too — the two surfaces must agree.
const rollups = computeScoutRollups([makeRun({ emitted_report_ids: ['r-1'] })])
expect(computeFleetSummary([], rollups).emitRate).toEqual(1)
})
it('dedupes touched reports across scouts and channels', () => {
// The pulse line counts distinct reports the fleet touched. Summing per-scout sets instead
// would double-count a report authored by one scout and edited by another (r-1 below), and
// the header would advertise more reports than the findings page lists.
const rollups = computeScoutRollups([
makeRun({ skill_name: 'scout-a', emitted_report_ids: ['r-1'] }),
makeRun({ skill_name: 'scout-b', edited_report_ids: ['r-1', 'r-2'] }),
])
expect(computeFleetSummary([], rollups).touchedReportCount).toEqual(2)
})
})
})
describe('scout schedule modes', () => {
it.each<[string, string | null, string]>([
['a rolling interval', null, '1440'],
['a plain daily cron', '0 9 * * *', SCOUT_DAILY_AT_SCHEDULE_MODE],
['a single weekday cron', '30 8 * * 4', SCOUT_WEEKLY_ON_SCHEDULE_MODE],
['a Sunday cron written as 7', '30 8 * * 7', SCOUT_WEEKLY_ON_SCHEDULE_MODE],
['a weekday-range cron', '0 9 * * 1-5', SCOUT_CUSTOM_CRON_SCHEDULE_MODE],
['a monthly cron', '0 9 1 * *', SCOUT_CUSTOM_CRON_SCHEDULE_MODE],
])('reads %s as its own mode', (_label, runCronSchedule, expected) => {
expect(getScoutScheduleMode({ run_interval_minutes: 1440, run_cron_schedule: runCronSchedule })).toEqual(
expected
)
})
it('round-trips a weekly day and time through the cron it writes', () => {
expect(dayTimeToWeeklyCron('4', '08:30')).toEqual('30 8 * * 4')
expect(weeklyCronToDayTime('30 8 * * 4')).toEqual({ day: '4', time: '08:30' })
})
it('reads the other Sunday spelling as the dropdown value', () => {
expect(weeklyCronToDayTime('30 8 * * 7')).toEqual({ day: '0', time: '08:30' })
})
describe('scoutCronScheduleError', () => {
it.each<[string, string]>([
['0 9 * * 1-5', 'weekdays'],
['30 8 * * 1,4', 'two days a week'],
['0 9 1 * *', 'the first of the month'],
['0 9,17 * * *', 'twice a day'],
['0 9 * * MON', 'a named weekday'],
['0 9 15 2 *', 'a real February date'],
['0 9 31 2,3 MON', 'a real date in one of the months'],
['10,50 0,23 * * 1', 'slots either side of midnight, but only one day a week'],
['0 9 * * 5#2', 'syntax only the backend models'],
['0 9 L * *', 'the last day of the month'],
['R 9 * * *', 'a random minute the scheduler picks'],
])('accepts %s (%s)', (expression) => {
expect(scoutCronScheduleError(expression)).toBeNull()
})
it.each<[string, string]>([
['0 9 * *', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],
['70 9 * * *', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],
['not a cron at all', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],
['0 0 31 2 *', 'This schedule never matches a real date. Check the day and month.'],
['0 0 31 2 MON', 'This schedule never matches a real date. Check the day and month.'],
['*/20 * * * *', 'Runs must be at least 30 minutes apart.'],
['0,15 9 * * *', 'Runs must be at least 30 minutes apart.'],
['10,50 0,23 * * *', 'Runs must be at least 30 minutes apart.'],
['*/1e2 9 * * *', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],
['0 9 * * @', 'Enter a five-field cron expression, like 0 9 * * 1-5.'],
])('refuses %s', (expression, expected) => {
expect(scoutCronScheduleError(expression)).toEqual(expected)
})
})
})