Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): render the scout scratchpad as a filterable ledger (#99458)

posthog[bot]d122877262a3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 81337bc95a4b..751dfa2a2515 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9588,6 +9588,34 @@ snapshots:
hash: v1.k794b7964.3362f7e3189434319ec363172447f3fbbe529b2d745ef0ddf7f8e8c494fcd4a2.2bUlzu2lgIJbm8s_5ic3TtAcZ9hHX4_JFAE8hd9fQVk
scenes-app-sidepanels--side-panel-support--light:
hash: v1.k794b7964.deb388fad6d54211a52bf0228e80a62f18903b5a91ed77f47408f1fbb9137480.c8bN-QxTmTOSLWxd37aThlQhlWmlZ9r6N1YUBjhRsU8
+ scenes-app-signals-scratchpadpanel--empty--dark:
+ hash: v1.k794b7964.757324c1b54ffaecee38977f672fd4472cdb48b03afd4e5dde2a6ffe6886be4c.hdnPdcSaYr7gkhjrtlmibhVPZ1eLWM15qg3ZUCaBlig
+ scenes-app-signals-scratchpadpanel--empty--light:
+ hash: v1.k794b7964.17d5468c4cea5ca9620ee6b972a8198c5b6e2116451a68ae9cc32b7cb5256120.2Ry2kEwC785PampavT7Y1CpLSxskkLlHwnJ2KVQsHYE
+ scenes-app-signals-scratchpadpanel--filtered-empty--dark:
+ hash: v1.k794b7964.241699adbe8f1f918f4534158483e000624547f401daf9554cb5b151a36daaaa.DHCnZKO_v-efHE_eY82DplgGm2Jssc-cvwSf80qVAgQ
+ scenes-app-signals-scratchpadpanel--filtered-empty--light:
+ hash: v1.k794b7964.fb47cb5f1e61919ad543296f711ff2c643b8d401df61a2ae0cf8b273e7494c5f.eN2x0BnkPS8QhMK_xhtSdyJBUjX-hx4UDoH374_H1Hc
+ scenes-app-signals-scratchpadpanel--load-failed--dark:
+ hash: v1.k794b7964.439a31db338fefa6c4e8c9fdb363d07d9abd269d0cea4644fd1e94bcb1ca2be7.mrSv70EL8abLM-rEpsqk3e5L0WdYUlujFGYWfoq497Q
+ scenes-app-signals-scratchpadpanel--load-failed--light:
+ hash: v1.k794b7964.ffa944efb6cbfe790e3e4b81971b09e2b70a3f810a057ddbf9e0ab541511efa5.AugMPKirqTsKfztoO6bkLA5-oT5goG47gBL3_G-MlWg
+ scenes-app-signals-scratchpadpanel--loading--dark:
+ hash: v1.k794b7964.bf0e49b2d071940a2b20ce3a08bb9db662eae8d055576a16ead4842794986133.wVa3Ngc_fO3A8YWqMPWF0nBslxYzbRAmU_Blam_hvIM
+ scenes-app-signals-scratchpadpanel--loading--light:
+ hash: v1.k794b7964.e67c1f1149a4cd37f8165a06cf9aa352e9384b65644acd538f881aa9032c8b49.SWfCcO3IvrnZ3n9VZmWwU3-zXiFJefSUazaw31eAi2w
+ scenes-app-signals-scratchpadpanel--loading-narrow--dark:
+ hash: v1.k794b7964.ba0f5af07c7d23506fc865211f48bc4fa2f96bd526ffe03a1a80090c0ab632be.kW3UZeQH5dDe9CyKpRnah974s7h5bvlo_hjLd3qIUHY
+ scenes-app-signals-scratchpadpanel--loading-narrow--light:
+ hash: v1.k794b7964.2089d8efb78a40aaddb8d37ff93ead347923ff58d7c363198b0379966e87ddbf.P0eRt5acCTA7bEHsaUhQz0gZsTHQ3LKOkRIKWK0pAFA
+ scenes-app-signals-scratchpadpanel--populated--dark:
+ hash: v1.k794b7964.bfd0c162a86b4d5cb791aeeccbce4cffbc8bba8cda552422e59952acccd07f60.kvevtGBCL85JSg8rTwP7WFgbLX1vrI0jRLHYujzom_E
+ scenes-app-signals-scratchpadpanel--populated--light:
+ hash: v1.k794b7964.cec7282f50a3008e568390aa0586896e28aedf708c373dc4c8a56c4df35f1554.kW7Q1--BbWardnN9D41YcyZphPUiY660og1cvQKWNmY
+ scenes-app-signals-scratchpadpanel--populated-narrow--dark:
+ hash: v1.k794b7964.6778108ade1085efcddf4ffe0b16a297e741e790672a3b33bc5d986f28a21ab2.i3oD4nY4Kcn08ehCHaLXHi7UVGVBK6MvVyfBqq-sJ8s
+ scenes-app-signals-scratchpadpanel--populated-narrow--light:
+ hash: v1.k794b7964.d816589bb55d55a5f400231ca5e2a0cd6b5a64ce1beb6e78287eca1c3b96e455.2bMTo4YcmA5wtKhveMZguqN_MUW1x_sYovK_8HWwfWs
scenes-app-stamphog-digests--digests-list--dark:
hash: v1.k794b7964.28fbaad98ddd90b171e6774057e8e9656af77e67fd0b5d462235a1d063c1777c.6E_uVxcZxkBaFZgqKmXAg4njrs4xCTiNBGWAUNg9GT0
scenes-app-stamphog-digests--digests-list--light:
diff --git a/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx b/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx
index aeb1aa4336a1..9f5734d7a357 100644
--- a/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx
+++ b/products/signals/frontend/inbox/components/scratchpad/ScratchpadEntryCard.tsx
@@ -1,5 +1,4 @@
import { useActions, useValues } from 'kea'
-import { type ComponentProps } from 'react'
import { IconChevronDown, IconClock } from '@posthog/icons'
import { LemonTag, Link } from '@posthog/lemon-ui'
@@ -13,35 +12,13 @@ import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api
import { scratchpadLogic } from '../../logics/scratchpadLogic'
import { scratchpadEntryBody, scratchpadEntryTitle } from '../../utils/scoutMemoryPresentation'
import { stripScoutPrefix } from '../../utils/scoutRunsWindow'
-
-type LemonTagType = ComponentProps<typeof LemonTag>['type']
-
-// The key prefix (everything before the first colon) encodes the note's *kind* — what the scout
-// was doing when it wrote it. Surface it as a colored tag so the list scans at a glance.
-const KIND_TAG_TYPE: Record<string, LemonTagType> = {
- pattern: 'highlight',
- dedupe: 'muted',
- noise: 'muted',
- baseline: 'success',
- watch: 'warning',
- watchlist: 'warning',
- coverage: 'completion',
- emerging: 'primary',
- explore: 'option',
- tags: 'option',
- recheck: 'caution',
-}
-
-function splitKey(key: string): { kind: string | null; body: string } {
- const idx = key.indexOf(':')
- return idx > 0 ? { kind: key.slice(0, idx), body: key.slice(idx + 1) } : { kind: null, body: key }
-}
+import { KIND_TAG_TYPE, scratchpadKindOf } from '../../utils/scratchpadKeys'
/**
- * One scratchpad entry the scout fleet has written about this project. Shares the collapse/expand
- * grammar of the scout emission cards: a header (chevron · kind · key · updated time) that stays
- * visible, a 2-line raw-text preview when collapsed, the full body plus an attribution footer
- * (which scout created it, when, and how long it's been carried forward) when open.
+ * One scratchpad entry, as the scout page's memory panel shows it. Shares the collapse/expand
+ * grammar of the scout emission cards: a header (chevron · kind · key · expiry · updated time) that
+ * stays visible, a 2-line preview when collapsed, the full body plus an attribution footer (which
+ * scout created it, when, and how long it's been carried forward) when open.
*
* The list only carries previews, so a long 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.
@@ -49,6 +26,8 @@ function splitKey(key: string): { kind: string | null; body: string } {
* 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.
+ *
+ * The fleet-wide panel uses a ledger table instead; this card is the compact per-scout shape.
*/
export function ScratchpadEntryCard({
entry,
@@ -65,7 +44,8 @@ export function ScratchpadEntryCard({
// `hasOwn` guards against a key like `constructor` resolving to an inherited prototype value.
const content = Object.hasOwn(fullContentByKey, entry.key) ? fullContentByKey[entry.key] : entry.content
- const { kind, body } = splitKey(entry.key)
+ const kind = scratchpadKindOf(entry.key)
+ const body = kind ? entry.key.slice(kind.length + 1) : 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.
@@ -100,6 +80,13 @@ export function ScratchpadEntryCard({
<span className="truncate font-mono text-xs text-primary">{body}</span>
)}
<span className="flex-1" />
+ {/* Most memories are durable, so an expiry is the exception worth calling out on the
+ row itself — a memory about to lapse should not look identical to one that holds. */}
+ {entry.expires_at && (
+ <span className="whitespace-nowrap text-[11px] text-warning">
+ exp {dayjs(entry.expires_at).format('D MMM')}
+ </span>
+ )}
{entry.updated_at && (
<span className="flex items-center gap-1 whitespace-nowrap text-[11px] text-muted">
<IconClock className="size-3" />
@@ -129,9 +116,11 @@ export function ScratchpadEntryCard({
{maintainedDays >= 1 && (
<span>· carried forward {maintainedDays === 1 ? '1 day' : `${maintainedDays} days`}</span>
)}
- {/* Most memories are durable, so an expiry is the exception worth calling out —
- without it a reader can't tell why an entry they remember has stopped showing up. */}
- {entry.expires_at && <span>· expires {humanFriendlyDetailedTime(entry.expires_at)}</span>}
+ {entry.expires_at ? (
+ <span>· expires {humanFriendlyDetailedTime(entry.expires_at)}</span>
+ ) : (
+ <span>· durable, no expiry</span>
+ )}
<span className="flex-1" />
{(scoutName || entry.created_by_run_id) && (
<span className="shrink-0">
diff --git a/products/signals/frontend/inbox/components/scratchpad/ScratchpadLedger.tsx b/products/signals/frontend/inbox/components/scratchpad/ScratchpadLedger.tsx
new file mode 100644
index 000000000000..754205ecc49d
--- /dev/null
+++ b/products/signals/frontend/inbox/components/scratchpad/ScratchpadLedger.tsx
@@ -0,0 +1,272 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonSkeleton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import type { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { urls } from 'scenes/urls'
+
+import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { SCRATCHPAD_PAGE_SIZE, scratchpadLogic } from '../../logics/scratchpadLogic'
+import { PIPELINE_WRITER_PREFIX, isPipelineWriter, stripScoutPrefix } from '../../utils/scoutRunsWindow'
+import { KIND_TAG_TYPE, isReportUuid, scratchpadKindOf, scratchpadTopicOf } from '../../utils/scratchpadKeys'
+
+// Below 52rem the six columns stop fitting, so every row collapses into one stacked cell. Broken
+// on the container, not the viewport: the panel gets about 520 px once the nav and a side panel
+// are open, which no viewport breakpoint ever reports. The variants are spelled out on each column
+// rather than built from a constant, because Tailwind only emits a class it can read in the source.
+const WIDE_ONLY = '@max-[52rem]/ledger:hidden'
+const NARROW_ONLY = 'hidden @max-[52rem]/ledger:table-cell'
+
+/**
+ * The fleet's memory as a dense, newest-first ledger: one row per entry, every signal as a column,
+ * and the full note as an expandable body. Reading a thousand cards top to bottom was the old
+ * shape; this one answers "what has the fleet learned about X" and "what did scout Y write".
+ */
+export function ScratchpadLedger(): JSX.Element {
+ const { filteredEntries, expandedKeys, reportTitles } = useValues(scratchpadLogic)
+ const { toggleEntry } = useActions(scratchpadLogic)
+
+ const columns: LemonTableColumns<ScratchpadEntryApi> = [
+ {
+ title: 'Updated',
+ key: 'updated',
+ className: `${WIDE_ONLY} w-32`,
+ render: (_, entry) => (entry.updated_at ? <TZLabel time={entry.updated_at} className="text-xs" /> : null),
+ },
+ {
+ title: 'Scout',
+ key: 'scout',
+ className: `${WIDE_ONLY} max-w-40`,
+ render: (_, entry) => <ScoutCell skillName={entry.created_by_skill} />,
+ },
+ {
+ title: 'Kind',
+ key: 'kind',
+ className: `${WIDE_ONLY} w-24`,
+ render: (_, entry) => <KindCell entryKey={entry.key} />,
+ },
+ {
+ title: 'Key',
+ key: 'key',
+ className: `${WIDE_ONLY} max-w-64`,
+ render: (_, entry) => <KeyCell entry={entry} reportTitles={reportTitles} />,
+ },
+ {
+ title: 'Note',
+ key: 'note',
+ className: WIDE_ONLY,
+ render: (_, entry) => <NotePreview content={entry.content} />,
+ },
+ {
+ title: 'Carried',
+ key: 'carried',
+ className: `${WIDE_ONLY} w-24 text-right`,
+ render: (_, entry) => <CarriedCell entry={entry} />,
+ },
+ {
+ title: 'Entry',
+ key: 'stacked',
+ className: NARROW_ONLY,
+ render: (_, entry) => <StackedCell entry={entry} reportTitles={reportTitles} />,
+ },
+ ]
+
+ return (
+ <div className="@container/ledger">
+ <LemonTable
+ dataSource={filteredEntries ?? []}
+ columns={columns}
+ rowKey="key"
+ size="small"
+ pagination={{ pageSize: SCRATCHPAD_PAGE_SIZE }}
+ expandable={{
+ // Expansion lives in the logic, not the table: the full body is fetched on
+ // expand, and the scout page's memory panel shares that cache.
+ isRowExpanded: (entry) => expandedKeys.includes(entry.key),
+ onRowExpand: (entry) => toggleEntry(entry.key),
+ onRowCollapse: (entry) => toggleEntry(entry.key),
+ expandedRowRender: (entry) => <ExpandedEntry entry={entry} />,
+ }}
+ />
+ </div>
+ )
+}
+
+// Pipeline stages write to the scratchpad too. They are not scouts and have no scout page, so the
+// Scout column names the stage and says which it is rather than linking nowhere.
+function ScoutCell({ skillName }: { skillName: string | null | undefined }): JSX.Element {
+ if (!skillName) {
+ return <span className="text-xs text-muted">—</span>
+ }
+ if (isPipelineWriter(skillName)) {
+ return (
+ <span className="truncate text-xs text-muted">
+ {skillName.slice(PIPELINE_WRITER_PREFIX.length)} (pipeline)
+ </span>
+ )
+ }
+ return (
+ <Link to={urls.inboxScout(skillName)} subtle className="truncate text-xs">
+ {stripScoutPrefix(skillName)}
+ </Link>
+ )
+}
+
+function KindCell({ entryKey }: { entryKey: string }): JSX.Element {
+ const kind = scratchpadKindOf(entryKey)
+ if (!kind) {
+ return <span className="text-xs text-muted">—</span>
+ }
+ return (
+ <LemonTag type={KIND_TAG_TYPE[kind] ?? 'muted'} size="small">
+ {kind}
+ </LemonTag>
+ )
+}
+
+/**
+ * The key, or the report it belongs to. Scouts namespace their per-report bookkeeping by report
+ * UUID, and a raw UUID tells a reader nothing — so once the title is resolved the row names the
+ * report and links to it, and falls back to the shortened UUID while it is not.
+ */
+function KeyCell({
+ entry,
+ reportTitles,
+}: {
+ entry: ScratchpadEntryApi
+ reportTitles: Record<string, string | null>
+}): JSX.Element {
+ const topic = scratchpadTopicOf(entry.key)
+ if (topic && isReportUuid(topic)) {
+ const title = reportTitles[topic]
+ return (
+ <Tooltip title={entry.key}>
+ <Link to={urls.inboxReport('reports', topic)} subtle className="truncate text-xs">
+ {/* Enough of the UUID to tell two apart while the title is loading, or gone. */}
+ Report: {title || topic.slice(0, 8)}
+ </Link>
+ </Tooltip>
+ )
+ }
+ return (
+ <Tooltip title={entry.key}>
+ <span className="block truncate font-mono text-xs text-primary">{entry.key}</span>
+ </Tooltip>
+ )
+}
+
+function NotePreview({ content }: { content: string | null | undefined }): JSX.Element {
+ if (!content) {
+ return <span className="text-xs italic text-muted">No content.</span>
+ }
+ return (
+ <LemonMarkdown lowKeyHeadings disableImages="all" className="line-clamp-1 text-xs [&_*]:inline [&_*]:text-xs">
+ {content}
+ </LemonMarkdown>
+ )
+}
+
+/**
+ * Days the entry has been carried forward — a large number means the fleet keeps re-touching this
+ * learning rather than deriving it again. An expiry replaces it, because a memory about to lapse is
+ * the more urgent thing to know and the row has one slot.
+ */
+function CarriedCell({ entry }: { entry: ScratchpadEntryApi }): JSX.Element {
+ if (entry.expires_at) {
+ return (
+ <Tooltip title={`Expires ${dayjs(entry.expires_at).format('D MMM YYYY, h:mm A')}`}>
+ <span className="whitespace-nowrap text-xs text-warning">
+ exp {dayjs(entry.expires_at).format('D MMM')}
+ </span>
+ </Tooltip>
+ )
+ }
+ const days = carriedDays(entry)
+ return (
+ <span className="whitespace-nowrap text-xs text-muted">
+ {days === null ? '—' : days < 1 ? 'new' : `${days} d`}
+ </span>
+ )
+}
+
+/** Every column's data in one cell, for a panel too narrow to hold six of them. */
+function StackedCell({
+ entry,
+ reportTitles,
+}: {
+ entry: ScratchpadEntryApi
+ reportTitles: Record<string, string | null>
+}): JSX.Element {
+ return (
+ <div className="flex min-w-0 flex-col gap-1 py-0.5">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ {entry.updated_at && <TZLabel time={entry.updated_at} className="text-xs text-muted" />}
+ <ScoutCell skillName={entry.created_by_skill} />
+ <KindCell entryKey={entry.key} />
+ <span className="flex-1" />
+ <CarriedCell entry={entry} />
+ </div>
+ <KeyCell entry={entry} reportTitles={reportTitles} />
+ <NotePreview content={entry.content} />
+ </div>
+ )
+}
+
+/**
+ * The open row: the note as its author wrote it (markdown, not the raw markup the cards showed),
+ * plus where it came from and how long it has held. The list carries previews only, so a long
+ * body arrives after the expand — until it lands the preview stays on screen under a skeleton.
+ */
+function ExpandedEntry({ entry }: { entry: ScratchpadEntryApi }): JSX.Element {
+ const { fullContentByKey, loadingContentKeys } = useValues(scratchpadLogic)
+
+ // `hasOwn` guards against a key like `constructor` resolving to an inherited prototype value.
+ const content = Object.hasOwn(fullContentByKey, entry.key) ? fullContentByKey[entry.key] : entry.content
+ const isLoadingContent = loadingContentKeys.includes(entry.key)
+ const days = carriedDays(entry)
+
+ return (
+ <div className="flex flex-col gap-2 px-2 py-2">
+ {content ? (
+ <LemonMarkdown lowKeyHeadings disableImages="all" className="text-xs">
+ {content}
+ </LemonMarkdown>
+ ) : (
+ <span className="text-xs italic text-muted">No content.</span>
+ )}
+ {isLoadingContent && <LemonSkeleton className="h-4 w-2/3" />}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t pt-2 text-xs text-tertiary">
+ {entry.created_at && (
+ <span>
+ Created <TZLabel time={entry.created_at} className="text-xs" />
+ </span>
+ )}
+ {days !== null && days >= 1 && <span>Carried forward {days === 1 ? '1 day' : `${days} days`}</span>}
+ {entry.expires_at ? (
+ <span className="text-warning">
+ Expires <TZLabel time={entry.expires_at} className="text-xs" />
+ </span>
+ ) : (
+ <span>Durable, no expiry</span>
+ )}
+ <span className="flex-1" />
+ {entry.created_by_run_url && (
+ <Link to={entry.created_by_run_url} className="shrink-0">
+ Open the run that created it
+ </Link>
+ )}
+ </div>
+ </div>
+ )
+}
+
+function carriedDays(entry: ScratchpadEntryApi): number | null {
+ if (!entry.created_at || !entry.updated_at) {
+ return null
+ }
+ return dayjs(entry.updated_at).diff(dayjs(entry.created_at), 'day')
+}
diff --git a/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.stories.tsx b/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.stories.tsx
new file mode 100644
index 000000000000..8b0c7c0f9929
--- /dev/null
+++ b/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.stories.tsx
@@ -0,0 +1,168 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { useEffect } from 'react'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { scratchpadLogic } from '../../logics/scratchpadLogic'
+import { ScratchpadPanel } from './ScratchpadPanel'
+
+const SCRATCHPAD_URL = '/api/projects/:team_id/signals/scout/scratchpad/'
+const REPORTS_URL = '/api/projects/:team_id/signals/reports/:id/'
+const REPORT_ID = '01a0918c-5f5f-74c4-b539-c634a8cb990a'
+
+// The panel gets about 520 px once the nav and a side panel are open. That is the width the
+// stacked layout exists for, so it gets its own story rather than a note in a review.
+const NARROW_WIDTH = 520
+
+function entry(overrides: Partial<ScratchpadEntryApi> & { key: string }): ScratchpadEntryApi {
+ return {
+ content: '',
+ created_at: '2026-07-31T09:00:00Z',
+ updated_at: '2026-09-11T17:15:00Z',
+ expires_at: null,
+ created_by_skill: null,
+ created_by_run_id: null,
+ created_by_run_url: null,
+ ...overrides,
+ } as ScratchpadEntryApi
+}
+
+const ENTRIES: ScratchpadEntryApi[] = [
+ entry({
+ key: 'pattern:apm:p95-regression-window',
+ created_by_skill: 'signals-scout-apm',
+ content:
+ 'Regressions on the query endpoint show up first in the **15-minute p95**, not p50. Compare against the same weekday last week, not yesterday.\n\n- Monday mornings carry a warm-cache dip that reads as a regression against Sunday.\n- Ruled out: a 7-day rolling mean. It smooths the weekday shape away.',
+ }),
+ entry({
+ key: `judged:${REPORT_ID}`,
+ created_by_skill: 'signals-scout-inbox-validation',
+ updated_at: '2026-09-11T17:14:00Z',
+ created_at: '2026-09-11T17:14:00Z',
+ content: 'Passed. The summary names an internal dashboard, which is fine for an internal surface.',
+ }),
+ entry({
+ key: 'followup:billing_spikes:34302',
+ created_by_skill: 'signals-scout-customer-analytics-billing-and-usage',
+ updated_at: '2026-09-11T17:12:00Z',
+ created_at: '2026-09-11T17:12:00Z',
+ expires_at: '2026-09-21T00:00:00Z',
+ content: 'Pending. Validate after the next billing period closes, once a second month of data exists.',
+ }),
+ entry({
+ key: 'baseline:slo_monitoring:export-error-rate',
+ created_by_skill: 'signals-scout-health-checks',
+ updated_at: '2026-09-11T17:09:00Z',
+ created_at: '2026-07-12T09:00:00Z',
+ content: 'Weekday export error rate sits at 0.4% of jobs. A weekend reading is not comparable.',
+ }),
+ entry({
+ key: 'noise:logs:redis-timeout-startup',
+ created_by_skill: 'signals-scout-logs',
+ updated_at: '2026-09-11T17:04:00Z',
+ created_at: '2026-08-14T09:00:00Z',
+ content: 'The Redis timeout burst on pod start is expected. It clears once the connection pool warms.',
+ }),
+ entry({
+ key: 'pattern:impl:reports-research',
+ created_by_skill: 'pipeline:report-research',
+ updated_at: '2026-09-11T16:47:00Z',
+ created_at: '2026-06-02T09:00:00Z',
+ content: 'Research that opens with the linked issue reads faster than research that opens with the query.',
+ }),
+]
+
+type Story = StoryObj<typeof ScratchpadPanel>
+
+const meta: Meta<typeof ScratchpadPanel> = {
+ component: ScratchpadPanel,
+ title: 'Scenes-App/Signals/ScratchpadPanel',
+ tags: ['autodocs'],
+ parameters: { mockDate: '2026-09-11T20:15:00Z' },
+}
+export default meta
+
+function Panel({ width }: { width?: number }): JSX.Element {
+ return (
+ <div style={{ width: width ?? '100%' }}>
+ <ScratchpadPanel />
+ </div>
+ )
+}
+
+export const Populated: Story = {
+ render: () => {
+ useStorybookMocks({
+ get: {
+ [SCRATCHPAD_URL]: () => [200, ENTRIES],
+ [REPORTS_URL]: () => [200, { id: REPORT_ID, title: 'Export error rate doubled on Tuesday' }],
+ },
+ })
+ return <Panel />
+ },
+}
+
+export const PopulatedNarrow: Story = {
+ render: () => {
+ useStorybookMocks({
+ get: {
+ [SCRATCHPAD_URL]: () => [200, ENTRIES],
+ [REPORTS_URL]: () => [200, { id: REPORT_ID, title: 'Export error rate doubled on Tuesday' }],
+ },
+ })
+ return <Panel width={NARROW_WIDTH} />
+ },
+}
+
+export const Loading: Story = {
+ parameters: {
+ testOptions: {
+ waitForLoadersToDisappear: false,
+ waitForSelector: '.LemonSkeleton',
+ },
+ },
+ render: () => {
+ useStorybookMocks({ get: { [SCRATCHPAD_URL]: () => new Promise(() => {}) } })
+ return <Panel />
+ },
+}
+
+export const LoadingNarrow: Story = {
+ parameters: Loading.parameters,
+ render: () => {
+ useStorybookMocks({ get: { [SCRATCHPAD_URL]: () => new Promise(() => {}) } })
+ return <Panel width={NARROW_WIDTH} />
+ },
+}
+
+export const Empty: Story = {
+ render: () => {
+ useStorybookMocks({ get: { [SCRATCHPAD_URL]: () => [200, []] } })
+ return <Panel />
+ },
+}
+
+/** A search nothing matches: the ledger is empty but the memory is not, so the state offers a way back. */
+export const FilteredEmpty: Story = {
+ render: () => {
+ useStorybookMocks({
+ get: {
+ [SCRATCHPAD_URL]: ({ request }) => [200, new URL(request.url).searchParams.get('text') ? [] : ENTRIES],
+ [REPORTS_URL]: () => [200, { id: REPORT_ID, title: 'Export error rate doubled on Tuesday' }],
+ },
+ })
+ useEffect(() => {
+ scratchpadLogic.findMounted()?.actions.setSearchText('nothing in memory matches this')
+ }, [])
+ return <Panel />
+ },
+}
+
+export const LoadFailed: Story = {
+ render: () => {
+ useStorybookMocks({ get: { [SCRATCHPAD_URL]: () => [500, {}] } })
+ return <Panel />
+ },
+}
diff --git a/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.tsx b/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.tsx
index 7763afba6ce3..2b4270787ebc 100644
--- a/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.tsx
+++ b/products/signals/frontend/inbox/components/scratchpad/ScratchpadPanel.tsx
@@ -1,18 +1,39 @@
import { useActions, useValues } from 'kea'
-import { IconChevronDown, IconClock, IconNotebook, IconStack } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonSegmentedButton, LemonSkeleton } from '@posthog/lemon-ui'
+import { IconNotebook } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonInput,
+ LemonInputSelect,
+ LemonSelect,
+ LemonSkeleton,
+ LemonSwitch,
+} from '@posthog/lemon-ui'
-import { TZLabel } from 'lib/components/TZLabel'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { pluralize } from 'lib/utils/strings'
+import type { ScratchpadFacet, ScratchpadTimeFilter } from '../../logics/scratchpadLogic'
import { scratchpadLogic } from '../../logics/scratchpadLogic'
-import { ScratchpadEntryCard } from './ScratchpadEntryCard'
+import { stripScoutPrefix } from '../../utils/scoutRunsWindow'
+import { BOOKKEEPING_KINDS } from '../../utils/scratchpadKeys'
+import { ScratchpadLedger } from './ScratchpadLedger'
+
+const TIME_OPTIONS: { value: ScratchpadTimeFilter; label: string }[] = [
+ { value: 'window', label: 'Loaded window' },
+ { value: '1h', label: 'Last hour' },
+ { value: '24h', label: 'Last 24 hours' },
+ { value: '7d', label: 'Last 7 days' },
+ { value: '30d', label: 'Last 30 days' },
+]
+
+const HIDE_BOOKKEEPING_TOOLTIP = `Drops the notes scouts write for themselves: ${[...BOOKKEEPING_KINDS].join(', ')}.`
/**
- * Browse + search surface for the scout fleet's scratchpad (`SignalScratchpad`). Frames what the
- * scratchpad is up top (the context scouts jot down + how much has accumulated), then lets the user
- * read it newest-first or clustered by topic, and search it via the endpoint's ILIKE.
+ * Browse + filter surface for the scout fleet's scratchpad (`SignalScratchpad`). Frames what the
+ * scratchpad is up top, says how much of it is loaded and over what span, then hands the rows to a
+ * ledger the reader can narrow by scout, kind, topic and time.
*
* Read-only: the harness writes scratchpad entries on internal scope; humans inspect them here.
*/
@@ -24,14 +45,37 @@ export function ScratchpadPanel(): JSX.Element {
searchResultsLoading,
searchFailed,
visibleEntries,
+ filteredEntries,
totalCount,
- lastUpdatedAt,
- groups,
+ loadedSpanLabel,
+ scoutFacets,
+ kindFacets,
+ topicFacets,
+ windowStats,
+ visibleBookkeepingCount,
+ hasActiveFilters,
+ canLoadOlderEntries,
+ olderEntriesFailed,
+ olderEntriesLoading,
searchText,
- grouping,
- expandedNamespaces,
+ scoutFilter,
+ kindFilter,
+ topicFilter,
+ timeFilter,
+ hideBookkeeping,
} = useValues(scratchpadLogic)
- const { setSearchText, setGrouping, toggleNamespace, loadEntries, loadSearchResults } = useActions(scratchpadLogic)
+ const {
+ setSearchText,
+ setScoutFilter,
+ setKindFilter,
+ setTopicFilter,
+ setTimeFilter,
+ setHideBookkeeping,
+ clearFilters,
+ loadEntries,
+ loadSearchResults,
+ loadOlderEntries,
+ } = useActions(scratchpadLogic)
const isSearching = searchText.trim().length > 0
// The window loads once on mount; a search loads its own result set on top of it. Either
@@ -43,132 +87,192 @@ export function ScratchpadPanel(): JSX.Element {
return (
<div className="flex flex-col gap-4 px-4 py-3">
- <ScratchpadHeader totalCount={totalCount} lastUpdatedAt={lastUpdatedAt} loading={isInitialLoad} />
+ <ScratchpadHeader
+ totalCount={totalCount}
+ loadedSpanLabel={loadedSpanLabel}
+ scoutCount={windowStats.scouts}
+ topicCount={windowStats.topics}
+ expiringSoonCount={windowStats.expiringSoon}
+ loading={isInitialLoad}
+ />
- <div className="flex flex-wrap items-center gap-2">
- <LemonInput
- type="search"
- placeholder="Search the scratchpad…"
- value={searchText}
- onChange={setSearchText}
- className="flex-1 min-w-[12rem]"
- allowClear
- />
- <LemonSegmentedButton
- size="small"
- value={grouping}
- onChange={setGrouping}
- options={[
- { value: 'recent', label: 'Recent', icon: <IconClock /> },
- { value: 'topic', label: 'By topic', icon: <IconStack /> },
- ]}
- />
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonInput
+ type="search"
+ placeholder="Search keys and notes…"
+ value={searchText}
+ onChange={setSearchText}
+ className="min-w-[12rem] flex-1"
+ allowClear
+ />
+ <FacetSelect
+ placeholder="Scout: all"
+ facets={scoutFacets}
+ value={scoutFilter}
+ onChange={setScoutFilter}
+ labelOf={stripScoutPrefix}
+ />
+ <FacetSelect
+ placeholder="Kind: any"
+ facets={kindFacets}
+ value={kindFilter}
+ onChange={setKindFilter}
+ />
+ <FacetSelect
+ placeholder="Topic: any"
+ facets={topicFacets}
+ value={topicFilter}
+ onChange={setTopicFilter}
+ />
+ <LemonSelect size="small" value={timeFilter} onChange={setTimeFilter} options={TIME_OPTIONS} />
+ </div>
+ <Tooltip title={HIDE_BOOKKEEPING_TOOLTIP}>
+ <LemonSwitch
+ checked={hideBookkeeping}
+ onChange={setHideBookkeeping}
+ label="Hide bookkeeping"
+ size="small"
+ className="w-fit"
+ />
+ </Tooltip>
</div>
{isInitialLoad ? (
- <div className="flex flex-col gap-2">
- <ScratchpadEntryCardSkeleton />
- <ScratchpadEntryCardSkeleton />
- <ScratchpadEntryCardSkeleton />
- </div>
- ) : listFailed && (!visibleEntries || visibleEntries.length === 0) ? (
+ <LemonSkeleton className="h-64 w-full rounded" />
+ ) : listFailed && (!filteredEntries || filteredEntries.length === 0) ? (
<ScratchpadErrorState onRetry={() => retry()} loading={retryLoading} />
- ) : !visibleEntries || visibleEntries.length === 0 ? (
- <ScratchpadEmptyState isSearching={isSearching} />
- ) : grouping === 'topic' ? (
- <div className="flex flex-col gap-3">
- {groups.map((group) => {
- // Collapsed by default for a high-level scan; a search forces every matching
- // topic open so results stay visible without a click.
- const isExpanded = isSearching || expandedNamespaces.includes(group.namespace)
- return (
- <div key={group.namespace} className="flex flex-col gap-2">
- <button
- type="button"
- onClick={() => toggleNamespace(group.namespace)}
- className="flex items-center gap-2 text-left"
- aria-expanded={isExpanded}
- >
- <IconChevronDown
- className={`size-4 shrink-0 text-muted transition-transform ${
- isExpanded ? '' : '-rotate-90'
- }`}
- />
- <span className="text-xs font-medium uppercase tracking-wide text-default">
- {group.label}
- </span>
- <span className="text-[11px] text-muted">
- {pluralize(group.entries.length, 'entry', 'entries')}
- </span>
- </button>
- {isExpanded &&
- group.entries.map((entry) => <ScratchpadEntryCard key={entry.key} entry={entry} />)}
- </div>
- )
- })}
- </div>
+ ) : !filteredEntries || filteredEntries.length === 0 ? (
+ <ScratchpadEmptyState
+ hasActiveFilters={hasActiveFilters}
+ loadedSpanLabel={loadedSpanLabel}
+ onClearFilters={clearFilters}
+ />
) : (
- <div className="flex flex-col gap-2">
- {visibleEntries.map((entry) => (
- <ScratchpadEntryCard key={entry.key} entry={entry} />
- ))}
- </div>
+ <>
+ {listFailed && (
+ // A reload rejected while a previous result set is still on screen, so these
+ // rows answer the search or the span the reader had before. Say so, rather
+ // than let the ledger assert they match the controls above.
+ <LemonBanner
+ type="warning"
+ action={{ children: 'Retry', onClick: () => retry(), loading: retryLoading }}
+ >
+ Couldn't refresh the list. These rows may not match the filters above.
+ </LemonBanner>
+ )}
+ <ScratchpadLedger />
+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
+ <span>
+ Showing the newest {pluralize(filteredEntries.length, 'entry', 'entries')}.
+ {canLoadOlderEntries ? ' Older memory is still there.' : ''}
+ </span>
+ {canLoadOlderEntries && (
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ onClick={() => loadOlderEntries()}
+ loading={olderEntriesLoading}
+ >
+ Load older entries
+ </LemonButton>
+ )}
+ {canLoadOlderEntries && olderEntriesFailed && (
+ <span className="text-danger">Couldn't load them. Try again.</span>
+ )}
+ <span className="flex-1" />
+ {visibleBookkeepingCount > 0 && !hideBookkeeping && (
+ <span>{visibleBookkeepingCount} of these are bookkeeping</span>
+ )}
+ </div>
+ </>
)}
</div>
)
}
-function ScratchpadEntryCardSkeleton(): JSX.Element {
+/** One multi-select over a facet of the loaded window, each option carrying how many rows match. */
+function FacetSelect({
+ placeholder,
+ facets,
+ value,
+ onChange,
+ labelOf,
+}: {
+ placeholder: string
+ facets: ScratchpadFacet[]
+ value: string[]
+ onChange: (value: string[]) => void
+ labelOf?: (value: string) => string
+}): JSX.Element {
return (
- <div className="flex h-20 flex-col gap-3 rounded border border-primary bg-bg-light px-3 py-2">
- <div className="flex items-center gap-2">
- <LemonSkeleton className="size-4 shrink-0 rounded" />
- <LemonSkeleton className="h-4 w-16 rounded" />
- <LemonSkeleton className="h-3 w-40 rounded" />
- <span className="flex-1" />
- <LemonSkeleton className="h-3 w-24 rounded" />
- </div>
- <div className="flex flex-col gap-1 pl-6">
- <LemonSkeleton className="h-3 w-full rounded" />
- <LemonSkeleton className="h-3 w-2/3 rounded" />
- </div>
+ // The select fills its parent, so the width it gets has to come from a wrapper.
+ <div className="w-44">
+ <LemonInputSelect
+ mode="multiple"
+ size="small"
+ placeholder={placeholder}
+ value={value}
+ onChange={onChange}
+ options={facets.map((facet) => ({
+ key: facet.value,
+ label: `${labelOf ? labelOf(facet.value) : facet.value} (${facet.count})`,
+ }))}
+ />
+ </div>
+ )
+}
+
+function Stat({ value, label, loading }: { value: string; label: string; loading: boolean }): JSX.Element {
+ return (
+ <div className="flex min-w-24 flex-col">
+ {loading ? (
+ <LemonSkeleton className="h-5 w-10 rounded" />
+ ) : (
+ <span className="text-base font-semibold tabular-nums text-default">{value}</span>
+ )}
+ <span className="text-xs text-muted">{label}</span>
</div>
)
}
function ScratchpadHeader({
totalCount,
- lastUpdatedAt,
+ loadedSpanLabel,
+ scoutCount,
+ topicCount,
+ expiringSoonCount,
loading,
}: {
totalCount: number | null
- lastUpdatedAt: string | null
+ loadedSpanLabel: string | null
+ scoutCount: number
+ topicCount: number
+ expiringSoonCount: number
loading: boolean
}): JSX.Element {
return (
- <div className="flex flex-col gap-1">
+ <div className="flex flex-col gap-2">
<div className="flex items-center gap-2">
<IconNotebook className="size-5 text-primary-3000" />
<span className="text-base font-semibold text-default">Scout scratchpad</span>
</div>
<p className="mb-0 text-sm text-secondary">
- Where your scouts jot down useful context as they scan your project — things they've classified, ruled
- out, or the vocabulary they've settled on. Browse it to see what they're picking up about your setup.
+ What your scouts have written down while scanning this project: patterns they trust, baselines they
+ settled on, things they ruled out, and the bookkeeping that keeps them from repeating themselves.
</p>
- <div className="flex min-h-4 items-center">
- {loading ? (
- <LemonSkeleton className="h-3 w-36 rounded" />
- ) : totalCount !== null && totalCount > 0 ? (
- <span className="text-xs text-muted">
- {pluralize(totalCount, 'entry', 'entries')}
- {lastUpdatedAt ? (
- <>
- {' · last updated '}
- <TZLabel time={lastUpdatedAt} />
- </>
- ) : null}
- </span>
- ) : null}
+ <div className="flex flex-wrap gap-x-6 gap-y-2">
+ {/* The count is what's loaded, not what exists: the endpoint caps at 1,000 newest-first,
+ which on a busy project is a few hours. Labelling it with the span it covers is what
+ stops it reading as the whole memory. */}
+ <Stat
+ value={totalCount === null ? '—' : String(totalCount)}
+ label={loadedSpanLabel ? `entries, ${loadedSpanLabel}` : 'entries loaded'}
+ loading={loading}
+ />
+ <Stat value={String(scoutCount)} label="scouts writing" loading={loading} />
+ <Stat value={String(topicCount)} label="topics" loading={loading} />
+ <Stat value={String(expiringSoonCount)} label="expiring soon" loading={loading} />
</div>
</div>
)
@@ -187,12 +291,30 @@ function ScratchpadErrorState({ onRetry, loading }: { onRetry: () => void; loadi
)
}
-function ScratchpadEmptyState({ isSearching }: { isSearching: boolean }): JSX.Element {
+function ScratchpadEmptyState({
+ hasActiveFilters,
+ loadedSpanLabel,
+ onClearFilters,
+}: {
+ hasActiveFilters: boolean
+ loadedSpanLabel: string | null
+ onClearFilters: () => void
+}): JSX.Element {
+ if (!hasActiveFilters) {
+ return (
+ <div className="rounded border border-dashed border-primary bg-bg-light px-4 py-8 text-center text-sm text-muted">
+ Your scouts haven't written anything down yet. As they scan your project, their entries show up here.
+ </div>
+ )
+ }
return (
- <div className="rounded border border-dashed border-primary bg-bg-light px-4 py-8 text-center text-sm text-muted">
- {isSearching
- ? 'No entries match your search.'
- : "Your scouts haven't written anything down yet. As they scan your project, their entries show up here."}
+ <div className="flex flex-col items-center gap-2 rounded border border-dashed border-primary bg-bg-light px-4 py-8 text-center text-sm text-muted">
+ <span>
+ No entries match. Clear the filters to see everything from the {loadedSpanLabel ?? 'loaded window'}.
+ </span>
+ <LemonButton type="secondary" size="small" onClick={onClearFilters}>
+ Clear filters
+ </LemonButton>
</div>
)
}
diff --git a/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts b/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts
index c46ec839790d..be8bbe60ed87 100644
--- a/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts
@@ -1,12 +1,21 @@
+import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'
+
/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */
import { expectLogic } from 'kea-test-utils'
+import { teamLogic } from 'scenes/teamLogic'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'
-import { SCRATCHPAD_FETCH_LIMIT, SCRATCHPAD_PREVIEW_CHARS, scratchpadLogic } from './scratchpadLogic'
+import {
+ SCRATCHPAD_FETCH_LIMIT,
+ SCRATCHPAD_PREVIEW_CHARS,
+ describeLoadedSpan,
+ scratchpadLogic,
+} from './scratchpadLogic'
const SCRATCHPAD_URL = '/api/projects/:team_id/signals/scout/scratchpad/'
@@ -166,6 +175,376 @@ describe('scratchpadLogic', () => {
expect(logic.values.recentlyLearnedCountCapped).toBe(false)
})
+ // Ledger filters narrow what is listed and nothing else. The roster's "learned" count and the
+ // scout page's memory panel read `entries`, so a filter that reached them would silently shrink
+ // numbers the reader never asked about.
+ it('combines the client-side filters and leaves the loaded window intact', async () => {
+ const rows = [
+ { ...entry('pattern:apm:p95', 'note'), created_by_skill: 'signals-scout-apm' },
+ { ...entry('baseline:apm:error-rate', 'note'), created_by_skill: 'signals-scout-apm' },
+ { ...entry('pattern:logs:redis', 'note'), created_by_skill: 'signals-scout-logs' },
+ { ...entry('dedupe:apm:34316', 'note'), created_by_skill: 'signals-scout-apm' },
+ ]
+ logic.actions.loadEntriesSuccess(rows)
+
+ logic.actions.setScoutFilter(['signals-scout-apm'])
+ expect(logic.values.filteredEntries?.map((e) => e.key)).toEqual([
+ 'pattern:apm:p95',
+ 'baseline:apm:error-rate',
+ 'dedupe:apm:34316',
+ ])
+
+ logic.actions.setKindFilter(['pattern', 'baseline'])
+ expect(logic.values.filteredEntries?.map((e) => e.key)).toEqual(['pattern:apm:p95', 'baseline:apm:error-rate'])
+ // The footer prints the bookkeeping count as a share of the listed rows, so a count taken
+ // before the facet filters can exceed the number of rows it describes.
+ expect(logic.values.visibleBookkeepingCount).toBe(0)
+
+ logic.actions.setTopicFilter(['logs'])
+ expect(logic.values.filteredEntries).toEqual([])
+ expect(logic.values.entries).toHaveLength(4)
+
+ logic.actions.clearFilters()
+ expect(logic.values.filteredEntries).toHaveLength(4)
+ expect(logic.values.hasActiveFilters).toBe(false)
+ })
+
+ // The span is the only filter the endpoint applies, so clearing has to refetch. Resetting the
+ // control alone leaves a narrowed response on screen with no filter shown, and an empty
+ // narrowed window then reads as a project whose scouts have written nothing.
+ it('refetches the full window when the filters are cleared', async () => {
+ logic.actions.setTimeFilter('1h')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(searchRequests.map((params) => params.get('date_from') !== null)).toEqual([true])
+
+ searchRequests = []
+ logic.actions.clearFilters()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(searchRequests.map((params) => params.get('date_from'))).toEqual([null])
+ })
+
+ // Report-pipeline stages write to this keyspace under a `pipeline:` identity. The ledger's
+ // Scout column already calls them what they are, so counting them as scouts would make the
+ // header claim more scouts than wrote.
+ it('leaves the pipeline writers out of the scouts stat', async () => {
+ logic.actions.loadEntriesSuccess([
+ { ...entry('pattern:apm:p95', 'note'), created_by_skill: 'signals-scout-apm' },
+ { ...entry('baseline:apm:error-rate', 'note'), created_by_skill: 'signals-scout-apm' },
+ { ...entry('judged:report-1', 'note'), created_by_skill: 'pipeline:report-research' },
+ { ...entry('watchlist:manual', 'note'), created_by_skill: null },
+ ])
+
+ expect(logic.values.windowStats.scouts).toBe(1)
+ })
+
+ // The bookkeeping kinds outnumber the durable knowledge, which is the whole reason the switch
+ // exists. A key whose prefix is not a known kind is a topic, not a kind, and must survive it.
+ it('drops only the bookkeeping kinds when the switch is on', async () => {
+ logic.actions.loadEntriesSuccess([
+ entry('pattern:apm:p95', 'note'),
+ entry('judged:report-1', 'note'),
+ entry('dedupe:apm:34316', 'note'),
+ entry('billing_spikes:34302', 'note'),
+ ])
+
+ logic.actions.setHideBookkeeping(true)
+ expect(logic.values.filteredEntries?.map((e) => e.key)).toEqual(['pattern:apm:p95', 'billing_spikes:34302'])
+ expect(logic.values.visibleBookkeepingCount).toBe(2)
+
+ logic.actions.setHideBookkeeping(false)
+ expect(logic.values.filteredEntries).toHaveLength(4)
+
+ // The switch counts towards `hasActiveFilters`, which is what renders the clear button, so
+ // a clear that spares it promises rows it does not bring back. A window of nothing but
+ // bookkeeping rows then renders the same empty state after every press.
+ logic.actions.setHideBookkeeping(true)
+ logic.actions.clearFilters()
+ expect(logic.values.hideBookkeeping).toBe(false)
+ expect(logic.values.filteredEntries).toHaveLength(4)
+ expect(logic.values.hasActiveFilters).toBe(false)
+ })
+
+ // kea-loaders leaves `entries` at its prior value on failure, so a failed reload keeps rows on
+ // screen that answer the span the reader had before. The flag is the only thing that can tell
+ // the panel to say so, instead of presenting those rows as the answer to the new span.
+ it('keeps the loaded rows and records the failure when a reload rejects', async () => {
+ logic.actions.loadEntriesSuccess([TRUNCATED, WHOLE])
+ useMocks({ get: { [SCRATCHPAD_URL]: () => [500, {}] } })
+
+ logic.actions.setTimeFilter('1h')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.loadFailed).toBe(true)
+ expect(logic.values.entries).toEqual([TRUNCATED, WHOLE])
+ expect(logic.values.filteredEntries).toHaveLength(2)
+ })
+
+ // A wider span is the slower read, so narrowing the span right after widening it is the order
+ // that lets the older response answer last. If it lands, the ledger and the header describe a
+ // span the select does not name, and re-picking that span fires nothing.
+ it('drops a window response that a newer span superseded', async () => {
+ const stale = entry('pattern:stale-span', 'note')
+ let narrowServed = (): void => {}
+ const narrowRequestServed = new Promise<void>((resolve) => {
+ narrowServed = resolve
+ })
+ let listRequests = 0
+ useMocks({
+ get: {
+ [SCRATCHPAD_URL]: async () => {
+ listRequests += 1
+ // The wide request answers only once the narrow one that superseded it has.
+ if (listRequests === 1) {
+ await narrowRequestServed
+ return [200, [stale]]
+ }
+ narrowServed()
+ return [200, [WHOLE]]
+ },
+ },
+ })
+
+ logic.actions.setTimeFilter('30d')
+ logic.actions.setTimeFilter('1h')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.entries).toEqual([WHOLE])
+ })
+
+ // Older pages walk the unfiltered window with a cursor, and a search is a separate one-shot
+ // read they never reach. A control offered during a search spends a page of up to a thousand
+ // rows the table cannot show, and moves the header counts while the listed rows stay put.
+ it('offers no older pages while a search is active', async () => {
+ logic.actions.loadEntriesSuccess(
+ Array.from({ length: SCRATCHPAD_FETCH_LIMIT }, (_, i) => entry(`pattern:${i}`, 'note'))
+ )
+ expect(logic.values.canLoadOlderEntries).toBe(true)
+
+ logic.actions.setSearchText('redis')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.canLoadOlderEntries).toBe(false)
+
+ logic.actions.setSearchText('')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.canLoadOlderEntries).toBe(true)
+ })
+
+ // A reload drops the walked pages, and the fresh first page has not yet said whether anything
+ // older is left. A control left live over that gap pages from the window that just went away.
+ it('retires the older-page control while the first page reloads', async () => {
+ logic.actions.loadEntriesSuccess(
+ Array.from({ length: SCRATCHPAD_FETCH_LIMIT }, (_, i) => entry(`pattern:${i}`, 'note'))
+ )
+ expect(logic.values.hasMoreOlderEntries).toBe(true)
+
+ logic.actions.loadEntries()
+ expect(logic.values.hasMoreOlderEntries).toBe(false)
+
+ // The fresh first page decides it again, and this one came back short.
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.hasMoreOlderEntries).toBe(false)
+ })
+
+ // A page read against a window that a reload replaced has nothing to attach to. Appending it
+ // files old rows under a new first page, and its dedupe set cannot see that page's keys, so a
+ // key can render twice in a table that keys rows by it.
+ it('drops an older page that answers after the first page reloaded', async () => {
+ const older = { ...entry('pattern:older', 'note'), updated_at: '2026-06-01T00:00:00Z' }
+ let firstPageServed = (): void => {}
+ const reloadServed = new Promise<void>((resolve) => {
+ firstPageServed = resolve
+ })
+ useMocks({
+ get: {
+ [SCRATCHPAD_URL]: async ({ request }) => {
+ const params = new URL(request.url).searchParams
+ // The walked page answers only once the reload that invalidated it has.
+ if (params.get('date_to')) {
+ await reloadServed
+ return [200, [older]]
+ }
+ firstPageServed()
+ return [200, [ALSO_TRUNCATED]]
+ },
+ },
+ })
+
+ logic.actions.loadEntriesSuccess([TRUNCATED, WHOLE])
+ logic.actions.loadOlderEntries()
+ logic.actions.loadEntries()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.windowEntries).toEqual([ALSO_TRUNCATED])
+ })
+
+ // The older-page request is the panel's heaviest, so a timeout or a 5xx is its likely end, and
+ // a page that succeeds can append nothing too once the dedupe drops it. Without a flag the
+ // spinner just stops, and the reader reads a failed press as an empty memory.
+ it('records a failed older page and clears the record on the retry', async () => {
+ logic.actions.loadEntriesSuccess(
+ Array.from({ length: SCRATCHPAD_FETCH_LIMIT }, (_, i) => entry(`pattern:${i}`, 'note'))
+ )
+ useMocks({ get: { [SCRATCHPAD_URL]: () => [500, {}] } })
+
+ logic.actions.loadOlderEntries()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.olderEntriesFailed).toBe(true)
+ expect(logic.values.olderEntriesLoading).toBe(false)
+ // The control stays, so the press can be repeated.
+ expect(logic.values.canLoadOlderEntries).toBe(true)
+
+ useMocks({ get: { [SCRATCHPAD_URL]: () => [200, []] } })
+ logic.actions.loadOlderEntries()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.olderEntriesFailed).toBe(false)
+ })
+
+ // Nothing older than the first page was reachable before: the endpoint caps at 1,000 rows and
+ // the panel only ever asked once. The `date_to` bound is exclusive, but rows can share a
+ // timestamp, so a page may still repeat a key already on screen.
+ it('walks the date_to cursor for older entries and drops keys already loaded', async () => {
+ const older = { ...entry('pattern:older', 'note'), updated_at: '2026-06-01T00:00:00Z' }
+ useMocks({
+ get: {
+ [SCRATCHPAD_URL]: ({ request }) => {
+ const params = new URL(request.url).searchParams
+ searchRequests.push(params)
+ return [200, params.get('date_to') ? [WHOLE, older] : [TRUNCATED, WHOLE]]
+ },
+ },
+ })
+ logic.actions.loadEntries()
+ await expectLogic(logic).toFinishAllListeners()
+ searchRequests = []
+
+ logic.actions.loadOlderEntries()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(searchRequests[0].get('date_to')).toEqual(WHOLE.updated_at)
+ expect(logic.values.olderEntries).toEqual([older])
+ expect(logic.values.windowEntries?.map((e) => e.key)).toEqual([TRUNCATED.key, WHOLE.key, older.key])
+ // A short page is the end of the memory, so the button goes away.
+ expect(logic.values.hasMoreOlderEntries).toBe(false)
+ // A fresh first page may already carry these rows, so the older pages are dropped with it.
+ logic.actions.loadEntries()
+ expect(logic.values.olderEntries).toEqual([])
+ })
+
+ // A key namespaced by a report UUID says nothing on its own, and the reports endpoint has no
+ // bulk-by-id filter, so each title is one request — resolved once and cached.
+ it('resolves report titles for UUID-namespaced keys exactly once', async () => {
+ const reportId = '01a0918c-5f5f-74c4-b539-c634a8cb990a'
+ let reportRequests = 0
+ useMocks({
+ get: {
+ [SCRATCHPAD_URL]: () => [200, [entry(`judged:${reportId}`, 'note')]],
+ '/api/projects/:team_id/signals/reports/:id/': () => {
+ reportRequests += 1
+ return [200, { id: reportId, title: 'Export error rate doubled' }]
+ },
+ },
+ })
+
+ logic.actions.loadEntries()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.reportTitles).toEqual({ [reportId]: 'Export error rate doubled' })
+ expect(reportRequests).toBe(1)
+ expect(logic.values.unresolvedReportIds).toEqual([])
+ })
+
+ // An id reaches `reportTitles` only when its response lands, so a pass that starts while
+ // another is in flight lists the same ids again. Two loads answering at different times is
+ // ordinary here, and the report detail read is one of the heaviest requests the product makes.
+ it('does not re-request a report title a pass is already fetching', async () => {
+ const reportId = '01a0918c-5f5f-74c4-b539-c634a8cb990a'
+ let reportRequests = 0
+ useMocks({
+ get: {
+ [SCRATCHPAD_URL]: () => [200, [entry(`judged:${reportId}`, 'note')]],
+ '/api/projects/:team_id/signals/reports/:id/': () => {
+ reportRequests += 1
+ return [200, { id: reportId, title: 'Export error rate doubled' }]
+ },
+ },
+ })
+
+ logic.actions.loadEntriesSuccess([entry(`judged:${reportId}`, 'note')])
+ // An older page landing while the first pass is still in flight starts the second one.
+ logic.actions.appendOlderEntries([], false)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(reportRequests).toBe(1)
+ expect(logic.values.reportTitles).toEqual({ [reportId]: 'Export error rate doubled' })
+ })
+
+ // A stored null asserts the report is gone and stops the key being asked for again, so a
+ // transient failure that stores one pins the row to its shortened UUID for the whole session.
+ // Only a 404 is terminal; anything else has to stay unresolved for a later pass to retry.
+ it.each([
+ [404, true],
+ [500, false],
+ ])('remembers a missing report title after status %s: %s', async (status, remembered) => {
+ const reportId = '01a0918c-5f5f-74c4-b539-c634a8cb990a'
+ useMocks({
+ get: {
+ [SCRATCHPAD_URL]: () => [200, [entry(`judged:${reportId}`, 'note')]],
+ '/api/projects/:team_id/signals/reports/:id/': () => [status, {}],
+ },
+ })
+
+ logic.actions.loadEntries()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(Object.hasOwn(logic.values.reportTitles, reportId)).toBe(remembered)
+ expect(logic.values.unresolvedReportIds).toEqual(remembered ? [] : [reportId])
+ })
+
+ // The harness writes every scout row under the canonical project, so a report a scratchpad key
+ // names belongs to the parent. The reports endpoint filters by the team the URL carries, so
+ // asking as a child environment 404s every title and caches each miss.
+ it('asks the canonical project for a report title from a child environment', async () => {
+ const reportId = '01a0918c-5f5f-74c4-b539-c634a8cb990a'
+ const reportPaths: string[] = []
+ useMocks({
+ get: {
+ [SCRATCHPAD_URL]: () => [200, [entry(`judged:${reportId}`, 'note')]],
+ '/api/projects/:team_id/signals/reports/:id/': ({ request }) => {
+ reportPaths.push(new URL(request.url).pathname)
+ return [200, { id: reportId, title: 'Export error rate doubled' }]
+ },
+ },
+ })
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, id: 4242, project_id: 99 })
+
+ logic.actions.loadEntries()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(reportPaths).toEqual([`/api/projects/99/signals/reports/${reportId}/`])
+ })
+
+ // 1,000 rows is a cap, not a total. The header has to say what span they cover, or a busy
+ // project's few hours of memory reads as everything the fleet has ever learned.
+ it.each([
+ ['nothing loaded', null, null],
+ ['a window ending 30 hours back', 30, 'last 30 h'],
+ ['a window ending 10 days back', 24 * 10, 'last 10 days'],
+ ])('describes the loaded span for %s', (_name, hoursBack, expected) => {
+ const entries =
+ hoursBack === null
+ ? null
+ : [
+ { ...entry('pattern:new', 'note'), updated_at: new Date().toISOString() },
+ {
+ ...entry('pattern:old', 'note'),
+ updated_at: new Date(Date.now() - hoursBack * 3600_000).toISOString(),
+ },
+ ]
+ expect(describeLoadedSpan(entries)).toEqual(expected)
+ })
+
it('keeps the card usable when the body lookup fails', async () => {
useMocks({ get: { [SCRATCHPAD_URL]: () => [500, {}] } })
diff --git a/products/signals/frontend/inbox/logics/scratchpadLogic.ts b/products/signals/frontend/inbox/logics/scratchpadLogic.ts
index 3040e0597076..be4d56172e47 100644
--- a/products/signals/frontend/inbox/logics/scratchpadLogic.ts
+++ b/products/signals/frontend/inbox/logics/scratchpadLogic.ts
@@ -1,51 +1,67 @@
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { ApiError } from 'lib/api-error'
import { dayjs } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'
-import { signalsScoutScratchpadSearch } from 'products/signals/frontend/generated/api'
+import { signalsReportsRetrieve, signalsScoutScratchpadSearch } from 'products/signals/frontend/generated/api'
import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'
-import { SCOUT_ROSTER_WINDOW_HOURS } from '../utils/scoutRunsWindow'
-
-// The list view shows two ways to read the fleet's memory: newest-first (the API's
-// native order) or clustered by the key namespace scouts choose (`tags:*`, `dedupe:*`).
-export type ScratchpadGrouping = 'recent' | 'topic'
+import { SCOUT_ROSTER_WINDOW_HOURS, isPipelineWriter } from '../utils/scoutRunsWindow'
+import { BOOKKEEPING_KINDS, isReportUuid, scratchpadKindOf, scratchpadTopicOf } from '../utils/scratchpadKeys'
// Search reruns the server-side ILIKE on every keystroke; debounce so typing doesn't
// fire a request per character.
const SEARCH_DEBOUNCE_MS = 300
// `list` caps at 1000 newest-first with no pagination wrapper — pull the whole window in
-// one read and group/search client-side. The endpoint exposes a `date_to` cursor for
-// walking past the cap; a team that routinely exceeds 1000 wants that wired into a "load
-// more" here, not a bigger single read.
+// one read and filter it client-side. Older memory arrives through `loadOlderEntries`, which
+// walks the endpoint's `date_to` cursor a page at a time.
export const SCRATCHPAD_FETCH_LIMIT = 1000
// Bodies are an unbounded TextField clamped at 50k chars on write, so a full-fat window of
-// 1000 entries is a payload nobody needs: the card renders a 2-line clamp until you open it.
-// Pull previews for the list and fetch the one body you expand. Sized well past two lines so
+// 1000 entries is a payload nobody needs: the ledger renders a one-line clamp until you open it.
+// Pull previews for the list and fetch the one body you expand. Sized well past one line so
// the overwhelming majority of notes arrive complete and never need the second read.
export const SCRATCHPAD_PREVIEW_CHARS = 1200
+// Rows per ledger page. Sized so the report-title resolution below covers the first page or two.
+export const SCRATCHPAD_PAGE_SIZE = 25
+/**
+ * How many report titles the panel resolves per pass. Keys namespaced by a report UUID need that
+ * report's title to read as anything, but the reports endpoint has no bulk-by-id filter, so each
+ * one costs a request. Cap the pass at the rows a reader can actually see; everything past it
+ * falls back to the shortened UUID until it scrolls into a later pass.
+ */
+const REPORT_TITLE_RESOLVE_CAP = 30
-/** One namespace cluster in the "By topic" view: the raw prefix, a friendly label, and its entries. */
-export interface ScratchpadNamespaceGroup {
- namespace: string
- label: string
- entries: ScratchpadEntryApi[]
-}
+/** The time spans the ledger can ask the endpoint for, mapped to `date_from`. */
+export type ScratchpadTimeFilter = 'window' | '1h' | '24h' | '7d' | '30d'
-/** Scouts namespace keys with a leading `prefix:` (e.g. `tags:errors:taxonomy`). Everything
- * before the first colon is the topic; keys without one fall into a shared "General" bucket. */
-export function scratchpadNamespaceOf(key: string): string {
- const idx = key.indexOf(':')
- return idx > 0 ? key.slice(0, idx) : 'general'
+const TIME_FILTER_HOURS: Record<Exclude<ScratchpadTimeFilter, 'window'>, number> = {
+ '1h': 1,
+ '24h': 24,
+ '7d': 24 * 7,
+ '30d': 24 * 30,
}
-export function humanizeNamespace(namespace: string): string {
- if (namespace === 'general') {
- return 'General'
+/** The `date_from` bound a time filter asks the endpoint for, or nothing for the default window. */
+function dateFromParam(timeFilter: ScratchpadTimeFilter): { date_from?: string } {
+ if (timeFilter === 'window') {
+ return {}
}
- return namespace.replace(/[-_]/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase())
+ return { date_from: dayjs().subtract(TIME_FILTER_HOURS[timeFilter], 'hour').toISOString() }
+}
+
+/** The header's headline numbers over the loaded window. */
+export interface ScratchpadWindowStats {
+ scouts: number
+ topics: number
+ expiringSoon: number
+}
+
+/** One option in the scout, kind or topic multi-select: the raw value and how many rows carry it. */
+export interface ScratchpadFacet {
+ value: string
+ count: number
}
/** Whether a listed entry's body may have been cut short by the preview projection. The API
@@ -66,31 +82,118 @@ export function entriesForSkill(entries: ScratchpadEntryApi[] | null, skillName:
return (entries ?? []).filter((entry) => entry.created_by_skill === skillName)
}
+/**
+ * How wide a span the loaded rows actually cover, e.g. "last 8 h". The header needs this because
+ * 1,000 rows is a cap, not a total: on a busy project the window closes after a few hours, and a
+ * bare "1,000 entries" reads as the whole memory.
+ */
+export function describeLoadedSpan(entries: ScratchpadEntryApi[] | null): string | null {
+ const stamps = (entries ?? []).map((entry) => entry.updated_at).filter((stamp): stamp is string => !!stamp)
+ if (stamps.length === 0) {
+ return null
+ }
+ const oldest = dayjs(stamps[stamps.length - 1])
+ const hours = dayjs().diff(oldest, 'hour')
+ if (hours < 1) {
+ return 'last hour'
+ }
+ if (hours < 48) {
+ return `last ${hours} h`
+ }
+ return `last ${Math.round(hours / 24)} days`
+}
+
+/** Counts of each distinct value across the rows, most common first, blanks dropped. */
+function facetsOf(
+ entries: ScratchpadEntryApi[],
+ valueOf: (entry: ScratchpadEntryApi) => string | null
+): ScratchpadFacet[] {
+ const counts = new Map<string, number>()
+ for (const entry of entries) {
+ const value = valueOf(entry)
+ if (value) {
+ counts.set(value, (counts.get(value) ?? 0) + 1)
+ }
+ }
+ return [...counts.entries()]
+ .map(([value, count]) => ({ value, count }))
+ .sort((a, b) => b.count - a.count || a.value.localeCompare(b.value))
+}
+
+/** Whether an entry passes the scout, kind and topic multi-selects. The bookkeeping switch is not
+ * part of this because the footer counts the rows that switch would hide, so the count has to see
+ * them. */
+function matchesFacetFilters(
+ entry: ScratchpadEntryApi,
+ scoutFilter: string[],
+ kindFilter: string[],
+ topicFilter: string[]
+): boolean {
+ if (scoutFilter.length > 0 && !scoutFilter.includes(entry.created_by_skill ?? '')) {
+ return false
+ }
+ const kind = scratchpadKindOf(entry.key)
+ if (kindFilter.length > 0 && (kind === null || !kindFilter.includes(kind))) {
+ return false
+ }
+ const topic = scratchpadTopicOf(entry.key)
+ if (topicFilter.length > 0 && (topic === null || !topicFilter.includes(topic))) {
+ return false
+ }
+ return true
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scratchpadLogicValues {
+ canLoadOlderEntries: boolean
entries: ScratchpadEntryApi[] | null
entriesLoading: boolean
expandedKeys: string[]
- expandedNamespaces: string[]
+ filteredEntries: ScratchpadEntryApi[] | null
fullContentByKey: Record<string, string>
- grouping: ScratchpadGrouping
- groups: ScratchpadNamespaceGroup[]
- lastUpdatedAt: string | null
+ hasActiveFilters: boolean
+ hasMoreOlderEntries: boolean
+ hideBookkeeping: boolean
+ kindFacets: ScratchpadFacet[]
+ kindFilter: string[]
loadFailed: boolean
+ loadedSpanLabel: string | null
loadingContentKeys: string[]
+ olderEntries: ScratchpadEntryApi[]
+ olderEntriesFailed: boolean
+ olderEntriesLoading: boolean
recentlyLearnedCount: number
recentlyLearnedCountCapped: boolean
+ reportTitles: Record<string, string | null>
+ scoutFacets: ScratchpadFacet[]
+ scoutFilter: string[]
searchFailed: boolean
searchResults: ScratchpadEntryApi[] | null
searchResultsLoading: boolean
searchText: string
+ timeFilter: ScratchpadTimeFilter
+ topicFacets: ScratchpadFacet[]
+ topicFilter: string[]
totalCount: number | null
+ unresolvedReportIds: string[]
+ visibleBookkeepingCount: number
visibleEntries: ScratchpadEntryApi[] | null
+ windowEntries: ScratchpadEntryApi[] | null
+ windowGeneration: number
+ windowStats: ScratchpadWindowStats
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scratchpadLogicActions {
- loadEntries: () => any
+ appendOlderEntries: (
+ entries: ScratchpadEntryApi[],
+ hasMore: boolean
+ ) => {
+ entries: ScratchpadEntryApi[]
+ hasMore: boolean
+ }
+ clearFilters: () => {}
+ loadEntries: (_payload: void) => void
loadEntriesFailure: (
error: string,
errorObject?: any
@@ -100,10 +203,10 @@ export interface scratchpadLogicActions {
}
loadEntriesSuccess: (
entries: ScratchpadEntryApi[],
- payload?: any
+ payload?: void
) => {
entries: ScratchpadEntryApi[]
- payload?: any
+ payload?: void
}
loadFullContent: (key: string) => {
key: string
@@ -118,6 +221,8 @@ export interface scratchpadLogicActions {
content: string
key: string
}
+ loadOlderEntries: () => {}
+ loadOlderEntriesFailure: () => {}
loadSearchResults: (_payload: void) => void
loadSearchResultsFailure: (
error: string,
@@ -133,33 +238,83 @@ export interface scratchpadLogicActions {
searchResults: ScratchpadEntryApi[] | null
payload?: void
}
- setGrouping: (grouping: ScratchpadGrouping) => {
- grouping: ScratchpadGrouping
+ resolveReportTitles: () => {}
+ setHideBookkeeping: (hideBookkeeping: boolean) => {
+ hideBookkeeping: boolean
+ }
+ setKindFilter: (kindFilter: string[]) => {
+ kindFilter: string[]
+ }
+ setReportTitle: (
+ reportId: string,
+ title: string | null
+ ) => {
+ reportId: string
+ title: string | null
+ }
+ setScoutFilter: (scoutFilter: string[]) => {
+ scoutFilter: string[]
}
setSearchText: (searchText: string) => {
searchText: string
}
+ setTimeFilter: (timeFilter: ScratchpadTimeFilter) => {
+ timeFilter: ScratchpadTimeFilter
+ }
+ setTopicFilter: (topicFilter: string[]) => {
+ topicFilter: string[]
+ }
toggleEntry: (key: string) => {
key: string
}
- toggleNamespace: (namespace: string) => {
- namespace: string
- }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface scratchpadLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- totalCount: (entries: ScratchpadEntryApi[] | null) => number | null
+ windowEntries: (
+ entries: ScratchpadEntryApi[] | null,
+ olderEntries: ScratchpadEntryApi[]
+ ) => ScratchpadEntryApi[] | null
+ totalCount: (windowEntries: ScratchpadEntryApi[] | null) => number | null
+ loadedSpanLabel: (windowEntries: ScratchpadEntryApi[] | null) => string | null
+ canLoadOlderEntries: (hasMoreOlderEntries: boolean, searchText: string) => boolean
recentlyLearnedCount: (entries: ScratchpadEntryApi[] | null) => number
recentlyLearnedCountCapped: (entries: ScratchpadEntryApi[] | null, recentlyLearnedCount: number) => boolean
- lastUpdatedAt: (entries: ScratchpadEntryApi[] | null) => string | null
visibleEntries: (
- entries: ScratchpadEntryApi[] | null,
+ windowEntries: ScratchpadEntryApi[] | null,
searchResults: ScratchpadEntryApi[] | null,
searchText: string
) => ScratchpadEntryApi[] | null
- groups: (visibleEntries: ScratchpadEntryApi[] | null) => ScratchpadNamespaceGroup[]
+ scoutFacets: (visibleEntries: ScratchpadEntryApi[] | null) => ScratchpadFacet[]
+ kindFacets: (visibleEntries: ScratchpadEntryApi[] | null) => ScratchpadFacet[]
+ topicFacets: (visibleEntries: ScratchpadEntryApi[] | null) => ScratchpadFacet[]
+ windowStats: (windowEntries: ScratchpadEntryApi[] | null) => ScratchpadWindowStats
+ visibleBookkeepingCount: (
+ visibleEntries: ScratchpadEntryApi[] | null,
+ scoutFilter: string[],
+ kindFilter: string[],
+ topicFilter: string[]
+ ) => number
+ hasActiveFilters: (
+ scoutFilter: string[],
+ kindFilter: string[],
+ topicFilter: string[],
+ hideBookkeeping: boolean,
+ searchText: string,
+ timeFilter: ScratchpadTimeFilter
+ ) => boolean
+ filteredEntries: (
+ visibleEntries: ScratchpadEntryApi[] | null,
+ scoutFilter: string[],
+ kindFilter: string[],
+ topicFilter: string[],
+ hideBookkeeping: boolean
+ ) => ScratchpadEntryApi[] | null
+ unresolvedReportIds: (
+ filteredEntries: ScratchpadEntryApi[] | null,
+ reportTitles: Record<string, string | null>
+ ) => string[]
}
}
@@ -171,41 +326,58 @@ export type scratchpadLogicType = MakeLogicType<
>
/**
- * Read-only view over the scout fleet's durable memory (`SignalScratchpad`). Owns the entry list,
- * the debounced search text (wired straight to the endpoint's `?text=` ILIKE), and the recent /
- * by-topic grouping toggle. There is no write surface on purpose — humans inspect this memory;
- * only the harness (internal-scope) writes it.
+ * Read-only view over the scout fleet's durable memory (`SignalScratchpad`). Owns the loaded
+ * window, the debounced search text (wired straight to the endpoint's `?text=` ILIKE), the
+ * client-side ledger filters, and the report titles that make UUID-namespaced keys readable.
+ * There is no write surface on purpose — humans inspect this memory; only the harness
+ * (internal-scope) writes it.
*
- * `entries` is always the unfiltered project window: the roster's "learned" headline and the
- * scout page's memory panel read it, and a search must not shrink those. A search lands in
- * `searchResults` instead, and the panel shows whichever applies via `visibleEntries`.
+ * `entries` is always the unfiltered first page: the roster's "learned" headline and the scout
+ * page's memory panel read it, and neither a search nor a ledger filter may shrink those. A
+ * search lands in `searchResults`, older pages land in `olderEntries`, and the ledger reads
+ * `filteredEntries` on top of whichever applies.
*/
export const scratchpadLogic = kea<scratchpadLogicType>([
path(['scenes', 'inbox', 'logics', 'scratchpadLogic']),
actions({
setSearchText: (searchText: string) => ({ searchText }),
- setGrouping: (grouping: ScratchpadGrouping) => ({ grouping }),
- toggleNamespace: (namespace: string) => ({ namespace }),
+ setScoutFilter: (scoutFilter: string[]) => ({ scoutFilter }),
+ setKindFilter: (kindFilter: string[]) => ({ kindFilter }),
+ setTopicFilter: (topicFilter: string[]) => ({ topicFilter }),
+ setTimeFilter: (timeFilter: ScratchpadTimeFilter) => ({ timeFilter }),
+ setHideBookkeeping: (hideBookkeeping: boolean) => ({ hideBookkeeping }),
+ clearFilters: () => ({}),
toggleEntry: (key: string) => ({ key }),
loadFullContent: (key: string) => ({ key }),
loadFullContentSuccess: (key: string, content: string) => ({ key, content }),
loadFullContentFailure: (key: string) => ({ key }),
+ loadOlderEntries: () => ({}),
+ appendOlderEntries: (entries: ScratchpadEntryApi[], hasMore: boolean) => ({ entries, hasMore }),
+ loadOlderEntriesFailure: () => ({}),
+ resolveReportTitles: () => ({}),
+ setReportTitle: (reportId: string, title: string | null) => ({ reportId, title }),
}),
loaders(({ values }) => ({
entries: [
null as ScratchpadEntryApi[] | null,
{
- loadEntries: async () => {
+ loadEntries: async (_payload: void, breakpoint) => {
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
return []
}
- return await signalsScoutScratchpadSearch(String(teamId), {
+ const page = await signalsScoutScratchpadSearch(String(teamId), {
limit: SCRATCHPAD_FETCH_LIMIT,
content_max_chars: SCRATCHPAD_PREVIEW_CHARS,
+ ...dateFromParam(values.timeFilter),
})
+ // Drop a stale response if the span moved on while this request was in flight.
+ // A wider span is the slower read, so narrowing right after widening is the
+ // order that would otherwise let the older response answer last.
+ breakpoint()
+ return page
},
},
],
@@ -222,6 +394,7 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
text,
limit: SCRATCHPAD_FETCH_LIMIT,
content_max_chars: SCRATCHPAD_PREVIEW_CHARS,
+ ...dateFromParam(values.timeFilter),
})
// Drop a stale response if the search moved on while this request was in flight.
breakpoint()
@@ -232,8 +405,27 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
})),
reducers({
- searchText: ['', { setSearchText: (_, { searchText }) => searchText }],
- grouping: ['recent' as ScratchpadGrouping, { setGrouping: (_, { grouping }) => grouping }],
+ searchText: ['', { setSearchText: (_, { searchText }) => searchText, clearFilters: () => '' }],
+ scoutFilter: [[] as string[], { setScoutFilter: (_, { scoutFilter }) => scoutFilter, clearFilters: () => [] }],
+ kindFilter: [[] as string[], { setKindFilter: (_, { kindFilter }) => kindFilter, clearFilters: () => [] }],
+ topicFilter: [[] as string[], { setTopicFilter: (_, { topicFilter }) => topicFilter, clearFilters: () => [] }],
+ timeFilter: [
+ 'window' as ScratchpadTimeFilter,
+ { setTimeFilter: (_, { timeFilter }) => timeFilter, clearFilters: () => 'window' as ScratchpadTimeFilter },
+ ],
+ // Whether to drop the scouts' self-bookkeeping. Off by default — a first-time reader should
+ // see everything the fleet writes — but a reader who turns it off keeps it off.
+ hideBookkeeping: [
+ false,
+ { persist: true },
+ {
+ setHideBookkeeping: (_, { hideBookkeeping }) => hideBookkeeping,
+ // The switch counts towards `hasActiveFilters`, which is what puts the clear
+ // button on screen, so the clear has to reach it. Otherwise a window of nothing
+ // but bookkeeping rows renders the same empty state after every press.
+ clearFilters: () => false,
+ },
+ ],
// Did the most recent load reject? Lets the panel tell a failed load apart from an empty
// project (kea-loaders leaves `entries` at its prior value on failure, so it can't).
loadFailed: [
@@ -258,19 +450,56 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
null as ScratchpadEntryApi[] | null,
{
setSearchText: (state, { searchText }) => (searchText.trim() ? state : null),
+ clearFilters: () => null,
},
],
- // Which "By topic" clusters are open. Start collapsed (high-level view of topics first);
- // switching grouping resets the set so entering "By topic" always opens fully collapsed.
- expandedNamespaces: [
- [] as string[],
+ // Which first page the walked pages belong to. A page read against an earlier window can
+ // still answer after a reload started, and this is bumped at dispatch, so the listener
+ // sees the invalidation without waiting for the fresh page to arrive.
+ windowGeneration: [0, { loadEntries: (state: number) => state + 1 }],
+ // Pages walked back past the 1,000-row cap with the endpoint's `date_to` cursor. A fresh
+ // first page invalidates them: it may already carry rows these pages hold.
+ olderEntries: [
+ [] as ScratchpadEntryApi[],
+ {
+ appendOlderEntries: (state, { entries }) => [...state, ...entries],
+ loadEntries: () => [],
+ },
+ ],
+ olderEntriesLoading: [
+ false,
{
- toggleNamespace: (state, { namespace }) =>
- state.includes(namespace) ? state.filter((n) => n !== namespace) : [...state, namespace],
- setGrouping: () => [],
+ loadOlderEntries: () => true,
+ appendOlderEntries: () => false,
+ loadOlderEntriesFailure: () => false,
+ loadEntries: () => false,
},
],
- // Which entry cards are open. Lives here rather than in the card's own state so the
+ // Did the last older-page request reject? A page that succeeds can also append nothing,
+ // once the dedupe below drops every row it carried, so an unchanged list cannot stand in
+ // for a failure and the footer has to be told.
+ olderEntriesFailed: [
+ false,
+ {
+ loadOlderEntries: () => false,
+ appendOlderEntries: () => false,
+ loadOlderEntriesFailure: () => true,
+ loadEntries: () => false,
+ },
+ ],
+ // Is there anything past what's loaded? A first page that came back short has already
+ // reached the end of the memory, so the load-older button stays hidden.
+ hasMoreOlderEntries: [
+ false,
+ {
+ loadEntriesSuccess: (_, { entries }) => entries.length >= SCRATCHPAD_FETCH_LIMIT,
+ appendOlderEntries: (_, { hasMore }) => hasMore,
+ // A reload drops the walked pages, so the control goes with them until the fresh
+ // first page says whether anything older is left.
+ loadEntries: () => false,
+ },
+ ],
+ // Which entry rows are open. Lives here rather than in the table's own state so the
// listener below can hang the full-body fetch off the same toggle.
expandedKeys: [
[] as string[],
@@ -297,12 +526,40 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
loadEntriesSuccess: () => [],
},
],
+ // Report titles for UUID-namespaced keys. A null means the lookup came back empty — the
+ // report is gone — and stops the key being asked for again.
+ reportTitles: [
+ {} as Record<string, string | null>,
+ {
+ setReportTitle: (state, { reportId, title }) => ({ ...state, [reportId]: title }),
+ },
+ ],
}),
selectors({
+ // Everything loaded, newest first: the first page plus any older pages walked after it.
+ windowEntries: [
+ (s) => [s.entries, s.olderEntries],
+ (entries: ScratchpadEntryApi[] | null, olderEntries: ScratchpadEntryApi[]): ScratchpadEntryApi[] | null =>
+ entries === null ? null : [...entries, ...olderEntries],
+ ],
totalCount: [
- (s) => [s.entries],
- (entries: ScratchpadEntryApi[] | null): number | null => (entries ? entries.length : null),
+ (s) => [s.windowEntries],
+ (windowEntries: ScratchpadEntryApi[] | null): number | null =>
+ windowEntries ? windowEntries.length : null,
+ ],
+ loadedSpanLabel: [
+ (s) => [s.windowEntries],
+ (windowEntries: ScratchpadEntryApi[] | null): string | null => describeLoadedSpan(windowEntries),
+ ],
+ /**
+ * Whether the load-older control has a page to fetch. The cursor walks the unfiltered
+ * window, and a search is a separate one-shot read that the appended pages never reach, so
+ * the control has nothing to offer a reader who is searching.
+ */
+ canLoadOlderEntries: [
+ (s) => [s.hasMoreOlderEntries, s.searchText],
+ (hasMoreOlderEntries: boolean, searchText: string): boolean => hasMoreOlderEntries && !searchText.trim(),
],
// Entries written or refreshed over the roster window, so the roster's "learned" headline
// sits on the same span as the run and report numbers the summary endpoint returns for it.
@@ -324,48 +581,139 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
(entries: ScratchpadEntryApi[] | null, recentlyLearnedCount: number): boolean =>
entries !== null && entries.length >= SCRATCHPAD_FETCH_LIMIT && recentlyLearnedCount === entries.length,
],
- // Entries are newest-first, so the head's timestamp drives the callout's "updated when" hint.
- lastUpdatedAt: [
- (s) => [s.entries],
- (entries: ScratchpadEntryApi[] | null): string | null => entries?.[0]?.updated_at ?? null,
- ],
- // What the panel lists: the search hits while a search is typed, the whole window otherwise.
- // Null while the applicable set is still loading.
+ // What the ledger filters over: the search hits while a search is typed, the whole loaded
+ // window otherwise. Null while the applicable set is still loading.
visibleEntries: [
- (s) => [s.entries, s.searchResults, s.searchText],
+ (s) => [s.windowEntries, s.searchResults, s.searchText],
(
- entries: ScratchpadEntryApi[] | null,
+ windowEntries: ScratchpadEntryApi[] | null,
searchResults: ScratchpadEntryApi[] | null,
searchText: string
- ): ScratchpadEntryApi[] | null => (searchText.trim() ? searchResults : entries),
+ ): ScratchpadEntryApi[] | null => (searchText.trim() ? searchResults : windowEntries),
+ ],
+ scoutFacets: [
+ (s) => [s.visibleEntries],
+ (visibleEntries: ScratchpadEntryApi[] | null): ScratchpadFacet[] =>
+ facetsOf(visibleEntries ?? [], (entry) => entry.created_by_skill ?? null),
],
- // Entries arrive newest-first; preserve that order within each namespace cluster, and order
- // the clusters by their most recently touched entry so the liveliest topic floats to the top.
- groups: [
+ kindFacets: [
(s) => [s.visibleEntries],
- (entries: ScratchpadEntryApi[] | null): ScratchpadNamespaceGroup[] => {
- const byNamespace = new Map<string, ScratchpadEntryApi[]>()
- for (const entry of entries ?? []) {
- const namespace = scratchpadNamespaceOf(entry.key)
- const bucket = byNamespace.get(namespace)
- if (bucket) {
- bucket.push(entry)
- } else {
- byNamespace.set(namespace, [entry])
+ (visibleEntries: ScratchpadEntryApi[] | null): ScratchpadFacet[] =>
+ facetsOf(visibleEntries ?? [], (entry) => scratchpadKindOf(entry.key)),
+ ],
+ topicFacets: [
+ (s) => [s.visibleEntries],
+ (visibleEntries: ScratchpadEntryApi[] | null): ScratchpadFacet[] =>
+ facetsOf(visibleEntries ?? [], (entry) => scratchpadTopicOf(entry.key)),
+ ],
+ /**
+ * The header's three counts. All read the loaded window rather than the filtered rows: the
+ * header says what is loaded and over what span, and a search that matches nothing must not
+ * make it read as though the fleet has no scouts.
+ *
+ * Expiry is the one property that changes what a row means without anyone touching it, so
+ * it gets counted rather than left to a reader to notice.
+ */
+ windowStats: [
+ (s) => [s.windowEntries],
+ (windowEntries: ScratchpadEntryApi[] | null): ScratchpadWindowStats => {
+ const horizon = dayjs().add(7, 'day')
+ const entries = windowEntries ?? []
+ return {
+ scouts: new Set(
+ entries
+ .map((entry) => entry.created_by_skill)
+ .filter((skillName): skillName is string => !!skillName && !isPipelineWriter(skillName))
+ ).size,
+ topics: new Set(entries.map((entry) => scratchpadTopicOf(entry.key)).filter(Boolean)).size,
+ expiringSoon: entries.filter(
+ (entry) => entry.expires_at && dayjs(entry.expires_at).isBefore(horizon)
+ ).length,
+ }
+ },
+ ],
+ /**
+ * The bookkeeping rows among the listed ones, because the footer prints this number as a
+ * share of the rows the table shows. The hide-bookkeeping switch is left out on purpose:
+ * while it is off, the number says how many rows it would drop, and the footer hides the
+ * line while it is on.
+ */
+ visibleBookkeepingCount: [
+ (s) => [s.visibleEntries, s.scoutFilter, s.kindFilter, s.topicFilter],
+ (
+ visibleEntries: ScratchpadEntryApi[] | null,
+ scoutFilter: string[],
+ kindFilter: string[],
+ topicFilter: string[]
+ ): number =>
+ (visibleEntries ?? []).filter((entry) => {
+ const kind = scratchpadKindOf(entry.key)
+ return (
+ kind !== null &&
+ BOOKKEEPING_KINDS.has(kind) &&
+ matchesFacetFilters(entry, scoutFilter, kindFilter, topicFilter)
+ )
+ }).length,
+ ],
+ hasActiveFilters: [
+ (s) => [s.scoutFilter, s.kindFilter, s.topicFilter, s.hideBookkeeping, s.searchText, s.timeFilter],
+ (
+ scoutFilter: string[],
+ kindFilter: string[],
+ topicFilter: string[],
+ hideBookkeeping: boolean,
+ searchText: string,
+ timeFilter: ScratchpadTimeFilter
+ ): boolean =>
+ scoutFilter.length > 0 ||
+ kindFilter.length > 0 ||
+ topicFilter.length > 0 ||
+ hideBookkeeping ||
+ searchText.trim().length > 0 ||
+ timeFilter !== 'window',
+ ],
+ // The rows the ledger lists. Newest-first order comes from the endpoint and is preserved.
+ filteredEntries: [
+ (s) => [s.visibleEntries, s.scoutFilter, s.kindFilter, s.topicFilter, s.hideBookkeeping],
+ (
+ visibleEntries: ScratchpadEntryApi[] | null,
+ scoutFilter: string[],
+ kindFilter: string[],
+ topicFilter: string[],
+ hideBookkeeping: boolean
+ ): ScratchpadEntryApi[] | null => {
+ if (visibleEntries === null) {
+ return null
+ }
+ return visibleEntries.filter((entry) => {
+ if (!matchesFacetFilters(entry, scoutFilter, kindFilter, topicFilter)) {
+ return false
+ }
+ const kind = scratchpadKindOf(entry.key)
+ return !(hideBookkeeping && kind !== null && BOOKKEEPING_KINDS.has(kind))
+ })
+ },
+ ],
+ // Report UUIDs on screen whose title hasn't been looked up yet, newest first and capped.
+ unresolvedReportIds: [
+ (s) => [s.filteredEntries, s.reportTitles],
+ (filteredEntries: ScratchpadEntryApi[] | null, reportTitles: Record<string, string | null>): string[] => {
+ const ids: string[] = []
+ for (const entry of filteredEntries ?? []) {
+ const topic = scratchpadTopicOf(entry.key)
+ if (topic && isReportUuid(topic) && !Object.hasOwn(reportTitles, topic) && !ids.includes(topic)) {
+ ids.push(topic)
+ if (ids.length >= REPORT_TITLE_RESOLVE_CAP) {
+ break
+ }
}
}
- return [...byNamespace.entries()]
- .map(([namespace, namespaceEntries]) => ({
- namespace,
- label: humanizeNamespace(namespace),
- entries: namespaceEntries,
- }))
- .sort((a, b) => (b.entries[0]?.updated_at ?? '').localeCompare(a.entries[0]?.updated_at ?? ''))
+ return ids
},
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
setSearchText: async ({ searchText }, breakpoint) => {
if (!searchText.trim()) {
return
@@ -374,7 +722,72 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
actions.loadSearchResults()
},
- // Opening a card is the only moment a full body is worth fetching — and only when the
+ // The time span is the one filter the endpoint applies, so changing it reloads rather than
+ // narrowing what's already here — a wider span has rows the loaded window never held.
+ setTimeFilter: () => {
+ actions.loadEntries()
+ if (values.searchText.trim()) {
+ actions.loadSearchResults()
+ }
+ },
+
+ // Clearing resets the span through a reducer, and the span is the one filter the endpoint
+ // applies, so the loaded rows can still be a narrowed response. Refetch rather than only
+ // reset the control: the select reads as the default span after the reset, so picking that
+ // span again fires nothing and the reader has no way back to the full window.
+ clearFilters: () => {
+ actions.loadEntries()
+ },
+
+ loadEntriesSuccess: () => {
+ actions.resolveReportTitles()
+ },
+
+ loadSearchResultsSuccess: () => {
+ actions.resolveReportTitles()
+ },
+
+ appendOlderEntries: () => {
+ actions.resolveReportTitles()
+ },
+
+ // Walk one page further back with the endpoint's `date_to` cursor. Exclusive upper bound,
+ // so the oldest loaded row's own timestamp is the right cursor and never repeats it.
+ loadOlderEntries: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ const loaded = values.windowEntries ?? []
+ const cursor = loaded[loaded.length - 1]?.updated_at
+ const generation = values.windowGeneration
+ if (!teamId || !cursor) {
+ actions.loadOlderEntriesFailure()
+ return
+ }
+ try {
+ const page = await signalsScoutScratchpadSearch(String(teamId), {
+ limit: SCRATCHPAD_FETCH_LIMIT,
+ content_max_chars: SCRATCHPAD_PREVIEW_CHARS,
+ date_to: cursor,
+ ...dateFromParam(values.timeFilter),
+ })
+ // The window this page was cursored from is gone if a reload started meanwhile.
+ // Appending would file its rows under a different first page, and the dedupe below
+ // was built from the old window, so it cannot drop keys the new page carries.
+ if (values.windowGeneration !== generation) {
+ return
+ }
+ // Rows sharing the cursor timestamp fall outside an exclusive bound, so a page can
+ // still carry a key already on screen. Keys are unique per team, so drop by key.
+ const seen = new Set(loaded.map((entry) => entry.key))
+ actions.appendOlderEntries(
+ page.filter((entry) => !seen.has(entry.key)),
+ page.length >= SCRATCHPAD_FETCH_LIMIT
+ )
+ } catch {
+ actions.loadOlderEntriesFailure()
+ }
+ },
+
+ // Opening a row is the only moment a full body is worth fetching — and only when the
// preview actually cut one off. Collapsing, re-opening a cached entry, or opening a note
// that arrived whole all stay local.
toggleEntry: ({ key }) => {
@@ -385,9 +798,9 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
if (Object.hasOwn(values.fullContentByKey, key) || values.loadingContentKeys.includes(key)) {
return
}
- // A card can sit in either list (the scout page renders from the window while a search
+ // A row can sit in either list (the scout page renders from the window while a search
// may still be typed in the panel), so look in both.
- const entry = [...(values.entries ?? []), ...(values.searchResults ?? [])].find((e) => e.key === key)
+ const entry = [...(values.windowEntries ?? []), ...(values.searchResults ?? [])].find((e) => e.key === key)
if (entry && isPreviewTruncated(entry.content)) {
actions.loadFullContent(key)
}
@@ -395,7 +808,7 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
// Deliberately no `breakpoint()`: kea's is per-action, not per-key, so opening a second
// note would unwind the first request mid-flight and strand its key in
- // `loadingContentKeys` — a card stuck on a skeleton that `toggleEntry` then refuses to
+ // `loadingContentKeys` — a row stuck on a skeleton that `toggleEntry` then refuses to
// retry. Every result is keyed, so a late response is written to its own entry and a
// superseded one is harmless.
loadFullContent: async ({ key }) => {
@@ -417,10 +830,51 @@ export const scratchpadLogic = kea<scratchpadLogicType>([
actions.loadFullContentFailure(key)
} catch {
// The preview stays on screen, so a failure costs the reader the tail of one note
- // rather than the whole card.
+ // rather than the whole row.
actions.loadFullContentFailure(key)
}
},
+
+ // One request per report, so the cap above is what keeps this bounded. A missing report
+ // resolves to null and is never asked for again.
+ resolveReportTitles: async () => {
+ // Ask the canonical project, not the environment in the URL. The harness writes every
+ // scout row through `_canonical_team_id` (parent_team_id or team_id), so a report a
+ // scratchpad key names belongs to the parent, while the reports endpoint filters by the
+ // team the URL carries and does not canonicalize it. A child-environment id would 404
+ // every title. `currentProjectId` mirrors that canonical id, and equals the team id for
+ // a root project; it reads '@current' until the team loads, which we reject.
+ const projectId = teamLogic.values.currentProjectId
+ // An id reaches `reportTitles` only when its response lands, so a pass that starts
+ // while another is in flight would list, and ask for, every id the first one is
+ // already fetching. Two loads answering at different times is ordinary here.
+ const inFlight: Set<string> = (cache.resolvingReportIds ??= new Set<string>())
+ const ids = values.unresolvedReportIds.filter((reportId) => !inFlight.has(reportId))
+ if (!projectId || projectId === '@current' || ids.length === 0) {
+ return
+ }
+ for (const reportId of ids) {
+ inFlight.add(reportId)
+ }
+ await Promise.all(
+ ids.map(async (reportId) => {
+ try {
+ const report = await signalsReportsRetrieve(String(projectId), reportId)
+ actions.setReportTitle(reportId, report.title ?? null)
+ } catch (error) {
+ // A stored null asserts the report is gone and stops the key being asked
+ // for again, so only a 404 earns one. Anything else is transient: leave the
+ // id unresolved, so the next pass asks again rather than pinning the row to
+ // its shortened UUID for the rest of the session.
+ if (error instanceof ApiError && error.status === 404) {
+ actions.setReportTitle(reportId, null)
+ }
+ } finally {
+ inFlight.delete(reportId)
+ }
+ })
+ )
+ },
})),
afterMount(({ actions }) => {
diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
index acb5afe25084..90126e7a5eef 100644
--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts
@@ -90,6 +90,15 @@ export function stripScoutPrefix(skillName: string): string {
: skillName
}
+/** The prefix on a report-pipeline stage's writer identity, such as `pipeline:report-research`. A
+ * stage writes scout memory but is not a scout. */
+export const PIPELINE_WRITER_PREFIX = 'pipeline:'
+
+/** Whether a writer identity belongs to a report-pipeline stage rather than to a scout. */
+export function isPipelineWriter(skillName: string): boolean {
+ return skillName.startsWith(PIPELINE_WRITER_PREFIX)
+}
+
/** "signals-scout-error-tracking" → "Error tracking" */
export function prettifyScoutSkillName(skillName: string): string {
const cleaned = stripScoutPrefix(skillName).replace(/[-_]/g, ' ').trim()
diff --git a/products/signals/frontend/inbox/utils/scratchpadKeys.test.ts b/products/signals/frontend/inbox/utils/scratchpadKeys.test.ts
new file mode 100644
index 000000000000..48fba3bcce0d
--- /dev/null
+++ b/products/signals/frontend/inbox/utils/scratchpadKeys.test.ts
@@ -0,0 +1,33 @@
+import { scratchpadKindOf, scratchpadTopicOf } from './scratchpadKeys'
+
+// The prefixes the scout memory contract defines for the fleet. One missing from the registry
+// parses as a topic rather than a kind, so every key carrying it reports its prefix as its topic
+// and the ledger's Topic filter answers with the wrong rows.
+const DOCUMENTED_PREFIXES = [
+ 'pattern',
+ 'watch',
+ 'noise',
+ 'addressed',
+ 'dedupe',
+ 'allowlist',
+ 'not-in-use',
+ 'mcp-gap',
+ 'improve',
+ 'reported',
+ 'report',
+ 'reviewer',
+]
+
+describe('scratchpadKeys', () => {
+ it.each(DOCUMENTED_PREFIXES)('reads %s as a kind and the next segment as the topic', (prefix) => {
+ expect(scratchpadKindOf(`${prefix}:error_tracking:entity`)).toBe(prefix)
+ expect(scratchpadTopicOf(`${prefix}:error_tracking:entity`)).toBe('error_tracking')
+ })
+
+ // Scouts coin their own namespaces, and the registry is what keeps one of those from becoming
+ // a ledger kind. A parser that trusted every prefix would lose the topic on these keys.
+ it('treats a prefix the fleet does not use as a kind as the topic itself', () => {
+ expect(scratchpadKindOf('billing_spikes:34316')).toBeNull()
+ expect(scratchpadTopicOf('billing_spikes:34316')).toBe('billing_spikes')
+ })
+})
diff --git a/products/signals/frontend/inbox/utils/scratchpadKeys.ts b/products/signals/frontend/inbox/utils/scratchpadKeys.ts
new file mode 100644
index 000000000000..3a70c0e6b8d6
--- /dev/null
+++ b/products/signals/frontend/inbox/utils/scratchpadKeys.ts
@@ -0,0 +1,88 @@
+import { type ComponentProps } from 'react'
+
+import { LemonTag } from '@posthog/lemon-ui'
+
+type LemonTagType = ComponentProps<typeof LemonTag>['type']
+
+/**
+ * The key prefix (everything before the first colon) encodes the note's *kind* — what the scout
+ * was doing when it wrote it. This map doubles as the roster of kinds the fleet actually uses: a
+ * key whose prefix is absent here is treated as a topic, not a kind, so one-off namespaces do not
+ * turn into ledger kinds.
+ */
+export const KIND_TAG_TYPE: Record<string, LemonTagType> = {
+ // Durable knowledge: what the fleet has worked out and trusts.
+ pattern: 'highlight',
+ baseline: 'success',
+ noise: 'muted',
+ allowlist: 'muted',
+ 'not-in-use': 'muted',
+ coverage: 'completion',
+ taxonomy: 'option',
+ tags: 'option',
+ watch: 'warning',
+ watchlist: 'warning',
+ emerging: 'primary',
+ explore: 'option',
+ recheck: 'caution',
+ finding: 'primary',
+ improve: 'caution',
+ 'mcp-gap': 'caution',
+ // Bookkeeping: what keeps a scout from repeating itself.
+ dedupe: 'muted',
+ judged: 'muted',
+ report: 'muted',
+ reported: 'muted',
+ reviewer: 'muted',
+ followup: 'muted',
+ cursor: 'muted',
+ snapshot: 'muted',
+ skip: 'muted',
+ covered: 'muted',
+ pending: 'muted',
+ addressed: 'muted',
+ already_addressed: 'muted',
+ disqualified: 'muted',
+}
+
+/**
+ * Kinds a scout writes for itself rather than for a reader: which signals it has already judged,
+ * which reports it has filed, where its last sweep stopped. They dominate the window by volume,
+ * so the panel can drop them in one switch and leave the durable knowledge behind.
+ */
+export const BOOKKEEPING_KINDS = new Set([
+ 'dedupe',
+ 'judged',
+ 'report',
+ 'followup',
+ 'cursor',
+ 'snapshot',
+ 'already_addressed',
+ 'addressed',
+ 'covered',
+ 'pending',
+])
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+/** Whether a key segment is a report UUID, which the ledger resolves to that report's title. */
+export function isReportUuid(segment: string): boolean {
+ return UUID_PATTERN.test(segment)
+}
+
+/** The note's kind, or null when the key's first segment is not one the fleet uses as a kind. */
+export function scratchpadKindOf(key: string): string | null {
+ const [first] = key.split(':')
+ return first && first !== key && first in KIND_TAG_TYPE ? first : null
+}
+
+/**
+ * What the note is about. A kind-prefixed key carries its topic in the second segment
+ * (`pattern:apm:p95-window` is about `apm`); a key with no recognized kind is its own topic
+ * (`billing_spikes:34316` is about `billing_spikes`).
+ */
+export function scratchpadTopicOf(key: string): string | null {
+ const segments = key.split(':')
+ const topic = scratchpadKindOf(key) ? segments[1] : segments[0]
+ return topic || null
+}