: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
fix(signals): paginate scout fleet runs window in web inbox (#64618)
Andrew Maguiree6c31a516865
diff --git a/frontend/src/scenes/inbox/components/config/scouts/ScoutsFleetSection.tsx b/frontend/src/scenes/inbox/components/config/scouts/ScoutsFleetSection.tsxindex f37bf8e2a5e1..12e73a3601db 100644--- a/frontend/src/scenes/inbox/components/config/scouts/ScoutsFleetSection.tsx+++ b/frontend/src/scenes/inbox/components/config/scouts/ScoutsFleetSection.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { useEffect } from 'react'import { IconChevronDown, IconCompass, IconPlus, IconSparkles } from '@posthog/icons'import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'@@ -27,7 +28,14 @@ import { ScoutRowCard } from './ScoutRowCard'*/export function ScoutsFleetSection(): JSX.Element {const { scoutConfigs, scoutConfigsLoading, expanded, enabledCount, lastRunAt } = useValues(scoutFleetLogic)- const { setExpanded, loadScoutConfigs } = useActions(scoutFleetLogic)+ const { setExpanded, loadScoutConfigs, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)++ // Poll the runs window only while the fleet list is open — the always-mounted setup+ // widget reads configs only and shouldn't trigger the paginated runs requests.+ useEffect(() => {+ startRunsPolling()+ return () => stopRunsPolling()+ }, [startRunsPolling, stopRunsPolling])if (scoutConfigsLoading && scoutConfigs === null) {return <LemonSkeleton className="h-12 w-full rounded" />diff --git a/frontend/src/scenes/inbox/logics/scoutFleetLogic.ts b/frontend/src/scenes/inbox/logics/scoutFleetLogic.tsindex c911d5bc0df3..c7299152e264 100644--- a/frontend/src/scenes/inbox/logics/scoutFleetLogic.ts+++ b/frontend/src/scenes/inbox/logics/scoutFleetLogic.ts@@ -5,6 +5,7 @@ import { router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { dayjs } from 'lib/dayjs'import { urls } from 'scenes/urls'import { OriginProduct } from 'products/tasks/frontend/types'@@ -15,6 +16,7 @@ import {computeScoutRollups,FleetSummary,getScoutOrigin,+ SCOUT_RUNS_WINDOW_HOURS,ScoutRollup,sortConfigsForDisplay,} from '../utils/scoutRunsWindow'@@ -23,7 +25,12 @@ import type { scoutFleetLogicType } from './scoutFleetLogicType'// Fleet runs are refetched on a slow cadence so "running now" / recent emissions// stay live without hammering the capped runs endpoint (desktop: 60s).const RUNS_REFETCH_INTERVAL_MS = 60_000+// The runs endpoint caps each page at 100 rows newest-first. To cover the whole+// window we walk back page-by-page via a `date_to` cursor (the oldest run's+// `started_at`, as the backend documents). MAX_RUNS_PAGES bounds the walk so a+// pathologically busy fleet can't spin forever — hitting it flags the window truncated.const RUNS_PAGE_LIMIT = 100+const MAX_RUNS_PAGES = 15/*** Cloud port of desktop's scouts fleet hooks (`useScoutConfigs`, `useScoutRuns`,@@ -41,6 +48,10 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([patchScoutConfigLocally: (configId: string, updates: SignalScoutConfigUpdate) => ({ configId, updates }),setHideDisabled: (hideDisabled: boolean) => ({ hideDisabled }),setExpanded: (expanded: boolean) => ({ expanded }),+ // Started/stopped by the fleet-list component so the always-mounted setup widget+ // (which only reads configs) doesn't trigger the paginated runs-window polling.+ startRunsPolling: true,+ stopRunsPolling: true,startScoutChatTask: (prompt: string, taskLabel: string, fallbackTitle: string) => ({prompt,taskLabel,@@ -66,10 +77,45 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([},{loadRunsWindow: async () => {- const runs = await api.signalScout.runs.list({ limit: RUNS_PAGE_LIMIT })- // The endpoint caps at 100 rows; if it returned a full page there may be- // older runs in the window we can't see, so flag the window as truncated.- return { runs, complete: runs.length < RUNS_PAGE_LIMIT }+ // Walk the full window newest→oldest, paginating via a `date_to` cursor so+ // every scout shows its real run history (not just the fleet-wide newest 100).+ const windowStart = dayjs().subtract(SCOUT_RUNS_WINDOW_HOURS, 'hours').toISOString()+ const seen = new Set<string>()+ const runs: SignalScoutRunSummary[] = []+ let cursor: string | undefined+ let complete = false++ for (let page = 0; page < MAX_RUNS_PAGES; page++) {+ const pageRuns = await api.signalScout.runs.list({+ limit: RUNS_PAGE_LIMIT,+ date_from: windowStart,+ date_to: cursor,+ })+ for (const run of pageRuns) {+ // `date_to` is exclusive, so a boundary row can reappear on the next+ // page — dedupe by run_id to be safe.+ if (!seen.has(run.run_id)) {+ seen.add(run.run_id)+ runs.push(run)+ }+ }+ // A short page means we reached the start of the window — nothing older left.+ if (pageRuns.length < RUNS_PAGE_LIMIT) {+ complete = true+ break+ }+ // Cursor on `created_at` — the exact field the endpoint filters/orders on, so+ // the walk can't skip runs (`started_at` is the TaskRun's time and can differ).+ const oldest = pageRuns[pageRuns.length - 1]+ // No usable cursor, or the cursor can't advance (a full page of identical+ // timestamps): stop, but the page was full so the window is NOT complete.+ if (!oldest.created_at || oldest.created_at === cursor) {+ break+ }+ cursor = oldest.created_at+ }++ return { runs, complete }},},],@@ -150,7 +196,7 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({updateScoutConfig: async ({ configId, updates }) => {const previousConfig = values.scoutConfigs?.find((config) => config.id === configId)// Optimistic update so the toggle/select feels instant.@@ -190,18 +236,26 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([actions.startScoutChatTaskFailure()}},- })),-- events(({ actions, cache }) => ({- afterMount: () => {- actions.loadScoutConfigs()+ startRunsPolling: () => {+ // Fetch once immediately, then a slow poll keeps "running now" + recent emissions+ // fresh. The keyed disposable replaces any prior poll and is torn down on+ // stopRunsPolling / unmount / tab hide.actions.loadRunsWindow()- // Slow poll keeps "running now" + recent emissions fresh. The keyed disposable- // is torn down automatically on unmount / tab hide.cache.disposables.add(() => {const interval = setInterval(() => actions.loadRunsWindow(), RUNS_REFETCH_INTERVAL_MS)return () => clearInterval(interval)}, 'runsPoll')},+ stopRunsPolling: () => {+ cache.disposables.dispose('runsPoll')+ },+ })),++ events(({ actions }) => ({+ afterMount: () => {+ // Configs are cheap and the always-mounted setup widget needs them. The paginated+ // runs window is loaded + polled only while the fleet list is open (startRunsPolling).+ actions.loadScoutConfigs()+ },})),])diff --git a/frontend/src/scenes/inbox/types.ts b/frontend/src/scenes/inbox/types.tsindex bf0f699f0731..d2265609da4c 100644--- a/frontend/src/scenes/inbox/types.ts+++ b/frontend/src/scenes/inbox/types.ts@@ -221,6 +221,8 @@ export interface SignalScoutRunSummary {skill_name: stringskill_version: numberstatus: SignalScoutRunStatus+ /** Bridge-row creation timestamp — the field the runs endpoint filters/orders on (the pagination cursor). */+ created_at: stringstarted_at: stringcompleted_at: string | nulltask_id?: string | nulldiff --git a/frontend/src/scenes/inbox/utils/scoutRunsWindow.ts b/frontend/src/scenes/inbox/utils/scoutRunsWindow.tsindex 11394e9c6cad..1cb856c434af 100644--- a/frontend/src/scenes/inbox/utils/scoutRunsWindow.ts+++ b/frontend/src/scenes/inbox/utils/scoutRunsWindow.ts@@ -1,8 +1,9 @@// Ported from PostHog Code desktop `packages/core/src/scouts/scoutRunsWindow.ts`// and `scoutPresentation.ts`. Pure metrics + display helpers over scout runs and-// configs; no I/O. The runs the cloud API returns are already the newest-first,-// 100-row-capped window the desktop assembled by hand, so the cursor-pagination-// loop is dropped here – but the same window framing and labels are preserved.+// configs; no I/O. The runs endpoint caps each response at 100 rows newest-first;+// `scoutFleetLogic.loadRunsWindow` assembles the full window by walking the+// `date_to` cursor (same as desktop), and these helpers frame all numbers as+// "the recent window" with a "truncated" suffix when that walk hits its page cap.import { humanFriendlyDuration } from 'lib/utils/durations'import { pluralize } from 'lib/utils/strings'diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 39a408a26c67..67ca3bf90180 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -40,6 +40,14 @@ class SignalScoutRunSummarySerializer(serializers.Serializer):status = serializers.CharField(help_text="Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled.",)+ created_at = serializers.CharField(+ help_text=(+ "ISO-8601 timestamp the bridge row was created — the field `date_from` / `date_to` "+ "filter and order on. Use this (not `started_at`) as the `date_to` cursor when walking "+ "past the 100-row cap, so runs created in the gap between a boundary run's TaskRun and "+ "its bridge row aren't skipped."+ ),+ )started_at = serializers.CharField(help_text="ISO-8601 timestamp the TaskRun was created.")completed_at = serializers.CharField(allow_null=True,@@ -204,7 +212,7 @@ class SearchRecentRunsQuerySerializer(serializers.Serializer):required=False,help_text=("ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result "- "cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run "+ "cap on subsequent calls (cursor-style: set to the `created_at` of the oldest run ""from the prior page)."),)diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.pyindex d448fe3fb44d..c78538066e6f 100644--- a/products/signals/backend/scout_harness/tools/runs.py+++ b/products/signals/backend/scout_harness/tools/runs.py@@ -40,6 +40,10 @@ class RunSummary:skill_name: strskill_version: intstatus: str+ # `created_at` is the bridge row's own timestamp — the field `search_recent_runs`+ # filters and orders on, hence the cursor key for walking past the result cap.+ # `started_at` is the linked TaskRun's creation time and can differ slightly.+ created_at: strstarted_at: strcompleted_at: str | Nonesummary: str@@ -70,6 +74,7 @@ class RunDetail:skill_name: strskill_version: intstatus: str+ created_at: strstarted_at: strcompleted_at: str | Nonesummary: str@@ -153,6 +158,7 @@ def _to_summary(row: SignalScoutRun, *, team_id: int) -> RunSummary:skill_name=row.skill_name,skill_version=row.skill_version,status=task_run.status if task_run is not None else "",+ created_at=row.created_at.isoformat(),started_at=task_run.created_at.isoformat() if task_run is not None else row.created_at.isoformat(),completed_at=task_run.completed_at.isoformat() if task_run is not None and task_run.completed_at else None,summary=row.summary,diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 8e34daa97cf5..375d5c2df560 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -809,6 +809,8 @@ export interface SignalScoutRunSummaryApi {skill_version: number/** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */status: string+ /** ISO-8601 timestamp the bridge row was created — the field `date_from` / `date_to` filter and order on. Use this (not `started_at`) as the `date_to` cursor when walking past the 100-row cap, so runs created in the gap between a boundary run's TaskRun and its bridge row aren't skipped. */+ created_at: string/** ISO-8601 timestamp the TaskRun was created. */started_at: string/**@@ -863,6 +865,8 @@ export interface SignalScoutRunDetailApi {skill_version: number/** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */status: string+ /** ISO-8601 timestamp the bridge row was created — the field `date_from` / `date_to` filter and order on. Use this (not `started_at`) as the `date_to` cursor when walking past the 100-row cap, so runs created in the gap between a boundary run's TaskRun and its bridge row aren't skipped. */+ created_at: string/** ISO-8601 timestamp the TaskRun was created. */started_at: string/**@@ -1350,7 +1354,7 @@ export type SignalsScoutRunsListParams = {*/date_from?: string/**- * ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run from the prior page).+ * ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `created_at` of the oldest run from the prior page).*/date_to?: string/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2a60fa7a0e72..3f8e803960c2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -44935,6 +44935,8 @@ export namespace Schemas {skill_version: number;/** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */status: string;+ /** ISO-8601 timestamp the bridge row was created — the field `date_from` / `date_to` filter and order on. Use this (not `started_at`) as the `date_to` cursor when walking past the 100-row cap, so runs created in the gap between a boundary run's TaskRun and its bridge row aren't skipped. */+ created_at: string;/** ISO-8601 timestamp the TaskRun was created. */started_at: string;/**@@ -44989,6 +44991,8 @@ export namespace Schemas {skill_version: number;/** Status from the linked TaskRun: not_started | queued | in_progress | completed | failed | cancelled. */status: string;+ /** ISO-8601 timestamp the bridge row was created — the field `date_from` / `date_to` filter and order on. Use this (not `started_at`) as the `date_to` cursor when walking past the 100-row cap, so runs created in the gap between a boundary run's TaskRun and its bridge row aren't skipped. */+ created_at: string;/** ISO-8601 timestamp the TaskRun was created. */started_at: string;/**@@ -60489,7 +60493,7 @@ export namespace Schemas {*/date_from?: string;/**- * ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run from the prior page).+ * ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `created_at` of the oldest run from the prior page).*/date_to?: string;/**diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 47e2e2cbaa74..54f5c0d550d9 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -267,7 +267,7 @@ export const SignalsScoutRunsListQueryParams = /* @__PURE__ */ zod.object({.datetime({ offset: true }).optional().describe(- 'ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run from the prior page).'+ 'ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `created_at` of the oldest run from the prior page).'),emitted: zod.boolean()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-runs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-runs-list.jsonindex 6a11adb904e9..2ce8bfaf528b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-runs-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-runs-list.json@@ -8,7 +8,7 @@"type": "string"},"date_to": {- "description": "ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `started_at` of the oldest run from the prior page).",+ "description": "ISO-8601 exclusive upper bound on `created_at`. Pass to walk back past the result cap on subsequent calls (cursor-style: set to the `created_at` of the oldest run from the prior page).","format": "date-time","pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$","type": "string"