: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
fix(replay-vision): paginate semantic search (#94248)
Hayne Ryu8b281791288f
diff --git a/products/replay_vision/frontend/components/ScannerOutputBadge.tsx b/products/replay_vision/frontend/components/ScannerOutputBadge.tsxnew file mode 100644index 000000000000..1052215fca0e--- /dev/null+++ b/products/replay_vision/frontend/components/ScannerOutputBadge.tsx@@ -0,0 +1,26 @@+import { LemonTag } from '@posthog/lemon-ui'++import { SCANNER_TYPE_TAG_TYPE, SUCCEEDED_OUTPUT_LABEL, ScannerType } from '../replay_scanners/types'+import { scannerTypeIcon } from './ScannerTypeBadge'++/**+ * Badge for what a scanner produced (Verdict, Categories, Score, Summary), named the way the observation+ * detail page names it. Carries the scanner type's icon and color, so a type stays recognizable at a glance.+ * Use ScannerTypeBadge instead wherever the scanner type itself is what's being shown.+ */+export function ScannerOutputBadge({+ scannerType,+ size = 'medium',+}: {+ scannerType: ScannerType+ size?: 'small' | 'medium'+}): JSX.Element {+ return (+ <LemonTag type={SCANNER_TYPE_TAG_TYPE[scannerType]} size={size} className="w-fit">+ <span className="flex items-center gap-1">+ {scannerTypeIcon(scannerType)}+ {SUCCEEDED_OUTPUT_LABEL[scannerType]}+ </span>+ </LemonTag>+ )+}diff --git a/products/replay_vision/frontend/components/ScannerTypeBadge.tsx b/products/replay_vision/frontend/components/ScannerTypeBadge.tsxindex b2b5d125b2d2..a4a20f24e785 100644--- a/products/replay_vision/frontend/components/ScannerTypeBadge.tsx+++ b/products/replay_vision/frontend/components/ScannerTypeBadge.tsx@@ -3,7 +3,7 @@ import { LemonTag } from '@posthog/lemon-ui'import { SCANNER_TYPE_TAG_TYPE, ScannerType, scannerTypeLabel } from '../replay_scanners/types'-function scannerTypeIcon(scannerType: ScannerType): JSX.Element {+export function scannerTypeIcon(scannerType: ScannerType): JSX.Element {switch (scannerType) {case 'monitor':return <IconEye />@@ -17,11 +17,11 @@ function scannerTypeIcon(scannerType: ScannerType): JSX.Element {}/**- * Canonical badge for a scanner type — icon + per-type color + label. Use everywhere a scanner type is shown so+ * Canonical badge for a scanner type: icon, per-type color, label. Use everywhere a scanner type is shown so* the badges stay consistent.- * - `default` — per-type color.- * - `muted` — greyed (e.g. a type with no scanners).- * - `deemphasized` — greyed + struck-through, for "available but not selected" sets (e.g. the read-only config+ * - `default`: per-type color.+ * - `muted`: greyed (e.g. a type with no scanners).+ * - `deemphasized`: greyed and struck-through, for "available but not selected" sets (e.g. the read-only config* showing all types with the active one highlighted).* `suffix` renders extra inline content after the label (e.g. an enabled/total count).*/diff --git a/products/replay_vision/frontend/search/ObservationSearchTab.tsx b/products/replay_vision/frontend/search/ObservationSearchTab.tsxindex bec9e9225a4d..a01e9cfb0b4c 100644--- a/products/replay_vision/frontend/search/ObservationSearchTab.tsx+++ b/products/replay_vision/frontend/search/ObservationSearchTab.tsx@@ -6,18 +6,19 @@ import { IconSearch } from '@posthog/icons'import { LemonButton, LemonInput, LemonTag, Link, Spinner } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'+import { PaginationControl } from 'lib/lemon-ui/PaginationControl'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'import { ObservationResultSummary } from '../components/ObservationCard'-import { ScannerTypeBadge } from '../components/ScannerTypeBadge'-import type { ObservationSearchResultApi } from '../generated/api.schemas'+import { ScannerOutputBadge } from '../components/ScannerOutputBadge'+import type { ObservationSearchResultApi, ReplayObservationApi } from '../generated/api.schemas'import { observationDetailUrl } from '../observations/replayObservationLogic'import { ReplayScannerTab } from '../replay_scanners/replayScannerSceneLogic'import type { ReplayScanner } from '../replay_scanners/types'import { scannerLabel } from '../utils/observation'-import { observationSearchLogic } from './observationSearchLogic'+import { SEARCH_PAGE_SIZE, observationSearchLogic } from './observationSearchLogic'import { snippetSegments } from './snippetSegments'const CROSS_SCANNER_EXAMPLE_QUERIES = ['users who got stuck and gave up', 'rage clicking out of frustration']@@ -91,6 +92,18 @@ function countLabel(count: number, truncated: boolean): string {return `${count === 1 ? '1 match' : `${count} matches`}, best first`}+// Email, then distinct id, then session id: whichever identifies the recorded person first.+function SubjectLabel({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ if (observation.recording_subject_email) {+ return <span className="text-xs text-muted truncate">{observation.recording_subject_email}</span>+ }+ return (+ <span className="font-mono text-xs text-muted truncate">+ {observation.distinct_id ?? observation.session_id}+ </span>+ )+}+function SearchResultCard({result,searchedQuery,@@ -116,12 +129,10 @@ function SearchResultCard({{showScanner && (<><span className="font-semibold text-sm truncate">{scannerLabel(observation)}</span>- {snapshot && (- <ScannerTypeBadge scannerType={snapshot.scanner_type} size="small" variant="muted" />- )}+ {snapshot && <ScannerOutputBadge scannerType={snapshot.scanner_type} size="small" />}</>)}- <span className="font-mono text-xs text-muted truncate">{observation.session_id}</span>+ <SubjectLabel observation={observation} /><span className="ml-auto shrink-0 flex items-center gap-2 text-xs text-muted">{strongMatch && (<LemonTag type="success" size="small">@@ -168,8 +179,13 @@ export function ObservationSearchTab({ scanner }: { scanner: ReplayScanner | nulrecentQueries,suggestedQueries,suggestedQueriesLoading,+ page,+ pageCount,+ pageResults,+ pageStartIndex,+ pageEndIndex,} = useValues(logic)- const { setQuery, search } = useActions(logic)+ const { setQuery, search, setPage } = useActions(logic)const crossScanner = scanner === null// A scanner-scoped search lives in the scanner URL, so a result can point back at the query it came from.const returnParams: Record<string, string> =@@ -258,7 +274,7 @@ export function ObservationSearchTab({ scanner }: { scanner: ReplayScanner | nul<><div className="text-muted text-sm">{countLabel(results.length, truncated)}</div><div className="flex flex-col gap-2">- {results.map((result) => (+ {pageResults.map((result) => (<SearchResultCardkey={result.observation.id}result={result}@@ -272,6 +288,20 @@ export function ObservationSearchTab({ scanner }: { scanner: ReplayScanner | nul/>))}</div>+ <PaginationControl+ pagination={{+ controlled: true,+ pageSize: SEARCH_PAGE_SIZE,+ }}+ currentPage={page}+ setCurrentPage={setPage}+ pageCount={pageCount}+ dataSourcePage={pageResults}+ entryCount={results.length}+ currentStartIndex={pageStartIndex}+ currentEndIndex={pageEndIndex}+ nouns={['match', 'matches']}+ /></>)}</div>diff --git a/products/replay_vision/frontend/search/observationSearchLogic.test.ts b/products/replay_vision/frontend/search/observationSearchLogic.test.tsindex 0e8958834606..10f26254492d 100644--- a/products/replay_vision/frontend/search/observationSearchLogic.test.ts+++ b/products/replay_vision/frontend/search/observationSearchLogic.test.ts@@ -13,7 +13,10 @@ import { observationSearchLogic } from './observationSearchLogic'function searchResults(distances: number[]): ObservationSearchResultApi[] {return distances.map((distance, index) =>- ({ observation: { id: `obs-${index}` }, distance }) as unknown as ObservationSearchResultApi+ ({+ observation: { id: `obs-${index}` },+ distance,+ }) as unknown as ObservationSearchResultApi)}@@ -71,6 +74,25 @@ describe('observationSearchLogic', () => {logic.unmount()})+ it.each([+ ['a full page plus one leaves a single result on page 2', 11, 2, ['obs-10']],+ ['an exact page fill has no second page', 10, 1, []],+ ])('%s', async (_name, resultCount, expectedPageCount, expectedSecondPageIds) => {+ const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ logic.mount()+ logic.actions.setPage(3)+ logic.actions.searchSuccess(searchResults(Array.from({ length: resultCount }, () => 0.1)), 'query', false)++ expect(logic.values.page).toBe(1)+ expect(logic.values.pageCount).toBe(expectedPageCount)+ expect(logic.values.pageResults).toHaveLength(Math.min(resultCount, 10))+ await expectLogic(logic, () => logic.actions.setPage(2)).toFinishAllListeners()+ expect(logic.values.pageResults.map((r) => r.observation.id)).toEqual(expectedSecondPageIds)+ // Paging slices the one ranked response, so a page change must not re-embed and re-rank.+ expect(searchSpy).not.toHaveBeenCalled()+ logic.unmount()+ })+it('a blank query never reaches the API', async () => {const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })logic.mount()@@ -85,11 +107,17 @@ describe('observationSearchLogic', () => {it('a deep-linked q runs the search once, not on every navigation', async () => {const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })logic.mount()- router.actions.push(urls.replayVision(), { tab: 'search', q: 'rage clicks' })+ router.actions.push(urls.replayVision(), {+ tab: 'search',+ q: 'rage clicks',+ })await expectLogic(logic).toFinishAllListeners()expect(searchSpy).toHaveBeenCalledTimes(1)- router.actions.push(urls.replayVision(), { tab: 'search', q: 'rage clicks' })+ router.actions.push(urls.replayVision(), {+ tab: 'search',+ q: 'rage clicks',+ })await expectLogic(logic).toFinishAllListeners()expect(searchSpy).toHaveBeenCalledTimes(1)logic.unmount()@@ -110,11 +138,18 @@ describe('observationSearchLogic', () => {searchSpy.mockImplementation(() => [500, { detail: 'embedding service down' }])const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })logic.mount()- router.actions.push(urls.replayVision(), { tab: 'search', q: 'rage clicks' })+ router.actions.push(urls.replayVision(), {+ tab: 'search',+ q: 'rage clicks',+ })await expectLogic(logic).toFinishAllListeners()expect(searchSpy).toHaveBeenCalledTimes(1)- router.actions.push(urls.replayVision(), { tab: 'search', q: 'rage clicks', unrelated: '1' })+ router.actions.push(urls.replayVision(), {+ tab: 'search',+ q: 'rage clicks',+ unrelated: '1',+ })await expectLogic(logic).toFinishAllListeners()expect(searchSpy).toHaveBeenCalledTimes(1)logic.unmount()diff --git a/products/replay_vision/frontend/search/observationSearchLogic.ts b/products/replay_vision/frontend/search/observationSearchLogic.tsindex dcb455db3f3c..8020e6c1e2a5 100644--- a/products/replay_vision/frontend/search/observationSearchLogic.ts+++ b/products/replay_vision/frontend/search/observationSearchLogic.ts@@ -29,6 +29,9 @@ import { ReplayScannerTab } from '../replay_scanners/replayScannerSceneLogic'// The server's MAX_SEARCH_LIMIT. A larger value would 400.const SEARCH_RESULT_LIMIT = 50+// Client-side paging over the single ranked response. Not in the URL, where the observations table owns `page`.+export const SEARCH_PAGE_SIZE = 10+// Relative to the best match, because distances are only comparable within one response.const STRONG_MATCH_MARGIN = 0.05// The server's error code when the organization has not allowed AI data processing.@@ -47,6 +50,11 @@ export interface ObservationSearchLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface observationSearchLogicValues {+ page: number+ pageCount: number+ pageEndIndex: number+ pageResults: ObservationSearchResultApi[]+ pageStartIndex: numberquery: stringrecentQueries: string[]results: ObservationSearchResultApi[] | null@@ -93,6 +101,9 @@ export interface observationSearchLogicActions {results: ObservationSearchResultApi[]truncated: boolean}+ setPage: (page: number) => {+ page: number+ }setQuery: (query: string) => {query: string}@@ -102,6 +113,10 @@ export interface observationSearchLogicActions {export interface observationSearchLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ pageCount: (results: ObservationSearchResultApi[] | null) => number+ pageResults: (results: ObservationSearchResultApi[] | null, page: number) => ObservationSearchResultApi[]+ pageStartIndex: (page: number) => number+ pageEndIndex: (pageStartIndex: number, pageResults: ObservationSearchResultApi[]) => numberstrongMatchDistanceCutoff: (results: ObservationSearchResultApi[] | null) => number | null}}@@ -120,6 +135,7 @@ export const observationSearchLogic = kea<observationSearchLogicType>([actions({setQuery: (query: string) => ({ query }),+ setPage: (page: number) => ({ page }),search: true,searchSuccess: (results: ObservationSearchResultApi[], query: string, truncated: boolean) => ({results,@@ -172,6 +188,13 @@ export const observationSearchLogic = kea<observationSearchLogicType>([: state,},],+ page: [+ 1 as number,+ {+ setPage: (_, { page }) => page,+ searchSuccess: () => 1,+ },+ ],// The server cut the response to `limit`, so the results are a top slice, not everything that matched.truncated: [false,@@ -209,6 +232,22 @@ export const observationSearchLogic = kea<observationSearchLogicType>([})),selectors({+ pageCount: [+ (s) => [s.results],+ (results: ObservationSearchResultApi[] | null): number =>+ results ? Math.ceil(results.length / SEARCH_PAGE_SIZE) : 0,+ ],+ pageResults: [+ (s) => [s.results, s.page],+ (results: ObservationSearchResultApi[] | null, page: number): ObservationSearchResultApi[] =>+ results ? results.slice((page - 1) * SEARCH_PAGE_SIZE, page * SEARCH_PAGE_SIZE) : [],+ ],+ pageStartIndex: [(s) => [s.page], (page: number): number => (page - 1) * SEARCH_PAGE_SIZE],+ pageEndIndex: [+ (s) => [s.pageStartIndex, s.pageResults],+ (pageStartIndex: number, pageResults: ObservationSearchResultApi[]): number =>+ pageStartIndex + pageResults.length,+ ],// Null when the tag would not separate anything, so it is never shown on every result.strongMatchDistanceCutoff: [(s) => [s.results],@@ -276,7 +315,10 @@ export const observationSearchLogic = kea<observationSearchLogicType>([actionToUrl(({ values }) => ({search: () => [router.values.location.pathname,- { ...router.values.searchParams, q: values.query.trim() || undefined },+ {+ ...router.values.searchParams,+ q: values.query.trim() || undefined,+ },router.values.hashParams,{ replace: true },],