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.

perf(signals): load a scout page without fetching the whole fleet's runs (#117942)

posthog[bot]a1413011cb92
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 5f6a7ccfa415..6723391e3c07 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -930,6 +930,14 @@ class ScoutFleetSyncQuerySerializer(serializers.Serializer):
class RecentRunsPerScoutQuerySerializer(serializers.Serializer):
"""Query parameters for the `recent-per-scout` action."""
+ skill_name = serializers.CharField(
+ required=False,
+ max_length=255,
+ help_text=(
+ "Return only this scout's runs. Omit to cover every configured scout. A single-scout "
+ "page passes it so it does not wait on the probes of the rest of the fleet."
+ ),
+ )
per_scout_limit = serializers.IntegerField(
required=False,
min_value=1,
diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.py
index 11d16f9be6ff..3a84570a4971 100644
--- a/products/signals/backend/scout_harness/tools/runs.py
+++ b/products/signals/backend/scout_harness/tools/runs.py
@@ -359,6 +359,7 @@ def recent_runs_per_scout(
per_scout_limit: int = DEFAULT_RUNS_PER_SCOUT,
max_age_days: int = DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS,
exclude_skill_name: str | None = None,
+ skill_name: str | None = None,
) -> list[RunSummary]:
"""Return each configured scout's most recent runs, newest first across the fleet.
@@ -369,6 +370,7 @@ def recent_runs_per_scout(
per_scout_limit=per_scout_limit,
max_age_days=max_age_days,
exclude_skill_name=exclude_skill_name,
+ skill_name=skill_name,
)
return runs_by_id(team_id=team_id, run_ids=run_ids)
@@ -379,6 +381,7 @@ def recent_run_ids_per_scout(
per_scout_limit: int = DEFAULT_RUNS_PER_SCOUT,
max_age_days: int = DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS,
exclude_skill_name: str | None = None,
+ skill_name: str | None = None,
) -> list[Any]:
"""Return the ids of each configured scout's most recent runs.
@@ -397,6 +400,7 @@ def recent_run_ids_per_scout(
staleness cutoff is derived from.
`max_age_days` is the floor of that cutoff, not a fixed window — see `_staleness_cutoff`.
+ `skill_name` narrows the probe to one scout.
"""
per_scout_limit = max(1, min(per_scout_limit, MAX_RUNS_PER_SCOUT))
floor_days = max(1, min(max_age_days, MAX_RUNS_PER_SCOUT_MAX_AGE_DAYS))
@@ -404,9 +408,11 @@ def recent_run_ids_per_scout(
# Enabled first so that if a fleet ever exceeds the bound, the scouts dropped are the ones
# nobody is watching run. Ordered within each group for a deterministic cut.
+ config_rows = SignalScoutConfig.objects.filter(team_id=team_id)
+ if skill_name is not None:
+ config_rows = config_rows.filter(skill_name=skill_name)
configs = list(
- SignalScoutConfig.objects.filter(team_id=team_id)
- .exclude(skill_name=exclude_skill_name or "")
+ config_rows.exclude(skill_name=exclude_skill_name or "")
.order_by("-enabled", "skill_name")
.only("skill_name", "run_interval_minutes", "run_cron_schedule", "enabled")
)
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index fde1862af899..e50e60e65185 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -775,7 +775,8 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"Runs older than the staleness guard are excluded too, so a scout that stopped running "
"reads as stale instead of healthy — `max_age_days` (default 30) is that guard's floor, "
"which each scout's own cadence extends. Use `list` instead when you want a literal "
- "time window or a text/emitted filter. Strictly team-scoped."
+ "time window or a text/emitted filter. Pass `skill_name` to probe one scout only. "
+ "Strictly team-scoped."
),
operation_id="signals_scout_runs_recent_per_scout",
)
@@ -792,16 +793,23 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
saved = saved_reads_for_request(request, _canonical_team_id(self))
per_scout_limit = validated.get("per_scout_limit") or DEFAULT_RUNS_PER_SCOUT
max_age_days = validated.get("max_age_days") or DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS
+ skill_name = validated.get("skill_name")
run_ids = recent_run_ids_per_scout(
team_id=_canonical_team_id(self),
per_scout_limit=per_scout_limit,
max_age_days=max_age_days,
exclude_skill_name=saved.context.skill_name if saved is not None else None,
+ skill_name=skill_name,
)
if saved is not None:
rows = runs_by_id(team_id=_canonical_team_id(self), run_ids=run_ids)
rows.extend(
- saved.recent_runs([], limit=per_scout_limit, date_from=timezone.now() - timedelta(days=max_age_days))
+ saved.recent_runs(
+ [],
+ limit=per_scout_limit,
+ date_from=timezone.now() - timedelta(days=max_age_days),
+ skill_name=skill_name,
+ )
)
rows.sort(key=lambda row: row.created_at, reverse=True)
return Response(SignalScoutRunSummarySerializer([row.as_dict() for row in rows], many=True).data)
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index c510da00337a..0d254d06a9d6 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -763,6 +763,15 @@ class TestScoutHarnessRecentPerScoutAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert {row["run_id"] for row in response.json()} == {str(busy[-1].id), str(quiet.id)}
+ def test_skill_name_returns_only_that_scouts_runs(self) -> None:
+ for skill_name in ("signals-scout-errors", "signals-scout-surveys"):
+ SignalScoutConfig.objects.create(team=self.team, skill_name=skill_name)
+ wanted = _make_run(self.team, skill_name="signals-scout-errors")
+ _make_run(self.team, skill_name="signals-scout-surveys")
+ response = self.client.get(self._url(), data={"skill_name": "signals-scout-errors"})
+ assert response.status_code == status.HTTP_200_OK
+ assert [row["run_id"] for row in response.json()] == [str(wanted.id)]
+
def test_rejects_a_per_scout_limit_over_the_cap(self) -> None:
response = self.client.get(self._url(), data={"per_scout_limit": 5000})
assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 6fb61bccdd91..f5ac320058aa 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -8313,6 +8313,12 @@ export type SignalsScoutRunsRecentPerScoutParams = {
* @maximum 100
*/
per_scout_limit?: number
+ /**
+ * Return only this scout's runs. Omit to cover every configured scout. A single-scout page passes it so it does not wait on the probes of the rest of the fleet.
+ * @minLength 1
+ * @maxLength 255
+ */
+ skill_name?: string
}
export type SignalsScoutReportCheckListParams = {
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 7f86cfd7e36d..9e068c06d5a4 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -2614,7 +2614,7 @@ export const getSignalsScoutRunsRecentPerScoutUrl = (
}
/**
- * Return the most recent `per_scout_limit` runs of *every* configured scout on the project (default 25), newest-first across the fleet. The per-scout probe is the point: a fleet-wide time window has to serve hourly and weekly scouts from one result cap, so the busy scouts crowd out the sparse ones and a scout's visible history shrinks as the rest of the fleet gets busier. Probing each `skill_name` gives every scout the same depth of history whatever its schedule, and bounds the response at scouts x `per_scout_limit` rather than at the fleet's run rate. Only scouts that still have a config are covered, so runs left behind by a deleted or renamed scout are excluded. Runs older than the staleness guard are excluded too, so a scout that stopped running reads as stale instead of healthy — `max_age_days` (default 30) is that guard's floor, which each scout's own cadence extends. Use `list` instead when you want a literal time window or a text/emitted filter. Strictly team-scoped.
+ * Return the most recent `per_scout_limit` runs of *every* configured scout on the project (default 25), newest-first across the fleet. The per-scout probe is the point: a fleet-wide time window has to serve hourly and weekly scouts from one result cap, so the busy scouts crowd out the sparse ones and a scout's visible history shrinks as the rest of the fleet gets busier. Probing each `skill_name` gives every scout the same depth of history whatever its schedule, and bounds the response at scouts x `per_scout_limit` rather than at the fleet's run rate. Only scouts that still have a config are covered, so runs left behind by a deleted or renamed scout are excluded. Runs older than the staleness guard are excluded too, so a scout that stopped running reads as stale instead of healthy — `max_age_days` (default 30) is that guard's floor, which each scout's own cadence extends. Use `list` instead when you want a literal time window or a text/emitted filter. Pass `skill_name` to probe one scout only. Strictly team-scoped.
* @summary List each scout's most recent runs
*/
export const signalsScoutRunsRecentPerScout = async (
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx
index 7346e7c201ff..e6d78296d653 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx
@@ -7,6 +7,7 @@ import { teamLogic } from 'scenes/teamLogic'
import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
+import { scoutDetailLogic } from '../../../logics/scoutDetailLogic'
import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
import { scoutCostLineParts, scoutCostWindowLabel } from '../../../utils/scoutCosts'
import { nextRunAt, SCOUT_GROUP_LABEL, ScoutGroupKey, scoutGroup } from '../../../utils/scoutGroups'
@@ -59,7 +60,8 @@ export function ScoutHealthStrip({
noteCount: number
learnedCount: number
}): JSX.Element {
- const { scoutCostRollups, scoutRunsLoadedOnce, scoutRunsCoverFleet } = useValues(scoutFleetLogic)
+ const { scoutCostRollups } = useValues(scoutFleetLogic)
+ const { scoutRunsLoadedOnce, scoutRunsCoverScout } = useValues(scoutDetailLogic({ skillName: config.skill_name }))
const { currentTeam } = useValues(teamLogic)
const now = new Date()
@@ -120,7 +122,7 @@ export function ScoutHealthStrip({
<span className="text-muted">
{runStripEmptyLabel({
loadedOnce: scoutRunsLoadedOnce,
- coversFleet: scoutRunsCoverFleet,
+ coversFleet: scoutRunsCoverScout,
})}
</span>
)}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx
index 3faf50d71442..eed7047b7c94 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx
@@ -9,6 +9,7 @@ import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { captureScoutAction } from '../../../inboxAnalytics'
+import { scoutDetailLogic } from '../../../logics/scoutDetailLogic'
import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
import { SignalScoutRunSummary } from '../../../types'
import {
@@ -426,7 +427,7 @@ export function ScoutRunHistorySection({
skillName: string
filter: ScoutRunFilter
}): JSX.Element {
- const { scoutRunsLoadedOnce, scoutRunsCoverFleet } = useValues(scoutFleetLogic)
+ const { scoutRunsLoadedOnce, scoutRunsCoverScout } = useValues(scoutDetailLogic({ skillName }))
const runs = useScoutRuns(skillName)
const filteredRuns = useMemo(() => runs.filter((run) => runMatchesFilter(run, filter)), [runs, filter])
@@ -436,7 +437,7 @@ export function ScoutRunHistorySection({
[filteredRuns, filter]
)
- // Hold the skeleton until the fleet's per-scout runs have settled once — otherwise a fresh
+ // Hold the skeleton until this scout's runs have settled once — otherwise a fresh
// deep-link flashes the empty state before we know this scout's runs.
if (!scoutRunsLoadedOnce) {
return <LemonSkeleton className="h-12 w-full rounded" />
@@ -450,7 +451,7 @@ export function ScoutRunHistorySection({
: // Past the fleet the per-scout response covers, this scout was never read, so
// reporting it as a scout with no recent runs would hide history rather than
// report it.
- scoutRunsCoverFleet
+ scoutRunsCoverScout
? SCOUT_NO_RECENT_RUNS
: SCOUT_RUN_HISTORY_UNAVAILABLE}
</div>
diff --git a/products/signals/frontend/inbox/logics/scoutDetailLogic.ts b/products/signals/frontend/inbox/logics/scoutDetailLogic.ts
index 310b3af65a68..9e110cace153 100644
--- a/products/signals/frontend/inbox/logics/scoutDetailLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutDetailLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
@@ -62,8 +62,9 @@ export interface ScoutEmissionRow {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutDetailLogicValues {
+ fleetScoutRunsLoadedOnce: boolean // scoutFleetLogic
rollups: Map<string, ScoutRollup> // scoutFleetLogic
- scoutRunsLoadedOnce: boolean // scoutFleetLogic
+ scoutRunsCoverFleet: boolean // scoutFleetLogic
emissionReports: SignalScoutEmissionReportLink[]
emissionReportsLoading: boolean
emissionRows: ScoutEmissionRow[]
@@ -72,10 +73,13 @@ export interface scoutDetailLogicValues {
emissionsLoading: boolean
emittedRuns: SignalScoutRunSummary[]
emittedRunsKey: string
+ ownRunsLoaded: boolean
reportBySourceId: Map<string, LinkedSignalReport>
reportRows: ScoutReportRow[]
scoutReports: SignalReport[]
scoutReportsLoading: boolean
+ scoutRunsCoverScout: boolean
+ scoutRunsLoadedOnce: boolean
touchedReports: {
action: ScoutReportAction
id: string
@@ -85,6 +89,7 @@ export interface scoutDetailLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutDetailLogicActions {
+ loadScoutRunsForSkill: (skillName: string) => string // scoutFleetLogic
loadEmissionReports: () => any
loadEmissionReportsFailure: (
error: string,
@@ -136,6 +141,8 @@ export interface scoutDetailLogicActions {
export interface scoutDetailLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ scoutRunsLoadedOnce: (fleetScoutRunsLoadedOnce: boolean, ownRunsLoaded: boolean) => boolean
+ scoutRunsCoverScout: (scoutRunsCoverFleet: boolean, ownRunsLoaded: boolean) => boolean
emittedRuns: (rollups: Map<string, ScoutRollup>, arg: any) => SignalScoutRunSummary[]
emittedRunsKey: (emittedRuns: SignalScoutRunSummary[]) => string
reportBySourceId: (emissionReports: SignalScoutEmissionReportLink[]) => Map<string, LinkedSignalReport>
@@ -175,10 +182,10 @@ export type scoutDetailLogicType = MakeLogicType<
>
/**
- * Per-scout detail logic, keyed by skill_name. Reuses the singleton `scoutFleetLogic`'s
- * runs window (already polled while the detail page is open) to find this scout's emitted
- * runs, then fetches each run's emissions and flattens them into one newest-first list — the
- * Signals section. The runs endpoint has no per-finding listing, so emissions are fetched
+ * Per-scout detail logic, keyed by skill_name. Loads this scout's runs into the singleton
+ * `scoutFleetLogic`'s runs window on mount (the fleet poll keeps them fresh after that) to find
+ * this scout's emitted runs, then fetches each run's emissions and flattens them into one
+ * newest-first list — the Signals section. The runs endpoint has no per-finding listing, so emissions are fetched
* per emitted run; quiet runs (the vast majority) are never hit.
*/
export const scoutDetailLogic = kea<scoutDetailLogicType>([
@@ -187,7 +194,11 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([
key((props) => props.skillName),
connect(() => ({
- values: [scoutFleetLogic, ['rollups', 'scoutRunsLoadedOnce']],
+ values: [
+ scoutFleetLogic,
+ ['rollups', 'scoutRunsLoadedOnce as fleetScoutRunsLoadedOnce', 'scoutRunsCoverFleet'],
+ ],
+ actions: [scoutFleetLogic, ['loadScoutRunsForSkill']],
})),
loaders(({ values }) => ({
@@ -299,7 +310,15 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([
],
})),
- reducers({
+ reducers(({ props }) => ({
+ // True once this scout's own runs land, so the page renders without the fleet-wide read.
+ ownRunsLoaded: [
+ false,
+ {
+ [scoutFleetLogic.actionTypes.loadScoutRunsForSkillSuccess]: (state, { payload }) =>
+ payload === props.skillName ? true : state,
+ },
+ ],
// True only when the most recent emissions load failed outright (all per-run fetches
// rejected). Reset when a fresh load starts or succeeds. Lets the Signals section show a
// retrying/error state instead of a false empty when findings exist but couldn't be loaded.
@@ -311,9 +330,21 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([
loadEmissionsFailure: () => true,
},
],
- }),
+ })),
selectors({
+ // Same "loaded once" contract as the fleet's flag, satisfied by either read.
+ scoutRunsLoadedOnce: [
+ (s) => [s.fleetScoutRunsLoadedOnce, s.ownRunsLoaded],
+ (fleetScoutRunsLoadedOnce: boolean, ownRunsLoaded: boolean): boolean =>
+ fleetScoutRunsLoadedOnce || ownRunsLoaded,
+ ],
+ // The single-scout read always probes this scout, so the fleet probe bound does not apply.
+ // The fleet loader keeps this scout's slice when its own response did not probe the scout.
+ scoutRunsCoverScout: [
+ (s) => [s.scoutRunsCoverFleet, s.ownRunsLoaded],
+ (scoutRunsCoverFleet: boolean, ownRunsLoaded: boolean): boolean => scoutRunsCoverFleet || ownRunsLoaded,
+ ],
// This scout's runs that emitted at least one finding, newest first, capped to the most
// recent MAX_EMITTED_RUNS. `.filter()` returns a fresh array, so the in-place `.sort()`
// never touches the shared rollup `runs` the header timeline reads (oldest-first).
@@ -461,4 +492,8 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([
}
},
})),
+
+ afterMount(({ actions, props }) => {
+ actions.loadScoutRunsForSkill(props.skillName)
+ }),
])
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
index def32ef521fd..419335a94517 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
@@ -25,6 +25,7 @@ import type { ScoutCostsApi, SignalScoutConfigApi, UserBasicApi } from 'products
import { llmSkillsNamePublishCommunityCreate } from 'products/skills/frontend/generated/api'
import { SignalScoutRunSummary } from '../types'
+import { SCOUT_RUNS_FLEET_COVERAGE_LIMIT } from '../utils/scoutRunsWindow'
import { ScoutRosterSort, scoutFleetLogic } from './scoutFleetLogic'
jest.mock('posthog-js')
@@ -965,6 +966,44 @@ describe('scoutFleetLogic', () => {
}
})
+ it('keeps a newer single-scout read when an earlier fleet read lands after it', async () => {
+ const fleetRequest = deferred<SignalScoutRunSummary[]>()
+ mockSignalsScoutRunsRecentPerScout.mockImplementationOnce(() => fleetRequest.promise)
+ logic.actions.loadScoutRuns()
+ mockSignalsScoutRunsRecentPerScout.mockResolvedValueOnce([makeRun({ run_id: 'run-fresh' })])
+ logic.actions.loadScoutRunsForSkill(BASE_CONFIG.skill_name)
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsForSkillSuccess'])
+
+ fleetRequest.resolve([
+ makeRun({ run_id: 'run-stale' }),
+ makeRun({ run_id: 'run-other', skill_name: 'signals-scout-surveys' }),
+ ])
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess'])
+
+ expect(logic.values.scoutRuns.map((run) => run.run_id).sort()).toEqual(['run-fresh', 'run-other'])
+ })
+
+ it('keeps a single-scout read that a fleet read past the probe bound did not cover', async () => {
+ const otherConfigs = Array.from({ length: SCOUT_RUNS_FLEET_COVERAGE_LIMIT }, (_, index) => ({
+ ...BASE_CONFIG,
+ id: `config-other-${index}`,
+ skill_name: `signals-scout-other-${index}`,
+ }))
+ logic.actions.loadScoutConfigsSuccess([BASE_CONFIG, ...otherConfigs])
+ expect(logic.values.scoutRunsCoverFleet).toBe(false)
+ mockSignalsScoutRunsRecentPerScout.mockResolvedValueOnce([makeRun({ run_id: 'run-own' })])
+ logic.actions.loadScoutRunsForSkill(BASE_CONFIG.skill_name)
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsForSkillSuccess'])
+
+ mockSignalsScoutRunsRecentPerScout.mockResolvedValueOnce([
+ makeRun({ run_id: 'run-other', skill_name: 'signals-scout-other-0' }),
+ ])
+ logic.actions.loadScoutRuns()
+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess'])
+
+ expect(logic.values.scoutRuns.map((run) => run.run_id).sort()).toEqual(['run-other', 'run-own'])
+ })
+
it('keeps the runs array and settled run references when a poll changes nothing', async () => {
const settledRun = makeRun({ run_id: 'run-settled', status: 'completed' })
mockSignalsScoutRunsRecentPerScout.mockImplementation(async () => [JSON.parse(JSON.stringify(settledRun))])
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
index c66219b1b8e6..d78ddc76d2c9 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
@@ -162,6 +162,16 @@ const RUN_COST_BATCH_CONCURRENCY = 4
// that settled before this answers with its final total. The rest covers clock skew.
const RUN_COST_FINAL_AFTER_MS = 10 * 60_000
+// Orders the fleet runs read and the single-scout runs read, which both write `scoutRuns`.
+function nextRunsRequestSeq(cache: Record<string, any>): number {
+ cache.runsRequestSeq = (cache.runsRequestSeq ?? 0) + 1
+ return cache.runsRequestSeq
+}
+
+function byNewestCreated(a: SignalScoutRunSummary, b: SignalScoutRunSummary): number {
+ return (b.created_at ?? '').localeCompare(a.created_at ?? '')
+}
+
// Roster filter state also lives in the URL so a filtered view survives a refresh and is shareable.
// The search param is written on this debounce, so typing does not rewrite the URL per keystroke.
const ROSTER_SEARCH_DEBOUNCE_MS = 600
@@ -537,6 +547,21 @@ export interface scoutFleetLogicActions {
error: string
errorObject?: any
}
+ loadScoutRunsForSkill: (skillName: string) => string
+ loadScoutRunsForSkillFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadScoutRunsForSkillSuccess: (
+ scoutRuns: SignalScoutRunSummary[],
+ payload?: string
+ ) => {
+ scoutRuns: SignalScoutRunSummary[]
+ payload?: string
+ }
loadScoutRunsSuccess: (
scoutRuns: SignalScoutRunSummary[],
payload?: void
@@ -909,15 +934,62 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
if (!teamId) {
return values.scoutRuns
}
+ const requestSeq = nextRunsRequestSeq(cache)
const runs = await signalsScoutRunsRecentPerScout(String(teamId), {
per_scout_limit: SCOUT_RUNS_PER_SCOUT,
})
breakpoint()
+ const fleetSkills = new Set(runs.map((run) => run.skill_name))
+ cache.lastFleetRuns = { seq: requestSeq, skills: fleetSkills }
+ // A scout page's own read wins over this response when it started later, or when
+ // this response could not probe that scout at all. Otherwise a slow fleet read
+ // would put back older runs, or drop a history the fleet read never saw.
+ const scopedRunsSeq: Record<string, number> = cache.scopedRunsSeq ?? {}
+ const keptSkills = new Set(
+ Object.entries(scopedRunsSeq)
+ .filter(
+ ([skillName, scopedSeq]) =>
+ scopedSeq > requestSeq ||
+ (!values.scoutRunsCoverFleet && !fleetSkills.has(skillName))
+ )
+ .map(([skillName]) => skillName)
+ )
+ const nextRuns =
+ keptSkills.size === 0
+ ? runs
+ : [
+ ...runs.filter((run) => !keptSkills.has(run.skill_name)),
+ ...values.scoutRuns.filter((run) => keptSkills.has(run.skill_name)),
+ ].sort(byNewestCreated)
// Reuse prior references for unchanged runs so the 60s poll doesn't churn every
// run's identity and needlessly re-render the memoized run/emission rows. Live
// (running/queued) runs are never reused: their rows show a wall-clock duration
// that must keep advancing with each poll.
- return reconcileById(values.scoutRuns, runs, (run) => run.run_id, isSettledRun)
+ return reconcileById(values.scoutRuns, nextRuns, (run) => run.run_id, isSettledRun)
+ },
+ // One scout's runs, merged over that scout's slice of the window. A scout page loads
+ // this first, so it does not wait on the probes of every other scout in the fleet.
+ loadScoutRunsForSkill: async (skillName: string, breakpoint) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return values.scoutRuns
+ }
+ const requestSeq = nextRunsRequestSeq(cache)
+ cache.scopedRunsSeq = { ...cache.scopedRunsSeq, [skillName]: requestSeq }
+ const runs = await signalsScoutRunsRecentPerScout(String(teamId), {
+ per_scout_limit: SCOUT_RUNS_PER_SCOUT,
+ skill_name: skillName,
+ })
+ breakpoint()
+ // A fleet read that started later already put newer runs for this scout in place.
+ const lastFleetRuns: { seq: number; skills: Set<string> } | undefined = cache.lastFleetRuns
+ if (lastFleetRuns && lastFleetRuns.seq > requestSeq && lastFleetRuns.skills.has(skillName)) {
+ return values.scoutRuns
+ }
+ const merged = [...values.scoutRuns.filter((run) => run.skill_name !== skillName), ...runs].sort(
+ byNewestCreated
+ )
+ return reconcileById(values.scoutRuns, merged, (run) => run.run_id, isSettledRun)
},
},
],
@@ -1661,7 +1733,11 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
})
lemonToast.success('Run started. It shows up in this scout’s runs when it finishes.')
// The run row appears on the next poll; pull once now so the page reacts immediately.
- actions.loadScoutRuns()
+ if (config) {
+ actions.loadScoutRunsForSkill(config.skill_name)
+ } else {
+ actions.loadScoutRuns()
+ }
} catch (error: any) {
// The endpoint refuses deliberately in several ordinary cases — already running,
// over the daily budget — so the backend's own message is the useful one.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 45074409caa6..6d8b30e2d3cf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -130127,6 +130127,12 @@ export namespace Schemas {
* @maximum 100
*/
per_scout_limit?: number;
+ /**
+ * Return only this scout's runs. Omit to cover every configured scout. A single-scout page passes it so it does not wait on the probes of the rest of the fleet.
+ * @minLength 1
+ * @maxLength 255
+ */
+ skill_name?: string;
};
export type SignalsScoutReportCheckListParams = {