: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): collapse long scout notes behind a show more (#87210)
Andrew Maguire6bcc3713d7ee
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNoteContent.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNoteContent.tsxnew file mode 100644index 000000000000..c8654c755b09--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNoteContent.tsx@@ -0,0 +1,51 @@+import { useId, useRef, useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'++import { scoutNotePreview } from './scoutNotePreview'++/** The opening of a note is enough to recognize it; the rest is one click away. */+export function ScoutNoteContent({ content }: { content: string }): JSX.Element {+ const [expanded, setExpanded] = useState(false)+ const bodyId = useId()+ const bodyRef = useRef<HTMLDivElement>(null)+ const preview = scoutNotePreview(content)+ const truncated = preview !== content++ const toggle = (): void => {+ const next = !expanded+ setExpanded(next)+ // The toggle sits after the note body, so the links a note's tail may hold now sit before+ // the focus. Move focus into the body on expand, so a keyboard user tabs onto them instead+ // of straight past them.+ if (next) {+ bodyRef.current?.focus()+ }+ }++ return (+ <div className="flex flex-col gap-1">+ {/* The body keeps the row's width, so a blockquote or a rule spans the note rather than+ shrinking to its own content. Only the toggle sits at the start. */}+ <div id={bodyId} ref={bodyRef} tabIndex={-1}>+ <LemonMarkdown className="text-xs text-secondary" disableImages>+ {expanded ? content : preview}+ </LemonMarkdown>+ </div>+ {truncated && (+ <LemonButton+ size="xsmall"+ type="tertiary"+ className="self-start"+ aria-expanded={expanded}+ aria-controls={bodyId}+ onClick={toggle}+ >+ {expanded ? 'Show less' : 'Show more'}+ </LemonButton>+ )}+ </div>+ )+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.test.tsxnew file mode 100644index 000000000000..18a48f3f9164--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.test.tsx@@ -0,0 +1,47 @@+import { cleanup, fireEvent, render } from '@testing-library/react'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { ScoutNotesPanel } from './ScoutNotesPanel'++const SKILL_NAME = 'signals-scout-daily-digest'+const OPENING = 'The dashboard was re-anchored last Thursday, so treat anything before it as a different metric.'+const TAIL = 'Retire this note once the first clean week of baselines is in.'+const LONG_NOTE = `${OPENING} ${'Baselines rebuild slowly. '.repeat(20)}${TAIL}`++describe('ScoutNotesPanel', () => {+ beforeEach(() => {+ useMocks({+ get: {+ '/api/projects/:team/signals/scout/notes/': [+ {+ id: 'note-1',+ content: LONG_NOTE,+ origin: 'human',+ skill_name: SKILL_NAME,+ created_by_name: 'Someone',+ created_at: '2026-08-21T10:00:00Z',+ expires_at: null,+ },+ ],+ },+ })+ initKeaTests()+ })++ afterEach(cleanup)++ it('shows the opening of a long note until it is expanded', async () => {+ const { findByText, getByText, queryByText } = render(<ScoutNotesPanel skillName={SKILL_NAME} />)++ // Matching on the tail rather than the whole note: the preview cuts at a word boundary, so+ // the exact cut point is not the thing worth pinning.+ expect(await findByText(new RegExp(OPENING))).toBeTruthy()+ expect(queryByText(new RegExp(TAIL))).toBeNull()++ fireEvent.click(getByText('Show more'))++ expect(getByText(new RegExp(TAIL))).toBeTruthy()+ })+})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsxindex 3de401795cdd..6245cf22df44 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.tsx@@ -5,7 +5,6 @@ import { IconPencil, IconTrash } from '@posthog/icons'import { LemonButton, LemonDialog, LemonTag, LemonTextArea, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'-import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { pluralize } from 'lib/utils/strings'@@ -19,6 +18,7 @@ import {scoutNoteOriginLabel,scoutNotesLogic,} from '../../../logics/scoutNotesLogic'+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@@ -222,9 +222,7 @@ function ScoutNoteRow({ note, onDelete }: { note: ScoutNoteApi; onDelete: () =></Tooltip>)}</div>- <LemonMarkdown className="text-xs text-secondary" disableImages>- {note.content}- </LemonMarkdown>+ <ScoutNoteContent content={note.content} /></div>{/* Only a note someone left here is retired here. A derived one is a record of whathappened in the inbox, and deleting it would rewrite that. */}diff --git a/products/signals/frontend/inbox/components/config/scouts/scoutNotePreview.test.ts b/products/signals/frontend/inbox/components/config/scouts/scoutNotePreview.test.tsnew file mode 100644index 000000000000..cdb22e143080--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/scoutNotePreview.test.ts@@ -0,0 +1,93 @@+import { NOTE_PREVIEW_CHARS, scoutNotePreview } from './scoutNotePreview'++describe('scoutNotePreview', () => {+ it('leaves a note that already fits', () => {+ expect(scoutNotePreview('Watch conversion closely this week.')).toBe('Watch conversion closely this week.')+ })++ it.each([+ ['spaces', ' '],+ ['newlines', '\n'],+ ])('backs up to the last whitespace when words are separated by %s', (_name, separator) => {+ const preview = scoutNotePreview(`${`alpha${separator}`.repeat(60)}omega`)++ expect(preview.endsWith('alpha…')).toBe(true)+ })++ it.each([+ // Each of these puts the limit inside a character: the first halfway through a surrogate+ // pair, the second inside a family emoji, which is seven code points joined together.+ ['a surrogate pair', 'a', '🙂'],+ ['a joined emoji', 'x'.repeat(NOTE_PREVIEW_CHARS - 1), '👨👩👧👦'],+ ])('keeps %s whole when there is no whitespace to back up to', (_name, lead, character) => {+ const filler = character.repeat(NOTE_PREVIEW_CHARS)++ expect(scoutNotePreview(`${lead}${filler}`)).toBe(+ `${lead}${character.repeat(NOTE_PREVIEW_CHARS - Array.from(lead).length)}…`+ )+ })++ it.each([+ ['a URL', `https://example.com/${'segment/'.repeat(50)}`],+ ['an email address', `someone@example.${'a'.repeat(300)}`],+ ])('drops %s rather than cutting one', (_name, link) => {+ // Without a space in front of it there is nothing to back up to, so the link is the only+ // thing the preview can drop. A cut one would still render as a link, to the wrong place.+ expect(scoutNotePreview(`${'あ'.repeat(200)}${link}`)).toBe(`${'あ'.repeat(200)}…`)+ expect(scoutNotePreview(link)).toBe('…')+ })++ it.each([+ // CommonMark takes the destination on the label's line or the line below it.+ ['on the label line', ' '],+ ['on the line below the label', '\n '],+ ])('drops a reference definition the cut ran through, destination %s', (_name, gap) => {+ // The label resolves against the definition wherever it sits, so a severed destination is+ // still a live link — to a path the note never pointed at.+ const preview = scoutNotePreview(`[docs][d]\n\n[d]:${gap}/runbooks/${'segment-'.repeat(60)}`)++ expect(preview).toBe('[docs][d]…')+ })++ it.each([+ // Shortening a preview is only worth it to avoid a broken character or a wrong link. None+ // of these is either, so each one fills the sidebar rather than stopping early.+ ['the last whitespace sits far behind the cut', `Note: ${'あ'.repeat(400)}`, `Note: ${'あ'.repeat(274)}…`],+ [+ 'an @ runs past the cut with no domain after it',+ `${'あ'.repeat(200)}build@${'a'.repeat(200)}`,+ `${'あ'.repeat(200)}build@${'a'.repeat(74)}…`,+ ],+ [+ 'a scheme GFM never autolinks runs past the cut',+ `${'あ'.repeat(200)}s3://bucket/${'x'.repeat(200)}`,+ `${'あ'.repeat(200)}s3://bucket/${'x'.repeat(68)}…`,+ ],+ [+ 'the last word is non-BMP but the space is within reach',+ `${'a'.repeat(249)} ${'𐐀'.repeat(100)}`,+ `${'a'.repeat(249)}…`,+ ],+ ])('fills the preview when %s', (_name, content, expected) => {+ expect(scoutNotePreview(content)).toBe(expected)+ })++ it('shows the note in full in a browser with no grapheme segmenter', async () => {+ // The panel is one import away from every scout page, so a segmenter built at module scope+ // takes the page down on a browser that has none. Without one, show the note in full rather+ // than risk a code-point cut splitting a character.+ const intl = Intl as { Segmenter?: typeof Intl.Segmenter }+ const segmenter = intl.Segmenter+ try {+ delete intl.Segmenter+ jest.resetModules()+ const { scoutNotePreview: withoutSegmenter } = await import('./scoutNotePreview')+ const note = '👨👩👧👦'.repeat(NOTE_PREVIEW_CHARS + 1)++ expect(withoutSegmenter(note)).toBe(note)+ } finally {+ intl.Segmenter = segmenter+ jest.resetModules()+ }+ })+})diff --git a/products/signals/frontend/inbox/components/config/scouts/scoutNotePreview.ts b/products/signals/frontend/inbox/components/config/scouts/scoutNotePreview.tsnew file mode 100644index 000000000000..39b35e4e3006--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/scoutNotePreview.ts@@ -0,0 +1,91 @@+/** Notes run to hundreds of words, and the panel sits in a narrow sidebar next to the reports. */+export const NOTE_PREVIEW_CHARS = 280++/**+ * How far the cut travels back to land on a word boundary, counted in characters. Longer than a+ * word, short enough that a note opening with a label and continuing in a script without spaces+ * still gets a preview.+ */+const MAX_WORD_BACKTRACK = 40++/**+ * What GFM autolinks on sight: an `http(s)` URL, a bare `www.` host, an email address on a dotted+ * domain. A cut inside one still links, sending a reader somewhere the note never pointed, so the+ * preview drops it whole. Other schemes (`s3://`, `file://`) and a plain `a@b` without a dotted+ * domain are not autolinked, so they stay.+ */+const SEVERED_LINK = /(?:https?:\/\/|\bwww\.)\S*$|[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/i++/**+ * A reference definition the cut ran through. A `[docs][d]` earlier in the note still resolves+ * against it, so the label renders as a live link to a shortened destination. The destination may+ * sit on the line below the label, which CommonMark allows. Only a cut that keeps the grapheme head+ * can sever a definition: backing up to whitespace stops before the destination, which leaves+ * `[d]:` and no definition at all.+ */+const SEVERED_DEFINITION = /(?:^|\n)[ \t]{0,3}\[[^\]\n]+\]:[ \t]*(?:\n[ \t]*)?[^\n]*$/++let segmenter: Intl.Segmenter | null | undefined++/**+ * The grapheme segmenter, built on first use and only if the browser has it. At module scope a+ * browser without `Intl.Segmenter` would fail the import and take the panel down, rather than just+ * showing long notes in full.+ */+function graphemeSegmenter(): Intl.Segmenter | null {+ if (segmenter === undefined) {+ segmenter = typeof Intl.Segmenter === 'function' ? new Intl.Segmenter('und', { granularity: 'grapheme' }) : null+ }+ return segmenter+}++/**+ * The first `limit` characters of a note as a person counts them — a flag, an accent or a family+ * emoji is one. Returns `null` when the note already fits, or when the browser has no segmenter to+ * count graphemes with: rather than split a character, such a browser shows the note in full.+ */+function head(content: string, limit: number): string[] | null {+ // A character is one code unit or more, so this rules out most notes without segmenting them.+ if (content.length <= limit) {+ return null+ }+ const segments = graphemeSegmenter()+ if (!segments) {+ return null+ }+ const characters: string[] = []+ for (const { segment } of segments.segment(content)) {+ characters.push(segment)+ // One character past the limit is enough to know the note is longer than the preview, and+ // stops the walk short of a body that can run to thousands of characters.+ if (characters.length > limit) {+ return characters.slice(0, limit)+ }+ }+ return null+}++/**+ * The opening of a note, short enough to sit in the sidebar. Cutting mid-word reads like a typo, so+ * back up to the last whitespace. Prose with no whitespace within reach — CJK, say — cuts at the+ * limit instead, on a character boundary.+ */+export function scoutNotePreview(content: string): string {+ const opening = head(content, NOTE_PREVIEW_CHARS)+ if (opening === null) {+ return content+ }+ let boundary = -1+ for (let i = opening.length - 1; i >= 0; i--) {+ if (opening[i].trim() === '') {+ boundary = i+ break+ }+ }+ const kept = boundary > 0 ? opening.slice(0, boundary).join('').trimEnd() : ''+ const backtrack = opening.length - 1 - boundary+ if (kept && backtrack <= MAX_WORD_BACKTRACK) {+ return `${kept}…`+ }+ return `${opening.join('').replace(SEVERED_LINK, '').replace(SEVERED_DEFINITION, '').trimEnd()}…`+}