: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-vision): search UI 2.0 (#101802)
Hayne Ryu267c61d2d1f3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4bf791f41c7d..15edcc430e1b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10165,21 +10165,21 @@ snapshots:scenes-app-replay-vision--observation-detail-monitor--light:hash: v1.k794b7964.266af7318c0609fc4b1df50ffdc70b05f6a33d7f0cedbd8fcaff5040de483cb2.flvYykloNw1KibfSjtHG9M_L_Gl_knRVLMgWHk5TRxEscenes-app-replay-vision--scanner-alerts--dark:- hash: v1.k794b7964.c416988b5908944127a58d491bf68dceb3f1f9caf728b69185f372f11f2ab68c.aHRUHVbQvkxQzLEFJmWx1YUCfAPgMVcTyiAeuvNfUS4+ hash: v1.k794b7964.87fdb6e06721ceec6ed9bb54eb0e48ab04c117a20e18d2b64a4253671999876f.4o_jktzFiZNieMvqKaefp4SP6mCmkG6X7OVBhkaXcWsscenes-app-replay-vision--scanner-alerts--light:- hash: v1.k794b7964.30c66d191a65b9cf05e8284d5071fefe9467e44e7ccbb250d63a8b34df49c27b.gHVmz1JrIkghgWc1qrWGIqgjCgqEM6311VjKAYakJf0+ hash: v1.k794b7964.2628f34e2afc6ae3de0dd163305ac123beb35162605a459ce27d5be4e64b1348.MCzcvn963uAvFXtcxt5QUpz-2YlH48oi74L2y_Y-6-Ascenes-app-replay-vision--scanner-alerts-empty--dark:- hash: v1.k794b7964.cd0860376440e9d94131e9ded840b07be77b28981c99be1b7a7b0cee70920b9f.eAtcfBJrUx574axqQ35VtEIL1GVNN0i2wzZPWuP9OpM+ hash: v1.k794b7964.ccc6612e3032bc8df51a78f1d5db9f05ab068fbf9dfcaa6e61c0b089269fcc20.qbpdY0ssP6h0w0MTmE1hkEICNtqz7vMLGb5PkzSZq8kscenes-app-replay-vision--scanner-alerts-empty--light:- hash: v1.k794b7964.0ef826b7658d0bd8ccaa3089d76cea2a4410b4124c3c81b957af439d5f9f549d.lEAwMkjqNuZhxqmK2y8cKPkc1lC8wUIQUJHmY9-04UY+ hash: v1.k794b7964.d90d7c951a6cc5eb3a8812b5b88ec6b487fc9cb7061c1eb9f8dedb8c3cd6997e.H9Vt0ME7aUMtsDLFF_jVNmlZGYWHsEvAj_x2_tq894cscenes-app-replay-vision--scanner-calibration--dark:hash: v1.k794b7964.5e0f861f7937065a33c6b68973fe2b5f853d0a2ce9660aaf41f53d1c7cfef4e0.p3b3ZO--YxEqmZWSi9DT8ndq3ZP2J2dU7WuRMhOhOd4scenes-app-replay-vision--scanner-calibration--light:hash: v1.k794b7964.43b310ff18e050913e41203405a1c07bc828efb546578e719db5fe304db986ec.bIxzTXCnMK2zCCr-iNlrImXP0hCopvBQTqpcyc_sIawscenes-app-replay-vision--scanner-calibration-activation-badge--dark:- hash: v1.k794b7964.3d58f2778bd955febde2246946648cb8f5bcfc709187e543be9f249cfa4a1339.NcAz_U6C3UbB7Sv_8BuecarPp1NKNOs3Q-A2HyUh8Ro+ hash: v1.k794b7964.29ac23a47de6f34ef5d51fd8e36b9a238f5aea7789d750828790d91362256961.Yhgjh0An9dM-SADDp5cxxL5TeNIzkTlV57QNEdAF6tUscenes-app-replay-vision--scanner-calibration-activation-badge--light:- hash: v1.k794b7964.b55c1a62f93cbcfa4bf67a70a366f846234e87844bf3ffc3c798c088d7b6dbb0.Gbtgw_gutHOyKMzZq3Dr-X-jfmj24w5nd8sLyjQl3Q0+ hash: v1.k794b7964.d28929c4ac28d432357a90b416c9bdcfed986df55ca55c5d01dd995d60315ff8.f0l_fgADuy7e8-QAaFjpc_BlAI0icVsqsi1UVW1iu5Escenes-app-replay-vision--scanner-calibration-activation-prompt--dark:hash: v1.k794b7964.ac385326a77b8943731bc6f58dfc17128bdfb0c9bcab0557cbabff8ac84e9266.AAHOM9SvqLqszqls1kpl2bG9AFbTaDfalHCB_sxZf0Mscenes-app-replay-vision--scanner-calibration-activation-prompt--light:@@ -10189,17 +10189,17 @@ snapshots:scenes-app-replay-vision--scanner-calibration-test-nudge--light:hash: v1.k794b7964.cd9edecc6e5724f6fabda9d3c67545ee900d8834ca875fa982544e6a82e959cc.dfLBW0Pc4UZBPc43ce00mYiKIWMLOKohcIevHVGJZ9cscenes-app-replay-vision--scanner-configuration--dark:- hash: v1.k794b7964.4596bbf4c6a43f0c735477d4a63b40aab754676d777ee5a4e93aaf480cd96bfe.J9MGM9riSXhFjfBTCC8UbnT5e323clk16BfpggM2Tyk+ hash: v1.k794b7964.301f453cefdf0fe2128e76c61bc1de01f8628229f855c9ae45f8a74f7a2688eb.LIiZp_TmIOBDZDyTJADogI-Ceqt5yt07I-u71xNNDvkscenes-app-replay-vision--scanner-configuration--light:- hash: v1.k794b7964.c2e4dea814848ef2bf61325776fd0fff64dc1c9f0a7e8a67b38caebebafc3798.McPralOmkS61h2hKaUNWgE0TnLo-ujyHM9liDC69QF8+ hash: v1.k794b7964.7e988a775c325a75ce5883bb1d11fcc02d64abb732b5c3f67a7d9daf85144423.bMsjttayvTrQQekiCtzm2uagEglefj5Zk81P2WdYzjoscenes-app-replay-vision--scanner-configuration-lite-standard-pro--dark:- hash: v1.k794b7964.4b34a2826a852c568ec9353c6a5fde5440a898f7685b97fed5e51a469e155202.RgAsIb8j2WG9qYPHGNCpK1qxTBFXKCZ2-DKJy6Jjc-I+ hash: v1.k794b7964.8694aae4c12bb68692b71e679cc5e4f3cd1d68caadd3197b6f4cf72853bb4609.gMNUr6auG0bBaMc8jtUhxdAUMsw-lZ6CbGIwAUQEmOwscenes-app-replay-vision--scanner-configuration-lite-standard-pro--light:- hash: v1.k794b7964.a803506cb2c25778fd1d9f965e48326e4eae15c832bac2b51d66cfd4a355fca8.aLvhYlsX92MKJu_Y4_fZ2Cd4ZfSE74LiS6npZAmekfk+ hash: v1.k794b7964.aede48e49edc8118aaf63f1e629774294ad9c82da8ed0b6573c1f040eda76eb7.JmC9-XqCP_VVxxmUFIEeSMez7QArWBm-2Gya8M1MrDgscenes-app-replay-vision--scanner-configuration-tier-names--dark:- hash: v1.k794b7964.ed44783674d2aa014cbc884127c06f48472f95affa90a77d14a552d98e5bf02a.YJH8P86Vimm3Db3ncEsyvtmEgkUOYYOj7dDxJJhoq1E+ hash: v1.k794b7964.6608759699f4c2cb9a7fe8b20ce707ba93fecc5ca1ef20f3111b509a45581ec5.q22jVY9nU23yEWsA6SRcDf5oPvfLanzi3H8953d_LjQscenes-app-replay-vision--scanner-configuration-tier-names--light:- hash: v1.k794b7964.097785d3714eb8124baf96f319fb1135e143f8b40e1de668e840e6e6ae2f6794.4t4U0eJ_35BccB2UrQnFiz3883LXwJVGwsmP89oHd4s+ hash: v1.k794b7964.99613f3da6df0b847d8e5aceee496d548249074a6aed2207189de67df11948f3.CE4owRhm1E7_bbxpAN6xVmTnQ2oNbfAP28Ya2lBluEEscenes-app-replay-vision--scanner-editor-budget--dark:hash: v1.k794b7964.37379538a705b9cfdaae3992ffbb357d3f7277abc9b77000c37e5d65d2d9a182.tIr_lkCBHvvxOjUsNFJ_VwNzAkD_MY2q-fN7anGin90scenes-app-replay-vision--scanner-editor-budget--light:@@ -10241,25 +10241,25 @@ snapshots:scenes-app-replay-vision--scanner-editor-triggers--light:hash: v1.k794b7964.1325a276c040c4fdec27fd9d75ecde45e08d343f4e76806a03819747f4c52973.6k8EbsIyUMKtWUuUvV-ElrJCGK5_-iSXLT4bi_fp3Ggscenes-app-replay-vision--scanner-observations--dark:- hash: v1.k794b7964.402fa9ac00801dcc40affa0aab0764fa66e3123f71d692459218b3a2b31608b9.C79AV3kXB1w8Sh4jz60Ch1ZxmN5OAsAmD3ivWpg8noo+ hash: v1.k794b7964.a752f7f891f1b2ceaea0400659ccc880f0ca28d966b658ef0f77ce844782c92e.PmMw6zm-TZLtplMoFrVe_tBEPca68mAqAkRRVJNdgyoscenes-app-replay-vision--scanner-observations--light:- hash: v1.k794b7964.00d24a18b12ab5fd776a9367e0aea1b7563617afffac960e4d693ab473d49717.ASmLzygbIkg4yJ2vKiSaImoFPpMALHMSluBBKkY4G5M+ hash: v1.k794b7964.8080138683d8e416aa3a924e9b9284b7803a3b16ba1228d816b73c63915a3b53.Lap3WKKKlTZ176TgR1uH5JfxbNqNn0zIWInq8W3bsT0scenes-app-replay-vision--scanner-on-demand--dark:- hash: v1.k794b7964.e3c55f635fcc957d786bf810c6be7f7ba8da1287a4390314893282062f43e108._oT0AUvPgnwHst_b6VX6Op2av3k5NsOyjnquUcgTB4c+ hash: v1.k794b7964.8613b8f3c572a259695f7658d33b058be49f3be5b73e050e3fb358289800c964.DPrs0SWEtTD2prJs342aey5-aX1mEuYdTblY4N9dqaEscenes-app-replay-vision--scanner-on-demand--light:- hash: v1.k794b7964.ee354fdd1202a3489ea67393713b268bbfe711e771102c975aeab4921a61f9f7.MP0HrALcb5hmcbxbIRroM0f93rHw-v6_egWPGV-CL9Y+ hash: v1.k794b7964.533c571e0ae254f05fe3183bcafa90f28006a8921608c718a012a5227ed2436f.rFjBuser9MhT4H20Nx5g14EIRIt0RqHNKQPC9hssCssscenes-app-replay-vision--scanner-scan-drought--dark:hash: v1.k794b7964.47963d3ee2fc2934b80cfd51b0db411baf326710d528c8995ed7eecbae4d6faa.zV2CxUwodEqwEiQT5_Tr3XAFLhkhAGTY3z8LUm97USoscenes-app-replay-vision--scanner-scan-drought--light:hash: v1.k794b7964.d3e3119d983ea105adcd26771cfdfbe14e082892971e48cb4000de6ca48e44df.pfdBzR5cE9sN8GjQF_54zIi5OvM-4nGsvyzsZd9TLSkscenes-app-replay-vision--scanner-scouts--dark:- hash: v1.k794b7964.8a95f790a279c39ae389ddef6327f09b607f61f3bf42026498beeca2779090e7.9CJc3oR8vxy97OUqFWI7gIvIwG9MvbpHWy_FeZ-qqnA+ hash: v1.k794b7964.05cd0d9a8bee23f703a575ecdd315f00c29cb482e83fbaeacf4e548e31bef15c.V8B-a6fRzpuTi6gRsRl1S6KaBcN32QEi2jnAQ2x5ISkscenes-app-replay-vision--scanner-scouts--light:- hash: v1.k794b7964.e574601527f6ee932adff3244f99b0422f8a32972d28e4391277387d26d967f1.BHVJsxaI0JG0RbtqtSvRrHgo2l7M60-mgfH2ZOFt8xg+ hash: v1.k794b7964.b0180eb02b9c80483d1876933bf2596bd4ae27bfe3821a1f5b40472b42480d0d.A0Kj3VCCbvv17Rm5RppBMGdDGyhlu2T1Y5qpKRw8Y0gscenes-app-replay-vision--scanner-scouts-empty--dark:- hash: v1.k794b7964.7f7434025d5fec47b6866e48735766c1c9125655617ebf63d2e92d2b740678fc.s_ygEWntMkDhp6ACIlK2h_KjJyScohJUaMaRQ_ARzmc+ hash: v1.k794b7964.e1b10948c3d6c52419f993497104c7e395a4b049da619e23f5c135ccb0d35ffb.Kf3lZFMUPqBIX1lhDr9s1kXLcM-cDYUP9Xaf65jtRSMscenes-app-replay-vision--scanner-scouts-empty--light:- hash: v1.k794b7964.ff3212b72908a9571d47b33e570197ecb4aeca4a3893ff4d6acbc669c5e24a56.7m1DF3U4Bzz3jCHIq6q5wRapDG-uvOdBJ3EfSbdBWM4+ hash: v1.k794b7964.12514db00b6d928ab64039a78a5ce02fe74b43daedd26b76621dd65e3088b1e3.6HfZozgO4OvkB-vqEQdBUKp_oL24qSTbw18hzpqsfN0scenes-app-replay-vision--scanner-templates--dark:hash: v1.k794b7964.5730130a0ab80bc33dc701a8cc69c354f8ac4f50df6c4a25f6b0627a4e90ceeb.0zwSfaSwHJZ0F2c__vQj7Bj3VUvQZD3nu5zcrxJym9oscenes-app-replay-vision--scanner-templates--light:@@ -10277,9 +10277,9 @@ snapshots:scenes-app-replay-vision--startup-program-cap--light:hash: v1.k794b7964.1f2fc262b5c742019e78b9fd8a13820c73291ee4c8086a34b01e8cdd47e31248.WubeGDNAdkP-6NxslVXFGWzr-pHvVfeYQQfEBk4LGj0scenes-app-replay-vision--summarizer-overview--dark:- hash: v1.k794b7964.50495283acb69918da7bbc449506a9d795d31179e6dbe5b4a872adad73252149.O_iQSRhe6as8aKj5HIWZhk0etaNDOI8p6UIR0cG7Cso+ hash: v1.k794b7964.0a6757ef4af2eca666787799e9521fd3d2c1e3d1310bc69ba983a50bfb742405.04FOFBX4MLEmhdRmTC_vFoRIuVRYA48ybJ2hMQx3pzEscenes-app-replay-vision--summarizer-overview--light:- hash: v1.k794b7964.c5df0e640d994a9c2ec8cbb2e383be1eb5fcf06dadb62b0f7523a90257dc2144.nIYMWvHWhAM9lExklaJV7toaICXFw_o16NgM684nV5o+ hash: v1.k794b7964.c897f2b307bb7929d66c0f57b6654cbefeaa609a2bcfbd0d422b7bbc8f8f7fed.2yTPtWm2bYe82ly06Db0a7RBqYCZWq83sZwE8zMSLcQscenes-app-replay-vision--usage-tab--dark:hash: v1.k794b7964.aab9212ef24367842f0c4b5c6e0b5568efa7b02455e0b762a0dae56f7a251ded.Vis7Q1vljRgKviTHYsDV5sgLm5fLA8DqNHkJ-26wpBEscenes-app-replay-vision--usage-tab--light:diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsxindex 90d874609181..a428fdd57741 100644--- a/products/replay_vision/frontend/components/ObservationCard.tsx+++ b/products/replay_vision/frontend/components/ObservationCard.tsx@@ -18,6 +18,7 @@ import {parseFailureReason,parseIneligibleReason,} from '../replay_scanners/types'+import { markSimilarSearchIntent, similarSearchUrl } from '../search/observationQueries'import { citedTextToPlainText, parseCitedSegments } from '../utils/citations'import { readReasoning, scannerLabel } from '../utils/observation'import { CitedMarkdown } from './CitedMarkdown'@@ -448,6 +449,7 @@ export function ObservationDockCard({// The prompt is the question the scan judged, so it gives the verdict its meaning. Show it inline here so a// reader does not have to open the details page to know what "Yes" answered.const prompt = snapshot ? (configFromSnapshot(snapshot)?.prompt ?? null) : null+ const similarUrl = observation.status === 'succeeded' ? similarSearchUrl(observation) : null// Summarizers excluded: their primary output already is the full textconst reasoning =observation.status === 'succeeded' && scannerType !== 'summarizer' ? readReasoning(observation) : null@@ -473,6 +475,16 @@ export function ObservationDockCard({<Link to={urls.replayVisionObservation(observation.id)} className="text-xs whitespace-nowrap">View details</Link>+ {similarUrl && (+ <Link+ to={similarUrl}+ onClick={() => markSimilarSearchIntent(observation)}+ className="text-xs whitespace-nowrap"+ data-attr="vision-dock-find-similar"+ >+ Find similar+ </Link>+ )}</div></div>diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.test.ts b/products/replay_vision/frontend/observations/replayObservationLogic.test.tsindex 19a57f9610b3..e1a2fc41b08c 100644--- a/products/replay_vision/frontend/observations/replayObservationLogic.test.ts+++ b/products/replay_vision/frontend/observations/replayObservationLogic.test.ts@@ -201,7 +201,7 @@ describe('replayObservationLogic', () => {try {await expectLogic(logic).toDispatchActions(['loadObservationSuccess'])const { breadcrumbs } = sceneLogic.values- expect(breadcrumbs[breadcrumbs.length - 2].path).toBe('/replay-vision/scanner-9?tab=search&q=true')+ expect(breadcrumbs[breadcrumbs.length - 2].path).toBe('/replay-vision?tab=search&q=true')} finally {logic.unmount()}diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.ts b/products/replay_vision/frontend/observations/replayObservationLogic.tsindex 6e1a2ec37b12..2042b2753ca3 100644--- a/products/replay_vision/frontend/observations/replayObservationLogic.ts+++ b/products/replay_vision/frontend/observations/replayObservationLogic.ts@@ -11,7 +11,9 @@ import { visionObservationsRetrieve, visionObservationsViewedCreate } from '../gimport type { ReplayObservationApi, VisionObservationsRetrieveParams } from '../generated/api.schemas'import { scheduleObservationPoll } from '../logics/observationPolling'import { requestObservationRetry } from '../logics/observationRetry'+import { ReplayScannerTab } from '../replay_scanners/replayScannerSceneLogic'import { OBSERVATION_LIST_FILTER_KEYS, OBSERVATION_LIST_URL_PARAM_KEYS } from '../replay_scanners/types'+import { searchBreadcrumb } from '../search/observationQueries'import {OBSERVATION_ORIGIN_PARAM,WATCH_FEED_ORIGIN,@@ -70,8 +72,7 @@ export function observationParentUrl(*/export function scannerReturnParams(searchParams: Record<string, unknown>): Record<string, string> {const params: Record<string, string> = {}- // `tab` and `q` (the Search tab's query) sit alongside the observations table's own params.- for (const key of ['tab', 'q', ...OBSERVATION_LIST_URL_PARAM_KEYS]) {+ for (const key of ['tab', 'q', 'scanner', 'similar', ...OBSERVATION_LIST_URL_PARAM_KEYS]) {const value = searchParams[key]// The router coerces a param by shape: `page=2` to a number, `q=true` to a boolean. Keep every// scalar and stringify it; dropping the coerced ones would lose that filter on the way back.@@ -321,10 +322,13 @@ export const replayObservationLogic = kea<replayObservationLogicType>([// to the feed rather than the scanner that owns the row.const setParentBreadcrumb = (observation: ReplayObservationApi): void => {const { searchParams } = router.values+ const returnParams = scannerReturnParams(searchParams)replayObservationSceneLogic().actions.setParentBreadcrumb(searchParams[OBSERVATION_ORIGIN_PARAM] === WATCH_FEED_ORIGIN? watchFeedBreadcrumb()- : observationParentBreadcrumb(observation, scannerReturnParams(searchParams))+ : returnParams.tab === ReplayScannerTab.Search+ ? searchBreadcrumb(returnParams)+ : observationParentBreadcrumb(observation, returnParams))}return {diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.test.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.test.tsxindex 5236363cabf8..7d8c3d6dfda5 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.test.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.test.tsx@@ -15,12 +15,6 @@ const mockImportedTabs: string[] = []jest.mock('./components/ScannerOverview', () => ({ ScannerOverview: () => <div>Overview content</div> }))jest.mock('./components/ScannerScoutCard', () => ({ ScannerScoutCard: () => null }))-jest.mock('../search/ObservationSearchTab', () => {- mockImportedTabs.push('Search')- return {- ObservationSearchTab: ({ scanner }: { scanner: { id: string } }) => <div>Search content {scanner.id}</div>,- }-})jest.mock('./components/ScannerRunTab', () => {mockImportedTabs.push('On-demand')return { ScannerRunTab: ({ scannerId }: { scannerId: string }) => <div>On-demand content {scannerId}</div> }@@ -102,7 +96,7 @@ describe('ReplayScanner', () => {expect(observationRequests[0].get('backfill_id')).toBe(backfillId)expect(mockImportedTabs).toEqual([])- const tabs = ['Search', 'On-demand', 'Backfills', 'Configuration', 'Calibration', 'Scouts', 'Alerts']+ const tabs = ['On-demand', 'Backfills', 'Configuration', 'Calibration', 'Scouts', 'Alerts']for (const [index, tab] of tabs.entries()) {fireEvent.click(screen.getByText(tab, { exact: true }))expect(screen.getByText('Observations', { exact: true })).toBeInTheDocument()diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsxindex 7ac599c5ac42..41f2453e7ca9 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx@@ -30,9 +30,6 @@ import { ReplayScannerTab, replayScannerSceneLogic } from './replayScannerSceneLimport { scanDrought } from './scanDrought'import { LIMIT_REACHED_TOOLTIP } from './scannerCopy'-const ObservationSearchTab = lazyWithRetry(() =>- import('../search/ObservationSearchTab').then((module) => ({ default: module.ObservationSearchTab }))-)const ScannerAlertsTab = lazyWithRetry(() =>import('./components/ScannerAlertsTab').then((module) => ({ default: module.ScannerAlertsTab })))@@ -165,11 +162,6 @@ export function ReplayScannerSceneComponent(): JSX.Element {label: 'Observations',content: <ScannerObservationsTable scannerId={scannerId} />,},- {- key: ReplayScannerTab.Search,- label: 'Search',- content: <ObservationSearchTab scanner={scanner} />,- },{key: ReplayScannerTab.OnDemand,label: 'On-demand',diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex 7589835e1b3e..423bad2072b6 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -38,7 +38,7 @@ import { ScannerTypeBadge } from '../components/ScannerTypeBadge'import { ScanningPausedBanner } from '../components/ScanningPausedBanner'import { replayVisionEmptyState } from '../emptyState/replayVisionEmptyState'import { visionQuotaLogic } from '../logics/visionQuotaLogic'-import { ObservationSearchTab } from '../search/ObservationSearchTab'+import { ObservationSearch } from '../search/ObservationSearch'import { getReplayVisionDeleteDisabledReason, getReplayVisionEditDisabledReason } from '../utils/accessControl'import { creditsToUsd, formatCreditCount } from '../utils/credits'import { CreateScannerButton } from './components/CreateScannerButton'@@ -312,7 +312,7 @@ export function ReplayScannersScene(): JSX.Element {{activeTab === 'watch' ? (<WatchFeedTab />) : activeTab === ReplayScannerTab.Search ? (- <ObservationSearchTab scanner={null} />+ <ObservationSearch className="mt-2 w-4/5 mx-auto" />) : activeTab === 'usage' ? (<VisionUsageTab />) : (diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex 1000cf2c5d3b..4d85cafbabcf 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { useEffect } from 'react'-import { IconCopy, IconEye, IconPlay, IconRefresh, IconX } from '@posthog/icons'+import { IconCopy, IconEye, IconPlay, IconRefresh, IconSearch, IconX } from '@posthog/icons'import { LemonButton, LemonInput, LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'@@ -20,6 +20,7 @@ import { ObservationRetryButton } from '../../components/ObservationRetryButton'import { ObservationThumbnail } from '../../components/ObservationThumbnail'import type { ReplayObservationApi } from '../../generated/api.schemas'import { observationDetailUrl } from '../../observations/replayObservationLogic'+import { markSimilarSearchIntent, searchTabUrl, similarSearchUrl } from '../../search/observationQueries'import { shortBackfillId } from '../../utils/backfills'import {OBSERVATIONS_PAGE_SIZE,@@ -253,18 +254,35 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):title: '',key: 'actions',width: 1,- render: (_, obs) => (- <LemonButton- size="small"- type="secondary"- icon={<IconEye />}- to={observationDetailUrl(obs.id, observationDetailLinkParams)}- className="whitespace-nowrap"- data-attr="vision-observation-view-details"- >- View details- </LemonButton>- ),+ render: (_, obs) => {+ const similarUrl = similarSearchUrl(obs)+ return (+ <div className="flex items-center gap-1">+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconEye />}+ to={observationDetailUrl(obs.id, observationDetailLinkParams)}+ className="whitespace-nowrap"+ data-attr="vision-observation-view-details"+ >+ View details+ </LemonButton>+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconSearch />}+ to={similarUrl ?? undefined}+ onClick={() => markSimilarSearchIntent(obs)}+ disabledReason={similarUrl ? undefined : 'This observation has no text to search with'}+ tooltip="Find similar observations across scanners"+ // A `to` renders a Link, which skips LemonButton's tooltip-to-aria-label fallback.+ aria-label="Find similar observations across scanners"+ data-attr="vision-observation-find-similar"+ />+ </div>+ )+ },},]@@ -281,6 +299,15 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):· {observationStats.inFlight.toLocaleString()} in flight</span><div className="ml-auto flex flex-wrap items-center gap-3 xl:flex-nowrap">+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconSearch />}+ to={searchTabUrl({ scanner: scannerId })}+ data-attr="vision-observations-search"+ >+ Search observations+ </LemonButton><div className="flex flex-wrap items-center gap-2 xl:flex-nowrap">{(observationStats.total > 0 || hasActiveObservationFilters) && (<>diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.tsnew file mode 100644index 000000000000..bf0b0993bf4f--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.test.ts@@ -0,0 +1,35 @@+import { router } from 'kea-router'++import { urls } from 'scenes/urls'++import { initKeaTests } from '~/test/init'++import { replayScannerSceneLogic } from './replayScannerSceneLogic'++describe('replayScannerSceneLogic', () => {+ beforeEach(() => {+ initKeaTests()+ })++ it.each([+ [+ 'a scanner and its query',+ 'scanner-9',+ { q: 'rage clicks' },+ { tab: 'search', scanner: 'scanner-9', q: 'rage clicks' },+ ],+ ['no scanner for a new one', 'new', {}, { tab: 'search' }],+ ])(+ 'an old per-scanner search link with %s opens the hub search and keeps the hash',+ (_name, id, extra, expected) => {+ const logic = replayScannerSceneLogic()+ logic.mount()+ router.actions.push(urls.replayVision(id), { tab: 'search', ...extra }, { sessionRecordingId: 'session-1' })++ expect(router.values.location.pathname).toMatch(new RegExp(`${urls.replayVision()}$`))+ expect(router.values.searchParams).toEqual(expected)+ expect(router.values.hashParams).toEqual({ sessionRecordingId: 'session-1' })+ logic.unmount()+ }+ )+})diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.tsindex 29990456e55f..15f8a2f50273 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts@@ -104,16 +104,26 @@ export const replayScannerSceneLogic = kea<replayScannerSceneLogicType>([} else {searchParams.tab = values.activeTab}- // The query belongs to the Search tab; carrying it to another tab would re-run it on return.- if (values.activeTab !== ReplayScannerTab.Search) {- delete searchParams.q- }return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]},})),urlToAction(({ actions, values }) => ({[urls.replayVision(':id')]: ({ id }, searchParams) => {+ // Old per-scanner search links open the hub search.+ if (searchParams.tab === ReplayScannerTab.Search) {+ const q = searchParams.q != null ? String(searchParams.q) : ''+ router.actions.replace(+ urls.replayVision(),+ {+ tab: ReplayScannerTab.Search,+ ...(id && id !== 'new' ? { scanner: id } : {}),+ ...(q ? { q } : {}),+ },+ router.values.hashParams+ )+ return+ }const scannerId = id || 'new'if (scannerId !== values.scannerId) {actions.setScannerId(scannerId)diff --git a/products/replay_vision/frontend/search/ObservationSearch.tsx b/products/replay_vision/frontend/search/ObservationSearch.tsxnew file mode 100644index 000000000000..836e41893943--- /dev/null+++ b/products/replay_vision/frontend/search/ObservationSearch.tsx@@ -0,0 +1,309 @@+import clsx from 'clsx'+import { useActions, useValues } from 'kea'+import { combineUrl } from 'kea-router'+import { useState } from 'react'++import * as researchPng from '@posthog/brand/hoggies/png/research'+import { IconChevronDown, IconClock, IconPlusSmall, IconSearch, IconSparkles, IconX } from '@posthog/icons'+import { LemonButton, LemonInput, LemonMenu, Popover, Spinner } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import { visionScannersListLogic } from '../logics/visionScannersListLogic'+import { type ReplayScanner, scannerFromApi } from '../replay_scanners/types'+import { type ObservationSearchLogicProps, observationSearchLogic } from './observationSearchLogic'+import { SearchResults } from './SearchResults'++const HedgehogResearch = pngHoggie(researchPng)++const FALLBACK_EXAMPLE_QUERIES = ['users who got stuck and gave up', 'rage clicking out of frustration']++function exampleQueries(scanner: ReplayScanner | null): string[] {+ switch (scanner?.scanner_type) {+ case 'monitor':+ return ['the most severe cases', 'sessions where the user recovered']+ case 'classifier': {+ const categories = scanner.scanner_config.tags.filter((tag) => tag.trim())+ return categories.length > 0 ? categories.slice(0, 3) : FALLBACK_EXAMPLE_QUERIES+ }+ case 'scorer':+ return ['sessions that struggled the most', 'sessions that went smoothly']+ case 'summarizer':+ return ['users who completed what they came to do', 'confusion and backtracking']+ default:+ return FALLBACK_EXAMPLE_QUERIES+ }+}++function SearchPalette({+ recents,+ suggestions,+ suggestionsLoading,+ disabledReason,+ onPick,+}: {+ recents: string[]+ suggestions: string[]+ suggestionsLoading: boolean+ disabledReason?: string+ onPick: (query: string) => void+}): JSX.Element {+ const item = (query: string, icon: JSX.Element, dataAttr: string): JSX.Element => (+ <LemonButton+ key={query}+ fullWidth+ size="small"+ icon={icon}+ disabledReason={disabledReason}+ // Mouse down would blur the input and close the palette first.+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => onPick(query)}+ data-attr={dataAttr}+ >+ <span className="truncate">{query}</span>+ </LemonButton>+ )+ return (+ <div className="flex flex-col gap-0.5 p-1" data-attr="vision-search-palette">+ {recents.length > 0 && (+ <>+ <span className="text-xs text-tertiary font-medium px-2 pt-1">Recent</span>+ <ul data-attr="vision-search-recent-list">+ {recents.map((recent) => (+ <li key={recent}>{item(recent, <IconClock />, 'vision-search-recent')}</li>+ ))}+ </ul>+ </>+ )}+ <span className="text-xs text-tertiary font-medium px-2 pt-1">Suggested searches</span>+ {suggestionsLoading ? (+ <Spinner className="self-center my-2" />+ ) : suggestions.length === 0 ? (+ <span className="text-xs text-tertiary px-2 py-1">+ Themes from what your scanners observed will appear here.+ </span>+ ) : (+ suggestions.map((suggestion) =>+ item(suggestion, <IconSparkles className="text-accent" />, 'vision-search-example')+ )+ )}+ </div>+ )+}++export function ObservationSearch({ className }: { className?: string }): JSX.Element {+ const { currentTeamId } = useValues(teamLogic)+ const { user } = useValues(userLogic)+ const { dataProcessingAccepted } = useValues(aiConsentLogic)+ const { scanners } = useValues(visionScannersListLogic)+ const logicProps: ObservationSearchLogicProps = { teamId: currentTeamId, userId: user?.uuid ?? null }+ const logic = observationSearchLogic(logicProps)+ const {+ query,+ scannerId,+ results,+ searching,+ searchedQuery,+ sourceObservationId,+ recentQueries,+ suggestedQueries,+ suggestedQueriesLoading,+ } = useValues(logic)+ const { setQuery, setScannerId, search, clearSearch } = useActions(logic)++ const [paletteOpen, setPaletteOpen] = useState(false)++ const selectedApi = scanners.find((scanner) => scanner.id === scannerId)+ const selectedScanner = selectedApi ? scannerFromApi(selectedApi) : null+ const suggestions = suggestedQueries.length > 0 ? suggestedQueries : exampleQueries(selectedScanner)+ const typed = query.trim().toLowerCase()+ const matchingRecents = recentQueries.filter((recent) => recent !== query && recent.toLowerCase().includes(typed))+ const consentReason = dataProcessingAccepted ? undefined : 'AI data processing is turned off for your organization'+ const idle = results === null && !searching+ const submitDisabledReason =+ consentReason ?? (searching ? 'Searching' : !query.trim() ? 'Describe what to look for first' : undefined)+ const runQuery = (value: string): void => {+ if (searching) {+ return+ }+ setPaletteOpen(false)+ setQuery(value)+ search()+ }+ const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>): void => {+ if (event.nativeEvent.isComposing) {+ return+ }+ if (event.key === 'Escape') {+ setPaletteOpen(false)+ } else if (event.key === 'Enter' && !submitDisabledReason) {+ setPaletteOpen(false)+ search()+ }+ }++ const palette = (+ <SearchPalette+ recents={matchingRecents}+ suggestions={suggestions}+ suggestionsLoading={suggestedQueriesLoading}+ disabledReason={consentReason}+ onPick={runQuery}+ />+ )+ const scopeItems = [+ { label: 'All scanners', active: scannerId === null, onClick: () => setScannerId(null) },+ ...[...scanners]+ .sort((a, b) => a.name.localeCompare(b.name))+ .map((scanner) => ({+ label: scanner.name,+ active: scanner.id === scannerId,+ onClick: () => setScannerId(scanner.id),+ })),+ ]+ const input = (+ <LemonInput+ fullWidth+ size={idle ? 'large' : 'medium'}+ value={query}+ onChange={(value) => {+ setQuery(value)+ setPaletteOpen(true)+ }}+ onFocus={() => setPaletteOpen(true)}+ onBlur={() => setPaletteOpen(false)}+ onKeyDown={onKeyDown}+ placeholder="Describe what to look for"+ disabledReason={consentReason}+ autoComplete="off"+ autoFocus={idle}+ data-attr="vision-search-query"+ prefix={<IconSearch className="text-tertiary" />}+ suffix={+ <>+ {query && (+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ onClick={clearSearch}+ tooltip="Clear"+ data-attr="vision-search-clear"+ />+ )}+ {/* The input chrome focuses the field on click, which opens the palette over the picker. */}+ <span onClick={(event) => event.stopPropagation()}>+ <LemonMenu items={scopeItems} placement="bottom-end">+ <LemonButton+ size="small"+ type="secondary"+ sideIcon={<IconChevronDown />}+ className="max-w-64"+ data-attr="vision-search-scope"+ >+ <span className="truncate">{selectedScanner?.name ?? 'All scanners'}</span>+ </LemonButton>+ </LemonMenu>+ </span>+ <LemonButton+ type="primary"+ size="small"+ // The palette popover wraps the input, and buttons inside a popover reference grow a chevron.+ sideIcon={null}+ onClick={search}+ disabledReason={submitDisabledReason}+ data-attr="vision-search-submit"+ >+ Search+ </LemonButton>+ </>+ }+ />+ )++ return (+ <div className={clsx('@container flex flex-col gap-4', className)} data-attr="vision-search">+ {idle && (+ <div className="flex flex-col items-center gap-3 pt-4">+ <HedgehogResearch className="w-32 h-32" />+ <h2 className="text-xl font-semibold m-0">What happened in your sessions?</h2>+ <span className="text-sm text-secondary">+ Describe a behavior in plain words. Results are ranked by how well they match.+ </span>+ </div>+ )}+ {/* One subtree for both states, so the input keeps focus and state when the first results land. */}+ <div className={clsx('flex flex-col items-center gap-2', idle && 'w-full max-w-3xl self-center')}>+ <Popover+ visible={!idle && paletteOpen && dataProcessingAccepted}+ onClickOutside={() => setPaletteOpen(false)}+ placement="bottom-start"+ matchWidth+ padded={false}+ overlay={palette}+ >+ <div className="w-full max-w-3xl">{input}</div>+ </Popover>+ {idle && <div className="w-full border border-primary rounded-lg bg-surface-primary">{palette}</div>}+ </div>+ {results?.length === 0 && !searching && (+ <div className="rounded bg-surface-secondary px-3 py-6 flex flex-col items-center gap-3 text-center">+ <HedgehogResearch className="w-24 h-24" />+ <div className="flex flex-col items-center gap-3 min-w-0 max-w-2xl">+ <div className="text-sm text-secondary">+ {scannerId+ ? `No matches in ${selectedScanner?.name ?? 'this scanner'} for "${searchedQuery}".`+ : `No matches for "${searchedQuery}". Only sessions a scanner has analyzed are searchable, so nothing found can also mean no scanner is watching for this yet.`}+ </div>+ <div className="flex flex-wrap items-center justify-center gap-2">+ {scannerId ? (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconSearch />}+ onClick={() => setScannerId(null)}+ data-attr="vision-search-all-scanners"+ >+ Search all scanners+ </LemonButton>+ ) : (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconPlusSmall />}+ to={+ combineUrl(+ urls.replayVisionTemplates(),+ searchedQuery && !sourceObservationId ? { goal: searchedQuery } : {}+ ).url+ }+ data-attr="vision-search-create-scanner"+ >+ Create a scanner for this+ </LemonButton>+ )}+ <span className="text-xs text-secondary">or try</span>+ {suggestions+ .filter((suggestion) => suggestion !== searchedQuery)+ .map((suggestion) => (+ <LemonButton+ key={suggestion}+ type="tertiary"+ size="xsmall"+ onClick={() => runQuery(suggestion)}+ data-attr="vision-search-example"+ >+ {suggestion}+ </LemonButton>+ ))}+ </div>+ </div>+ </div>+ )}+ <SearchResults {...logicProps} />+ </div>+ )+}diff --git a/products/replay_vision/frontend/search/ObservationSearchTab.tsx b/products/replay_vision/frontend/search/ObservationSearchTab.tsxdeleted file mode 100644index a01e9cfb0b4c..000000000000--- a/products/replay_vision/frontend/search/ObservationSearchTab.tsx+++ /dev/null@@ -1,311 +0,0 @@-import clsx from 'clsx'-import { useActions, useValues } from 'kea'-import { Fragment } from 'react'--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 { 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 { 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']--// Examples should read like phrases the scanner type writes into observation content, which search matches semantically-function exampleQueries(scanner: ReplayScanner | null): string[] {- switch (scanner?.scanner_type) {- case 'monitor':- return ['the most severe cases', 'sessions where the user recovered']- case 'classifier': {- const categories = scanner.scanner_config.tags.filter((tag) => tag.trim())- return categories.length > 0 ? categories.slice(0, 3) : CROSS_SCANNER_EXAMPLE_QUERIES- }- case 'scorer':- return ['sessions that struggled the most', 'sessions that went smoothly']- case 'summarizer':- return ['users who completed what they came to do', 'confusion and backtracking']- default:- return CROSS_SCANNER_EXAMPLE_QUERIES- }-}--function suggestionDescription(crossScanner: boolean, fromObservations: boolean): string {- const subject = crossScanner ? 'your scanners' : 'this scanner'- if (fromObservations) {- return `Themes from what ${subject} observed recently.`- }- return `Examples to get started. Themes from what ${subject} observed will appear here once more sessions are analyzed.`-}--function QuerySection({- title,- description,- queries,- dataAttr,- onPick,-}: {- title: string- description: string- queries: string[]- dataAttr: string- onPick: (query: string) => void-}): JSX.Element {- return (- <div className="flex flex-col items-center gap-2">- <div>- <div className="font-semibold">{title}</div>- <div className="text-muted text-xs">{description}</div>- </div>- <div className="flex items-center justify-center gap-2 flex-wrap">- {queries.map((query) => (- <LemonButton- key={query}- type="secondary"- size="small"- onClick={() => onPick(query)}- data-attr={dataAttr}- >- {query}- </LemonButton>- ))}- </div>- </div>- )-}--function countLabel(count: number, truncated: boolean): string {- if (truncated) {- return `Showing the top ${count === 1 ? 'match' : `${count} matches`}, best first`- }- 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,- showScanner,- strongMatch,- returnParams,-}: {- result: ObservationSearchResultApi- searchedQuery: string- showScanner: boolean- strongMatch: boolean- returnParams: Record<string, string>-}): JSX.Element {- const observation = result.observation- const snapshot = observation.scanner_snapshot- return (- <Link- to={observationDetailUrl(observation.id, returnParams)}- className="block border rounded p-3 bg-surface-primary hover:border-accent space-y-2 text-primary"- data-attr="vision-search-result"- >- <div className="flex items-center gap-2 min-w-0">- {showScanner && (- <>- <span className="font-semibold text-sm truncate">{scannerLabel(observation)}</span>- {snapshot && <ScannerOutputBadge scannerType={snapshot.scanner_type} size="small" />}- </>- )}- <SubjectLabel observation={observation} />- <span className="ml-auto shrink-0 flex items-center gap-2 text-xs text-muted">- {strongMatch && (- <LemonTag type="success" size="small">- Strong match- </LemonTag>- )}- <TZLabel time={observation.created_at} />- </span>- </div>- {result.matched_content && (- <div className="text-sm text-secondary line-clamp-2">- {snippetSegments(result.matched_content, searchedQuery).map((segment, index) =>- segment.highlighted ? (- <span key={index} className="font-semibold text-accent">- {segment.text}- </span>- ) : (- <Fragment key={index}>{segment.text}</Fragment>- )- )}- </div>- )}- <ObservationResultSummary observation={observation} />- </Link>- )-}--export function ObservationSearchTab({ scanner }: { scanner: ReplayScanner | null }): JSX.Element {- const { currentTeamId } = useValues(teamLogic)- const { user } = useValues(userLogic)- const { dataProcessingAccepted } = useValues(aiConsentLogic)- const logic = observationSearchLogic({- scannerId: scanner?.id ?? null,- teamId: currentTeamId,- userId: user?.uuid ?? null,- })- const {- query,- results,- searching,- searchedQuery,- strongMatchDistanceCutoff,- truncated,- recentQueries,- suggestedQueries,- suggestedQueriesLoading,- page,- pageCount,- pageResults,- pageStartIndex,- pageEndIndex,- } = useValues(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> =- crossScanner || !searchedQuery ? {} : { tab: ReplayScannerTab.Search, q: searchedQuery }- const tryQueries = suggestedQueries.length > 0 ? suggestedQueries : exampleQueries(scanner)- const runQuery = (value: string): void => {- setQuery(value)- search()- }-- return (- <div className="w-full max-w-3xl mx-auto flex flex-col gap-4 pt-2">- <div className="flex gap-2">- <LemonInput- type="search"- fullWidth- prefix={<IconSearch />}- placeholder="Describe what to look for"- value={query}- onChange={setQuery}- onPressEnter={() => !searching && dataProcessingAccepted && search()}- autoFocus- data-attr="vision-search-query"- />- <LemonButton- type="primary"- onClick={() => search()}- loading={searching}- disabledReason={- !dataProcessingAccepted- ? 'AI data processing is turned off for your organization'- : !query.trim()- ? 'Describe what to look for first'- : undefined- }- data-attr="vision-search-submit"- >- Search- </LemonButton>- </div>-- {results === null ? (- searching ? (- <div className="flex items-center justify-center h-40">- <Spinner className="text-2xl" />- </div>- ) : (- <div className="text-center pt-8 flex flex-col gap-6">- <div className="text-muted">- {crossScanner- ? 'Search everything your scanners have observed, ranked by how well it matches.'- : 'Search everything this scanner has observed, ranked by how well it matches.'}- </div>- {recentQueries.length > 0 && (- <QuerySection- title="Recent searches"- description="Searches that returned results, saved in this browser."- queries={recentQueries}- dataAttr="vision-search-recent"- onPick={runQuery}- />- )}- {suggestedQueriesLoading ? (- // Hold the section rather than flash the fixed examples and swap them out a moment later.- <div className="flex items-center justify-center h-16">- <Spinner />- </div>- ) : (- <QuerySection- title="Suggested searches"- description={suggestionDescription(crossScanner, suggestedQueries.length > 0)}- queries={tryQueries}- dataAttr="vision-search-example"- onPick={runQuery}- />- )}- </div>- )- ) : (- <div className={clsx('flex flex-col gap-4', searching && 'opacity-50 pointer-events-none')}>- {results.length === 0 ? (- <div className="text-center text-muted pt-8">- No matches for "{searchedQuery}". Only sessions a scanner has analyzed are searchable.- </div>- ) : (- <>- <div className="text-muted text-sm">{countLabel(results.length, truncated)}</div>- <div className="flex flex-col gap-2">- {pageResults.map((result) => (- <SearchResultCard- key={result.observation.id}- result={result}- searchedQuery={searchedQuery ?? ''}- showScanner={crossScanner}- returnParams={returnParams}- strongMatch={- strongMatchDistanceCutoff !== null &&- result.distance <= strongMatchDistanceCutoff- }- />- ))}- </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>- )}- </div>- )-}diff --git a/products/replay_vision/frontend/search/SearchResults.tsx b/products/replay_vision/frontend/search/SearchResults.tsxnew file mode 100644index 000000000000..86ea10c457ee--- /dev/null+++ b/products/replay_vision/frontend/search/SearchResults.tsx@@ -0,0 +1,372 @@+import clsx from 'clsx'+import { useActions, useValues } from 'kea'+import { combineUrl, router } from 'kea-router'++import { IconGridMasonry, IconList, IconPlayFilled } from '@posthog/icons'+import { LemonCard, LemonSegmentedButton, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { PaginationControl } from 'lib/lemon-ui/PaginationControl'+import { colonDelimitedDuration } from 'lib/utils/durations'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import { ObservationResultSummary } from '../components/ObservationCard'+import { ObservationThumbnail } from '../components/ObservationThumbnail'+import { ScannerOutputBadge } from '../components/ScannerOutputBadge'+import { TimestampCitation } from '../components/TimestampCitation'+import type { ObservationSearchResultApi, ReplayObservationApi } from '../generated/api.schemas'+import { observationDetailUrl } from '../observations/replayObservationLogic'+import { parseCitedSegments } from '../utils/citations'+import { hasScannerPage, scannerLabel } from '../utils/observation'+import { firstCitedTimestampMs, searchReturnParams } from './observationQueries'+import {+ type ObservationSearchLogicProps,+ type ResultsView,+ SEARCH_PAGE_SIZE,+ observationSearchLogic,+} from './observationSearchLogic'+import { snippetSegments } from './snippetSegments'++// The global SessionPlayerModal opens from the hash and seeks from `t`.+function watchMomentUrl(+ observation: ReplayObservationApi,+ citedMs: number | null,+ { location, searchParams, hashParams }: typeof router.values+): string {+ return combineUrl(+ location.pathname,+ { ...searchParams, t: citedMs !== null ? Math.floor(citedMs / 1000) : undefined },+ { ...hashParams, sessionRecordingId: observation.session_id }+ ).url+}++type Tier = 'top' | 'other'+type TierGroup = { tier: Tier | null; results: ObservationSearchResultApi[] }++interface ResultProps {+ result: ObservationSearchResultApi+ searchedQuery: string+ returnParams: Record<string, string>+}++function WatchLink({ observation, compact }: { observation: ReplayObservationApi; compact?: boolean }): JSX.Element {+ const routerValues = useValues(router)+ const citedMs = firstCitedTimestampMs(observation)+ return (+ <Link+ to={watchMomentUrl(observation, citedMs, routerValues)}+ className={clsx('relative block text-primary group', compact && 'w-28')}+ data-attr="vision-search-result-watch"+ >+ {/* The card clips its own corners and draws its own edge, so the poster goes edge to edge there. */}+ <ObservationThumbnail observation={observation} className={clsx(!compact && 'rounded-none border-0')}>+ {/* A fixed dark scrim, not a theme surface: the chip sits on a frame of any colour, white included. */}+ <span+ className={clsx(+ 'rounded-full bg-black/60 text-white flex items-center justify-center group-hover:bg-black/80',+ compact ? 'size-6 text-sm' : 'size-10 text-lg'+ )}+ >+ <IconPlayFilled />+ </span>+ </ObservationThumbnail>+ {!compact && (+ <span className="absolute bottom-2 right-2 text-xs font-medium px-1.5 py-0.5 rounded bg-surface-primary border border-primary">+ {citedMs !== null+ ? `Watch at ${colonDelimitedDuration(Math.floor(citedMs / 1000), null)}`+ : 'Watch recording'}+ </span>+ )}+ </Link>+ )+}++function ScannerName({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ return hasScannerPage(observation) ? (+ <Link+ to={urls.replayVision(observation.scanner_id)}+ className="font-semibold text-sm truncate text-primary"+ data-attr="vision-search-result-scanner"+ >+ {scannerLabel(observation)}+ </Link>+ ) : (+ <span className="font-semibold text-sm truncate">{scannerLabel(observation)}</span>+ )+}++function MatchSnippet({+ result,+ searchedQuery,+}: {+ result: ObservationSearchResultApi+ searchedQuery: string+}): JSX.Element | null {+ const snippet = parseCitedSegments(result.matched_content, undefined)+ if (snippet.length === 0) {+ return null+ }+ return (+ <div className="text-sm text-secondary line-clamp-2">+ {snippet.map((cited, citedIndex) =>+ cited.kind === 'chip' ? (+ <TimestampCitation key={citedIndex} timestampMs={cited.timestamp_ms} />+ ) : (+ snippetSegments(cited.value, searchedQuery).map((segment, index) => (+ <span+ key={`${citedIndex}-${index}`}+ className={segment.highlighted ? 'font-semibold' : undefined}+ >+ {segment.text}+ </span>+ ))+ )+ )}+ </div>+ )+}++function SubjectLink({ observation }: { observation: ReplayObservationApi }): JSX.Element {+ const email = observation.recording_subject_email+ const subjectClass = clsx('text-xs truncate', !email && 'font-mono')+ return observation.distinct_id ? (+ <Link+ to={urls.personByDistinctId(observation.distinct_id)}+ className={clsx(subjectClass, 'text-primary')}+ data-attr="vision-search-result-person"+ >+ {email ?? observation.distinct_id}+ </Link>+ ) : (+ <span className={clsx(subjectClass, 'text-muted')}>{email ?? observation.session_id}</span>+ )+}++function TopMatchTag(): JSX.Element {+ return (+ <LemonTag type="success" size="small">+ Top match+ </LemonTag>+ )+}++function MomentCard({ result, searchedQuery, returnParams, tier }: ResultProps & { tier: Tier | null }): JSX.Element {+ const observation = result.observation+ const snapshot = observation.scanner_snapshot+ return (+ <LemonCard className="flex flex-col rounded-lg p-0 overflow-hidden" data-attr="vision-search-result">+ <div className="relative">+ <WatchLink observation={observation} />+ <span className="absolute top-2 left-2 flex items-center gap-1">+ {snapshot && <ScannerOutputBadge scannerType={snapshot.scanner_type} size="small" />}+ {tier === 'top' && <TopMatchTag />}+ </span>+ </div>+ <div className="flex flex-col gap-1.5 p-3 min-w-0">+ <div className="flex items-center gap-2 min-w-0">+ <ScannerName observation={observation} />+ <span className="ml-auto shrink-0 text-xs text-muted">+ <TZLabel time={observation.created_at} />+ </span>+ </div>+ <MatchSnippet result={result} searchedQuery={searchedQuery} />+ <ObservationResultSummary observation={observation} />+ <div className="flex items-center gap-2 min-w-0 text-xs">+ <SubjectLink observation={observation} />+ <Link+ to={observationDetailUrl(observation.id, returnParams)}+ className="ml-auto shrink-0"+ data-attr="vision-search-result-detail"+ >+ Details+ </Link>+ </div>+ </div>+ </LemonCard>+ )+}++function MomentRow({ result, searchedQuery, returnParams }: ResultProps): JSX.Element {+ const observation = result.observation+ const snapshot = observation.scanner_snapshot+ return (+ <LemonCard className="flex gap-3 rounded-lg p-2 min-w-0" data-attr="vision-search-result">+ <div className="shrink-0 self-center">+ <WatchLink observation={observation} compact />+ </div>+ <div className="flex flex-col gap-1 min-w-0 flex-1">+ <div className="flex items-center gap-2 min-w-0">+ <ScannerName observation={observation} />+ {snapshot && <ScannerOutputBadge scannerType={snapshot.scanner_type} size="small" />}+ <SubjectLink observation={observation} />+ <span className="ml-auto shrink-0 flex items-center gap-2 text-xs text-muted">+ <TZLabel time={observation.created_at} />+ <Link+ to={observationDetailUrl(observation.id, returnParams)}+ data-attr="vision-search-result-detail"+ >+ Details+ </Link>+ </span>+ </div>+ <MatchSnippet result={result} searchedQuery={searchedQuery} />+ <ObservationResultSummary observation={observation} />+ </div>+ </LemonCard>+ )+}++function TierHeading({ tier }: { tier: Tier }): JSX.Element {+ return (+ <div className="flex items-baseline gap-2 px-3 py-1.5 rounded border border-primary bg-surface-tertiary dark:bg-surface-secondary text-xs">+ <span className="font-semibold">{tier === 'top' ? 'Top matches' : 'Other matches'}</span>+ <span className="text-muted">+ {tier === 'top' ? 'Closest to what you described.' : 'Related, but further from what you described.'}+ </span>+ </div>+ )+}++function tierGroups(+ results: ObservationSearchResultApi[],+ tierOf: (result: ObservationSearchResultApi) => Tier | null+): TierGroup[] {+ const groups: TierGroup[] = []+ for (const result of results) {+ const tier = tierOf(result)+ const last = groups[groups.length - 1]+ if (last && last.tier === tier) {+ last.results.push(result)+ } else {+ groups.push({ tier, results: [result] })+ }+ }+ return groups+}++function ResultsSkeleton({ view }: { view: ResultsView }): JSX.Element {+ const lines = (+ <div className="flex flex-col gap-1.5 min-w-0 flex-1">+ <LemonSkeleton className="h-4 w-1/3" />+ <LemonSkeleton className="h-3 w-full" />+ <LemonSkeleton className="h-3 w-2/3" />+ </div>+ )+ return view === 'grid' ? (+ <div className="grid gap-3 grid-cols-1 @xl:grid-cols-2 @3xl:grid-cols-3" aria-busy>+ {Array.from({ length: 6 }, (_, index) => (+ <div key={index} className="flex flex-col border border-primary rounded-lg overflow-hidden">+ <LemonSkeleton className="aspect-video w-full rounded-none" />+ <div className="p-3">{lines}</div>+ </div>+ ))}+ </div>+ ) : (+ <div className="flex flex-col gap-2" aria-busy>+ {Array.from({ length: 5 }, (_, index) => (+ <div key={index} className="flex items-center gap-3 border border-primary rounded-lg p-2">+ <LemonSkeleton className="w-28 aspect-video shrink-0" />+ {lines}+ </div>+ ))}+ </div>+ )+}++export function SearchResults(logicProps: ObservationSearchLogicProps): JSX.Element | null {+ const logic = observationSearchLogic(logicProps)+ const {+ results,+ searching,+ searchedQuery,+ scannerId,+ sourceObservationId,+ truncated,+ topMatchDistanceCutoff,+ view,+ page,+ pageCount,+ pageResults,+ pageStartIndex,+ pageEndIndex,+ } = useValues(logic)+ const { setPage, setView } = useActions(logic)++ if (!searching && (!results || results.length === 0)) {+ return null+ }+ const returnParams = searchReturnParams(searchedQuery ?? '', scannerId, sourceObservationId)+ const tierOf = (result: ObservationSearchResultApi): Tier | null =>+ topMatchDistanceCutoff === null ? null : result.distance <= topMatchDistanceCutoff ? 'top' : 'other'+ return (+ <div className="flex flex-col">+ <div className="flex items-center gap-2 mb-1">+ <span className="text-xs text-secondary">+ {searching || !results+ ? 'Searching…'+ : `${truncated ? 'Showing the top ' : ''}${pluralize(results.length, 'match', 'matches')}, best first`}+ </span>+ <LemonSegmentedButton<ResultsView>+ size="xsmall"+ className="ml-auto"+ value={view}+ onChange={setView}+ options={[+ {+ value: 'grid',+ icon: <IconGridMasonry />,+ tooltip: 'Thumbnails',+ 'data-attr': 'vision-search-view-grid',+ },+ { value: 'list', icon: <IconList />, tooltip: 'List', 'data-attr': 'vision-search-view-list' },+ ]}+ />+ </div>+ <div className="flex flex-col gap-3">+ {searching || !results ? (+ <ResultsSkeleton view={view} />+ ) : view === 'grid' ? (+ <div className="grid gap-3 grid-cols-1 @xl:grid-cols-2 @3xl:grid-cols-3">+ {pageResults.map((result) => (+ <MomentCard+ key={result.observation.id}+ result={result}+ searchedQuery={searchedQuery ?? ''}+ returnParams={returnParams}+ tier={tierOf(result)}+ />+ ))}+ </div>+ ) : (+ tierGroups(pageResults, tierOf).map((group) => (+ <div key={group.tier ?? 'all'} className="flex flex-col gap-2">+ {group.tier && <TierHeading tier={group.tier} />}+ {group.results.map((result) => (+ <MomentRow+ key={result.observation.id}+ result={result}+ searchedQuery={searchedQuery ?? ''}+ returnParams={returnParams}+ />+ ))}+ </div>+ ))+ )}+ {!searching && results && (+ <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>+ </div>+ )+}diff --git a/products/replay_vision/frontend/search/observationQueries.test.ts b/products/replay_vision/frontend/search/observationQueries.test.tsnew file mode 100644index 000000000000..3e2d80666e7e--- /dev/null+++ b/products/replay_vision/frontend/search/observationQueries.test.ts@@ -0,0 +1,63 @@+import { userLogic } from 'scenes/userLogic'++import { initKeaTests } from '~/test/init'++import type { ReplayObservationApi } from '../generated/api.schemas'+import {+ firstCitedTimestampMs,+ markSimilarSearchIntent,+ readSimilarSearchIntent,+ similarSearchQuery,+ similarSearchUrl,+} from './observationQueries'++function observation(modelOutput: Record<string, unknown> | null): ReplayObservationApi {+ return {+ id: 'obs-1',+ session_id: 'session-1',+ scanner_result: modelOutput ? { model_output: modelOutput } : null,+ } as unknown as ReplayObservationApi+}++describe('observationQueries', () => {+ beforeEach(() => {+ initKeaTests()+ userLogic.mount()+ })++ it.each([+ ['a summary citation, ahead of the reasoning', { summary: 'a (t 12)', reasoning: 'c (t 5)' }, 12000],+ ['a reasoning citation when the summary has none', { summary: 'plain', reasoning: 'c (t 5)' }, 5000],+ ['nothing when nothing is cited', { summary: 'plain' }, null],+ ])('cites %s', (_name, modelOutput, expected) => {+ expect(firstCitedTimestampMs(observation(modelOutput))).toBe(expected)+ })++ it.each([+ [+ 'drops citations and collapses the gap',+ { summary: 'User rage clicked (t 12) the button' },+ 'User rage clicked the button',+ ],+ ['falls back to the reasoning', { reasoning: 'Hesitated on pricing' }, 'Hesitated on pricing'],+ ['gives null when there is no prose', { summary: ' ' }, null],+ ])('%s', (_name, modelOutput, expected) => {+ expect(similarSearchQuery(observation(modelOutput))).toBe(expected)+ })++ it('cuts a long summary at a word boundary', () => {+ const query = similarSearchQuery(observation({ summary: `${'word '.repeat(80)}tail` }))+ expect(query!.length).toBeLessThanOrEqual(300)+ expect(query!.endsWith('word')).toBe(true)+ })++ it('hands the prose off to the one navigation that armed it, never through the URL', () => {+ const source = observation({ summary: 'stuck at checkout' })+ expect(similarSearchUrl(source)).toBe('/replay-vision?tab=search&similar=obs-1')++ markSimilarSearchIntent(source)+ expect(readSimilarSearchIntent('another-observation')).toBeNull()+ expect(readSimilarSearchIntent('obs-1')).toBe('stuck at checkout')+ expect(readSimilarSearchIntent('obs-1')).toBe('stuck at checkout')+ })+})diff --git a/products/replay_vision/frontend/search/observationQueries.ts b/products/replay_vision/frontend/search/observationQueries.tsnew file mode 100644index 000000000000..7f399782e4a7--- /dev/null+++ b/products/replay_vision/frontend/search/observationQueries.ts@@ -0,0 +1,119 @@+import { combineUrl } from 'kea-router'++import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import { Breadcrumb } from '~/types'++import type { ReplayObservationApi } from '../generated/api.schemas'+import { ReplayScannerTab } from '../replay_scanners/replayScannerSceneLogic'+import { parseCitedSegments, stripCitations } from '../utils/citations'+import { readModelOutput, readTitle } from '../utils/observation'++const SIMILAR_QUERY_MAX_CHARS = 300++export function firstCitedTimestampMs(observation: ReplayObservationApi): number | null {+ const result = readModelOutput(observation)+ if (!result) {+ return null+ }+ for (const [textKey, segmentsKey] of [+ ['summary', 'summary_segments'],+ ['reasoning', 'reasoning_segments'],+ ] as const) {+ const text = result[textKey]+ if (typeof text !== 'string') {+ continue+ }+ const chip = parseCitedSegments(text, result[segmentsKey]).find((segment) => segment.kind === 'chip')+ if (chip && chip.kind === 'chip' && chip.timestamp_ms >= 0) {+ return chip.timestamp_ms+ }+ }+ return null+}++export function similarSearchQuery(observation: ReplayObservationApi): string | null {+ const result = readModelOutput(observation)+ if (!result) {+ return null+ }+ const summary = typeof result.summary === 'string' ? stripCitations(result.summary, result.summary_segments) : ''+ const reasoning =+ typeof result.reasoning === 'string' ? stripCitations(result.reasoning, result.reasoning_segments) : ''+ const text = [readTitle(observation), summary || reasoning].filter(Boolean).join(' ')+ if (!text) {+ return null+ }+ if (text.length <= SIMILAR_QUERY_MAX_CHARS) {+ return text+ }+ const cut = text.slice(0, SIMILAR_QUERY_MAX_CHARS)+ const lastSpace = cut.lastIndexOf(' ')+ // A cut inside a surrogate pair would make encodeURIComponent throw.+ return (lastSpace > 0 ? cut.slice(0, lastSpace) : cut.replace(/[\uD800-\uDBFF]$/, '')).trim()+}++export function searchTabUrl(params: Record<string, string> = {}): string {+ return combineUrl(urls.replayVision(), { tab: ReplayScannerTab.Search, ...params }).url+}++export function searchReturnParams(+ searchedQuery: string,+ scannerId: string | null,+ sourceObservationId: string | null+): Record<string, string> {+ return {+ tab: ReplayScannerTab.Search,+ ...(scannerId ? { scanner: scannerId } : {}),+ ...(sourceObservationId ? { similar: sourceObservationId } : searchedQuery ? { q: searchedQuery } : {}),+ }+}++export function searchBreadcrumb(returnParams: Record<string, string>): Breadcrumb {+ const { tab: _tab, ...params } = returnParams+ return { key: 'search', name: 'Search', path: searchTabUrl(params) }+}++const SIMILAR_SEARCH_INTENT_KEY = 'replay-vision.similar-search-intent'++// Both logics are mounted app-wide. `values` throws if not, where `findMounted` would silently mismatch owners.+function intentOwner(): string {+ return `${userLogic.values.user?.uuid ?? ''}:${teamLogic.values.currentTeamId ?? ''}`+}++/** The query travels through sessionStorage, not the URL: it is observation prose that can carry customer+ * names, so it must stay out of $current_url and browser history. It is bound to the user who armed it. */+export function similarSearchUrl(observation: ReplayObservationApi): string | null {+ return similarSearchQuery(observation) ? searchTabUrl({ similar: observation.id }) : null+}++export function markSimilarSearchIntent(observation: ReplayObservationApi): void {+ try {+ sessionStorage.setItem(+ SIMILAR_SEARCH_INTENT_KEY,+ JSON.stringify({+ query: similarSearchQuery(observation),+ sourceObservationId: observation.id,+ owner: intentOwner(),+ })+ )+ } catch {+ // No storage: the hub opens on its empty state.+ }+}++export function readSimilarSearchIntent(sourceObservationId: string): string | null {+ try {+ const raw = sessionStorage.getItem(SIMILAR_SEARCH_INTENT_KEY)+ const parsed = raw ? JSON.parse(raw) : null+ return parsed?.sourceObservationId === sourceObservationId &&+ parsed.owner === intentOwner() &&+ typeof parsed.query === 'string'+ ? parsed.query+ : null+ } catch {+ return null+ }+}diff --git a/products/replay_vision/frontend/search/observationSearchLogic.test.ts b/products/replay_vision/frontend/search/observationSearchLogic.test.tsindex 268366764578..e8936ec45371 100644--- a/products/replay_vision/frontend/search/observationSearchLogic.test.ts+++ b/products/replay_vision/frontend/search/observationSearchLogic.test.ts@@ -4,12 +4,14 @@ import posthog from 'posthog-js'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import type { ObservationSearchResultApi } from '../generated/api.schemas'-import { observationSearchLogic } from './observationSearchLogic'+import type { ObservationSearchResultApi, ReplayObservationApi } from '../generated/api.schemas'+import { markSimilarSearchIntent } from './observationQueries'+import { SEARCH_COALESCE_MS, SEARCH_PAGE_SIZE, observationSearchLogic } from './observationSearchLogic'function searchResults(distances: number[]): ObservationSearchResultApi[] {return distances.map(@@ -28,6 +30,7 @@ describe('observationSearchLogic', () => {beforeEach(() => {localStorage.clear()+ sessionStorage.clear()searchSpy = jest.fn(() => [200, { results: [{ observation: { id: 'obs-1' }, distance: 0.1 }] }])suggestionsSpy = jest.fn(() => [200, { queries: ['coupon rejected at checkout'] }])viewedSpy = jest.fn(() => [204, null])@@ -41,52 +44,63 @@ describe('observationSearchLogic', () => {},})initKeaTests()+ userLogic.mount()})it.each([- ['a scanner-scoped', 'scanner-1', 'scanner-1'],- ['a cross-scanner', null, null],- ])('%s search sends the right scope and stores ranked results', async (_name, scannerId, expectedScope) => {- const logic = observationSearchLogic({ scannerId, teamId: 1, userId: 'user-1' })+ ['one scanner', 'scanner-1'],+ ['all scanners', null],+ ])('searching %s sends the scope from the URL and stores ranked results', async (_name, scannerId) => {+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()- // On the live page URL, the actionToUrl echo would re-dispatch search without the in-flight guard.- router.actions.push(scannerId ? urls.replayVision(scannerId) : urls.replayVision(), { tab: 'search' })+ router.actions.push(urls.replayVision(), { tab: 'search', scanner: scannerId ?? undefined })logic.actions.setQuery('confused users')await expectLogic(logic, () => logic.actions.search()).toFinishAllListeners()expect(searchSpy).toHaveBeenCalledTimes(1)const requestUrl = new URL(searchSpy.mock.calls[0][0].request.url)expect(requestUrl.searchParams.get('q')).toBe('confused users')- expect(requestUrl.searchParams.get('scanner_id')).toBe(expectedScope)+ expect(requestUrl.searchParams.get('scanner_id')).toBe(scannerId)expect(logic.values.results?.map((r) => r.observation.id)).toEqual(['obs-1'])+ expect(router.values.searchParams.q).toBe('confused users')+ expect(router.values.searchParams.scanner).toBe(scannerId ?? undefined)++ await expectLogic(logic, () => logic.actions.setScannerId('scanner-2')).toFinishAllListeners()+ expect(searchSpy).toHaveBeenCalledTimes(2)+ expect(new URL(searchSpy.mock.calls[1][0].request.url).searchParams.get('scanner_id')).toBe('scanner-2')++ router.actions.push(urls.replayVision(), { tab: 'search', scanner: 'scanner-3', q: 'rage clicks' })+ await expectLogic(logic).toFinishAllListeners()+ expect(searchSpy).toHaveBeenCalledTimes(3)+ const lastRequest = new URL(searchSpy.mock.calls[2][0].request.url).searchParams+ expect([lastRequest.get('scanner_id'), lastRequest.get('q')]).toEqual(['scanner-3', 'rage clicks'])logic.unmount()})it.each([- ['spread distances tag the top tier', [0.1, 0.12, 0.4], expect.closeTo(0.15)],- ['clustered distances tag nothing', [0.1, 0.12, 0.14], null],- ['a single result tags nothing', [0.2], null],+ ['spread distances split off a top tier', [0.1, 0.12, 0.4], expect.closeTo(0.15)],+ ['clustered distances stay one tier', [0.1, 0.12, 0.14], null],])('%s', (_name, distances, expectedCutoff) => {- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()logic.actions.searchSuccess(searchResults(distances), 'query', false)- expect(logic.values.strongMatchDistanceCutoff).toEqual(expectedCutoff)+ expect(logic.values.topMatchDistanceCutoff).toEqual(expectedCutoff)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, []],+ ['a full page plus one leaves a single result on page 2', SEARCH_PAGE_SIZE + 1, 2, [`obs-${SEARCH_PAGE_SIZE}`]],+ ['an exact page fill has no second page', SEARCH_PAGE_SIZE, 1, []],])('%s', async (_name, resultCount, expectedPageCount, expectedSecondPageIds) => {- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ 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))+ expect(logic.values.pageResults).toHaveLength(Math.min(resultCount, SEARCH_PAGE_SIZE))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.@@ -95,7 +109,7 @@ describe('observationSearchLogic', () => {})it('a blank query never reaches the API', async () => {- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()logic.actions.setQuery(' ')await expectLogic(logic, () => logic.actions.search()).toFinishAllListeners()@@ -106,7 +120,7 @@ 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' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()router.actions.push(urls.replayVision(), {tab: 'search',@@ -125,7 +139,7 @@ describe('observationSearchLogic', () => {})it('a query with trailing whitespace searches once, despite the trimmed actionToUrl echo', async () => {- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()router.actions.push(urls.replayVision(), { tab: 'search' })logic.actions.setQuery('rage clicks ')@@ -137,7 +151,7 @@ describe('observationSearchLogic', () => {it('a failed deep-linked search does not re-fire on unrelated URL changes', async () => {searchSpy.mockImplementation(() => [500, { detail: 'embedding service down' }])- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()router.actions.push(urls.replayVision(), {tab: 'search',@@ -164,7 +178,7 @@ describe('observationSearchLogic', () => {searchSpy.mockImplementation(mockResponse as () => any)}const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()router.actions.push(urls.replayVision(), { tab: 'search' })logic.actions.setQuery('rage clicks')@@ -179,18 +193,25 @@ describe('observationSearchLogic', () => {})it('a superseded failure is dropped, so the rate counts only the searches a person waited for', async () => {+ let releaseFirst: () => void = () => {}+ const firstHeld = new Promise<void>((resolve) => (releaseFirst = resolve))+ searchSpy.mockImplementationOnce(async () => {+ await firstHeld+ return [500, { detail: 'embedding service down' }]+ })searchSpy.mockImplementation(() => [500, { detail: 'embedding service down' }])const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()router.actions.push(urls.replayVision(), { tab: 'search' })logic.actions.setQuery('rage clicks')logic.actions.search()- // The second search starts while the first request is in flight, which supersedes the first.+ await new Promise((resolve) => setTimeout(resolve, SEARCH_COALESCE_MS + 1))logic.actions.setQuery('coupon rejected at checkout')logic.actions.search()+ releaseFirst()await expectLogic(logic).toFinishAllListeners()expect(searchSpy).toHaveBeenCalledTimes(2)@@ -208,7 +229,7 @@ describe('observationSearchLogic', () => {it('an AI consent error points the user at the organization setting', async () => {searchSpy.mockImplementation(() => [400, { code: 'ai_data_processing_not_approved', detail: 'off' }])const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()router.actions.push(urls.replayVision(), { tab: 'search' })logic.actions.setQuery('anything')@@ -221,32 +242,36 @@ describe('observationSearchLogic', () => {logic.unmount()})- it('loads suggestions for the scope on mount', async () => {- const logic = observationSearchLogic({ scannerId: 'scanner-1', teamId: 1, userId: 'user-1' })+ it('loads suggestions for the scope, and a deep link into a scope records one view, not two', async () => {+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()+ router.actions.push(urls.replayVision(), { tab: 'search', scanner: 'scanner-1' })await expectLogic(logic).toFinishAllListeners()expect(suggestionsSpy).toHaveBeenCalledTimes(1)expect(new URL(suggestionsSpy.mock.calls[0][0].request.url).searchParams.get('scanner_id')).toBe('scanner-1')expect(logic.values.suggestedQueries).toEqual(['coupon rejected at checkout'])- // The view is recorded through a POST, so the read itself has no side effect.expect(viewedSpy).toHaveBeenCalledTimes(1)expect(await viewedSpy.mock.calls[0][0].request.json()).toEqual({ scanner_id: 'scanner-1' })++ await expectLogic(logic, () => logic.actions.setScannerId(null)).toFinishAllListeners()+ expect(suggestionsSpy).toHaveBeenCalledTimes(2)+ expect(new URL(suggestionsSpy.mock.calls[1][0].request.url).searchParams.get('scanner_id')).toBeNull()logic.unmount()})it('remembers queries that found something, newest first, without duplicates, capped', async () => {- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()for (const query of ['one', 'two', 'three', 'four', 'five', 'six', 'two']) {logic.actions.searchSuccess(searchResults([0.2]), query, false)}logic.actions.searchSuccess([], 'nothing', false)- expect(logic.values.recentQueries).toEqual(['two', 'six', 'five', 'four', 'three'])+ expect(logic.values.recentQueries).toEqual(['two', 'six', 'five'])logic.unmount()})it('emptying the input returns to the empty state and drops q from the URL', async () => {- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()router.actions.push(urls.replayVision(), { tab: 'search' })logic.actions.setQuery('rage clicks')@@ -260,8 +285,55 @@ describe('observationSearchLogic', () => {logic.unmount()})+ it('a "find similar" hand-off searches without the prose in the URL or recents, minus its source', async () => {+ searchSpy.mockImplementation(() => [+ 200,+ {+ results: [+ { observation: { id: 'obs-0' }, distance: 0 },+ { observation: { id: 'obs-1' }, distance: 0.2 },+ ],+ },+ ])+ markSimilarSearchIntent({+ id: 'obs-0',+ scanner_result: { model_output: { summary: 'Stalled at checkout' } },+ } as unknown as ReplayObservationApi)+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })+ logic.mount()+ router.actions.push(urls.replayVision(), { tab: 'search', similar: 'obs-0', scanner: 'scanner-2' })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.results?.map((r) => r.observation.id)).toEqual(['obs-1'])+ expect(router.values.searchParams.q).toBeUndefined()+ expect(logic.values.recentQueries).toEqual([])+ expect(searchSpy).toHaveBeenCalledTimes(1)+ expect(new URL(searchSpy.mock.calls[0][0].request.url).searchParams.get('scanner_id')).toBe('scanner-2')++ // Editing the prose keeps the shown results' provenance until the edited search lands as a regular one.+ logic.actions.setQuery('Stalled at checkout twice')+ expect(logic.values.sourceObservationId).toBe('obs-0')+ router.actions.push(urls.replayVision(), { tab: 'search', similar: 'obs-0', scanner: 'scanner-2', t: 12 })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.query).toBe('Stalled at checkout twice')+ expect(searchSpy).toHaveBeenCalledTimes(1)++ await expectLogic(logic, () => logic.actions.search()).toFinishAllListeners()+ expect(logic.values.sourceObservationId).toBeNull()+ expect(router.values.searchParams.q).toBe('Stalled at checkout twice')+ expect(logic.values.recentQueries).toEqual(['Stalled at checkout twice'])++ router.actions.push(urls.replayVision(), { tab: 'search', similar: 'obs-9', scanner: 'scanner-2' })+ await expectLogic(logic).toFinishAllListeners()+ expect(router.values.searchParams.similar).toBeUndefined()+ expect(router.values.searchParams.q).toBeUndefined()+ expect(logic.values.results).toBeNull()+ expect(searchSpy).toHaveBeenCalledTimes(2)+ logic.unmount()+ })+it('a URL without q after a search shows the empty state instead of the old results', async () => {- const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })logic.mount()router.actions.push(urls.replayVision(), { tab: 'search', q: 'rage clicks' })await expectLogic(logic).toFinishAllListeners()diff --git a/products/replay_vision/frontend/search/observationSearchLogic.ts b/products/replay_vision/frontend/search/observationSearchLogic.tsindex 8a1fc8e5dfe3..41a5e7276c84 100644--- a/products/replay_vision/frontend/search/observationSearchLogic.ts+++ b/products/replay_vision/frontend/search/observationSearchLogic.ts@@ -26,23 +26,25 @@ import {} from '../generated/api'import type { ObservationSearchResultApi } from '../generated/api.schemas'import { ReplayScannerTab } from '../replay_scanners/replayScannerSceneLogic'+import { readSimilarSearchIntent } from './observationQueries'// 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+export const SEARCH_PAGE_SIZE = 9// Relative to the best match, because distances are only comparable within one response.-const STRONG_MATCH_MARGIN = 0.05+const TOP_MATCH_MARGIN = 0.05// The server's error code when the organization has not allowed AI data processing.const AI_CONSENT_REQUIRED_CODE = 'ai_data_processing_not_approved'-// Enough to recall a working phrasing, few enough to stay a single row of chips.-const RECENT_QUERIES_LIMIT = 5+const RECENT_QUERIES_LIMIT = 3+// One URL change can dispatch the same action twice. A short breakpoint collapses them into one request.+export const SEARCH_COALESCE_MS = 10++export type ResultsView = 'grid' | 'list'export interface ObservationSearchLogicProps {- /** Scope the search to one scanner. Null searches every scanner the user can read. */- scannerId: string | null/** Keys the persisted recent searches, so one project's queries never show in another. */teamId: number | null/** Also keys the persisted recent searches, so another account on this browser starts empty. */@@ -56,15 +58,19 @@ export interface observationSearchLogicValues {pageEndIndex: numberpageResults: ObservationSearchResultApi[]pageStartIndex: number+ pendingSourceObservationId: string | nullquery: stringrecentQueries: string[]results: ObservationSearchResultApi[] | null+ scannerId: string | nullsearchedQuery: string | nullsearching: boolean- strongMatchDistanceCutoff: number | null+ sourceObservationId: string | nullsuggestedQueries: string[]suggestedQueriesLoading: boolean+ topMatchDistanceCutoff: number | nulltruncated: boolean+ view: ResultsView}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -72,7 +78,7 @@ export interface observationSearchLogicActions {clearSearch: () => {value: true}- loadSuggestedQueries: () => any+ loadSuggestedQueries: (_: void) => voidloadSuggestedQueriesFailure: (error: string,errorObject?: any@@ -82,10 +88,10 @@ export interface observationSearchLogicActions {}loadSuggestedQueriesSuccess: (suggestedQueries: string[],- payload?: any+ payload?: void) => {suggestedQueries: string[]- payload?: any+ payload?: void}search: () => {value: true@@ -93,13 +99,22 @@ export interface observationSearchLogicActions {searchFailure: () => {value: true}+ searchSimilar: (+ query: string,+ sourceObservationId: string+ ) => {+ query: string+ sourceObservationId: string+ }searchSuccess: (results: ObservationSearchResultApi[],query: string,- truncated: boolean+ truncated: boolean,+ sourceObservationId?: string | null) => {query: stringresults: ObservationSearchResultApi[]+ sourceObservationId: string | nulltruncated: boolean}setPage: (page: number) => {@@ -108,6 +123,12 @@ export interface observationSearchLogicActions {setQuery: (query: string) => {query: string}+ setScannerId: (scannerId: string | null) => {+ scannerId: string | null+ }+ setView: (view: ResultsView) => {+ view: ResultsView+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -118,7 +139,7 @@ export interface observationSearchLogicMeta {pageResults: (results: ObservationSearchResultApi[] | null, page: number) => ObservationSearchResultApi[]pageStartIndex: (page: number) => numberpageEndIndex: (pageStartIndex: number, pageResults: ObservationSearchResultApi[]) => number- strongMatchDistanceCutoff: (results: ObservationSearchResultApi[] | null) => number | null+ topMatchDistanceCutoff: (results: ObservationSearchResultApi[] | null) => number | null}}@@ -144,16 +165,25 @@ function captureSearchOutcome(export const observationSearchLogic = kea<observationSearchLogicType>([path(['products', 'replay_vision', 'frontend', 'search', 'observationSearchLogic']),props({} as ObservationSearchLogicProps),- key((props) => `${props.userId ?? 'user'}:${props.teamId ?? 'team'}:${props.scannerId ?? 'cross-scanner'}`),+ key((props) => `${props.userId ?? 'user'}:${props.teamId ?? 'team'}`),actions({setQuery: (query: string) => ({ query }),+ setScannerId: (scannerId: string | null) => ({ scannerId }),setPage: (page: number) => ({ page }),+ setView: (view: ResultsView) => ({ view }),search: true,- searchSuccess: (results: ObservationSearchResultApi[], query: string, truncated: boolean) => ({+ searchSimilar: (query: string, sourceObservationId: string) => ({ query, sourceObservationId }),+ searchSuccess: (+ results: ObservationSearchResultApi[],+ query: string,+ truncated: boolean,+ sourceObservationId: string | null = null+ ) => ({results,query,truncated,+ sourceObservationId,}),searchFailure: true,clearSearch: true,@@ -164,9 +194,33 @@ export const observationSearchLogic = kea<observationSearchLogicType>(['' as string,{setQuery: (_, { query }) => query,+ searchSimilar: (_, { query }) => query,clearSearch: () => '',},],+ scannerId: [+ null as string | null,+ {+ setScannerId: (_, { scannerId }) => scannerId,+ },+ ],+ // Provenance of the next search. Editing the prose makes it a regular search.+ pendingSourceObservationId: [+ null as string | null,+ {+ searchSimilar: (_, { sourceObservationId }) => sourceObservationId,+ setQuery: () => null,+ clearSearch: () => null,+ },+ ],+ // Provenance of the displayed results, so their links keep the prose out of the URL until a new search lands.+ sourceObservationId: [+ null as string | null,+ {+ searchSuccess: (_, { sourceObservationId }) => sourceObservationId,+ clearSearch: () => null,+ },+ ],// null until the first search, so the empty state can tell "not searched yet" from "no matches".results: [null as ObservationSearchResultApi[] | null,@@ -181,6 +235,7 @@ export const observationSearchLogic = kea<observationSearchLogicType>([search: () => true,searchSuccess: () => false,searchFailure: () => false,+ clearSearch: () => false,},],searchedQuery: [@@ -190,13 +245,12 @@ export const observationSearchLogic = kea<observationSearchLogicType>([clearSearch: () => null,},],- // Per search scope, in this browser only: a cheap way back to a phrasing that found something.recentQueries: [[] as string[],{ persist: true },{- searchSuccess: (state, { query, results }) =>- results.length > 0+ searchSuccess: (state, { query, results, sourceObservationId }) =>+ sourceObservationId === null && results.length > 0? [query, ...state.filter((recent) => recent !== query)].slice(0, RECENT_QUERIES_LIMIT): state,},@@ -208,6 +262,13 @@ export const observationSearchLogic = kea<observationSearchLogicType>([searchSuccess: () => 1,},],+ view: [+ 'grid' as ResultsView,+ { persist: true },+ {+ setView: (_, { view }) => view,+ },+ ],// The server cut the response to `limit`, so the results are a top slice, not everything that matched.truncated: [false,@@ -218,17 +279,18 @@ export const observationSearchLogic = kea<observationSearchLogicType>([],}),- loaders(({ props }) => ({+ loaders(({ values }) => ({suggestedQueries: [[] as string[],{- loadSuggestedQueries: async () => {+ loadSuggestedQueries: async (_: void, breakpoint) => {+ await breakpoint(SEARCH_COALESCE_MS)const teamId = teamLogic.values.currentTeamId// A deep-linked query renders results, never the empty state, so its suggestions would go unseen.if (!teamId || router.values.searchParams.q) {return []}- const scope = props.scannerId ? { scanner_id: props.scannerId } : undefined+ const scope = values.scannerId ? { scanner_id: values.scannerId } : undefined// The view is what keeps a scanner's suggestions refreshing; it is a separate POST so the read// stays side-effect free, and nothing here waits on it.void visionObservationsSearchViewedCreate(String(teamId), scope).catch(() => undefined)@@ -261,27 +323,35 @@ export const observationSearchLogic = kea<observationSearchLogicType>([(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: [+ // Null when the tiers would not separate anything, so a lone tier is never labeled.+ topMatchDistanceCutoff: [(s) => [s.results],(results: ObservationSearchResultApi[] | null): number | null => {if (!results || results.length < 2) {return null}- const cutoff = Math.min(...results.map((r) => r.distance)) + STRONG_MATCH_MARGIN+ const cutoff = Math.min(...results.map((r) => r.distance)) + TOP_MATCH_MARGINreturn results.some((r) => r.distance > cutoff) ? cutoff : null},],}),- listeners(({ actions, props, values }) => ({+ listeners(({ actions, values }) => ({// Emptying the input (the field's clear button included) is how a person gets back to the empty state.setQuery: ({ query }) => {if (!query.trim() && values.searchedQuery !== null) {actions.clearSearch()}},+ setScannerId: () => {+ actions.loadSuggestedQueries()+ if (values.searchedQuery !== null || values.searching) {+ actions.search()+ }+ },+ searchSimilar: () => actions.search(),search: async (_, breakpoint) => {+ await breakpoint(SEARCH_COALESCE_MS)const query = values.query.trim()if (!query) {actions.searchFailure()@@ -292,17 +362,23 @@ export const observationSearchLogic = kea<observationSearchLogicType>([actions.searchFailure()return}+ const sourceObservationId = values.pendingSourceObservationIdtry {const response = await visionObservationsSearchRetrieve(String(teamId), {q: query,limit: SEARCH_RESULT_LIMIT,- ...(props.scannerId ? { scanner_id: props.scannerId } : {}),+ ...(values.scannerId ? { scanner_id: values.scannerId } : {}),})// Drop out-of-order responses. The newest search owns the results.breakpoint()- const results = response.results ?? []- captureSearchOutcome(props.scannerId, { succeeded: true, result_count: results.length })- actions.searchSuccess(results, query, response.truncated ?? false)+ // The source of a "find similar" search is its own nearest neighbour.+ const results = (response.results ?? []).filter((r) => r.observation.id !== sourceObservationId)+ captureSearchOutcome(values.scannerId, { succeeded: true, result_count: results.length })+ // Cleared while in flight: the late response must not refill the card.+ if (!values.searching) {+ return+ }+ actions.searchSuccess(results, query, response.truncated ?? false, sourceObservationId)} catch (error: any) {if (error instanceof Error && isBreakpoint(error)) {throw error@@ -310,7 +386,7 @@ export const observationSearchLogic = kea<observationSearchLogicType>([// Drop out-of-order failures, like the success path above. A newer search owns the outcome,// so an older failure must not skew the capture, raise a toast, or stop the spinner.breakpoint()- captureSearchOutcome(props.scannerId, {+ captureSearchOutcome(values.scannerId, {succeeded: false,error_status: error?.status,error_code: error?.code,@@ -335,42 +411,66 @@ export const observationSearchLogic = kea<observationSearchLogicType>([actions.loadSuggestedQueries()}),- actionToUrl(({ values }) => ({- search: () => [+ actionToUrl(({ values }) => {+ const withScope = (+ q: string | undefined+ ): [string, Record<string, unknown>, Record<string, unknown>, { replace: boolean }] => [router.values.location.pathname,{...router.values.searchParams,- q: values.query.trim() || undefined,+ q,+ scanner: values.scannerId ?? undefined,+ similar: values.pendingSourceObservationId ?? undefined,},router.values.hashParams,{ replace: true },- ],- clearSearch: () => [- router.values.location.pathname,- { ...router.values.searchParams, q: undefined },- router.values.hashParams,- { replace: true },- ],- })),+ ]+ return {+ // Observation prose stays out of the URL (see markSimilarSearchIntent).+ search: () => withScope(values.pendingSourceObservationId ? undefined : values.query.trim() || undefined),+ clearSearch: () => withScope(undefined),+ setScannerId: () => withScope(router.values.searchParams.q),+ }+ }),- urlToAction(({ actions, props, values }) => ({- [props.scannerId ? urls.replayVision(props.scannerId) : urls.replayVision()]: (_, searchParams) => {- if (searchParams.tab !== ReplayScannerTab.Search) {- return- }- // kea-router decodes ?q=true to a boolean, so stringify instead of dropping it.- const raw = searchParams.q- const q = typeof raw === 'string' ? raw : raw != null ? String(raw) : ''- // Run a deep-linked query once. Comparing against the trimmed input blocks the actionToUrl- // echo of an interactive search, and stops a failed query (which never reaches searchedQuery)- // from re-firing on every unrelated URL change while it still fills the input.- if (q && q !== values.searchedQuery && q !== values.query.trim()) {- actions.setQuery(q)- actions.search()- } else if (!q && values.searchedQuery !== null) {- // The URL lost its query (back navigation, or a tab switch dropped it), so show the empty state.- actions.clearSearch()- }- },- })),+ urlToAction(({ actions, values }) => {+ return {+ [urls.replayVision()]: (_: unknown, searchParams: Record<string, unknown>) => {+ if (searchParams.tab !== ReplayScannerTab.Search) {+ return+ }+ const scanner = typeof searchParams.scanner === 'string' ? searchParams.scanner : null+ if (scanner !== values.scannerId) {+ actions.setScannerId(scanner)+ }+ const similar = typeof searchParams.similar === 'string' ? searchParams.similar : ''+ if (similar) {+ // Result links keep `similar` after typing cleared the pending source, so match the shown source too.+ if (similar === values.pendingSourceObservationId || similar === values.sourceObservationId) {+ return+ }+ const similarQuery = readSimilarSearchIntent(similar)+ if (similarQuery) {+ actions.searchSimilar(similarQuery, similar)+ } else {+ // No stored query: clearing drops the param and the previous results.+ actions.clearSearch()+ }+ return+ }+ // kea-router decodes ?q=true to a boolean, so stringify instead of dropping it.+ const raw = searchParams.q+ const q = typeof raw === 'string' ? raw : raw != null ? String(raw) : ''+ // Run a deep-linked query once. The trimmed-input check blocks the actionToUrl echo and keeps+ // a failed query from re-firing on unrelated URL changes.+ if (q && q !== values.searchedQuery && q !== values.query.trim()) {+ actions.setQuery(q)+ actions.search()+ } else if (!q && values.searchedQuery !== null && values.sourceObservationId === null) {+ // The URL lost its query (back navigation, or a tab switch dropped it), so show the empty state.+ actions.clearSearch()+ }+ },+ }+ }),])diff --git a/products/replay_vision/frontend/utils/citations.test.ts b/products/replay_vision/frontend/utils/citations.test.tsindex a17717091076..a45a8220ad6c 100644--- a/products/replay_vision/frontend/utils/citations.test.ts+++ b/products/replay_vision/frontend/utils/citations.test.ts@@ -11,6 +11,18 @@ describe('parseCitedSegments', () => {segments: [text('changed the filter (t 1437, 1441), scrolling'), chip(1479)],expected: [text('changed the filter'), chip(1437), chip(1441), text(', scrolling'), chip(1479)],},+ {+ name: 'seeks a range to its start only, and keeps a moment listed after it',+ text: '',+ segments: [text('Hovered the plan table (t 34-42, 50) without clicking')],+ expected: [text('Hovered the plan table'), chip(34), chip(50), text(' without clicking')],+ },+ {+ name: 'reads worded ranges and lists, seeking each range to its start',+ text: 'Stalled on checkout (t 448 to t 2865 and t 3112 to t 3708) then left',+ segments: undefined,+ expected: [text('Stalled on checkout'), chip(448), chip(3112), text(' then left')],+ },{name: 'handles the comma-joined variant that repeats the t prefix',text: '',diff --git a/products/replay_vision/frontend/utils/citations.ts b/products/replay_vision/frontend/utils/citations.tsindex 5ab653bdd81a..2ffcdb8362dd 100644--- a/products/replay_vision/frontend/utils/citations.ts+++ b/products/replay_vision/frontend/utils/citations.ts@@ -19,9 +19,8 @@ export function isSegment(value: unknown): value is Segment {return false}-// Matches `(t 123)` and leaked comma-joined variants like `(t 123, 456)` / `(t 12, t 34)`.-// Mirrors the backend's TIMESTAMP_CITATION_RE (backend/temporal/scanners/base.py).-const TIMESTAMP_CITATION_RE = /\s*\(\s*t\s*(\d+(?:\s*,\s*t?\s*\d+)*)\s*\)/g+// Wider than the backend's TIMESTAMP_CITATION_RE (scanners/base.py), which only parses comma-joined lists.+const TIMESTAMP_CITATION_RE = /\s*\(\s*t\s*(\d+(?:\s*(?:[,\u2013-]|to|and)\s*t?\s*\d+)*)\s*\)/g/** Split leaked `(t <sec>)` markers in plain text into chip segments, one chip per cited second. */function splitLeakedCitations(text: string): Segment[] {@@ -32,8 +31,12 @@ function splitLeakedCitations(text: string): Segment[] {if (chunk) {segments.push({ kind: 'text', value: chunk })}- for (const seconds of match[1].match(/\d+/g) ?? []) {- segments.push({ kind: 'chip', timestamp_ms: parseInt(seconds, 10) * 1000 })+ // Each comma-separated item is one cited moment. A range has a duration, so only its start seeks.+ for (const item of match[1].split(/,|\band\b/)) {+ const seconds = item.match(/\d+/)+ if (seconds) {+ segments.push({ kind: 'chip', timestamp_ms: parseInt(seconds[0], 10) * 1000 })+ }}lastEnd = match.index + match[0].length}@@ -108,3 +111,11 @@ export function citedTimestampRange(text: string, segments: unknown): { startMs:const timestamps = chips.map((chip) => Math.max(0, chip.timestamp_ms))return { startMs: Math.min(...timestamps), endMs: Math.max(...timestamps) }}++export function stripCitations(text: string, segments?: unknown): string {+ return parseCitedSegments(text, segments)+ .map((segment) => (segment.kind === 'text' ? segment.value : ' '))+ .join('')+ .replace(/\s+/g, ' ')+ .trim()+}