:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): add notes to inbox reports, optionally sent to the scouts (#124456)
Dylan Martin99afb07780f2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a35c5db719c3..4cce66f94b2b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -12222,6 +12222,10 @@ snapshots:hash: v1.k794b7964.da604dcafaf4ba22c7c00febc5956b4143660cb2455cdf613748ecb81688116e.tHlZgbxkc6M5nBT0v7CBw_TXlQHZNuNaQJI31HCHnQgscenes-app-inbox-cards--skeleton--light:hash: v1.k794b7964.d74decf0d1eec3cb7e66535e5071bbe8026b34fe398c355dedf63124eb91cd9e.zZmTI-hkVOKyADi7R2mvJyeYSzxT0HpvXctUwJQuFXg+ scenes-app-inbox-detail--activity-notes--dark:+ hash: v1.k794b7964.5ea52d068ec7edbb0790aa554cbde001d08487fd58aa37817fee955afdb051df.ZeiGHmprlF7Wum82e9hH7oKR3B7-uqxPSdvAE83fOt4+ scenes-app-inbox-detail--activity-notes--light:+ hash: v1.k794b7964.40c66686ccfe3fe947605b545c2fd6bf9a1e6ac337a5605c20f61fef6da6f14f.oYK9koJGkdcaO0qjh_wCzfAwnLTW6dnhy815xGpzq0cscenes-app-inbox-detail--pull-request--dark:hash: v1.k794b7964.51280499a41683257d9e73732602c06a3d24ddb3ce5ed1593682a2d0fc985ede.kOXk8NNGyuQAQ0ERaBjcygzunDspJ19jLRIr4ugnEtAscenes-app-inbox-detail--pull-request--light:@@ -12258,6 +12262,10 @@ snapshots:hash: v1.k794b7964.c4e555471b01104fdd11e1e7c68ccd13e7a2429111a6e7f6fe4ae322676e0c1a.bVuGlznqrR1iHoALy6uSHeE2xjzh2AHbfTnO05OhXFwscenes-app-inbox-detail--report-minimal--light:hash: v1.k794b7964.8856ba9efc8521132842a7a11b9635e83600b55582a50e144a2a8595e829aedc.UQ-krMEfd3qR4Es6nVNNq4hR3AeEj3jKN1v7017Uy0A+ scenes-app-inbox-detail--report-notes--dark:+ hash: v1.k794b7964.0a9e067e462cdea50bb0967ee6d377e5be85a1e2684ac7eaf4f21bde982fadba.o6ErGGCdWAG7ppbTzSTmlGxd15u7WTvo_4lZ0K-fey4+ scenes-app-inbox-detail--report-notes--light:+ hash: v1.k794b7964.48a1f6aa62677763e65ff4bb57a0aff0aa4222bee1d83f3a23109857beb6d4e1.DsrNZEDSDVw8TFnn1nA6nYQvC9Z0UMCZ7qm7XwZqx1Mscenes-app-inbox-detail--report-plan--dark:hash: v1.k794b7964.094e8e01c3919420e636fab86f6975ce5f49f0a4c33680936869483de7268fed.CSl1ad3TwfA_2-M7Pa5XrLOncyFQty8w90IJM2yXmeMscenes-app-inbox-detail--report-plan--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 3265be0a3a5f..998b99b35af4 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -239,6 +239,7 @@ export const FEATURE_FLAGS = {SIGNALS_REPORT_CHECKS_REPLACE: 'signals-report-checks-replace', // owner: #team-self-drivingSIGNALS_REPORT_METRICS: 'signals-report-metrics', // owner: #team-self-driving, gates the live impact metrics on inbox report rows and the report detail, and the snapshot refresh calls they makeSIGNALS_REPORT_MONITORING: 'signals-report-monitoring', // owner: #team-self-driving+ SIGNALS_REPORT_NOTES: 'signals-report-notes', // owner: #team-self-driving, gates the notes list and composer at the end of an inbox report, and the quoted notes in its activitySTARTUP_PROGRAM_INTENT: 'startup-program-intent', // owner: @pawel-cebula #team-billingSURVEYS_ACTIONS: 'surveys-actions', // owner: #team-surveysSURVEYS_ADAPTIVE_LIMITS: 'surveys-adaptive-limits', // owner: #team-surveysdiff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.tsindex b9093fc455a8..902621ce0d45 100644--- a/frontend/src/mocks/handlers.ts+++ b/frontend/src/mocks/handlers.ts@@ -371,6 +371,7 @@ export const defaultMocks: Mocks = {completed_at: null,github_optional_available: false,},+ '/api/projects/:team_id/signals/scout/notes/': [],'/api/projects/:team_id/feature_flags/:feature_flag_id/dependent_flags/': EMPTY_PAGINATED_RESPONSE,'/api/environments/:team_id/llm_prompts/resolve/': {},'/api/environments/:team_id/llm_analytics/': {},diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNoteComposer.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNoteComposer.tsxnew file mode 100644index 000000000000..10237ecda3a0--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNoteComposer.tsx@@ -0,0 +1,33 @@+import { useState } from 'react'++import { LemonTextArea } from '@posthog/lemon-ui'++import { SCOUT_NOTE_MAX_CHARS } from '../../../logics/scoutNotesLogic'++/**+ * Controlled so LemonTextArea's counter has a value to count; an uncontrolled textarea reports+ * 0 / max no matter what is typed.+ */+export function ScoutNoteComposer({+ onChange,+ placeholder = 'e.g. we shipped a new checkout on Tuesday, watch conversion closely',+ maxLength = SCOUT_NOTE_MAX_CHARS,+}: {+ onChange: (content: string) => void+ placeholder?: string+ maxLength?: number+}): JSX.Element {+ const [content, setContent] = useState('')+ return (+ <LemonTextArea+ autoFocus+ value={content}+ maxLength={maxLength}+ placeholder={placeholder}+ onChange={(value) => {+ setContent(value)+ onChange(value)+ }}+ />+ )+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsxindex fb9f46ee27f8..4796595cc823 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx@@ -2,14 +2,11 @@ import { useActions, useValues } from 'kea'import { useState } from 'react'import { IconChevronDown, IconChevronRight, IconPencil, IconTrash } from '@posthog/icons'-import { LemonButton, LemonDialog, LemonTag, LemonTextArea, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonDialog, LemonTag, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { pluralize } from 'lib/utils/strings'-import { AccessControlLevel, AccessControlResourceType } from '~/types'-import type { ScoutNoteApi } from 'products/signals/frontend/generated/api.schemas'import { scoutDetailLogic } from '../../../logics/scoutDetailLogic'@@ -17,40 +14,14 @@ import {isDirectScoutNote,NOTES_FETCH_LIMIT,scoutNoteOriginLabel,+ scoutNoteWriteDisabledReason,scoutNotesLogic,} from '../../../logics/scoutNotesLogic'import { linkReportIdsInNote } from '../../../utils/scoutMemoryPresentation'import { OpenScratchpadButton } from './OpenScratchpadButton'+import { ScoutNoteComposer } from './ScoutNoteComposer'import { ScoutNoteContent } from './ScoutNoteContent'-/** Bounded by the create serializer; mirrored here so the dialog can say so before a failed request. */-const NOTE_MAX_CHARS = 10000--/**- * Controlled so LemonTextArea's counter has a value to count; an uncontrolled textarea reports- * 0 / max no matter what is typed.- */-function NoteComposer({ onChange }: { onChange: (content: string) => void }): JSX.Element {- const [content, setContent] = useState('')- return (- <LemonTextArea- autoFocus- value={content}- maxLength={NOTE_MAX_CHARS}- placeholder="e.g. we shipped a new checkout on Tuesday, watch conversion closely"- onChange={(value) => {- setContent(value)- onChange(value)- }}- />- )-}--/** Notes are written and retired through the skill, so the same editor access gates both. */-function noteWriteDisabledReason(): string | undefined {- return getAccessControlDisabledReason(AccessControlResourceType.LlmSkill, AccessControlLevel.Editor) ?? undefined-}-/*** The dialog closes itself only once the note saved. A failed request leaves it open with the text* still in the composer, so a long note is never lost to a transient error.@@ -72,7 +43,7 @@ function LeaveNoteDialog({content: (close) => {closeDialog = closereturn (- <NoteComposer+ <ScoutNoteComposeronChange={(value) => {content = value}}@@ -109,7 +80,7 @@ export function LeaveScoutNoteButton({}): JSX.Element {const logic = scoutNotesLogic({ skillName })const { savingNote } = useValues(logic)- const disabledReason = noteWriteDisabledReason()+ const disabledReason = scoutNoteWriteDisabledReason()return (<LemonButton@@ -268,7 +239,7 @@ function ScoutNoteRow({onDelete: () => void}): JSX.Element {const direct = isDirectScoutNote(note)- const disabledReason = noteWriteDisabledReason()+ const disabledReason = scoutNoteWriteDisabledReason()return (<div className="flex gap-3 border-b border-primary px-3 py-2.5 last:border-b-0">diff --git a/products/signals/frontend/inbox/components/detail/ActivityNoteQuote.tsx b/products/signals/frontend/inbox/components/detail/ActivityNoteQuote.tsxnew file mode 100644index 000000000000..7e5c81fb5218--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ActivityNoteQuote.tsx@@ -0,0 +1,29 @@+import { ScoutNoteAudience } from './ScoutNoteAudience'++/**+ * A note a person left, as it reads in Activity. The Notes list under the report shows the note itself+ * with its controls, so here it is a quote: the record of what was said and when.+ */+export function ActivityNoteQuote({+ reportId,+ text,+ scoutSkillName,+}: {+ reportId: string+ text: string+ /** Set for a note sent to the scouts. Blank means every scout. */+ scoutSkillName?: string+}): JSX.Element {+ return (+ <div className="w-full">+ {scoutSkillName !== undefined && (+ <span className="mb-1 block text-xs text-tertiary">+ <ScoutNoteAudience reportId={reportId} skillName={scoutSkillName} />+ </span>+ )}+ <blockquote className="m-0 whitespace-pre-wrap border-l-2 border-primary pl-2 text-xs italic text-secondary">+ {text}+ </blockquote>+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/detail/ArtefactLogList.test.tsx b/products/signals/frontend/inbox/components/detail/ArtefactLogList.test.tsxindex 7676e005c471..042152d9572c 100644--- a/products/signals/frontend/inbox/components/detail/ArtefactLogList.test.tsx+++ b/products/signals/frontend/inbox/components/detail/ArtefactLogList.test.tsx@@ -69,10 +69,10 @@ describe('ArtefactLogList', () => {/>)- expect(screen.getByText('Scout note left')).toBeInTheDocument()+ expect(screen.getByText('Note left for the scouts')).toBeInTheDocument()expect(screen.queryByText('scout_note_left')).not.toBeInTheDocument()expect(screen.getByText('Focus on the new checkout flow.')).toBeInTheDocument()- expect(screen.getByText('For signals-scout-web-analytics')).toBeInTheDocument()+ expect(screen.getByText('For Web analytics')).toBeInTheDocument()})it('labels an inconclusive check result and explains why', () => {diff --git a/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx b/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsxindex 1c041370d1d9..4d3efa880cae 100644--- a/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx+++ b/products/signals/frontend/inbox/components/detail/ArtefactLogList.tsx@@ -42,10 +42,12 @@ import { INBOX_RANKING_SCORES, PRIORITY_TAG_TYPE, rankingScoreForHead } from '..import { SignalCard } from '../../SignalCard'import { EnrichedReviewer, SignalReportActionability, SignalReportPriority, SignalReportArtefact } from '../../types'import { dismissalReasonLabel } from '../../utils/dismissalReasons'+import { prettifyScoutSkillName } from '../../utils/scoutRunsWindow'import { SignalReportActionabilityBadge } from '../badges/SignalReportActionabilityBadge'import { formatRankingLift, formatRankingProbability } from '../cards/rankingFormat'import { RankingLiftBar } from '../cards/RankingLiftBar'import { SignalCardDisclosureProvider } from '../signalCards/SignalCardShell'+import { ActivityNoteQuote } from './ActivityNoteQuote'import { ArtefactCommit } from './ArtefactCommit'import { ArtefactPullRequest } from './ArtefactPullRequest'import { ArtefactTaskRun } from './ArtefactTaskRun'@@ -152,7 +154,7 @@ const ARTEFACT_MARKER: Record<string, ComponentType<{ className?: string }>> = {commit: IconCommit,task_run: IconTerminal,note: IconComment,- scout_note_left: IconComment,+ scout_note_left: IconPencil,priority_judgment: IconFlag,actionability_judgment: IconListCheck,safety_judgment: IconShield,@@ -718,6 +720,7 @@ function renderArtefactSummary(artefact: SignalReportArtefact, monitoringEnabledfunction renderArtefactBody({monitoringEnabled,+ notesEnabled,reportId,artefact,knownTasks,@@ -728,6 +731,7 @@ function renderArtefactBody({knownTasks?: Map<string, Task>knownPullRequests: Map<string, SignalReportPullRequestApi>monitoringEnabled: boolean+ notesEnabled: boolean}): JSX.Element | null {const content = artefact.contentconst renderPullRequest = (url: string, outcome?: 'closed' | 'already_closed' | 'skipped'): JSX.Element => {@@ -773,15 +777,22 @@ function renderArtefactBody({}case 'note': {const c = content as NoteContent+ if (notesEnabled && artefact.actor_kind === 'user') {+ return <ActivityNoteQuote reportId={reportId} text={c.note} />+ }return <NoteBody note={c.note} author={c.author} />}case 'scout_note_left': {const c = content as ScoutNoteLeftContent+ if (notesEnabled) {+ return <ActivityNoteQuote reportId={reportId} text={c.note} scoutSkillName={c.skill_name} />+ }+ // Without the Notes list, the entry is the only place the note shows, so it reads as a note.return (<div className="w-full"><NoteBody note={c.note} /><span className="mt-1 block text-xs text-tertiary">- {c.skill_name?.trim() ? `For ${c.skill_name}` : 'For every scout on this project'}+ {c.skill_name?.trim() ? `For ${prettifyScoutSkillName(c.skill_name)}` : 'For every scout'}</span></div>)@@ -916,6 +927,7 @@ function ArtefactRow({knownPullRequests: Map<string, SignalReportPullRequestApi>}): JSX.Element {const monitoringEnabled = useFeatureFlag('SIGNALS_REPORT_MONITORING')+ const notesEnabled = useFeatureFlag('SIGNALS_REPORT_NOTES')const signalId = artefact.type === 'signal_finding' ? (artefact.content as SignalFindingContent).signal_id : nullconst signal = signalId ? knownSignals?.get(signalId) : undefinedconst location = artefactLocationLabel(artefact)@@ -924,7 +936,7 @@ function ArtefactRow({const body = signal ? (<SignalFindingBody signal={signal} />) : (- renderArtefactBody({ reportId, artefact, knownTasks, knownPullRequests, monitoringEnabled })+ renderArtefactBody({ reportId, artefact, knownTasks, knownPullRequests, monitoringEnabled, notesEnabled }))const bodyHasOwnCard = artefact.type === 'signal_finding' || artefact.type === 'commit'const MarkerIcon =diff --git a/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx b/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsxindex 75bc44be96fb..4b65f86d2134 100644--- a/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx+++ b/products/signals/frontend/inbox/components/detail/InboxDetail.stories.tsx@@ -24,9 +24,11 @@ import {} from '../../__mocks__/inboxMocks'import { reportMetricQueryHandler, reportMetricsFixture } from '../../__mocks__/reportMetricMocks'import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'-import { SignalReport, SignalReportStatus } from '../../types'+import { SignalReport, SignalReportArtefact, SignalReportStatus } from '../../types'import { AgentRunDetail } from './AgentRunDetail'+import { ArtefactLogList } from './ArtefactLogList'import { ReportDetail } from './ReportDetail'+import { ReportNotesSection } from './ReportNotesSection'import { ReportStatusSection } from './ReportStatusSection'const mixedPrChecks = {@@ -328,6 +330,110 @@ export const ReportClaimedByTeammate: Story = {),}+const NOTES_REPORT_ID = reportTabReports[0].id++// The active note is still listed; the retired one is gone from the list, so its entry reads inactive.+const reportNotesMocks = mswDecorator({+ get: {+ '/api/projects/:id/signals/scout/notes/': () => [+ 200,+ [+ {+ id: 'note-active',+ skill_name: 'signals-scout-checkout',+ content: `Note on inbox report \`${NOTES_REPORT_ID}\`:\n\nThe checkout flow is being rebuilt next month.`,+ created_at: '2026-06-10T09:00:00Z',+ expires_at: null,+ created_by_name: 'Octo Cat',+ origin: 'human',+ },+ ],+ ],+ '/api/projects/:id/signals/scout/configs/': () => [+ 200,+ [{ id: 'config-checkout', skill_name: 'signals-scout-checkout', display_name: 'Checkout watcher' }],+ ],+ },+})++const NOTE_AUTHOR = { id: 1, uuid: 'u-1', distinct_id: 'u-1', email: '[email protected]', first_name: 'Octo' }++const noteArtefacts: SignalReportArtefact[] = [+ {+ id: 'artefact-scout-note-active',+ type: 'scout_note_left',+ content: {+ note: 'The checkout flow is being rebuilt next month. Focus on the new flow instead.',+ skill_name: 'signals-scout-checkout',+ scout_note_id: 'note-active',+ },+ created_at: '2026-06-10T09:00:00Z',+ created_by: NOTE_AUTHOR,+ actor_kind: 'user',+ },+ {+ id: 'artefact-scout-note-retired',+ type: 'scout_note_left',+ content: { note: 'Anything under /legacy is out of scope.', skill_name: '', scout_note_id: 'note-retired' },+ created_at: '2026-06-09T09:00:00Z',+ created_by: NOTE_AUTHOR,+ actor_kind: 'user',+ },+ {+ id: 'artefact-note',+ type: 'note',+ content: { note: 'Support confirmed two more customers hit this on Monday.' },+ created_at: '2026-06-08T09:00:00Z',+ created_by: NOTE_AUTHOR,+ actor_kind: 'user',+ },+ {+ id: 'artefact-agent-note',+ type: 'note',+ content: { note: 'Confirmed the validation gap reproduces on an empty recipient row.' },+ created_at: '2026-06-07T09:00:00Z',+ task_id: 'task-research',+ actor_kind: 'task',+ },+]++// The notes under the report body. The agent's note stays out of the list, and the retired note reads inactive.+export const ReportNotes: Story = {+ decorators: [+ reportNotesMocks,+ mswDecorator({+ get: {+ '/api/projects/:id/signals/reports/:reportId/artefacts': () => [+ 200,+ { results: noteArtefacts, count: noteArtefacts.length },+ ],+ },+ }),+ ],+ render: () => (+ <Frame>+ <div className="w-full max-w-[44rem] border border-primary bg-surface-primary p-5">+ <ReportNotesSection report={{ ...reportTabReports[0], scout_name: 'signals-scout-checkout' }} />+ </div>+ </Frame>+ ),+}++// The activity log alone at rail width: in the full detail it sits collapsed below the snapshot's fold.+export const ActivityNotes: Story = {+ decorators: [reportNotesMocks],+ parameters: {+ featureFlags: { ...meta.parameters?.featureFlags, [FEATURE_FLAGS.SIGNALS_REPORT_NOTES]: true },+ },+ render: () => (+ <Frame>+ <div className="w-[26rem] border border-primary bg-surface-primary p-5">+ <ArtefactLogList reportId={NOTES_REPORT_ID} artefacts={noteArtefacts} />+ </div>+ </Frame>+ ),+}+export const ReportWithMetrics: Story = {render: () => (<Frame>diff --git a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx b/products/signals/frontend/inbox/components/detail/ReportDetail.tsxindex efbe7d24c790..cf3171595228 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetail.tsx@@ -55,6 +55,7 @@ import { useReportDetailActions } from './ReportDetailActions'import { ReportExpectedImpact } from './ReportExpectedImpact'import { ReportFeedbackFooter } from './ReportFeedbackFooter'import { ReportImpactMetrics } from './ReportImpactMetrics'+import { ReportNotesSection } from './ReportNotesSection'import { ReportPlanBlock } from './ReportPlanBlock'import { ReportPrimaryMetric } from './ReportPrimaryMetric'import { ReportSourceSuggestion } from './ReportSourceSuggestion'@@ -355,6 +356,7 @@ export function InboxDetailFrame({// The key observation leads the evidence rail; the supporting tiles belong to the body's Impact section.const metricsEnabled = useFeatureFlag('SIGNALS_REPORT_METRICS')const expectedImpactEnabled = useFeatureFlag('SIGNALS_EXPECTED_IMPACT_DISPLAY')+ const notesEnabled = useFeatureFlag('SIGNALS_REPORT_NOTES')const primaryMetric = metricsEnabled ? report.metrics?.find((metric) => metric.role === 'primary') : undefinedconst supportingMetrics = metricsEnabled? (report.metrics?.filter((metric) => metric.role !== 'primary') ?? [])@@ -417,8 +419,9 @@ export function InboxDetailFrame({)}</div></ReportChartsContext.Provider>- {/* The rating closes out the report body, pinned to the bottom of the column. */}+ {/* The notes and the rating close out the report body, pinned to the bottom of the column. */}<div className="mt-auto">+ {notesEnabled && <ReportNotesSection report={report} />}<ReportFeedbackFooter report={report} align="end" /></div></div>diff --git a/products/signals/frontend/inbox/components/detail/ReportNoteComposer.tsx b/products/signals/frontend/inbox/components/detail/ReportNoteComposer.tsxnew file mode 100644index 000000000000..0ef9c72d0356--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportNoteComposer.tsx@@ -0,0 +1,104 @@+import { useValues } from 'kea'+import { useState } from 'react'++import { LemonButton, LemonCheckbox, LemonInput, LemonSelect } from '@posthog/lemon-ui'++import { EVERY_SCOUT, reportNoteTargetOptions, reportNotesLogic } from '../../logics/reportNotesLogic'+import { scoutNoteWriteDisabledReason } from '../../logics/scoutNotesLogic'+import { SignalReport } from '../../types'+import { reportNoteMaxChars } from '../../utils/reportNotes'+import { ScoutNoteComposer } from '../config/scouts/ScoutNoteComposer'++/**+ * The open composer. It mounts the notes logic, so a report that nobody writes a note on never loads+ * the scout fleet for the target picker.+ */+function OpenComposer({ report, onClose }: { report: SignalReport; onClose: () => void }): JSX.Element {+ const reportScoutName = report.scout_name ?? null+ const logic = reportNotesLogic({ reportId: report.id })+ const { scoutNamesBySkill, scoutConfigsLoading, savingNote } = useValues(logic)+ const steerDisabledReason = scoutNoteWriteDisabledReason()+ const [text, setText] = useState('')+ // A note on a scout's report is most often steering for that scout, so start with it selected+ // when the person is allowed to send one.+ const [sendToScouts, setSendToScouts] = useState(!!reportScoutName && !steerDisabledReason)+ const [skillName, setSkillName] = useState(reportScoutName ?? EVERY_SCOUT)++ const submit = async (): Promise<void> => {+ await logic.asyncActions.addNote(text.trim(), sendToScouts ? skillName : null, reportScoutName)+ // A failed save keeps the composer open with the text, so a long note is never lost.+ if (!logic.values.lastSaveFailed) {+ onClose()+ }+ }++ return (+ <div className="flex flex-col gap-2 rounded border border-primary bg-surface-primary p-2">+ <ScoutNoteComposer+ maxLength={reportNoteMaxChars(report.id)}+ placeholder="e.g. this checkout flow is being replaced next month"+ onChange={setText}+ />+ <div className="flex flex-wrap items-center gap-2">+ <LemonCheckbox+ size="small"+ checked={sendToScouts}+ disabledReason={steerDisabledReason}+ onChange={setSendToScouts}+ label="Also send to the scouts"+ data-attr="inbox-report-note-send-to-scouts"+ />+ {sendToScouts && (+ <LemonSelect+ size="small"+ value={skillName}+ options={reportNoteTargetOptions(scoutNamesBySkill, reportScoutName)}+ loading={scoutConfigsLoading}+ onChange={setSkillName}+ data-attr="inbox-report-note-target"+ />+ )}+ <span className="flex-1" />+ <LemonButton+ size="small"+ type="tertiary"+ onClick={onClose}+ disabledReason={savingNote ? 'Saving' : undefined}+ >+ Cancel+ </LemonButton>+ <LemonButton+ size="small"+ type="primary"+ loading={savingNote}+ disabledReason={text.trim() ? undefined : 'Write a note first'}+ onClick={() => void submit()}+ data-attr="inbox-report-note-submit"+ >+ Add note+ </LemonButton>+ </div>+ {sendToScouts && (+ <span className="text-xs text-tertiary">+ Scouts read the note at the start of every run until you retire it.+ </span>+ )}+ </div>+ )+}++export function ReportNoteComposer({ report }: { report: SignalReport }): JSX.Element {+ const [open, setOpen] = useState(false)+ if (open) {+ return <OpenComposer report={report} onClose={() => setOpen(false)} />+ }+ return (+ <LemonInput+ size="small"+ placeholder="Add a note…"+ onFocus={() => setOpen(true)}+ aria-label="Add a note about this report"+ data-attr="inbox-report-note-box"+ />+ )+}diff --git a/products/signals/frontend/inbox/components/detail/ReportNoteRow.tsx b/products/signals/frontend/inbox/components/detail/ReportNoteRow.tsxnew file mode 100644index 000000000000..65bc1e0ea733--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportNoteRow.tsx@@ -0,0 +1,38 @@+import { LemonTag, ProfilePicture } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'++import { SignalReportArtefact } from '../../types'+import { artefactAttributionLabel, NoteContent, ScoutNoteLeftContent } from './artefactTypes'+import { ScoutNoteAudience } from './ScoutNoteAudience'+import { ScoutNoteStatus } from './ScoutNoteStatus'++export function ReportNoteRow({ reportId, note }: { reportId: string; note: SignalReportArtefact }): JSX.Element {+ const scoutNote = note.type === 'scout_note_left' ? (note.content as ScoutNoteLeftContent) : null+ const text = scoutNote ? scoutNote.note : (note.content as NoteContent).note+ const author = artefactAttributionLabel(note) ?? 'Someone'++ return (+ <div className="flex gap-2.5 border-b border-primary px-3 py-2.5 last:border-b-0">+ <ProfilePicture user={note.created_by ?? { first_name: author }} size="md" />+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-1.5 text-xs">+ <span className="font-medium text-default">{author}</span>+ <TZLabel time={note.created_at} className="text-tertiary" />+ {scoutNote && (+ <>+ <LemonTag size="small" type="option">+ <ScoutNoteAudience reportId={reportId} skillName={scoutNote.skill_name} />+ </LemonTag>+ <ScoutNoteStatus reportId={reportId} scoutNoteId={scoutNote.scout_note_id} />+ </>+ )}+ </div>+ <LemonMarkdown className="mt-1 text-sm text-default" disableImages>+ {text}+ </LemonMarkdown>+ </div>+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/detail/ReportNotesSection.tsx b/products/signals/frontend/inbox/components/detail/ReportNotesSection.tsxnew file mode 100644index 000000000000..81a5ae7a548d--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ReportNotesSection.tsx@@ -0,0 +1,32 @@+import { useValues } from 'kea'++import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'+import { SignalReport } from '../../types'+import { reportNotesFromArtefacts } from '../../utils/reportNotes'+import { ReportNoteComposer } from './ReportNoteComposer'+import { ReportNoteRow } from './ReportNoteRow'++/**+ * The notes people left on the report, at the end of its body. Activity records the same notes as+ * quotes in the report's history, so this list is where they are read and retired.+ */+export function ReportNotesSection({ report }: { report: SignalReport }): JSX.Element {+ const { reportArtefacts } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))+ const notes = reportNotesFromArtefacts(reportArtefacts ?? [])++ return (+ <div className="mb-4 flex flex-col gap-2" data-attr="inbox-report-notes">+ {notes.length > 0 && (+ <>+ <span className="text-xs font-semibold text-secondary">Notes · {notes.length}</span>+ <div className="flex flex-col rounded border border-primary bg-surface-primary">+ {notes.map((note) => (+ <ReportNoteRow key={note.id} reportId={report.id} note={note} />+ ))}+ </div>+ </>+ )}+ <ReportNoteComposer report={report} />+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/detail/ScoutNoteAudience.tsx b/products/signals/frontend/inbox/components/detail/ScoutNoteAudience.tsxnew file mode 100644index 000000000000..0d0a363afa11--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ScoutNoteAudience.tsx@@ -0,0 +1,9 @@+import { useValues } from 'kea'++import { reportNoteAudience, reportNotesLogic } from '../../logics/reportNotesLogic'++/** "For <scout>" or "For every scout", using the scout's display name once the fleet has loaded. */+export function ScoutNoteAudience({ reportId, skillName }: { reportId: string; skillName: string }): JSX.Element {+ const { scoutNamesBySkill } = useValues(reportNotesLogic({ reportId }))+ return <>{reportNoteAudience(skillName, scoutNamesBySkill)}</>+}diff --git a/products/signals/frontend/inbox/components/detail/ScoutNoteStatus.tsx b/products/signals/frontend/inbox/components/detail/ScoutNoteStatus.tsxnew file mode 100644index 000000000000..a422e98c2f45--- /dev/null+++ b/products/signals/frontend/inbox/components/detail/ScoutNoteStatus.tsx@@ -0,0 +1,64 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonDialog, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { reportNotesLogic } from '../../logics/reportNotesLogic'+import { scoutNoteWriteDisabledReason } from '../../logics/scoutNotesLogic'++/** Whether the scouts still read a note sent from this report, and the control to stop them. */+export function ScoutNoteStatus({+ reportId,+ scoutNoteId,+}: {+ reportId: string+ scoutNoteId: string+}): JSX.Element | null {+ const logic = reportNotesLogic({ reportId })+ const { activeNoteIds, notesResolved, notesLoadFailed, notesCapped } = useValues(logic)+ const { retireNote } = useActions(logic)++ // Unknown until the notes load. A failed load says nothing rather than claim the note is retired,+ // and neither does a capped read, which can leave an older active note out of what it returned.+ if (!notesResolved || notesLoadFailed) {+ return null+ }+ if (!activeNoteIds.has(scoutNoteId)) {+ if (notesCapped) {+ return null+ }+ return (+ <Tooltip title="Retired or expired. Scouts no longer read it.">+ <LemonTag size="small" type="muted">+ Inactive+ </LemonTag>+ </Tooltip>+ )+ }+ return (+ <>+ <LemonTag size="small" type="success">+ Active+ </LemonTag>+ <LemonButton+ size="xsmall"+ type="tertiary"+ disabledReason={scoutNoteWriteDisabledReason()}+ onClick={() =>+ LemonDialog.open({+ title: 'Retire this note?',+ description: 'Scouts stop reading it from their next run onward. It stays on the report.',+ primaryButton: {+ children: 'Retire',+ status: 'danger',+ onClick: () => retireNote(scoutNoteId),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+ data-attr="inbox-report-note-retire"+ >+ Retire+ </LemonButton>+ </>+ )+}diff --git a/products/signals/frontend/inbox/components/detail/artefactTypes.ts b/products/signals/frontend/inbox/components/detail/artefactTypes.tsindex 818f20008e16..f3f74eec7952 100644--- a/products/signals/frontend/inbox/components/detail/artefactTypes.ts+++ b/products/signals/frontend/inbox/components/detail/artefactTypes.ts@@ -51,9 +51,9 @@ export interface NoteContent {export interface ScoutNoteLeftContent {note: string- /** Blank when the note was addressed to every scout on the project. */- skill_name?: string- scout_note_id?: string+ /** Blank when the note went to every scout. */+ skill_name: string+ scout_note_id: string}export interface SignalFindingContent {@@ -359,7 +359,7 @@ export const ARTEFACT_TYPE_LABELS: Record<string, string> = {commit: 'Commit pushed',task_run: 'Task run',note: 'Note added',- scout_note_left: 'Scout note left',+ scout_note_left: 'Note left for the scouts',priority_judgment: 'Priority assessed',actionability_judgment: 'Actionability assessed',safety_judgment: 'Safety assessed',diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex 0cbb2d9214d5..cbc927ad6125 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -194,6 +194,7 @@ export type InboxReportActionType =| 'claim'| 'unclaim'| 'expand_preview'+ | 'add_note'/*** Where the text of an "Ask AI" question came from. `suggested` is a scout-authored question sent as@@ -239,10 +240,10 @@ export type InboxReportActionOutcome = 'success' | 'failure' | 'blocked' | 'limiexport type InboxPanelName = 'runs' | 'config' | 'sources' | 'scratchpad' | 'findings' | 'triage' | 'onboarding'/** A panel read that carries its own timeout, named so each one's stall rate reads separately. */-export type InboxPanelLoad = 'scout_notes' | 'scout_memory'+export type InboxPanelLoad = 'scout_notes' | 'scout_memory' | 'report_notes'/** A report write that carries its own timeout. `state` covers dismiss, resolve, restore, and monitoring. */-export type InboxWrite = 'claim' | 'priority' | 'state'+export type InboxWrite = 'claim' | 'note' | 'priority' | 'retire_note' | 'state'/** Which control moved the report list to a new query. `url` is a shared/deep link being applied. */export type InboxQueryChange =@@ -258,7 +259,7 @@ export type InboxQueryChange =| 'created_window'/** Surface a scout-management event fired from. Matches the desktop values. */-export type ScoutSurface = 'fleet_list' | 'scout_detail' | 'empty_state' | 'replay_vision_scanner'+export type ScoutSurface = 'fleet_list' | 'scout_detail' | 'empty_state' | 'replay_vision_scanner' | 'report_detail'/*** Scout-management actions. The first block matches desktop's enum; the trailing block isdiff --git a/products/signals/frontend/inbox/logics/reportNotesLogic.test.ts b/products/signals/frontend/inbox/logics/reportNotesLogic.test.tsnew file mode 100644index 000000000000..424be52344fa--- /dev/null+++ b/products/signals/frontend/inbox/logics/reportNotesLogic.test.ts@@ -0,0 +1,106 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { EVERY_SCOUT, reportNotesLogic } from './reportNotesLogic'++const NOTES_URL = '/api/projects/:team_id/signals/scout/notes/'+const ARTEFACTS_URL = '/api/projects/:team_id/signals/reports/:report_id/artefacts/'+const REPORT_ID = '0b9f8a52-3c1e-4d7a-9f60-2a4e1c7b8d01'+const REPORT_SCOUT = 'signals-scout-checkout'++describe('reportNotesLogic', () => {+ let logic: ReturnType<typeof reportNotesLogic.build>+ let listQueries: URLSearchParams[]+ let scoutNoteBodies: Record<string, unknown>[]+ let artefactBodies: Record<string, unknown>[]+ let notesOnServer: Record<string, unknown>[]++ beforeEach(() => {+ listQueries = []+ scoutNoteBodies = []+ artefactBodies = []+ notesOnServer = []+ useMocks({+ get: {+ [NOTES_URL]: ({ request }) => {+ listQueries.push(new URL(request.url).searchParams)+ return [200, notesOnServer]+ },+ '/api/projects/:team_id/signals/scout/configs/': () => [200, []],+ },+ post: {+ [NOTES_URL]: async ({ request }) => {+ const body = (await request.json()) as Record<string, unknown>+ scoutNoteBodies.push(body)+ return [201, { id: 'note-1', origin: 'human', ...body }]+ },+ [ARTEFACTS_URL]: async ({ request }) => {+ const body = (await request.json()) as Record<string, unknown>+ artefactBodies.push(body)+ return [201, { id: 'artefact-1', type: 'note', content: body.content }]+ },+ },+ })+ initKeaTests()+ logic = reportNotesLogic({ reportId: REPORT_ID })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('finds notes by the report id they quote, across every scout', async () => {+ await expectLogic(logic).toFinishAllListeners()++ // A `skill_name` here would miss notes sent to other scouts, so their entries would read inactive.+ expect(listQueries[0].get('text')).toEqual(REPORT_ID)+ expect(listQueries[0].has('skill_name')).toBe(false)+ })++ it.each([+ {+ name: 'a note for the report scout goes to the scouts, tied to the report',+ scoutTarget: REPORT_SCOUT,+ scoutNotes: [{ content: 'Focus on the new checkout flow', report_id: REPORT_ID, skill_name: REPORT_SCOUT }],+ artefacts: [],+ },+ {+ name: 'a note for every scout leaves the target blank',+ scoutTarget: EVERY_SCOUT,+ scoutNotes: [{ content: 'Focus on the new checkout flow', report_id: REPORT_ID }],+ artefacts: [],+ },+ {+ name: 'a note kept on the report never reaches the scouts',+ scoutTarget: null,+ scoutNotes: [],+ artefacts: [{ artefact_type: 'note', content: { note: 'Focus on the new checkout flow' } }],+ },+ ])('$name', async ({ scoutTarget, scoutNotes, artefacts }) => {+ await logic.asyncActions.addNote('Focus on the new checkout flow', scoutTarget, REPORT_SCOUT)++ expect(scoutNoteBodies).toEqual(scoutNotes)+ expect(artefactBodies).toEqual(artefacts)+ expect(logic.values.lastSaveFailed).toBe(false)+ })++ it('reads the notes back when a retire fails, since the delete may still have landed', async () => {+ notesOnServer = [{ id: 'note-1', origin: 'human', content: `About ${REPORT_ID}` }]+ logic.actions.loadNotes()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.activeNoteIds.has('note-1')).toBe(true)++ // The delete landed and the response did not, so the optimistic flag alone would be undone+ // and the entry would read active again.+ useMocks({ delete: { [`${NOTES_URL}:id/`]: () => [500, {}] } })+ notesOnServer = []+ logic.actions.retireNote('note-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.activeNoteIds.has('note-1')).toBe(false)+ })+})diff --git a/products/signals/frontend/inbox/logics/reportNotesLogic.ts b/products/signals/frontend/inbox/logics/reportNotesLogic.tsnew file mode 100644index 000000000000..b0f519f87b8d--- /dev/null+++ b/products/signals/frontend/inbox/logics/reportNotesLogic.ts@@ -0,0 +1,366 @@+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import { teamLogic } from 'scenes/teamLogic'++import {+ signalsReportArtefactsCreate,+ signalsScoutConfigList,+ signalsScoutNotesCreate,+ signalsScoutNotesDestroy,+} from 'products/signals/frontend/generated/api'+import type { ScoutNoteApi, SignalScoutConfigApi } from 'products/signals/frontend/generated/api.schemas'++import { captureInboxReportAction, captureScoutAction } from '../inboxAnalytics'+import { prettifyScoutSkillName, scoutDisplayName } from '../utils/scoutRunsWindow'+import { withInboxWriteTimeout } from '../utils/writeTimeout'+import { inboxReportDetailLogic } from './inboxReportDetailLogic'+import { NOTES_FETCH_LIMIT, fetchScoutNotes } from './scoutNotesLogic'++export interface ReportNotesLogicProps {+ reportId: string+}++/** The note target that reaches every scout. Matches the blank `skill_name` the API stores. */+export const EVERY_SCOUT = ''++export interface ReportNoteTargetOption {+ value: string+ label: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface reportNotesLogicValues {+ activeNoteIds: Set<string>+ lastSaveFailed: boolean+ notes: ScoutNoteApi[]+ notesCapped: boolean+ notesLoadFailed: boolean+ notesLoading: boolean+ notesResolved: boolean+ retiredNoteIds: string[]+ savingNote: boolean+ scoutConfigs: SignalScoutConfigApi[] | null+ scoutConfigsLoading: boolean+ scoutNamesBySkill: Record<string, string>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface reportNotesLogicActions {+ addNote: (+ content: string,+ scoutTarget: string | null,+ reportScoutName: string | null+ ) => {+ content: string+ reportScoutName: string | null+ scoutTarget: string | null+ }+ addNoteFailed: () => {+ value: true+ }+ addNoteFinished: () => {+ value: true+ }+ loadNotes: (_payload: void) => void+ loadNotesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadNotesSuccess: (+ notes: ScoutNoteApi[],+ payload?: void+ ) => {+ notes: ScoutNoteApi[]+ payload?: void+ }+ loadScoutConfigs: () => any+ loadScoutConfigsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadScoutConfigsSuccess: (+ scoutConfigs: SignalScoutConfigApi[] | null,+ payload?: any+ ) => {+ scoutConfigs: SignalScoutConfigApi[] | null+ payload?: any+ }+ retireNote: (noteId: string) => {+ noteId: string+ }+ retireNoteFailed: (noteId: string) => {+ noteId: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface reportNotesLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ activeNoteIds: (notes: ScoutNoteApi[], retiredNoteIds: string[]) => Set<string>+ notesCapped: (notes: ScoutNoteApi[]) => boolean+ scoutNamesBySkill: (scoutConfigs: SignalScoutConfigApi[] | null) => Record<string, string>+ }+}++export type reportNotesLogicType = MakeLogicType<+ reportNotesLogicValues,+ reportNotesLogicActions,+ ReportNotesLogicProps,+ reportNotesLogicMeta+>++/** Who a scout note reaches, in the words the Activity entry and the target picker use. */+export function reportNoteAudience(skillName: string, scoutNamesBySkill: Record<string, string>): string {+ return skillName === EVERY_SCOUT+ ? 'For every scout'+ : `For ${scoutNamesBySkill[skillName] ?? prettifyScoutSkillName(skillName)}`+}++/**+ * The report's own scout first, since that is who a note on its report is usually for. Without one,+ * every scout leads. The rest of the fleet follows by name.+ */+export function reportNoteTargetOptions(+ scoutNamesBySkill: Record<string, string>,+ reportScoutName: string | null+): ReportNoteTargetOption[] {+ const everyScout = { value: EVERY_SCOUT, label: 'Every scout' }+ const others = Object.entries(scoutNamesBySkill)+ .filter(([skillName]) => skillName !== reportScoutName)+ .map(([skillName, name]) => ({ value: skillName, label: name }))+ .sort((a, b) => a.label.localeCompare(b.label))+ if (!reportScoutName) {+ return [everyScout, ...others]+ }+ const reportScoutLabel = scoutNamesBySkill[reportScoutName] ?? prettifyScoutSkillName(reportScoutName)+ return [{ value: reportScoutName, label: `${reportScoutLabel} (filed this report)` }, everyScout, ...others]+}++/**+ * Notes people add to a report. Every note lands on the report's activity log: a plain `note` entry,+ * or, when it is sent to the scouts, a scout note that the server records as a `scout_note_left` entry.+ * The scout notes that quote the report id are loaded so each such entry can say whether the scouts+ * still read it.+ */+export const reportNotesLogic = kea<reportNotesLogicType>([+ path((key) => ['products', 'signals', 'inbox', 'logics', 'reportNotesLogic', key]),+ props({} as ReportNotesLogicProps),+ key((props) => props.reportId),++ actions({+ // `scoutTarget` is null for a note that stays on the report, else a skill name or `EVERY_SCOUT`.+ addNote: (content: string, scoutTarget: string | null, reportScoutName: string | null) => ({+ content,+ scoutTarget,+ reportScoutName,+ }),+ addNoteFailed: true,+ addNoteFinished: true,+ retireNote: (noteId: string) => ({ noteId }),+ retireNoteFailed: (noteId: string) => ({ noteId }),+ }),++ loaders(({ props }) => ({+ notes: [+ [] as ScoutNoteApi[],+ {+ loadNotes: async (_payload: void, breakpoint) =>+ await fetchScoutNotes(+ 'report_notes',+ { text: props.reportId, limit: NOTES_FETCH_LIMIT },+ breakpoint+ ),+ },+ ],+ scoutConfigs: [+ null as SignalScoutConfigApi[] | null,+ {+ loadScoutConfigs: async () => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return null+ }+ return await signalsScoutConfigList(String(teamId))+ },+ },+ ],+ })),++ reducers({+ // Retired here, whatever the server has said since. A load that was already in flight when+ // the note was retired can resolve after the delete and would otherwise mark it active again.+ retiredNoteIds: [+ [] as string[],+ {+ retireNote: (state, { noteId }) => [...state, noteId],+ retireNoteFailed: (state, { noteId }) => state.filter((id) => id !== noteId),+ },+ ],+ notesLoadFailed: [+ false,+ {+ loadNotes: () => false,+ loadNotesSuccess: () => false,+ loadNotesFailure: () => true,+ },+ ],+ // Until the first read lands, a scout note's status is unknown rather than inactive.+ notesResolved: [+ false,+ {+ loadNotesSuccess: () => true,+ },+ ],+ savingNote: [+ false,+ {+ addNote: () => true,+ addNoteFinished: () => false,+ },+ ],+ // The composer awaits `addNote` and reads this to decide whether to close, since a listener+ // cannot return a result.+ lastSaveFailed: [+ false,+ {+ addNote: () => false,+ addNoteFailed: () => true,+ },+ ],+ }),++ selectors({+ activeNoteIds: [+ (s) => [s.notes, s.retiredNoteIds],+ (notes: ScoutNoteApi[], retiredNoteIds: string[]): Set<string> =>+ new Set(notes.map((note) => note.id).filter((id) => !retiredNoteIds.includes(id))),+ ],+ // One request, newest first. A report that somehow fills it leaves older notes out, so an+ // entry whose note is missing cannot be called retired.+ notesCapped: [(s) => [s.notes], (notes: ScoutNoteApi[]): boolean => notes.length >= NOTES_FETCH_LIMIT],+ scoutNamesBySkill: [+ (s) => [s.scoutConfigs],+ (scoutConfigs: SignalScoutConfigApi[] | null): Record<string, string> =>+ Object.fromEntries((scoutConfigs ?? []).map((config) => [config.skill_name, scoutDisplayName(config)])),+ ],+ }),++ listeners(({ actions, props, values }) => ({+ addNote: async ({ content, scoutTarget, reportScoutName }) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ actions.addNoteFailed()+ actions.addNoteFinished()+ return+ }+ const detailLogic = inboxReportDetailLogic.findMounted({ reportId: props.reportId })+ try {+ if (scoutTarget === null) {+ await withInboxWriteTimeout('note', (options) =>+ signalsReportArtefactsCreate(+ String(teamId),+ props.reportId,+ { artefact_type: 'note', content: { note: content } },+ options+ )+ )+ } else {+ await withInboxWriteTimeout('note', (options) =>+ signalsScoutNotesCreate(+ String(teamId),+ {+ content,+ report_id: props.reportId,+ ...(scoutTarget !== EVERY_SCOUT ? { skill_name: scoutTarget } : {}),+ },+ options+ )+ )+ }+ const noteTarget =+ scoutTarget === null+ ? 'report'+ : scoutTarget === EVERY_SCOUT+ ? 'fleet'+ : scoutTarget === reportScoutName+ ? 'report_scout'+ : 'other_scout'+ captureInboxReportAction({+ report: detailLogic?.props.report,+ actionType: 'add_note',+ surface: 'detail_pane',+ extra: { sent_to_scouts: scoutTarget !== null, note_target: noteTarget },+ })+ if (scoutTarget !== null) {+ // Scout surfaces count notes left from every surface through this event.+ captureScoutAction({+ actionType: 'leave_note',+ surface: 'report_detail',+ skillName: scoutTarget || null,+ extra: {+ report_id: props.reportId,+ report_has_scout: !!reportScoutName,+ note_target: noteTarget,+ },+ })+ lemonToast.success(+ scoutTarget === EVERY_SCOUT+ ? 'Note added. Every scout picks it up on its next run.'+ : 'Note added. The scout picks it up on its next run.'+ )+ actions.loadNotes()+ } else {+ lemonToast.success('Note added')+ }+ detailLogic?.actions.loadReportArtefacts()+ } catch (error: any) {+ lemonToast.error(error?.detail || error?.message || 'Failed to add the note')+ actions.addNoteFailed()+ // A write that timed out can still have landed, so read both surfaces back rather+ // than trust the local copy.+ actions.loadNotes()+ detailLogic?.actions.loadReportArtefacts()+ } finally {+ actions.addNoteFinished()+ }+ },+ retireNote: async ({ noteId }) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return+ }+ const skillName = values.notes.find((note) => note.id === noteId)?.skill_name+ try {+ await withInboxWriteTimeout('retire_note', (options) =>+ signalsScoutNotesDestroy(String(teamId), noteId, options)+ )+ captureScoutAction({+ actionType: 'delete_note',+ surface: 'report_detail',+ skillName: skillName || null,+ extra: { report_id: props.reportId },+ })+ } catch (error: any) {+ lemonToast.error(error?.detail || error?.message || 'Failed to retire the note')+ actions.retireNoteFailed(noteId)+ // The delete may still have landed, so let the next read decide the entry's status.+ actions.loadNotes()+ }+ },+ })),++ afterMount(({ actions }) => {+ actions.loadNotes()+ actions.loadScoutConfigs()+ }),+])diff --git a/products/signals/frontend/inbox/logics/scoutNotesLogic.ts b/products/signals/frontend/inbox/logics/scoutNotesLogic.tsindex 73bc1f6b2310..96f37e426e2b 100644--- a/products/signals/frontend/inbox/logics/scoutNotesLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutNotesLogic.ts@@ -1,18 +1,34 @@-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import {+ BreakPointFunction,+ MakeLogicType,+ actions,+ afterMount,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'import { loaders } from 'kea-loaders'import { lemonToast } from '@posthog/lemon-ui'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { teamLogic } from 'scenes/teamLogic'+import { AccessControlLevel, AccessControlResourceType } from '~/types'+import {signalsScoutNotesCreate,signalsScoutNotesDestroy,signalsScoutNotesList,} from 'products/signals/frontend/generated/api'-import type { ScoutNoteApi } from 'products/signals/frontend/generated/api.schemas'+import type { ScoutNoteApi, SignalsScoutNotesListParams } from 'products/signals/frontend/generated/api.schemas'import { captureScoutAction } from '../inboxAnalytics'+import type { InboxPanelLoad } from '../inboxAnalytics'import { withPanelLoadTimeout } from '../utils/panelLoadTimeout'export interface ScoutNotesLogicProps {@@ -44,12 +60,44 @@ export function isDirectScoutNote(note: ScoutNoteApi): boolean {return note.origin === 'human'}+/** Bounded by the create serializer; mirrored here so a composer can say so before a failed request. */+export const SCOUT_NOTE_MAX_CHARS = 10000++/** Notes are written and retired through the skill, so the same editor access gates both. */+export function scoutNoteWriteDisabledReason(): string | undefined {+ return getAccessControlDisabledReason(AccessControlResourceType.LlmSkill, AccessControlLevel.Editor) ?? undefined+}+/*** One request, newest first. Well above any real history (a scout carries a handful of notes), but* a scout that somehow hits it shows a caption rather than a silently short list.*/export const NOTES_FETCH_LIMIT = 200+/**+ * A save reloads the notes, so a second read can start while the first is still in flight. The+ * breakpoint on both paths stops the older read answering for the newer one — including when what+ * it has to say is its own timeout.+ */+export async function fetchScoutNotes(+ load: InboxPanelLoad,+ params: SignalsScoutNotesListParams,+ breakpoint: BreakPointFunction+): Promise<ScoutNoteApi[]> {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return []+ }+ const notes = await withPanelLoadTimeout(load, (options) =>+ signalsScoutNotesList(String(teamId), params, options)+ ).catch((error: unknown) => {+ breakpoint()+ throw error+ })+ breakpoint()+ return notes+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scoutNotesLogicValues {activeNotes: ScoutNoteApi[]@@ -147,30 +195,15 @@ export const scoutNotesLogic = kea<scoutNotesLogicType>([notes: [[] as ScoutNoteApi[],{- loadNotes: async (_payload: void, breakpoint) => {- const teamId = teamLogic.values.currentTeamId- if (!teamId) {- return []- }- // A save reloads the notes, so a second read can start while the first is still- // in flight. The breakpoint on both paths stops the older read answering for- // the newer one — including when what it has to say is its own timeout.- const notes = await withPanelLoadTimeout('scout_notes', (options) =>- signalsScoutNotesList(- String(teamId),- {- limit: NOTES_FETCH_LIMIT,- ...(props.skillName ? { skill_name: props.skillName } : {}),- },- options- )- ).catch((error: unknown) => {- breakpoint()- throw error- })- breakpoint()- return notes- },+ loadNotes: async (_payload: void, breakpoint) =>+ await fetchScoutNotes(+ 'scout_notes',+ {+ limit: NOTES_FETCH_LIMIT,+ ...(props.skillName ? { skill_name: props.skillName } : {}),+ },+ breakpoint+ ),},],})),diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.tsindex b6d62566890b..8f6ccc5502d3 100644--- a/products/signals/frontend/inbox/types.ts+++ b/products/signals/frontend/inbox/types.ts@@ -1,5 +1,6 @@import type { UserBasicType } from '~/types'+import type { SignalActorKindEnumApi } from 'products/signals/frontend/generated/api.schemas'import {type SignalReportApi,type PatchedSignalSourceConfigApi,@@ -197,6 +198,8 @@ export interface SignalReportArtefact {created_by?: UserBasicType | null/** Set when an agent task produced the artefact (attribution reads "by agent"). */task_id?: string | null+ /** Who produced the artefact: a person, an internal task, an external agent, or the pipeline. */+ actor_kind?: SignalActorKindEnumApi}export interface SignalReportArtefactResponse {diff --git a/products/signals/frontend/inbox/utils/reportNotes.test.ts b/products/signals/frontend/inbox/utils/reportNotes.test.tsnew file mode 100644index 000000000000..c999c5fb6f6e--- /dev/null+++ b/products/signals/frontend/inbox/utils/reportNotes.test.ts@@ -0,0 +1,28 @@+import type { SignalReportArtefact } from '../types'+import { reportNotesFromArtefacts } from './reportNotes'++function artefact(overrides: Partial<SignalReportArtefact>): SignalReportArtefact {+ return { id: 'a', type: 'note', content: { note: 'text' }, created_at: '2026-06-10T09:00:00Z', ...overrides }+}++describe('reportNotesFromArtefacts', () => {+ it('keeps the notes people left, oldest first, and leaves agent and pipeline notes in Activity only', () => {+ const notes = reportNotesFromArtefacts([+ artefact({+ id: 'scout-note',+ type: 'scout_note_left',+ actor_kind: 'user',+ created_at: '2026-06-11T09:00:00Z',+ }),+ artefact({ id: 'agent-scout-note', type: 'scout_note_left', actor_kind: 'agent' }),+ artefact({ id: 'task-scout-note', type: 'scout_note_left', actor_kind: 'task' }),+ artefact({ id: 'person-note', actor_kind: 'user', created_at: '2026-06-09T09:00:00Z' }),+ artefact({ id: 'task-note', actor_kind: 'task' }),+ artefact({ id: 'mcp-agent-note', actor_kind: 'agent' }),+ artefact({ id: 'legacy-note', actor_kind: 'system' }),+ artefact({ id: 'commit', type: 'commit', actor_kind: 'user' }),+ ])++ expect(notes.map((note) => note.id)).toEqual(['person-note', 'scout-note'])+ })+})diff --git a/products/signals/frontend/inbox/utils/reportNotes.ts b/products/signals/frontend/inbox/utils/reportNotes.tsnew file mode 100644index 000000000000..8f24b338bc06--- /dev/null+++ b/products/signals/frontend/inbox/utils/reportNotes.ts@@ -0,0 +1,30 @@+import { SCOUT_NOTE_MAX_CHARS } from '../logics/scoutNotesLogic'+import type { SignalReportArtefact } from '../types'++/**+ * The notes API writes this prefix when a note is created with a `report_id` (`report_note_content`+ * in `report_scout_notes.py`), so the text a person types has to leave room for it.+ */+function reportNotePrefix(reportId: string): string {+ return `Note on inbox report \`${reportId}\`:\n\n`+}++/** What a person can type, so the prefixed note still fits under the create serializer's cap. */+export function reportNoteMaxChars(reportId: string): number {+ return SCOUT_NOTE_MAX_CHARS - reportNotePrefix(reportId).length+}++/**+ * A note a person left on the report. Agents write both kinds too, through the MCP notes tool and the+ * artefact API, and those stay in Activity only, so the Notes list reads as what people said about the+ * report. An agent note also carries the human principal in `created_by`, so without this check the row+ * would put automated text under that person's name and avatar.+ */+export function isPersonReportNote(artefact: SignalReportArtefact): boolean {+ return (artefact.type === 'scout_note_left' || artefact.type === 'note') && artefact.actor_kind === 'user'+}++/** Oldest first, so a new note lands at the bottom next to the box it was written in. */+export function reportNotesFromArtefacts(artefacts: SignalReportArtefact[]): SignalReportArtefact[] {+ return artefacts.filter(isPersonReportNote).sort((a, b) => a.created_at.localeCompare(b.created_at))+}