: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(replay): say and choose which summarizer the button runs (#87366)
Kim Svatos Dugandef397d722f3
diff --git a/products/replay_vision/frontend/components/ObservationsDock.tsx b/products/replay_vision/frontend/components/ObservationsDock.tsxindex 5e419c3240f7..bf19af478911 100644--- a/products/replay_vision/frontend/components/ObservationsDock.tsx+++ b/products/replay_vision/frontend/components/ObservationsDock.tsx@@ -1,21 +1,25 @@import { useActions, useValues } from 'kea'import { useRef, useState } from 'react'-import { IconChevronDown, IconNotebook } from '@posthog/icons'-import { LemonButton, Spinner } from '@posthog/lemon-ui'+import { IconChevronDown, IconInfo, IconLogomark, IconNotebook } from '@posthog/icons'+import { LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'import { Resizer } from 'lib/components/Resizer/Resizer'import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'+import { LemonMenuItem, LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'+import { AccessControlLevel } from '~/types'++import type { ReplayScannerApi } from '../generated/api.schemas'import { observationsDockLogic } from '../logics/observationsDockLogic'import { visionQuotaLogic } from '../logics/visionQuotaLogic'import { getReplayVisionEditDisabledReason } from '../utils/accessControl'import { isSummaryObservation } from '../utils/observation'import { quotaUx } from '../utils/quotaProjection'-import { VisionDocsLink } from './DocsLink'+import { VisionDocsLink, visionDocsUrl } from './DocsLink'import { ObservationDockCard } from './ObservationCard'const COLLAPSED_HEIGHT = 44@@ -32,18 +36,61 @@ export function ObservationsDock(): JSX.Element | null {return <ObservationsDockContent sessionId={sessionRecordingId} />}-/** One-click summary: an inline summarizer scan, so it needs no saved scanner. */+/** Runs whichever summarizer `resolveSummarizer` settles on, and lets the user pick another. */function SummarizeButton({ sessionId }: { sessionId: string }): JSX.Element {const logic = observationsDockLogic({ sessionId })- const { summarizing } = useValues(logic)- const { summarize } = useActions(logic)+ const { summarizing, defaultSummarizer, summarizerScanners } = useValues(logic)+ const { summarize, summarizeWith } = useActions(logic)const { quota } = useValues(visionQuotaLogic)const { dataProcessingAccepted } = useValues(aiConsentLogic)const [consentRequested, setConsentRequested] = useState(false)const { disabledReason: quotaDisabledReason, tooltip: quotaTooltip } = quotaUx(quota)- // An inline scan mints a scanner, so the endpoint holds it to scanner-editor access. Without this the- // button looks available to a viewer and answers 403.- const accessDisabledReason = getReplayVisionEditDisabledReason()+ // `loading` only disables the button itself. The caret and the menu rows are their own buttons, so+ // without this a second summarizer is one click away mid-run, and it spends the quota again.+ const inFlightDisabledReason = summarizing ? 'A summary is already running' : null+ // Both paths are scanner writes: an inline scan mints a scanner, and `observe` is a write action on+ // the scanner it runs. Each also exposes recording contents, so both need recording read as well.+ const builtInDisabledReason = inFlightDisabledReason ?? getReplayVisionEditDisabledReason() ?? quotaDisabledReason+ // Object-level, so a scanner this user cannot edit is disabled rather than answering with a 403.+ const scannerDisabledReason = (scanner: ReplayScannerApi): string | null | undefined =>+ inFlightDisabledReason ??+ getReplayVisionEditDisabledReason(scanner.user_access_level as AccessControlLevel | null) ??+ quotaDisabledReason+ // Nobody could tell which summarizer the button used, so it says so.+ const label = defaultSummarizer ? `Summarize with ${defaultSummarizer.name}` : 'Summarize this recording'+ const summarizerTooltip = defaultSummarizer+ ? `Runs your "${defaultSummarizer.name}" scanner on this recording.`+ : 'Writes a summary using a built-in prompt.'++ const menuItems: LemonMenuItem[] = [+ ...summarizerScanners.map((scanner) => ({+ key: scanner.id,+ label: scanner.name,+ active: scanner.id === defaultSummarizer?.id,+ disabledReason: scannerDisabledReason(scanner),+ onClick: () => summarizeWith(scanner.id),+ 'data-attr': 'vision-summarize-pick-scanner',+ })),+ {+ key: 'built-in',+ // Every other row is a scanner the team owns and can open. This one is PostHog's, so it+ // carries the logomark and says so, rather than reading as a scanner they cannot find.+ label: (+ <span className="flex items-center justify-between gap-2 w-full">+ <span className="truncate">Quick summary</span>+ <span className="flex items-center gap-1.5 text-xs shrink-0">+ <IconLogomark className="text-base text-primary" />+ <span className="text-muted">Built in</span>+ </span>+ </span>+ ),+ tooltip: 'Uses a built-in prompt. Nothing is saved to your scanners, so there is nothing to open or edit.',+ active: !defaultSummarizer,+ disabledReason: builtInDisabledReason,+ onClick: () => summarizeWith(null),+ 'data-attr': 'vision-summarize-pick-built-in',+ },+ ]const button = (<LemonButton@@ -53,11 +100,25 @@ function SummarizeButton({ sessionId }: { sessionId: string }): JSX.Element {loading={summarizing}// The endpoint refuses without org AI approval, so ask for it here rather than toasting a 400.onClick={() => (dataProcessingAccepted ? summarize() : setConsentRequested(true))}- disabledReason={accessDisabledReason ?? quotaDisabledReason}- tooltip={quotaTooltip ?? 'Write a summary of what happened in this recording'}+ disabledReason={defaultSummarizer ? scannerDisabledReason(defaultSummarizer) : builtInDisabledReason}+ tooltip={quotaTooltip ?? summarizerTooltip}data-attr="vision-summarize-recording"+ data-ph-capture-attribute-summarizer={defaultSummarizer ? 'configured' : 'built-in'}+ // The dropdown is the only way to reach a second summarizer, so it appears once one exists.+ sideAction={+ summarizerScanners.length > 0 && dataProcessingAccepted+ ? {+ icon: <IconChevronDown />,+ dropdown: { placement: 'bottom-end', overlay: <LemonMenuOverlay items={menuItems} /> },+ divider: false,+ disabledReason: inFlightDisabledReason,+ 'aria-label': 'Choose a summarizer',+ 'data-attr': 'vision-summarize-choose',+ }+ : null+ }>- {dataProcessingAccepted ? 'Summarize this recording' : 'Allow AI analysis and summarize'}+ <span className="truncate">{dataProcessingAccepted ? label : 'Allow AI analysis and summarize'}</span></LemonButton>)@@ -83,6 +144,34 @@ function SummarizeButton({ sessionId }: { sessionId: string }): JSX.Element {)}+/**+ * The dock sits on every standard replay player, so it reaches people who have never heard of Replay+ * vision and meet the summarize button with no idea what it is or what it will spend.+ */+function SummarizeExplainer(): JSX.Element {+ return (+ <Tooltip+ placement="bottom"+ // Base UI opens tooltips on hover only, which leaves this unreachable on a touch device.+ openOnClick+ title={+ <>+ <p className="mb-1">Replay vision uses AI to watch recordings for you.</p>+ <p className="mb-0">+ Summarizing writes up what the user did in this session, so you can read it instead of watching+ it.+ </p>+ </>+ }+ docLink={`${visionDocsUrl()}?utm_medium=in-product&utm_campaign=summarize-explainer`}+ >+ <span className="inline-flex items-center text-muted" data-attr="vision-summarize-info">+ <IconInfo />+ </span>+ </Tooltip>+ )+}+function ObservationsDockContent({ sessionId }: { sessionId: string }): JSX.Element {const logic = observationsDockLogic({ sessionId })const { observations, observationsLoading, dockOpen, retryingObservationIds } = useValues(logic)@@ -122,6 +211,7 @@ function ObservationsDockContent({ sessionId }: { sessionId: string }): JSX.Elem{dockOpen && <Resizer {...resizerProps} />}<div className="flex items-center gap-2 lg:gap-3 h-11 px-3 shrink-0"><SummarizeButton sessionId={sessionId} />+ <SummarizeExplainer />{hasContent && (<LemonButtonclassName="ml-auto"@@ -131,6 +221,9 @@ function ObservationsDockContent({ sessionId }: { sessionId: string }): JSX.Elemtooltip={dockOpen ? 'Collapse' : 'Expand'}aria-label={dockOpen ? 'Collapse summary' : 'Expand summary'}data-attr="vision-dock-toggle"+ // This click also sets the auto-expand preference, so which way it went is the+ // signal for whether people keep summaries open by default.+ data-ph-capture-attribute-dock-action={dockOpen ? 'collapse' : 'expand'}/>)}</div>diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.test.ts b/products/replay_vision/frontend/logics/observationsDockLogic.test.tsindex 9bb32fbf1535..104be45b4faa 100644--- a/products/replay_vision/frontend/logics/observationsDockLogic.test.ts+++ b/products/replay_vision/frontend/logics/observationsDockLogic.test.ts@@ -5,7 +5,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import type { ReplayObservationApi } from '../generated/api.schemas'+import type { ReplayObservationApi, ReplayScannerApi } from '../generated/api.schemas'import { observationsDockLogic } from './observationsDockLogic'import { visionDockPreferenceLogic } from './visionDockPreferenceLogic'import { visionScannersListLogic } from './visionScannersListLogic'@@ -14,6 +14,10 @@ jest.mock('lib/lemon-ui/LemonToast', () => ({lemonToast: { success: jest.fn(), info: jest.fn(), warning: jest.fn(), error: jest.fn() },}))+function scanner(id: string, scannerType: string): ReplayScannerApi {+ return { id, name: `Scanner ${id}`, scanner_type: scannerType } as ReplayScannerApi+}+function summaryObservation(): ReplayObservationApi {return {id: 'obs-summary',@@ -34,6 +38,7 @@ describe('observationsDockLogic', () => {let releaseScanners: () => voidlet inlineScanOutcome: stringlet observationResults: ReplayObservationApi[]+ let scannerResults: ReplayScannerApi[]beforeEach(() => {jest.clearAllMocks()@@ -41,13 +46,14 @@ describe('observationsDockLogic', () => {inlineScanCalls = 0inlineScanOutcome = 'started'observationResults = []+ scannerResults = []useMocks({get: {'/api/projects/:team/vision/scanners/': async () => {await new Promise<void>((resolve) => {releaseScanners = resolve})- return [200, { results: [] }]+ return [200, { results: scannerResults }]},'/api/projects/:team/vision/observations/': () => [200, { results: observationResults }],},@@ -81,6 +87,7 @@ describe('observationsDockLogic', () => {preferences = visionDockPreferenceLogic()preferences.mount()preferences.actions.setSummaryDockAutoExpand(true)+ preferences.actions.setPreferredSummarizerId(null)logic = observationsDockLogic({ sessionId: 'sess-1' })logic.mount()})@@ -191,4 +198,42 @@ describe('observationsDockLogic', () => {await expectLogic(nextRecording).toMatchValues({ dockOpen: false })nextRecording.unmount()})++ const loadScanners = async (scanners: ReplayScannerApi[]): Promise<void> => {+ scannerResults = scanners+ // The mock holds the scanner fetch open, and its release hook only exists once the handler runs.+ await new Promise((resolve) => setTimeout(resolve, 0))+ releaseScanners()+ await expectLogic(visionScannersListLogic).toDispatchActions(['loadScannersSuccess'])+ }++ // Which scanner it resolves to is settled by `resolveSummarizer` and tested there. What only this+ // level shows is that the two answers reach two different endpoints: a scanner runs through+ // `observe`, and the built-in prompt through `inline_scan`.+ test.each([+ { shape: 'a summarizer of their own', scanners: [scanner('s1', 'summarizer')], runsOwnScanner: true },+ { shape: 'no summarizer', scanners: [scanner('m1', 'monitor')], runsOwnScanner: false },+ ])('summarize with $shape runs own scanner: $runsOwnScanner', async (routingCase) => {+ await loadScanners(routingCase.scanners)++ logic.actions.summarize()+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(observeCalls).toBe(routingCase.runsOwnScanner ? 1 : 0)+ expect(inlineScanCalls).toBe(routingCase.runsOwnScanner ? 0 : 1)+ })++ it('keeps the summarizer picked from the dropdown on the next recording', async () => {+ // Picking from the dropdown has to outlive the recording it was picked on, or a team with+ // several summarizers re-picks on every recording and the button never settles on their choice.+ await loadScanners([scanner('s1', 'summarizer'), scanner('s2', 'summarizer')])+ await expectLogic(logic).toMatchValues({ defaultSummarizer: null })++ logic.actions.summarizeWith('s2')++ const nextRecording = observationsDockLogic({ sessionId: 'sess-2' })+ nextRecording.mount()+ await expectLogic(nextRecording).toMatchValues({ defaultSummarizer: expect.objectContaining({ id: 's2' }) })+ nextRecording.unmount()+ })})diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.ts b/products/replay_vision/frontend/logics/observationsDockLogic.tsindex d7a1f6bd1f98..6881735b26f3 100644--- a/products/replay_vision/frontend/logics/observationsDockLogic.ts+++ b/products/replay_vision/frontend/logics/observationsDockLogic.ts@@ -7,10 +7,16 @@ import { teamLogic } from 'scenes/teamLogic'import { visionObservationsList, visionScannersInlineScanCreate, visionScannersObserveCreate } from '../generated/api'import type { ReplayScannerApi, ReplayObservationApi } from '../generated/api.schemas'+import { isSummarizerScanner } from '../replay_scanners/types'import { ObservationSeekbarMark, isSummaryObservation, observationSeekbarMarks } from '../utils/observation'import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from './observationPolling'import { requestObservationRetry } from './observationRetry'-import { SUMMARIZE_RECORDING_CONFIG, summarizeOutcomeMessage } from './summarizeRecording'+import {+ BUILT_IN_SUMMARIZER,+ SUMMARIZE_RECORDING_CONFIG,+ resolveSummarizer,+ summarizeOutcomeMessage,+} from './summarizeRecording'import { visionDockPreferenceLogic } from './visionDockPreferenceLogic'import { refreshVisionQuota } from './visionQuotaLogic'import { visionScannersListLogic } from './visionScannersListLogic'@@ -21,9 +27,11 @@ export interface ObservationsDockLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface observationsDockLogicValues {+ preferredSummarizerId: string | null // visionDockPreferenceLogicsummaryDockAutoExpand: boolean // visionDockPreferenceLogicscanners: ReplayScannerApi[] // visionScannersListLogicscannersLoading: boolean // visionScannersListLogic+ defaultSummarizer: ReplayScannerApi | nulldockOpen: booleanfilteredScanners: ReplayScannerApi[]hasObservationsInFlight: boolean@@ -35,11 +43,15 @@ export interface observationsDockLogicValues {scannerPickerOpen: booleanscannerSearch: stringseekbarMarks: ObservationSeekbarMark[]+ summarizerScanners: ReplayScannerApi[]summarizing: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface observationsDockLogicActions {+ setPreferredSummarizerId: (scannerId: string | null) => {+ scannerId: string | null+ } // visionDockPreferenceLogicsetSummaryDockAutoExpand: (autoExpand: boolean) => {autoExpand: boolean} // visionDockPreferenceLogic@@ -88,6 +100,9 @@ export interface observationsDockLogicActions {summarizeSuccess: () => {value: true}+ summarizeWith: (scannerId: string | null) => {+ scannerId: string | null+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -96,6 +111,11 @@ export interface observationsDockLogicMeta {__keaTypeGenInternalSelectorTypes: {hasObservationsInFlight: (observations: ReplayObservationApi[]) => booleanseekbarMarks: (observations: ReplayObservationApi[]) => ObservationSeekbarMark[]+ summarizerScanners: (scanners: ReplayScannerApi[]) => ReplayScannerApi[]+ defaultSummarizer: (+ scanners: ReplayScannerApi[],+ preferredSummarizerId: string | null+ ) => ReplayScannerApi | nullfilteredScanners: (scanners: ReplayScannerApi[], scannerSearch: string) => ReplayScannerApi[]}}@@ -118,9 +138,9 @@ export const observationsDockLogic = kea<observationsDockLogicType>([visionScannersListLogic,['scanners', 'scannersLoading'],visionDockPreferenceLogic,- ['summaryDockAutoExpand'],+ ['summaryDockAutoExpand', 'preferredSummarizerId'],],- actions: [visionDockPreferenceLogic, ['setSummaryDockAutoExpand']],+ actions: [visionDockPreferenceLogic, ['setSummaryDockAutoExpand', 'setPreferredSummarizerId']],})),actions({@@ -137,6 +157,7 @@ export const observationsDockLogic = kea<observationsDockLogicType>([setScannerPickerOpen: (open: boolean) => ({ open }),setScannerSearch: (search: string) => ({ search }),summarize: true,+ summarizeWith: (scannerId: string | null) => ({ scannerId }),summarizeSuccess: true,summarizeFailure: true,}),@@ -168,8 +189,13 @@ export const observationsDockLogic = kea<observationsDockLogicType>([false,{summarize: () => true,+ summarizeWith: () => true,summarizeSuccess: () => false,summarizeFailure: () => false,+ // `summarize` hands off to `observe` when the team has its own summarizer, so the+ // button's spinner has to settle on that run's outcome too.+ observeSuccess: () => false,+ observeFailure: () => false,},],dockOpen: [@@ -226,6 +252,16 @@ export const observationsDockLogic = kea<observationsDockLogicType>([(s) => [s.observations],(observations: ReplayObservationApi[]): ObservationSeekbarMark[] => observationSeekbarMarks(observations),],+ summarizerScanners: [+ (s) => [s.scanners],+ (scanners: ReplayScannerApi[]): ReplayScannerApi[] => scanners.filter(isSummarizerScanner),+ ],+ // What the button runs, and names. Null means the built-in prompt.+ defaultSummarizer: [+ (s) => [s.scanners, s.preferredSummarizerId],+ (scanners: ReplayScannerApi[], preferredSummarizerId: string | null): ReplayScannerApi | null =>+ resolveSummarizer(scanners, preferredSummarizerId),+ ],filteredScanners: [(s) => [s.scanners, s.scannerSearch],(scanners: ReplayScannerApi[], scannerSearch: string): ReplayScannerApi[] => {@@ -265,6 +301,86 @@ export const observationsDockLogic = kea<observationsDockLogicType>([const detail = error instanceof ApiError && error.detail ? `: ${error.detail}` : ''lemonToast.error(`${message}${detail}`)}+ // Run a summary, through one of the team's own scanners or the built-in prompt. A named scanner+ // is just `observe`, which already owns its double-click guard and its already-run check.+ const runSummary = async (scannerId: string | null): Promise<void> => {+ if (scannerId) {+ actions.observe(scannerId)+ return+ }+ // A cache flag for the same reason `observe` uses one: the reducer has already flipped+ // `summarizing` by the time this runs.+ if (cache.summarizeInFlight) {+ return+ }+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ actions.summarizeFailure()+ return+ }+ cache.summarizeInFlight = true+ try {+ const response = await visionScannersInlineScanCreate(String(teamId), {+ ...SUMMARIZE_RECORDING_CONFIG,+ session_ids: [props.sessionId],+ })+ // One session in, so one result out. The inline scanner is shared per project, so a+ // recording somebody already summarized comes back settled instead of started.+ const outcome = response.results?.[0]?.scan_outcome+ if (outcome === 'already_scanned') {+ // A row settled server-side, but the inline scanner is shared and RBAC-scoped, so+ // the row may not be readable here, and the reload can also fail. Confirm the row+ // is in hand before naming it, and leave a way to re-read when it stays hidden.+ actions.summarizeFailure()+ actions.setDockOpen(true)+ const tryAgain = { label: 'Try again', action: () => actions.loadObservations() }+ try {+ const reloaded = await visionObservationsList(String(teamId), {+ session_id: props.sessionId,+ })+ const results = reloaded.results ?? []+ actions.loadObservationsSuccess(results)+ if (response.scan_id && results.some((o) => o.scanner_id === response.scan_id)) {+ // The row is readable below. A failed or ineligible one still shows its retry+ // control there, so the user has a way to run the summary again.+ lemonToast.info('This recording already has a result below.')+ } else {+ lemonToast.warning(+ 'This recording was already summarized, but the result is not available here.',+ { button: tryAgain }+ )+ }+ } catch {+ metricCount('replay_vision_frontend_observations_load_failures')+ actions.loadObservationsFailure()+ lemonToast.warning("Couldn't load this recording's summary.", { button: tryAgain })+ }+ return+ }+ const { level, message } = summarizeOutcomeMessage(outcome)+ lemonToast[level](message)+ if (outcome === 'started' || outcome === 'already_running') {+ // A scan is in flight either way — ours, or one this project already had running+ // against the shared inline scanner — so the poll window has a row to wait for.+ actions.summarizeSuccess()+ actions.setDockOpen(true)+ afterScanStarted()+ } else {+ // Nothing started and nothing to read, so the poll window would watch for a row+ // that never arrives.+ actions.summarizeFailure()+ }+ } catch (error) {+ reportTriggerFailure(+ error,+ 'replay_vision_frontend_summarize_failures',+ 'Failed to summarize recording'+ )+ actions.summarizeFailure()+ } finally {+ cache.summarizeInFlight = false+ }+ }return {loadObservations: async (_, breakpoint) => {// Poll, observe, retry, and the SSE hook all call this; without it a slow earlier response@@ -334,79 +450,13 @@ export const observationsDockLogic = kea<observationsDockLogicType>([}},- summarize: async () => {- // A cache flag for the same reason `observe` uses one: the reducer has already flipped- // `summarizing` by the time this runs.- if (cache.summarizeInFlight) {- return- }- const teamId = teamLogic.values.currentTeamId- if (!teamId) {- actions.summarizeFailure()- return- }- cache.summarizeInFlight = true- try {- const response = await visionScannersInlineScanCreate(String(teamId), {- ...SUMMARIZE_RECORDING_CONFIG,- session_ids: [props.sessionId],- })- // One session in, so one result out. The inline scanner is shared per project, so a- // recording somebody already summarized comes back settled instead of started.- const outcome = response.results?.[0]?.scan_outcome- if (outcome === 'already_scanned') {- // A row settled server-side, but the inline scanner is shared and RBAC-scoped, so- // the row may not be readable here, and the reload can also fail. Confirm the row- // is in hand before naming it, and leave a way to re-read when it stays hidden.- actions.summarizeFailure()- actions.setDockOpen(true)- const tryAgain = { label: 'Try again', action: () => actions.loadObservations() }- try {- const reloaded = await visionObservationsList(String(teamId), {- session_id: props.sessionId,- })- const results = reloaded.results ?? []- actions.loadObservationsSuccess(results)- if (response.scan_id && results.some((o) => o.scanner_id === response.scan_id)) {- // The row is readable below. A failed or ineligible one still shows its retry- // control there, so the user has a way to run the summary again.- lemonToast.info('This recording already has a result below.')- } else {- lemonToast.warning(- 'This recording was already summarized, but the result is not available here.',- { button: tryAgain }- )- }- } catch {- metricCount('replay_vision_frontend_observations_load_failures')- actions.loadObservationsFailure()- lemonToast.warning("Couldn't load this recording's summary.", { button: tryAgain })- }- return- }- const { level, message } = summarizeOutcomeMessage(outcome)- lemonToast[level](message)- if (outcome === 'started' || outcome === 'already_running') {- // A scan is in flight either way — ours, or one this project already had running- // against the shared inline scanner — so the poll window has a row to wait for.- actions.summarizeSuccess()- actions.setDockOpen(true)- afterScanStarted()- } else {- // Nothing started and nothing to read, so the poll window would watch for a row- // that never arrives.- actions.summarizeFailure()- }- } catch (error) {- reportTriggerFailure(- error,- 'replay_vision_frontend_summarize_failures',- 'Failed to summarize recording'- )- actions.summarizeFailure()- } finally {- cache.summarizeInFlight = false- }+ // Runs whatever the button currently resolves to, without disturbing the stored preference.+ summarize: () => runSummary(values.defaultSummarizer?.id ?? null),++ // An explicit pick from the dropdown, which also becomes the preference for next time.+ summarizeWith: ({ scannerId }) => {+ actions.setPreferredSummarizerId(scannerId ?? BUILT_IN_SUMMARIZER)+ return runSummary(scannerId)},retryObservation: async ({ observationId }) => {diff --git a/products/replay_vision/frontend/logics/summarizeRecording.test.ts b/products/replay_vision/frontend/logics/summarizeRecording.test.tsindex 76911dd594ce..a69e8032abf7 100644--- a/products/replay_vision/frontend/logics/summarizeRecording.test.ts+++ b/products/replay_vision/frontend/logics/summarizeRecording.test.ts@@ -1,5 +1,13 @@-import type { ScanOutcomeEnumApi } from '../generated/api.schemas'-import { type SummarizeOutcomeMessage, summarizeOutcomeMessage } from './summarizeRecording'+import type { ReplayScannerApi, ScanOutcomeEnumApi } from '../generated/api.schemas'+import {+ BUILT_IN_SUMMARIZER,+ type SummarizeOutcomeMessage,+ resolveSummarizer,+ summarizeOutcomeMessage,+} from './summarizeRecording'++const summarizer = (id: string): ReplayScannerApi => ({ id, name: id, scanner_type: 'summarizer' }) as ReplayScannerApi+const monitor = (id: string): ReplayScannerApi => ({ id, name: id, scanner_type: 'monitor' }) as ReplayScannerApidescribe('summarizeRecording', () => {// The inline scan answers 202 even when it started nothing, so an outcome that falls through to a@@ -14,4 +22,17 @@ describe('summarizeRecording', () => {])('reports %s as %s', (outcome, level) => {expect(summarizeOutcomeMessage(outcome).level).toBe(level)})++ // Null means the built-in prompt. The two ways of arriving there differ: no usable preference and+ // nothing unambiguous to pick, versus the user asking for it, which has to survive owning a scanner.+ it.each<[string, ReplayScannerApi[], string | null, string | null]>([+ ['a lone summarizer needs no preference', [summarizer('s1')], null, 's1'],+ ['other scanner types do not make it ambiguous', [summarizer('s1'), monitor('m1')], null, 's1'],+ ['several summarizers are ambiguous', [summarizer('s1'), summarizer('s2')], null, null],+ ['a stored pick wins', [summarizer('s1'), summarizer('s2')], 's2', 's2'],+ ['a deleted pick falls back', [summarizer('s1')], 'gone', 's1'],+ ['choosing the built-in prompt sticks', [summarizer('s1')], BUILT_IN_SUMMARIZER, null],+ ])('%s', (_, scanners, preferredId, expectedId) => {+ expect(resolveSummarizer(scanners, preferredId)?.id ?? null).toBe(expectedId)+ })})diff --git a/products/replay_vision/frontend/logics/summarizeRecording.ts b/products/replay_vision/frontend/logics/summarizeRecording.tsindex 2e017595d1ab..79d2021f8475 100644--- a/products/replay_vision/frontend/logics/summarizeRecording.ts+++ b/products/replay_vision/frontend/logics/summarizeRecording.ts@@ -1,4 +1,14 @@-import type { InlineScanRequestApi, ScanOutcomeEnumApi } from '../generated/api.schemas'+import type { InlineScanRequestApi, ReplayScannerApi, ScanOutcomeEnumApi } from '../generated/api.schemas'+import { isSummarizerScanner } from '../replay_scanners/types'++/**+ * The stored preference for "run the built-in prompt", as opposed to no preference at all.+ *+ * Scanner ids are UUIDs, so this cannot collide with one. The two cases have to stay distinct: a team+ * with a single summarizer gets it by default, but must still be able to choose the built-in prompt+ * and have that stick.+ */+export const BUILT_IN_SUMMARIZER = 'built-in'/*** The config behind "Summarize this recording".@@ -21,6 +31,26 @@ export const SUMMARIZE_RECORDING_CONFIG: Pick<InlineScanRequestApi, 'prompt' | 'scanner_config: { length: 'medium' },}+/**+ * Which summarizer the button runs, or null for the built-in prompt.+ *+ * A stored preference wins while the scanner it names still exists, so a deleted scanner falls back+ * rather than leaving the button pointed at nothing. With no usable preference, a lone summarizer is+ * an unambiguous choice and anything else is not: picking one of several deliberate prompts for the+ * user would silently favor one, so that case runs the built-in prompt and says so.+ */+export function resolveSummarizer(scanners: ReplayScannerApi[], preferredId: string | null): ReplayScannerApi | null {+ if (preferredId === BUILT_IN_SUMMARIZER) {+ return null+ }+ const summarizers = scanners.filter(isSummarizerScanner)+ const preferred = preferredId ? summarizers.find((scanner) => scanner.id === preferredId) : undefined+ if (preferred) {+ return preferred+ }+ return summarizers.length === 1 ? summarizers[0] : null+}+export interface SummarizeOutcomeMessage {level: 'success' | 'info' | 'warning' | 'error'message: stringdiff --git a/products/replay_vision/frontend/logics/visionDockPreferenceLogic.ts b/products/replay_vision/frontend/logics/visionDockPreferenceLogic.tsindex 1f54ab0a2a56..730a259c8d87 100644--- a/products/replay_vision/frontend/logics/visionDockPreferenceLogic.ts+++ b/products/replay_vision/frontend/logics/visionDockPreferenceLogic.ts@@ -2,11 +2,15 @@ import { MakeLogicType, actions, kea, path, reducers } from 'kea'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface visionDockPreferenceLogicValues {+ preferredSummarizerId: string | nullsummaryDockAutoExpand: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface visionDockPreferenceLogicActions {+ setPreferredSummarizerId: (scannerId: string | null) => {+ scannerId: string | null+ }setSummaryDockAutoExpand: (autoExpand: boolean) => {autoExpand: boolean}@@ -18,16 +22,18 @@ export type visionDockPreferenceLogicType = MakeLogicType<>/**- * Whether the summary dock opens on its own for a recording that already has a summary.+ * How the summary dock behaves, across recordings.** Propless and persisted on purpose. `observationsDockLogic` is keyed by session, so a preference- * kept there would reset on every recording the user opens and re-expand a dock they just collapsed.+ * kept there would reset on every recording the user opens: it would re-expand a dock they just+ * collapsed, and forget the summarizer they just picked.*/export const visionDockPreferenceLogic = kea<visionDockPreferenceLogicType>([path(['products', 'replay_vision', 'frontend', 'logics', 'visionDockPreferenceLogic']),actions({setSummaryDockAutoExpand: (autoExpand: boolean) => ({ autoExpand }),+ setPreferredSummarizerId: (scannerId: string | null) => ({ scannerId }),}),reducers({@@ -38,5 +44,14 @@ export const visionDockPreferenceLogic = kea<visionDockPreferenceLogicType>([setSummaryDockAutoExpand: (_: boolean, { autoExpand }: { autoExpand: boolean }) => autoExpand,},],+ // Holds a scanner id, BUILT_IN_SUMMARIZER, or null for "never chose". Resolved against the+ // team's current scanner list by `resolveSummarizer`, so a stale id falls back on its own.+ preferredSummarizerId: [+ null as string | null,+ { persist: true },+ {+ setPreferredSummarizerId: (_: string | null, { scannerId }: { scannerId: string | null }) => scannerId,+ },+ ],}),])diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex 600b943e298b..9d03cb2e94dd 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -302,6 +302,11 @@ export function defaultScannerName(teamName: string | null | undefined, scannerTreturn teamName ? `${teamName} ${type}` : `New ${type}`}+/** The summarize button resolves against these; every other type belongs to the sidebar's scanner picker. */+export function isSummarizerScanner(scanner: ReplayScannerApi): boolean {+ return scanner.scanner_type === 'summarizer'+}+export function scannerTypeLabel(scannerType: ScannerType | null | undefined): string {if (!scannerType) {return '—'