:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): scout page with tabs and a health strip (#99447)
posthog[bot]236e02946685
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 03d1e009e72a..81337bc95a4b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7949,17 +7949,21 @@ snapshots:scenes-app-inbox-scoutconfigform--weekly-schedule--light:hash: v1.k794b7964.b305519fa776432d2e8d1686d536e09782a66f217c75ce2b37038343e3b8cef8.Rug7RUaqdbIMdQ1ra_OhS6bzMQJ6f-AIjdbTEJCeHmoscenes-app-inbox-scoutdetailview--scout-page--dark:- hash: v1.k794b7964.087c9f8e7270660c414e1ae443c032dac44817cb099ed93dd81aa341ff658a7b.t5vsjylrvrYr-03aEMNg8ePJ3cgF2ITKlZRf9ZoT1ic+ hash: v1.k794b7964.7994cd307f5adb384df6008caa4d535248e8e10ba5505840e7b2661704cfa054.HD73lbCqzK0mXr4mcQ7lZJdj5J5aGTd_5LtbP3TDbLUscenes-app-inbox-scoutdetailview--scout-page--light:- hash: v1.k794b7964.506dbf875fb885f91c6bf58bfedc7e597d6513ad9a1c3d065e74716d96200fed.mpI8nafsVcoPRVDcXspuyKsZEIXq1Cb0dDtbYIRfuxw+ hash: v1.k794b7964.f454ae3221999ed68732348749e7c5f286fd43f2adec4d4ff8ff274838d2a54d.s8PQU8oE_xW92edEk-ECeT6rwiVD--sDGW6nLZREex8+ scenes-app-inbox-scoutdetailview--scout-page-narrow-run-history--dark:+ hash: v1.k794b7964.cba49833d3eb57aded98cafd76f676a6c1feb808924b19154dec6bb9f63b60e6.wZR_-jlqugAqxerahE07ZQo1GBzhlr1F-F8tpiFGRI4+ scenes-app-inbox-scoutdetailview--scout-page-narrow-run-history--light:+ hash: v1.k794b7964.29a25254c6bb076d39a3563745329967eb7bf35dc14695ac2cd2d5ed52e805c1.QfvBLsh_-oFabf0kUj4s0jU9Z6KUuTU0c8eoKawJfTEscenes-app-inbox-scoutdetailview--scout-page-no-reports--dark:- hash: v1.k794b7964.0783344b02a68556a4980a0d38d19d4690f71a7ee93a0f0e153d1e6459e977bb.pe0x-ea0w_x8Lp3secczCeswShZOwDXyZPSNYIjeCL4+ hash: v1.k794b7964.d7ed0465f710d53f6a8f71c07e6da79bcf5ca1e45a7526b193ad6ac6e3705cf2.dx3rW_FGV-cDGGL53kWhmGSVbPntqWPYcQOiiSj1_dAscenes-app-inbox-scoutdetailview--scout-page-no-reports--light:- hash: v1.k794b7964.d19235babe1cb01ad1220fa6db8859fad964d926b75ae345868de144aa67c580.VvPbd_hWIQ8wFmK-iolWBAeKY8jMA2hYumfW2Pz3jhA+ hash: v1.k794b7964.172f39eb20a2e4448e4af948054a1085fb65c04f617a397bf0897690e296e55d.mf4fGETMJgWAyXLnpASLysY9kQBxWfSyisxzWQpiG88scenes-app-inbox-scoutdetailview--scout-page-non-staff--dark:- hash: v1.k794b7964.a2ebecea102d059f7764bef59f9e2291f25414fe78a177a44675164e4abc5d92.j04rYU9j-J2Gdafk9wBtOv3Ly2Rc6Unq3nm8WIs4WtA+ hash: v1.k794b7964.58935ffa94a60443ca4d4e9fc36ae5166db3084a40b8fc27e5544fa3f67c8676.GLYQ79n6vM5vnkyA0s1HIpNyaWIxEjQrNBOu5bmUb7gscenes-app-inbox-scoutdetailview--scout-page-non-staff--light:- hash: v1.k794b7964.b326031e884274e8a06cc11b86f919a6817d5af7f559c71ffff6e145924c44a0.2nWL--TkwE632GlU_8y7cuUdpkWp24zRzwNldGTtpkc+ hash: v1.k794b7964.b02062fb06fed2b8dcf9420248e766e7eeb568eed6ae95fdbd64cd492bb7a5cb.QRExoYG5mqVAJzaTmxuySi9THVuOFVKwiQDOIxQLWNsscenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--dark:hash: v1.k794b7964.afe2203f4dd53373a3203fcfa611b5b65555341bdc2fc7fd73c15c2d83914600.O4kSRnOgICuQDkyD2HJCwBXdzE-KwsfzWT98nm43_5Ascenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--light:diff --git a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts b/products/signals/frontend/inbox/__mocks__/scoutConfigs.tsindex 63b2a0d43706..0fe33439d74e 100644--- a/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts+++ b/products/signals/frontend/inbox/__mocks__/scoutConfigs.ts@@ -109,6 +109,34 @@ export function mockScoutRuns(configs: SignalScoutConfigApi[]): SignalScoutRunSu)}+/**+ * One scout's runs a day apart, all quiet, none of them from the last two days. A folded group of+ * these carries the long date form at both ends of its header, because `humanFriendlyDetailedTime`+ * keeps the short "Today" and "Yesterday" forms for the last two days only. That is the widest+ * that header ever gets.+ */+export function mockDailyQuietRuns(config: SignalScoutConfigApi): SignalScoutRunSummaryApi[] {+ return Array.from({ length: 6 }, (_, runIndex) => {+ const startedAt = MOCK_NOW_MS - (runIndex + 2) * 24 * HOUR_MS+ return {+ run_id: `${config.skill_name}-daily-run-${runIndex}`,+ skill_name: config.skill_name,+ skill_version: 1,+ status: 'completed' as const,+ created_at: new Date(startedAt).toISOString(),+ started_at: new Date(startedAt).toISOString(),+ completed_at: new Date(startedAt + 12 * 60000).toISOString(),+ task_url: null,+ summary: 'Swept the window and found nothing worth filing.',+ emitted_count: 0,+ emitted_finding_ids: [],+ emitted_report_ids: [],+ edited_report_ids: [],+ metadata: {},+ }+ })+}+export const mockLargeScoutFleet: SignalScoutConfigApi[] = [makeMockScout({id: 'scout-error-tracking',diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsxindex cc15ed22a44c..9d6623d45f2f 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailHeader.tsx@@ -1,8 +1,8 @@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 { IconArrowLeft, IconExternal, IconRefresh } from '@posthog/icons'+import { LemonButton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'@@ -11,27 +11,15 @@ import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signalsimport { captureScoutAction } from '../../../inboxAnalytics'import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'-import { scoutCostWindowLabel } from '../../../utils/scoutCosts'-import { formatRunCost, scoutDisplayName, SCOUT_RUNS_PER_SCOUT, ScoutRollup } from '../../../utils/scoutRunsWindow'-import { ScoutStatusTag } from './ScoutBadges'-import { ScoutCadenceLabel } from './ScoutCadenceLabel'+import { scoutDisplayName, ScoutRollup } from '../../../utils/scoutRunsWindow'import { ScoutEnabledSwitch } from './ScoutConfigControls'-import { ScoutNextRunLabel } from './ScoutNextRunLabel'+import { ScoutHealthStrip } from './ScoutHealthStrip'import { LeaveScoutNoteButton } from './ScoutNotesPanel'import { ScoutOwners } from './ScoutOwners'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+ * Canonical descriptions run to a paragraph. One line 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 {@@ -39,9 +27,9 @@ function ScoutDescription({ text }: { text: string }): JSX.Element {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.+ // Measure whether the 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)@@ -49,12 +37,12 @@ function ScoutDescription({ text }: { text: string }): JSX.Element {}, [text])const paragraph = (- <p ref={ref} className={`mb-0 text-sm leading-snug text-secondary ${expanded ? '' : 'line-clamp-2'}`}>+ <p ref={ref} className={`mb-0 text-sm leading-snug text-secondary ${expanded ? '' : 'line-clamp-1'}`}>{text}</p>)- // A description that fits in two lines stays plain text — no control that changes nothing on click.+ // A description that fits on one line stays plain text — no control that changes nothing on click.if (!truncatable) {return paragraph}@@ -73,8 +61,8 @@ function ScoutDescription({ text }: { text: string }): JSX.Element {}/**- * The scout page header: what it is, the controls that act on it, and the numbers that say whether- * it is worth keeping on.+ * The scout page header: what it is, the controls that act on it, and one health strip that says+ * whether it is worth keeping on.*/export function ScoutDetailHeader({config,@@ -92,21 +80,28 @@ export function ScoutDetailHeader({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)).lengthreturn (- <div className="flex flex-col gap-3 border-b border-primary bg-surface-primary px-4 py-3">+ <div className="flex flex-col gap-2 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">{scoutDisplayName(config)}</h2>+ <h2 className="mb-0 flex min-w-0 items-baseline gap-1.5 text-lg font-semibold">+ {/* Navigation only: the scouts URL handler clears the selected scout, so+ nothing is dispatched here. */}+ <Link+ to={urls.inbox('scouts')}+ className="flex items-center gap-0.5 text-sm font-normal text-secondary"+ >+ <IconArrowLeft className="size-3.5" />+ Scouts+ </Link>+ <span className="text-sm font-normal text-muted" aria-hidden>+ /+ </span>+ <span className="min-w-0 truncate">{scoutDisplayName(config)}</span>+ </h2><LemonTag size="small" type={config.scout_origin === 'canonical' ? 'muted' : 'highlight'}>{config.scout_origin === 'canonical' ? 'Canonical' : 'Custom'}</LemonTag>- <ScoutStatusTag config={config} /><ScoutOwners config={config} /><span className="flex-1" /><Tooltip title="Dispatch a run now, outside the schedule. Counts against the project's daily run budget.">@@ -150,48 +145,11 @@ export function ScoutDetailHeader({{config.description && <ScoutDescription text={config.description} />}- <div className="flex flex-wrap rounded border border-primary">- <Metric value={<ScoutCadenceLabel config={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" />- <ScoutCostMetrics skillName={config.skill_name} />- </div>+ <ScoutHealthStrip config={config} rollup={rollup} noteCount={noteCount} learnedCount={learnedCount} /></div>)}-/**- * What the scout cost over the window, and what that buys per run and per report. Staff only, and- * absent while it has no priced run in the window, the same way the per-run tooltip omits a cost it- * cannot attribute.- */-function ScoutCostMetrics({ skillName }: { skillName: string }): JSX.Element | null {- const { scoutCostRollups } = useValues(scoutFleetLogic)- const rollup = scoutCostRollups.get(skillName)-- if (!rollup) {- return null- }-- return (- <>- <Metric- value={formatRunCost(rollup.spendUsd)}- label={`Cost · ${scoutCostWindowLabel(rollup.windowDays)}`}- />- <Metric value={formatRunCost(rollup.perRun)} label="Cost per run" />- <Metric- value={rollup.perReport === null ? 'No reports' : formatRunCost(rollup.perReport)}- label="Cost per report"- />- </>- )-}-/*** 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, sodiff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsxindex e126cb04e237..bb6db63c0fe7 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.stories.tsx@@ -6,11 +6,11 @@ import { FEATURE_FLAGS } from 'lib/constants'import { mswDecorator } from '~/mocks/browser'-import { mockScoutConfigs, mockScoutCosts, mockScoutRuns } from '../../../__mocks__/scoutConfigs'+import { mockDailyQuietRuns, mockScoutConfigs, mockScoutCosts, mockScoutRuns } from '../../../__mocks__/scoutConfigs'import { ScoutDetailView } from './ScoutDetailView'-// One scout's page. Use this to check the stat strip, including the staff-only cost tiles and the-// spend line under it.+// One scout's page. Use this to check the health strip, including the staff-only cost segment, and+// the Reports / Runs / Signals tabs below it.const SKILL_NAME = mockScoutConfigs[0].skill_name@@ -45,7 +45,7 @@ type Story = StoryObj<typeof ScoutDetailView>export const ScoutPage: Story = {}-// The same scout for a non-staff reader: no cost tiles, no spend line, and no request for either.+// The same scout for a non-staff reader: no cost segment, and no request for one.export const ScoutPageNonStaff: Story = {decorators: [mswDecorator({@@ -54,7 +54,24 @@ export const ScoutPageNonStaff: Story = {],}-// A scout that spent but filed nothing: the third tile says so rather than pricing zero reports.+// A scout that spent but filed nothing: no reports segment, and Runs leads the tabs.export const ScoutPageNoReports: Story = {args: { skillName: mockScoutConfigs[1].skill_name },}++// The folded run group at its widest, in the narrowest pane it has to survive: runs a day apart+// carry the long date form at both ends of the group header, which has to wrap rather than clip.+export const ScoutPageNarrowRunHistory: Story = {+ args: { skillName: mockScoutConfigs[1].skill_name },+ parameters: { testOptions: { viewport: { width: 375, height: 900 }, waitForLoadersToDisappear: false } },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:id/signals/scout/runs/recent-per-scout/': () => [+ 200,+ mockDailyQuietRuns(mockScoutConfigs[1]),+ ],+ },+ }),+ ],+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsxindex fd01d0484266..ccb00c2f31db 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutDetailView.tsx@@ -1,38 +1,67 @@import { useActions, useValues } from 'kea'-import { useEffect, useRef } from 'react'+import { useEffect, useRef, useState } from 'react'import { IconArrowLeft } from '@posthog/icons'-import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'+import { LemonButton, LemonSkeleton, LemonTabs } from '@posthog/lemon-ui'-import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'-import { captureScoutDetailViewed } from '../../../inboxAnalytics'-import { inboxSceneLogic } from '../../../inboxSceneLogic'+import { captureScoutAction, captureScoutDetailViewed } from '../../../inboxAnalytics'+import { inboxSceneLogic, ScoutDetailTab } from '../../../inboxSceneLogic'import { scoutDetailLogic } from '../../../logics/scoutDetailLogic'import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'import { scoutNotesLogic } from '../../../logics/scoutNotesLogic'import { entriesForSkill, scratchpadLogic } from '../../../logics/scratchpadLogic'-import { ScoutCostRollup, scoutCostWindowLabel } from '../../../utils/scoutCosts'-import { formatRunCost, SCOUT_NO_RECENT_RUNS, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'-import { ScoutDetailHeader, ScoutAttentionBanner } from './ScoutDetailHeader'+import { ScoutRunFilter, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'+import { ScoutAttentionBanner, ScoutDetailHeader } from './ScoutDetailHeader'import { ScoutEmissionCard } from './ScoutEmissionCard'import { ScoutLearnedPanel } from './ScoutLearnedPanel'-import { ScoutNotesPanel } from './ScoutNotesPanel'+import { LeaveScoutNoteButton, ScoutNotesPanel } from './ScoutNotesPanel'import { ScoutReportCard } from './ScoutReportCard'-import { ScoutRunHistorySection } from './ScoutRunHistorySection'+import { ScoutRunFilterPills, ScoutRunHistorySection } from './ScoutRunHistorySection'++/** The two panes that sit in the right rail at full width, and join the main tab bar below it. */+const RAIL_TABS: ScoutDetailTab[] = ['told', 'learned']++function isRailTab(tab: ScoutDetailTab): boolean {+ return RAIL_TABS.includes(tab)+}/**- * 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.+ * One scout's page, at `/inbox/scouts/:skillName`. The header says whether the scout is worth+ * keeping on; tabs below it hold what it produced (Reports, Runs, Signals) and what it carries+ * (Told, Learned). Configuration lives behind the header's settings modal — this page is for+ * reading the scout, not adjusting it.+ *+ * Tabs rather than stacked sections because the sections restated each other's numbers and an+ * uncapped report list pushed the run history — the reason most people open the page — off the+ * first screen.*/export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Element {const { scoutConfigs, scoutConfigsLoading, rollups } = useValues(scoutFleetLogic)const { startRunsPolling, stopRunsPolling, loadScoutConfigs } = useActions(scoutFleetLogic)const { entries } = useValues(scratchpadLogic)const { scoutNotes } = useValues(scoutNotesLogic({ skillName }))+ const { touchedReports, emissionRows, scoutRunsLoadedOnce } = useValues(scoutDetailLogic({ skillName }))+ const { scoutDetailTab } = useValues(inboxSceneLogic)+ const { setScoutDetailTab } = useActions(inboxSceneLogic)+ const [runFilter, setRunFilter] = useState<ScoutRunFilter>('all')+ // Above the breakpoint both tab bars are on screen, so a click in one has to leave the other+ // where it was. The URL has room for one pane, the one the last click opened, so each column+ // also keeps its own last pane here. Following the URL rather than the click keeps these right+ // through a Back press, which moves the pane without going through the bar.+ const [mainColumnTab, setMainColumnTab] = useState<ScoutDetailTab | null>(null)+ const [railColumnTab, setRailColumnTab] = useState<ScoutDetailTab>('told')+ useEffect(() => {+ if (!scoutDetailTab) {+ return+ }+ if (isRailTab(scoutDetailTab)) {+ setRailColumnTab(scoutDetailTab)+ } else {+ setMainColumnTab(scoutDetailTab)+ }+ }, [scoutDetailTab])// 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@@ -44,6 +73,13 @@ export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Elemeconst config = scoutConfigs?.find((c) => c.skill_name === skillName) ?? nullconst rollup = rollups.get(skillName)+ const learnedCount = entriesForSkill(entries, skillName).length+ const reportCount = touchedReports.length+ // Reports leads for a scout that files them, because that is what the scout is for; Runs leads+ // for the rest. Held until the runs window settles, so the default doesn't move under a reader+ // a beat after the page opens.+ const defaultMainTab: ScoutDetailTab = !scoutRunsLoadedOnce || reportCount > 0 ? 'reports' : 'runs'+ const tab = scoutDetailTab ?? defaultMainTab// Once per scout opened, as soon as its config resolves — the run rollup fills in a beat later// off the polled window, so the counts are whatever had loaded by then.@@ -65,6 +101,24 @@ export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Eleme})}, [skillName, config, rollup])+ // A scout that files nothing opens Runs with no click, so counting switch_detail_tab alone+ // would miss the pane most readers land on. Held until the runs window settles, because the+ // default reads Reports until then. Same property key as the switch, so one breakdown covers+ // both ways of arriving at a pane.+ const openTabCapturedForRef = useRef<string | null>(null)+ useEffect(() => {+ if (!config || !scoutRunsLoadedOnce || openTabCapturedForRef.current === skillName) {+ return+ }+ openTabCapturedForRef.current = skillName+ captureScoutAction({+ actionType: 'open_detail_tab',+ surface: 'scout_detail',+ skillName,+ extra: { filter: tab },+ })+ }, [skillName, config, scoutRunsLoadedOnce, tab])+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@@ -106,29 +160,136 @@ export function ScoutDetailView({ skillName }: { skillName: string }): JSX.Eleme)}+ const signalCount = emissionRows.length+ const runCount = rollup?.runs.length ?? 0+ const windowEmittedCount = rollup?.emittedCount ?? 0+ const mainTab = isRailTab(tab) ? (mainColumnTab ?? defaultMainTab) : tab+ const railTab = isRailTab(tab) ? tab : railColumnTab++ const switchTab = (next: ScoutDetailTab): void => {+ captureScoutAction({+ actionType: 'switch_detail_tab',+ surface: 'scout_detail',+ skillName,+ extra: { filter: next },+ })+ setScoutDetailTab(next)+ }++ // Reports and Signals hide once the window has settled and says the scout has none of them —+ // the same rule the stacked sections used, now applied to the tab rather than the section.+ // Signals asks the runs window, not the emissions fetched per run: those land a beat later and+ // can fail outright, and hiding the tab then would say the scout emitted nothing while its+ // panel is the only place that reports the failed fetch. Whichever pane is open also keeps its+ // tab, so a link naming a pane this scout has none of still has a tab to select.+ const mainTabs = [+ (!scoutRunsLoadedOnce || reportCount > 0 || mainTab === 'reports') && {+ key: 'reports' as ScoutDetailTab,+ label: `Reports ${reportCount}`,+ },+ { key: 'runs' as ScoutDetailTab, label: `Runs ${runCount}` },+ (!scoutRunsLoadedOnce || windowEmittedCount > 0 || mainTab === 'signals') && {+ key: 'signals' as ScoutDetailTab,+ // The window's count stands in until the rows land, so a failed fetch is not labelled+ // zero beside a panel that says the fetch failed.+ label: `Signals ${signalCount > 0 ? signalCount : windowEmittedCount}`,+ },+ ]+ const railTabs = [+ { key: 'told' as ScoutDetailTab, label: `Told ${scoutNotes.length}` },+ { key: 'learned' as ScoutDetailTab, label: `Learned ${learnedCount}` },+ ]++ const mainPanel = (which: ScoutDetailTab): JSX.Element =>+ which === 'runs' ? (+ <ScoutRunHistorySection skillName={skillName} filter={runFilter} />+ ) : which === 'signals' ? (+ <ScoutSignalsPanel skillName={skillName} />+ ) : (+ <ScoutReportsPanel skillName={skillName} />+ )++ const railPanel = (which: ScoutDetailTab): JSX.Element =>+ which === 'learned' ? <ScoutLearnedPanel skillName={skillName} /> : <ScoutNotesPanel skillName={skillName} />+return (- <div className="flex min-h-0 flex-1 flex-col overflow-auto">- <div className="flex px-4 pt-3">- <BackToScouts />- </div>+ <div className="@container flex min-h-0 flex-1 flex-col overflow-auto"><ScoutDetailHeaderconfig={config}rollup={rollup}noteCount={scoutNotes.length}- learnedCount={entriesForSkill(entries, skillName).length}+ learnedCount={learnedCount}/>- <div className="grid grid-cols-1 items-start gap-4 px-4 py-4 xl:grid-cols-[minmax(0,1fr)_20rem]">+ <div className="grid grid-cols-1 items-start gap-4 px-4 py-4 @4xl: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} />++ {/* Two tab bars for the same state: below the breakpoint the rail's panes have+ nowhere to sit, so they join this bar rather than stacking under the run+ list where nobody scrolls to them. */}+ <div className="flex flex-col gap-1 @4xl:hidden">+ <LemonTabs+ activeKey={tab}+ onChange={switchTab}+ size="small"+ tabs={[...mainTabs, ...railTabs]}+ />+ {/* The open pane's control gets its own row here rather than the bar's+ right slot. This bar carries five tabs, and the slot does not shrink:+ it pins over the tab strip and hides the rail tabs behind it. The note+ button is repeated from the rail bar because the rail column itself is+ not rendered at this width, which would leave the pane unwritable. */}+ {tab === 'runs' && (+ <ScoutRunFilterPills skillName={skillName} filter={runFilter} onChange={setRunFilter} />+ )}+ {tab === 'told' && (+ <div className="flex">+ <LeaveScoutNoteButton skillName={skillName} size="xsmall" />+ </div>+ )}+ </div>+ <div className="hidden @4xl:block">+ <LemonTabs+ activeKey={mainTab}+ onChange={switchTab}+ size="small"+ tabs={mainTabs}+ rightSlot={+ mainTab === 'runs' ? (+ <ScoutRunFilterPills+ skillName={skillName}+ filter={runFilter}+ onChange={setRunFilter}+ />+ ) : undefined+ }+ />+ </div>++ {isRailTab(tab) ? (+ <>+ <div className="@4xl:hidden">{railPanel(tab)}</div>+ <div className="hidden @4xl:block">{mainPanel(mainTab)}</div>+ </>+ ) : (+ mainPanel(tab)+ )}</div>- <div className="flex min-w-0 flex-col gap-4">- <ScoutNotesPanel skillName={skillName} />- <ScoutLearnedPanel skillName={skillName} />++ <div className="hidden min-w-0 flex-col gap-4 @4xl:flex">+ <LemonTabs+ activeKey={railTab}+ onChange={switchTab}+ size="small"+ tabs={railTabs}+ rightSlot={+ railTab === 'told' ? (+ <LeaveScoutNoteButton skillName={skillName} size="xsmall" />+ ) : undefined+ }+ />+ {railPanel(railTab)}</div></div></div>@@ -144,159 +305,129 @@ function BackToScouts(): JSX.Element {)}-/** 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, scoutCostRollups } = useValues(scoutFleetLogic)- const rollup = rollups.get(skillName)- const costRollup = scoutCostRollups.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>- {costRollup && <span className="text-sm text-secondary tabular-nums">{scoutSpendSummary(costRollup)}</span>}- </div>- )-}--/**- * What the scout spent over the cost window and what it produced for it, e.g.- * "$1.68 across 14 priced runs · 11 reports filed or added to · $0.15 per report". Staff only, and- * on its own line because it describes the cost window rather than the run window above it.- *- * The count is the priced runs rather than every run started, because it is the divisor behind the- * "Cost per run" tile. It keeps the qualifier so it does not read as the activity count that the- * run summary above states over its own window.- */-function scoutSpendSummary(rollup: ScoutCostRollup): string {- return [- `${formatRunCost(rollup.spendUsd)} across ${pluralize(rollup.pricedRunCount, 'priced run')} in the ${scoutCostWindowLabel(rollup.windowDays)}`,- rollup.reportsTouched > 0- ? `${pluralize(rollup.reportsTouched, 'report')} filed or added to`- : 'no reports filed or added to',- ...(rollup.perReport === null ? [] : [`${formatRunCost(rollup.perReport)} per report`]),- ].join(' · ')-}-/**- * The Reports section: the inbox reports this scout authored or edited directly via the report- * channel (`emit_report` / `edit_report`) in the recent window, newest-updated first. Distinct from- * the Signals section, which lists weak `emit_signal` findings. Hidden entirely for the common scout- * that never authors a report, so it only appears for report-channel scouts.+ * The Reports tab: the inbox reports this scout authored or edited directly via the report channel+ * (`emit_report` / `edit_report`) in the recent window, newest-updated first. The list is never+ * trimmed for length, because the tab keeps it from pushing anything away, but the per-id fetch+ * behind it is capped, so the panel says how many of the tab's count it is holding.*/-function ScoutReportsSection({ skillName }: { skillName: string }): JSX.Element | null {+function ScoutReportsPanel({ skillName }: { skillName: string }): JSX.Element {const { reportRows, touchedReports, scoutReportsLoading, scoutRunsLoadedOnce } = useValues(scoutDetailLogic({ skillName }))+ const { loadScoutReports } = useActions(scoutDetailLogic({ skillName }))- // Most scouts never author a report — keep the section out entirely rather than show an empty box.- if (touchedReports.length === 0) {- return null+ if (!scoutRunsLoadedOnce || (scoutReportsLoading && reportRows.length === 0)) {+ return <LemonSkeleton className="h-12 w-full rounded" />}- const loading = !scoutRunsLoadedOnce || (scoutReportsLoading && reportRows.length === 0)- const editedAny = reportRows.some(({ action }) => action === 'edited')+ if (reportRows.length === 0) {+ // The runs name the reports, and a separate fetch resolves each one by id. When the runs+ // name some and none resolve, the reports were deleted or the fetch failed, so an empty+ // state would deny the count the tab above it is showing. Nothing refetches on its own+ // here: the touched set is unchanged, so its subscription doesn't fire again.+ if (touchedReports.length > 0) {+ 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 reports this scout filed or added to. They may have been deleted, or the+ request failed.+ </span>+ <LemonButton type="secondary" size="small" status="danger" onClick={() => loadScoutReports()}>+ Retry+ </LemonButton>+ </div>+ )+ }+ return (+ <div className="rounded border border-dashed border-primary bg-surface-primary px-4 py-6 text-center text-sm text-muted">+ {`No reports filed or added to in the ${SCOUT_RUNS_PER_SCOUT_LABEL}.`}+ </div>+ )+ }return (<div className="flex flex-col gap-2">- <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-surface-primary px-4 py-6 text-center text-sm text-muted">- Couldn’t load the reports this scout authored.- </div>- ) : (- reportRows.map(({ report, action }) => (- <ScoutReportCard key={report.id} report={report} action={action} />- ))+ {/* The tab counts every report the runs name, while this list holds the ones a bounded+ by-id fetch resolved. Say so when they differ, rather than leaving the reader to+ count the cards against the tab. */}+ {!scoutReportsLoading && reportRows.length < touchedReports.length && (+ <span className="text-xs text-muted">+ {`Showing ${reportRows.length} of ${touchedReports.length} reports.`}+ </span>)}+ {reportRows.map(({ report, action }) => (+ <ScoutReportCard key={report.id} report={report} action={action} />+ ))}</div>)}/**- * The Signals section: every finding this scout emitted in the recent window, newest first.- * Emissions are fetched per emitted run by `scoutDetailLogic` (keyed by skill) off the fleet's- * already-polled runs window. Most runs are quiet — and scouts are moving to the report channel —- * so the section is hidden entirely when nothing emitted, rather than showing an empty box.+ * The Signals tab: every finding this scout emitted in the recent window, newest first. Emissions+ * are fetched per emitted run by `scoutDetailLogic` (keyed by skill) off the fleet's already-polled+ * runs window.*/-function ScoutSignalsSection({ skillName }: { skillName: string }): JSX.Element | null {- const { emissionRows, emissionsLoading, emissionsLoadFailed, emittedRuns, scoutRunsLoadedOnce } = useValues(+function ScoutSignalsPanel({ skillName }: { skillName: string }): JSX.Element {+ const { emissionRows, emissionsLoading, emissionsLoadFailed, scoutRunsLoadedOnce } = useValues(scoutDetailLogic({ skillName }))+ const { loadEmissions } = useActions(scoutDetailLogic({ skillName }))const { selectedScoutFindingId } = useValues(inboxSceneLogic)- // No run in this scout's window emitted anything — keep the section out entirely rather than show an- // empty box (mirrors the Reports section above). Only once the runs window has settled, though:- // before that, `emittedRuns` is empty by default and hiding would skip the loading skeleton- // for scouts that do have signals.- if (scoutRunsLoadedOnce && emittedRuns.length === 0) {- return null- }-// "Loading" until the fleet's per-scout runs have settled once AND this scout's emissions have// resolved — otherwise a fresh deep-link would flash the empty state before we know the- // emitted runs. Gating on the fleet's first-load flag (not its per-poll loading) keeps the- // quiet-scout empty state from flickering to a skeleton every 60s poll.- const loading = !scoutRunsLoadedOnce || emissionsLoading+ // emitted runs.const hasRows = emissionRows.length > 0- // The unique emission the deep-link resolves to: the newest row whose finding matches.+ if ((!scoutRunsLoadedOnce || emissionsLoading) && !hasRows) {+ return <LemonSkeleton className="h-12 w-full rounded" />+ }++ if (!hasRows) {+ // Every per-run emissions fetch failed while the rollup says these runs emitted, so don't+ // claim "no signals". Nothing comes back on its own: the emitted runs are unchanged, so the+ // key their subscription watches holds, and the runs poll refetches only the report links.+ if (emissionsLoadFailed) {+ return (+ <div className="flex flex-col items-center gap-2 rounded border border-dashed border-primary bg-surface-primary px-4 py-6 text-center text-sm text-muted">+ <span>Couldn't load signals for this scout.</span>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => loadEmissions()}+ loading={emissionsLoading}+ >+ Retry+ </LemonButton>+ </div>+ )+ }+ return (+ <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>+ )+ }++ // `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.const deepLinkedEmissionId = selectedScoutFindingId? (emissionRows.find(({ emission }) => emission.finding_id === selectedScoutFindingId)?.emission.id ?? null): nullreturn (<div className="flex flex-col gap-2">- <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-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-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}+ isDeepLinked={emission.id === deepLinkedEmissionId}+ />+ ))}</div>)}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsxnew file mode 100644index 000000000000..f99bb29c359b--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx@@ -0,0 +1,142 @@+import { useValues } from 'kea'++import { Tooltip } from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'+import { teamLogic } from 'scenes/teamLogic'++import type { SignalScoutConfigApi as SignalScoutConfig } from 'products/signals/frontend/generated/api.schemas'++import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'+import { scoutCostLineParts, scoutCostWindowLabel } from '../../../utils/scoutCosts'+import { nextRunAt, SCOUT_GROUP_LABEL, ScoutGroupKey, scoutGroup } from '../../../utils/scoutGroups'+import { filedOrAddedLabel, ScoutRollup, SCOUT_RUNS_PER_SCOUT_LABEL } from '../../../utils/scoutRunsWindow'+import { ScoutStatusTag } from './ScoutBadges'+import { ScoutCadenceLabel } from './ScoutCadenceLabel'+import { ScoutNextRunLabel } from './ScoutNextRunLabel'+import { ScoutRunBoxes } from './ScoutRunBoxes'+import { ScoutStatusDot } from './ScoutStatusDot'++/**+ * One labelled group of the strip. The window each group describes is not the same — run counts+ * cover the last 25 runs, cost covers the last 7 days — so each carries the definition its tile+ * label used to carry, as a tooltip.+ */+function Segment({ tooltip, children }: { tooltip: string; children: React.ReactNode }): JSX.Element {+ return (+ <Tooltip title={tooltip}>+ <div className="flex min-w-0 items-center gap-1.5 border-r border-primary pr-3 last:border-r-0 last:pr-0">+ {children}+ </div>+ </Tooltip>+ )+}++/** The groups `ScoutStatusTag` cannot tell apart: it reads "On patrol" for each of them. */+const TAG_SILENT_GROUPS: ScoutGroupKey[] = ['working', 'watching', 'settling_in']++/**+ * Whether a scout is worth keeping on, in one wrapping row: where it stands, how its recent runs+ * went, what it filed, what it cost, and how much steering it carries.+ *+ * This replaces a grid of equal-weight tiles plus a prose summary that restated them. The two could+ * disagree, and the failed-run count — the thing a reader opens this page for — only appeared in the+ * prose. Here it sits next to the run strip, in the same vocabulary the roster uses.+ */+export function ScoutHealthStrip({+ config,+ rollup,+ noteCount,+ learnedCount,+}: {+ config: SignalScoutConfig+ rollup: ScoutRollup | undefined+ noteCount: number+ learnedCount: number+}): JSX.Element {+ const { scoutRunCosts, scoutCostRollups, expensiveRunCostThreshold, scoutRunsLoadedOnce } =+ useValues(scoutFleetLogic)+ const { currentTeam } = useValues(teamLogic)+ const now = new Date()++ const runs = rollup?.runs ?? []+ const failed = rollup?.failedCount ?? 0+ const costRollup = scoutCostRollups.get(config.skill_name)+ // Shared with the run rows, so the strip cannot word the same report activity differently.+ const reportLabel = filedOrAddedLabel(rollup?.authoredReportIds ?? [], rollup?.editedReportIds ?? [])+ // Only an enabled scout has a next run; a paused one would otherwise carry an empty dash.+ const hasNextRun = nextRunAt(config, currentTeam?.timezone ?? 'UTC', now) !== null+ const group = scoutRunsLoadedOnce ? scoutGroup(config, rollup, now) : null++ return (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 text-xs text-secondary">+ <Segment tooltip="Where this scout stands, and when it next runs.">+ {/* The dot's group is read off the run window, so an unloaded rollup would show a+ scout that files plenty as "nothing worth filing", and it would keep saying so+ for as long as the runs request fails. The tag beside it is config-only, so it+ stays right either way. */}+ {group && (+ <>+ <ScoutStatusDot group={group} />+ {/* Named in text, not colour alone: a reader would otherwise have to hover+ an 8px dot to tell a producing scout from a quiet or a brand-new one.+ The roster pairs the dot with this same label. */}+ {TAG_SILENT_GROUPS.includes(group) && (+ <span className="whitespace-nowrap">{SCOUT_GROUP_LABEL[group]}</span>+ )}+ </>+ )}+ <ScoutStatusTag config={config} />+ <ScoutCadenceLabel config={config} />+ {hasNextRun && (+ <span className="tabular-nums">+ · next run <ScoutNextRunLabel config={config} />+ </span>+ )}+ </Segment>++ <Segment tooltip={`Runs this scout made in the ${SCOUT_RUNS_PER_SCOUT_LABEL}, quiet ones included.`}>+ {runs.length > 0 ? (+ <>+ <ScoutRunBoxes runs={runs} costs={scoutRunCosts} costThreshold={expensiveRunCostThreshold} />+ <span className="whitespace-nowrap tabular-nums">{pluralize(runs.length, 'run')}</span>+ {/* The counts here and below change while the page is open, so each number+ gets its own element — see "Rule 7" in frontend/src/AGENTS.md for what a+ translated page does to a bare text node that has siblings. */}+ {failed > 0 && (+ <span className="whitespace-nowrap text-danger">+ · <span translate="no">{failed}</span> failed+ </span>+ )}+ </>+ ) : (+ // 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.+ <span className="text-muted">{scoutRunsLoadedOnce ? 'No runs yet' : '…'}</span>+ )}+ </Segment>++ {reportLabel && (+ <Segment+ tooltip={`Inbox reports this scout filed or added to in the ${SCOUT_RUNS_PER_SCOUT_LABEL}. A report it filed and later edited counts once, as filed.`}+ >+ <span className="whitespace-nowrap tabular-nums">{reportLabel}</span>+ </Segment>+ )}++ {costRollup && (+ <Segment+ tooltip={`What this scout spent on model calls in the ${scoutCostWindowLabel(costRollup.windowDays)}, and what that buys per run and per report.`}+ >+ <span className="whitespace-nowrap tabular-nums">{scoutCostLineParts(costRollup).join(' · ')}</span>+ </Segment>+ )}++ <Segment tooltip="Notes the team has left this scout, and entries it has written for itself.">+ <span className="whitespace-nowrap tabular-nums">+ <span translate="no">{noteCount}</span> told · <span translate="no">{learnedCount}</span> learned+ </span>+ </Segment>+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutLearnedPanel.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutLearnedPanel.tsxindex a0e71a9c2ad0..af586603627c 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutLearnedPanel.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutLearnedPanel.tsx@@ -16,64 +16,57 @@ const INITIAL_VISIBLE = 3* 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 {+export function ScoutLearnedPanel({ skillName }: { skillName: string }): JSX.Element {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>- )+ return <LemonSkeleton className="h-16 w-full rounded" />}- // A failed load is not an empty memory: say so, rather than silently dropping the panel.+ // A failed load is not an empty memory: say so, rather than silently showing nothing.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 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>)}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>+ {scoutEntries.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. Scouts write here when they settle on a baseline or rule something out.+ </div>+ ) : (+ <>+ {visible.map((entry) => (+ <ScratchpadEntryCard key={entry.key} entry={entry} titled />+ ))}+ {scoutEntries.length > visible.length && (+ <LemonButton+ size="xsmall"+ type="tertiary"+ className="self-start"+ onClick={() => setShowAll(true)}+ >+ Show all {pluralize(scoutEntries.length, 'entry', 'entries')}+ </LemonButton>+ )}+ </>)}+ <LemonButton size="xsmall" type="tertiary" className="self-start" onClick={() => setScratchpadOpen(true)}>+ All scouts+ </LemonButton></div>)}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsxindex 6245cf22df44..d123202acddd 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx@@ -12,12 +12,14 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import type { ScoutNoteApi } from 'products/signals/frontend/generated/api.schemas'+import { scoutDetailLogic } from '../../../logics/scoutDetailLogic'import {isDirectScoutNote,NOTES_FETCH_LIMIT,scoutNoteOriginLabel,scoutNotesLogic,} from '../../../logics/scoutNotesLogic'+import { linkReportIdsInNote } from '../../../utils/scoutMemoryPresentation'import { ScoutNoteContent } from './ScoutNoteContent'/** Bounded by the create serializer; mirrored here so the dialog can say so before a failed request. */@@ -139,19 +141,16 @@ export function ScoutNotesPanel({ skillName }: { skillName: string }): JSX.Elemeconst logic = scoutNotesLogic({ skillName })const { scoutNotes, fleetWideNotes, notesLoading, notesLoadFailed, notesCapped } = useValues(logic)const { deleteNote, loadNotes } = useActions(logic)+ const { reportRows } = useValues(scoutDetailLogic({ skillName }))const [showAll, setShowAll] = useState(false)const visible = showAll ? scoutNotes : scoutNotes.slice(0, 4)const otherFleetNotes = skillName ? fleetWideNotes.filter((note) => !scoutNotes.includes(note)) : []+ // Reports this scout touched in the window, so a note naming one by id can name it by title.+ const reportsById = new Map(reportRows.map(({ report }) => [report.id.toLowerCase(), report]))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…@@ -171,7 +170,14 @@ export function ScoutNotesPanel({ skillName }: { skillName: string }): JSX.Eleme) : (<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)} />+ <ScoutNoteRow+ key={note.id}+ note={note}+ content={linkReportIdsInNote(note.content, reportsById, {+ truncateUnmatched: !isDirectScoutNote(note),+ })}+ onDelete={() => deleteNote(note.id)}+ />))}{scoutNotes.length > visible.length && (<div className="border-t border-primary px-3 py-2">@@ -198,7 +204,15 @@ export function ScoutNotesPanel({ skillName }: { skillName: string }): JSX.Eleme)}-function ScoutNoteRow({ note, onDelete }: { note: ScoutNoteApi; onDelete: () => void }): JSX.Element {+function ScoutNoteRow({+ note,+ content,+ onDelete,+}: {+ note: ScoutNoteApi+ content: string+ onDelete: () => void+}): JSX.Element {const direct = isDirectScoutNote(note)const disabledReason = noteWriteDisabledReason()@@ -222,7 +236,7 @@ function ScoutNoteRow({ note, onDelete }: { note: ScoutNoteApi; onDelete: () =></Tooltip>)}</div>- <ScoutNoteContent content={note.content} />+ <ScoutNoteContent content={content} /></div>{/* Only a note someone left here is retired here. A derived one is a record of whathappened in the inbox, and deleting it would rewrite that. */}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsxindex e38884787724..1e6db98be652 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunHistorySection.tsx@@ -14,21 +14,27 @@ import { SignalScoutRunSummary } from '../../../types'import {deriveRunFailureKind,formatRunDuration,+ groupScoutRuns,normalizeRunStatus,runDurationSeconds,runMatchesFilter,runProducedOutput,runReportActivity,ScoutRunFilter,- scoutReportActivityLabel,+ ScoutRunGroup,+ scoutRunFailureLine,+ scoutRunGroupKey,+ scoutRunReportLabel,SCOUT_NO_RECENT_RUNS,SCOUT_RUNS_PER_SCOUT_LABEL,} from '../../../utils/scoutRunsWindow'import { ScoutTimestamp } from './ScoutTimestamp'+// This pill matches any run that produced output, either a signal finding or report activity, so its+// label names neither channel. Each row names the channel its own run used.const FILTERS: { value: ScoutRunFilter; label: string }[] = [{ value: 'all', label: 'All' },- { value: 'emitted', label: 'Emitted' },+ { value: 'emitted', label: 'Found something' },{ value: 'quiet', label: 'Quiet' },{ value: 'failed', label: 'Failed' },]@@ -63,9 +69,159 @@ function RunGlyph({ run }: { run: SignalScoutRunSummary }): JSX.Element {return <span className="text-muted text-sm leading-none">·</span>}+/** Chevron that points down when open, right when shut. Shared by run rows and folded groups. */+function ExpandChevron({ expanded }: { expanded: boolean }): JSX.Element {+ return (+ <IconChevronDown+ className={`size-4 shrink-0 text-muted transition-transform ${expanded ? '' : '-rotate-90'}`}+ />+ )+}++/** The times a folded group spans: one timestamp for a lone run, first-to-last for several. */+function GroupTimeSpan({ runs }: { runs: SignalScoutRunSummary[] }): JSX.Element | null {+ // Rows are newest first, so the group's last entry is its earliest run.+ const newest = runs[0]?.started_at+ const oldest = runs[runs.length - 1]?.started_at+ if (!newest) {+ return null+ }+ if (!oldest || oldest === newest) {+ return <ScoutTimestamp time={newest} />+ }+ return (+ <span className="flex flex-wrap items-center gap-x-1">+ <ScoutTimestamp time={oldest} />+ <span className="text-[11px] text-muted">to</span>+ <ScoutTimestamp time={newest} />+ </span>+ )+}++/**+ * What a run produced: its findings if it emitted any, otherwise its report activity. A run can+ * file a report and then fail, so this is shown for a failed run too.+ */+function RunOutputTag({ run }: { run: SignalScoutRunSummary }): JSX.Element | null {+ const emitted = run.emitted_count ?? 0+ if (emitted > 0) {+ return (+ <LemonTag type="highlight" size="small">+ {pluralize(emitted, 'signal')} emitted+ </LemonTag>+ )+ }+ const reportLabel = scoutRunReportLabel(run)+ return reportLabel ? (+ <LemonTag type="highlight" size="small">+ {reportLabel}+ </LemonTag>+ ) : null+}++/** Records that a folded group was opened, so we can see whether the folded rows get read. */+function captureExpandRunGroup(skillName: string, kind: 'quiet' | 'failed', size: number): void {+ captureScoutAction({+ actionType: 'expand_run_group',+ surface: 'scout_detail',+ skillName,+ extra: { group_kind: kind, group_size: size },+ })+}++/**+ * Consecutive runs that found nothing, folded into one line: how many, when, and that no report+ * changed. A scout's history is mostly quiet, so a flat list spends its first screen on runs that+ * found nothing. Expanding restores the individual rows. A lone quiet run keeps the same one-line+ * shape, so the list does not switch grammar for a group of one.+ */+function QuietRunGroup({ runs, skillName }: { runs: SignalScoutRunSummary[]; skillName: string }): JSX.Element {+ const [expanded, setExpanded] = useState(false)++ return (+ <div className="flex flex-col border-b border-primary last:border-b-0">+ <button+ type="button"+ onClick={() => {+ if (!expanded) {+ captureExpandRunGroup(skillName, 'quiet', runs.length)+ }+ setExpanded((value) => !value)+ }}+ className="flex flex-wrap items-center gap-x-2 gap-y-0.5 px-3 py-2 text-left transition-colors hover:bg-surface-secondary"+ aria-expanded={expanded}+ >+ <ExpandChevron expanded={expanded} />+ <span className="text-muted text-sm leading-none">·</span>+ <span className="whitespace-nowrap text-[11px] text-muted">+ {runs.length === 1 ? '1 quiet run' : `${runs.length} quiet runs`}+ </span>+ <GroupTimeSpan runs={runs} />+ <span className="flex-1" />+ <span className="whitespace-nowrap text-[11px] text-muted">no report changed</span>+ </button>+ {expanded && runs.map((run) => <ScoutRunRow key={run.run_id} run={run} skillName={skillName} />)}+ </div>+ )+}++/**+ * Consecutive failures, folded into one danger-tinted group: the count and time span, then one line+ * per run with its time, whether it merely ran out of time, what it managed to say, and its own+ * task-run link. Failures are what a reader opens this list for, so they stay readable without+ * expanding anything.+ */+function FailedRunGroup({ runs, skillName }: { runs: SignalScoutRunSummary[]; skillName: string }): JSX.Element {+ const now = new Date()++ return (+ <div className="flex flex-col border-b border-primary bg-danger-highlight last:border-b-0">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 px-3 py-2">+ <span className="text-danger text-sm font-medium leading-none">✗</span>+ <span className="whitespace-nowrap text-[11px] font-medium text-danger">+ {runs.length === 1 ? '1 run failed' : `${runs.length} runs failed`}+ </span>+ <GroupTimeSpan runs={runs} />+ </div>+ {runs.map((run) => (+ <div+ key={run.run_id}+ className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5 px-3 pb-2 pl-9 text-[13px] leading-snug"+ >+ <ScoutTimestamp time={run.started_at} />+ {/* A run that only hit its deadline is marked, in the colour an unfolded row+ gives it. An error carries no mark: the group header already says failed,+ in the same red a row would use. */}+ {deriveRunFailureKind(run, now) === 'timed_out' && (+ <span className="whitespace-nowrap text-[11px] text-warning">· timed out</span>+ )}+ <span className="min-w-0 flex-1 text-secondary">{scoutRunFailureLine(run, now)}</span>+ <RunOutputTag run={run} />+ {run.task_url && (+ <Link+ to={run.task_url}+ className="flex shrink-0 items-center gap-1 text-xs font-medium"+ onClick={() =>+ captureScoutAction({+ actionType: 'open_task_run',+ surface: 'scout_detail',+ skillName,+ extra: { run_id: run.run_id, run_status: 'failed' },+ })+ }+ >+ Open task run <IconExternal className="size-3" />+ </Link>+ )}+ </div>+ ))}+ </div>+ )+}+/*** One run in the history list. Shares the collapse/expand grammar of `ScoutEmissionCard`: a header- * (chevron · glyph · timestamp · duration · failure · emitted count) that stays visible, the run+ * (chevron · glyph · timestamp · duration · failure · report activity) that stays visible, the run* summary markdown (2-line preview collapsed, full expanded), and an id/task-run footer when open.** Memoized because the 60s runs-window poll re-renders the whole history list; `loadRunsWindow`@@ -84,7 +240,6 @@ const ScoutRunRow = memo(function ScoutRunRow({const failureKind = deriveRunFailureKind(run, now)const duration = formatRunDuration(runDurationSeconds(run, now))const emitted = run.emitted_count ?? 0- const reportActivityLabel = scoutReportActivityLabel(run)const { authored: authoredReportIds, edited: editedReportIds } = runReportActivity(run)const hasBody = Boolean(run.summary) || status === 'failed' || expanded@@ -104,27 +259,23 @@ const ScoutRunRow = memo(function ScoutRunRow({className="flex items-center gap-2 px-3 py-2.5 text-left transition-colors hover:bg-surface-secondary"aria-expanded={expanded}>- <IconChevronDown- className={`size-4 shrink-0 text-muted transition-transform ${expanded ? '' : '-rotate-90'}`}- />+ <ExpandChevron expanded={expanded} /><RunGlyph run={run} /><ScoutTimestamp time={run.started_at} />{duration && <span className="whitespace-nowrap text-[11px] text-muted">· {duration}</span>}+ {/* One colour per failure kind, matching the glyph — a red glyph next to amber text+ read as two different states of the same run. */}{failureKind && (- <span className="whitespace-nowrap text-[11px] text-warning">+ <span+ className={`whitespace-nowrap text-[11px] ${+ failureKind === 'timed_out' ? 'text-warning' : 'text-danger'+ }`}+ >· {failureKind === 'timed_out' ? 'timed out' : 'failed'}</span>)}<span className="flex-1" />- {emitted > 0 ? (- <LemonTag type="highlight" size="small">- {pluralize(emitted, 'signal')} emitted- </LemonTag>- ) : reportActivityLabel ? (- <LemonTag type="highlight" size="small">- {reportActivityLabel}- </LemonTag>- ) : null}+ <RunOutputTag run={run} /></button>{hasBody && (@@ -157,7 +308,7 @@ const ScoutRunRow = memo(function ScoutRunRow({className="flex items-center gap-1 font-medium shrink-0"onClick={() => captureOpenLinkedReport(skillName, reportId, 'authored')}>- Authored report <IconArrowRight className="size-3" />+ Filed report <IconArrowRight className="size-3" /></Link>))}{editedReportIds.map((reportId) => (@@ -167,7 +318,7 @@ const ScoutRunRow = memo(function ScoutRunRow({className="flex items-center gap-1 font-medium shrink-0"onClick={() => captureOpenLinkedReport(skillName, reportId, 'edited')}>- Edited report <IconArrowRight className="size-3" />+ Added to report <IconArrowRight className="size-3" /></Link>))}{run.task_url && (@@ -197,22 +348,31 @@ const ScoutRunRow = memo(function ScoutRunRow({)})-/**- * The Runs section on the scout detail surface: this scout's runs in the recent window, newest- * first, with All/Emitted/Quiet/Failed filter chips (each showing its match count). Runs come- * from `scoutFleetLogic`'s already-polled per-scout rollup (oldest-first timeline order, reversed- * here); the filter chips narrow that set client-side.- */-export function ScoutRunHistorySection({ skillName }: { skillName: string }): JSX.Element {- const { rollups, scoutRunsLoadedOnce } = useValues(scoutFleetLogic)- const [filter, setFilter] = useState<ScoutRunFilter>('all')-- // Newest first for a history list; the rollup keeps runs oldest-first for the header timeline.- const runs = useMemo(() => {+/** This scout's runs in the recent window, newest first. */+function useScoutRuns(skillName: string): SignalScoutRunSummary[] {+ const { rollups } = useValues(scoutFleetLogic)+ return useMemo(() => {+ // Newest first for a history list; the rollup keeps runs oldest-first for the header timeline.const windowRuns = rollups.get(skillName)?.runs ?? []return [...windowRuns].reverse()}, [rollups, skillName])+}+/**+ * The All / Found something / Quiet / Failed pills, each with its match count. They live in the Runs+ * tab bar's right slot rather than above the list, so the tab bar carries both what you are looking+ * at and how it is narrowed.+ */+export function ScoutRunFilterPills({+ skillName,+ filter,+ onChange,+}: {+ skillName: string+ filter: ScoutRunFilter+ onChange: (filter: ScoutRunFilter) => void+}): JSX.Element {+ const runs = useScoutRuns(skillName)const filterCounts = useMemo(() => {const counts = new Map<ScoutRunFilter, number>()for (const entry of FILTERS) {@@ -221,58 +381,92 @@ export function ScoutRunHistorySection({ skillName }: { skillName: string }): JSreturn counts}, [runs])+ return (+ <div className="flex flex-wrap items-center gap-1">+ {FILTERS.map((entry) => (+ <LemonButton+ key={entry.value}+ size="xsmall"+ type="tertiary"+ active={filter === entry.value}+ onClick={() => {+ captureScoutAction({+ actionType: 'filter_runs',+ surface: 'scout_detail',+ skillName,+ extra: {+ filter: entry.value,+ filter_match_count: filterCounts.get(entry.value) ?? 0,+ },+ })+ onChange(entry.value)+ }}+ >+ {entry.label} {filterCounts.get(entry.value) ?? 0}+ </LemonButton>+ ))}+ </div>+ )+}++/**+ * The Runs tab on the scout detail surface: this scout's runs in the recent window, newest first,+ * with consecutive quiet runs and consecutive failures each folded into one entry. Runs come from+ * `scoutFleetLogic`'s already-polled per-scout rollup (oldest-first timeline order, reversed here);+ * the tab bar's filter pills narrow that set client-side.+ *+ * Folding is skipped while a filter is on: a list of nothing but quiet runs folded into one row+ * would hide what the reader just asked to see.+ */+export function ScoutRunHistorySection({+ skillName,+ filter,+}: {+ skillName: string+ filter: ScoutRunFilter+}): JSX.Element {+ const { scoutRunsLoadedOnce } = useValues(scoutFleetLogic)+ const runs = useScoutRuns(skillName)+const filteredRuns = useMemo(() => runs.filter((run) => runMatchesFilter(run, filter)), [runs, filter])+ const groups = useMemo(+ (): ScoutRunGroup[] =>+ filter === 'all' ? groupScoutRuns(filteredRuns) : filteredRuns.map((run) => ({ kind: 'run', run })),+ [filteredRuns, filter]+ )// Hold the skeleton until the fleet's per-scout runs have settled once — otherwise a fresh// deep-link flashes the empty state before we know this scout's runs.- const loading = !scoutRunsLoadedOnce+ if (!scoutRunsLoadedOnce) {+ return <LemonSkeleton className="h-12 w-full rounded" />+ }++ if (groups.length === 0) {+ return (+ <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>+ )+ }return (<div className="flex flex-col gap-2">- <div className="flex items-center gap-2 flex-wrap">- <span className="text-xs font-medium text-default uppercase tracking-wide">Runs</span>- <span className="flex-1" />- {FILTERS.map((entry) => (- <LemonButton- key={entry.value}- size="xsmall"- type="tertiary"- active={filter === entry.value}- onClick={() => {- captureScoutAction({- actionType: 'filter_runs',- surface: 'scout_detail',- skillName,- extra: {- filter: entry.value,- filter_match_count: filterCounts.get(entry.value) ?? 0,- },- })- setFilter(entry.value)- }}- >- {entry.label} {filterCounts.get(entry.value) ?? 0}- </LemonButton>- ))}+ {/* 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">+ {groups.map((group) =>+ group.kind === 'run' ? (+ <ScoutRunRow key={scoutRunGroupKey(group)} run={group.run} skillName={skillName} />+ ) : group.kind === 'quiet' ? (+ <QuietRunGroup key={scoutRunGroupKey(group)} runs={group.runs} skillName={skillName} />+ ) : (+ <FailedRunGroup key={scoutRunGroupKey(group)} runs={group.runs} skillName={skillName} />+ )+ )}</div>-- {loading ? (- <LemonSkeleton className="h-12 w-full rounded" />- ) : filteredRuns.length === 0 ? (- <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>- )}+ <span className="text-[11px] text-muted">From the {SCOUT_RUNS_PER_SCOUT_LABEL}.</span></div>)}diff --git a/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx b/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsxindex f1d0fff3afcd..aeb1aa4336a1 100644--- a/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx+++ b/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx@@ -11,6 +11,7 @@ import { humanFriendlyDetailedTime } from 'lib/utils/datetime'import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'import { scratchpadLogic } from '../../logics/scratchpadLogic'+import { scratchpadEntryBody, scratchpadEntryTitle } from '../../utils/scoutMemoryPresentation'import { stripScoutPrefix } from '../../utils/scoutRunsWindow'type LemonTagType = ComponentProps<typeof LemonTag>['type']@@ -44,8 +45,18 @@ function splitKey(key: string): { kind: string | null; body: string } {** 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.+ *+ * On a single scout's page pass `titled`: the entry's own opening heading leads in regular type and+ * the storage key drops out. Every entry there belongs to that scout, so a truncated key says less+ * than the name the scout gave the learning.*/-export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): JSX.Element {+export function ScratchpadEntryCard({+ entry,+ titled = false,+}: {+ entry: ScratchpadEntryApi+ titled?: boolean+}): JSX.Element {const { expandedKeys, fullContentByKey, loadingContentKeys } = useValues(scratchpadLogic)const { toggleEntry } = useActions(scratchpadLogic)@@ -56,6 +67,9 @@ export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): Jconst { kind, body } = splitKey(entry.key)const scoutName = entry.created_by_skill ? stripScoutPrefix(entry.created_by_skill) : null+ // Collapsed, a titled card previews the body under its own heading, so the heading isn't said+ // twice. Expanded, the entry reads as written.+ const preview = titled && !expanded ? scratchpadEntryBody(content) : content// How long the note has been carried forward: a fresh creation reads ~0 days; a large gap// means the fleet has re-touched this learning across many runs — the "gets sharper" signal.@@ -78,7 +92,13 @@ export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): J{kind}</LemonTag>)}- <span className="truncate font-mono text-xs text-primary">{body}</span>+ {titled ? (+ <span className="truncate text-xs font-medium text-default">+ {scratchpadEntryTitle(content, body)}+ </span>+ ) : (+ <span className="truncate font-mono text-xs text-primary">{body}</span>+ )}<span className="flex-1" />{entry.updated_at && (<span className="flex items-center gap-1 whitespace-nowrap text-[11px] text-muted">@@ -89,11 +109,13 @@ export function ScratchpadEntryCard({ entry }: { entry: ScratchpadEntryApi }): J</button><div className="px-3 pb-2 pl-9">- {content ? (+ {preview ? (<pre- className={`m-0 whitespace-pre-wrap break-words font-mono text-xs text-primary ${expanded ? '' : 'line-clamp-2'}`}+ className={`m-0 whitespace-pre-wrap break-words font-mono text-xs text-primary ${+ expanded ? '' : titled ? 'line-clamp-1' : 'line-clamp-2'+ }`}>- {content}+ {preview}</pre>) : (<span className="text-xs italic text-muted">No content.</span>diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex 1eac380a1b42..0122a4617c65 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -171,7 +171,8 @@ export type ScoutSurface = 'fleet_list' | 'scout_detail' | 'empty_state' | 'repl/*** Scout-management actions. The first block matches desktop's enum; the trailing block is* cloud-only, covering affordances desktop doesn't have (creating and deleting scouts, the- * scratchpad callout, and the roster's on/off filter, owner filter, and search).+ * scratchpad callout, the roster's on/off filter, owner filter, and search, and opening a folded+ * run group).*/export type ScoutActionType =| 'open_settings'@@ -191,6 +192,8 @@ export type ScoutActionType =| 'copy_finding_link'| 'open_task_run'| 'open_linked_report'+ | 'switch_detail_tab'+ | 'open_detail_tab'| 'open_create_modal'| 'create_scout'| 'delete_scout'@@ -198,6 +201,7 @@ export type ScoutActionType =| 'filter_enabled'| 'filter_owner'| 'search_scouts'+ | 'expand_run_group'/** What a scout chat CTA was asking for. Matches the desktop values. */export type ScoutChatType = 'author_scout' | 'fleet_overview' | 'recent_signals'diff --git a/products/signals/frontend/inbox/inboxSceneLogic.test.ts b/products/signals/frontend/inbox/inboxSceneLogic.test.tsindex 8ab1a3b0ad6d..311d3ab44202 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.test.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.test.ts@@ -216,6 +216,80 @@ describe('inboxSceneLogic routing', () => {expect(opened(logic.values)).toBe(true)})+ // The scout page's tabs live in the URL, so a link to a scout's runs has to survive a reload.+ // Selecting a scout resets the tab, so the URL's tab had to be applied after that reset.+ describe('the scout page tab in the URL', () => {+ it('opens the tab a reloaded URL names', () => {+ mountWithRedesign(true)+ router.actions.push(urls.inboxScout('signals-scout-web-vitals'), { tab: 'runs' })+ expect(logic.values.selectedScoutSkillName).toBe('signals-scout-web-vitals')+ expect(logic.values.scoutDetailTab).toBe('runs')+ })++ it('leaves the tab on its default for a bare scout URL', () => {+ mountWithRedesign(true)+ router.actions.push(urls.inboxScout('signals-scout-web-vitals'))+ expect(logic.values.scoutDetailTab).toBeNull()+ })++ it('ignores a tab the page has no pane for', () => {+ mountWithRedesign(true)+ router.actions.push(urls.inboxScout('signals-scout-web-vitals'), { tab: 'nonsense' })+ expect(logic.values.scoutDetailTab).toBeNull()+ })++ it('writes the chosen tab back to the URL, and drops it again on the default', () => {+ mountWithRedesign(true)+ router.actions.push(urls.inboxScout('signals-scout-web-vitals'))+ logic.actions.setScoutDetailTab('learned')+ expect(router.values.searchParams.tab).toBe('learned')+ logic.actions.setScoutDetailTab(null)+ expect(router.values.searchParams.tab).toBeUndefined()+ })++ // Hydrating a deep link must not add a history entry, or the first Back press lands on the+ // same page with the same tab and reads as a dead control.+ it.each<[string, string, Record<string, string> | undefined]>([+ ['a tab deep link', urls.inboxScout('signals-scout-web-vitals'), { tab: 'runs' }],+ ['a finding deep link', urls.inboxScout('signals-scout-web-vitals', 'finding-1'), undefined],+ [+ 'a finding link on another pane',+ urls.inboxScout('signals-scout-web-vitals', 'finding-1'),+ { tab: 'runs' },+ ],+ ])('opens %s with one history entry', (_name, path, searchParams) => {+ mountWithRedesign(true)+ const push = jest.spyOn(router.actions, 'push')+ router.actions.push(path, searchParams)+ expect(push).toHaveBeenCalledTimes(1)+ push.mockRestore()+ })++ it('opens Signals for a finding deep-link, which is what the link is asking for', () => {+ mountWithRedesign(true)+ router.actions.push(urls.inboxScout('signals-scout-web-vitals', 'finding-1'))+ expect(logic.values.scoutDetailTab).toBe('signals')+ })++ // A finding opens on Signals, but the reader can move to another pane and share that URL.+ it('opens the pane a finding URL names instead of resetting to Signals', () => {+ mountWithRedesign(true)+ router.actions.push(urls.inboxScout('signals-scout-web-vitals', 'finding-1'), { tab: 'runs' })+ expect(logic.values.scoutDetailTab).toBe('runs')+ expect(logic.values.selectedScoutFindingId).toBe('finding-1')+ })++ it('records a pane move on a finding page, and drops the param back on Signals', () => {+ mountWithRedesign(true)+ router.actions.push(urls.inboxScout('signals-scout-web-vitals', 'finding-1'))+ logic.actions.setScoutDetailTab('runs')+ expect(router.values.location.pathname.endsWith('/finding-1')).toBe(true)+ expect(router.values.searchParams.tab).toBe('runs')+ logic.actions.setScoutDetailTab('signals')+ expect(router.values.searchParams.tab).toBeUndefined()+ })+ })+// A held report deep-link still opens the report under the persisted layout, so the page is not// empty while flags load; the replay only settles the tab once the layout is known.it('before flags resolve /inbox/pulls/<id> opens the report and lands on Reports once the redesign resolves', () => {diff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.tsindex 9c59851023d4..260629ccefc8 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts@@ -137,6 +137,43 @@ export function mergeSignalRuns(scoutRuns: SignalScoutRunSummary[], signalTasks:)}+/**+ * Which pane of the scout detail page is open. The main column holds Reports, Runs and Signals; the+ * rail holds Told and Learned. One value covers both, because below the detail page's container+ * breakpoint the rail's tabs join the main tab bar and only one pane shows at a time.+ *+ * `null` means nobody has chosen: the page picks Reports when the scout has any, else Runs.+ */+export const SCOUT_DETAIL_TABS = ['reports', 'runs', 'signals', 'told', 'learned'] as const+export type ScoutDetailTab = (typeof SCOUT_DETAIL_TABS)[number]++function asScoutDetailTab(value: string | undefined): ScoutDetailTab | null {+ return value !== undefined && (SCOUT_DETAIL_TABS as readonly string[]).includes(value)+ ? (value as ScoutDetailTab)+ : null+}++/** The pane a scout URL's path states on its own: a finding is addressed within Signals. */+function panePathImplies(findingId: string | null): ScoutDetailTab | null {+ return findingId ? 'signals' : null+}++/** The pane a scout URL opens: the one its `tab` names, or the one its path implies. */+function scoutUrlPane(tab: ScoutDetailTab | null, findingId: string | null): ScoutDetailTab | null {+ return tab ?? panePathImplies(findingId)+}++/**+ * The search params a scout-page navigation should carry: whatever is on the URL now, with `tab`+ * set to the open pane, or dropped when the path already states that pane. A bare scout URL states+ * the default pane and a finding URL states Signals, so both stay clean, and every other pane is+ * named in the URL so it survives a reload.+ */+function scoutTabSearchParams(pane: ScoutDetailTab | null, findingId: string | null): Record<string, any> {+ const { tab: _ignored, ...rest } = router.values.searchParams+ return pane && pane !== panePathImplies(findingId) ? { ...rest, tab: pane } : rest+}+/** Whether a URL segment is one of the current layout's page tabs. */function isInboxTabKey(value: string | undefined, redesign: boolean): value is InboxTabKey {const tabKeys = (redesign ? INBOX_TAB_KEYS : INBOX_LEGACY_TAB_KEYS) as string[]@@ -329,6 +366,7 @@ export interface inboxSceneLogicValues {isScratchpadOpen: booleanisStaff: booleanisTriageOpen: boolean+ scoutDetailTab: ScoutDetailTab | nullscoutTemplateDraft: ScoutCreateInitialValues | nullselectedReport: SignalReport | nullselectedReportId: string | null@@ -404,6 +442,9 @@ export interface inboxSceneLogicActions {setRunsOpen: (open: boolean) => {open: boolean}+ setScoutDetailTab: (tab: ScoutDetailTab | null) => {+ tab: 'learned' | 'reports' | 'runs' | 'signals' | 'told' | null+ }setScoutTemplateDraft: (draft: ScoutCreateInitialValues | null) => {draft: ScoutCreateInitialValues | null}@@ -419,10 +460,12 @@ export interface inboxSceneLogicActions {}setSelectedScoutSkillName: (skillName: string | null,- findingId?: string | null+ findingId?: string | null,+ tab?: ScoutDetailTab | null) => {findingId: string | nullskillName: string | null+ tab: 'learned' | 'reports' | 'runs' | 'signals' | 'told' | null}setTriageOpen: (open: boolean) => {open: boolean@@ -480,11 +523,21 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([setActiveTab: (tab: InboxTabKey) => ({ tab }),// Scout detail surface: selecting a scout opens its full-width detail over the list. An// optional finding id deep-links to one emitted finding within that scout (highlighted +- // scrolled into view if it's still in the recent window).- setSelectedScoutSkillName: (skillName: string | null, findingId: string | null = null) => ({+ // scrolled into view if it's still in the recent window). The pane travels with the+ // selection so a route can name the tab its URL asked for in the same action: a second+ // action for the tab would first write a URL without it, and that write is a history entry.+ setSelectedScoutSkillName: (+ skillName: string | null,+ findingId: string | null = null,+ tab: ScoutDetailTab | null = null+ ) => ({skillName,findingId,+ tab,}),+ // Which pane of the open scout's page is showing. Carried in the URL so a link to a scout's+ // runs survives a reload.+ setScoutDetailTab: (tab: ScoutDetailTab | null) => ({ tab }),// Scout fleet-memory (scratchpad) surface: a full-width browse/search view over the list,// mutually exclusive with the report and scout-detail views. Reached from the fleet-memory callout.setScratchpadOpen: (open: boolean) => ({ open }),@@ -656,6 +709,16 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([setSelectedScoutSkillName: (_, { findingId }) => findingId,},],+ scoutDetailTab: [+ null as ScoutDetailTab | null,+ {+ setScoutDetailTab: (_, { tab }) => tab,+ // The pane the navigation named wins: a route passes the tab its URL carries, so a+ // finding link that names another pane opens that one. A roster click passes+ // nothing, which leaves the page on the pane its path implies.+ setSelectedScoutSkillName: (_, { findingId, tab }) => scoutUrlPane(tab, findingId),+ },+ ],}),selectors({@@ -999,12 +1062,19 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([router.values.hashParams,{ replace: false },],- setSelectedScoutSkillName: () => [+ setSelectedScoutSkillName: ({ findingId }) => [inboxSurfaceUrl(values),- router.values.searchParams,+ scoutTabSearchParams(values.scoutDetailTab, findingId),router.values.hashParams,{ replace: false },],+ setScoutDetailTab: () => [+ inboxSurfaceUrl(values),+ scoutTabSearchParams(values.scoutDetailTab, values.selectedScoutFindingId),+ router.values.hashParams,+ // A tab switch is not a navigation step — Back should leave the scout, not walk its tabs.+ { replace: true },+ ],setScratchpadOpen: () => [inboxSurfaceUrl(values),router.values.searchParams,@@ -1132,7 +1202,10 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([}closeAllSurfaces()},- [urls.inboxScout(':skillName')]: ({ skillName }: { skillName?: string }) => {+ [urls.inboxScout(':skillName')]: (+ { skillName }: { skillName?: string },+ searchParams: Record<string, string | undefined>+ ) => {// `/inbox/scouts/scratchpad`, `/inbox/scouts/findings`, and `/inbox/scouts/runs` also match// this pattern; their own handlers own those paths (no real scout skill_name collides —// they're `signals-scout-*`).@@ -1140,22 +1213,33 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([return}const name = skillName ?? null+ const tab = asScoutDetailTab(searchParams.tab)// Also reset the finding when landing on the bare scout URL after a finding deep-link.if (values.selectedScoutSkillName !== name || values.selectedScoutFindingId !== null) {- actions.setSelectedScoutSkillName(name)+ actions.setSelectedScoutSkillName(name, null, tab)+ }+ // Only a tab move within the scout already open reaches this, because the selection+ // above carries the tab. Sending both would push a URL without the tab first.+ if (values.scoutDetailTab !== tab) {+ actions.setScoutDetailTab(tab)}},- [urls.inboxScout(':skillName', ':findingId')]: ({- skillName,- findingId,- }: {- skillName?: string- findingId?: string- }) => {+ [urls.inboxScout(':skillName', ':findingId')]: (+ { skillName, findingId }: { skillName?: string; findingId?: string },+ searchParams: Record<string, string | undefined>+ ) => {const name = skillName ?? nullconst finding = findingId ?? null+ // A finding opens on Signals, where it is highlighted, but the reader can move to+ // another pane without leaving the finding behind. The URL records that move, so it+ // has to be read back here rather than reset to Signals.+ const tab = asScoutDetailTab(searchParams.tab)if (values.selectedScoutSkillName !== name || values.selectedScoutFindingId !== finding) {- actions.setSelectedScoutSkillName(name, finding)+ actions.setSelectedScoutSkillName(name, finding, tab)+ }+ const pane = scoutUrlPane(tab, finding)+ if (values.scoutDetailTab !== pane) {+ actions.setScoutDetailTab(pane)}},[urls.inboxReport(':tab', ':reportId')]: (diff --git a/products/signals/frontend/inbox/logics/scoutNotesLogic.ts b/products/signals/frontend/inbox/logics/scoutNotesLogic.tsindex 6cd20eaac130..eee9b6a03813 100644--- a/products/signals/frontend/inbox/logics/scoutNotesLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutNotesLogic.ts@@ -26,10 +26,12 @@ export interface ScoutNotesLogicProps {*/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',- report_reviewer_correction: 'From a reviewer change',+ // No "From a" prefix: these sit in a tag beside the note, where the preposition is the widest+ // part of a label that already reads as a source.+ report_dismissal: 'Dismissal',+ report_discussion: 'Discussion',+ report_feedback: 'Rating',+ report_reviewer_correction: 'Reviewer change',}export function scoutNoteOriginLabel(origin: string): string {diff --git a/products/signals/frontend/inbox/utils/scoutMemoryPresentation.test.ts b/products/signals/frontend/inbox/utils/scoutMemoryPresentation.test.tsnew file mode 100644index 000000000000..c0ad7b558f2e--- /dev/null+++ b/products/signals/frontend/inbox/utils/scoutMemoryPresentation.test.ts@@ -0,0 +1,84 @@+import { linkReportIdsInNote, scratchpadEntryBody, scratchpadEntryTitle } from './scoutMemoryPresentation'++const REPORT_ID = '01a0918c-51db-73c3-a1f1-177d5990cf1e'+const OTHER_ID = '01a0918c-51db-73c3-a1f1-177d5990cf99'++describe('scoutMemoryPresentation', () => {+ describe('linkReportIdsInNote', () => {+ const reports = new Map([[REPORT_ID, { id: REPORT_ID, title: 'fix(web-vitals): LCP regression on /pricing' }]])++ it('names a resolved report by title and links it', () => {+ const linked = linkReportIdsInNote(`Suggested reviewers changed on ${REPORT_ID}.`, reports)+ expect(linked).toContain('[LCP regression on /pricing](')+ expect(linked).toContain(REPORT_ID)+ expect(linked).not.toContain(`on ${REPORT_ID}`)+ })++ // A pipeline note writes report ids and nothing else, so an unresolved one shrinks rather+ // than wrapping the whole uuid. A uuid in typed prose can name anything, so it stays whole.+ it.each<[string, { truncateUnmatched?: boolean } | undefined, string]>([+ ['is truncated in a note the pipeline wrote', undefined, 'Dismissed `01a0918c…` as noise.'],+ ['stays whole in a note someone typed', { truncateUnmatched: false }, `Dismissed ${OTHER_ID} as noise.`],+ ])('an id no report resolves for %s', (_name, options, expected) => {+ expect(linkReportIdsInNote(`Dismissed ${OTHER_ID} as noise.`, reports, options)).toBe(expected)+ })++ // Report titles are untrusted agent output. These are the characters that escape a markdown+ // link label, so a resolved report's title must not carry them into the rewritten note.+ it.each<[string, string, string]>([+ ['a backtick, which closes the code span a note wraps the id in', 'LCP `regression`', 'LCP regression'],+ [+ 'an angle autolink, which links out of the label',+ 'LCP <https://evil.example>',+ 'LCP https://evil.example',+ ],+ [+ 'a blank line, which ends the paragraph the link sits in',+ 'LCP\n\nhttps://evil.example',+ 'LCP https://evil.example',+ ],+ ['everything, leaving a label that would be invisible', '`<>`', 'Untitled report'],+ ])('drops %s', (_name, title, expected) => {+ const linked = linkReportIdsInNote(+ `Dismissed ${REPORT_ID}.`,+ new Map([[REPORT_ID, { id: REPORT_ID, title }]])+ )+ expect(linked).toContain(`[${expected}](`)+ })++ it('leaves an id that already sits in a link target alone', () => {+ const note = `See [the report](/project/2/inbox/reports/${REPORT_ID}).`+ expect(linkReportIdsInNote(note, reports)).toBe(note)+ })++ it('matches an id whatever case it was written in', () => {+ expect(linkReportIdsInNote(REPORT_ID.toUpperCase(), reports)).toContain('LCP regression on /pricing')+ })+ })++ describe('scratchpadEntryTitle', () => {+ it('uses the entry’s opening heading, without its hashes', () => {+ expect(scratchpadEntryTitle('## Baseline p75 per top page\n\n/pricing 2.1s', 'key')).toBe(+ 'Baseline p75 per top page'+ )+ })++ it('falls back to the key for an entry that opens into prose', () => {+ expect(scratchpadEntryTitle('/pricing 2.1s, /docs 1.6s', 'baseline:web-vitals')).toBe('baseline:web-vitals')+ })++ it('falls back to the key for an entry with no content', () => {+ expect(scratchpadEntryTitle(null, 'baseline:web-vitals')).toBe('baseline:web-vitals')+ })+ })++ describe('scratchpadEntryBody', () => {+ it('drops the heading the title already shows', () => {+ expect(scratchpadEntryBody('# Known regressions\n\nTwo open reports.')).toBe('Two open reports.')+ })++ it('keeps a body that never had a heading', () => {+ expect(scratchpadEntryBody('Two open reports.')).toBe('Two open reports.')+ })+ })+})diff --git a/products/signals/frontend/inbox/utils/scoutMemoryPresentation.ts b/products/signals/frontend/inbox/utils/scoutMemoryPresentation.tsnew file mode 100644index 000000000000..f89636b5f5e7--- /dev/null+++ b/products/signals/frontend/inbox/utils/scoutMemoryPresentation.ts@@ -0,0 +1,96 @@+import { urls } from 'scenes/urls'++import { displayConventionalCommitTitle } from './reportPresentation'++/**+ * A report id as the pipeline writes it into a note. Derived notes name the report they came from by+ * uuid, which tells a reader nothing — the note's whole value is which report it is about.+ *+ * A uuid that already sits in a link target is left alone: rewriting it would break the link the+ * note author wrote.+ */+const REPORT_ID_IN_NOTE = /(?<![/(])\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi++/** Only the leading chunk of a uuid earns space once it is clear nobody can resolve it. */+function truncateReportId(id: string): string {+ return `\`${id.slice(0, 8)}…\``+}++/**+ * A report title as a markdown link label. The title is untrusted: an agent writes it from ticket+ * and issue text. The characters that escape the label are removed rather than escaped, because a+ * derived note wraps the report id in a code span, and a backslash escape inside a code span+ * renders as a literal backslash. `[` and `]` close the label, a backtick closes that code span,+ * and `<url>` renders as a link inside the link, carrying a target the title chose. Whitespace+ * collapses because a blank line ends the paragraph the link sits in. A bare url needs nothing:+ * inside a link label GFM leaves it as text.+ */+function reportLinkLabel(title: string | null, fallback: string): string {+ const label = displayConventionalCommitTitle(title, fallback)+ .replace(/[[\]`<>]/g, '')+ .replace(/\s+/g, ' ')+ .trim()+ // A title of nothing but stripped characters would render as an invisible empty link.+ return label || fallback+}++/**+ * The note, with every report id that resolves to a report this scout touched rewritten as a+ * markdown link carrying the report's title. Ids that resolve to nothing — an older window, a+ * deleted report — shrink to a truncated code span, because the full uuid wraps to a second line+ * and says no more than its head does.+ *+ * Pass `truncateUnmatched: false` for a note a person typed. Only the pipeline guarantees that+ * every uuid it writes is a report id. In typed prose a uuid can name a session, a trace, or an+ * error issue, and shortening one would corrupt a value the reader cannot recover from this page.+ */+export function linkReportIdsInNote(+ content: string,+ reportsById: Map<string, { id: string; title: string | null }>,+ { truncateUnmatched = true }: { truncateUnmatched?: boolean } = {}+): string {+ return content.replace(REPORT_ID_IN_NOTE, (id) => {+ const report = reportsById.get(id.toLowerCase())+ if (!report) {+ return truncateUnmatched ? truncateReportId(id) : id+ }+ return `[${reportLinkLabel(report.title, 'Untitled report')}](${urls.inboxReport('reports', report.id)})`+ })+}++/**+ * A scratchpad entry split into what to show as its title and what to show under it. Scouts write+ * these as markdown, opening with a heading, so the heading is the entry's own name for itself —+ * better than the storage key, which is a slug.+ *+ * Falls back to the key body for an entry that opens straight into prose.+ */+export function scratchpadEntryTitle(content: string | null | undefined, fallback: string): string {+ const heading = content+ ?.split('\n')+ .find((line) => line.trim().length > 0)+ ?.trim()+ if (heading?.startsWith('#')) {+ const stripped = heading.replace(/^#+\s*/, '').trim()+ if (stripped) {+ return stripped+ }+ }+ return fallback+}++/** The entry's body with its opening heading removed, so a preview doesn't restate the title. */+export function scratchpadEntryBody(content: string | null | undefined): string {+ if (!content) {+ return ''+ }+ const lines = content.split('\n')+ const firstIndex = lines.findIndex((line) => line.trim().length > 0)+ if (firstIndex >= 0 && lines[firstIndex].trim().startsWith('#')) {+ return lines+ .slice(firstIndex + 1)+ .join('\n')+ .trim()+ }+ return content.trim()+}diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.tsindex a6daf7519420..922549ef53e4 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.test.ts@@ -7,6 +7,8 @@ import {deriveRunOutcome,expensiveRunCostThreshold,formatRunCost,+ filedOrAddedLabel,+ groupScoutRuns,mostRecentEmittedRuns,rosterRunCosts,runMatchesFilter,@@ -19,6 +21,9 @@ import {scoutCronScheduleError,scoutDisplayName,scoutReportActivityLabel,+ scoutRunFailureLine,+ scoutRunGroupKey,+ scoutRunReportLabel,weeklyCronToDayTime,} from './scoutRunsWindow'@@ -185,6 +190,130 @@ describe('scoutRunsWindow report channel', () => {})})+ // The row tags read in the report channel's words, and a report both filed and later edited is+ // one report — the header strip derives it the same way, so the two must not disagree.+ describe('scoutRunReportLabel', () => {+ it.each<[string, Partial<SignalScoutRunSummary>, string | null]>([+ ['filed only', { emitted_report_ids: ['r-1'] }, `Filed ${pluralize(1, 'report')}`],+ ['added to only', { edited_report_ids: ['r-1', 'r-2'] }, `Added to ${pluralize(2, 'report')}`],+ [+ 'filed one and added to another',+ { emitted_report_ids: ['r-1'], edited_report_ids: ['r-2'] },+ 'Filed 1 · added to 1',+ ],+ [+ 'filed then edited the same report counts once',+ { emitted_report_ids: ['r-1'], edited_report_ids: ['r-1'] },+ `Filed ${pluralize(1, 'report')}`,+ ],+ ['no report activity', {}, null],+ ])('%s', (_name, overrides, expected) => {+ expect(scoutRunReportLabel(makeRun(overrides))).toEqual(expected)+ })++ // The header strip shares this label, and hands it the rollup's deduped id sets rather+ // than one run's arrays.+ it('takes id sets, and drops a filed report from the added-to count', () => {+ expect(filedOrAddedLabel(new Set(['r-1']), new Set(['r-1', 'r-2']))).toEqual('Filed 1 · added to 1')+ })+ })++ describe('scoutRunFailureLine', () => {+ // The close-out is agent prose, so its first line can open with any markdown marker. Each+ // has to go before the sentence split, or the split stops on the marker's own punctuation.+ it.each<[string, string, string]>([+ ['a heading', '## Stopped mid-plan\nEligibility is healthy. More.', 'Stopped mid-plan'],+ ['a bullet', '- Stopped mid-plan. More.', 'Stopped mid-plan.'],+ ['an ordered item', '1. Stopped mid-plan. More.', 'Stopped mid-plan.'],+ ['an ordered item in brackets', '1) Stopped mid-plan. More.', 'Stopped mid-plan.'],+ ['a decimal that is not a marker', '1.5s of runtime. More.', '1.5s of runtime.'],+ ])('takes the first sentence of a close-out opening with %s', (_name, summary, expected) => {+ expect(scoutRunFailureLine(makeRun({ status: 'failed', summary }), NOW)).toBe(expected)+ })++ // The serializer sends the first line of the task's error message as `failure_reason`, so a+ // failure that never got to its close-out still says what went wrong.+ it.each<[string, Partial<SignalScoutRunSummary>, string]>([+ [+ 'the recorded reason when the run wrote no close-out',+ {+ summary: '',+ error: 'ToolError: the sandbox closed the connection\n at step 3',+ failure_reason: 'ToolError: the sandbox closed the connection',+ },+ 'ToolError: the sandbox closed the connection',+ ],+ [+ 'the close-out ahead of the reason',+ {+ summary: 'Stopped mid-plan. More.',+ error: 'ToolError: the sandbox closed the connection',+ failure_reason: 'ToolError: the sandbox closed the connection',+ },+ 'Stopped mid-plan.',+ ],+ ])('takes %s', (_name, overrides, expected) => {+ expect(scoutRunFailureLine(makeRun({ status: 'failed', ...overrides }), NOW)).toBe(expected)+ })++ // A run killed at the deadline records no message, so the serializer derives a placeholder+ // reason with a null `error`. The elapsed time says more than the placeholder does.+ it('names the duration when the run never wrote a close-out', () => {+ const run = makeRun({+ status: 'failed',+ summary: '',+ error: null,+ failure_reason: 'failed (no error message recorded)',+ started_at: '2026-06-27T21:00:00Z',+ completed_at: '2026-06-27T21:00:37Z',+ })+ expect(scoutRunFailureLine(run, NOW)).toBe('Ended after 37s without a close-out.')+ })+ })++ // A scout's history is mostly quiet, so a flat list buries the failures anyone opened it for.+ describe('groupScoutRuns', () => {+ const quiet = (id: string): SignalScoutRunSummary => makeRun({ run_id: id })+ const failed = (id: string): SignalScoutRunSummary => makeRun({ run_id: id, status: 'failed' })+ const filed = (id: string): SignalScoutRunSummary => makeRun({ run_id: id, emitted_report_ids: ['r-1'] })++ it('folds a run of quiet runs into one group and keeps them in order', () => {+ const groups = groupScoutRuns([quiet('a'), quiet('b'), quiet('c')])+ expect(groups).toHaveLength(1)+ expect(groups[0]).toMatchObject({ kind: 'quiet' })+ expect(groups[0].kind === 'quiet' && groups[0].runs.map((run) => run.run_id)).toEqual(['a', 'b', 'c'])+ })++ it('folds consecutive failures into one group', () => {+ const groups = groupScoutRuns([failed('a'), failed('b'), failed('c')])+ expect(groups).toHaveLength(1)+ expect(groups[0].kind === 'failed' && groups[0].runs).toHaveLength(3)+ })++ it('never merges across a productive run, so a group only spans what it says it does', () => {+ const groups = groupScoutRuns([quiet('a'), filed('b'), quiet('c'), failed('d'), quiet('e')])+ expect(groups.map((group) => group.kind)).toEqual(['quiet', 'run', 'quiet', 'failed', 'quiet'])+ })++ it('never merges a failure into a quiet group', () => {+ const groups = groupScoutRuns([quiet('a'), failed('b')])+ expect(groups.map((group) => group.kind)).toEqual(['quiet', 'failed'])+ })++ it('keeps a lone quiet run as a group of one, so the list does not switch grammar', () => {+ const groups = groupScoutRuns([quiet('a')])+ expect(groups[0].kind === 'quiet' && groups[0].runs).toHaveLength(1)+ })++ // The detail view polls and prepends, so a group's key has to survive a newer run joining+ // it. Otherwise React remounts the group and the reader's open rows close.+ it('keys a folded group the same way once a newer run joins it', () => {+ const [before] = groupScoutRuns([quiet('b'), quiet('c')])+ const [after] = groupScoutRuns([quiet('a'), quiet('b'), quiet('c')])+ expect(scoutRunGroupKey(after)).toEqual(scoutRunGroupKey(before))+ })+ })+describe('computeScoutRollups', () => {it('dedupes report ids across runs into the authored/edited sets', () => {const skill = 'signals-scout-dev-report-probe'diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.tsindex 2ba3319bfd8d..acb5afe25084 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts@@ -354,6 +354,107 @@ export function scoutRunOutcomeLabel(run: SignalScoutRunSummary, now: Date): str}}+/**+ * How reports were touched, in the words the page uses everywhere else: "Filed 1 report",+ * "Filed 1 · added to 4", "Added to 2 reports". Returns null when no report was touched.+ *+ * A report both filed and later edited counts once, as filed. The run rows and the header health+ * strip both come through here, so the two cannot word the same activity differently.+ */+export function filedOrAddedLabel(authored: Iterable<string>, edited: Iterable<string>): string | null {+ const authoredIds = new Set(authored)+ const addedTo = [...edited].filter((id) => !authoredIds.has(id))+ if (authoredIds.size === 0) {+ return addedTo.length > 0 ? `Added to ${pluralize(addedTo.length, 'report')}` : null+ }+ if (addedTo.length === 0) {+ return `Filed ${pluralize(authoredIds.size, 'report')}`+ }+ return `Filed ${authoredIds.size} · added to ${addedTo.length}`+}++/** What one run did in the report channel. */+export function scoutRunReportLabel(run: SignalScoutRunSummary): string | null {+ const { authored, edited } = runReportActivity(run)+ return filedOrAddedLabel(authored, edited)+}++/**+ * The first sentence of a run's close-out, for a folded failure group where a full markdown preview+ * per run would bury the group. Falls back to the recorded failure reason, then to the run's+ * duration, when it never wrote one.+ */+export function scoutRunFailureLine(run: SignalScoutRunSummary, now: Date): string {+ const summary = run.summary?.trim()+ if (summary) {+ // Markdown headings and list bullets read as punctuation in a one-line preview, so drop them.+ // An ordered item's marker goes separately, because its own period ends the sentence match+ // below and the line collapses to "1.". The trailing space is required, so a version or a+ // decimal in ordinary prose is left alone.+ const firstLine =+ summary+ .split('\n')+ .find((line) => line.trim().length > 0)+ ?.replace(/^[#>\-*\s]+/, '')+ .replace(/^\d+[.)]\s+/, '') ?? ''+ const firstSentence = firstLine.match(/^.*?[.!?](?=\s|$)/)?.[0] ?? firstLine+ if (firstSentence.trim()) {+ return firstSentence.trim()+ }+ }+ // `failure_reason` is the first line of the task's error message, or a placeholder the+ // serializer derives when the task recorded none — and `error` is null in exactly that case. A+ // run hard-killed at the deadline is the common failure here, and its elapsed time says more+ // than "failed (no error message recorded)", so only a reason with a message behind it wins.+ const reason = run.error ? run.failure_reason?.trim() : undefined+ if (reason) {+ return reason+ }+ const duration = formatRunDuration(runDurationSeconds(run, now))+ return duration ? `Ended after ${duration} without a close-out.` : 'Ended without a close-out.'+}++/**+ * A run list folded for reading: a productive or in-flight run stays its own row, while consecutive+ * quiet runs and consecutive failures each collapse into one group. A scout's history is mostly+ * quiet, so a flat list spends its first screen on runs that found nothing and pushes the failures+ * — the reason anyone opens the list — out of sight.+ *+ * Order is preserved, so the caller decides newest-first or oldest-first.+ */+export type ScoutRunGroup =+ | { kind: 'run'; run: SignalScoutRunSummary }+ | { kind: 'quiet'; runs: SignalScoutRunSummary[] }+ | { kind: 'failed'; runs: SignalScoutRunSummary[] }++/**+ * A group's React key. A folded group is keyed by its last run rather than its first, because the+ * detail view passes runs newest-first: a poll that prepends a run, or an in-flight run that+ * settles into the fold, changes the first run. That would remount the group and discard the+ * expanded state it owns, closing it under the reader.+ */+export function scoutRunGroupKey(group: ScoutRunGroup): string {+ return group.kind === 'run' ? group.run.run_id : group.runs[group.runs.length - 1].run_id+}++export function groupScoutRuns(runs: SignalScoutRunSummary[]): ScoutRunGroup[] {+ const groups: ScoutRunGroup[] = []+ for (const run of runs) {+ const foldKind = runMatchesFilter(run, 'quiet') ? 'quiet' : runMatchesFilter(run, 'failed') ? 'failed' : null+ if (!foldKind) {+ groups.push({ kind: 'run', run })+ continue+ }+ const last = groups[groups.length - 1]+ if (last && last.kind === foldKind) {+ last.runs.push(run)+ continue+ }+ groups.push({ kind: foldKind, runs: [run] })+ }+ return groups+}+// ── Per-scout rollups ────────────────────────────────────────────────────────export interface ScoutRollup {