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.

feat(signals): record scout fleet sync outcomes (#91843)

posthog[bot]aeb662903bc8
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index cde9a4a5e59f..cfe43a9ab395 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -170,6 +170,22 @@ export function getPosthogApiClientAppVersion(): string {
return clientAppVersion;
}
+/**
+ * A scout endpoint answered with a non-2xx. Carries the status so a caller can tell a
+ * refusal it has to live with — 403 for a member without `signal_scout:write`, 404 for a
+ * stale project id — from a real outage worth retrying or reporting.
+ */
+export class ScoutRequestError extends Error {
+ constructor(
+ readonly status: number,
+ subPath: string,
+ statusText: string,
+ ) {
+ super(`Scout request failed (${subPath}): ${statusText}`);
+ this.name = "ScoutRequestError";
+ }
+}
+
export class SandboxCustomImagesDisabledError extends Error {
constructor(message?: string) {
super(message ?? "Custom sandbox images are not enabled");
@@ -2171,8 +2187,10 @@ export class PostHogAPIClient {
path: urlPath,
});
if (!response.ok) {
- throw new Error(
- `Scout request failed (${subPath}): ${response.statusText}`,
+ throw new ScoutRequestError(
+ response.status,
+ subPath,
+ response.statusText,
);
}
return (await response.json()) as T;
@@ -2182,9 +2200,13 @@ export class PostHogAPIClient {
projectId: number,
subPath: string,
body: unknown,
+ query?: Record<string, string | number | boolean | undefined>,
): Promise<T> {
const urlPath = `/api/projects/${projectId}/signals/scout/${subPath}`;
const url = new URL(`${this.api.baseUrl}${urlPath}`);
+ for (const [key, value] of Object.entries(query ?? {})) {
+ if (value !== undefined) url.searchParams.set(key, String(value));
+ }
const response = await this.api.fetcher.fetch({
method: "post",
url,
@@ -2194,8 +2216,10 @@ export class PostHogAPIClient {
},
});
if (!response.ok) {
- throw new Error(
- `Scout request failed (${subPath}): ${response.statusText}`,
+ throw new ScoutRequestError(
+ response.status,
+ subPath,
+ response.statusText,
);
}
return (await response.json()) as T;
@@ -2217,7 +2241,7 @@ export class PostHogAPIClient {
async syncScoutConfigs(projectId: number): Promise<ScoutConfig[]> {
const data = await this.scoutPost<
{ results: ScoutConfig[] } | ScoutConfig[]
- >(projectId, "configs/sync/", {});
+ >(projectId, "configs/sync/", {}, { surface: "desktop" });
return Array.isArray(data) ? data : (data.results ?? []);
}
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index b5f92128dec4..1767fd45fdec 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -908,12 +908,30 @@ type ScoutActionType =
| "filter_findings"
| "sort_findings";
+/**
+ * How the fleet materialization that preceded this view ended. Without it an
+ * `is_empty: true` view from a viewer whose sync was refused looks exactly like
+ * one from a project whose fleet genuinely failed to arrive.
+ */
+export type ScoutFleetSyncOutcome =
+ /** The sync ran and answered with the fleet. */
+ | "synced"
+ /** No sync was issued — no project was resolved when the section opened. */
+ | "not_attempted"
+ /** 403: a member without `signal_scout:write`. The list query still fills the section. */
+ | "skipped_permission"
+ /** 404: a stale project id. */
+ | "not_found"
+ /** Anything else, including a 5xx. */
+ | "failed";
+
export interface ScoutFleetViewedProperties {
scout_count: number;
enabled_count: number;
dry_run_count: number;
custom_count: number;
is_empty: boolean;
+ sync_outcome: ScoutFleetSyncOutcome;
}
export interface ScoutDetailViewedProperties {
diff --git a/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsx b/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsx
index c51d67536a03..91cf62803f43 100644
--- a/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsx
+++ b/products/desktop/packages/ui/src/features/scouts/components/ScoutsFleetSection.tsx
@@ -27,7 +27,7 @@ import {
type ScoutRunsWindow,
scoutRunsWindowLabel,
} from "@posthog/core/scouts/scoutRunsWindow";
-import type { ScoutChatType } from "@posthog/shared";
+import type { ScoutChatType, ScoutFleetSyncOutcome } from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared";
import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";
import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";
@@ -58,7 +58,7 @@ 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 { isSyncing, syncOutcome } = useScoutFleetSync();
const [expanded, setExpanded] = useState(false);
const lastRunAt = useMemo(() => {
@@ -105,7 +105,7 @@ export function ScoutsFleetSection() {
}
if (!configs || configs.length === 0) {
- return <ScoutsEmptyState />;
+ return <ScoutsEmptyState syncOutcome={syncOutcome} />;
}
const enabledCount = configs.filter((config) => config.enabled).length;
@@ -150,15 +150,22 @@ export function ScoutsFleetSection() {
}`}
/>
</button>
- {expanded ? <ScoutsFleetList configs={configs} /> : null}
+ {expanded ? (
+ <ScoutsFleetList configs={configs} syncOutcome={syncOutcome} />
+ ) : null}
</Flex>
);
}
-function useTrackFleetViewed(configs: ScoutConfig[]) {
+function useTrackFleetViewed(
+ configs: ScoutConfig[],
+ syncOutcome: ScoutFleetSyncOutcome | null,
+) {
const tracked = useRef(false);
useEffect(() => {
- if (tracked.current) return;
+ // Wait for the sync to settle, so a fleet the sync is about to change is
+ // never reported against an outcome the request has not reached yet.
+ if (tracked.current || syncOutcome === null) return;
tracked.current = true;
track(ANALYTICS_EVENTS.SCOUT_FLEET_VIEWED, {
scout_count: configs.length,
@@ -168,16 +175,23 @@ function useTrackFleetViewed(configs: ScoutConfig[]) {
(config) => getScoutOrigin(config) === "custom",
).length,
is_empty: configs.length === 0,
+ sync_outcome: syncOutcome,
});
- }, [configs]);
+ }, [configs, syncOutcome]);
}
-function ScoutsFleetList({ configs }: { configs: ScoutConfig[] }) {
+function ScoutsFleetList({
+ configs,
+ syncOutcome,
+}: {
+ configs: ScoutConfig[];
+ syncOutcome: ScoutFleetSyncOutcome | null;
+}) {
const { data: runsWindow } = useScoutRuns();
const { updateConfig } = useScoutConfigMutations();
const { data: creators } = useScoutSkillCreators();
const { data: currentUser } = useMeQuery();
- useTrackFleetViewed(configs);
+ useTrackFleetViewed(configs, syncOutcome);
return (
<ScoutsFleetListView
@@ -448,8 +462,12 @@ function ScoutChatCta({
);
}
-function ScoutsEmptyState() {
- useTrackFleetViewed(EMPTY_CONFIGS);
+function ScoutsEmptyState({
+ syncOutcome,
+}: {
+ syncOutcome: ScoutFleetSyncOutcome | null;
+}) {
+ useTrackFleetViewed(EMPTY_CONFIGS, syncOutcome);
return (
<Flex direction="column" gap="3">
<Flex
diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.test.tsx b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.test.tsx
new file mode 100644
index 000000000000..e9b2cd06c953
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.test.tsx
@@ -0,0 +1,70 @@
+import { ScoutRequestError } from "@posthog/api-client/posthog-client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderHook, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const syncScoutConfigs = vi.hoisted(() => vi.fn());
+
+vi.mock("@posthog/ui/features/auth/store", () => ({
+ useAuthStateValue: (
+ select: (state: { currentProjectId: number | null }) => unknown,
+ ) => select({ currentProjectId: 42 }),
+}));
+vi.mock("@posthog/ui/features/auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => ({ syncScoutConfigs }),
+}));
+vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({
+ AUTH_SCOPED_QUERY_META: {},
+}));
+
+import { useScoutFleetSync } from "./useScoutFleetSync";
+
+function wrapper({ children }: { children: ReactNode }) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+describe("useScoutFleetSync", () => {
+ beforeEach(() => {
+ syncScoutConfigs.mockReset();
+ });
+
+ // A refused sync leaves the section on whatever the list query returned, so an empty fleet
+ // from a viewer who cannot write looks exactly like a project that has no scouts. The
+ // outcome is what tells those apart on `Scout fleet viewed`.
+ it.each([
+ ["a fleet", "synced", null],
+ [
+ "403",
+ "skipped_permission",
+ new ScoutRequestError(403, "configs/sync/", "Forbidden"),
+ ],
+ [
+ "404",
+ "not_found",
+ new ScoutRequestError(404, "configs/sync/", "Not Found"),
+ ],
+ [
+ "500",
+ "failed",
+ new ScoutRequestError(500, "configs/sync/", "Server Error"),
+ ],
+ ["a network drop", "failed", new Error("offline")],
+ ])("reports %s as %s", async (_label, expected, error) => {
+ if (error) {
+ syncScoutConfigs.mockRejectedValue(error);
+ } else {
+ syncScoutConfigs.mockResolvedValue([]);
+ }
+
+ const { result } = renderHook(() => useScoutFleetSync(), { wrapper });
+
+ await waitFor(() => expect(result.current.isSyncing).toBe(false));
+ expect(result.current.syncOutcome).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.ts b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.ts
index 42f6d6bc4101..a65db715557a 100644
--- a/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.ts
+++ b/products/desktop/packages/ui/src/features/scouts/hooks/useScoutFleetSync.ts
@@ -1,4 +1,6 @@
import type { ScoutConfig } from "@posthog/api-client/posthog-client";
+import { ScoutRequestError } from "@posthog/api-client/posthog-client";
+import type { ScoutFleetSyncOutcome } from "@posthog/shared";
import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
import { useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
@@ -10,6 +12,29 @@ import { scoutQueryKeys } from "./scoutQueryKeys";
// re-running the reconcile every time they reopen the section buys nothing.
const FLEET_SYNC_STALE_MS = 60 * 60_000;
+// A refused sync leaves the section on whatever the list query returned, so the
+// fleet on screen can be stale (403, a member without write access) or from
+// another project (404, a stale project id) with nothing on screen saying so.
+// The outcome rides on `Scout fleet viewed` to keep those apart. Null while the
+// sync is still in flight, so a view is never reported against an outcome the
+// request has not reached yet.
+function syncOutcomeFor(
+ isSyncing: boolean,
+ isPending: boolean,
+ error: Error | null,
+): ScoutFleetSyncOutcome | null {
+ if (isSyncing) return null;
+ if (error instanceof ScoutRequestError) {
+ if (error.status === 403) return "skipped_permission";
+ if (error.status === 404) return "not_found";
+ return "failed";
+ }
+ if (error) return "failed";
+ // A query the hook disables (signed out, no project) settles pending, and no
+ // sync was ever issued for it.
+ return isPending ? "not_attempted" : "synced";
+}
+
/**
* Materializes the project's scout fleet when the scouts section opens. A
* project the Temporal coordinator never reached has no scout configs at all,
@@ -23,10 +48,14 @@ const FLEET_SYNC_STALE_MS = 60 * 60_000;
export function useScoutFleetSync(): {
/** False once the first sync settles, success or failure. */
isSyncing: boolean;
+ /** How that sync ended, for the `Scout fleet viewed` event. Null until it settles. */
+ syncOutcome: ScoutFleetSyncOutcome | null;
} {
const projectId = useAuthStateValue((state) => state.currentProjectId);
const queryClient = useQueryClient();
- const { data, isLoading } = useAuthenticatedQuery<ScoutConfig[]>(
+ const { data, isLoading, isPending, error } = useAuthenticatedQuery<
+ ScoutConfig[]
+ >(
scoutQueryKeys.fleetSync(projectId),
(client) =>
projectId ? client.syncScoutConfigs(projectId) : Promise.resolve([]),
@@ -49,5 +78,8 @@ export function useScoutFleetSync(): {
// `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 };
+ return {
+ isSyncing: isLoading,
+ syncOutcome: syncOutcomeFor(isLoading, isPending, error),
+ };
}
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index d8af3f22904a..73a6ecad483e 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -20,6 +20,9 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
`resolve_skill_owner_user_uuids` exposes the owner set (seed-creator first) to the report tools' reviewer provenance stamp (`is_skill_owner`). Author resolution is opt-in via `load_skill_for_run(..., include_authors=True)` — only the runner's prompt-building path pays for it; the report-authorization gate in `views.py` loads the skill per report write just to check `allowed_tools` and skips it.
- `lazy_seed.py`
Canonical skill sync. Reads `products/signals/skills/signals-scout-*/` from disk and reconciles them against the team's `LLMSkill` rows: creates missing rows, updates ones the team hasn't edited, leaves diverged / hand-authored rows alone, tombstones rows whose canonical skill was deleted. Only rows tagged `metadata.seeded_by="signals_scout_harness"` are ever updated. Called both lazily (coordinator tick, runner cold-start) and explicitly via the `sync_signals_scout_skills` management command.
+- `fleet_sync.py`
+ `materialize_scout_fleet(team, surface=...)` — the on-demand `configs/sync/` path, and the only place that records what a materialization did. Resolves the seed posture + holdback from one flag read, runs `sync_canonical_skills(prune=True)` and `register_missing_configs`, then captures `signals_scout_fleet_synced` with the per-bucket counts the `SyncResult` carries (created / updated / diverged / tombstoned / pruned), the configs it registered, the fleet it left behind, whether the project had one before (`was_empty` — the rescue metric), the `surface` the caller declared, and how long the pass took. Every sync captures, zero counts included: a no-op sync is the denominator for "how often does opening the tab find work to do". Best-effort, like every other scout event.
+ It also carries the mass-prune tripwire. A reap that takes more than half the canonical fleet, and at least `MASS_PRUNE_FLOOR` scouts, is not a retirement — it means the sync read a fleet the deploy did not ship — so it stamps `unexpected_prune` on the event and captures `UnexpectedScoutFleetPrune` into error tracking. A detector, not a guard: by the time the count exists the rows are tombstoned.
- `config_registry.py`
`register_missing_configs(team_id)` — auto-creates an enabled, default-schedule `SignalScoutConfig` for any `signals-scout-*` skill lacking one ("author a skill, get a scout"). Called by the coordinator tick; the HTTP surface registers explicitly via the write-scoped config `create` endpoint instead (reads stay side-effect free). A canonical scout's `scout-tags` frontmatter (read through `lazy_seed.canonical_config_tags_for`) is stamped on the row it creates, which is how a product surface claims its scouts by tag instead of by hardcoded skill name — AI observability's self-driving tab lists the `ai-observability`-tagged configs. Forward-only like the rest of the seed posture: adding the key to an already-seeded scout leaves that team's existing config untagged until someone tags it through the config API.
- `slack_delivery.py` / `slack_delivery_queue.py` / `slack_charts.py`
@@ -112,6 +115,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
`signals_scout_run_started` (the run cleared the guards and a TaskRun exists), `signals_scout_run_finished` (terminal: `completed`/`failed`/`cancelled` + runtime + emit count), and `signals_scout_run_reaped` (a stranded orphan was reaped by `_self_heal_stale_runs`). They join on `run_id`/`task_run_id` and are the event-derived (no-warehouse-lag) basis for throughput, stall, and worker-death alerting — a `started` with no `finished` is a run that died before finalize; a reaped run emits no `finished`.
When the model resolution (a config pin, the `scouts-model-selection` gate, or a runtime pin) routes the run, `started` and `finished` also carry `model` / `runtime_adapter`, so run outcomes are sliceable by model without joining through `$ai_generation`; absence means the agent-server default served it.
A `finished` run that died at the per-turn poll wall also carries the turn-log diagnostics from `TurnPollTimeout.diagnostics()` (`poll_timeout_stage` + elapsed/stale/line counts), because every wall failure raises one error string and the fleet's timeout rate is otherwise a single undifferentiated bucket: `no_turn_output` (the agent never emitted a turn-relevant line — it never got going), `stalled_after_output` (worked, then went quiet past the salvage window), `active_at_budget` (still streaming when the budget expired — the budget is the constraint, not the agent).
+ `signals_scout_fleet_synced` is the fleet-level companion, emitted from `fleet_sync.py` on the request path rather than per run — see that module's bullet above.
`signals_scout_config_auto_paused` fires once when a `(team, skill)` lane's failure-streak breaker trips (see the run-lifecycle bullet above) — the alertable signal for a wedged lane, which is otherwise invisible in a stream of individually-unremarkable `failed` runs.
The report channel adds `signals_scout_report_emitted` / `signals_scout_report_edited` (plus customer-facing `$scout_report_*` copies), stamped with derived classification properties (`report_kind` = `finding`/`self_improvement`, `is_self_improvement_report`) via `_report_classification_props` in `tools/report.py` — classified server-side off the prompt's mandated title prefix (`prompt.SELF_IMPROVEMENT_REPORT_TITLE_PREFIX`), so self-improvement reports are separable without downstream title heuristics. That helper is the single extension point for future derived telemetry dimensions on these events — add new flags there (both events pick them up), not as model columns.
- Emit happens via the harness's `emit_signal_*` tools, which call `emit_signal()` with `source_product="signals_scout"` and `source_type="cross_source_issue"`.
diff --git a/products/signals/backend/scout_harness/fleet_sync.py b/products/signals/backend/scout_harness/fleet_sync.py
new file mode 100644
index 000000000000..b200e0c6e489
--- /dev/null
+++ b/products/signals/backend/scout_harness/fleet_sync.py
@@ -0,0 +1,174 @@
+"""On-demand scout fleet materialization, and the telemetry that makes it measurable.
+
+The body of the `signals/scout/configs/sync/` action minus its HTTP shell: resolve the team's
+seed posture and holdback from one flag read, reconcile the canonical skills, register a config
+for every scout missing one, and record what the pass actually did.
+
+The recording is the reason this module exists. `sync_canonical_skills` returns a full
+`SyncResult` and the endpoint discarded it, so the only trace of a materialization was a server
+log line. Nothing could count the projects a tab-open rescued, the scouts a sync seeded, or how
+long a cold project waited for its catalog. Every sync now captures
+`signals_scout_fleet_synced`, zero counts included — a no-op sync is the denominator for "how
+often does opening the tab find work to do".
+"""
+
+from __future__ import annotations
+
+import time
+import logging
+
+import posthoganalytics
+
+from posthog.event_usage import groups
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team.team import Team
+
+from products.signals.backend.models import SignalScoutConfig
+from products.signals.backend.scout_harness.config_registry import register_missing_configs
+from products.signals.backend.scout_harness.lazy_seed import SyncResult, canonical_skill_names, sync_canonical_skills
+from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX
+from products.signals.backend.scout_harness.team_limits import resolve_sync_seed_inputs
+
+logger = logging.getLogger(__name__)
+
+FLEET_SYNCED_EVENT = "signals_scout_fleet_synced"
+
+# Which surface asked for the materialization. The whole point of the `surface` dimension is to
+# separate a fleet the coordinator was going to deliver anyway from one a person's tab-open
+# rescued, so an unlabelled caller is recorded as unknown rather than folded into a real surface.
+SYNC_SURFACES = ("roster", "desktop", "wizard")
+UNKNOWN_SURFACE = "unknown"
+
+# A prune reaping more than half the canonical fleet, and at least this many scouts, is not a
+# retirement. Canonical scouts retire one or two at a time; a reap that size means the sync read
+# a fleet the deploy did not actually ship, and it has just tombstoned live scouts on every
+# project that opened the tab. The floor keeps a one-scout fleet from crying wolf.
+MASS_PRUNE_FLOOR = 3
+
+
+class UnexpectedScoutFleetPrune(Exception):
+ """One fleet sync tombstoned more canonical scouts than a retirement explains.
+
+ Captured, never raised at the caller: by the time the count exists the rows are already
+ tombstoned, so this is a detector, not a guard. It rides into error tracking because the
+ mass-prune failure mode has to be noticed within a deploy, not found later in an event
+ breakdown.
+ """
+
+
+def materialize_scout_fleet(team: Team, *, surface: str | None = None) -> set[str]:
+ """Reconcile `team`'s scout fleet against the canonical skills on disk, and record the outcome.
+
+ Returns the team's holdback denylist so the caller can keep withheld scouts out of the fleet
+ it answers with.
+
+ `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 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.
+ """
+ # Timed from the first read, not from the reconcile: `duration_ms` is what a cold project
+ # waits with its roster under a skeleton, and the flag read is part of that wait.
+ started_at = time.monotonic()
+ # Resolve the holdback denylist and the launch seed posture from a single flag read so they
+ # can't disagree if the flag changes mid-request (the coordinator reads once and threads the
+ # snapshot too). Holdback: a held-back scout can't be seeded or enabled by a manual fleet
+ # materialization. Posture: seed the same launch shape the coordinator applies, so a
+ # self-serve materialization doesn't bypass the launch cost posture by enabling the fleet.
+ seed_config_layers, withheld = resolve_sync_seed_inputs(team.id)
+ configs_before = _config_skill_names(team.id)
+ result = sync_canonical_skills(team, prune=True, withheld_skill_names=withheld)
+ register_missing_configs(team.id, seed_config_layers, withheld_skill_names=withheld)
+ configs_after = _config_skill_names(team.id)
+ _capture_fleet_synced(
+ team=team,
+ surface=surface,
+ result=result,
+ configs_before=configs_before,
+ configs_after=configs_after,
+ withheld_count=len(withheld),
+ duration_ms=round((time.monotonic() - started_at) * 1000),
+ )
+ return withheld
+
+
+def _config_skill_names(team_id: int) -> set[str]:
+ return set(SignalScoutConfig.objects.for_team(team_id).values_list("skill_name", flat=True))
+
+
+def _is_mass_prune(pruned_count: int) -> bool:
+ fleet_size = len([name for name in canonical_skill_names() if name.startswith(SIGNALS_SCOUT_SKILL_PREFIX)])
+ return pruned_count >= MASS_PRUNE_FLOOR and pruned_count > fleet_size // 2
+
+
+def _capture_fleet_synced(
+ *,
+ team: Team,
+ surface: str | None,
+ result: SyncResult,
+ configs_before: set[str],
+ configs_after: set[str],
+ withheld_count: int,
+ duration_ms: int,
+) -> None:
+ """Emit the fleet-synced analytics event, and trip the mass-prune wire when the reap is absurd.
+
+ Best-effort on both halves: a materialization that worked must not fail because its telemetry
+ did. `was_empty` paired with `fleet_size` is the rescue metric — a project that had no configs
+ and now has a fleet is one the coordinator had not reached.
+ """
+ pruned_count = len(result.pruned_skill_names)
+ unexpected_prune = _is_mass_prune(pruned_count)
+ if unexpected_prune:
+ _trip_mass_prune_wire(team=team, surface=surface, pruned_skill_names=result.pruned_skill_names)
+ try:
+ organization = team.organization
+ posthoganalytics.capture(
+ event=FLEET_SYNCED_EVENT,
+ distinct_id=str(team.uuid),
+ properties={
+ "team_id": team.id,
+ "organization_id": str(organization.id),
+ "surface": surface or UNKNOWN_SURFACE,
+ "created_count": len(result.created_skill_names),
+ "updated_count": len(result.updated_skill_names),
+ "diverged_count": len(result.diverged_skill_names),
+ "tombstoned_count": len(result.tombstoned_skill_names),
+ "pruned_count": pruned_count,
+ "configs_registered_count": len(configs_after - configs_before),
+ "withheld_count": withheld_count,
+ "fleet_size": len(configs_after),
+ "was_empty": not configs_before,
+ # Set when the canonical fleet could not be read at all, which is the one branch
+ # where every count above is zero for a reason other than "nothing to do".
+ "skipped_reason": result.skipped_reason,
+ "unexpected_prune": unexpected_prune,
+ "duration_ms": duration_ms,
+ },
+ groups=groups(organization, team),
+ )
+ except Exception:
+ logger.warning(
+ "signals_scout: failed to capture fleet-synced analytics event",
+ extra={"team_id": team.id},
+ )
+
+
+def _trip_mass_prune_wire(*, team: Team, surface: str | None, pruned_skill_names: tuple[str, ...]) -> None:
+ try:
+ capture_exception(
+ UnexpectedScoutFleetPrune(
+ f"Scout fleet sync tombstoned {len(pruned_skill_names)} canonical scouts in one pass"
+ ),
+ additional_properties={
+ "team_id": team.id,
+ "surface": surface or UNKNOWN_SURFACE,
+ "pruned_count": len(pruned_skill_names),
+ "pruned_skills": list(pruned_skill_names),
+ },
+ )
+ except Exception:
+ logger.warning(
+ "signals_scout: failed to report an unexpected fleet prune",
+ extra={"team_id": team.id, "pruned_skills": list(pruned_skill_names)},
+ )
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index d26dc579c3e4..c4c8fa544f2e 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -36,6 +36,7 @@ from products.signals.backend.models import SignalScoutConfig, SignalScoutEmissi
from products.signals.backend.report_charts import MAX_REPORT_CHARTS
from products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPT_LENGTH, MAX_SUGGESTED_PROMPTS
from products.signals.backend.scout_harness.derived_metadata import DERIVED_FLAG_KEYS, DERIVED_METADATA_KEY
+from products.signals.backend.scout_harness.fleet_sync import SYNC_SURFACES
from products.signals.backend.scout_harness.model_selection import scout_model_config_enabled, scout_model_pin_catalog
from products.signals.backend.scout_harness.note_targets import PIPELINE_AUDIENCES
from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX
@@ -537,6 +538,21 @@ class FleetFindingsSummaryQuerySerializer(serializers.Serializer):
)
+class ScoutFleetSyncQuerySerializer(serializers.Serializer):
+ """Query parameters for the `sync` action."""
+
+ surface = serializers.ChoiceField(
+ choices=SYNC_SURFACES,
+ required=False,
+ help_text=(
+ "Which surface asked for the materialization, recorded on the "
+ "`signals_scout_fleet_synced` analytics event so a fleet a person's tab-open "
+ "delivered is separable from one the coordinator was going to deliver anyway. "
+ "Omitted means unknown."
+ ),
+ )
+
+
class RecentRunsPerScoutQuerySerializer(serializers.Serializer):
"""Query parameters for the `recent-per-scout` action."""
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 5f8e1da6761b..82dff448d6f9 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -67,12 +67,9 @@ from products.signals.backend.pipeline_identity import pipeline_writer_identity
from products.signals.backend.quota import is_team_signals_quota_limited
from products.signals.backend.report_charts import ChartSize
from products.signals.backend.report_generation.resolve_reviewers import MAX_PROJECT_MEMBERS, list_project_members
-from products.signals.backend.scout_harness.config_registry import (
- enabled_scout_count,
- ensure_scout_category,
- register_missing_configs,
-)
-from products.signals.backend.scout_harness.lazy_seed import scout_skill_origin, sync_canonical_skills
+from products.signals.backend.scout_harness.config_registry import enabled_scout_count, ensure_scout_category
+from products.signals.backend.scout_harness.fleet_sync import materialize_scout_fleet
+from products.signals.backend.scout_harness.lazy_seed import scout_skill_origin
from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM, STALE_RUN_CUTOFF_S
from products.signals.backend.scout_harness.serializers import (
EditReportRequestSerializer,
@@ -94,6 +91,7 @@ from products.signals.backend.scout_harness.serializers import (
RecordStructuredOutputResponseSerializer,
RememberRequestSerializer,
ScoutEmissionReportLinkSerializer,
+ ScoutFleetSyncQuerySerializer,
ScoutMemberSerializer,
ScoutMembersQuerySerializer,
ScoutMetadataSerializer,
@@ -130,7 +128,6 @@ from products.signals.backend.scout_harness.team_limits import (
_resolve_max_runs_per_day,
_runs_today_by_team,
_team_configs,
- resolve_sync_seed_inputs,
resolve_team_metadata,
withheld_skills_for_team,
)
@@ -2386,8 +2383,8 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
config.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
- @extend_schema(
- request=None,
+ @validated_request(
+ query_serializer=ScoutFleetSyncQuerySerializer,
responses={
200: OpenApiResponse(
response=SignalScoutConfigSerializer(many=True),
@@ -2415,27 +2412,12 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
required_scopes=["signal_scout:write"],
pagination_class=None,
)
- def sync(self, request: Request, *args, **kwargs) -> Response:
+ def sync(self, request: ValidatedRequest, *args, **kwargs) -> Response:
# Scout rows persist under the canonical parent team (see `_canonical_team_id`);
# seed and register against that team so child-environment requests don't fork
# a second fleet.
team = self.team if self.team.parent_team_id is None else Team.objects.get(id=self.team.parent_team_id)
- # Resolve the holdback denylist + the launch seed posture from a single flag read so they
- # can't disagree if the flag changes mid-request (the coordinator reads once and threads the
- # snapshot too). Holdback: a held-back scout can't be seeded/enabled by a manual fleet
- # materialization (the coordinator already gates the scheduled path). Posture: seed the same
- # launch shape the coordinator applies (general-only / daily etc., team_configs over
- # 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)
- # `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)
+ withheld = materialize_scout_fleet(team, surface=request.validated_query_data.get("surface"))
# 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 would
# advertise an unreleased scout despite the holdback. Storage is left untouched (no
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 36e4a0f5eeb3..0febc4fe57d3 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -43,7 +43,9 @@ from products.signals.backend.pipeline_identity import AI_STAGE_RESEARCH
from 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,
+ SyncResult,
_compute_row_hash,
+ canonical_skill_names,
discover_canonical_skills,
)
from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_S
@@ -53,6 +55,7 @@ from products.signals.backend.scout_harness.serializers import (
SignalScoutConfigUpdateSerializer,
SignalScoutSlackDestinationSerializer,
)
+from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX
from products.signals.backend.scout_harness.team_limits import MAX_RUNS_PER_TEAM_PER_TICK
from products.signals.backend.scout_harness.tools import structured_output as structured_output_tool
from products.signals.backend.scout_harness.tools.profile import compute_project_profile
@@ -2749,6 +2752,73 @@ class TestScoutHarnessConfigAPI(APIBaseTest):
assert hand_authored.deleted is False
assert "signals-scout-mine" in {c["skill_name"] for c in response.json()}
+ def test_sync_records_what_the_materialization_did(self) -> None:
+ # The endpoint discarded the `SyncResult` it got back, so a materialization left nothing
+ # countable behind: not the projects a tab-open rescued, not the scouts a sync seeded.
+ with patch("products.signals.backend.scout_harness.fleet_sync.posthoganalytics.capture") as capture:
+ response = self.client.post(f"{self._sync_url()}?surface=roster")
+
+ assert response.status_code == status.HTTP_200_OK
+ (call,) = [c for c in capture.call_args_list if c.kwargs.get("event") == "signals_scout_fleet_synced"]
+ properties = call.kwargs["properties"]
+ assert properties["surface"] == "roster"
+ assert properties["team_id"] == self.team.id
+ # The rescue metric: this project had nothing and now has its fleet.
+ assert properties["was_empty"] is True
+ assert properties["created_count"] == len(discover_canonical_skills())
+ assert properties["configs_registered_count"] == len(response.json())
+ assert properties["fleet_size"] == len(response.json())
+ assert properties["pruned_count"] == 0
+ assert properties["unexpected_prune"] is False
+ assert properties["skipped_reason"] is None
+
+ def test_sync_records_a_no_op_pass(self) -> None:
+ # Zero counts are the denominator for "how often does opening the tab find work to do",
+ # so a pass that changed nothing still has to report.
+ self.client.post(self._sync_url())
+
+ with patch("products.signals.backend.scout_harness.fleet_sync.posthoganalytics.capture") as capture:
+ response = self.client.post(self._sync_url())
+
+ assert response.status_code == status.HTTP_200_OK
+ (call,) = [c for c in capture.call_args_list if c.kwargs.get("event") == "signals_scout_fleet_synced"]
+ properties = call.kwargs["properties"]
+ assert properties["created_count"] == 0
+ assert properties["configs_registered_count"] == 0
+ assert properties["was_empty"] is False
+ assert properties["surface"] == "unknown"
+
+ @parameterized.expand([("a retirement", False), ("a mass prune", True)])
+ def test_sync_reports_a_prune_too_large_to_be_a_retirement(self, _name: str, mass: bool) -> None:
+ # A deploy that ships a partial `products/signals/skills/` makes the reap strip live
+ # scouts off every project that opens the tab. Retiring one scout at a time is ordinary
+ # and must stay quiet; reaping the whole fleet in one pass has to reach error tracking,
+ # because the server log line it used to leave is watched by nothing.
+ fleet_size = len([n for n in canonical_skill_names() if n.startswith(SIGNALS_SCOUT_SKILL_PREFIX)])
+ pruned = tuple(f"signals-scout-gone-{i}" for i in range(fleet_size if mass else 1))
+ with (
+ patch(
+ "products.signals.backend.scout_harness.fleet_sync.sync_canonical_skills",
+ return_value=SyncResult(pruned_skill_names=pruned),
+ ),
+ patch("products.signals.backend.scout_harness.fleet_sync.capture_exception") as capture_exception,
+ patch("products.signals.backend.scout_harness.fleet_sync.posthoganalytics.capture") as capture,
+ ):
+ response = self.client.post(self._sync_url())
+
+ assert response.status_code == status.HTTP_200_OK
+ (call,) = [c for c in capture.call_args_list if c.kwargs.get("event") == "signals_scout_fleet_synced"]
+ assert call.kwargs["properties"]["pruned_count"] == len(pruned)
+ assert call.kwargs["properties"]["unexpected_prune"] is mass
+ assert capture_exception.called is mass
+
+ def test_sync_rejects_an_unknown_surface(self) -> None:
+ # Wiring guard for `@validated_request`: the action reads `validated_query_data`, which
+ # only the decorator sets, so dropping it turns every sync into a 500.
+ response = self.client.post(f"{self._sync_url()}?surface=somewhere")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
def test_sync_rejects_read_only_scope(self) -> None:
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 7cffe4315a4c..94035c1dd4c0 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -4197,6 +4197,27 @@ export type SignalsScoutConfigListParams = {
tags?: string
}
+export type SignalsScoutConfigSyncParams = {
+ /**
+ * Which surface asked for the materialization, recorded on the `signals_scout_fleet_synced` analytics event so a fleet a person's tab-open delivered is separable from one the coordinator was going to deliver anyway. Omitted means unknown.
+ *
+ * * `roster` - roster
+ * * `desktop` - desktop
+ * * `wizard` - wizard
+ * @minLength 1
+ */
+ surface?: SignalsScoutConfigSyncSurface
+}
+
+export type SignalsScoutConfigSyncSurface =
+ (typeof SignalsScoutConfigSyncSurface)[keyof typeof SignalsScoutConfigSyncSurface]
+
+export const SignalsScoutConfigSyncSurface = {
+ Roster: 'roster',
+ Desktop: 'desktop',
+ Wizard: 'wizard',
+} as const
+
export type SignalsScoutMembersListParams = {
/**
* Case-insensitive substring filter over member email and first/last name. Use it to narrow a large project's roster to the owner you're trying to match instead of pulling every member.
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 064ec428679d..398f5753f6a9 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -76,6 +76,7 @@ import type {
SignalsReportArtefactsListParams,
SignalsReportsListParams,
SignalsScoutConfigListParams,
+ SignalsScoutConfigSyncParams,
SignalsScoutMembersListParams,
SignalsScoutNotesListParams,
SignalsScoutProjectProfileGetParams,
@@ -854,8 +855,20 @@ export const signalsScoutConfigRun = async (
})
}
-export const getSignalsScoutConfigSyncUrl = (projectId: string) => {
- return `/api/projects/${projectId}/signals/scout/configs/sync/`
+export const getSignalsScoutConfigSyncUrl = (projectId: string, params?: SignalsScoutConfigSyncParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/signals/scout/configs/sync/?${stringifiedParams}`
+ : `/api/projects/${projectId}/signals/scout/configs/sync/`
}
/**
@@ -864,9 +877,10 @@ export const getSignalsScoutConfigSyncUrl = (projectId: string) => {
*/
export const signalsScoutConfigSync = async (
projectId: string,
+ params?: SignalsScoutConfigSyncParams,
options?: RequestInit
): Promise<SignalScoutConfigApi[]> => {
- return apiMutator<SignalScoutConfigApi[]>(getSignalsScoutConfigSyncUrl(projectId), {
+ return apiMutator<SignalScoutConfigApi[]>(getSignalsScoutConfigSyncUrl(projectId, params), {
...options,
method: 'POST',
})
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx
index 846723461212..3b7f30c47d1e 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx
@@ -25,8 +25,14 @@ 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, scoutFleetSynced, enabledCount, customScoutCount } =
- useValues(scoutFleetLogic)
+ const {
+ scoutConfigs,
+ scoutConfigsLoading,
+ scoutFleetSynced,
+ scoutFleetSyncOutcome,
+ enabledCount,
+ customScoutCount,
+ } = useValues(scoutFleetLogic)
const { loadScoutConfigs, materializeScoutFleet, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)
useEffect(() => {
@@ -41,11 +47,12 @@ export function ScoutsRoster(): JSX.Element {
}, [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. An empty fleet waits for
- // the materialization too, so a troop that is about to arrive is never counted as no troop.
+ // and reports nothing — an unreachable scout API isn't an empty troop. The report waits for the
+ // materialization either way: an empty troop that is about to arrive is never counted as no
+ // troop, and `sync_outcome` only means something once the sync has settled.
const fleetViewedFiredRef = useRef(false)
useEffect(() => {
- if (scoutConfigs === null || (scoutConfigs.length === 0 && !scoutFleetSynced) || fleetViewedFiredRef.current) {
+ if (scoutConfigs === null || !scoutFleetSynced || fleetViewedFiredRef.current) {
return
}
fleetViewedFiredRef.current = true
@@ -54,8 +61,9 @@ export function ScoutsRoster(): JSX.Element {
enabledCount,
customCount: customScoutCount,
dryRunCount: scoutConfigs.filter((config) => !config.emit).length,
+ syncOutcome: scoutFleetSyncOutcome,
})
- }, [scoutConfigs, scoutFleetSynced, enabledCount, customScoutCount])
+ }, [scoutConfigs, scoutFleetSynced, scoutFleetSyncOutcome, enabledCount, customScoutCount])
if (scoutConfigsLoading && scoutConfigs === null) {
return (
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterLegacy.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterLegacy.tsx
index a5d2c7cb6c9d..6eb75416ba65 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterLegacy.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterLegacy.tsx
@@ -28,8 +28,14 @@ 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, scoutFleetSynced, enabledCount, customScoutCount } =
- useValues(scoutFleetLogic)
+ const {
+ scoutConfigs,
+ scoutConfigsLoading,
+ scoutFleetSynced,
+ scoutFleetSyncOutcome,
+ 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.
@@ -51,11 +57,12 @@ export function ScoutsRosterLegacy(): JSX.Element {
}, [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. An empty fleet waits for
- // the materialization too, so a troop that is about to arrive is never counted as no troop.
+ // and reports nothing — an unreachable scout API isn't an empty troop. The report waits for the
+ // materialization either way: an empty troop that is about to arrive is never counted as no
+ // troop, and `sync_outcome` only means something once the sync has settled.
const fleetViewedFiredRef = useRef(false)
useEffect(() => {
- if (scoutConfigs === null || (scoutConfigs.length === 0 && !scoutFleetSynced) || fleetViewedFiredRef.current) {
+ if (scoutConfigs === null || !scoutFleetSynced || fleetViewedFiredRef.current) {
return
}
fleetViewedFiredRef.current = true
@@ -64,8 +71,9 @@ export function ScoutsRosterLegacy(): JSX.Element {
enabledCount,
customCount: customScoutCount,
dryRunCount: scoutConfigs.filter((config) => !config.emit).length,
+ syncOutcome: scoutFleetSyncOutcome,
})
- }, [scoutConfigs, scoutFleetSynced, enabledCount, customScoutCount])
+ }, [scoutConfigs, scoutFleetSynced, scoutFleetSyncOutcome, enabledCount, customScoutCount])
// 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
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.ts
index 2c8d4ab35c01..5787ab042d29 100644
--- a/products/signals/frontend/inbox/inboxAnalytics.ts
+++ b/products/signals/frontend/inbox/inboxAnalytics.ts
@@ -638,12 +638,30 @@ function settingValueProperties(key: string, value: unknown): Record<string, unk
return { [key]: value ?? null, [`${key}_size`]: null }
}
+/**
+ * How the fleet materialization that preceded this view ended. The roster keeps its existing list
+ * when the sync is refused, so without this an `is_empty: true` view from a viewer who cannot write
+ * looks exactly like one from a project whose fleet genuinely failed to arrive.
+ */
+export type ScoutFleetSyncOutcome =
+ /** The sync ran and answered with the fleet. */
+ | 'synced'
+ /** No sync was issued — the roster opened before a project was resolved. */
+ | 'not_attempted'
+ /** 403: a member without `signal_scout:write`. The roster shows whatever the list read returned. */
+ | 'skipped_permission'
+ /** 404: a stale project id, usually left in the URL by a project switch. */
+ | 'not_found'
+ /** Anything else, including a 5xx. */
+ | 'failed'
+
/** Roster shape at the moment the scout troop list was opened. Mirrors desktop's `Scout fleet viewed`. */
export function captureScoutFleetViewed(params: {
scoutCount: number
enabledCount: number
customCount: number
dryRunCount: number
+ syncOutcome: ScoutFleetSyncOutcome
}): void {
captureInboxEvent(INBOX_EVENTS.SCOUT_FLEET_VIEWED, {
scout_count: params.scoutCount,
@@ -651,6 +669,7 @@ export function captureScoutFleetViewed(params: {
custom_count: params.customCount,
dry_run_count: params.dryRunCount,
is_empty: params.scoutCount === 0,
+ sync_outcome: params.syncOutcome,
})
}
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
index de9488b2063c..4726ae115aa1 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
@@ -336,9 +336,10 @@ describe('scoutFleetLogic', () => {
logic.actions.materializeScoutFleet()
await expectLogic(logic).toDispatchActions(['syncScoutFleetSuccess'])
- expect(mockSignalsScoutConfigSync).toHaveBeenCalledWith(String(MOCK_TEAM_ID))
+ expect(mockSignalsScoutConfigSync).toHaveBeenCalledWith(String(MOCK_TEAM_ID), { surface: 'roster' })
expect(logic.values.scoutConfigs).toEqual([BASE_CONFIG])
expect(logic.values.scoutFleetSynced).toBe(true)
+ expect(logic.values.scoutFleetSyncOutcome).toBe('synced')
})
it('materializes the fleet at most once per roster session', async () => {
@@ -370,20 +371,26 @@ describe('scoutFleetLogic', () => {
// 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.
+ // row keeps a real outage from being swallowed into the same silent branch. Each refusal has to
+ // report its own outcome — a roster kept because the sync was refused reads as an empty fleet
+ // otherwise, and `Scout fleet viewed` can't tell that from a project with no scouts.
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)
- })
+ [403, 'syncScoutFleetSuccess', 'skipped_permission'],
+ [404, 'syncScoutFleetSuccess', 'not_found'],
+ [500, 'syncScoutFleetFailure', 'failed'],
+ ])(
+ 'keeps the roster and settles the sync when it is refused with %s',
+ async (status, expectedAction, expectedOutcome) => {
+ 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)
+ expect(logic.values.scoutFleetSyncOutcome).toBe(expectedOutcome)
+ }
+ )
it('sends newer queued updates after an earlier request fails', async () => {
const firstRequest = deferred<SignalScoutConfigApi>()
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
index 7ff680a6c94f..015913face58 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
@@ -47,6 +47,7 @@ import {
captureScoutChatStarted,
captureScoutConfigChanged,
ScoutChatType,
+ ScoutFleetSyncOutcome,
ScoutSurface,
} from '../inboxAnalytics'
import { SignalScoutRunSummary } from '../types'
@@ -245,6 +246,7 @@ export interface scoutFleetLogicValues {
scoutConfigs: SignalScoutConfig[] | null
scoutConfigsLoading: boolean
scoutEnabledFilter: ScoutEnabledFilter
+ scoutFleetSyncOutcome: ScoutFleetSyncOutcome
scoutFleetSyncRequested: boolean
scoutFleetSynced: boolean
scoutMetadata: ScoutMetadataApi | null
@@ -390,6 +392,9 @@ export interface scoutFleetLogicActions {
setScoutEnabledFilter: (filter: ScoutEnabledFilter) => {
filter: ScoutEnabledFilter
}
+ setScoutFleetSyncOutcome: (outcome: ScoutFleetSyncOutcome) => {
+ outcome: ScoutFleetSyncOutcome
+ }
setScoutOwnerFilter: (owner: string | null) => {
owner: string | null
}
@@ -574,9 +579,10 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
}),
startScoutChatTaskSuccess: true,
startScoutChatTaskFailure: true,
+ setScoutFleetSyncOutcome: (outcome: ScoutFleetSyncOutcome) => ({ outcome }),
}),
- loaders(({ values }) => ({
+ loaders(({ actions, values }) => ({
scoutConfigs: [
null as SignalScoutConfig[] | null,
{
@@ -618,9 +624,10 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
return values.scoutConfigs
}
try {
- const configs = await signalsScoutConfigSync(String(teamId))
+ const configs = await signalsScoutConfigSync(String(teamId), { surface: 'roster' })
// Same unmount race as `loadScoutConfigs`: break before reading `values`.
breakpoint()
+ actions.setScoutFleetSyncOutcome('synced')
return reconcileById(values.scoutConfigs ?? [], configs, (config) => config.id)
} catch (error) {
// Materializing is a write, so a member without write access gets a 403 —
@@ -628,6 +635,10 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
// 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)) {
+ // Record which refusal it was. Both leave the roster on whatever the
+ // list read returned, so the `Scout fleet viewed` that follows would
+ // otherwise be indistinguishable from a project with no scouts.
+ actions.setScoutFleetSyncOutcome(error.status === 403 ? 'skipped_permission' : 'not_found')
return values.scoutConfigs
}
throw error
@@ -842,6 +853,17 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
syncScoutFleetFailure: () => true,
},
],
+ // Why the roster looks the way it does, read by `Scout fleet viewed`. The sync loader
+ // swallows the refusals it can't act on and answers with the previous list, so only the
+ // loader knows which branch it took — hence the explicit set rather than a mapping off
+ // success. `syncScoutFleetFailure` covers the branch that rethrows.
+ scoutFleetSyncOutcome: [
+ 'not_attempted' as ScoutFleetSyncOutcome,
+ {
+ setScoutFleetSyncOutcome: (_, { outcome }) => outcome,
+ syncScoutFleetFailure: () => 'failed' as ScoutFleetSyncOutcome,
+ },
+ ],
// 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: [
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 61a494110d9a..9a48ba44bde0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -97552,6 +97552,27 @@ export namespace Schemas {
tags?: string;
};
+ export type SignalsScoutConfigSyncParams = {
+ /**
+ * Which surface asked for the materialization, recorded on the `signals_scout_fleet_synced` analytics event so a fleet a person's tab-open delivered is separable from one the coordinator was going to deliver anyway. Omitted means unknown.
+ *
+ * * `roster` - roster
+ * * `desktop` - desktop
+ * * `wizard` - wizard
+ * @minLength 1
+ */
+ surface?: SignalsScoutConfigSyncSurface;
+ };
+
+ export type SignalsScoutConfigSyncSurface = typeof SignalsScoutConfigSyncSurface[keyof typeof SignalsScoutConfigSyncSurface];
+
+
+ export const SignalsScoutConfigSyncSurface = {
+ Roster: 'roster',
+ Desktop: 'desktop',
+ Wizard: 'wizard',
+ } as const;
+
export type SignalsScoutMembersListParams = {
/**
* Case-insensitive substring filter over member email and first/last name. Use it to narrow a large project's roster to the owner you're trying to match instead of pulling every member.
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index e7a76b420e7a..c0b1e755c4c5 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -1028,6 +1028,15 @@ export const SignalsScoutConfigSyncParams = /* @__PURE__ */ zod.object({
),
})
+export const SignalsScoutConfigSyncQueryParams = /* @__PURE__ */ zod.object({
+ surface: zod
+ .enum(['roster', 'desktop', 'wizard'])
+ .optional()
+ .describe(
+ "Which surface asked for the materialization, recorded on the `signals_scout_fleet_synced` analytics event so a fleet a person's tab-open delivered is separable from one the coordinator was going to deliver anyway. Omitted means unknown.\n\n\* `roster` - roster\n\* `desktop` - desktop\n\* `wizard` - wizard"
+ ),
+})
+
/**
* Return the people who can review work on this project — one row per member with access to it, each with their `user_uuid`, `email`, `first_name`/`last_name`, and resolved GitHub `login` (null when they have no linked GitHub identity). The cold-start reviewer-routing path: when a finding's owner can't be read off a fetched entity's `created_by` and there's no cached `reviewer:<area>` memory or inbox precedent, list members, match the owner by email/name, then put their resolved `github_login` in `suggested_reviewers` on `emit-report` / `edit-report`. Pass `search` to narrow a large roster; the result is capped at 200. Strictly team-scoped.
* @summary List project members for reviewer routing
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index c24609c841cb..98dfb2972855 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -22,6 +22,7 @@ import {
SignalsScoutConfigDestroyParams,
SignalsScoutConfigListQueryParams,
SignalsScoutConfigRunParams,
+ SignalsScoutConfigSyncQueryParams,
SignalsScoutConfigUpdateBody,
SignalsScoutConfigUpdateParams,
SignalsScoutCreateBody,
@@ -602,17 +603,19 @@ const scoutConfigList = (): ToolBase<typeof ScoutConfigListSchema, WithPostHogUr
},
})
-const ScoutConfigSyncSchema = z.object({})
+const ScoutConfigSyncSchema = SignalsScoutConfigSyncQueryParams
const scoutConfigSync = (): ToolBase<typeof ScoutConfigSyncSchema, WithPostHogUrl<Schemas.SignalScoutConfig[]>> => ({
name: 'scout-config-sync',
schema: ScoutConfigSyncSchema,
- // eslint-disable-next-line no-unused-vars
handler: async (context: Context, params: z.infer<typeof ScoutConfigSyncSchema>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.SignalScoutConfig[]>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/sync/`,
+ query: {
+ surface: params.surface,
+ },
})
return await withPostHogUrl(context, result, '/inbox')
},
@@ -1312,7 +1315,7 @@ const signalsScoutConfigList = (): ToolBase<
},
})
-const SignalsScoutConfigSyncSchema = z.object({})
+const SignalsScoutConfigSyncSchema = SignalsScoutConfigSyncQueryParams
const signalsScoutConfigSync = (): ToolBase<
typeof SignalsScoutConfigSyncSchema,
@@ -1320,12 +1323,14 @@ const signalsScoutConfigSync = (): ToolBase<
> => ({
name: 'signals-scout-config-sync',
schema: SignalsScoutConfigSyncSchema,
- // eslint-disable-next-line no-unused-vars
handler: async (context: Context, params: z.infer<typeof SignalsScoutConfigSyncSchema>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.SignalScoutConfig[]>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/sync/`,
+ query: {
+ surface: params.surface,
+ },
})
return await withPostHogUrl(context, result, '/inbox')
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-sync.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-sync.json
index 7b7ea9186078..ae87855e45bb 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-sync.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-sync.json
@@ -1,5 +1,11 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
- "properties": {},
+ "properties": {
+ "surface": {
+ "description": "Which surface asked for the materialization, recorded on the `signals_scout_fleet_synced` analytics event so a fleet a person's tab-open delivered is separable from one the coordinator was going to deliver anyway. Omitted means unknown.\n\n* `roster` - roster\n* `desktop` - desktop\n* `wizard` - wizard",
+ "enum": ["roster", "desktop", "wizard"],
+ "type": "string"
+ }
+ },
"type": "object"
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-sync.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-sync.json
index 7b7ea9186078..ae87855e45bb 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-sync.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-sync.json
@@ -1,5 +1,11 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
- "properties": {},
+ "properties": {
+ "surface": {
+ "description": "Which surface asked for the materialization, recorded on the `signals_scout_fleet_synced` analytics event so a fleet a person's tab-open delivered is separable from one the coordinator was going to deliver anyway. Omitted means unknown.\n\n* `roster` - roster\n* `desktop` - desktop\n* `wizard` - wizard",
+ "enum": ["roster", "desktop", "wizard"],
+ "type": "string"
+ }
+ },
"type": "object"
}