: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): materialize the scout fleet when the Scouts tab opens (#91630)
posthog[bot]0cb2e4aa7bc2
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 3ba9a0a6185a..cde9a4a5e59f 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -2208,6 +2208,19 @@ export class PostHogAPIClient {return Array.isArray(data) ? data : (data.results ?? []);}+ /**+ * Materialize the project's scout fleet and return it: the backend seeds the+ * canonical `signals-scout-*` skills, registers a config for every scout+ * missing one, and retires the ones no longer shipped. Idempotent, and the+ * only way a project the Temporal coordinator never reached gets any scouts.+ */+ async syncScoutConfigs(projectId: number): Promise<ScoutConfig[]> {+ const data = await this.scoutPost<+ { results: ScoutConfig[] } | ScoutConfig[]+ >(projectId, "configs/sync/", {});+ return Array.isArray(data) ? data : (data.results ?? []);+ }+async updateScoutConfig(projectId: number,configId: string,diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsxindex 4d130fed5d84..c51d67536a03 100644--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsx+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsx@@ -39,6 +39,7 @@ import { useScoutChatTask } from "../hooks/useScoutChatTask";import type { ScoutConfigUpdate } from "../hooks/useScoutConfigMutations";import { useScoutConfigMutations } from "../hooks/useScoutConfigMutations";import { useScoutConfigs } from "../hooks/useScoutConfigs";+import { useScoutFleetSync } from "../hooks/useScoutFleetSync";import { useScoutRuns } from "../hooks/useScoutRuns";import { useScoutSkillCreators } from "../hooks/useScoutSkillCreators";import { FleetFindingsCallout } from "./FleetFindingsCallout";@@ -55,6 +56,9 @@ const EMPTY_CONFIGS: ScoutConfig[] = [];*/export function ScoutsFleetSection() {const { data: configs, isLoading, isError, refetch } = useScoutConfigs();+ // Opening this section is what materializes the fleet, so a project the+ // coordinator never reached still gets its scouts.+ const { isSyncing } = useScoutFleetSync();const [expanded, setExpanded] = useState(false);const lastRunAt = useMemo(() => {@@ -67,7 +71,9 @@ export function ScoutsFleetSection() {return latest;}, [configs]);- if (isLoading) {+ // An empty fleet while the sync is still running is a fleet being assembled,+ // not an empty one — the pulse holds until we know which it is.+ if (isLoading || (isSyncing && !configs?.length)) {return (<Box className="h-12 w-full animate-pulse rounded-(--radius-2) bg-(--gray-3)" />);@@ -459,11 +465,10 @@ function ScoutsEmptyState() {</Text></Flex><Text className="max-w-2xl text-[12.5px] text-gray-11 leading-snug">- Scouts are rolling out gradually. Once your project is enrolled, the- canonical fleet appears here automatically and you can add custom- scouts by creating{" "}- <span className="font-mono text-[11px]">signals-scout-*</span> skills- in PostHog.+ Scouts run on a schedule to investigate a recurring signal or+ behavior. Add one by creating a{" "}+ <span className="font-mono text-[11px]">signals-scout-*</span> skill+ in your PostHog project.</Text><ScoutHelperSkillLinks surface="empty_state" /></Flex>diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/scoutQueryKeys.ts b/products/desktop/packages/ui/src/features/scouts/hooks/scoutQueryKeys.tsindex 0a8181a5778f..a865b4845c63 100644--- a/products/desktop/packages/ui/src/features/scouts/hooks/scoutQueryKeys.ts+++ b/products/desktop/packages/ui/src/features/scouts/hooks/scoutQueryKeys.ts@@ -1,6 +1,8 @@export const scoutQueryKeys = {configs: (projectId: number | null) =>["scouts", "configs", projectId] as const,+ fleetSync: (projectId: number | null) =>+ ["scouts", "fleetSync", projectId] as const,runs: (projectId: number | null) => ["scouts", "runs", projectId] as const,skillCreators: (projectId: number | null) =>["scouts", "skillCreators", projectId] as const,diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.tsnew file mode 100644index 000000000000..42f6d6bc4101--- /dev/null+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.ts@@ -0,0 +1,53 @@+import type { ScoutConfig } from "@posthog/api-client/posthog-client";+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";+import { useQueryClient } from "@tanstack/react-query";+import { useEffect } from "react";+import { useAuthStateValue } from "../../auth/store";+import { scoutQueryKeys } from "./scoutQueryKeys";++// Once per app session is the whole debounce. The canonical fleet only changes+// on a deploy, and a scout the person creates lands in the list on its own, so+// re-running the reconcile every time they reopen the section buys nothing.+const FLEET_SYNC_STALE_MS = 60 * 60_000;++/**+ * Materializes the project's scout fleet when the scouts section opens. A+ * project the Temporal coordinator never reached has no scout configs at all,+ * so without this the section shows an empty fleet no matter how long you wait.+ *+ * The endpoint answers with the fleet it just materialized, which the hook+ * writes into the cache `useScoutConfigs` reads. That keeps one source of truth+ * for the fleet, and saves the section from waiting out a poll cycle to show+ * the scouts that were just created.+ */+export function useScoutFleetSync(): {+ /** False once the first sync settles, success or failure. */+ isSyncing: boolean;+} {+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const queryClient = useQueryClient();+ const { data, isLoading } = useAuthenticatedQuery<ScoutConfig[]>(+ scoutQueryKeys.fleetSync(projectId),+ (client) =>+ projectId ? client.syncScoutConfigs(projectId) : Promise.resolve([]),+ {+ enabled: !!projectId,+ staleTime: FLEET_SYNC_STALE_MS,+ gcTime: FLEET_SYNC_STALE_MS,+ refetchOnWindowFocus: false,+ // A member without write access gets a 403 here, which retrying can't fix.+ // The list query is what keeps the section usable for them.+ retry: false,+ },+ );++ useEffect(() => {+ if (!data || !projectId) return;+ queryClient.setQueryData(scoutQueryKeys.configs(projectId), data);+ }, [data, projectId, queryClient]);++ // `isLoading`, not `isPending`: a query the hook disables (signed out, no+ // project) stays pending forever, and reading that as "still syncing" would+ // hold the section under a skeleton it can never leave.+ return { isSyncing: isLoading };+}diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex ba6052487335..020c048a582d 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -2395,9 +2395,10 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):description=("Materialize the scout fleet for this project on demand (idempotent): seed the ""canonical `signals-scout-*` skills, create a default-schedule config for any scout "- "lacking one, and return all scout configs. Normally the Temporal coordinator does "- "this on its next tick; this action exists so setup flows (e.g. the wizard's "- "self-driving program) can hand the user a tunable fleet immediately."+ "lacking one, retire the skills whose canonical scout no longer ships, and return all "+ "scout configs. Normally the Temporal coordinator does this on its next tick; this "+ "action exists so the scout UIs and setup flows (e.g. the wizard's self-driving "+ "program) can hand the user a tunable fleet immediately."),operation_id="signals_scout_config_sync",)@@ -2424,7 +2425,13 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# default_team_config) so a self-serve materialization doesn't bypass the launch cost posture# by enabling the full fleet.seed_config_layers, withheld = resolve_sync_seed_inputs(team.id)- sync_canonical_skills(team, withheld_skill_names=withheld)+ # `prune=True` puts this on the same terms as the coordinator tick: a scout retired from+ # `products/signals/skills/` is tombstoned on the team instead of lingering as a live row+ # the fleet UI keeps listing. The scout UIs call this on open, so a team that never reaches+ # the coordinator (not enrolled) still reconciles in both directions. The reap only touches+ # rows the harness seeded and the team never edited, so a hand-authored or forked scout of+ # the same name survives it.+ sync_canonical_skills(team, prune=True, withheld_skill_names=withheld)register_missing_configs(team.id, seed_config_layers, withheld_skill_names=withheld)# Exclude held-back scouts from the materialized fleet response too: a scout that was# previously seeded and later withheld still has a row, and surfacing it here woulddiff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 9bf2f24b0b23..283b163dc95b 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -41,7 +41,11 @@ from products.signals.backend.models import ()from products.signals.backend.pipeline_identity import AI_STAGE_RESEARCHfrom products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEY, stamp_derived_metadata-from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, discover_canonical_skills+from products.signals.backend.scout_harness.lazy_seed import (+ HARNESS_SEEDED_BY,+ _compute_row_hash,+ discover_canonical_skills,+)from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_Sfrom products.signals.backend.scout_harness.note_targets import PIPELINE_AUDIENCE_REPORT_RESEARCH as PIPELINE_AUDIENCEfrom products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIX@@ -2684,6 +2688,36 @@ class TestScoutHarnessConfigAPI(APIBaseTest):# Storage is untouched — the row is hidden from the response, not deleted.assert SignalScoutConfig.objects.filter(team=self.team, skill_name="signals-scout-error-tracking").exists()+ def test_sync_tombstones_a_retired_canonical_scout(self) -> None:+ # A scout removed from `products/signals/skills/` leaves a live row on every team the+ # harness seeded it into, and the roster keeps listing a scout that can never run again.+ # The sync reaps it, on the same terms as the coordinator tick.+ retired = LLMSkill.objects.create(+ team=self.team,+ name="signals-scout-retired",+ description="retired scout",+ body="# retired scout",+ metadata={"seeded_by": HARNESS_SEEDED_BY, "source": "products/signals/skills"},+ category="scout",+ version=1,+ is_latest=True,+ )+ retired.metadata["canonical_hash"] = _compute_row_hash(retired, [])+ retired.save(update_fields=["metadata"])+ hand_authored = self._make_skill("signals-scout-mine")++ response = self.client.post(self._sync_url())++ assert response.status_code == status.HTTP_200_OK+ retired.refresh_from_db()+ assert retired.deleted is True+ assert retired.is_latest is False+ assert "signals-scout-retired" not in {c["skill_name"] for c in response.json()}+ # A team's own scout carrying the same prefix is never the harness's to reap.+ hand_authored.refresh_from_db()+ assert hand_authored.deleted is False+ assert "signals-scout-mine" in {c["skill_name"] for c in response.json()}+def test_sync_rejects_read_only_scope(self) -> None:from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuediff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex b482f07832d7..064ec428679d 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -859,7 +859,7 @@ export const getSignalsScoutConfigSyncUrl = (projectId: string) => {}/**- * Materialize the scout fleet for this project on demand (idempotent): seed the canonical `signals-scout-*` skills, create a default-schedule config for any scout lacking one, and return all scout configs. Normally the Temporal coordinator does this on its next tick; this action exists so setup flows (e.g. the wizard's self-driving program) can hand the user a tunable fleet immediately.+ * Materialize the scout fleet for this project on demand (idempotent): seed the canonical `signals-scout-*` skills, create a default-schedule config for any scout lacking one, retire the skills whose canonical scout no longer ships, and return all scout configs. Normally the Temporal coordinator does this on its next tick; this action exists so the scout UIs and setup flows (e.g. the wizard's self-driving program) can hand the user a tunable fleet immediately.* @summary Sync scout configs*/export const signalsScoutConfigSync = async (diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsxindex 564c77be29d3..846723461212 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx@@ -25,19 +25,27 @@ const ROSTER_COLUMN_CLASS = '@container mx-auto flex w-full max-w-4xl flex-col g* stays in the scene header, so it is reachable even when the filters narrow the roster to nothing.*/export function ScoutsRoster(): JSX.Element {- const { scoutConfigs, scoutConfigsLoading, enabledCount, customScoutCount } = useValues(scoutFleetLogic)- const { loadScoutConfigs, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)+ const { scoutConfigs, scoutConfigsLoading, scoutFleetSynced, enabledCount, customScoutCount } =+ useValues(scoutFleetLogic)+ const { loadScoutConfigs, materializeScoutFleet, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)useEffect(() => {startRunsPolling()return () => stopRunsPolling()}, [startRunsPolling, stopRunsPolling])+ // Opening the roster is what materializes the fleet, so a project the coordinator never reached+ // still gets its scouts. The logic decides whether a sync is actually owed.+ useEffect(() => {+ materializeScoutFleet()+ }, [materializeScoutFleet])+// Roster shape once per opening, the first time the fleet resolves. A failed load stays `null`- // and reports nothing — an unreachable scout API isn't an empty troop.+ // and reports nothing — an unreachable scout API isn't an empty troop. An empty fleet waits for+ // the materialization too, so a troop that is about to arrive is never counted as no troop.const fleetViewedFiredRef = useRef(false)useEffect(() => {- if (scoutConfigs === null || fleetViewedFiredRef.current) {+ if (scoutConfigs === null || (scoutConfigs.length === 0 && !scoutFleetSynced) || fleetViewedFiredRef.current) {return}fleetViewedFiredRef.current = true@@ -47,7 +55,7 @@ export function ScoutsRoster(): JSX.Element {customCount: customScoutCount,dryRunCount: scoutConfigs.filter((config) => !config.emit).length,})- }, [scoutConfigs, enabledCount, customScoutCount])+ }, [scoutConfigs, scoutFleetSynced, enabledCount, customScoutCount])if (scoutConfigsLoading && scoutConfigs === null) {return (@@ -75,10 +83,13 @@ export function ScoutsRoster(): JSX.Element {)}+ // An empty fleet before the first sync settles is a troop still being assembled, not an empty+ // one — showing the empty state here would tell people to create a scout moments before their+ // canonical fleet lands.if (scoutConfigs.length === 0) {return (<div className={ROSTER_COLUMN_CLASS}>- <ScoutsEmptyState />+ {scoutFleetSynced ? <ScoutsEmptyState /> : <CardSkeleton count={3} variant="cards" dashed={false} />}</div>)}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterLegacy.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterLegacy.tsxindex 9696a7b5f759..a5d2c7cb6c9d 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterLegacy.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterLegacy.tsx@@ -28,8 +28,9 @@ const ROSTER_COMPACT_MAX_PX = 768* outgrew a 760px portal, and a modal can't host the scout pages it links to.*/export function ScoutsRosterLegacy(): JSX.Element {- const { scoutConfigs, scoutConfigsLoading, enabledCount, customScoutCount } = useValues(scoutFleetLogic)- const { loadScoutConfigs, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)+ const { scoutConfigs, scoutConfigsLoading, scoutFleetSynced, enabledCount, customScoutCount } =+ useValues(scoutFleetLogic)+ const { loadScoutConfigs, materializeScoutFleet, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)// One measurement for the whole roster, so the header chrome and the table agree on which// layout they're in — two observers could disagree for a frame mid-resize.const { ref: widthRef, size } = useResizeBreakpoints(@@ -43,11 +44,18 @@ export function ScoutsRosterLegacy(): JSX.Element {return () => stopRunsPolling()}, [startRunsPolling, stopRunsPolling])+ // Opening the roster is what materializes the fleet, so a project the coordinator never reached+ // still gets its scouts. The logic decides whether a sync is actually owed.+ useEffect(() => {+ materializeScoutFleet()+ }, [materializeScoutFleet])+// Roster shape once per opening, the first time the fleet resolves. A failed load stays `null`- // and reports nothing — an unreachable scout API isn't an empty troop.+ // and reports nothing — an unreachable scout API isn't an empty troop. An empty fleet waits for+ // the materialization too, so a troop that is about to arrive is never counted as no troop.const fleetViewedFiredRef = useRef(false)useEffect(() => {- if (scoutConfigs === null || fleetViewedFiredRef.current) {+ if (scoutConfigs === null || (scoutConfigs.length === 0 && !scoutFleetSynced) || fleetViewedFiredRef.current) {return}fleetViewedFiredRef.current = true@@ -57,9 +65,12 @@ export function ScoutsRosterLegacy(): JSX.Element {customCount: customScoutCount,dryRunCount: scoutConfigs.filter((config) => !config.emit).length,})- }, [scoutConfigs, enabledCount, customScoutCount])+ }, [scoutConfigs, scoutFleetSynced, enabledCount, customScoutCount])- if (scoutConfigsLoading && scoutConfigs === null) {+ // An empty fleet before the first sync settles is a troop still being assembled, not an empty+ // one — showing the empty state here would tell people to create a scout moments before their+ // canonical fleet lands.+ if ((scoutConfigsLoading && scoutConfigs === null) || (scoutConfigs?.length === 0 && !scoutFleetSynced)) {return (<div className="flex flex-col gap-2 p-6"><LemonSkeleton className="h-8 w-full rounded" />diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.tsindex 4e56da9a5567..de9488b2063c 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts@@ -14,6 +14,7 @@ import { initKeaTests } from '~/test/init'import {signalsScoutChatTasksCreate,signalsScoutConfigList,+ signalsScoutConfigSync,signalsScoutConfigUpdate,signalsScoutRunsRecentPerScout,} from 'products/signals/frontend/generated/api'@@ -27,6 +28,7 @@ jest.mock('products/signals/frontend/generated/api', () => ({signalsScoutChatTasksCreate: jest.fn(),signalsScoutConfigDestroy: jest.fn(),signalsScoutConfigList: jest.fn(),+ signalsScoutConfigSync: jest.fn(),signalsScoutConfigUpdate: jest.fn(),signalsScoutRunsFindingsSummary: jest.fn(),signalsScoutRunsList: jest.fn(),@@ -37,6 +39,7 @@ const mockSignalsScoutChatTasksCreate = signalsScoutChatTasksCreate as jest.Mocktypeof signalsScoutChatTasksCreate>const mockSignalsScoutConfigList = signalsScoutConfigList as jest.MockedFunction<typeof signalsScoutConfigList>+const mockSignalsScoutConfigSync = signalsScoutConfigSync as jest.MockedFunction<typeof signalsScoutConfigSync>const mockSignalsScoutConfigUpdate = signalsScoutConfigUpdate as jest.MockedFunction<typeof signalsScoutConfigUpdate>const mockSignalsScoutRunsRecentPerScout = signalsScoutRunsRecentPerScout as jest.MockedFunction<typeof signalsScoutRunsRecentPerScout@@ -118,6 +121,7 @@ describe('scoutFleetLogic', () => {initKeaTests()mockSignalsScoutChatTasksCreate.mockReset()mockSignalsScoutConfigList.mockReset().mockResolvedValue([])+ mockSignalsScoutConfigSync.mockReset().mockResolvedValue([])mockSignalsScoutConfigUpdate.mockReset()mockSignalsScoutRunsRecentPerScout.mockReset().mockResolvedValue([])logic = scoutFleetLogic()@@ -323,6 +327,64 @@ describe('scoutFleetLogic', () => {await expectLogic(logic).toDispatchActions([expectedAction])})+ // The whole point of materializing on open: a project the coordinator never reached has no+ // configs at all, and the roster has no other way to get any.+ it('fills an empty roster from the fleet the sync materializes', async () => {+ mockSignalsScoutConfigSync.mockResolvedValue([BASE_CONFIG])+ logic.actions.loadScoutConfigsSuccess([])++ logic.actions.materializeScoutFleet()++ await expectLogic(logic).toDispatchActions(['syncScoutFleetSuccess'])+ expect(mockSignalsScoutConfigSync).toHaveBeenCalledWith(String(MOCK_TEAM_ID))+ expect(logic.values.scoutConfigs).toEqual([BASE_CONFIG])+ expect(logic.values.scoutFleetSynced).toBe(true)+ })++ it('materializes the fleet at most once per roster session', async () => {+ logic.actions.materializeScoutFleet()+ await expectLogic(logic).toDispatchActions(['syncScoutFleetSuccess'])++ logic.actions.materializeScoutFleet()+ await expectLogic(logic).toFinishAllListeners()++ expect(mockSignalsScoutConfigSync).toHaveBeenCalledTimes(1)+ })++ // Syncing on top of an in-flight list read would let the older read land last and blank the+ // roster the sync just filled.+ it('waits for an in-flight config read before materializing the fleet', async () => {+ const listRequest = deferred<SignalScoutConfigApi[]>()+ mockSignalsScoutConfigList.mockReturnValueOnce(listRequest.promise)+ mockSignalsScoutConfigSync.mockResolvedValue([BASE_CONFIG])+ logic.actions.loadScoutConfigs()++ logic.actions.materializeScoutFleet()+ await new Promise(setImmediate)+ expect(mockSignalsScoutConfigSync).not.toHaveBeenCalled()++ listRequest.resolve([])+ await expectLogic(logic).toDispatchActions(['loadScoutConfigsSuccess', 'syncScoutFleetSuccess'])+ expect(logic.values.scoutConfigs).toEqual([BASE_CONFIG])+ })++ // Materializing is a write, so a member without write access gets a 403. Either way the sync+ // has to settle: a roster stuck unsynced shows a skeleton over its empty state forever. The 500+ // row keeps a real outage from being swallowed into the same silent branch.+ it.each([+ [403, 'syncScoutFleetSuccess'],+ [404, 'syncScoutFleetSuccess'],+ [500, 'syncScoutFleetFailure'],+ ])('keeps the roster and settles the sync when it is refused with %s', async (status, expectedAction) => {+ mockSignalsScoutConfigSync.mockRejectedValueOnce(new ApiError('nope', status))++ logic.actions.materializeScoutFleet()++ await expectLogic(logic).toDispatchActions([expectedAction])+ expect(logic.values.scoutConfigs).toEqual([BASE_CONFIG])+ expect(logic.values.scoutFleetSynced).toBe(true)+ })+it('sends newer queued updates after an earlier request fails', async () => {const firstRequest = deferred<SignalScoutConfigApi>()const failingRequest = deferred<SignalScoutConfigApi>()diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.tsindex 5f115ed0154f..7ff680a6c94f 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts@@ -1,4 +1,15 @@-import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'+import {+ MakeLogicType,+ actions,+ connect,+ events,+ kea,+ listeners,+ path,+ reducers,+ selectors,+ sharedListeners,+} from 'kea'import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'@@ -16,6 +27,7 @@ import {signalsScoutConfigDestroy,signalsScoutConfigList,signalsScoutConfigRun,+ signalsScoutConfigSync,signalsScoutConfigUpdate,signalsScoutMetadataGet,signalsScoutRunsFindingsSummary,@@ -44,6 +56,8 @@ import { compareScoutsByName, SCOUT_GROUP_ORDER, scoutGroup, ScoutGroupKey, Scouexport type ScoutEnabledFilter = 'all' | 'enabled' | 'disabled'/** Roster order: A to Z by name, or by lifecycle group so scouts that need a decision lead. */export type ScoutRosterSort = 'name' | 'status'+import type { BreakPointFunction } from 'kea'+import { configMatchesScoutOwner, listScoutOwnerOptions } from '../utils/scoutOwners'import type { ScoutOwnerOption } from '../utils/scoutOwners'import {@@ -231,6 +245,8 @@ export interface scoutFleetLogicValues {scoutConfigs: SignalScoutConfig[] | nullscoutConfigsLoading: booleanscoutEnabledFilter: ScoutEnabledFilter+ scoutFleetSyncRequested: boolean+ scoutFleetSynced: booleanscoutMetadata: ScoutMetadataApi | nullscoutMetadataLoading: booleanscoutOwnerOptions: ScoutOwnerOption[]@@ -349,6 +365,9 @@ export interface scoutFleetLogicActions {scoutRuns: SignalScoutRunSummary[]payload?: void}+ materializeScoutFleet: () => {+ value: true+ }patchScoutConfigLocally: (configId: string,updates: Partial<SignalScoutConfig> | SignalScoutConfigUpdate@@ -402,6 +421,21 @@ export interface scoutFleetLogicActions {stopRunsPolling: () => {value: true}+ syncScoutFleet: (_: void) => void+ syncScoutFleetFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ syncScoutFleetSuccess: (+ scoutConfigs: SignalScoutConfigApi[] | null,+ payload?: void+ ) => {+ scoutConfigs: SignalScoutConfigApi[] | null+ payload?: void+ }updateScoutConfig: (configId: string,updates: SignalScoutConfigUpdate@@ -416,6 +450,17 @@ export interface scoutFleetLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scoutFleetLogicMeta {+ sharedListeners: {+ syncScoutFleetIfOwed: (+ payload: any,+ breakpoint: BreakPointFunction,+ action: {+ type: string+ payload: any+ },+ previousState: any+ ) => void | Promise<void>+ }__keaTypeGenInternalSelectorTypes: {aiConsentDisabledReason: (dataProcessingAccepted: boolean,@@ -490,6 +535,9 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([}),actions({+ // Fired when the roster opens. The listener decides whether a sync is still owed, so the+ // caller never has to know whether one already ran.+ materializeScoutFleet: true,updateScoutConfig: (configId: string, updates: SignalScoutConfigUpdate) => ({ configId, updates }),updateScoutConfigFinished: (configId: string) => ({ configId }),// A full server config doubles as a local patch when reconciling optimistic edits.@@ -558,6 +606,33 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([throw error}},+ // Materializing the fleet is what fills an empty roster: the endpoint seeds the+ // canonical `signals-scout-*` skills, registers a config for every scout missing+ // one, retires the ones no longer shipped, and answers with the whole fleet. A+ // project the Temporal coordinator never reached would otherwise show no scouts at+ // all, and one seeded before a scout shipped would never pick that scout up.+ // Answering with the fleet means the roster fills from this call alone.+ syncScoutFleet: async (_: void, breakpoint) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return values.scoutConfigs+ }+ try {+ const configs = await signalsScoutConfigSync(String(teamId))+ // Same unmount race as `loadScoutConfigs`: break before reading `values`.+ breakpoint()+ return reconcileById(values.scoutConfigs ?? [], configs, (config) => config.id)+ } catch (error) {+ // Materializing is a write, so a member without write access gets a 403 —+ // as does a stale project id (404). Keep whatever the list read returned+ // rather than blanking the roster. Anything else, notably a 5xx, still+ // throws so a real backend failure reaches error tracking.+ if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {+ return values.scoutConfigs+ }+ throw error+ }+ },},],// Cheap fleet-wide output tally for the "Scout findings" callout — one backend query over@@ -745,6 +820,28 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([state?.filter((config) => config.id !== configId) ?? state,},],+ // Set when the roster opens. Without it the retry on `loadScoutConfigsSuccess` would fire a+ // materialization for the always-mounted setup widget too, POSTing on every page load from+ // people who never opened the Scouts tab.+ scoutFleetSyncRequested: [+ false,+ {+ materializeScoutFleet: () => true,+ },+ ],+ // Flips true once the fleet materialization settles, either way. It does double duty: the+ // listener reads it so one roster session syncs at most once, and the roster reads it to+ // tell "the fleet is still being materialized" from "this project genuinely has no scouts",+ // so nobody is shown an empty state over a fleet that is seconds from arriving. Set on+ // failure too — a roster that can never sync has to reach its empty state rather than+ // sit under a skeleton forever.+ scoutFleetSynced: [+ false,+ {+ syncScoutFleetSuccess: () => true,+ syncScoutFleetFailure: () => true,+ },+ ],// Scouts with a delete request in flight — drives the delete button's loading/disabled state// so a slow request can't be submitted twice from the still-visible row.deletingScoutIds: [@@ -989,7 +1086,20 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([],}),- listeners(({ actions, values, cache }) => ({+ sharedListeners(({ actions, values }) => ({+ // Materialize the fleet once the roster has asked for it and nothing is reading configs.+ // Once per roster session is the whole debounce: the canonical fleet only changes on a+ // deploy, and a scout the person creates lands in the roster on its own, so re-running the+ // reconcile every time they flip back to the tab buys nothing.+ syncScoutFleetIfOwed: () => {+ if (!values.scoutFleetSyncRequested || values.scoutFleetSynced || values.scoutConfigsLoading) {+ return+ }+ actions.syncScoutFleet()+ },+ })),++ listeners(({ actions, values, cache, sharedListeners }) => ({loadScoutRunsSuccess: () => {const evaluatedAt = new Date(values.rosterEvaluatedAt)const now = new Date()@@ -1268,6 +1378,12 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([actions.startScoutChatTaskFailure()}},+ materializeScoutFleet: sharedListeners.syncScoutFleetIfOwed,+ // The roster can open while the first config read is still in flight. Syncing on top of it+ // would let the older read land last and blank the roster again, so the sync waits for the+ // read to settle and starts from here instead.+ loadScoutConfigsSuccess: sharedListeners.syncScoutFleetIfOwed,+ loadScoutConfigsFailure: sharedListeners.syncScoutFleetIfOwed,startRunsPolling: () => {// Fetch once immediately, then a slow poll keeps "running now" + recent emissions// fresh. The keyed disposable is torn down on stopRunsPolling / unmount / tab hide.diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 21d5dc26eca9..f039863733e5 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -953,7 +953,7 @@ export const SignalsScoutConfigRunParams = /* @__PURE__ */ zod.object({})/**- * Materialize the scout fleet for this project on demand (idempotent): seed the canonical `signals-scout-*` skills, create a default-schedule config for any scout lacking one, and return all scout configs. Normally the Temporal coordinator does this on its next tick; this action exists so setup flows (e.g. the wizard's self-driving program) can hand the user a tunable fleet immediately.+ * Materialize the scout fleet for this project on demand (idempotent): seed the canonical `signals-scout-*` skills, create a default-schedule config for any scout lacking one, retire the skills whose canonical scout no longer ships, and return all scout configs. Normally the Temporal coordinator does this on its next tick; this action exists so the scout UIs and setup flows (e.g. the wizard's self-driving program) can hand the user a tunable fleet immediately.* @summary Sync scout configs*/export const SignalsScoutConfigSyncParams = /* @__PURE__ */ zod.object({