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): rebuild the scouts UI as a roster tab and scout page (#84356)

Andrew Maguirede31eb65479c
diff --git a/frontend/src/lib/cron.ts b/frontend/src/lib/cron.ts
new file mode 100644
index 000000000000..09e88aee16c8
--- /dev/null
+++ b/frontend/src/lib/cron.ts
@@ -0,0 +1,46 @@
+import { CronExpressionParser } from 'cron-parser'
+import cronstrue from 'cronstrue'
+
+/** Every schedule we accept is a standard 5-field expression: minute hour day-of-month month day-of-week. */
+const CRON_FIELD_COUNT = 5
+
+function hasFiveFields(expr: string): boolean {
+ return expr.trim().split(/\s+/).length === CRON_FIELD_COUNT
+}
+
+/** Human-readable description of a 5-field cron expression, or an error string. Returns null for empty input. */
+export function describeCron(expr: string | null | undefined): string | null {
+ if (!expr) {
+ return null
+ }
+ if (!hasFiveFields(expr)) {
+ return 'Invalid cron expression'
+ }
+ try {
+ // Validate with cron-parser first — cronstrue is lenient and can
+ // produce garbled output (e.g. "Monday through undefined") for
+ // syntactically incomplete expressions like "0 9 * * 1-".
+ CronExpressionParser.parse(expr)
+ return cronstrue.toString(expr)
+ } catch {
+ return 'Invalid cron expression'
+ }
+}
+
+/**
+ * The next time a cron expression fires, evaluated in `timezone` — which must be the project's,
+ * because that is what the scheduler evaluates cron schedules in. Null when the expression is
+ * unparseable, so callers can fall back rather than render a wrong time.
+ */
+export function nextCronOccurrence(expr: string | null | undefined, timezone: string, from?: Date): Date | null {
+ if (!expr || !hasFiveFields(expr)) {
+ return null
+ }
+ try {
+ return CronExpressionParser.parse(expr, { currentDate: from ?? new Date(), tz: timezone })
+ .next()
+ .toDate()
+ } catch {
+ return null
+ }
+}
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
index 79cb279d310d..a968f0e86f4f 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
@@ -25,6 +25,7 @@ import {
} from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
+import { describeCron } from 'lib/cron'
import { dayjs } from 'lib/dayjs'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
@@ -43,7 +44,6 @@ import {
} from '~/types'
import {
- describeCron,
featureFlagLogic,
hasZeroRollout,
PAIRED_PRESETS,
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index b2b77ce7417f..d1fe63a18bf7 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -1,5 +1,4 @@
import { CronExpressionParser } from 'cron-parser'
-import cronstrue from 'cronstrue'
import {
MakeLogicType,
actions,
@@ -29,6 +28,7 @@ import { ACTIVITY_SEARCH_PARAM } from 'lib/components/ActivityLog/activityLogLog
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
+import { describeCron } from 'lib/cron'
import { Dayjs, dayjs } from 'lib/dayjs'
import { scrollToFormError } from 'lib/forms/scrollToFormError'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
@@ -256,26 +256,6 @@ interface PairedPresetDefinition {
disableCron: string
}
-/** Human-readable description of a 5-field cron expression, or an error string. Returns null for empty input. */
-export function describeCron(expr: string | null): string | null {
- if (!expr) {
- return null
- }
- const fields = expr.trim().split(/\s+/)
- if (fields.length !== 5) {
- return 'Invalid cron expression'
- }
- try {
- // Validate with cron-parser first — cronstrue is lenient and can
- // produce garbled output (e.g. "Monday through undefined") for
- // syntactically incomplete expressions like "0 9 * * 1-".
- CronExpressionParser.parse(expr)
- return cronstrue.toString(expr)
- } catch {
- return 'Invalid cron expression'
- }
-}
-
/**
* Schedule pickers operate on the browser's wall clock, but users expect the time they enter
* to be interpreted in the project's timezone (shown via `ScheduleTimezoneHint`).
diff --git a/frontend/src/scenes/feature-flags/featureFlagScheduleEditLogic.ts b/frontend/src/scenes/feature-flags/featureFlagScheduleEditLogic.ts
index bdadbc71a8eb..bc9bd4ba2542 100644
--- a/frontend/src/scenes/feature-flags/featureFlagScheduleEditLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagScheduleEditLogic.ts
@@ -2,6 +2,7 @@ import { CronExpressionParser } from 'cron-parser'
import { MakeLogicType, actions, connect, key, kea, listeners, path, props, reducers, selectors } from 'kea'
import api from 'lib/api'
+import { describeCron } from 'lib/cron'
import { Dayjs, dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
@@ -9,12 +10,7 @@ import { RecurrenceInterval, ScheduledChangeOperationType, ScheduledChangeType }
import type { TeamPublicType, TeamType } from '../../types'
import { teamLogic } from '../teamLogic'
-import {
- describeCron,
- featureFlagLogic,
- scheduleDateFromStoredISO,
- scheduleDateToProjectTzISO,
-} from './featureFlagLogic'
+import { featureFlagLogic, scheduleDateFromStoredISO, scheduleDateToProjectTzISO } from './featureFlagLogic'
// Used from reducers, which don't receive `values` — we still need a synchronous read at
// action-dispatch time. Selectors and listeners use the reactive `projectTimezone` selector instead.
diff --git a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx
index 60be839a0b75..c8768eafde40 100644
--- a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx
+++ b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx
@@ -29,7 +29,7 @@ import type { InsightShortId } from '~/types'
import type { AlertApi } from 'products/alerts/frontend/generated/api.schemas'
import { ScoutCreateButton } from 'products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton'
-import { ScoutRowCard } from 'products/signals/frontend/inbox/components/config/scouts/ScoutRowCard'
+import { ScoutSummaryRow } from 'products/signals/frontend/inbox/components/config/scouts/ScoutSummaryRow'
import { scoutFleetLogic } from 'products/signals/frontend/inbox/logics/scoutFleetLogic'
import { signalSourcesLogic } from 'products/signals/frontend/inbox/signalSourcesLogic'
@@ -188,8 +188,8 @@ function ScoutTemplateCard({ template }: { template: AIObservabilityScoutTemplat
export function AIObservabilitySelfDriving(): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
- const { scoutConfigs, scoutConfigsLoading, deletingScoutIds, updatingScoutIds } = useValues(scoutFleetLogic)
- const { deleteScout, loadScoutConfigs, updateScoutConfig } = useActions(scoutFleetLogic)
+ const { scoutConfigs, scoutConfigsLoading, updatingScoutIds } = useValues(scoutFleetLogic)
+ const { loadScoutConfigs, updateScoutConfig } = useActions(scoutFleetLogic)
const { evaluations, evaluationsLoadFailed, evaluationsLoading } = useValues(llmEvaluationsLogic)
const { loadEvaluations } = useActions(llmEvaluationsLogic)
const {
@@ -319,13 +319,10 @@ export function AIObservabilitySelfDriving(): JSX.Element {
scoutsContent = (
<div className="flex flex-col gap-2">
{aiObservabilityScouts.map((config) => (
- <ScoutRowCard
+ <ScoutSummaryRow
key={config.id}
config={config}
- rollup={undefined}
onUpdate={updateScoutConfig}
- onDelete={deleteScout}
- deleting={deletingScoutIds.includes(config.id)}
updating={updatingScoutIds.includes(config.id)}
/>
))}
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 226c82c956b3..5c6554dfc2c3 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -497,6 +497,13 @@ class FleetFindingsSummarySerializer(serializers.Serializer):
"falls outside the cap counts as edited)."
)
)
+ run_count = serializers.IntegerField(
+ help_text=(
+ "Number of scout runs created in the window, whether or not they produced output. "
+ "Unlike the report tallies it is not capped, so it is the fleet's activity over the "
+ "same span the output counts describe."
+ )
+ )
latest_at = serializers.DateTimeField(
allow_null=True,
help_text=(
diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.py
index f62a00589473..4edf8603048d 100644
--- a/products/signals/backend/scout_harness/tools/runs.py
+++ b/products/signals/backend/scout_harness/tools/runs.py
@@ -353,6 +353,7 @@ class FleetFindingsSummary:
scout_count: int
authored_report_count: int
edited_report_count: int
+ run_count: int
latest_at: str | None
def as_dict(self) -> dict[str, Any]:
@@ -379,6 +380,9 @@ def fleet_findings_summary(*, team_id: int, window_hours: int = DEFAULT_FINDINGS
"""
window_hours = max(1, min(window_hours, MAX_FINDINGS_WINDOW_HOURS))
window_start = timezone.now() - timedelta(hours=window_hours)
+ # Every run in the window, quiet ones included, so the roster's runs headline sits on the same
+ # span as its report tallies instead of a per-scout depth that doesn't sum across a fleet.
+ run_count = SignalScoutRun.objects.filter(team_id=team_id, created_at__gte=window_start).count()
touched_a_report = (~Q(emitted_report_ids=[]) & ~Q(emitted_report_ids__isnull=True)) | (
~Q(edited_report_ids=[]) & ~Q(edited_report_ids__isnull=True)
)
@@ -428,6 +432,7 @@ def fleet_findings_summary(*, team_id: int, window_hours: int = DEFAULT_FINDINGS
scout_count=len(scouts),
authored_report_count=len(authored_reports),
edited_report_count=len(edited_reports),
+ run_count=run_count,
latest_at=latest_at.isoformat() if latest_at is not None else None,
)
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 8228731418a3..a068abb64a9e 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -577,6 +577,8 @@ class TestScoutHarnessFindingsSummaryAPI(APIBaseTest):
body = response.json()
assert body["count"] == 3
assert body["scout_count"] == 2
+ # The quiet run counts as a run; the other team's does not.
+ assert body["run_count"] == 3
assert body["latest_at"] is not None
def test_summary_counts_report_channel_activity(self) -> None:
@@ -624,6 +626,7 @@ class TestScoutHarnessFindingsSummaryAPI(APIBaseTest):
body = response.json()
assert body["count"] == 1
assert body["scout_count"] == 1
+ assert body["run_count"] == 1
class TestScoutHarnessEmitFindingAPI(APIBaseTest):
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index d0fe35b789a7..b5405f5eceb6 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3708,6 +3708,8 @@ export interface FleetFindingsSummaryApi {
authored_report_count: number
/** Number of distinct inbox reports scouts edited via `edit_report`, deduped across runs, over the same most-recent-120-output-runs set as `count`, capped to the 50 most recently touched reports (the same slice the findings page lists) and excluding reports also authored within that set (authoring supersedes an edit; a report whose authoring run falls outside the cap counts as edited). */
edited_report_count: number
+ /** Number of scout runs created in the window, whether or not they produced output. Unlike the report tallies it is not capped, so it is the fleet's activity over the same span the output counts describe. */
+ run_count: number
/**
* ISO-8601 timestamp of the most recent output run (TaskRun completion, falling back to run creation), or null when nothing was produced in the window.
* @nullable
diff --git a/products/signals/frontend/inbox/InboxScene.tsx b/products/signals/frontend/inbox/InboxScene.tsx
index ad6be9ac39c6..eb246d0ff808 100644
--- a/products/signals/frontend/inbox/InboxScene.tsx
+++ b/products/signals/frontend/inbox/InboxScene.tsx
@@ -14,6 +14,8 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { CardSkeleton } from './components/cards/CardSkeleton'
import { ScoutDetailView } from './components/config/scouts/ScoutDetailView'
+import { ScoutsRoster } from './components/config/scouts/ScoutsRoster'
+import { ScoutsRosterActions } from './components/config/scouts/ScoutsRosterActions'
import { ReportDetail, ReportDetailSkeleton } from './components/detail/ReportDetail'
import { FindingsPanel } from './components/findings/FindingsPanel'
import { InboxOnboardingBanner, InboxOnboardingTakeover } from './components/onboarding/InboxOnboarding'
@@ -95,6 +97,8 @@ function ActiveTabBody({
return <NotActionableTab />
case 'archived':
return <ArchivedTab />
+ case 'scouts':
+ return <ScoutsRoster />
case 'runs':
return <RunsTab runs={signalRuns} loading={signalRunsLoading} />
case 'config':
@@ -125,7 +129,9 @@ function InboxListView(): JSX.Element {
// The takeover verdict is still settling: commit to neither UI. Rendering the tab bar or the
// rail here is what caused the normal inbox to flash in and get replaced by the welcome page.
const pending = onboardingMode === 'pending'
- const showRail = wide && !onboarding && !pending
+ // The Scouts tab is a full-width table, and the rail's own scout widget just links here — so
+ // the rail would be both redundant and the reason the table has nowhere to breathe.
+ const showRail = wide && !onboarding && !pending && activeTab !== 'scouts'
// The rail and the Configuration tab are mutually exclusive – never leave 'config' active
// (e.g. via a deep link) while the rail shows, or the rail and a config body would both appear.
const effectiveTab = showRail && activeTab === 'config' ? 'pulls' : activeTab
@@ -307,7 +313,15 @@ export function InboxScene(): JSX.Element {
: INBOX_TAB_DESCRIPTION[activeTab]
}
resourceType={{ type: 'inbox' }}
- actions={undefined}
+ // Creating a scout is the Scouts tab's primary action, so it sits in the scene
+ // header rather than inside the roster — one predictable place, and it stays
+ // reachable when the roster is filtered down to nothing. Not while onboarding
+ // has the tab locked (or is still deciding): the roster isn't reachable then.
+ actions={
+ activeTab === 'scouts' && onboardingMode !== 'takeover' && onboardingMode !== 'pending' ? (
+ <ScoutsRosterActions />
+ ) : undefined
+ }
/>
<div className="flex flex-col -mx-4 -mt-4 flex-1 min-h-0">
diff --git a/products/signals/frontend/inbox/components/config/AgentsTab.tsx b/products/signals/frontend/inbox/components/config/AgentsTab.tsx
index 7de50a5e7784..076d24619966 100644
--- a/products/signals/frontend/inbox/components/config/AgentsTab.tsx
+++ b/products/signals/frontend/inbox/components/config/AgentsTab.tsx
@@ -1,17 +1,18 @@
import { useActions, useValues } from 'kea'
import { useEffect } from 'react'
-import { IconArrowLeft } from '@posthog/icons'
+import { IconArrowLeft, IconCompass } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { urls } from 'scenes/urls'
+import { scoutFleetLogic } from '../../logics/scoutFleetLogic'
import { signalSourcesLogic } from '../../signalSourcesLogic'
import { AgentsRoster } from './AgentsRoster'
import { ConnectionsSection } from './ConnectionsSection'
import { DataSourceSetup } from './DataSourceSetup'
-import { ScoutsFleetSection } from './scouts/ScoutsFleetSection'
import { SlackNotificationsSection } from './SlackNotificationsSection'
function Subsection({
@@ -36,6 +37,28 @@ function Subsection({
)
}
+/**
+ * The roster lives on its own tab now, so this points at it rather than mounting a second copy —
+ * two live rosters on one project would each poll the runs window and fight over the same state.
+ */
+function ScoutsSubsectionLink(): JSX.Element {
+ const { scoutConfigs, enabledCount } = useValues(scoutFleetLogic)
+
+ return (
+ <div className="flex items-center gap-3 rounded border border-primary bg-surface-primary px-4 py-3">
+ <IconCompass className="size-5 shrink-0 text-accent" />
+ <span className="flex-1 text-sm text-secondary">
+ {scoutConfigs === null
+ ? 'Manage the scouts sweeping this project.'
+ : `${enabledCount} of ${scoutConfigs.length} scouts on patrol.`}
+ </span>
+ <LemonButton type="secondary" size="small" to={urls.inbox('scouts')}>
+ Open scouts
+ </LemonButton>
+ </div>
+ )
+}
+
function BackLink({ onClick }: { onClick: () => void }): JSX.Element {
return (
<LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} onClick={onClick} className="-ml-2 w-fit">
@@ -88,7 +111,7 @@ export function AgentsTab(): JSX.Element {
title="Scouts"
description="Scheduled agents that sweep this project on a cadence and emit signals to your inbox."
>
- <ScoutsFleetSection />
+ <ScoutsSubsectionLink />
</Subsection>
<Subsection
diff --git a/products/signals/frontend/inbox/components/config/scouts/FleetFindingsCallout.tsx b/products/signals/frontend/inbox/components/config/scouts/FleetFindingsCallout.tsx
deleted file mode 100644
index 788582d1dd13..000000000000
--- a/products/signals/frontend/inbox/components/config/scouts/FleetFindingsCallout.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useValues } from 'kea'
-
-import { IconArrowRight, IconSparkles } from '@posthog/icons'
-import { LemonSkeleton } from '@posthog/lemon-ui'
-
-import { TZLabel } from 'lib/components/TZLabel'
-import { pluralize } from 'lib/utils/strings'
-
-import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
-
-/**
- * Findings stat card for the scout troop list, above the scratchpad callout. Advertises the troop's
- * recent output — legacy findings plus reports authored/edited via the report channel — and links
- * into the cross-fleet findings page. Reads the cheap `emittedFindingsSummary` (a single backend
- * query) so it appears as soon as that lands rather than after the full paginated runs-window walk.
- * Renders nothing until there's at least one finding or touched report.
- */
-export function FleetFindingsCallout({ onOpen }: { onOpen: () => void }): JSX.Element | null {
- const { emittedFindingsSummary, fleetFindingsSummaryLoadedOnce } = useValues(scoutFleetLogic)
-
- const { count, authoredReportCount, editedReportCount, scoutCount, latestAt } = emittedFindingsSummary
-
- if (!fleetFindingsSummaryLoadedOnce) {
- return <LemonSkeleton className="h-16 w-full rounded" />
- }
-
- // Once this request settles, only show the callout when there's something to read on either channel.
- if (count === 0 && authoredReportCount === 0 && editedReportCount === 0) {
- return null
- }
-
- const outputParts: string[] = []
- if (count > 0) {
- outputParts.push(pluralize(count, 'signal'))
- }
- if (authoredReportCount > 0) {
- outputParts.push(`${pluralize(authoredReportCount, 'report')} authored`)
- }
- if (editedReportCount > 0) {
- outputParts.push(`${pluralize(editedReportCount, 'report')} edited`)
- }
-
- return (
- <button
- type="button"
- onClick={onOpen}
- className="flex w-full items-center gap-3 rounded border border-primary bg-bg-light px-4 py-3.5 text-left transition-colors hover:border-primary-3000 hover:bg-bg-3000"
- >
- <IconSparkles className="size-5 shrink-0 text-primary-3000" />
- <div className="flex min-w-0 flex-col">
- <span className="text-sm font-medium text-default">Scout signals</span>
- <span className="truncate text-xs text-secondary leading-snug">
- {outputParts.join(' · ')} across {pluralize(scoutCount, 'scout')}
- {latestAt ? (
- <>
- {' · latest '}
- <TZLabel time={latestAt} />
- </>
- ) : null}
- </span>
- </div>
- <span className="flex-1" />
- <IconArrowRight className="size-4 shrink-0 text-muted" />
- </button>
- )
-}
diff --git a/products/signals/frontend/inbox/components/config/scouts/FleetMemoryCallout.tsx b/products/signals/frontend/inbox/components/config/scouts/FleetMemoryCallout.tsx
deleted file mode 100644
index 21bdd4121b0d..000000000000
--- a/products/signals/frontend/inbox/components/config/scouts/FleetMemoryCallout.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { useValues } from 'kea'
-
-import { IconArrowRight, IconNotebook } from '@posthog/icons'
-import { LemonSkeleton } from '@posthog/lemon-ui'
-
-import { TZLabel } from 'lib/components/TZLabel'
-import { pluralize } from 'lib/utils/strings'
-
-import { scratchpadLogic } from '../../../logics/scratchpadLogic'
-
-/**
- * Scratchpad stat card for the scout troop list. Surfaces that the scouts have jotted down context
- * about this project — count + recency hint at what they're picking up — and links into the full
- * scratchpad browse/search surface. Renders nothing until there is at least one note, so a fresh
- * project isn't nudged toward an empty page.
- */
-export function FleetMemoryCallout({ onOpen }: { onOpen: () => void }): JSX.Element | null {
- const { entries, totalCount, lastUpdatedAt } = useValues(scratchpadLogic)
-
- if (entries === null) {
- return <LemonSkeleton className="h-16 w-full rounded" />
- }
-
- // Once this request settles, only show the callout when there's something to read.
- if (!totalCount) {
- return null
- }
-
- return (
- <button
- type="button"
- onClick={onOpen}
- className="flex w-full items-center gap-3 rounded border border-primary bg-bg-light px-4 py-3.5 text-left transition-colors hover:border-primary-3000 hover:bg-bg-3000"
- >
- <IconNotebook className="size-5 shrink-0 text-primary-3000" />
- <div className="flex min-w-0 flex-col">
- <span className="text-sm font-medium text-default">Scout scratchpad</span>
- <span className="truncate text-xs text-secondary leading-snug">
- {pluralize(totalCount, 'note')} your scouts have jotted down about this project
- {lastUpdatedAt ? (
- <>
- {' · updated '}
- <TZLabel time={lastUpdatedAt} />
- </>
- ) : null}
- </span>
- </div>
- <span className="flex-1" />
- <IconArrowRight className="size-4 shrink-0 text-muted" />
- </button>
- )
-}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutAlphaBanner.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutAlphaBanner.tsx
new file mode 100644
index 000000000000..113a52ace09d
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutAlphaBanner.tsx
@@ -0,0 +1,22 @@
+import { useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+
+/**
+ * Announcement banner above the roster, sourced from the `signals-scout` flag payload via the scout
+ * metadata endpoint. Operator-controlled so a rollout or run-limit notice can change without a
+ * frontend deploy; nothing renders when the payload carries no message.
+ */
+export function ScoutAlphaBanner(): JSX.Element | null {
+ const { scoutBannerMessage } = useValues(scoutFleetLogic)
+ if (!scoutBannerMessage) {
+ return null
+ }
+ return (
+ <LemonBanner type="info" className="mx-6 mt-4" dismissKey={`signals-scout-banner-${scoutBannerMessage}`}>
+ {scoutBannerMessage}
+ </LemonBanner>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutBadges.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutBadges.tsx
index 38c5f6c2cba3..d734534bf0c1 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutBadges.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutBadges.tsx
@@ -93,3 +93,36 @@ export function ScoutTagBadge({ tag }: { tag: string }): JSX.Element {
</LemonTag>
)
}
+
+/** Where a scout stands right now, in one tag. Used on the scout page header and its settings modal. */
+export function ScoutStatusTag({ config }: { config: SignalScoutConfig }): JSX.Element {
+ if (config.status === 'paused_by_system') {
+ return (
+ <LemonTag type="danger" size="small">
+ Paused by the system
+ </LemonTag>
+ )
+ }
+ if (config.status === 'pending_pause') {
+ return (
+ <LemonTag type="warning" size="small">
+ {config.pause_reason === 'ignored' ? 'Pausing soon' : 'Warned'}
+ </LemonTag>
+ )
+ }
+ if (!config.enabled) {
+ return <LemonTag size="small">Off</LemonTag>
+ }
+ if (!config.emit) {
+ return (
+ <LemonTag type="option" size="small">
+ Dry run
+ </LemonTag>
+ )
+ }
+ return (
+ <LemonTag type="success" size="small">
+ On patrol
+ </LemonTag>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsx
new file mode 100644
index 000000000000..45c5b3793122
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsx
@@ -0,0 +1,214 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useRef, useState } from 'react'
+
+import { IconExternal, IconRefresh } from '@posthog/icons'
+import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
+
+import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
+
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import { scoutCadenceLabel } from '../../../utils/scoutGroups'
+import { prettifyScoutSkillName, SCOUT_RUNS_PER_SCOUT, ScoutRollup } from '../../../utils/scoutRunsWindow'
+import { ScoutStatusTag } from './ScoutBadges'
+import { ScoutEnabledSwitch } from './ScoutConfigControls'
+import { ScoutNextRunLabel } from './ScoutNextRunLabel'
+import { LeaveScoutNoteButton } from './ScoutNotesPanel'
+import { ScoutSettingsButton } from './ScoutSettingsModal'
+
+function Metric({ value, label }: { value: React.ReactNode; label: string }): JSX.Element {
+ return (
+ <div className="flex flex-1 flex-col border-r border-primary px-3 py-1.5 last:border-r-0">
+ <span className="text-sm font-semibold tabular-nums leading-tight">{value}</span>
+ <span className="text-[10px] uppercase tracking-wide text-muted">{label}</span>
+ </div>
+ )
+}
+
+/**
+ * Canonical descriptions run to a paragraph. Two lines is enough to recognise the scout; the rest
+ * is there on a click for the reader who wants the full brief.
+ */
+function ScoutDescription({ text }: { text: string }): JSX.Element {
+ const ref = useRef<HTMLParagraphElement | null>(null)
+ const [expanded, setExpanded] = useState(false)
+ const [truncatable, setTruncatable] = useState(false)
+
+ // Measure whether the two-line clamp actually hides anything, mirroring FlagDescription in
+ // feature flags. Runs while the paragraph is still clamped, so the toggle only appears when
+ // there is more to reveal.
+ useEffect(() => {
+ if (ref.current) {
+ setTruncatable(ref.current.scrollHeight > ref.current.clientHeight)
+ }
+ }, [text])
+
+ const paragraph = (
+ <p ref={ref} className={`mb-0 text-sm leading-snug text-secondary ${expanded ? '' : 'line-clamp-2'}`}>
+ {text}
+ </p>
+ )
+
+ // A description that fits in two lines stays plain text — no control that changes nothing on click.
+ if (!truncatable) {
+ return paragraph
+ }
+
+ return (
+ <button
+ type="button"
+ className="group w-full cursor-pointer text-left"
+ aria-expanded={expanded}
+ onClick={() => setExpanded((value) => !value)}
+ >
+ {paragraph}
+ <span className="text-xs text-muted group-hover:text-primary">{expanded ? 'Show less' : 'Show more'}</span>
+ </button>
+ )
+}
+
+/**
+ * The scout page header: what it is, the controls that act on it, and the numbers that say whether
+ * it is worth keeping on.
+ */
+export function ScoutDetailHeader({
+ config,
+ rollup,
+ noteCount,
+ learnedCount,
+}: {
+ config: SignalScoutConfig
+ rollup: ScoutRollup | undefined
+ noteCount: number
+ learnedCount: number
+}): JSX.Element {
+ const { updatingScoutIds, manualRunScoutIds } = useValues(scoutFleetLogic)
+ const { updateScoutConfig, runScoutNow } = useActions(scoutFleetLogic)
+
+ const updating = updatingScoutIds.includes(config.id)
+ const running = manualRunScoutIds.includes(config.id)
+ // Filed and edited stay separate — adding the weak-signal count on top produced a total of two
+ // different things, which is exactly what made the old "filed" number unreadable. A report the
+ // scout filed and later added to counts once, as filed.
+ const authoredIds = rollup?.authoredReportIds ?? new Set<string>()
+ const authored = authoredIds.size
+ const edited = [...(rollup?.editedReportIds ?? [])].filter((id) => !authoredIds.has(id)).length
+
+ return (
+ <div className="flex flex-col gap-3 border-b border-primary bg-surface-primary px-4 py-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="mb-0 text-lg font-semibold">{prettifyScoutSkillName(config.skill_name)}</h2>
+ <LemonTag size="small" type={config.scout_origin === 'canonical' ? 'muted' : 'highlight'}>
+ {config.scout_origin === 'canonical' ? 'Canonical' : 'Custom'}
+ </LemonTag>
+ <ScoutStatusTag config={config} />
+ <span className="flex-1" />
+ <Tooltip title="Dispatch a run now, outside the schedule. Counts against the project's daily run budget.">
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconRefresh />}
+ loading={running}
+ disabledReason={running ? 'Starting a run' : undefined}
+ onClick={() => runScoutNow(config.id)}
+ >
+ Run now
+ </LemonButton>
+ </Tooltip>
+ <ScoutSettingsButton config={config} surface="scout_detail" showLabel />
+ <Tooltip title="Open the skill that defines what this scout does">
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconExternal />}
+ to={urls.skill(config.skill_name)}
+ aria-label={`Open the ${config.skill_name} skill`}
+ />
+ </Tooltip>
+ <ScoutEnabledSwitch config={config} onUpdate={updateScoutConfig} updating={updating} />
+ </div>
+
+ {config.description && <ScoutDescription text={config.description} />}
+
+ <div className="flex flex-wrap rounded border border-primary">
+ <Metric value={scoutCadenceLabel(config)} label="Cadence" />
+ <Metric value={<ScoutNextRunLabel config={config} />} label="Next run" />
+ <Metric value={rollup?.runCount ?? 0} label={`Runs · last ${SCOUT_RUNS_PER_SCOUT}`} />
+ <Metric value={authored} label="Reports filed" />
+ <Metric value={edited} label="Reports edited" />
+ <Metric value={learnedCount} label="Learned" />
+ <Metric value={noteCount} label="Told" />
+ </div>
+ </div>
+ )
+}
+
+/**
+ * The one thing to do about a scout the scheduler has flagged, stated in the words of the reason it
+ * recorded. A paused or warned scout is the only case where a page should tell you what to do, so
+ * this renders for nothing else.
+ */
+export function ScoutAttentionBanner({ config }: { config: SignalScoutConfig }): JSX.Element | null {
+ const { updatingScoutIds } = useValues(scoutFleetLogic)
+ const { updateScoutConfig } = useActions(scoutFleetLogic)
+ const updating = updatingScoutIds.includes(config.id)
+
+ if (config.status !== 'paused_by_system' && config.status !== 'pending_pause') {
+ return null
+ }
+
+ const paused = config.status === 'paused_by_system'
+ let headline: string
+ let detail: string
+ if (config.pause_reason === 'repeated_failures') {
+ headline = 'This scout paused itself after its runs kept failing'
+ // A settings edit resets the streak without resuming the scout, so a stored zero is not a count.
+ const streak =
+ config.consecutive_failure_count > 0
+ ? `${pluralize(config.consecutive_failure_count, 'run')} in a row failed.`
+ : 'Its last few runs all failed.'
+ detail = `${streak} It retries about once a day on its own, and resumes its normal schedule after one clean run. Turning it on resumes it now.`
+ } else if (config.pause_reason === 'ignored') {
+ headline = paused
+ ? 'This scout was paused because nobody acted on its reports'
+ : 'This scout pauses soon unless something changes'
+ detail =
+ 'Nothing came of the reports it filed recently. Tell it what to look at instead, or opt it out of auto-pause in settings if the reports are worth keeping.'
+ } else {
+ headline = paused ? 'This scout was paused after surfacing nothing' : 'This scout has been quiet for two weeks'
+ detail =
+ "It keeps running, but it's worth checking it's still watching the right things. If quiet is the point, opt it out of auto-pause in settings."
+ }
+
+ return (
+ <div className="flex flex-col gap-2 rounded border border-danger bg-danger-highlight px-4 py-3">
+ <span className="text-sm font-medium text-default">{headline}</span>
+ <span className="text-xs leading-snug text-secondary">{detail}</span>
+ <div className="flex flex-wrap items-center gap-2">
+ {!config.enabled && (
+ <LemonButton
+ type="primary"
+ size="xsmall"
+ loading={updating}
+ onClick={() => updateScoutConfig(config.id, { enabled: true })}
+ >
+ Resume it
+ </LemonButton>
+ )}
+ {config.enabled && !config.auto_pause_exempt && (
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ loading={updating}
+ onClick={() => updateScoutConfig(config.id, { auto_pause_exempt: true })}
+ >
+ Keep it running
+ </LemonButton>
+ )}
+ <LeaveScoutNoteButton skillName={config.skill_name} size="xsmall" type="tertiary" />
+ </div>
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx
index b81cc3515feb..2d6a7f59bac0 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx
@@ -5,30 +5,37 @@ import { IconArrowLeft } from '@posthog/icons'
import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
import { pluralize } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
import { captureScoutDetailViewed } from '../../../inboxAnalytics'
import { inboxSceneLogic } from '../../../inboxSceneLogic'
import { scoutDetailLogic } from '../../../logics/scoutDetailLogic'
import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import { scoutNotesLogic } from '../../../logics/scoutNotesLogic'
+import { entriesForSkill, scratchpadLogic } from '../../../logics/scratchpadLogic'
import { SCOUT_NO_RECENT_RUNS, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'
+import { ScoutDetailHeader, ScoutAttentionBanner } from './ScoutDetailHeader'
import { ScoutEmissionCard } from './ScoutEmissionCard'
+import { ScoutLearnedPanel } from './ScoutLearnedPanel'
+import { ScoutNotesPanel } from './ScoutNotesPanel'
import { ScoutReportCard } from './ScoutReportCard'
-import { ScoutRowCard } from './ScoutRowCard'
import { ScoutRunHistorySection } from './ScoutRunHistorySection'
/**
- * Full-width scout detail surface, rendered over the inbox list at `/inbox/scouts/:skillName`.
- * Skeleton (W1): back link, the shared `ScoutRowCard` as the header, and the recent-window
- * rollup line. The Signals section (emission cards) and per-scout run history land next (W2/W3).
+ * One scout's page, at `/inbox/scouts/:skillName`. In order of what a reader needs: anything the
+ * scheduler wants decided, then what the scout produced, and down the side what it has worked out
+ * for itself and what the team has told it. Configuration lives behind the header's settings modal —
+ * this page is for reading the scout, not adjusting it.
*/
export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Element {
- const { scoutConfigs, rollups, updatingScoutIds } = useValues(scoutFleetLogic)
- const { updateScoutConfig, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)
- const { setSelectedScoutSkillName } = useActions(inboxSceneLogic)
+ const { scoutConfigs, scoutConfigsLoading, rollups } = useValues(scoutFleetLogic)
+ const { startRunsPolling, stopRunsPolling, loadScoutConfigs } = useActions(scoutFleetLogic)
+ const { entries } = useValues(scratchpadLogic)
+ const { scoutNotes } = useValues(scoutNotesLogic({ skillName }))
- // Deep-linking straight to a scout (or a narrow viewport where the fleet list isn't mounted)
+ // Deep-linking straight to a scout (or a narrow viewport where the roster isn't mounted)
// means nobody else is polling the runs window, so the header + rollup would read empty
- // defaults. Drive the same start/stop lifecycle the fleet section uses.
+ // defaults. Drive the same start/stop lifecycle the roster uses.
useEffect(() => {
startRunsPolling()
return () => stopRunsPolling()
@@ -57,68 +64,112 @@ export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Eleme
})
}, [skillName, config, rollup])
- return (
- <div className="flex flex-col min-h-0 flex-1 overflow-auto gap-4 px-4 py-3">
- <LemonButton
- type="tertiary"
- size="small"
- icon={<IconArrowLeft />}
- onClick={() => setSelectedScoutSkillName(null)}
- className="self-start"
- >
- Scouts
- </LemonButton>
-
- {scoutConfigs === null ? (
- // Configs unresolved (loading, not-yet-fetched on a fresh deep-link mount, or a failed
- // load — never an empty fleet, which is `[]`). Hold the skeleton so "Scout not found"
- // can't flash before we actually have the fleet to look in.
- <LemonSkeleton className="h-16 w-full rounded" />
- ) : config === null ? (
- <div className="flex flex-1 items-center justify-center text-sm text-tertiary">Scout not found.</div>
- ) : (
- <>
- <ScoutRowCard
- config={config}
- rollup={rollup}
- onUpdate={updateScoutConfig}
- updating={updatingScoutIds.includes(config.id)}
- asHeader
- />
-
- {config.description ? (
- <p className="text-sm text-secondary leading-snug mb-0">{config.description}</p>
- ) : null}
-
- <div className="flex flex-col gap-1">
- <span className="text-xs font-medium text-default uppercase tracking-wide">
- {SCOUT_RUNS_PER_SCOUT_LABEL}
- </span>
- <span className="text-sm text-secondary">
- {rollup && rollup.runCount > 0 ? (
- <>
- {pluralize(rollup.runCount, 'run')} · {rollup.completedCount} completed ·{' '}
- {rollup.failedCount} failed · {pluralize(rollup.emittedCount, 'signal')} emitted
- {rollup.authoredReportIds.size > 0 && (
- <> · {pluralize(rollup.authoredReportIds.size, 'report')} authored</>
- )}
- {rollup.editedReportIds.size > 0 && (
- <> · {pluralize(rollup.editedReportIds.size, 'report')} edited</>
- )}
- </>
- ) : (
- SCOUT_NO_RECENT_RUNS
- )}
+ if (scoutConfigs === null) {
+ // Configs unresolved — never an empty fleet, which is `[]`. While the fetch is in flight
+ // (the fleet logic starts it on mount, so a fresh deep link is loading from its first
+ // render), hold a skeleton so "Scout not found" can't flash before we have the fleet to
+ // look in. Once it has failed, say so and offer a retry. The back link stays either way.
+ return (
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-auto px-4 py-3">
+ <div className="flex">
+ <BackToScouts />
+ </div>
+ {scoutConfigsLoading ? (
+ <>
+ <LemonSkeleton className="h-24 w-full rounded" />
+ <LemonSkeleton className="h-40 w-full rounded" />
+ </>
+ ) : (
+ <div className="flex items-center gap-3 rounded border border-danger bg-danger-highlight px-4 py-3.5">
+ <span className="flex-1 text-xs text-danger">
+ Couldn't load this scout. The scout API may be unavailable or this project may not be
+ enrolled yet.
</span>
+ <LemonButton type="secondary" size="small" status="danger" onClick={() => loadScoutConfigs()}>
+ Retry
+ </LemonButton>
</div>
+ )}
+ </div>
+ )
+ }
- <ScoutReportsSection skillName={skillName} />
+ if (config === null) {
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-auto px-4 py-3">
+ <div className="flex">
+ <BackToScouts />
+ </div>
+ <div className="flex flex-1 items-center justify-center text-sm text-tertiary">Scout not found.</div>
+ </div>
+ )
+ }
- <ScoutSignalsSection skillName={skillName} />
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-auto">
+ <div className="flex px-4 pt-3">
+ <BackToScouts />
+ </div>
+ <ScoutDetailHeader
+ config={config}
+ rollup={rollup}
+ noteCount={scoutNotes.length}
+ learnedCount={entriesForSkill(entries, skillName).length}
+ />
+ <div className="grid grid-cols-1 items-start gap-4 px-4 py-4 xl:grid-cols-[minmax(0,1fr)_20rem]">
+ <div className="flex min-w-0 flex-col gap-4">
+ <ScoutAttentionBanner config={config} />
+ <ScoutActivitySummary skillName={skillName} />
+ <ScoutReportsSection skillName={skillName} />
+ <ScoutSignalsSection skillName={skillName} />
<ScoutRunHistorySection skillName={skillName} />
- </>
- )}
+ </div>
+ <div className="flex min-w-0 flex-col gap-4">
+ <ScoutNotesPanel skillName={skillName} />
+ <ScoutLearnedPanel skillName={skillName} />
+ </div>
+ </div>
+ </div>
+ )
+}
+
+/** Navigation only: the scouts URL handler clears the selected scout, so no action is dispatched here. */
+function BackToScouts(): JSX.Element {
+ return (
+ <LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} to={urls.inbox('scouts')} className="w-fit">
+ Scouts
+ </LemonButton>
+ )
+}
+
+/** The window's totals in one line, so the sections below don't each restate the same window. */
+function ScoutActivitySummary({ skillName }: { skillName: string }): JSX.Element {
+ const { rollups } = useValues(scoutFleetLogic)
+ const rollup = rollups.get(skillName)
+
+ if (!rollup || rollup.runCount === 0) {
+ return <span className="text-sm text-secondary">{SCOUT_NO_RECENT_RUNS}</span>
+ }
+
+ // Reports filed lead; reports it only added to are stated as such rather than as a second
+ // report count, which read as two flavours of the same number.
+ const parts = [
+ pluralize(rollup.runCount, 'run'),
+ ...(rollup.failedCount > 0 ? [`${rollup.failedCount} failed`] : []),
+ ...(rollup.authoredReportIds.size > 0 ? [`${pluralize(rollup.authoredReportIds.size, 'report')} filed`] : []),
+ ...(rollup.editedReportIds.size > 0
+ ? [`added to ${pluralize(rollup.editedReportIds.size, 'existing report')}`]
+ : []),
+ ...(rollup.emittedCount > 0 ? [`${pluralize(rollup.emittedCount, 'signal')} emitted`] : []),
+ ]
+
+ return (
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs font-medium uppercase tracking-wide text-default">
+ {SCOUT_RUNS_PER_SCOUT_LABEL}
+ </span>
+ <span className="text-sm text-secondary">{parts.join(' · ')}</span>
</div>
)
}
@@ -140,15 +191,18 @@ function ScoutReportsSection({ skillName }: { skillName: string }): JSX.Element
}
const loading = !scoutRunsLoadedOnce || (scoutReportsLoading && reportRows.length === 0)
+ const editedAny = reportRows.some(({ action }) => action === 'edited')
return (
<div className="flex flex-col gap-2">
- <span className="text-xs font-medium text-default uppercase tracking-wide">Reports</span>
+ <span className="text-xs font-medium uppercase tracking-wide text-default">
+ {editedAny ? 'Reports it filed or added to' : 'Reports it filed'}
+ </span>
{loading ? (
<LemonSkeleton className="h-12 w-full rounded" />
) : reportRows.length === 0 ? (
// Touched ids exist but none resolved — the reports were deleted, or the fetch failed.
- <div className="rounded border border-dashed border-primary bg-bg-light px-4 py-6 text-center text-sm text-muted">
+ <div className="rounded border border-dashed border-primary bg-surface-primary px-4 py-6 text-center text-sm text-muted">
Couldn’t load the reports this scout authored.
</div>
) : (
@@ -193,35 +247,33 @@ function ScoutSignalsSection({ skillName }: { skillName: string }): JSX.Element
return (
<div className="flex flex-col gap-2">
- <span className="text-xs font-medium text-default uppercase tracking-wide">Signals</span>
+ <span className="text-xs font-medium uppercase tracking-wide text-default">Signals</span>
{loading && !hasRows ? (
<LemonSkeleton className="h-12 w-full rounded" />
) : emissionsLoadFailed && !hasRows ? (
// Every per-run emissions fetch failed while the rollup says these runs emitted —
// don't claim "no signals". The 60s poll keeps retrying.
- <div className="rounded border border-dashed border-primary bg-bg-light px-4 py-6 text-center text-sm text-muted">
+ <div className="rounded border border-dashed border-primary bg-surface-primary px-4 py-6 text-center text-sm text-muted">
Couldn’t load signals for this scout. Retrying…
</div>
) : !hasRows ? (
- <div className="rounded border border-dashed border-primary bg-bg-light px-4 py-6 text-center text-sm text-muted">
+ <div className="rounded border border-dashed border-primary bg-surface-primary px-4 py-6 text-center text-sm text-muted">
{`No signals emitted in the ${SCOUT_RUNS_PER_SCOUT_LABEL}.`}
</div>
) : (
- <>
- {emissionRows.map(({ emission, run, report }) => (
- <ScoutEmissionCard
- key={emission.id}
- skillName={skillName}
- emission={emission}
- run={run}
- report={report}
- // `finding_id` repeats across runs (it's a dedup trace id, not unique), so only
- // mark the newest matching emission — rows are newest-first — to keep the
- // highlight/scroll deterministic for a single shared link.
- isDeepLinked={emission.id === deepLinkedEmissionId}
- />
- ))}
- </>
+ emissionRows.map(({ emission, run, report }) => (
+ <ScoutEmissionCard
+ key={emission.id}
+ skillName={skillName}
+ emission={emission}
+ run={run}
+ report={report}
+ // `finding_id` repeats across runs (it's a dedup trace id, not unique), so only
+ // mark the newest matching emission — rows are newest-first — to keep the
+ // highlight/scroll deterministic for a single shared link.
+ isDeepLinked={emission.id === deepLinkedEmissionId}
+ />
+ ))
)}
</div>
)
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutLearnedPanel.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutLearnedPanel.tsx
new file mode 100644
index 000000000000..a0e71a9c2ad0
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutLearnedPanel.tsx
@@ -0,0 +1,79 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import { inboxSceneLogic } from '../../../inboxSceneLogic'
+import { entriesForSkill, scratchpadLogic } from '../../../logics/scratchpadLogic'
+import { ScratchpadEntryCard } from '../../scratchpad/ScratchpadEntryCard'
+
+const INITIAL_VISIBLE = 3
+
+/**
+ * What this scout has worked out for itself — the slice of the fleet scratchpad it wrote. Baselines
+ * it settled on, things it ruled out, vocabulary it learned. This is the difference between a
+ * scout that looks like a cron job and one that visibly gets better at its job.
+ */
+export function ScoutLearnedPanel({ skillName }: { skillName: string }): JSX.Element | null {
+ const { entries, entriesLoading, loadFailed } = useValues(scratchpadLogic)
+ const { loadEntries } = useActions(scratchpadLogic)
+ const { setScratchpadOpen } = useActions(inboxSceneLogic)
+ const [showAll, setShowAll] = useState(false)
+
+ if (entriesLoading && entries === null) {
+ return (
+ <div className="flex flex-col gap-2">
+ <span className="text-xs font-medium uppercase tracking-wide text-default">What it has learned</span>
+ <LemonSkeleton className="h-16 w-full rounded" />
+ </div>
+ )
+ }
+
+ // A failed load is not an empty memory: say so, rather than silently dropping the panel.
+ if (loadFailed && entries === null) {
+ return (
+ <div className="flex flex-col gap-2">
+ <span className="text-xs font-medium uppercase tracking-wide text-default">What it has learned</span>
+ <div className="flex flex-col items-center gap-2 rounded border border-danger bg-danger-highlight px-4 py-6 text-center text-sm text-danger">
+ <span>Couldn't load what this scout has learned.</span>
+ <LemonButton size="xsmall" type="secondary" onClick={() => loadEntries()}>
+ Try again
+ </LemonButton>
+ </div>
+ </div>
+ )
+ }
+
+ const scoutEntries = entriesForSkill(entries, skillName)
+ // Plenty of scouts never write a note. An empty box would say less than no box at all.
+ if (scoutEntries.length === 0) {
+ return null
+ }
+
+ const visible = showAll ? scoutEntries : scoutEntries.slice(0, INITIAL_VISIBLE)
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-medium uppercase tracking-wide text-default">What it has learned</span>
+ <span className="text-xs text-muted">{pluralize(scoutEntries.length, 'entry', 'entries')}</span>
+ <span className="flex-1" />
+ <LemonButton size="xsmall" type="tertiary" onClick={() => setScratchpadOpen(true)}>
+ All scouts
+ </LemonButton>
+ </div>
+ <div className="flex flex-col gap-2">
+ {visible.map((entry) => (
+ <ScratchpadEntryCard key={entry.key} entry={entry} />
+ ))}
+ </div>
+ {scoutEntries.length > visible.length && (
+ <LemonButton size="xsmall" type="tertiary" className="self-start" onClick={() => setShowAll(true)}>
+ Show all {pluralize(scoutEntries.length, 'entry', 'entries')}
+ </LemonButton>
+ )}
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNameCell.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNameCell.tsx
new file mode 100644
index 000000000000..c8952f662503
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNameCell.tsx
@@ -0,0 +1,55 @@
+import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { urls } from 'scenes/urls'
+
+import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
+
+import { ScoutGroupKey, scoutSubtitle } from '../../../utils/scoutGroups'
+import { prettifyScoutSkillName, ScoutRollup } from '../../../utils/scoutRunsWindow'
+import { ScoutStatusDot } from './ScoutStatusDot'
+
+const SUBTITLE_TONE_CLASS = {
+ danger: 'text-danger',
+ warning: 'text-warning',
+ muted: 'text-muted',
+} as const
+
+export function ScoutNameCell({
+ config,
+ group,
+ rollup,
+}: {
+ config: SignalScoutConfig
+ group: ScoutGroupKey
+ rollup: ScoutRollup | undefined
+}): JSX.Element {
+ const subtitle = scoutSubtitle(config, rollup, new Date())
+ return (
+ <div className="flex flex-col gap-0.5 py-0.5">
+ <div className="flex items-center gap-2">
+ <ScoutStatusDot group={group} />
+ <Link to={urls.inboxScout(config.skill_name)} subtle className="truncate text-sm font-medium">
+ {prettifyScoutSkillName(config.skill_name)}
+ </Link>
+ {config.auto_pause_exempt && group === 'watching' && (
+ <Tooltip title="Exempt from auto-pause — this scout is supposed to stay quiet">
+ <LemonTag size="small">Quiet by design</LemonTag>
+ </Tooltip>
+ )}
+ {!config.emit && (
+ <Tooltip title="This scout runs and investigates, but nothing it finds reaches your inbox">
+ <LemonTag size="small" type="option">
+ Dry run
+ </LemonTag>
+ </Tooltip>
+ )}
+ </div>
+ {subtitle && (
+ <span className={cn('ml-4 line-clamp-1 text-[11.5px]', SUBTITLE_TONE_CLASS[subtitle.tone])}>
+ {subtitle.text}
+ </span>
+ )}
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNextRunLabel.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNextRunLabel.tsx
new file mode 100644
index 000000000000..e06fbebf170d
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNextRunLabel.tsx
@@ -0,0 +1,33 @@
+import { useValues } from 'kea'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
+
+import { nextRunAt } from '../../../utils/scoutGroups'
+
+/**
+ * When the scout next runs, resolved in the project timezone. A rolling scout whose interval has
+ * already elapsed is waiting on the scheduler's next pass, so it reads "Due now" rather than as a
+ * time in the past labelled as the future.
+ */
+export function ScoutNextRunLabel({ config }: { config: SignalScoutConfig }): JSX.Element {
+ const { currentTeam } = useValues(teamLogic)
+ const now = new Date()
+ const next = nextRunAt(config, currentTeam?.timezone ?? 'UTC', now)
+
+ if (!next) {
+ return <span className="text-muted">—</span>
+ }
+ if (next.getTime() <= now.getTime()) {
+ return (
+ <Tooltip title="Past its scheduled time. The scheduler picks it up on its next pass, usually within half an hour.">
+ <span>Due now</span>
+ </Tooltip>
+ )
+ }
+ return <TZLabel time={next.toISOString()} />
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx
new file mode 100644
index 000000000000..3de401795cdd
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx
@@ -0,0 +1,251 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconPencil, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonTag, LemonTextArea, Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { pluralize } from 'lib/utils/strings'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import type { ScoutNoteApi } from 'products/signals/frontend/generated/api.schemas'
+
+import {
+ isDirectScoutNote,
+ NOTES_FETCH_LIMIT,
+ scoutNoteOriginLabel,
+ scoutNotesLogic,
+} from '../../../logics/scoutNotesLogic'
+
+/** Bounded by the create serializer; mirrored here so the dialog can say so before a failed request. */
+const NOTE_MAX_CHARS = 10000
+
+/**
+ * Controlled so LemonTextArea's counter has a value to count; an uncontrolled textarea reports
+ * 0 / max no matter what is typed.
+ */
+function NoteComposer({ onChange }: { onChange: (content: string) => void }): JSX.Element {
+ const [content, setContent] = useState('')
+ return (
+ <LemonTextArea
+ autoFocus
+ value={content}
+ maxLength={NOTE_MAX_CHARS}
+ placeholder="e.g. we shipped a new checkout on Tuesday, watch conversion closely"
+ onChange={(value) => {
+ setContent(value)
+ onChange(value)
+ }}
+ />
+ )
+}
+
+/** Notes are written and retired through the skill, so the same editor access gates both. */
+function noteWriteDisabledReason(): string | undefined {
+ return getAccessControlDisabledReason(AccessControlResourceType.LlmSkill, AccessControlLevel.Editor) ?? undefined
+}
+
+/**
+ * The dialog closes itself only once the note saved. A failed request leaves it open with the text
+ * still in the composer, so a long note is never lost to a transient error.
+ */
+function LeaveNoteDialog({
+ skillName,
+ onSubmit,
+}: {
+ skillName: string
+ onSubmit: (content: string) => Promise<boolean>
+}): void {
+ let content = ''
+ let closeDialog: (() => void) | null = null
+ LemonDialog.open({
+ title: skillName ? 'Tell this scout something' : 'Tell every scout something',
+ description: skillName
+ ? 'It picks this up on its next run and folds what it takes from it into what it has learned.'
+ : 'Every scout on this project picks this up on its next run.',
+ content: (close) => {
+ closeDialog = close
+ return (
+ <NoteComposer
+ onChange={(value) => {
+ content = value
+ }}
+ />
+ )
+ },
+ shouldAwaitSubmit: true,
+ primaryButton: {
+ children: 'Leave note',
+ preventClosing: true,
+ onClick: async () => {
+ const trimmed = content.trim()
+ if (!trimmed) {
+ return
+ }
+ if (await onSubmit(trimmed)) {
+ closeDialog?.()
+ }
+ },
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+}
+
+/** Opens the note composer. Sits in the scout page header and above the notes panel. */
+export function LeaveScoutNoteButton({
+ skillName,
+ size = 'small',
+ type = 'secondary',
+}: {
+ skillName: string
+ size?: 'xsmall' | 'small'
+ type?: 'primary' | 'secondary' | 'tertiary'
+}): JSX.Element {
+ const logic = scoutNotesLogic({ skillName })
+ const { savingNote } = useValues(logic)
+ const disabledReason = noteWriteDisabledReason()
+
+ return (
+ <LemonButton
+ type={type}
+ size={size}
+ icon={<IconPencil />}
+ loading={savingNote}
+ disabledReason={disabledReason ?? (savingNote ? 'Saving the note' : undefined)}
+ onClick={() =>
+ LeaveNoteDialog({
+ skillName,
+ onSubmit: async (content) => {
+ await logic.asyncActions.createNote(content)
+ return !logic.values.lastSaveFailed
+ },
+ })
+ }
+ >
+ {skillName ? 'Tell it something' : 'Tell them all something'}
+ </LemonButton>
+ )
+}
+
+/**
+ * What the team has told this scout: notes someone typed, plus the ones the inbox forwarded when a
+ * report was dismissed, discussed, or rated. Without this the loop is invisible — people teach the
+ * fleet by judging its reports and never see that it landed.
+ */
+export function ScoutNotesPanel({ skillName }: { skillName: string }): JSX.Element {
+ const logic = scoutNotesLogic({ skillName })
+ const { scoutNotes, fleetWideNotes, notesLoading, notesLoadFailed, notesCapped } = useValues(logic)
+ const { deleteNote, loadNotes } = useActions(logic)
+ const [showAll, setShowAll] = useState(false)
+
+ const visible = showAll ? scoutNotes : scoutNotes.slice(0, 4)
+ const otherFleetNotes = skillName ? fleetWideNotes.filter((note) => !scoutNotes.includes(note)) : []
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-medium uppercase tracking-wide text-default">What you've told it</span>
+ <span className="flex-1" />
+ <LeaveScoutNoteButton skillName={skillName} size="xsmall" />
+ </div>
+
+ {notesLoading && scoutNotes.length === 0 ? (
+ <div className="rounded border border-primary bg-surface-primary px-4 py-6 text-center text-sm text-muted">
+ Loading notes…
+ </div>
+ ) : notesLoadFailed && scoutNotes.length === 0 ? (
+ <div className="flex flex-col items-center gap-2 rounded border border-danger bg-danger-highlight px-4 py-6 text-center text-sm text-danger">
+ <span>Couldn't load the notes.</span>
+ <LemonButton size="xsmall" type="secondary" onClick={() => loadNotes()}>
+ Try again
+ </LemonButton>
+ </div>
+ ) : scoutNotes.length === 0 ? (
+ <div className="rounded border border-dashed border-primary bg-surface-primary px-4 py-6 text-center text-sm text-muted">
+ Nothing yet. Leave a note to steer what this scout looks at, or dismiss one of its reports with a
+ reason, and that reaches it too.
+ </div>
+ ) : (
+ <div className="flex flex-col rounded border border-primary bg-surface-primary">
+ {visible.map((note) => (
+ <ScoutNoteRow key={note.id} note={note} onDelete={() => deleteNote(note.id)} />
+ ))}
+ {scoutNotes.length > visible.length && (
+ <div className="border-t border-primary px-3 py-2">
+ <LemonButton size="xsmall" type="tertiary" onClick={() => setShowAll(true)}>
+ Show all {pluralize(scoutNotes.length, 'note')}
+ </LemonButton>
+ </div>
+ )}
+ {showAll && notesCapped && (
+ <span className="border-t border-primary px-3 py-2 text-[11px] text-muted">
+ Showing the newest {NOTES_FETCH_LIMIT} notes.
+ </span>
+ )}
+ </div>
+ )}
+
+ <span className="text-xs text-muted">
+ New notes are picked up on the next run and folded into what it has learned. Delete a note once it has
+ done its job.
+ {otherFleetNotes.length > 0 &&
+ ` ${pluralize(otherFleetNotes.length, 'note')} addressed to every scout applies here too.`}
+ </span>
+ </div>
+ )
+}
+
+function ScoutNoteRow({ note, onDelete }: { note: ScoutNoteApi; onDelete: () => void }): JSX.Element {
+ const direct = isDirectScoutNote(note)
+ const disabledReason = noteWriteDisabledReason()
+
+ return (
+ <div className="flex gap-3 border-b border-primary px-3 py-2.5 last:border-b-0">
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex flex-wrap items-center gap-2 text-[11px] text-muted">
+ {direct ? (
+ <span className="font-medium text-secondary">{note.created_by_name ?? 'Someone'}</span>
+ ) : (
+ <LemonTag size="small" type="option">
+ {scoutNoteOriginLabel(note.origin)}
+ </LemonTag>
+ )}
+ {note.created_at && <TZLabel time={note.created_at} />}
+ {note.expires_at && (
+ <Tooltip title="This note retires itself, so time-boxed steering doesn't linger">
+ <span>
+ expires <TZLabel time={note.expires_at} />
+ </span>
+ </Tooltip>
+ )}
+ </div>
+ <LemonMarkdown className="text-xs text-secondary" disableImages>
+ {note.content}
+ </LemonMarkdown>
+ </div>
+ {/* Only a note someone left here is retired here. A derived one is a record of what
+ happened in the inbox, and deleting it would rewrite that. */}
+ {direct && (
+ <Tooltip title="Retire this note">
+ <LemonButton
+ size="xsmall"
+ icon={<IconTrash />}
+ disabledReason={disabledReason}
+ onClick={() =>
+ LemonDialog.open({
+ title: 'Retire this note?',
+ description: 'Scouts stop reading it from their next run onward.',
+ primaryButton: { children: 'Retire', status: 'danger', onClick: onDelete },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ aria-label="Retire note"
+ />
+ </Tooltip>
+ )}
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutReportCard.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutReportCard.tsx
index 7b591cddf6f7..a997931e9877 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutReportCard.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutReportCard.tsx
@@ -1,21 +1,28 @@
-import { IconArrowRight } from '@posthog/icons'
import { LemonTag, Link } from '@posthog/lemon-ui'
-import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { TZLabel } from 'lib/components/TZLabel'
import { urls } from 'scenes/urls'
import { ScoutReportAction } from '../../../logics/scoutDetailLogic'
import { SignalReport } from '../../../types'
+import {
+ deriveHeadline,
+ displayConventionalCommitTitle,
+ parseConventionalCommitTitle,
+} from '../../../utils/reportPresentation'
import { prettifyScoutSkillName } from '../../../utils/scoutRunsWindow'
import { SignalReportPriorityBadge } from '../../badges/SignalReportPriorityBadge'
import { SignalReportStatusBadge } from '../../badges/SignalReportStatusBadge'
+import { ConventionalCommitScopeTag } from '../../cards/ReportCard'
/**
- * One report a scout touched through the report channel (`emit_report` / `edit_report`), in the
- * detail Reports section and the cross-fleet findings page. Unlike a finding's "In report" chip, the
- * run carries the report id directly, so this links straight to the inbox report — the whole card is
- * the link. An "Authored" vs "Edited" tag records how the scout touched it; priority/status come from
- * the live report. Cross-fleet listings pass `skillName` to surface which scout touched it.
+ * One report a scout touched through the report channel (`emit_report` / `edit_report`).
+ *
+ * Deliberately shaped like the inbox list card — same priority-first layout, conventional-commit
+ * title treatment, and summary headline — because it points at the same object. It stays a separate
+ * component rather than reusing `ReportCard`: that card carries archive/restore affordances and a
+ * PR-vs-report split this surface has no use for, and it adds how the *scout* touched the report,
+ * which the inbox card has no concept of.
*/
export function ScoutReportCard({
report,
@@ -24,32 +31,41 @@ export function ScoutReportCard({
}: {
report: SignalReport
action: ScoutReportAction
- /** Set on cross-fleet listings to show the touching scout's name (omitted on the per-scout detail page). */
+ /** Set on cross-fleet listings to show the touching scout's name (omitted on the per-scout page). */
skillName?: string
}): JSX.Element {
+ const conventionalTitle = parseConventionalCommitTitle(report.title)
+ const cardTitle = displayConventionalCommitTitle(report.title, 'Untitled report')
+ const headline = deriveHeadline(report.summary)
+
return (
<Link
to={urls.inboxReport('reports', report.id)}
- className="flex flex-col gap-1 rounded border border-primary bg-bg-light px-3 py-2 hover:border-accent"
+ className="group flex w-full items-start gap-3 rounded border border-primary bg-surface-primary px-4 py-3.5 text-left no-underline transition-all duration-150 hover:border-secondary hover:bg-surface-secondary"
>
- <div className="flex items-center gap-2">
- <LemonTag size="small" type={action === 'authored' ? 'success' : 'default'}>
- {action === 'authored' ? 'Authored' : 'Edited'}
- </LemonTag>
- <SignalReportPriorityBadge priority={report.priority} />
- <SignalReportStatusBadge status={report.status} />
- {skillName && (
- <span className="truncate text-xs font-medium text-default">
- {prettifyScoutSkillName(skillName)}
- </span>
- )}
- <span className="flex-1" />
- <span className="whitespace-nowrap text-[11px] text-muted">
- {humanFriendlyDetailedTime(report.updated_at)}
+ {report.priority && (
+ <div className="shrink-0">
+ <SignalReportPriorityBadge priority={report.priority} />
+ </div>
+ )}
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <span className="line-clamp-2 text-sm font-medium text-default">
+ {conventionalTitle && (
+ <ConventionalCommitScopeTag type={conventionalTitle.type} scope={conventionalTitle.scope} />
+ )}
+ {cardTitle}
</span>
- <IconArrowRight className="size-3 shrink-0 text-muted" />
+ {headline && <span className="line-clamp-2 text-xs leading-snug text-secondary">{headline}</span>}
+ <div className="flex flex-wrap items-center gap-2 text-[11px] text-tertiary">
+ <LemonTag size="small" type={action === 'authored' ? 'success' : 'muted'}>
+ {action === 'authored' ? 'Authored' : 'Edited'}
+ </LemonTag>
+ <SignalReportStatusBadge status={report.status} />
+ {skillName && <span className="truncate">{prettifyScoutSkillName(skillName)}</span>}
+ <span className="flex-1" />
+ <TZLabel time={report.updated_at} />
+ </div>
</div>
- <span className="line-clamp-2 text-sm font-medium text-primary">{report.title || 'Untitled report'}</span>
</Link>
)
}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRowCard.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRowCard.tsx
deleted file mode 100644
index 7dc4dac54d90..000000000000
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRowCard.tsx
+++ /dev/null
@@ -1,197 +0,0 @@
-import clsx from 'clsx'
-import { useActions } from 'kea'
-import { useState } from 'react'
-
-import { IconArrowUpRight, IconGear } from '@posthog/icons'
-import { LemonButton, Link, Tooltip } from '@posthog/lemon-ui'
-
-import { pluralize } from 'lib/utils/strings'
-import { urls } from 'scenes/urls'
-
-import type {
- PatchedSignalScoutConfigUpdateApi as SignalScoutConfigUpdate,
- SignalScoutConfigApi as SignalScoutConfig,
-} from 'products/signals/frontend/generated/api.schemas'
-
-import { captureScoutAction } from '../../../inboxAnalytics'
-import {
- dailyCronToTime,
- formatRunIntervalShort,
- prettifyScoutSkillName,
- ScoutRollup,
-} from '../../../utils/scoutRunsWindow'
-import { scoutTags } from '../../../utils/scoutTags'
-import { agentSetupModalLogic } from '../../shell/agentSetupModalLogic'
-import { ScoutLifecycleBadge, ScoutOriginBadge, ScoutTagBadge } from './ScoutBadges'
-import { ScoutConfigForm, ScoutEnabledSwitch } from './ScoutConfigControls'
-import { ScoutRunBoxes } from './ScoutRunBoxes'
-
-/**
- * The one scout card: name, badges, cadence, emitted count, run boxes, enable
- * switch, and a gear that expands the settings form.
- */
-export function ScoutRowCard({
- config,
- rollup,
- onUpdate,
- onDelete,
- deleting = false,
- updating = false,
- asHeader = false,
-}: {
- config: SignalScoutConfig
- rollup: ScoutRollup | undefined
- onUpdate: (configId: string, updates: SignalScoutConfigUpdate) => void
- /** Delete the scout (archives its skill + removes the config). Omitted where deletion isn't
- * offered, e.g. the detail header; the form also hides it for canonical scouts. */
- onDelete?: (configId: string) => void
- /** True while this scout's delete request is in flight — disables the delete button. */
- deleting?: boolean
- /** True while this scout's config update request is in flight. */
- updating?: boolean
- /** When rendered as the scout detail header the name is plain text (the row IS the page). */
- asHeader?: boolean
-}): JSX.Element {
- const [settingsOpen, setSettingsOpen] = useState(false)
- const { closeSetupModal } = useActions(agentSetupModalLogic)
- const displayName = prettifyScoutSkillName(config.skill_name)
- // The same card is both a fleet row and the detail page header, and the two read very differently.
- const surface = asHeader ? 'scout_detail' : 'fleet_list'
-
- // What the scout investigates, from the skill frontmatter — surfaced on hover over the name.
- const description = config.description?.trim()
-
- return (
- <div
- className={clsx(
- 'flex flex-col rounded border border-primary bg-bg-light px-4 py-3',
- !asHeader && 'group transition-colors hover:border-primary-3000 hover:bg-bg-3000',
- !config.enabled && 'opacity-65'
- )}
- >
- {/* On narrow (mobile) widths the row wraps: the run boxes drop to their own
- full-width line so they can't collide with the name and controls. From `sm`
- up the row is forced back onto a single line — the original layout. */}
- <div className="flex flex-wrap items-center gap-x-4 gap-y-2 sm:flex-nowrap">
- {/* Name + badges on top, cadence/emitted as a muted subtitle below — keeps the
- metadata off the main row so the sparkline and controls have room to breathe. */}
- <div className="flex flex-col gap-0.5 min-w-0 flex-1">
- <div className="flex items-center gap-2 min-w-0">
- {asHeader ? (
- // min-w keeps the name from being squeezed to zero width by the
- // trailing badges — truncate should clip to an ellipsis, never vanish.
- <Tooltip title={description}>
- <span className="truncate font-medium text-sm min-w-[6rem]">{displayName}</span>
- </Tooltip>
- ) : (
- <Tooltip
- title={
- <div className="flex flex-col gap-1 max-w-sm">
- {config.description ? (
- <span className="line-clamp-6">{config.description}</span>
- ) : null}
- <span className="text-muted">{config.skill_name} · view scout</span>
- </div>
- }
- >
- <Link
- to={urls.inboxScout(config.skill_name)}
- // The fleet list lives in the setup modal, which portals outside the
- // (hidden) list subtree — close it so it doesn't cover the detail page.
- onClick={() => closeSetupModal()}
- subtle
- className="truncate font-medium text-sm min-w-[6rem]"
- >
- {displayName}
- </Link>
- </Tooltip>
- )}
- {/* Badges hug the name instead of being shoved to the column's right edge.
- They never shrink (shrink-0); the name absorbs width pressure by shrinking
- and truncating (down to its min-w floor), so the pill is never sliced. */}
- <div className="flex items-center gap-2 shrink-0">
- <Tooltip title={`${config.skill_name} · open skill`}>
- <Link
- to={urls.skill(config.skill_name)}
- target="_blank"
- targetBlankIcon={false}
- subtle
- className="text-muted"
- aria-label={`Open the ${config.skill_name} skill`}
- onClick={() =>
- captureScoutAction({
- actionType: 'open_skill_in_posthog',
- surface,
- skillName: config.skill_name,
- })
- }
- >
- <IconArrowUpRight className="size-3.5" />
- </Link>
- </Tooltip>
- <ScoutOriginBadge origin={config.scout_origin} />
- <ScoutLifecycleBadge config={config} />
- </div>
- </div>
- <div className="flex flex-wrap items-center gap-1 text-[11px] text-muted">
- {/* A cron schedule overrides the rolling interval, so the badge shows it instead. */}
- <span>
- {config.run_cron_schedule
- ? dailyCronToTime(config.run_cron_schedule)
- ? `daily at ${dailyCronToTime(config.run_cron_schedule)}`
- : config.run_cron_schedule
- : formatRunIntervalShort(config.run_interval_minutes)}
- </span>
- {rollup && rollup.emittedCount > 0 ? (
- <span>· {pluralize(rollup.emittedCount, 'signal')} emitted</span>
- ) : null}
- {/* Tags are a wall of pills on a long fleet list and say little about
- any one scout, so they stay on the detail header. The settings form
- and the tag filter still surface them where they're actionable. */}
- {asHeader ? scoutTags(config).map((tag) => <ScoutTagBadge key={tag} tag={tag} />) : null}
- </div>
- </div>
- {/* The sparkline is the flexible region: it shrinks and clips the oldest runs
- off the left so it can never push the controls column off the row. When the
- row wraps (mobile) it goes order-last + full-width so it lands on its own
- line; the wrapper is skipped entirely when there are no runs so an empty
- scout doesn't reserve a blank wrapped line. */}
- {(rollup?.runs?.length ?? 0) > 0 ? (
- <div className="order-last flex w-full min-w-0 overflow-hidden sm:order-none sm:w-auto">
- <ScoutRunBoxes runs={rollup?.runs ?? []} />
- </div>
- ) : null}
- <div className="flex items-center gap-2 shrink-0">
- <ScoutEnabledSwitch config={config} onUpdate={onUpdate} updating={updating} />
- <Tooltip title="Scout settings">
- <LemonButton
- size="small"
- icon={<IconGear />}
- active={settingsOpen}
- onClick={() => {
- captureScoutAction({
- actionType: settingsOpen ? 'close_settings' : 'open_settings',
- surface,
- skillName: config.skill_name,
- })
- setSettingsOpen((value) => !value)
- }}
- aria-label={`${config.skill_name} settings`}
- />
- </Tooltip>
- </div>
- </div>
- {settingsOpen ? (
- <div className="mt-3 border-t border-primary pt-3">
- <ScoutConfigForm
- config={config}
- onUpdate={onUpdate}
- onDelete={onDelete}
- deleting={deleting}
- updating={updating}
- />
- </div>
- ) : null}
- </div>
- )
-}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx
index b7478e3b71ce..f72db342c674 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx
@@ -51,8 +51,12 @@ function runTooltip(run: SignalScoutRunSummary, now: Date): string {
*
* Laid out with `flex-row-reverse` (newest first in the DOM) so that when the
* row is too narrow for every box the container clips the oldest runs off the
- * left edge, keeping the most recent activity — and the controls column to the
- * right — always visible.
+ * left edge, keeping the most recent activity always visible.
+ *
+ * The strip therefore hangs off the RIGHT of whatever contains it, and it should stay that way:
+ * scouts hold different numbers of runs, so right-anchoring puts every row's newest run on one
+ * vertical line. Left-aligning instead scatters the newest run across the column by run count,
+ * which is the one box a reader is scanning for.
*/
export function ScoutRunBoxes({ runs }: { runs: SignalScoutRunSummary[] }): JSX.Element | null {
const visible = useMemo(() => {
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx
index 872834059092..e38884787724 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx
@@ -2,7 +2,7 @@ import { useValues } from 'kea'
import { memo, useMemo, useState } from 'react'
import { IconArrowRight, IconChevronDown, IconExternal } from '@posthog/icons'
-import { LemonButton, LemonSkeleton, Link } from '@posthog/lemon-ui'
+import { LemonButton, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { pluralize } from 'lib/utils/strings'
@@ -89,7 +89,7 @@ const ScoutRunRow = memo(function ScoutRunRow({
const hasBody = Boolean(run.summary) || status === 'failed' || expanded
return (
- <div className="flex flex-col rounded border border-primary bg-bg-light">
+ <div className="flex flex-col border-b border-primary last:border-b-0">
<button
type="button"
onClick={() => {
@@ -101,7 +101,7 @@ const ScoutRunRow = memo(function ScoutRunRow({
})
setExpanded((value) => !value)
}}
- className="flex items-center gap-2 px-3 py-2 text-left"
+ className="flex items-center gap-2 px-3 py-2.5 text-left transition-colors hover:bg-surface-secondary"
aria-expanded={expanded}
>
<IconChevronDown
@@ -117,36 +117,38 @@ const ScoutRunRow = memo(function ScoutRunRow({
)}
<span className="flex-1" />
{emitted > 0 ? (
- <span className="whitespace-nowrap rounded bg-primary-highlight px-1.5 py-0.5 text-[11px] font-medium text-primary-3000">
+ <LemonTag type="highlight" size="small">
{pluralize(emitted, 'signal')} emitted
- </span>
+ </LemonTag>
) : reportActivityLabel ? (
- <span className="whitespace-nowrap rounded bg-primary-highlight px-1.5 py-0.5 text-[11px] font-medium text-primary-3000">
+ <LemonTag type="highlight" size="small">
{reportActivityLabel}
- </span>
- ) : status === 'completed' ? (
- <span className="whitespace-nowrap text-[11px] text-muted">0 signals emitted</span>
+ </LemonTag>
) : null}
</button>
{hasBody && (
- <div className="px-3 pb-2 pl-9">
+ <div className="px-3 pb-2.5 pl-9">
{run.summary ? (
<LemonMarkdown
disableImages
- className={expanded ? 'text-sm text-primary' : 'text-sm text-primary line-clamp-2'}
+ className={
+ expanded
+ ? 'text-[13px] leading-snug text-secondary'
+ : 'text-[13px] leading-snug text-secondary line-clamp-2'
+ }
>
{run.summary}
</LemonMarkdown>
) : status === 'failed' ? (
- <span className="text-sm italic text-muted">
+ <span className="text-[13px] italic text-muted">
No summary — the run ended before writing its close-out. The task run in PostHog is the only
diagnostic.
</span>
) : null}
{expanded && (
- <div className="flex items-center flex-wrap gap-x-3 gap-y-1 border-t pt-2 mt-2 text-xs text-tertiary">
+ <div className="mt-2.5 flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-primary pt-2 text-xs text-tertiary">
<span className="font-mono">{truncateId(run.run_id)}</span>
{authoredReportIds.map((reportId) => (
<Link
@@ -257,17 +259,19 @@ export function ScoutRunHistorySection({ skillName }: { skillName: string }): JS
{loading ? (
<LemonSkeleton className="h-12 w-full rounded" />
) : filteredRuns.length === 0 ? (
- <div className="rounded border border-dashed border-primary bg-bg-light px-4 py-6 text-center text-sm text-muted">
+ <div className="rounded border border-dashed border-primary bg-surface-primary px-4 py-6 text-center text-sm text-muted">
{runs.length > 0
? `No runs match this filter in the ${SCOUT_RUNS_PER_SCOUT_LABEL}.`
: SCOUT_NO_RECENT_RUNS}
</div>
) : (
- <>
+ // One card with attached rows, rather than a stack of separate bordered cards — a run
+ // list reads as a log, and 25 individually-bordered boxes is a lot of chrome for it.
+ <div className="overflow-hidden rounded border border-primary bg-surface-primary">
{filteredRuns.map((run) => (
<ScoutRunRow key={run.run_id} run={run} skillName={skillName} />
))}
- </>
+ </div>
)}
</div>
)
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx
new file mode 100644
index 000000000000..9bbae332afc6
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSettingsModal.tsx
@@ -0,0 +1,91 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconGear } from '@posthog/icons'
+import { LemonButton, type LemonButtonProps, LemonModal, Tooltip } from '@posthog/lemon-ui'
+
+import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
+
+import { captureScoutAction } from '../../../inboxAnalytics'
+import type { ScoutSurface } from '../../../inboxAnalytics'
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import { prettifyScoutSkillName } from '../../../utils/scoutRunsWindow'
+import { ScoutConfigForm } from './ScoutConfigControls'
+
+/**
+ * A scout's configuration, in a modal. It used to expand inline, which pushed whatever you were
+ * reading off the screen on the scout page and reflowed the whole table on the roster — and the form
+ * is long enough (schedule, network, model, tags, destination, delete) that neither host had room
+ * for it. Both surfaces open the same one.
+ */
+export function ScoutSettingsModal({
+ config,
+ surface,
+ isOpen,
+ onClose,
+}: {
+ config: SignalScoutConfig
+ surface: ScoutSurface
+ isOpen: boolean
+ onClose: () => void
+}): JSX.Element {
+ const { updatingScoutIds, deletingScoutIds } = useValues(scoutFleetLogic)
+ const { updateScoutConfig, deleteScout } = useActions(scoutFleetLogic)
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={onClose}
+ title={`${prettifyScoutSkillName(config.skill_name)} settings`}
+ description="Changes take effect on this scout's next run."
+ width={560}
+ >
+ <ScoutConfigForm
+ config={config}
+ onUpdate={updateScoutConfig}
+ onDelete={(configId) => deleteScout(configId, surface)}
+ deleting={deletingScoutIds.includes(config.id)}
+ updating={updatingScoutIds.includes(config.id)}
+ />
+ </LemonModal>
+ )
+}
+
+/** The gear that opens {@link ScoutSettingsModal}, owning the open state so hosts don't each repeat it. */
+export function ScoutSettingsButton({
+ config,
+ surface,
+ size = 'small',
+ showLabel = false,
+}: {
+ config: SignalScoutConfig
+ surface: ScoutSurface
+ size?: LemonButtonProps['size']
+ showLabel?: boolean
+}): JSX.Element {
+ const [isOpen, setIsOpen] = useState(false)
+
+ return (
+ <>
+ <Tooltip title={showLabel ? undefined : 'Scout settings'}>
+ <LemonButton
+ type={showLabel ? 'secondary' : undefined}
+ size={size}
+ icon={<IconGear />}
+ onClick={() => {
+ captureScoutAction({
+ actionType: 'open_settings',
+ surface,
+ skillName: config.skill_name,
+ })
+ setIsOpen(true)
+ }}
+ aria-label={`${config.skill_name} settings`}
+ >
+ {showLabel ? 'Settings' : null}
+ </LemonButton>
+ </Tooltip>
+ {isOpen && <ScoutSettingsModal config={config} surface={surface} isOpen onClose={() => setIsOpen(false)} />}
+ </>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutStatusDot.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutStatusDot.tsx
new file mode 100644
index 000000000000..e0c9bf187f43
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutStatusDot.tsx
@@ -0,0 +1,33 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import type { ScoutGroupKey } from '../../../utils/scoutGroups'
+
+const DOT_CLASS: Record<ScoutGroupKey, string> = {
+ needs_you: 'bg-danger',
+ working: 'bg-success',
+ watching: 'bg-secondary',
+ // Outlined rather than filled: a dry-run scout is running, but nothing reaches the inbox.
+ dry_run: 'border border-dashed border-brand-blue',
+ settling_in: 'bg-brand-blue',
+ off: 'border border-secondary',
+}
+
+const DOT_TOOLTIP: Record<ScoutGroupKey, string> = {
+ needs_you: 'This scout needs a decision from you',
+ working: 'Filed something recently',
+ watching: 'Running — nothing worth filing',
+ dry_run: 'Running, but filing nothing',
+ settling_in: 'Too new to judge',
+ off: 'Turned off',
+}
+
+/** The state glyph at the head of a roster row, matching its group. */
+export function ScoutStatusDot({ group }: { group: ScoutGroupKey }): JSX.Element {
+ return (
+ <Tooltip title={DOT_TOOLTIP[group]}>
+ <span className={cn('size-2 shrink-0 rounded-full', DOT_CLASS[group])} />
+ </Tooltip>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSummaryRow.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSummaryRow.tsx
new file mode 100644
index 000000000000..24aff7475484
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSummaryRow.tsx
@@ -0,0 +1,87 @@
+import { useValues } from 'kea'
+
+import { IconArrowUpRight } from '@posthog/icons'
+import { LemonButton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { cn } from 'lib/utils/css-classes'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import type {
+ PatchedSignalScoutConfigUpdateApi as SignalScoutConfigUpdate,
+ SignalScoutConfigApi as SignalScoutConfig,
+} from 'products/signals/frontend/generated/api.schemas'
+
+import { nextRunAt, scoutCadenceLabel } from '../../../utils/scoutGroups'
+import { prettifyScoutSkillName } from '../../../utils/scoutRunsWindow'
+import { ScoutLifecycleBadge } from './ScoutBadges'
+import { ScoutEnabledSwitch } from './ScoutConfigControls'
+
+/**
+ * A compact scout row for surfaces outside the roster — product pages that show the handful of
+ * scouts they own (e.g. AI observability). Deliberately read-mostly: name, cadence, the enable
+ * switch, and a link into the scout's own page, which is where the rest of it lives.
+ */
+export function ScoutSummaryRow({
+ config,
+ onUpdate,
+ updating = false,
+}: {
+ config: SignalScoutConfig
+ onUpdate: (configId: string, updates: SignalScoutConfigUpdate) => void
+ updating?: boolean
+}): JSX.Element {
+ const { currentTeam } = useValues(teamLogic)
+ const timezone = currentTeam?.timezone ?? 'UTC'
+ const now = new Date()
+ const next = nextRunAt(config, timezone, now)
+ // Shown in the project timezone, the one the cadence is stated in; a rolling scout past its
+ // interval is waiting on the scheduler rather than scheduled for a time that has passed.
+ const nextRunText =
+ !next || !config.enabled ? null : next <= now ? 'due now' : dayjs(next).tz(timezone).format('h:mm A')
+
+ return (
+ <div
+ className={cn(
+ 'flex flex-wrap items-center gap-x-4 gap-y-2 rounded border border-primary bg-surface-primary px-4 py-2.5',
+ !config.enabled && 'opacity-65'
+ )}
+ >
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <div className="flex items-center gap-2">
+ <Tooltip title={config.description || undefined}>
+ <Link
+ to={urls.inboxScout(config.skill_name)}
+ subtle
+ className="truncate text-sm font-medium min-w-[6rem]"
+ >
+ {prettifyScoutSkillName(config.skill_name)}
+ </Link>
+ </Tooltip>
+ {!config.emit && (
+ <LemonTag size="small" type="option">
+ Dry run
+ </LemonTag>
+ )}
+ <ScoutLifecycleBadge config={config} />
+ </div>
+ <span className="text-[11px] text-muted">
+ {scoutCadenceLabel(config)}
+ {nextRunText && ` · next run ${nextRunText}`}
+ </span>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <ScoutEnabledSwitch config={config} onUpdate={onUpdate} updating={updating} />
+ <Tooltip title="Open this scout">
+ <LemonButton
+ size="small"
+ icon={<IconArrowUpRight />}
+ to={urls.inboxScout(config.skill_name)}
+ aria-label={`Open the ${config.skill_name} scout`}
+ />
+ </Tooltip>
+ </div>
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsEmptyState.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsEmptyState.tsx
new file mode 100644
index 000000000000..8cbfdcdd12b7
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsEmptyState.tsx
@@ -0,0 +1,29 @@
+import { useActions } from 'kea'
+
+import { IconCompass } from '@posthog/icons'
+
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import { ScoutCreateButton } from './ScoutCreateButton'
+import { ScoutHelperSkillLinks } from './ScoutHelperSkillLinks'
+import { ScoutSuggestButton } from './ScoutSuggestButton'
+
+export function ScoutsEmptyState(): JSX.Element {
+ const { loadScoutConfigs } = useActions(scoutFleetLogic)
+
+ return (
+ <div className="m-6 flex flex-col items-start gap-2 rounded border border-primary bg-surface-primary px-5 py-5">
+ <div className="flex items-center gap-2">
+ <IconCompass className="size-[18px] text-accent" />
+ <span className="text-sm font-medium text-default">No scouts on this project yet</span>
+ </div>
+ <p className="mb-0 max-w-2xl text-xs leading-snug text-secondary">
+ Create a scout to investigate a recurring signal or behavior on a schedule.
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <ScoutCreateButton onCreated={() => loadScoutConfigs()} />
+ <ScoutSuggestButton />
+ </div>
+ <ScoutHelperSkillLinks />
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsx
deleted file mode 100644
index 8fdb1341d15a..000000000000
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsFleetSection.tsx
+++ /dev/null
@@ -1,359 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { useEffect, useRef } from 'react'
-
-import { IconCompass, IconSparkles } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
-
-import { TZLabel } from 'lib/components/TZLabel'
-import { percentage } from 'lib/utils/numbers'
-import { pluralize } from 'lib/utils/strings'
-
-import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
-
-import { captureScoutAction, captureScoutFleetViewed } from '../../../inboxAnalytics'
-import type { ScoutChatType } from '../../../inboxAnalytics'
-import { inboxSceneLogic } from '../../../inboxSceneLogic'
-import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
-import { FleetSummary, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'
-import { agentSetupModalLogic } from '../../shell/agentSetupModalLogic'
-import { FleetFindingsCallout } from './FleetFindingsCallout'
-import { FleetMemoryCallout } from './FleetMemoryCallout'
-import { ScoutCreateButton } from './ScoutCreateButton'
-import { ScoutHelperSkillLinks } from './ScoutHelperSkillLinks'
-import { ScoutRowCard } from './ScoutRowCard'
-import { ScoutSuggestButton } from './ScoutSuggestButton'
-import { ScoutTagsFilter } from './ScoutTagsFilter'
-
-/**
- * Scout troop manager, hosted in the Scout troop setup modal (and the Agents settings tab). Both
- * hosts already title the section "Scout troop", so this always shows the full fleet: a stats
- * header (roster + run pulse) followed by every scout with inline config controls.
- * Cloud port of desktop's `ScoutsFleetSection`.
- */
-export function ScoutsFleetSection(): JSX.Element {
- const { scoutConfigs, enabledCount, customScoutCount } = useValues(scoutFleetLogic)
- const { startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)
- const { setScratchpadOpen, setFindingsOpen } = useActions(inboxSceneLogic)
- const { closeSetupModal } = useActions(agentSetupModalLogic)
-
- // Poll the runs window only while the fleet list is open — the always-mounted setup
- // widget reads configs only and shouldn't trigger the paginated runs requests.
- useEffect(() => {
- startRunsPolling()
- return () => stopRunsPolling()
- }, [startRunsPolling, stopRunsPolling])
-
- // 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.
- const fleetViewedFiredRef = useRef(false)
- useEffect(() => {
- if (scoutConfigs === null || fleetViewedFiredRef.current) {
- return
- }
- fleetViewedFiredRef.current = true
- captureScoutFleetViewed({
- scoutCount: scoutConfigs.length,
- enabledCount,
- customCount: customScoutCount,
- dryRunCount: scoutConfigs.filter((config) => !config.emit).length,
- })
- }, [scoutConfigs, enabledCount, customScoutCount])
-
- return (
- <div className="flex flex-col gap-3">
- <ScoutAlphaBanner />
- <FleetStatsHeader />
- <FleetFindingsCallout
- onOpen={() => {
- captureScoutAction({ actionType: 'open_findings', surface: 'fleet_list' })
- // This section can render inside the scout-troop setup modal; dismiss it so the
- // findings view isn't left hidden behind the portal'd modal. No-op outside a modal.
- closeSetupModal()
- setFindingsOpen(true)
- }}
- />
- <FleetMemoryCallout
- onOpen={() => {
- captureScoutAction({ actionType: 'open_memory', surface: 'fleet_list' })
- // This section can render inside the scout-troop setup modal; dismiss it so the
- // memory view isn't left hidden behind the portal'd modal. No-op outside a modal.
- closeSetupModal()
- setScratchpadOpen(true)
- }}
- />
- <ScoutsFleetList />
- </div>
- )
-}
-
-/**
- * Alpha/announcement banner for the scout troop, sourced from the `signals-scout` flag payload via
- * the metadata endpoint — so the copy (e.g. a run-limit notice) can change with no deploy. Renders
- * nothing when no message is set. Dismissal is remembered per-message, so a reworded notice resurfaces.
- */
-function ScoutAlphaBanner(): JSX.Element | null {
- const { scoutBannerMessage, scoutMetadata, scoutMetadataLoading } = useValues(scoutFleetLogic)
- if (scoutMetadataLoading && scoutMetadata === null) {
- return <LemonSkeleton className="h-12 w-full rounded" />
- }
- if (!scoutBannerMessage) {
- return null
- }
- return (
- <LemonBanner type="info" dismissKey={`signals-scout-banner-${scoutBannerMessage}`}>
- {scoutBannerMessage}
- </LemonBanner>
- )
-}
-
-/** One-line fleet pulse: running, success rate, output on both emit channels + output rate. */
-function summarize(summary: FleetSummary | null): string {
- if (!summary) {
- return 'None running now'
- }
- const parts = [summary.runningCount > 0 ? `${summary.runningCount} running now` : 'None running now']
- if (summary.successRate !== null) {
- parts.push(`${percentage(summary.successRate, 0)} success`)
- }
- // Output across both emit channels, zero parts dropped — a report-only fleet reads
- // "4 reports touched", not "0 signals emitted". The rate shares the channel-agnostic
- // definition of output (`emitRate`), so the count and the percentage always agree.
- const outputParts: string[] = []
- if (summary.emittedCount > 0) {
- outputParts.push(pluralize(summary.emittedCount, 'signal'))
- }
- if (summary.touchedReportCount > 0) {
- outputParts.push(`${pluralize(summary.touchedReportCount, 'report')} touched`)
- }
- if (outputParts.length === 0) {
- parts.push('no output yet')
- } else if (summary.emitRate !== null) {
- parts.push(`${outputParts.join(' · ')} (${percentage(summary.emitRate, 0)} of runs)`)
- } else {
- parts.push(outputParts.join(' · '))
- }
- return parts.join(' · ')
-}
-
-/**
- * Top-of-modal troop summary: roster (enabled / total + last dispatched) over the run pulse
- * (running / success / signals emitted across the window). Sits above the toggle row so the modal
- * leads with "what the troop is" before its controls.
- */
-function FleetStatsHeader(): JSX.Element {
- const { scoutConfigs, scoutConfigsLoading, enabledCount, lastRunAt, fleetSummary, scoutRunsLoadedOnce } =
- useValues(scoutFleetLogic)
-
- return (
- <div className="flex flex-col gap-0.5">
- <div className="flex items-center gap-2 flex-wrap">
- {scoutConfigsLoading && scoutConfigs === null ? (
- <LemonSkeleton className="h-4 w-40 rounded" />
- ) : (
- <>
- <span className="text-sm font-medium text-default">
- {enabledCount} of {scoutConfigs?.length ?? enabledCount} scouts enabled
- </span>
- {lastRunAt ? (
- <span className="text-xs text-secondary">
- last dispatched <TZLabel time={lastRunAt} />
- </span>
- ) : null}
- </>
- )}
- </div>
- {scoutRunsLoadedOnce ? (
- <span className="text-xs text-muted">
- {summarize(fleetSummary)} · {SCOUT_RUNS_PER_SCOUT_LABEL} per scout
- </span>
- ) : (
- <LemonSkeleton className="h-3 w-72 rounded" />
- )}
- </div>
- )
-}
-
-function ScoutsFleetListSkeleton(): JSX.Element {
- return (
- <div className="flex flex-col gap-3">
- <div className="flex items-center gap-2">
- <LemonSkeleton.Button />
- <LemonSkeleton.Button />
- <LemonSkeleton className="h-7 w-48 rounded" />
- </div>
- <div className="flex flex-col gap-2">
- <LemonSkeleton className="h-16 w-full rounded" />
- <LemonSkeleton className="h-16 w-full rounded" />
- <LemonSkeleton className="h-16 w-full rounded" />
- </div>
- </div>
- )
-}
-
-function ScoutFleetError({ onRetry }: { onRetry: () => void }): JSX.Element {
- return (
- <div className="flex items-center gap-3 rounded border border-danger bg-danger-highlight px-4 py-3.5">
- <span className="flex-1 text-xs text-danger">
- Couldn't load the scout troop. The scout API may be unavailable or this project may not be enrolled yet.
- </span>
- <LemonButton type="secondary" size="small" status="danger" onClick={onRetry}>
- Retry
- </LemonButton>
- </div>
- )
-}
-
-function ScoutsFleetList(): JSX.Element {
- const {
- scoutConfigs,
- scoutConfigsLoading,
- visibleConfigs,
- rollups,
- hideDisabled,
- deletingScoutIds,
- updatingScoutIds,
- activeScoutTags,
- scoutTagOptions,
- } = useValues(scoutFleetLogic)
- const { setHideDisabled, setScoutTagFilter, updateScoutConfig, deleteScout, loadScoutConfigs } =
- useActions(scoutFleetLogic)
-
- if (scoutConfigsLoading && scoutConfigs === null) {
- return <ScoutsFleetListSkeleton />
- }
-
- // A failed request must not masquerade as an empty troop – a missing scope or
- // regional rollout gap would otherwise be indistinguishable from "no scouts yet".
- if (scoutConfigs === null) {
- return <ScoutFleetError onRetry={() => loadScoutConfigs()} />
- }
-
- if (scoutConfigs.length === 0) {
- return <ScoutsEmptyState />
- }
-
- return (
- <div className="flex flex-col gap-3">
- <div className="flex items-center gap-2 flex-wrap">
- <ScoutCreateButton type="secondary" size="xsmall" onCreated={() => loadScoutConfigs()} />
- <ScoutSuggestButton type="secondary" size="xsmall" />
- <ScoutChatCta label="How is my scout troop performing?" chatType="fleet_overview" />
- <ScoutChatCta label="What signals were emitted recently?" chatType="recent_signals" />
- <span className="flex-1" />
- {scoutTagOptions.length > 0 ? (
- <div className="flex items-center gap-2">
- <span className="text-xs text-muted">Tagged</span>
- <ScoutTagsFilter
- options={scoutTagOptions}
- selected={activeScoutTags}
- onToggle={(tag) =>
- setScoutTagFilter(
- activeScoutTags.includes(tag)
- ? activeScoutTags.filter((candidate) => candidate !== tag)
- : [...activeScoutTags, tag]
- )
- }
- onClear={() => setScoutTagFilter([])}
- />
- </div>
- ) : null}
- <LemonButton
- size="xsmall"
- type="tertiary"
- onClick={() => {
- captureScoutAction({
- actionType: 'toggle_hide_disabled',
- surface: 'fleet_list',
- extra: { hide_disabled: !hideDisabled },
- })
- setHideDisabled(!hideDisabled)
- }}
- >
- {hideDisabled ? 'Show disabled' : 'Hide disabled'}
- </LemonButton>
- </div>
-
- {/* The enclosing modal owns the scroll, so the list stays flat here — a nested
- overflow container would create a scroll-area-within-a-scroll-area. */}
- <div className="flex flex-col gap-2">
- {visibleConfigs.length === 0 ? (
- <span className="px-1 py-2 text-xs text-muted">No scouts match the current filters.</span>
- ) : (
- visibleConfigs.map((config: SignalScoutConfig) => (
- <ScoutRowCard
- key={config.id}
- config={config}
- rollup={rollups.get(config.skill_name)}
- onUpdate={updateScoutConfig}
- onDelete={deleteScout}
- deleting={deletingScoutIds.includes(config.id)}
- updating={updatingScoutIds.includes(config.id)}
- />
- ))
- )}
- </div>
-
- <div className="flex flex-col gap-1">
- <span className="text-xs text-muted">
- Run counts and emitted totals cover each scout’s {SCOUT_RUNS_PER_SCOUT_LABEL}, so scouts on
- different schedules are comparable. New scouts are created as{' '}
- <span className="font-mono text-[11px]">signals-scout-*</span> skills in your PostHog project.
- </span>
- <ScoutHelperSkillLinks />
- </div>
- </div>
- )
-}
-
-/**
- * Suggestion-chip CTA that fires an auto-mode cloud task asking a templated
- * question, then navigates to it – same one-click shape as the inbox
- * discuss / create-PR flows.
- */
-function ScoutChatCta({
- label,
- chatType,
- icon,
-}: {
- label: string
- chatType: ScoutChatType
- icon?: JSX.Element
-}): JSX.Element {
- const { startScoutChatTask } = useActions(scoutFleetLogic)
- const { runningChatType, aiConsentDisabledReason } = useValues(scoutFleetLogic)
- const isRunning = runningChatType === chatType
- const anyRunning = runningChatType !== null
- return (
- <LemonButton
- type="secondary"
- size="xsmall"
- icon={icon ?? <IconSparkles />}
- loading={isRunning}
- disabledReason={anyRunning ? 'Starting a task…' : (aiConsentDisabledReason ?? undefined)}
- onClick={() => startScoutChatTask(chatType, label)}
- >
- {label}
- </LemonButton>
- )
-}
-
-function ScoutsEmptyState(): JSX.Element {
- const { loadScoutConfigs } = useActions(scoutFleetLogic)
-
- return (
- <div className="flex flex-col items-start gap-2 rounded border border-primary bg-bg-light px-5 py-5">
- <div className="flex items-center gap-2">
- <IconCompass className="size-[18px] text-primary-3000" />
- <span className="font-medium text-sm text-default">No scouts on this project yet</span>
- </div>
- <p className="max-w-2xl text-xs text-secondary leading-snug mb-0">
- Create a scout to investigate a recurring signal or behavior on a schedule.
- </p>
- <div className="flex items-center gap-2 flex-wrap">
- <ScoutCreateButton onCreated={() => loadScoutConfigs()} />
- <ScoutSuggestButton />
- </div>
- <ScoutHelperSkillLinks />
- </div>
- )
-}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx
new file mode 100644
index 000000000000..b258b726314b
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRoster.tsx
@@ -0,0 +1,91 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useRef } from 'react'
+
+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { captureScoutFleetViewed } from '../../../inboxAnalytics'
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import { SCOUT_ROSTER_WINDOW_LABEL, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'
+import { ScoutAlphaBanner } from './ScoutAlphaBanner'
+import { ScoutHelperSkillLinks } from './ScoutHelperSkillLinks'
+import { ScoutsEmptyState } from './ScoutsEmptyState'
+import { ScoutsRosterGroups } from './ScoutsRosterGroups'
+import { ScoutsRosterHeader } from './ScoutsRosterHeader'
+
+/**
+ * The scout roster: one grouped table over the whole troop, ordered so the scouts that need a
+ * decision sit above the ones that don't. Replaces the card list that used to live in the Scout
+ * troop modal — the fleet outgrew a 760px portal, and a modal can't host the scout pages it links to.
+ */
+export function ScoutsRoster(): JSX.Element {
+ const { scoutConfigs, scoutConfigsLoading, enabledCount, customScoutCount } = useValues(scoutFleetLogic)
+ const { loadScoutConfigs, startRunsPolling, stopRunsPolling } = useActions(scoutFleetLogic)
+
+ useEffect(() => {
+ startRunsPolling()
+ return () => stopRunsPolling()
+ }, [startRunsPolling, stopRunsPolling])
+
+ // 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.
+ const fleetViewedFiredRef = useRef(false)
+ useEffect(() => {
+ if (scoutConfigs === null || fleetViewedFiredRef.current) {
+ return
+ }
+ fleetViewedFiredRef.current = true
+ captureScoutFleetViewed({
+ scoutCount: scoutConfigs.length,
+ enabledCount,
+ customCount: customScoutCount,
+ dryRunCount: scoutConfigs.filter((config) => !config.emit).length,
+ })
+ }, [scoutConfigs, enabledCount, customScoutCount])
+
+ if (scoutConfigsLoading && scoutConfigs === null) {
+ return (
+ <div className="flex flex-col gap-2 p-6">
+ <LemonSkeleton className="h-8 w-full rounded" />
+ <LemonSkeleton className="h-8 w-full rounded" />
+ <LemonSkeleton className="h-8 w-full rounded" />
+ </div>
+ )
+ }
+
+ // A failed request must not masquerade as an empty troop – a missing scope or
+ // regional rollout gap would otherwise be indistinguishable from "no scouts yet".
+ if (scoutConfigs === null) {
+ return (
+ <div className="m-6 flex items-center gap-3 rounded border border-danger bg-danger-highlight px-4 py-3.5">
+ <span className="flex-1 text-xs text-danger">
+ Couldn't load the scout roster. The scout API may be unavailable or this project may not be enrolled
+ yet.
+ </span>
+ <LemonButton type="secondary" size="small" status="danger" onClick={() => loadScoutConfigs()}>
+ Retry
+ </LemonButton>
+ </div>
+ )
+ }
+
+ if (scoutConfigs.length === 0) {
+ return <ScoutsEmptyState />
+ }
+
+ return (
+ <div className="flex flex-col">
+ <ScoutAlphaBanner />
+ <ScoutsRosterHeader />
+ <ScoutsRosterGroups />
+ <div className="flex flex-col gap-1 px-6 py-4">
+ <span className="text-xs text-muted">
+ The totals above cover the {SCOUT_ROSTER_WINDOW_LABEL}. Each scout's run strip shows its{' '}
+ {SCOUT_RUNS_PER_SCOUT_LABEL}, so scouts on different schedules stay comparable. New scouts are
+ created as <span className="font-mono text-[11px]">signals-scout-*</span> skills in your PostHog
+ project.
+ </span>
+ <ScoutHelperSkillLinks />
+ </div>
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterActions.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterActions.tsx
new file mode 100644
index 000000000000..2546eb433714
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterActions.tsx
@@ -0,0 +1,48 @@
+import { useActions, useValues } from 'kea'
+
+import { IconSparkles } from '@posthog/icons'
+import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
+
+import type { ScoutChatType } from '../../../inboxAnalytics'
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import { ScoutCreateButton } from './ScoutCreateButton'
+import { ScoutSuggestButton } from './ScoutSuggestButton'
+
+/** Actions for the roster, lifted into the scene header so they sit in one predictable place. */
+export function ScoutsRosterActions(): JSX.Element {
+ const { loadScoutConfigs } = useActions(scoutFleetLogic)
+ return (
+ <>
+ <AskAboutScoutsMenu />
+ <ScoutSuggestButton type="secondary" size="small" />
+ <ScoutCreateButton size="small" onCreated={() => loadScoutConfigs()} />
+ </>
+ )
+}
+
+/**
+ * The templated chat kickoffs, behind one button. As peers of "Create scout" they read as primary
+ * actions, which they aren't — each one navigates away to a task rather than changing anything here.
+ */
+function AskAboutScoutsMenu(): JSX.Element {
+ const { startScoutChatTask } = useActions(scoutFleetLogic)
+ const { runningChatType, aiConsentDisabledReason } = useValues(scoutFleetLogic)
+ const prompts: { label: string; chatType: ScoutChatType }[] = [
+ { label: 'How is my scout troop performing?', chatType: 'fleet_overview' },
+ { label: 'What signals were emitted recently?', chatType: 'recent_signals' },
+ ]
+
+ return (
+ <LemonMenu
+ items={prompts.map(({ label, chatType }) => ({
+ label,
+ onClick: () => startScoutChatTask(chatType, label),
+ disabledReason: runningChatType !== null ? 'Starting a task…' : (aiConsentDisabledReason ?? undefined),
+ }))}
+ >
+ <LemonButton type="secondary" size="small" icon={<IconSparkles />} loading={runningChatType !== null}>
+ Ask
+ </LemonButton>
+ </LemonMenu>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFilters.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFilters.tsx
new file mode 100644
index 000000000000..87ad9a33b0ab
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFilters.tsx
@@ -0,0 +1,51 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui'
+
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import { ScoutTagsFilter } from './ScoutTagsFilter'
+
+export function ScoutsRosterFilters(): JSX.Element {
+ const { scoutSearch, scoutEnabledFilter, scoutTagOptions, activeScoutTags } = useValues(scoutFleetLogic)
+ const { setScoutSearch, setScoutEnabledFilter, setScoutTagFilter } = useActions(scoutFleetLogic)
+
+ return (
+ <div className="ml-auto flex flex-wrap items-center gap-2">
+ <LemonSegmentedButton
+ size="small"
+ value={scoutEnabledFilter}
+ onChange={setScoutEnabledFilter}
+ options={[
+ { value: 'all', label: 'All' },
+ { value: 'enabled', label: 'On' },
+ { value: 'disabled', label: 'Off' },
+ ]}
+ />
+ <LemonInput
+ type="search"
+ size="small"
+ placeholder="Search scouts…"
+ value={scoutSearch}
+ onChange={setScoutSearch}
+ className="w-56"
+ allowClear
+ />
+ {scoutTagOptions.length > 0 && (
+ <>
+ <ScoutTagsFilter
+ options={scoutTagOptions}
+ selected={activeScoutTags}
+ onToggle={(tag) =>
+ setScoutTagFilter(
+ activeScoutTags.includes(tag)
+ ? activeScoutTags.filter((candidate) => candidate !== tag)
+ : [...activeScoutTags, tag]
+ )
+ }
+ onClear={() => setScoutTagFilter([])}
+ />
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterGroup.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterGroup.tsx
new file mode 100644
index 000000000000..cd73d263fe59
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterGroup.tsx
@@ -0,0 +1,156 @@
+import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+
+import { LemonTable } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { urls } from 'scenes/urls'
+
+import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
+
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import {
+ SCOUT_GROUP_HINT,
+ SCOUT_GROUP_LABEL,
+ ScoutGroupBucket,
+ ScoutGroupKey,
+ scoutCadenceLabel,
+} from '../../../utils/scoutGroups'
+import { ScoutEnabledSwitch } from './ScoutConfigControls'
+import { ScoutNameCell } from './ScoutNameCell'
+import { ScoutNextRunLabel } from './ScoutNextRunLabel'
+import { ScoutRunBoxes } from './ScoutRunBoxes'
+
+const GROUP_HEADING_CLASS: Record<ScoutGroupKey, string> = {
+ needs_you: 'bg-danger-highlight text-danger',
+ working: 'bg-surface-secondary text-secondary',
+ watching: 'bg-surface-secondary text-secondary',
+ dry_run: 'bg-surface-secondary text-secondary',
+ settling_in: 'bg-surface-secondary text-secondary',
+ off: 'bg-surface-secondary text-secondary',
+}
+
+export function ScoutsRosterGroup({
+ bucket,
+ showHeader,
+}: {
+ bucket: ScoutGroupBucket
+ showHeader: boolean
+}): JSX.Element {
+ const { rollups, updatingScoutIds, scoutRunsLoadedOnce } = useValues(scoutFleetLogic)
+ const { updateScoutConfig } = useActions(scoutFleetLogic)
+ const hint = SCOUT_GROUP_HINT[bucket.key]
+ // Watching holds the watchdogs whose silence is the job, so say so on the group rather than
+ // leaving a reader to wonder why a scout with no output is fine.
+ const exemptCount =
+ bucket.key === 'watching' ? bucket.configs.filter((config) => config.auto_pause_exempt).length : 0
+
+ return (
+ <div className="flex flex-col">
+ <div
+ className={cn(
+ 'flex items-center gap-2 border-y border-primary px-6 py-1 text-[11px] font-semibold uppercase tracking-wide',
+ GROUP_HEADING_CLASS[bucket.key]
+ )}
+ >
+ <span>{SCOUT_GROUP_LABEL[bucket.key]}</span>
+ <span className="font-medium opacity-60">{bucket.configs.length}</span>
+ {hint && (
+ <span className="font-normal normal-case tracking-normal opacity-70">
+ {hint}
+ {exemptCount > 0 && ` — ${exemptCount} quiet by design`}
+ </span>
+ )}
+ </div>
+ <LemonTable
+ embedded
+ size="small"
+ showHeader={showHeader}
+ rowKey={(config: SignalScoutConfig) => config.id}
+ dataSource={bucket.configs}
+ rowClassName={(config: SignalScoutConfig) => cn('cursor-pointer', !config.enabled && 'opacity-65')}
+ onRow={(config: SignalScoutConfig) => ({
+ // The row is one big target for the scout page, but a link or button inside it
+ // (a run box, the name) already navigates itself: a second push here would
+ // override the run box's task URL.
+ onClick: (event) => {
+ if ((event.target as HTMLElement).closest('a, button')) {
+ return
+ }
+ router.actions.push(urls.inboxScout(config.skill_name))
+ },
+ })}
+ columns={[
+ {
+ title: 'Scout',
+ key: 'scout',
+ width: '34%',
+ render: (_, config: SignalScoutConfig) => (
+ <ScoutNameCell config={config} group={bucket.key} rollup={rollups.get(config.skill_name)} />
+ ),
+ },
+ {
+ title: 'Cadence',
+ key: 'cadence',
+ width: '12%',
+ render: (_, config: SignalScoutConfig) => (
+ <span className="text-xs text-secondary">{scoutCadenceLabel(config)}</span>
+ ),
+ },
+ {
+ title: 'Next run',
+ key: 'nextRun',
+ width: '12%',
+ render: (_, config: SignalScoutConfig) => (
+ <span className="text-xs text-secondary tabular-nums">
+ <ScoutNextRunLabel config={config} />
+ </span>
+ ),
+ },
+ {
+ title: 'Recent runs',
+ key: 'runs',
+ width: '30%',
+ // The strip is a timeline ending at "now", anchored right so every row's
+ // newest run shares one vertical line; the header follows its content.
+ align: 'right',
+ render: (_, config: SignalScoutConfig) => {
+ const runs = rollups.get(config.skill_name)?.runs ?? []
+ if (runs.length) {
+ return <ScoutRunBoxes runs={runs} />
+ }
+ // Until the runs request has landed once, an empty rollup means "not
+ // loaded", not "never ran"; the poll retries a failed load on its own.
+ return scoutRunsLoadedOnce ? (
+ <span className="text-xs text-muted">No runs yet</span>
+ ) : (
+ <span className="text-xs text-muted">…</span>
+ )
+ },
+ },
+ {
+ title: '',
+ key: 'enabled',
+ width: '8%',
+ render: (_, config: SignalScoutConfig) => (
+ // Stop the row's navigation: flipping a scout off is not a request to
+ // open it, and landing on its page afterwards hides the row you just changed.
+ <div
+ className="flex justify-end"
+ onClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => event.stopPropagation()}
+ role="presentation"
+ >
+ <ScoutEnabledSwitch
+ config={config}
+ onUpdate={updateScoutConfig}
+ updating={updatingScoutIds.includes(config.id)}
+ />
+ </div>
+ ),
+ },
+ ]}
+ />
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterGroups.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterGroups.tsx
new file mode 100644
index 000000000000..163cb72d4347
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterGroups.tsx
@@ -0,0 +1,20 @@
+import { useValues } from 'kea'
+
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import { ScoutsRosterGroup } from './ScoutsRosterGroup'
+
+export function ScoutsRosterGroups(): JSX.Element {
+ const { rosterBuckets } = useValues(scoutFleetLogic)
+
+ if (rosterBuckets.length === 0) {
+ return <span className="px-6 py-6 text-sm text-muted">No scouts match the current filters.</span>
+ }
+
+ return (
+ <div className="flex flex-col">
+ {rosterBuckets.map((bucket, index) => (
+ <ScoutsRosterGroup key={bucket.key} bucket={bucket} showHeader={index === 0} />
+ ))}
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterHeader.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterHeader.tsx
new file mode 100644
index 000000000000..d683e019e339
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterHeader.tsx
@@ -0,0 +1,79 @@
+import { useValues } from 'kea'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'
+import { scratchpadLogic } from '../../../logics/scratchpadLogic'
+import { SCOUT_ROSTER_WINDOW_LABEL } from '../../../utils/scoutRunsWindow'
+import { ScoutsRosterFilters } from './ScoutsRosterFilters'
+
+function Stat({ value, label, alert = false }: { value: string; label: string; alert?: boolean }): JSX.Element {
+ return (
+ <div className="flex flex-col border-r border-primary pr-4 last:border-r-0">
+ <span className={cn('text-lg font-semibold tabular-nums leading-tight', alert && 'text-danger')}>
+ {value}
+ </span>
+ <span className="text-[11px] text-muted">{label}</span>
+ </div>
+ )
+}
+
+/**
+ * Headline numbers on the left, search and the tag filter pushed right on the same line. They were
+ * two stacked rows before, which burned a whole row of height at every width — `ml-auto` keeps the
+ * search right-aligned, and the row only wraps once the two halves genuinely can't share a line.
+ */
+export function ScoutsRosterHeader(): JSX.Element {
+ return (
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-3 px-6 pt-4 pb-3">
+ <RosterStats />
+ <ScoutsRosterFilters />
+ </div>
+ )
+}
+
+/**
+ * The troop's headline numbers. Output is stated as reports filed rather than as a run success
+ * rate: every run completing tells you nothing crashed, not that the troop is earning its keep.
+ */
+function RosterStats(): JSX.Element {
+ const { rosterGroupCounts, enabledCount, emittedFindingsSummary, fleetFindingsSummaryLoadedOnce } =
+ useValues(scoutFleetLogic)
+ // Mounted here rather than by the fleet logic, so the 1,000-entry scratchpad read only happens
+ // on the surfaces that show it, not on every inbox tab that mounts the fleet.
+ const { recentlyLearnedCount, entries: scratchpadEntries } = useValues(scratchpadLogic)
+ // A summary that hasn't landed is not zero runs. The number holds a dash until it does; a failed
+ // request keeps the dash rather than claiming a quiet week.
+ const summaryValue = (value: number): string => (fleetFindingsSummaryLoadedOnce ? String(value) : '—')
+
+ return (
+ <div className="flex flex-wrap items-center gap-4">
+ {rosterGroupCounts.needs_you > 0 && (
+ <Stat value={String(rosterGroupCounts.needs_you)} label="need you" alert />
+ )}
+ <Stat value={String(enabledCount)} label="on patrol" />
+ <Tooltip title={`Runs your scouts made in the ${SCOUT_ROSTER_WINDOW_LABEL}, quiet ones included.`}>
+ <span>
+ <Stat value={summaryValue(emittedFindingsSummary.runCount)} label="runs" />
+ </span>
+ </Tooltip>
+ <Tooltip title={`New reports your scouts filed in the ${SCOUT_ROSTER_WINDOW_LABEL}.`}>
+ <span>
+ <Stat value={summaryValue(emittedFindingsSummary.authoredReportCount)} label="reports filed" />
+ </span>
+ </Tooltip>
+ <Tooltip title={`Existing reports your scouts added to in the ${SCOUT_ROSTER_WINDOW_LABEL}.`}>
+ <span>
+ <Stat value={summaryValue(emittedFindingsSummary.editedReportCount)} label="reports edited" />
+ </span>
+ </Tooltip>
+ <Tooltip title={`Scratchpad entries your scouts wrote or refreshed in the ${SCOUT_ROSTER_WINDOW_LABEL}.`}>
+ <span>
+ <Stat value={scratchpadEntries === null ? '—' : String(recentlyLearnedCount)} label="learned" />
+ </span>
+ </Tooltip>
+ </div>
+ )
+}
diff --git a/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx b/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx
index 8b3b14d25541..449dac41d827 100644
--- a/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx
+++ b/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx
@@ -5,7 +5,6 @@ import { IconChevronDown, IconClock } from '@posthog/icons'
import { LemonTag, Link } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
@@ -38,12 +37,12 @@ function splitKey(key: string): { kind: string | null; body: string } {
}
/**
- * One scratchpad note the scout fleet has written about this project. Shares the collapse/expand
+ * One scratchpad entry the scout fleet has written about this project. Shares the collapse/expand
* grammar of the scout emission cards: a header (chevron · kind · key · updated time) that stays
- * visible, a 2-line markdown preview when collapsed, the full body plus an attribution footer
+ * visible, a 2-line raw-text preview when collapsed, the full body plus an attribution footer
* (which scout created it, when, and how long it's been carried forward) when open.
*
- * The list only carries previews, so a long note's tail arrives on expand — until it lands, the
+ * The list only carries previews, so a long entry's tail arrives on expand — until it lands, the
* preview stays on screen with a skeleton under it rather than the card going blank.
*/
export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): JSX.Element {
@@ -90,12 +89,15 @@ export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): J
</button>
<div className="px-3 pb-2 pl-9">
- <LemonMarkdown
- disableImages
- className={expanded ? 'text-sm text-primary' : 'text-sm text-primary line-clamp-2'}
- >
- {content || '_No content._'}
- </LemonMarkdown>
+ {content ? (
+ <pre
+ className={`m-0 whitespace-pre-wrap break-words font-mono text-xs text-primary ${expanded ? '' : 'line-clamp-2'}`}
+ >
+ {content}
+ </pre>
+ ) : (
+ <span className="text-xs italic text-muted">No content.</span>
+ )}
{expanded && isLoadingContent && <LemonSkeleton className="h-4 w-2/3 mt-1" />}
diff --git a/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.tsx b/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.tsx
index 00ee4851d1d6..7763afba6ce3 100644
--- a/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.tsx
+++ b/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.tsx
@@ -14,13 +14,16 @@ import { ScratchpadEntryCard } from './ScratchpadEntryCard'
* scratchpad is up top (the context scouts jot down + how much has accumulated), then lets the user
* read it newest-first or clustered by topic, and search it via the endpoint's ILIKE.
*
- * Read-only: the harness writes scratchpad notes on internal scope; humans inspect them here.
+ * Read-only: the harness writes scratchpad entries on internal scope; humans inspect them here.
*/
export function ScratchpadPanel(): JSX.Element {
const {
entries,
entriesLoading,
loadFailed,
+ searchResultsLoading,
+ searchFailed,
+ visibleEntries,
totalCount,
lastUpdatedAt,
groups,
@@ -28,10 +31,15 @@ export function ScratchpadPanel(): JSX.Element {
grouping,
expandedNamespaces,
} = useValues(scratchpadLogic)
- const { setSearchText, setGrouping, toggleNamespace, loadEntries } = useActions(scratchpadLogic)
+ const { setSearchText, setGrouping, toggleNamespace, loadEntries, loadSearchResults } = useActions(scratchpadLogic)
- const isInitialLoad = entriesLoading && entries === null
const isSearching = searchText.trim().length > 0
+ // The window loads once on mount; a search loads its own result set on top of it. Either
+ // list shows a skeleton until its first response, and its own retry when that response fails.
+ const isInitialLoad = isSearching ? visibleEntries === null && !searchFailed : entriesLoading && entries === null
+ const listFailed = isSearching ? searchFailed : loadFailed
+ const retry = isSearching ? loadSearchResults : loadEntries
+ const retryLoading = isSearching ? searchResultsLoading : entriesLoading
return (
<div className="flex flex-col gap-4 px-4 py-3">
@@ -63,9 +71,9 @@ export function ScratchpadPanel(): JSX.Element {
<ScratchpadEntryCardSkeleton />
<ScratchpadEntryCardSkeleton />
</div>
- ) : loadFailed && (!entries || entries.length === 0) ? (
- <ScratchpadErrorState onRetry={() => loadEntries()} loading={entriesLoading} />
- ) : !entries || entries.length === 0 ? (
+ ) : listFailed && (!visibleEntries || visibleEntries.length === 0) ? (
+ <ScratchpadErrorState onRetry={() => retry()} loading={retryLoading} />
+ ) : !visibleEntries || visibleEntries.length === 0 ? (
<ScratchpadEmptyState isSearching={isSearching} />
) : grouping === 'topic' ? (
<div className="flex flex-col gap-3">
@@ -90,7 +98,7 @@ export function ScratchpadPanel(): JSX.Element {
{group.label}
</span>
<span className="text-[11px] text-muted">
- {pluralize(group.entries.length, 'note')}
+ {pluralize(group.entries.length, 'entry', 'entries')}
</span>
</button>
{isExpanded &&
@@ -101,7 +109,7 @@ export function ScratchpadPanel(): JSX.Element {
</div>
) : (
<div className="flex flex-col gap-2">
- {entries.map((entry) => (
+ {visibleEntries.map((entry) => (
<ScratchpadEntryCard key={entry.key} entry={entry} />
))}
</div>
@@ -152,7 +160,7 @@ function ScratchpadHeader({
<LemonSkeleton className="h-3 w-36 rounded" />
) : totalCount !== null && totalCount > 0 ? (
<span className="text-xs text-muted">
- {pluralize(totalCount, 'note')}
+ {pluralize(totalCount, 'entry', 'entries')}
{lastUpdatedAt ? (
<>
{' · last updated '}
@@ -183,8 +191,8 @@ function ScratchpadEmptyState({ isSearching }: { isSearching: boolean }): JSX.El
return (
<div className="rounded border border-dashed border-primary bg-bg-light px-4 py-8 text-center text-sm text-muted">
{isSearching
- ? 'No notes match your search.'
- : "Your scouts haven't jotted anything down yet. As they scan your project, their notes show up here."}
+ ? 'No entries match your search.'
+ : "Your scouts haven't written anything down yet. As they scan your project, their entries show up here."}
</div>
)
}
diff --git a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx
index ae10794505f0..34de75eaab86 100644
--- a/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx
+++ b/products/signals/frontend/inbox/components/shell/AgentSetupColumn.tsx
@@ -9,12 +9,12 @@ import { slackChannelDisplayName } from 'lib/integrations/slackChannel'
import { IconSlack } from 'lib/lemon-ui/icons'
import { cn } from 'lib/utils/css-classes'
import { GithubIntegration } from 'scenes/integrations/components/GithubIntegration'
+import { urls } from 'scenes/urls'
import { scoutFleetLogic } from '../../logics/scoutFleetLogic'
import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'
import { userAutonomyLogic } from '../../logics/userAutonomyLogic'
import { signalSourcesLogic } from '../../signalSourcesLogic'
-import { ScoutsFleetSection } from '../config/scouts/ScoutsFleetSection'
import { SelfDrivingSection } from '../config/SelfDrivingSection'
import { SignalSourcesPanel } from '../config/SignalSourcesPanel'
import { SlackNotificationsSection } from '../config/SlackNotificationsSection'
@@ -183,7 +183,6 @@ function SignalSourcesWidget(): JSX.Element {
function ScoutTroopWidget(): JSX.Element {
useMountedLogic(scoutFleetLogic)
const { scoutConfigs, enabledCount } = useValues(scoutFleetLogic)
- const { openSetupModal } = useActions(agentSetupModalLogic)
const hasAny = enabledCount > 0
return (
<SetupWidgetCard
@@ -194,7 +193,7 @@ function ScoutTroopWidget(): JSX.Element {
loading={scoutConfigs === null}
status={hasAny ? `${enabledCount} on patrol` : 'No scouts running'}
description="Scheduled agents that sweep this project on a cadence and report signals."
- onClick={() => openSetupModal('scout-troop')}
+ to={urls.inbox('scouts')}
/>
)
}
@@ -270,12 +269,6 @@ const SETUP_MODALS: Record<
width: 760,
body: <SignalSourcesPanel />,
},
- 'scout-troop': {
- title: 'Scout troop',
- description: 'Scheduled agents that sweep this project on a cadence and emit signals to your inbox.',
- width: 760,
- body: <ScoutsFleetSection />,
- },
slack: {
title: 'Notifications',
description: 'Get pinged in Slack when you’re a suggested reviewer on a new report.',
diff --git a/products/signals/frontend/inbox/components/shell/agentSetupModalLogic.ts b/products/signals/frontend/inbox/components/shell/agentSetupModalLogic.ts
index 7661385ea857..b8176bcb78ae 100644
--- a/products/signals/frontend/inbox/components/shell/agentSetupModalLogic.ts
+++ b/products/signals/frontend/inbox/components/shell/agentSetupModalLogic.ts
@@ -4,7 +4,7 @@ import { router, urlToAction } from 'kea-router'
import { urls } from 'scenes/urls'
/** Setup widgets whose management UI opens in a modal. */
-export type AgentSetupModalKey = 'signal-sources' | 'scout-troop' | 'slack' | 'github'
+export type AgentSetupModalKey = 'signal-sources' | 'slack' | 'github'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface agentSetupModalLogicValues {
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.ts
index 1b734daedace..a78a2abcc516 100644
--- a/products/signals/frontend/inbox/inboxAnalytics.ts
+++ b/products/signals/frontend/inbox/inboxAnalytics.ts
@@ -106,8 +106,10 @@ export type ScoutActionType =
| 'open_skill_in_posthog'
| 'open_helper_skill'
| 'open_findings'
- | 'toggle_hide_disabled'
| 'filter_tags'
+ | 'leave_note'
+ | 'delete_note'
+ | 'run_now'
| 'expand_run'
| 'collapse_run'
| 'filter_runs'
diff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.ts
index ecf05573c68a..7f6b52705291 100644
--- a/products/signals/frontend/inbox/inboxSceneLogic.ts
+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts
@@ -139,9 +139,9 @@ function isStaffOnlyTab(tab: string | undefined): boolean {
* detail instantly from the list row instead of waiting on a fresh
* `GET`. The background fetch still runs to converge on the authoritative record.
*/
-// The Fleet memory callout reads the same singleton `scratchpadLogic` the panel filters, so a
-// leftover search (especially a no-match one) would make it count zero and hide itself. Clear the
-// search whenever the scratchpad closes — by any path (close button, report/scout open, Back nav).
+// A search typed into the scratchpad is transient: reopening the panel later should show the whole
+// window again, not the last query. Clear it whenever the scratchpad closes — by any path (close
+// button, report/scout open, Back nav).
function clearScratchpadSearch(): void {
const mounted = scratchpadLogic.findMounted()
if (mounted?.values.searchText) {
@@ -642,6 +642,12 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
if (values.selectedReportId !== null) {
actions.setSelectedReportId(null)
}
+ // A scout page is a Scouts-tab surface even when reached from a report or a cold
+ // deep link, so anything that closes back to "the tab" returns to the roster. After
+ // the report clear, so the tab change resolves to this scout's URL, not the report's.
+ if (values.activeTab !== 'scouts') {
+ actions.setActiveTab('scouts')
+ }
}
},
setScratchpadOpen: ({ open }) => {
@@ -654,6 +660,10 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
if (values.selectedScoutSkillName !== null) {
actions.setSelectedScoutSkillName(null)
}
+ // Same as opening a scout: the panel's Back control returns to the Scouts tab.
+ if (values.activeTab !== 'scouts') {
+ actions.setActiveTab('scouts')
+ }
} else {
clearScratchpadSearch()
}
@@ -661,7 +671,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
setFindingsOpen: ({ open }) => {
if (open) {
// Same dwell-tracking-preserving close as the scratchpad path; clear its transient
- // search so the memory callout isn't left hidden behind a stale filter on the way back.
+ // search so the panel doesn't reopen behind a stale filter on the way back.
clearScratchpadSearch()
if (values.selectedReportId !== null) {
actions.setSelectedReportId(null)
@@ -669,6 +679,9 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
if (values.selectedScoutSkillName !== null) {
actions.setSelectedScoutSkillName(null)
}
+ if (values.activeTab !== 'scouts') {
+ actions.setActiveTab('scouts')
+ }
}
},
})),
@@ -698,16 +711,15 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
})),
actionToUrl(({ values }) => ({
+ // Each action resolves to whichever full-width view is left open (or the list), so clearing one
+ // because another opened honors that surface's URL rather than bouncing to the list — and a
+ // tab change made while a scout surface is open leaves that surface's URL alone.
setActiveTab: () => [
- values.selectedReportId
- ? urls.inboxReport(values.activeTab, values.selectedReportId)
- : urls.inbox(values.activeTab),
+ inboxSurfaceUrl(values),
router.values.searchParams,
router.values.hashParams,
{ replace: false },
],
- // Each toggle resolves to whichever full-width view is left open (or the list), so clearing one
- // because another opened honors that surface's URL rather than bouncing to the list.
setSelectedReportId: () => [
inboxSurfaceUrl(values),
router.values.searchParams,
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
index 42ad5f53e54b..7b574e91a62b 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts
@@ -12,10 +12,10 @@ import {
signalsScoutChatTasksCreate,
signalsScoutConfigList,
signalsScoutConfigUpdate,
- signalsScoutMetadataGet,
} from 'products/signals/frontend/generated/api'
import type { SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'
+import { SignalScoutRunSummary } from '../types'
import { scoutFleetLogic } from './scoutFleetLogic'
jest.mock('products/signals/frontend/generated/api', () => ({
@@ -23,7 +23,6 @@ jest.mock('products/signals/frontend/generated/api', () => ({
signalsScoutConfigDestroy: jest.fn(),
signalsScoutConfigList: jest.fn(),
signalsScoutConfigUpdate: jest.fn(),
- signalsScoutMetadataGet: jest.fn(),
signalsScoutRunsFindingsSummary: jest.fn(),
}))
@@ -32,7 +31,6 @@ const mockSignalsScoutChatTasksCreate = signalsScoutChatTasksCreate as jest.Mock
>
const mockSignalsScoutConfigList = signalsScoutConfigList as jest.MockedFunction<typeof signalsScoutConfigList>
const mockSignalsScoutConfigUpdate = signalsScoutConfigUpdate as jest.MockedFunction<typeof signalsScoutConfigUpdate>
-const mockSignalsScoutMetadataGet = signalsScoutMetadataGet as jest.MockedFunction<typeof signalsScoutMetadataGet>
const BASE_CONFIG: SignalScoutConfigApi = {
id: 'config-1',
@@ -57,6 +55,25 @@ const BASE_CONFIG: SignalScoutConfigApi = {
created_at: '2026-07-22T00:00:00Z',
}
+function makeRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {
+ return {
+ run_id: 'run-1',
+ skill_name: BASE_CONFIG.skill_name,
+ skill_version: 1,
+ status: 'completed',
+ metadata: {},
+ created_at: '2026-07-22T01:00:00Z',
+ started_at: '2026-07-22T01:00:00Z',
+ completed_at: '2026-07-22T01:02:00Z',
+ summary: '',
+ emitted_count: 0,
+ emitted_finding_ids: [],
+ emitted_report_ids: [],
+ edited_report_ids: [],
+ ...overrides,
+ }
+}
+
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void; reject: (error: Error) => void } {
let resolvePromise!: (value: T) => void
let rejectPromise!: (error: Error) => void
@@ -75,17 +92,6 @@ describe('scoutFleetLogic', () => {
mockSignalsScoutChatTasksCreate.mockReset()
mockSignalsScoutConfigList.mockReset().mockResolvedValue([])
mockSignalsScoutConfigUpdate.mockReset()
- mockSignalsScoutMetadataGet.mockReset().mockResolvedValue({
- enrolled: true,
- banner_message: null,
- limits: {
- max_runs_per_tick: 1,
- max_runs_per_day: null,
- runs_today: 0,
- runs_remaining_today: null,
- },
- })
-
logic = scoutFleetLogic()
logic.mount()
await expectLogic(logic).toFinishAllListeners()
@@ -134,6 +140,10 @@ describe('scoutFleetLogic', () => {
expect(logic.values.updatingScoutIds).toEqual([])
})
+ // The roster is the only consumer of the tag filter, so assert through the buckets it renders.
+ const rosterConfigIds = (): string[] =>
+ logic.values.rosterBuckets.flatMap((bucket) => bucket.configs.map((config) => config.id))
+
it('filters scouts by any selected tag and stops applying tags that are no longer in use', () => {
const revenueScout = { ...BASE_CONFIG, tags: ['revenue'] }
const onCallScout = {
@@ -153,14 +163,81 @@ describe('scoutFleetLogic', () => {
logic.actions.setScoutTagFilter(['revenue', 'on-call'])
expect(logic.values.activeScoutTags).toEqual(['revenue', 'on-call'])
- expect(logic.values.visibleConfigs.map((config) => config.id)).toEqual(['config-1', 'config-2'])
+ expect(rosterConfigIds()).toEqual(['config-1', 'config-2'])
logic.actions.patchScoutConfigLocally(revenueScout.id, { tags: [] })
logic.actions.patchScoutConfigLocally(onCallScout.id, { tags: [] })
expect(logic.values.selectedScoutTags).toEqual(['revenue', 'on-call'])
expect(logic.values.activeScoutTags).toEqual([])
- expect(logic.values.visibleConfigs).toHaveLength(3)
+ expect(rosterConfigIds()).toHaveLength(3)
+ })
+
+ it('groups the roster by lifecycle, leading with the scouts that are producing', () => {
+ logic.actions.loadScoutConfigsSuccess([
+ { ...BASE_CONFIG, id: 'quiet', skill_name: 'signals-scout-quiet' },
+ { ...BASE_CONFIG, id: 'busy', skill_name: 'signals-scout-busy' },
+ {
+ ...BASE_CONFIG,
+ id: 'off',
+ skill_name: 'signals-scout-off',
+ enabled: false,
+ status: 'paused_by_user',
+ },
+ {
+ ...BASE_CONFIG,
+ id: 'broken',
+ skill_name: 'signals-scout-broken',
+ enabled: false,
+ status: 'paused_by_system',
+ pause_reason: 'repeated_failures',
+ },
+ ])
+ // `busy` filed a report in the window, which is what separates Working from Watching.
+ logic.actions.loadScoutRunsSuccess([makeRun({ skill_name: 'signals-scout-busy', emitted_report_ids: ['r-1'] })])
+
+ expect(logic.values.rosterBuckets.map((bucket) => bucket.key)).toEqual([
+ 'working',
+ 'needs_you',
+ 'watching',
+ 'off',
+ ])
+ expect(logic.values.rosterGroupCounts).toMatchObject({ working: 1, needs_you: 1, watching: 1, off: 1 })
+ })
+
+ it('leaves a row where it is when its switch is flipped, instead of relocating it mid-click', async () => {
+ logic.actions.loadScoutConfigsSuccess([
+ { ...BASE_CONFIG, id: 'quiet', skill_name: 'signals-scout-quiet' },
+ { ...BASE_CONFIG, id: 'other', skill_name: 'signals-scout-other' },
+ ])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.rosterBuckets.map((bucket) => bucket.key)).toEqual(['watching'])
+
+ // The optimistic half of a toggle: the switch reads off immediately...
+ logic.actions.patchScoutConfigLocally('quiet', { enabled: false })
+
+ // ...but the row stays in the group it was rendered in, rather than jumping to Off.
+ expect(logic.values.rosterBuckets.map((bucket) => bucket.key)).toEqual(['watching'])
+ expect(rosterConfigIds()).toEqual(['other', 'quiet'])
+ expect(logic.values.scoutConfigs?.find((config) => config.id === 'quiet')?.enabled).toBe(false)
+ })
+
+ it('re-places rows once server data lands', async () => {
+ logic.actions.loadScoutConfigsSuccess([{ ...BASE_CONFIG, id: 'quiet', skill_name: 'signals-scout-quiet' }])
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.loadScoutConfigsSuccess([
+ {
+ ...BASE_CONFIG,
+ id: 'quiet',
+ skill_name: 'signals-scout-quiet',
+ enabled: false,
+ status: 'paused_by_user',
+ },
+ ])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.rosterBuckets.map((bucket) => bucket.key)).toEqual(['off'])
})
it('keeps configs unresolved until the current team is available', async () => {
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
index c9dc56a9c759..7841944e5485 100644
--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts
@@ -13,6 +13,7 @@ import {
signalsScoutChatTasksCreate,
signalsScoutConfigDestroy,
signalsScoutConfigList,
+ signalsScoutConfigRun,
signalsScoutConfigUpdate,
signalsScoutMetadataGet,
signalsScoutRunsFindingsSummary,
@@ -32,9 +33,13 @@ import {
captureScoutChatStarted,
captureScoutConfigChanged,
ScoutChatType,
+ ScoutSurface,
} from '../inboxAnalytics'
import { SignalScoutRunSummary } from '../types'
import { aiConsentDisabledReason } from '../utils/aiConsent'
+import { groupScouts, scoutGroup, ScoutGroupBucket, ScoutGroupKey } from '../utils/scoutGroups'
+
+export type ScoutEnabledFilter = 'all' | 'enabled' | 'disabled'
import {
computeFleetSummary,
computeScoutRollups,
@@ -42,10 +47,10 @@ import {
isSettledRun,
prettifyScoutSkillName,
reconcileById,
+ SCOUT_ROSTER_WINDOW_HOURS,
SCOUT_RUNS_PER_SCOUT,
SCOUT_RUNS_WINDOW_HOURS,
ScoutRollup,
- sortConfigsForDisplay,
} from '../utils/scoutRunsWindow'
import { configMatchesScoutTags, listScoutTagOptions } from '../utils/scoutTags'
import type { ScoutTagOption } from '../utils/scoutTags'
@@ -86,6 +91,19 @@ const RUNS_REFETCH_INTERVAL_MS = 60_000
const RUNS_PAGE_LIMIT = 100
const MAX_RUNS_PAGES = 15
+/** Where each scout's row belongs, given the configs and run rollups currently loaded. */
+function computeRosterPlacement(values: {
+ scoutConfigs: SignalScoutConfig[] | null
+ rollups: Map<string, ScoutRollup>
+}): Record<string, ScoutGroupKey> {
+ const now = new Date()
+ const placement: Record<string, ScoutGroupKey> = {}
+ for (const config of values.scoutConfigs ?? []) {
+ placement[config.id] = scoutGroup(config, values.rollups.get(config.skill_name), now)
+ }
+ return placement
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutFleetLogicValues {
dataProcessingAccepted: boolean // aiConsentLogic
@@ -99,17 +117,20 @@ export interface scoutFleetLogicValues {
count: number
editedReportCount: number
latestAt: string | null
+ runCount: number
scoutCount: number
}
enabledCount: number
- expanded: boolean
fleetFindingsSummary: FleetFindingsSummaryApi | null
fleetFindingsSummaryLoadedOnce: boolean
fleetFindingsSummaryLoading: boolean
fleetSummary: FleetSummary | null
- hideDisabled: boolean
lastRunAt: string | null
+ manualRunScoutIds: string[]
rollups: Map<string, ScoutRollup>
+ rosterBuckets: ScoutGroupBucket[]
+ rosterGroupCounts: Record<ScoutGroupKey, number>
+ rosterPlacement: Record<string, ScoutGroupKey>
runningChatType: ScoutChatType | null
runsWindow: {
complete: boolean
@@ -120,21 +141,26 @@ export interface scoutFleetLogicValues {
scoutBannerMessage: string | null
scoutConfigs: SignalScoutConfig[] | null
scoutConfigsLoading: boolean
+ scoutEnabledFilter: ScoutEnabledFilter
scoutMetadata: ScoutMetadataApi | null
scoutMetadataLoading: boolean
scoutRuns: SignalScoutRunSummary[]
scoutRunsLoadedOnce: boolean
scoutRunsLoading: boolean
+ scoutSearch: string
scoutTagOptions: ScoutTagOption[]
selectedScoutTags: string[]
updatingScoutIds: string[]
- visibleConfigs: SignalScoutConfig[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scoutFleetLogicActions {
- deleteScout: (configId: string) => {
+ deleteScout: (
+ configId: string,
+ surface?: ScoutSurface
+ ) => {
configId: string
+ surface: ScoutSurface
}
deleteScoutFinished: (configId: string) => {
configId: string
@@ -230,11 +256,20 @@ export interface scoutFleetLogicActions {
removeScoutConfigLocally: (configId: string) => {
configId: string
}
- setExpanded: (expanded: boolean) => {
- expanded: boolean
+ runScoutNow: (configId: string) => {
+ configId: string
+ }
+ runScoutNowFinished: (configId: string) => {
+ configId: string
+ }
+ setRosterPlacement: (placement: Record<string, ScoutGroupKey>) => {
+ placement: Record<string, ScoutGroupKey>
}
- setHideDisabled: (hideDisabled: boolean) => {
- hideDisabled: boolean
+ setScoutEnabledFilter: (filter: ScoutEnabledFilter) => {
+ filter: ScoutEnabledFilter
+ }
+ setScoutSearch: (search: string) => {
+ search: string
}
setScoutTagFilter: (tags: string[]) => {
tags: string[]
@@ -277,26 +312,35 @@ export interface scoutFleetLogicMeta {
dataProcessingAccepted: boolean,
dataProcessingApprovalDisabledReason: string | null
) => string | null
- scoutBannerMessage: (scoutMetadata: ScoutMetadataApi | null) => string | null
rollups: (scoutRuns: SignalScoutRunSummary[]) => Map<string, ScoutRollup>
fleetSummary: (
scoutConfigs: SignalScoutConfigApi[] | null,
rollups: Map<string, ScoutRollup>
) => FleetSummary | null
+ scoutBannerMessage: (scoutMetadata: ScoutMetadataApi | null) => string | null
enabledCount: (scoutConfigs: SignalScoutConfigApi[] | null) => number
lastRunAt: (scoutConfigs: SignalScoutConfigApi[] | null) => string | null
scoutTagOptions: (scoutConfigs: SignalScoutConfigApi[] | null) => ScoutTagOption[]
activeScoutTags: (selectedScoutTags: string[], scoutTagOptions: ScoutTagOption[]) => string[]
- visibleConfigs: (
+ rosterBuckets: (
+ scoutConfigs: SignalScoutConfigApi[] | null,
+ rollups: Map<string, ScoutRollup>,
+ activeScoutTags: string[],
+ scoutSearch: string,
+ scoutEnabledFilter: ScoutEnabledFilter,
+ rosterPlacement: Record<string, ScoutGroupKey>
+ ) => ScoutGroupBucket[]
+ rosterGroupCounts: (
scoutConfigs: SignalScoutConfigApi[] | null,
- hideDisabled: boolean,
- activeScoutTags: string[]
- ) => SignalScoutConfig[]
+ rollups: Map<string, ScoutRollup>,
+ rosterPlacement: Record<string, ScoutGroupKey>
+ ) => Record<ScoutGroupKey, number>
emittedFindingsSummary: (fleetFindingsSummary: FleetFindingsSummaryApi | null) => {
authoredReportCount: number
count: number
editedReportCount: number
latestAt: string | null
+ runCount: number
scoutCount: number
}
customScoutCount: (scoutConfigs: SignalScoutConfigApi[] | null) => number
@@ -333,12 +377,15 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
configId,
updates,
}),
- deleteScout: (configId: string) => ({ configId }),
+ deleteScout: (configId: string, surface: ScoutSurface = 'fleet_list') => ({ configId, surface }),
deleteScoutFinished: (configId: string) => ({ configId }),
removeScoutConfigLocally: (configId: string) => ({ configId }),
- setHideDisabled: (hideDisabled: boolean) => ({ hideDisabled }),
setScoutTagFilter: (tags: string[]) => ({ tags }),
- setExpanded: (expanded: boolean) => ({ expanded }),
+ setScoutSearch: (search: string) => ({ search }),
+ setScoutEnabledFilter: (filter: ScoutEnabledFilter) => ({ filter }),
+ runScoutNow: (configId: string) => ({ configId }),
+ runScoutNowFinished: (configId: string) => ({ configId }),
+ setRosterPlacement: (placement: Record<string, ScoutGroupKey>) => ({ placement }),
// Started/stopped by the fleet-list component so the always-mounted setup widget
// (which only reads configs) doesn't trigger the paginated runs-window polling.
startRunsPolling: true,
@@ -361,6 +408,12 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
},
},
],
+ // Cheap fleet-wide output tally for the "Scout findings" callout — one backend query over
+ // runs that produced output (findings or report-channel activity), so the callout no longer
+ // waits on the full paginated runs-window walk (which could take ~10s and was the reason the
+ // callout appeared long after the modal opened).
+ // Feeds the announcement banner: an operator-set notice on the `signals-scout` flag payload
+ // (rollout, run-limit changes) that has to reach the roster without a frontend deploy.
scoutMetadata: [
null as ScoutMetadataApi | null,
{
@@ -372,17 +425,12 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
try {
return await signalsScoutMetadataGet(String(teamId))
} catch {
- // The metadata feeds only the optional alpha banner, so a transient
- // backend blip should degrade silently rather than surface a hard error.
+ // Only the optional banner reads this, so a blip degrades to no banner.
return null
}
},
},
],
- // Cheap fleet-wide output tally for the "Scout findings" callout — one backend query over
- // runs that produced output (findings or report-channel activity), so the callout no longer
- // waits on the full paginated runs-window walk (which could take ~10s and was the reason the
- // callout appeared long after the modal opened).
fleetFindingsSummary: [
null as FleetFindingsSummaryApi | null,
{
@@ -391,7 +439,9 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
if (!teamId) {
return null
}
- return await signalsScoutRunsFindingsSummary(String(teamId))
+ return await signalsScoutRunsFindingsSummary(String(teamId), {
+ window_hours: SCOUT_ROSTER_WINDOW_HOURS,
+ })
},
},
],
@@ -490,24 +540,22 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
startScoutChatTaskFailure: () => null,
},
],
- expanded: [
- // Defaults open: the only consumer is the Scout troop setup modal, which should
- // show the troop list immediately rather than a collapsed one-line pulse.
- true,
+ selectedScoutTags: [
+ [] as string[],
{
- setExpanded: (_, { expanded }) => expanded,
+ setScoutTagFilter: (_, { tags }) => tags,
},
],
- hideDisabled: [
- false,
+ scoutSearch: [
+ '',
{
- setHideDisabled: (_, { hideDisabled }) => hideDisabled,
+ setScoutSearch: (_, { search }) => search,
},
],
- selectedScoutTags: [
- [] as string[],
+ scoutEnabledFilter: [
+ 'all' as ScoutEnabledFilter,
{
- setScoutTagFilter: (_, { tags }) => tags,
+ setScoutEnabledFilter: (_, { filter }) => filter,
},
],
scoutConfigs: [
@@ -537,6 +585,24 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
updateScoutConfigFinished: (state, { configId }) => state.filter((id) => id !== configId),
},
],
+ /**
+ * Which group each scout's row currently sits in. Refreshed only when server data lands
+ * (configs or the runs window), never on a local edit — so toggling a scout leaves its row
+ * where it is instead of relocating it mid-click. The next poll re-places it truthfully.
+ */
+ rosterPlacement: [
+ {} as Record<string, ScoutGroupKey>,
+ {
+ setRosterPlacement: (_, { placement }) => placement,
+ },
+ ],
+ manualRunScoutIds: [
+ [] as string[],
+ {
+ runScoutNow: (state, { configId }) => (state.includes(configId) ? state : [...state, configId]),
+ runScoutNowFinished: (state, { configId }) => state.filter((id) => id !== configId),
+ },
+ ],
// Flips true the first time the runs window loads *successfully* and stays true across the
// 60s polls. Consumers (e.g. the scout detail Signals section) use it to tell "not loaded
// yet" from "loaded, genuinely empty" without flickering a skeleton on polls. Deliberately
@@ -574,11 +640,6 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
(dataProcessingAccepted: boolean, dataProcessingApprovalDisabledReason: string | null): string | null =>
aiConsentDisabledReason(dataProcessingAccepted, dataProcessingApprovalDisabledReason),
],
- // Editorial alpha/announcement banner from the signals-scout flag, or null when unset.
- scoutBannerMessage: [
- (s) => [s.scoutMetadata],
- (scoutMetadata: ScoutMetadataApi | null): string | null => scoutMetadata?.banner_message ?? null,
- ],
rollups: [
(s) => [s.scoutRuns],
(scoutRuns: SignalScoutRunSummary[]): Map<string, ScoutRollup> => computeScoutRollups(scoutRuns),
@@ -588,6 +649,10 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
(scoutConfigs: SignalScoutConfig[] | null, rollups: Map<string, ScoutRollup>): FleetSummary | null =>
scoutConfigs ? computeFleetSummary(scoutConfigs, rollups) : null,
],
+ scoutBannerMessage: [
+ (s) => [s.scoutMetadata],
+ (scoutMetadata: ScoutMetadataApi | null): string | null => scoutMetadata?.banner_message ?? null,
+ ],
enabledCount: [
(s) => [s.scoutConfigs],
(scoutConfigs: SignalScoutConfig[] | null): number =>
@@ -614,18 +679,74 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
(selectedScoutTags: string[], scoutTagOptions: ScoutTagOption[]): string[] =>
selectedScoutTags.filter((tag) => scoutTagOptions.some((option) => option.tag === tag)),
],
- visibleConfigs: [
- (s) => [s.scoutConfigs, s.hideDisabled, s.activeScoutTags],
+ /**
+ * The roster, bucketed by lifecycle group and narrowed by the roster's own chrome (search
+ * and the tag filter). Grouping is time-dependent (the cold-start window), so this
+ * recomputes on every runs poll — which is also when a scout can cross between Working and
+ * Watching, so the two stay in step.
+ */
+ rosterBuckets: [
+ (s) => [
+ s.scoutConfigs,
+ s.rollups,
+ s.activeScoutTags,
+ s.scoutSearch,
+ s.scoutEnabledFilter,
+ s.rosterPlacement,
+ ],
+ (
+ scoutConfigs: SignalScoutConfig[] | null,
+ rollups: Map<string, ScoutRollup>,
+ activeScoutTags: string[],
+ scoutSearch: string,
+ scoutEnabledFilter: ScoutEnabledFilter,
+ rosterPlacement: Record<string, ScoutGroupKey>
+ ): ScoutGroupBucket[] => {
+ const query = scoutSearch.trim().toLowerCase()
+ // Alphabetical only. Sorting by `enabled` too would jump a row to the bottom of its
+ // group the moment you switched it off, on top of the group change itself.
+ const matching = [...(scoutConfigs ?? [])]
+ .sort((a, b) =>
+ prettifyScoutSkillName(a.skill_name).localeCompare(prettifyScoutSkillName(b.skill_name))
+ )
+ .filter((config) => configMatchesScoutTags(config, activeScoutTags))
+ .filter(
+ (config) =>
+ scoutEnabledFilter === 'all' || config.enabled === (scoutEnabledFilter === 'enabled')
+ )
+ .filter(
+ (config) =>
+ !query ||
+ prettifyScoutSkillName(config.skill_name).toLowerCase().includes(query) ||
+ config.skill_name.toLowerCase().includes(query) ||
+ (config.description ?? '').toLowerCase().includes(query)
+ )
+ return groupScouts(matching, rollups, new Date(), rosterPlacement)
+ },
+ ],
+ /**
+ * Group sizes over the whole fleet, unnarrowed by search — the roster header states how many
+ * scouts need a decision, and that number must not move as you type into the search box.
+ */
+ rosterGroupCounts: [
+ (s) => [s.scoutConfigs, s.rollups, s.rosterPlacement],
(
scoutConfigs: SignalScoutConfig[] | null,
- hideDisabled: boolean,
- activeScoutTags: string[]
- ): SignalScoutConfig[] => {
- let sorted = sortConfigsForDisplay(scoutConfigs ?? [])
- if (hideDisabled) {
- sorted = sorted.filter((config) => config.enabled)
+ rollups: Map<string, ScoutRollup>,
+ rosterPlacement: Record<string, ScoutGroupKey>
+ ): Record<ScoutGroupKey, number> => {
+ const counts: Record<ScoutGroupKey, number> = {
+ needs_you: 0,
+ working: 0,
+ watching: 0,
+ dry_run: 0,
+ settling_in: 0,
+ off: 0,
+ }
+ for (const bucket of groupScouts(scoutConfigs ?? [], rollups, new Date(), rosterPlacement)) {
+ counts[bucket.key] = bucket.configs.length
}
- return sorted.filter((config) => configMatchesScoutTags(config, activeScoutTags))
+ return counts
},
],
// Fleet-wide output tally for the "Scout findings" callout, read from the cheap backend
@@ -642,12 +763,14 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
scoutCount: number
authoredReportCount: number
editedReportCount: number
+ runCount: number
latestAt: string | null
} => ({
count: fleetFindingsSummary?.count ?? 0,
scoutCount: fleetFindingsSummary?.scout_count ?? 0,
authoredReportCount: fleetFindingsSummary?.authored_report_count ?? 0,
editedReportCount: fleetFindingsSummary?.edited_report_count ?? 0,
+ runCount: fleetFindingsSummary?.run_count ?? 0,
latestAt: fleetFindingsSummary?.latest_at ?? null,
}),
],
@@ -671,6 +794,39 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
},
})
},
+ // Placement is refreshed here, off server data only, and deliberately not from
+ // `patchScoutConfigLocally` — an optimistic toggle must not relocate the row being clicked.
+ loadScoutConfigsSuccess: () => {
+ actions.setRosterPlacement(computeRosterPlacement(values))
+ },
+ loadScoutRunsSuccess: () => {
+ actions.setRosterPlacement(computeRosterPlacement(values))
+ },
+ runScoutNow: async ({ configId }) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.runScoutNowFinished(configId)
+ return
+ }
+ const config = values.scoutConfigs?.find((candidate) => candidate.id === configId)
+ try {
+ await signalsScoutConfigRun(String(teamId), configId)
+ captureScoutAction({
+ actionType: 'run_now',
+ surface: 'scout_detail',
+ skillName: config?.skill_name ?? null,
+ })
+ lemonToast.success('Run started. It shows up in this scout’s runs when it finishes.')
+ // The run row appears on the next poll; pull once now so the page reacts immediately.
+ actions.loadScoutRuns()
+ } catch (error: any) {
+ // The endpoint refuses deliberately in several ordinary cases — already running,
+ // over the daily budget — so the backend's own message is the useful one.
+ lemonToast.error(error?.detail || error?.message || 'Could not start a run')
+ } finally {
+ actions.runScoutNowFinished(configId)
+ }
+ },
updateScoutConfig: async ({ configId, updates }) => {
const inFlight: Set<string> = (cache.updatingScoutIds ??= new Set())
const pendingUpdates: Map<string, SignalScoutConfigUpdate> = (cache.pendingScoutConfigUpdates ??= new Map())
@@ -735,7 +891,7 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
}
}
},
- deleteScout: async ({ configId }) => {
+ deleteScout: async ({ configId, surface }) => {
// The reducer above already flags this id, but that value is reactive (for the button)
// and can't tell a fresh submit from a duplicate. The cache Set is the non-reactive guard:
// a second submit while the first is in flight bails before issuing another request.
@@ -789,15 +945,22 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
actions.removeScoutConfigLocally(configId)
captureScoutAction({
actionType: 'delete_scout',
- surface: 'fleet_list',
+ surface,
skillName: config.skill_name,
extra: { scout_origin: config.scout_origin, success: true },
})
lemonToast.success(`Deleted ${displayName}`)
+ // The scout's own page (and any finding deep link under it) has nothing left to show
+ // once it is gone.
+ const scoutPath = urls.inboxScout(config.skill_name)
+ const { pathname } = router.values.location
+ if (pathname.endsWith(scoutPath) || pathname.includes(`${scoutPath}/`)) {
+ router.actions.push(urls.inbox('scouts'))
+ }
} catch (error: any) {
captureScoutAction({
actionType: 'delete_scout',
- surface: 'fleet_list',
+ surface,
skillName: config.skill_name,
extra: { scout_origin: config.scout_origin, success: false },
})
@@ -841,23 +1004,38 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
},
startRunsPolling: () => {
// Fetch once immediately, then a slow poll keeps "running now" + recent emissions
- // fresh. The keyed disposable replaces any prior poll and is torn down on
- // stopRunsPolling / unmount / tab hide. The cheap findings summary rides the same
- // cadence so the "Scout findings" callout fills in on its own fast query. The fleet
- // list needs only the per-scout runs; the paginated window is the findings page's own
- // source and is polled there.
+ // fresh. The keyed disposable is torn down on stopRunsPolling / unmount / tab hide.
+ // The cheap findings summary rides the same cadence so the roster headline fills in on
+ // its own fast query. The fleet list needs only the per-scout runs; the paginated
+ // window is the findings page's own source and is polled there.
+ //
+ // Reference-counted: the roster stays mounted (hidden) under a scout page, and both
+ // subscribe. Without the count the page's unmount would stop the roster's poll.
+ cache.runsPollSubscribers = (cache.runsPollSubscribers ?? 0) + 1
actions.loadScoutRuns()
actions.loadFleetFindingsSummary()
+ if (values.scoutMetadata === null) {
+ actions.loadScoutMetadata()
+ }
+ if (cache.runsPollSubscribers > 1) {
+ return
+ }
cache.disposables.add(() => {
const interval = setInterval(() => {
actions.loadScoutRuns()
actions.loadFleetFindingsSummary()
+ // The coordinator stamps `last_run_at` on dispatch, and the next-run labels derive from
+ // it, so a page left open across a scheduled run would otherwise read "Due now" forever.
+ actions.loadScoutConfigs()
}, RUNS_REFETCH_INTERVAL_MS)
return () => clearInterval(interval)
}, 'runsPoll')
},
stopRunsPolling: () => {
- cache.disposables.dispose('runsPoll')
+ cache.runsPollSubscribers = Math.max(0, (cache.runsPollSubscribers ?? 0) - 1)
+ if (cache.runsPollSubscribers === 0) {
+ cache.disposables.dispose('runsPoll')
+ }
},
})),
@@ -866,8 +1044,6 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([
// Configs are cheap and the always-mounted setup widget needs them. The paginated
// runs window is loaded + polled only while the fleet list is open (startRunsPolling).
actions.loadScoutConfigs()
- // Metadata carries the alpha banner; a one-shot read is enough (it changes rarely).
- actions.loadScoutMetadata()
},
})),
])
diff --git a/products/signals/frontend/inbox/logics/scoutNotesLogic.ts b/products/signals/frontend/inbox/logics/scoutNotesLogic.ts
new file mode 100644
index 000000000000..308e119095c2
--- /dev/null
+++ b/products/signals/frontend/inbox/logics/scoutNotesLogic.ts
@@ -0,0 +1,271 @@
+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import {
+ signalsScoutNotesCreate,
+ signalsScoutNotesDestroy,
+ signalsScoutNotesList,
+} from 'products/signals/frontend/generated/api'
+import type { ScoutNoteApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { captureScoutAction } from '../inboxAnalytics'
+
+export interface ScoutNotesLogicProps {
+ /** The scout these notes steer, or '' for the fleet-wide view. */
+ skillName: string
+}
+
+/**
+ * Where a note came from, in the words a reader needs. A note someone typed is a directive; one
+ * derived from inbox activity is evidence about a particular report, and reads very differently —
+ * so the origin is shown rather than flattened into "a note".
+ */
+export const SCOUT_NOTE_ORIGIN_LABEL: Record<string, string> = {
+ human: 'Left directly',
+ report_dismissal: 'From a dismissal',
+ report_discussion: 'From a discussion',
+ report_feedback: 'From a rating',
+}
+
+export function scoutNoteOriginLabel(origin: string): string {
+ return SCOUT_NOTE_ORIGIN_LABEL[origin] ?? 'From the inbox'
+}
+
+/** A note left directly is the team steering the fleet; the rest are derived from inbox activity. */
+export function isDirectScoutNote(note: ScoutNoteApi): boolean {
+ return note.origin === 'human'
+}
+
+/**
+ * One request, newest first. Well above any real history (a scout carries a handful of notes), but
+ * a scout that somehow hits it shows a caption rather than a silently short list.
+ */
+export const NOTES_FETCH_LIMIT = 200
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scoutNotesLogicValues {
+ activeNotes: ScoutNoteApi[]
+ directNotes: ScoutNoteApi[]
+ fleetWideNotes: ScoutNoteApi[]
+ lastSaveFailed: boolean
+ notes: ScoutNoteApi[]
+ notesCapped: boolean
+ notesLoadFailed: boolean
+ notesLoading: boolean
+ retiredNoteIds: string[]
+ savingNote: boolean
+ scoutNotes: ScoutNoteApi[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scoutNotesLogicActions {
+ createNote: (content: string) => {
+ content: string
+ }
+ createNoteFailed: () => {
+ value: true
+ }
+ createNoteFinished: () => {
+ value: true
+ }
+ deleteNote: (noteId: string) => {
+ noteId: string
+ }
+ deleteNoteFailed: (noteId: string) => {
+ noteId: string
+ }
+ loadNotes: () => any
+ loadNotesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadNotesSuccess: (
+ notes: ScoutNoteApi[],
+ payload?: any
+ ) => {
+ notes: ScoutNoteApi[]
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scoutNotesLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ activeNotes: (notes: ScoutNoteApi[], retiredNoteIds: string[]) => ScoutNoteApi[]
+ notesCapped: (notes: ScoutNoteApi[]) => boolean
+ scoutNotes: (activeNotes: ScoutNoteApi[], arg: any) => ScoutNoteApi[]
+ fleetWideNotes: (activeNotes: ScoutNoteApi[]) => ScoutNoteApi[]
+ directNotes: (activeNotes: ScoutNoteApi[]) => ScoutNoteApi[]
+ }
+}
+
+export type scoutNotesLogicType = MakeLogicType<
+ scoutNotesLogicValues,
+ scoutNotesLogicActions,
+ ScoutNotesLogicProps,
+ scoutNotesLogicMeta
+>
+
+/**
+ * The steering channel between a team and its scouts (`SignalScoutNote`): notes a person left, plus
+ * the ones the inbox forwards on their behalf when they dismiss, discuss, or rate a report. Every
+ * run reads them as prior context, so this is what tuning a scout looks like short of editing its
+ * skill.
+ *
+ * Keyed by skill name; the empty key is the fleet-wide view. The list endpoint returns a scout's
+ * own notes *plus* the general ones when given a `skill_name`, so the selectors split them back
+ * apart — a note addressed to every scout shouldn't read as something said about this one.
+ */
+export const scoutNotesLogic = kea<scoutNotesLogicType>([
+ path((key) => ['scenes', 'inbox', 'logics', 'scoutNotesLogic', key]),
+ props({} as ScoutNotesLogicProps),
+ key((props) => props.skillName || 'fleet'),
+
+ actions({
+ createNote: (content: string) => ({ content }),
+ createNoteFailed: true,
+ createNoteFinished: true,
+ deleteNote: (noteId: string) => ({ noteId }),
+ deleteNoteFailed: (noteId: string) => ({ noteId }),
+ }),
+
+ loaders(({ props }) => ({
+ notes: [
+ [] as ScoutNoteApi[],
+ {
+ loadNotes: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return []
+ }
+ return await signalsScoutNotesList(String(teamId), {
+ limit: NOTES_FETCH_LIMIT,
+ ...(props.skillName ? { skill_name: props.skillName } : {}),
+ })
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ // Retired here, whatever the server has said since. A load that was already in flight when
+ // the note was retired can resolve after the delete and would otherwise resurrect the row.
+ retiredNoteIds: [
+ [] as string[],
+ {
+ deleteNote: (state, { noteId }) => [...state, noteId],
+ deleteNoteFailed: (state, { noteId }) => state.filter((id) => id !== noteId),
+ },
+ ],
+ notesLoadFailed: [
+ false,
+ {
+ loadNotes: () => false,
+ loadNotesSuccess: () => false,
+ loadNotesFailure: () => true,
+ },
+ ],
+ savingNote: [
+ false,
+ {
+ createNote: () => true,
+ createNoteFinished: () => false,
+ },
+ ],
+ // Whether the most recent save failed. The composer awaits `createNote` and reads this to
+ // decide whether to close, since a listener cannot return a result.
+ lastSaveFailed: [
+ false,
+ {
+ createNote: () => false,
+ createNoteFailed: () => true,
+ },
+ ],
+ }),
+
+ selectors({
+ activeNotes: [
+ (s) => [s.notes, s.retiredNoteIds],
+ (notes: ScoutNoteApi[], retiredNoteIds: string[]): ScoutNoteApi[] =>
+ retiredNoteIds.length ? notes.filter((note) => !retiredNoteIds.includes(note.id)) : notes,
+ ],
+ notesCapped: [(s) => [s.notes], (notes: ScoutNoteApi[]): boolean => notes.length >= NOTES_FETCH_LIMIT],
+ // Notes addressed to this scout specifically. On the fleet view every note qualifies.
+ scoutNotes: [
+ (s) => [s.activeNotes, (_, props) => props],
+ (activeNotes: ScoutNoteApi[], props: ScoutNotesLogicProps): ScoutNoteApi[] =>
+ props.skillName ? activeNotes.filter((note) => note.skill_name === props.skillName) : activeNotes,
+ ],
+ fleetWideNotes: [
+ (s) => [s.activeNotes],
+ (activeNotes: ScoutNoteApi[]): ScoutNoteApi[] => activeNotes.filter((note) => !note.skill_name),
+ ],
+ directNotes: [
+ (s) => [s.activeNotes],
+ (activeNotes: ScoutNoteApi[]): ScoutNoteApi[] => activeNotes.filter(isDirectScoutNote),
+ ],
+ }),
+
+ listeners(({ actions, props }) => ({
+ createNote: async ({ content }) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.createNoteFailed()
+ actions.createNoteFinished()
+ return
+ }
+ try {
+ await signalsScoutNotesCreate(String(teamId), {
+ content,
+ ...(props.skillName ? { skill_name: props.skillName } : {}),
+ })
+ captureScoutAction({
+ actionType: 'leave_note',
+ surface: props.skillName ? 'scout_detail' : 'fleet_list',
+ skillName: props.skillName || null,
+ })
+ lemonToast.success(
+ props.skillName
+ ? 'Your scout picks this up on its next run'
+ : 'Every scout picks this up on its next run'
+ )
+ actions.loadNotes()
+ } catch (error: any) {
+ lemonToast.error(error?.detail || error?.message || 'Failed to leave the note')
+ actions.createNoteFailed()
+ } finally {
+ actions.createNoteFinished()
+ }
+ },
+ deleteNote: async ({ noteId }) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ // Optimistic: `retiredNoteIds` hides the row at once; a failed delete un-hides it.
+ try {
+ await signalsScoutNotesDestroy(String(teamId), noteId)
+ captureScoutAction({
+ actionType: 'delete_note',
+ surface: props.skillName ? 'scout_detail' : 'fleet_list',
+ skillName: props.skillName || null,
+ })
+ } catch (error: any) {
+ lemonToast.error(error?.detail || error?.message || 'Failed to retire the note')
+ actions.deleteNoteFailed(noteId)
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadNotes()
+ }),
+])
diff --git a/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts b/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts
index 9cfd4b35c3b3..b41626d01768 100644
--- a/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts
@@ -116,6 +116,36 @@ describe('scratchpadLogic', () => {
expect(logic.values.expandedKeys).toEqual([TRUNCATED.key])
})
+ // The roster's "learned" count and the scout page's memory panel read `entries`; a fleet search
+ // must land somewhere else or it silently shrinks a scout's memory until the next reload.
+ it('keeps the unfiltered window intact while a search runs', async () => {
+ useMocks({
+ get: {
+ [SCRATCHPAD_URL]: ({ request }) => {
+ const params = new URL(request.url).searchParams
+ searchRequests.push(params)
+ return [200, params.get('text') ? [WHOLE] : [TRUNCATED, ALSO_TRUNCATED, WHOLE]]
+ },
+ },
+ })
+
+ logic.actions.setSearchText('short')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(searchRequests.map((params) => params.get('text'))).toEqual(['short'])
+ expect(logic.values.entries).toHaveLength(3)
+ expect(logic.values.searchResults).toEqual([WHOLE])
+ expect(logic.values.visibleEntries).toEqual([WHOLE])
+
+ logic.actions.setSearchText('')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.searchResults).toBeNull()
+ expect(logic.values.visibleEntries).toHaveLength(3)
+ // Clearing the box needs no request: the window never went anywhere.
+ expect(searchRequests).toHaveLength(1)
+ })
+
it('keeps the card usable when the body lookup fails', async () => {
useMocks({ get: { [SCRATCHPAD_URL]: () => [500, {}] } })
diff --git a/products/signals/frontend/inbox/logics/scratchpadLogic.ts b/products/signals/frontend/inbox/logics/scratchpadLogic.ts
index b352b3467474..8784c3c8e88e 100644
--- a/products/signals/frontend/inbox/logics/scratchpadLogic.ts
+++ b/products/signals/frontend/inbox/logics/scratchpadLogic.ts
@@ -1,11 +1,14 @@
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { dayjs } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'
import { signalsScoutScratchpadSearch } from 'products/signals/frontend/generated/api'
import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'
+import { SCOUT_ROSTER_WINDOW_HOURS } from '../utils/scoutRunsWindow'
+
// The list view shows two ways to read the fleet's memory: newest-first (the API's
// native order) or clustered by the key namespace scouts choose (`tags:*`, `dedupe:*`).
export type ScratchpadGrouping = 'recent' | 'topic'
@@ -53,6 +56,16 @@ export function isPreviewTruncated(content: string | null | undefined): boolean
return (content?.length ?? 0) >= SCRATCHPAD_PREVIEW_CHARS
}
+/**
+ * The notes one scout wrote, newest first. The search endpoint has no per-scout filter, but every
+ * entry carries the skill that created it, so the scout page narrows the already-loaded project
+ * window rather than issuing a second read. Always fed the unfiltered `entries`, never search
+ * results: a scout's memory shouldn't shrink because someone typed in the fleet search box.
+ */
+export function entriesForSkill(entries: ScratchpadEntryApi[] | null, skillName: string): ScratchpadEntryApi[] {
+ return (entries ?? []).filter((entry) => entry.created_by_skill === skillName)
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scratchpadLogicValues {
entries: ScratchpadEntryApi[] | null
@@ -65,13 +78,18 @@ export interface scratchpadLogicValues {
lastUpdatedAt: string | null
loadFailed: boolean
loadingContentKeys: string[]
+ recentlyLearnedCount: number
+ searchFailed: boolean
+ searchResults: ScratchpadEntryApi[] | null
+ searchResultsLoading: boolean
searchText: string
totalCount: number | null
+ visibleEntries: ScratchpadEntryApi[] | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scratchpadLogicActions {
- loadEntries: (_payload: void) => void
+ loadEntries: () => any
loadEntriesFailure: (
error: string,
errorObject?: any
@@ -81,10 +99,10 @@ export interface scratchpadLogicActions {
}
loadEntriesSuccess: (
entries: ScratchpadEntryApi[],
- payload?: void
+ payload?: any
) => {
entries: ScratchpadEntryApi[]
- payload?: void
+ payload?: any
}
loadFullContent: (key: string) => {
key: string
@@ -99,6 +117,21 @@ export interface scratchpadLogicActions {
content: string
key: string
}
+ loadSearchResults: (_payload: void) => void
+ loadSearchResultsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSearchResultsSuccess: (
+ searchResults: ScratchpadEntryApi[] | null,
+ payload?: void
+ ) => {
+ searchResults: ScratchpadEntryApi[] | null
+ payload?: void
+ }
setGrouping: (grouping: ScratchpadGrouping) => {
grouping: ScratchpadGrouping
}
@@ -117,8 +150,14 @@ export interface scratchpadLogicActions {
export interface scratchpadLogicMeta {
__keaTypeGenInternalSelectorTypes: {
totalCount: (entries: ScratchpadEntryApi[] | null) => number | null
+ recentlyLearnedCount: (entries: ScratchpadEntryApi[] | null) => number
lastUpdatedAt: (entries: ScratchpadEntryApi[] | null) => string | null
- groups: (entries: ScratchpadEntryApi[] | null) => ScratchpadNamespaceGroup[]
+ visibleEntries: (
+ entries: ScratchpadEntryApi[] | null,
+ searchResults: ScratchpadEntryApi[] | null,
+ searchText: string
+ ) => ScratchpadEntryApi[] | null
+ groups: (visibleEntries: ScratchpadEntryApi[] | null) => ScratchpadNamespaceGroup[]
}
}
@@ -134,6 +173,10 @@ export type scratchpadLogicType = MakeLogicType<
* the debounced search text (wired straight to the endpoint's `?text=` ILIKE), and the recent /
* by-topic grouping toggle. There is no write surface on purpose — humans inspect this memory;
* only the harness (internal-scope) writes it.
+ *
+ * `entries` is always the unfiltered project window: the roster's "learned" headline and the
+ * scout page's memory panel read it, and a search must not shrink those. A search lands in
+ * `searchResults` instead, and the panel shows whichever applies via `visibleEntries`.
*/
export const scratchpadLogic = kea<scratchpadLogicType>([
path(['scenes', 'inbox', 'logics', 'scratchpadLogic']),
@@ -152,14 +195,29 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
entries: [
null as ScratchpadEntryApi[] | null,
{
- loadEntries: async (_payload: void, breakpoint) => {
+ loadEntries: async () => {
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
return []
}
+ return await signalsScoutScratchpadSearch(String(teamId), {
+ limit: SCRATCHPAD_FETCH_LIMIT,
+ content_max_chars: SCRATCHPAD_PREVIEW_CHARS,
+ })
+ },
+ },
+ ],
+ searchResults: [
+ null as ScratchpadEntryApi[] | null,
+ {
+ loadSearchResults: async (_payload: void, breakpoint) => {
+ const teamId = teamLogic.values.currentTeamId
const text = values.searchText.trim()
+ if (!teamId || !text) {
+ return null
+ }
const results = await signalsScoutScratchpadSearch(String(teamId), {
- text: text || undefined,
+ text,
limit: SCRATCHPAD_FETCH_LIMIT,
content_max_chars: SCRATCHPAD_PREVIEW_CHARS,
})
@@ -184,6 +242,22 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
loadEntriesFailure: () => true,
},
],
+ searchFailed: [
+ false,
+ {
+ loadSearchResults: () => false,
+ loadSearchResultsSuccess: () => false,
+ loadSearchResultsFailure: () => true,
+ },
+ ],
+ // Clearing the box drops the last result set at once, so the unfiltered window shows
+ // without waiting on the debounce.
+ searchResults: [
+ null as ScratchpadEntryApi[] | null,
+ {
+ setSearchText: (state, { searchText }) => (searchText.trim() ? state : null),
+ },
+ ],
// Which "By topic" clusters are open. Start collapsed (high-level view of topics first);
// switching grouping resets the set so entering "By topic" always opens fully collapsed.
expandedNamespaces: [
@@ -203,8 +277,8 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
state.includes(key) ? state.filter((k) => k !== key) : [...state, key],
},
],
- // Full bodies fetched on expand, keyed by entry key. Dropped on every reload since a new
- // search returns a different set of entries (and possibly newer bodies for the same keys).
+ // Full bodies fetched on expand, keyed by entry key. Dropped on every reload of the window,
+ // which may carry newer bodies for the same keys.
fullContentByKey: [
{} as Record<string, string>,
{
@@ -228,15 +302,38 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
(s) => [s.entries],
(entries: ScratchpadEntryApi[] | null): number | null => (entries ? entries.length : null),
],
+ // Entries written or refreshed over the roster window, so the roster's "learned" headline
+ // sits on the same span as the run and report numbers the summary endpoint returns for it.
+ recentlyLearnedCount: [
+ (s) => [s.entries],
+ (entries: ScratchpadEntryApi[] | null): number => {
+ if (!entries) {
+ return 0
+ }
+ const windowStart = dayjs().subtract(SCOUT_ROSTER_WINDOW_HOURS, 'hours')
+ return entries.filter((entry) => entry.updated_at && dayjs(entry.updated_at).isAfter(windowStart))
+ .length
+ },
+ ],
// Entries are newest-first, so the head's timestamp drives the callout's "updated when" hint.
lastUpdatedAt: [
(s) => [s.entries],
(entries: ScratchpadEntryApi[] | null): string | null => entries?.[0]?.updated_at ?? null,
],
+ // What the panel lists: the search hits while a search is typed, the whole window otherwise.
+ // Null while the applicable set is still loading.
+ visibleEntries: [
+ (s) => [s.entries, s.searchResults, s.searchText],
+ (
+ entries: ScratchpadEntryApi[] | null,
+ searchResults: ScratchpadEntryApi[] | null,
+ searchText: string
+ ): ScratchpadEntryApi[] | null => (searchText.trim() ? searchResults : entries),
+ ],
// Entries arrive newest-first; preserve that order within each namespace cluster, and order
// the clusters by their most recently touched entry so the liveliest topic floats to the top.
groups: [
- (s) => [s.entries],
+ (s) => [s.visibleEntries],
(entries: ScratchpadEntryApi[] | null): ScratchpadNamespaceGroup[] => {
const byNamespace = new Map<string, ScratchpadEntryApi[]>()
for (const entry of entries ?? []) {
@@ -260,9 +357,12 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
}),
listeners(({ actions, values }) => ({
- setSearchText: async (_, breakpoint) => {
+ setSearchText: async ({ searchText }, breakpoint) => {
+ if (!searchText.trim()) {
+ return
+ }
await breakpoint(SEARCH_DEBOUNCE_MS)
- actions.loadEntries()
+ actions.loadSearchResults()
},
// Opening a card is the only moment a full body is worth fetching — and only when the
@@ -276,7 +376,9 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
if (Object.hasOwn(values.fullContentByKey, key) || values.loadingContentKeys.includes(key)) {
return
}
- const entry = values.entries?.find((e) => e.key === key)
+ // A card can sit in either list (the scout page renders from the window while a search
+ // may still be typed in the panel), so look in both.
+ const entry = [...(values.entries ?? []), ...(values.searchResults ?? [])].find((e) => e.key === key)
if (entry && isPreviewTruncated(entry.content)) {
actions.loadFullContent(key)
}
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index c7a3c5d344d7..b6e97fb4d571 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -169,13 +169,22 @@ export const SOURCE_STEERING_MAX_LENGTH = 2000
// ── Inbox 2.0 IA: tabs + scope ──────────────────────────────────────────────
-export type InboxTabKey = 'pulls' | 'reports' | 'not-actionable' | 'runs' | 'archived' | 'config'
-
-export const INBOX_TAB_KEYS: InboxTabKey[] = ['pulls', 'reports', 'not-actionable', 'runs', 'archived', 'config']
+export type InboxTabKey = 'pulls' | 'reports' | 'scouts' | 'not-actionable' | 'runs' | 'archived' | 'config'
+
+export const INBOX_TAB_KEYS: InboxTabKey[] = [
+ 'pulls',
+ 'reports',
+ 'scouts',
+ 'not-actionable',
+ 'runs',
+ 'archived',
+ 'config',
+]
export const INBOX_TAB_LABEL: Record<InboxTabKey, string> = {
pulls: 'Pull requests',
reports: 'Reports',
+ scouts: 'Scouts',
'not-actionable': 'Not actionable',
runs: 'Runs',
archived: 'Archive',
@@ -186,6 +195,7 @@ export const INBOX_TAB_LABEL: Record<InboxTabKey, string> = {
export const INBOX_TAB_DESCRIPTION: Record<InboxTabKey, string> = {
pulls: 'Pull requests agents opened to resolve reports. Review and merge them on GitHub.',
reports: 'Issues and opportunities agents found in your product data, researched and prioritized for your review.',
+ scouts: 'Scheduled agents that sweep this project and file what they find.',
'not-actionable':
'Reports judged not actionable because they are too vague, lack supporting evidence, or describe expected behavior.',
runs: 'Project-wide list of agent runs, for debugging.',
diff --git a/products/signals/frontend/inbox/utils/scoutGroups.test.ts b/products/signals/frontend/inbox/utils/scoutGroups.test.ts
new file mode 100644
index 000000000000..e50d5e8d0809
--- /dev/null
+++ b/products/signals/frontend/inbox/utils/scoutGroups.test.ts
@@ -0,0 +1,218 @@
+import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
+
+import { SignalScoutRunSummary } from '../types'
+import { groupScouts, nextRunAt, scoutCadenceLabel, scoutGroup, ScoutGroupKey, scoutSubtitle } from './scoutGroups'
+import { computeScoutRollups, ScoutRollup } from './scoutRunsWindow'
+
+const NOW = new Date('2026-06-27T22:00:00Z')
+
+function makeConfig(overrides: Partial<SignalScoutConfig> = {}): SignalScoutConfig {
+ return {
+ id: 'config-1',
+ skill_name: 'signals-scout-apm',
+ description: 'Watches latency and throughput.',
+ scout_origin: 'canonical',
+ enabled: true,
+ status: 'active',
+ pause_reason: null,
+ emit: true,
+ run_interval_minutes: 60,
+ run_cron_schedule: null,
+ output_destinations: {},
+ structured_output_schema: null,
+ network_access: 'trusted',
+ model: null,
+ last_run_at: '2026-06-27T21:30:00Z',
+ consecutive_failure_count: 0,
+ status_changed_at: null,
+ auto_pause_exempt: false,
+ tags: [],
+ created_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ } as SignalScoutConfig
+}
+
+function makeRun(overrides: Partial<SignalScoutRunSummary> = {}): SignalScoutRunSummary {
+ return {
+ run_id: 'run-1',
+ skill_name: 'signals-scout-apm',
+ skill_version: 1,
+ status: 'completed',
+ metadata: {},
+ created_at: '2026-06-27T21:00:00Z',
+ started_at: '2026-06-27T21:00:00Z',
+ completed_at: '2026-06-27T21:02:00Z',
+ summary: '',
+ emitted_count: 0,
+ emitted_finding_ids: [],
+ emitted_report_ids: [],
+ edited_report_ids: [],
+ ...overrides,
+ }
+}
+
+function rollupFor(runs: SignalScoutRunSummary[]): ScoutRollup | undefined {
+ return computeScoutRollups(runs).get('signals-scout-apm')
+}
+
+describe('scoutGroups', () => {
+ describe('scoutGroup', () => {
+ it.each<[string, Partial<SignalScoutConfig>, SignalScoutRunSummary[], ScoutGroupKey]>([
+ [
+ 'a system pause outranks everything else',
+ { status: 'paused_by_system', pause_reason: 'repeated_failures', enabled: false },
+ [],
+ 'needs_you',
+ ],
+ [
+ 'a warning still needs a person even though it keeps running',
+ { status: 'pending_pause', pause_reason: 'ignored' },
+ [makeRun({ emitted_report_ids: ['r-1'] })],
+ 'needs_you',
+ ],
+ ['a human pause is off, not trouble', { status: 'paused_by_user', enabled: false }, [], 'off'],
+ ['dry run beats output — it files nothing', { emit: false }, [makeRun({ emitted_count: 3 })], 'dry_run'],
+ [
+ 'a new scout is not judged on its output yet',
+ { created_at: '2026-06-25T00:00:00Z' },
+ [makeRun({ emitted_count: 1 })],
+ 'settling_in',
+ ],
+ ['reports authored count as producing', {}, [makeRun({ emitted_report_ids: ['r-1'] })], 'working'],
+ ['edited reports count as producing', {}, [makeRun({ edited_report_ids: ['r-2'] })], 'working'],
+ ['findings count as producing', {}, [makeRun({ emitted_count: 2 })], 'working'],
+ ['running with no output is watching, not trouble', {}, [makeRun()], 'watching'],
+ ['no runs at all is still watching', {}, [], 'watching'],
+ ])('%s', (_name, overrides, runs, expected) => {
+ expect(scoutGroup(makeConfig(overrides), rollupFor(runs), NOW)).toEqual(expected)
+ })
+
+ it('restarts the settling-in window when a human re-enables a scout', () => {
+ const reEnabled = makeConfig({
+ created_at: '2026-01-01T00:00:00Z',
+ status_changed_at: '2026-06-24T00:00:00Z',
+ })
+ expect(scoutGroup(reEnabled, rollupFor([]), NOW)).toEqual('settling_in')
+ })
+ })
+
+ describe('groupScouts', () => {
+ it('returns buckets in display order and drops empty ones', () => {
+ const buckets = groupScouts(
+ [
+ makeConfig({ id: 'a', skill_name: 'signals-scout-a' }),
+ makeConfig({ id: 'b', skill_name: 'signals-scout-b', status: 'paused_by_user', enabled: false }),
+ makeConfig({ id: 'c', skill_name: 'signals-scout-c', status: 'paused_by_system', enabled: false }),
+ ],
+ new Map(),
+ NOW
+ )
+ expect(buckets.map((bucket) => bucket.key)).toEqual(['needs_you', 'watching', 'off'])
+ expect(buckets[0].configs.map((config) => config.id)).toEqual(['c'])
+ })
+ })
+
+ describe('scoutSubtitle', () => {
+ it('names the failure streak so a paused scout says why', () => {
+ const config = makeConfig({
+ status: 'paused_by_system',
+ pause_reason: 'repeated_failures',
+ consecutive_failure_count: 4,
+ enabled: false,
+ })
+ expect(scoutSubtitle(config, undefined, NOW)).toEqual({
+ text: 'Paused itself — 4 runs in a row failed',
+ tone: 'danger',
+ })
+ })
+
+ it.each<[string, Partial<SignalScoutConfig>, string]>([
+ [
+ 'an ignored pause blames consumption, not silence',
+ { status: 'paused_by_system', pause_reason: 'ignored', enabled: false },
+ 'Paused — nobody acted on its reports',
+ ],
+ [
+ 'a no-output warning asks a person to look',
+ { status: 'pending_pause', pause_reason: 'no_output' },
+ 'Warned — nothing surfaced in the last two weeks',
+ ],
+ ['a dry run says it files nothing', { emit: false }, 'Runs and investigates, but files nothing'],
+ ])('%s', (_name, overrides, expected) => {
+ expect(scoutSubtitle(makeConfig(overrides), undefined, NOW)?.text).toEqual(expected)
+ })
+
+ it('prefers what the last run checked over the scout description', () => {
+ const rollup = rollupFor([
+ makeRun({ summary: 'Swept 40 event series against the 14-day baseline. All inside range.' }),
+ ])
+ expect(scoutSubtitle(makeConfig(), rollup, NOW)?.text).toEqual(
+ 'Swept 40 event series against the 14-day baseline. All inside range.'
+ )
+ })
+
+ it('falls back to the description when no run has closed out', () => {
+ expect(scoutSubtitle(makeConfig(), rollupFor([]), NOW)?.text).toEqual('Watches latency and throughput.')
+ })
+
+ // Both anchor the settling-in window; only a fresh scout was actually created recently.
+ it.each([
+ ['a fresh scout', { created_at: '2026-06-26T22:00:00Z', status_changed_at: null }, 'Created '],
+ [
+ 'a re-enabled scout',
+ { created_at: '2026-01-01T00:00:00Z', status_changed_at: '2026-06-26T22:00:00Z' },
+ 'Turned on ',
+ ],
+ ])('says how %s entered the settling-in window', (_name, overrides, verb) => {
+ // `fromNow()` reads the wall clock, so only the verb is stable enough to pin.
+ expect(scoutSubtitle(makeConfig(overrides), rollupFor([]), NOW)?.text.startsWith(verb)).toBe(true)
+ })
+ })
+
+ describe('scoutCadenceLabel', () => {
+ it.each<[string, Partial<SignalScoutConfig>, string]>([
+ ['a rolling interval', { run_interval_minutes: 60 }, 'hourly'],
+ ['a plain daily cron keeps the friendlier phrasing', { run_cron_schedule: '0 9 * * *' }, 'daily at 09:00'],
+ [
+ 'a richer cron is spelled out rather than shown raw',
+ { run_cron_schedule: '35 8 * * 1-5' },
+ 'at 08:35 am, monday through friday',
+ ],
+ ])('%s', (_name, overrides, expected) => {
+ expect(scoutCadenceLabel(makeConfig(overrides))).toEqual(expected)
+ })
+ })
+
+ describe('nextRunAt', () => {
+ it('adds the rolling interval to the last run', () => {
+ expect(nextRunAt(makeConfig({ run_interval_minutes: 60 }), 'UTC', NOW)).toEqual(
+ new Date('2026-06-27T22:30:00Z')
+ )
+ })
+
+ it.each<[string, Partial<SignalScoutConfig>]>([
+ ['a scout that has never run', { last_run_at: null }],
+ ['a disabled scout', { enabled: false }],
+ ['an expression that does not parse', { run_cron_schedule: 'not a cron' }],
+ ])('says nothing for %s', (_name, overrides) => {
+ expect(nextRunAt(makeConfig(overrides), 'UTC', NOW)).toBeNull()
+ })
+
+ it('resolves a multi-slot cron rather than giving up on it', () => {
+ // 09:00 and 17:00 daily; NOW is 22:00, so the next slot is tomorrow morning.
+ const config = makeConfig({ run_cron_schedule: '0 9,17 * * *' })
+ expect(nextRunAt(config, 'UTC', NOW)).toEqual(new Date('2026-06-28T09:00:00Z'))
+ })
+
+ it('evaluates a cron in the project timezone, not the browser one', () => {
+ const config = makeConfig({ run_cron_schedule: '0 9 * * *' })
+ // 09:00 in New York on Jun 28 is 13:00 UTC (EDT, UTC-4).
+ expect(nextRunAt(config, 'America/New_York', NOW)).toEqual(new Date('2026-06-28T13:00:00Z'))
+ })
+
+ it('rolls a daily cron to tomorrow once today’s slot has passed', () => {
+ const config = makeConfig({ run_cron_schedule: '0 9 * * *' })
+ expect(nextRunAt(config, 'UTC', NOW)).toEqual(new Date('2026-06-28T09:00:00Z'))
+ })
+ })
+})
diff --git a/products/signals/frontend/inbox/utils/scoutGroups.ts b/products/signals/frontend/inbox/utils/scoutGroups.ts
new file mode 100644
index 000000000000..d61178a74523
--- /dev/null
+++ b/products/signals/frontend/inbox/utils/scoutGroups.ts
@@ -0,0 +1,244 @@
+import { describeCron, nextCronOccurrence } from 'lib/cron'
+import { dayjs } from 'lib/dayjs'
+
+import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'
+
+import { dailyCronToTime, formatRunIntervalShort, ScoutRollup } from './scoutRunsWindow'
+
+/**
+ * Where a scout sits in the roster, in the backend's own lifecycle vocabulary.
+ *
+ * `needs_you`, `off`, `dry_run` and `settling_in` each read straight off a stored field
+ * (`status` / `emit` / `created_at`), so the roster groups by what the scheduler already decided
+ * rather than by a second opinion computed in the UI. Only `working` vs `watching` is derived,
+ * from whether the run window produced output.
+ */
+export type ScoutGroupKey = 'needs_you' | 'working' | 'watching' | 'dry_run' | 'settling_in' | 'off'
+
+// Working leads: the roster's first job is to show the troop earning its keep, and trouble is
+// legible wherever it sits — the group heading is the only red band on the page.
+export const SCOUT_GROUP_ORDER: ScoutGroupKey[] = ['working', 'needs_you', 'watching', 'dry_run', 'settling_in', 'off']
+
+export const SCOUT_GROUP_LABEL: Record<ScoutGroupKey, string> = {
+ needs_you: 'Needs you',
+ working: 'Working',
+ watching: 'Watching',
+ dry_run: 'Dry run',
+ settling_in: 'Settling in',
+ off: 'Off',
+}
+
+/** Shown beside the group heading, so a group's bar is stated rather than inferred from its name. */
+export const SCOUT_GROUP_HINT: Record<ScoutGroupKey, string | null> = {
+ needs_you: null,
+ working: 'filed something recently',
+ watching: 'running, nothing worth filing',
+ dry_run: 'investigating, but filing nothing',
+ settling_in: 'too new to judge',
+ off: null,
+}
+
+/** Matches `SignalScoutConfig.COLD_START_GRACE` — how long the sweep leaves a new scout alone. */
+export const SCOUT_COLD_START_DAYS = 14
+
+/**
+ * A scout counts as producing when the window holds any output on either emit channel. Mirrors
+ * `runProducedOutput` at rollup scope: a report-channel scout that authors reports without ever
+ * emitting a weak finding is producing just as much as one that emits.
+ */
+function rollupProducedOutput(rollup: ScoutRollup | undefined): boolean {
+ if (!rollup) {
+ return false
+ }
+ return rollup.emittedCount > 0 || rollup.authoredReportIds.size > 0 || rollup.editedReportIds.size > 0
+}
+
+/**
+ * When the scout's current cold-start grace began: creation, or the later re-enable if there was one.
+ * `status_changed_at` is null on a freshly created scout and stamped on every later status change,
+ * so it restarts the grace on a human re-enable, matching the sweep's own anchor.
+ */
+function coldStartAnchor(config: SignalScoutConfig): { at: string; reenabled: boolean } | null {
+ const changedAt = config.status_changed_at
+ if (changedAt && (!config.created_at || dayjs(changedAt).isAfter(dayjs(config.created_at)))) {
+ return { at: changedAt, reenabled: true }
+ }
+ return config.created_at ? { at: config.created_at, reenabled: false } : null
+}
+
+function isWithinColdStart(config: SignalScoutConfig, now: Date): boolean {
+ const anchor = coldStartAnchor(config)
+ if (!anchor) {
+ return false
+ }
+ return dayjs(now).diff(dayjs(anchor.at), 'day', true) < SCOUT_COLD_START_DAYS
+}
+
+export function scoutGroup(config: SignalScoutConfig, rollup: ScoutRollup | undefined, now: Date): ScoutGroupKey {
+ // Status first: a system pause or warning outranks everything else the scout looks like, and a
+ // human pause means "off" no matter what the scout was doing when it stopped.
+ if (config.status === 'paused_by_system' || config.status === 'pending_pause') {
+ return 'needs_you'
+ }
+ if (!config.enabled || config.status === 'paused_by_user') {
+ return 'off'
+ }
+ if (!config.emit) {
+ return 'dry_run'
+ }
+ if (isWithinColdStart(config, now)) {
+ return 'settling_in'
+ }
+ return rollupProducedOutput(rollup) ? 'working' : 'watching'
+}
+
+export interface ScoutGroupBucket {
+ key: ScoutGroupKey
+ configs: SignalScoutConfig[]
+}
+
+/**
+ * Buckets in display order, empty groups dropped. Input order is preserved inside each bucket.
+ *
+ * `placement` pins a scout to the group it was last placed in. Without it, flipping a scout's
+ * switch moves its row to another group the instant you click — the row you were aiming at jumps
+ * out from under the pointer. Placement is refreshed when server data lands, not on local edits.
+ */
+export function groupScouts(
+ configs: SignalScoutConfig[],
+ rollups: Map<string, ScoutRollup>,
+ now: Date,
+ placement?: Record<string, ScoutGroupKey>
+): ScoutGroupBucket[] {
+ const buckets = new Map<ScoutGroupKey, SignalScoutConfig[]>()
+ for (const config of configs) {
+ const key = placement?.[config.id] ?? scoutGroup(config, rollups.get(config.skill_name), now)
+ const bucket = buckets.get(key)
+ if (bucket) {
+ bucket.push(config)
+ } else {
+ buckets.set(key, [config])
+ }
+ }
+ return SCOUT_GROUP_ORDER.filter((key) => buckets.has(key)).map((key) => ({
+ key,
+ configs: buckets.get(key) ?? [],
+ }))
+}
+
+/** Longest run summary the roster shows before it stops being scannable. */
+const SUBTITLE_MAX_CHARS = 110
+
+function truncate(text: string): string {
+ const collapsed = text.replace(/\s+/g, ' ').trim()
+ return collapsed.length > SUBTITLE_MAX_CHARS ? `${collapsed.slice(0, SUBTITLE_MAX_CHARS - 1)}…` : collapsed
+}
+
+export type ScoutSubtitleTone = 'danger' | 'warning' | 'muted'
+
+export interface ScoutSubtitle {
+ text: string
+ tone: ScoutSubtitleTone
+}
+
+/**
+ * The one line under a scout's name. For a scout in trouble it states the reason the scheduler
+ * recorded; for a healthy one it states what its last run actually looked at. Both are the reason
+ * a roster row is enough on its own — a status colour alone tells you something is wrong but not
+ * whether you can ignore it.
+ */
+export function scoutSubtitle(
+ config: SignalScoutConfig,
+ rollup: ScoutRollup | undefined,
+ now: Date
+): ScoutSubtitle | null {
+ if (config.status === 'paused_by_system') {
+ if (config.pause_reason === 'repeated_failures') {
+ const streak = config.consecutive_failure_count
+ return {
+ text:
+ streak > 0
+ ? `Paused itself — ${streak} runs in a row failed`
+ : 'Paused itself — its runs kept failing',
+ tone: 'danger',
+ }
+ }
+ return {
+ text:
+ config.pause_reason === 'ignored'
+ ? 'Paused — nobody acted on its reports'
+ : 'Paused — it stopped surfacing anything',
+ tone: 'danger',
+ }
+ }
+ if (config.status === 'pending_pause') {
+ return {
+ text:
+ config.pause_reason === 'ignored'
+ ? 'Pauses soon — nobody acted on its reports'
+ : 'Warned — nothing surfaced in the last two weeks',
+ tone: 'warning',
+ }
+ }
+ if (config.status === 'paused_by_user' || !config.enabled) {
+ const changedAt = config.status_changed_at
+ return {
+ text: changedAt ? `Turned off ${dayjs(changedAt).format('MMM D, YYYY')}` : 'Turned off',
+ tone: 'muted',
+ }
+ }
+ if (!config.emit) {
+ return { text: 'Runs and investigates, but files nothing', tone: 'muted' }
+ }
+ const anchor = coldStartAnchor(config)
+ if (anchor && isWithinColdStart(config, now)) {
+ // A re-enabled scout is months old; only a fresh one was "created" recently.
+ const verb = anchor.reenabled ? 'Turned on' : 'Created'
+ return { text: `${verb} ${dayjs(anchor.at).fromNow()}`, tone: 'muted' }
+ }
+ // What the last settled run actually checked. The scout writes this at close-out, so it reads
+ // as work done rather than as an absence of output.
+ const summary = rollup?.latestRun?.summary?.trim()
+ if (summary) {
+ return { text: truncate(summary), tone: 'muted' }
+ }
+ const description = config.description?.trim()
+ return description ? { text: truncate(description), tone: 'muted' } : null
+}
+
+/**
+ * When this scout is next due, or null when that can't be said: no run yet (the coordinator picks
+ * it up on its next tick), a paused scout, or an expression that doesn't parse.
+ *
+ * A rolling cadence is arithmetic on `last_run_at`; a cron is resolved by `cron-parser` in
+ * `timezone`, which must be the project's — that is what the coordinator evaluates cron schedules
+ * in, so evaluating in the browser's would drift a scheduled run by the offset between them.
+ */
+export function nextRunAt(config: SignalScoutConfig, timezone: string, now: Date): Date | null {
+ if (!config.enabled) {
+ return null
+ }
+ if (config.run_cron_schedule) {
+ return nextCronOccurrence(config.run_cron_schedule, timezone, now)
+ }
+ if (!config.last_run_at) {
+ return null
+ }
+ return dayjs(config.last_run_at).add(config.run_interval_minutes, 'minutes').toDate()
+}
+
+/**
+ * The cadence cell. A raw expression like `35 8 * * 1-5` is unreadable at a glance in a table, so
+ * a cron is rendered in words; the plain daily case keeps its shorter, friendlier phrasing rather
+ * than cronstrue's "At 09:00 AM".
+ */
+export function scoutCadenceLabel(config: SignalScoutConfig): string {
+ if (config.run_cron_schedule) {
+ const dailyTime = dailyCronToTime(config.run_cron_schedule)
+ if (dailyTime) {
+ return `daily at ${dailyTime}`
+ }
+ return describeCron(config.run_cron_schedule)?.toLowerCase() ?? config.run_cron_schedule
+ }
+ return formatRunIntervalShort(config.run_interval_minutes)
+}
diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
index 83570069b07c..073e5c30d0ac 100644
--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
@@ -27,6 +27,16 @@ export const SCOUT_RUNS_PER_SCOUT = 25
/** Label for per-scout stats, e.g. "last 25 runs". */
export const SCOUT_RUNS_PER_SCOUT_LABEL = `last ${SCOUT_RUNS_PER_SCOUT} runs`
+/**
+ * The span every fleet-level number on the roster describes: runs, reports filed and edited, and
+ * scratchpad entries learned. Per-scout depth is a run count, but summing "last 25 each" across a
+ * fleet is bounded by fleet size, so the fleet headline needs a common time span - and a week is
+ * the shortest one that gives a daily scout enough runs to say anything.
+ */
+export const SCOUT_ROSTER_WINDOW_DAYS = 7
+export const SCOUT_ROSTER_WINDOW_HOURS = SCOUT_ROSTER_WINDOW_DAYS * 24
+export const SCOUT_ROSTER_WINDOW_LABEL = `last ${SCOUT_ROSTER_WINDOW_DAYS} days`
+
/**
* Empty-state copy for a scout the window returned nothing for. Deliberately not "no runs in the
* last 30 days": the endpoint's staleness guard stretches with each scout's own cadence, so the
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 27b3954aaed8..d7c760d608b5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -37917,6 +37917,8 @@ export namespace Schemas {
authored_report_count: number;
/** Number of distinct inbox reports scouts edited via `edit_report`, deduped across runs, over the same most-recent-120-output-runs set as `count`, capped to the 50 most recently touched reports (the same slice the findings page lists) and excluding reports also authored within that set (authoring supersedes an edit; a report whose authoring run falls outside the cap counts as edited). */
edited_report_count: number;
+ /** Number of scout runs created in the window, whether or not they produced output. Unlike the report tallies it is not capped, so it is the fleet's activity over the same span the output counts describe. */
+ run_count: number;
/**
* ISO-8601 timestamp of the most recent output run (TaskRun completion, falling back to run creation), or null when nothing was produced in the window.
* @nullable