:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay-vision): make back navigation return where the reader came from (#113621)
Tue Haulund35bd647ce223
diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsxindex 113b5a781625..50caf903767b 100644--- a/products/replay_vision/frontend/components/ObservationCard.tsx+++ b/products/replay_vision/frontend/components/ObservationCard.tsx@@ -2,7 +2,6 @@ import { IconCopy, IconSparkles } from '@posthog/icons'import { LemonButton, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { copyToClipboard } from 'lib/utils/copyToClipboard'-import { urls } from 'scenes/urls'import type { ReplayObservationApi } from '../generated/api.schemas'import {@@ -16,6 +15,7 @@ import {parseIneligibleReason,} from '../replay_scanners/types'import { markSimilarSearchIntent, similarSearchUrl } from '../search/observationQueries'+import { RECORDING_ORIGIN, observationFromOriginUrl } from '../utils/breadcrumbs'import { citedTextToPlainText, parseCitedSegments } from '../utils/citations'import { VERDICT_LABEL, confidenceLevel, isSummaryScannerType, readReasoning, scannerLabel } from '../utils/observation'import { CitedMarkdown } from './CitedMarkdown'@@ -395,11 +395,14 @@ export function ObservationDockCard({onSeek,onRetry,retrying = false,+ returnPath,}: {observation: ReplayObservationApionSeek?: (timestampMs: number) => voidonRetry?: () => voidretrying?: boolean+ /** The page the player is on, so the observation's back button returns to it. */+ returnPath?: string}): JSX.Element {const snapshot = observation.scanner_snapshotconst scannerType = snapshot?.scanner_type@@ -430,7 +433,7 @@ export function ObservationDockCard({{observation.status === 'succeeded' && result && <ObservationConfidence result={result} />}<Linkdata-attr="vision-observation-open"- to={urls.replayVisionObservation(observation.id)}+ to={observationFromOriginUrl(observation.id, RECORDING_ORIGIN, returnPath)}className="text-xs whitespace-nowrap">View detailsdiff --git a/products/replay_vision/frontend/components/ObservationsDock.tsx b/products/replay_vision/frontend/components/ObservationsDock.tsxindex 15c73e5a5e77..09bcb4c60a12 100644--- a/products/replay_vision/frontend/components/ObservationsDock.tsx+++ b/products/replay_vision/frontend/components/ObservationsDock.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { router } from 'kea-router'import posthog from 'posthog-js'import { useRef, useState } from 'react'@@ -20,6 +21,7 @@ import { observationsDockLogic } from '../logics/observationsDockLogic'import { visionQuotaLogic } from '../logics/visionQuotaLogic'import { LIMIT_REACHED_TOOLTIP } from '../replay_scanners/scannerCopy'import { getReplayVisionEditDisabledReason } from '../utils/accessControl'+import { currentReturnPath } from '../utils/breadcrumbs'import {BUILT_IN_SUMMARY_LABEL,dockObservations,@@ -248,6 +250,7 @@ function ObservationsDockContent({// sessionRecordingPlayerLogic is keyed by playerKey+sessionRecordingId; seek the exact mounted// player by its bound props rather than a propless default instance.const { logicProps, sessionPlayerMetaData } = useValues(sessionRecordingPlayerLogic)+ const returnPath = currentReturnPath(useValues(router).location)const seekToTime = (ms: number): void => {sessionRecordingPlayerLogic.findMounted(logicProps)?.actions.seekToTime(ms)}@@ -350,6 +353,7 @@ function ObservationsDockContent({onSeek={seekToTime}onRetry={() => retryObservation(observation.id)}retrying={retryingObservationIds.includes(observation.id)}+ returnPath={returnPath}/>)))}diff --git a/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx b/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsxindex ccb32ec78242..5e0ef58634b1 100644--- a/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx+++ b/products/replay_vision/frontend/components/PlayerSidebarObservationsTab.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { router } from 'kea-router'import { useEffect, useMemo, useRef } from 'react'import { IconChevronDown, IconChevronRight, IconEye } from '@posthog/icons'@@ -14,6 +15,7 @@ import type { ReplayObservationApi, ReplayScannerApi } from '../generated/api.scimport { observationsDockLogic } from '../logics/observationsDockLogic'import { visionQuotaLogic } from '../logics/visionQuotaLogic'import { SCANNER_TYPE_TAG_TYPE, scannerTypeLabel } from '../replay_scanners/types'+import { RECORDING_ORIGIN, currentReturnPath, observationFromOriginUrl } from '../utils/breadcrumbs'import { isSummaryObservation, readModelOutput, readReasoning, scannerLabel } from '../utils/observation'import { quotaUx } from '../utils/quotaProjection'import { currentRowIndex, nextTimelineStopMs, timelineRows as buildTimelineRows } from '../utils/recordingTimeline'@@ -244,6 +246,7 @@ function FocusPane({retrying: boolean}): JSX.Element {const { height: contentHeight, ref: contentRef } = useResizeObserver<HTMLDivElement>({ box: 'border-box' })+ const { location } = useValues(router)const isSummary = isSummaryObservation(observation)const reasoning = observation.status === 'succeeded' && !isSummary ? readReasoning(observation) : nullconst hasText = observation.status === 'succeeded' && (isSummary || reasoning !== null)@@ -306,7 +309,7 @@ function FocusPane({)}<Linkdata-attr="vision-observation-open-from-sidebar"- to={urls.replayVisionObservation(observation.id)}+ to={observationFromOriginUrl(observation.id, RECORDING_ORIGIN, currentReturnPath(location))}className="text-xs self-end">View detailsdiff --git a/products/replay_vision/frontend/observations/replayObservationLogic.test.ts b/products/replay_vision/frontend/observations/replayObservationLogic.test.tsindex e1a2fc41b08c..fefa20674235 100644--- a/products/replay_vision/frontend/observations/replayObservationLogic.test.ts+++ b/products/replay_vision/frontend/observations/replayObservationLogic.test.ts@@ -3,6 +3,7 @@ import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -150,6 +151,7 @@ describe('replayObservationLogic', () => {},])('$origin scanner observations lead back to $leadsTo', async ({ origin, destination }) => {scannerOrigin = origin+ router.actions.push(urls.replayVisionObservation('obs-1'))const logic = replayObservationLogic({ id: 'obs-1' })logic.mount()try {@@ -173,7 +175,7 @@ describe('replayObservationLogic', () => {// The list view rides along in the observation URL, so the back crumb restores the tab, filters,// sort, and page the reader opened the observation from rather than the scanner overview.it('back returns to the filtered observations list the reader came from', async () => {- router.actions.push('/replay-vision/observation/obs-1', {+ router.actions.push(urls.replayVisionObservation('obs-1'), {tab: 'observations',verdict: 'yes',sort: 'score',@@ -195,7 +197,7 @@ describe('replayObservationLogic', () => {// The router decodes `q=true` to a boolean, so a naive string-only guard would drop it and land// back on an empty search. Searching the literal text "true" must survive the round trip.it('preserves a search query the router decoded to a boolean', async () => {- router.actions.push('/replay-vision/observation/obs-1', { tab: 'search', q: 'true' })+ router.actions.push(urls.replayVisionObservation('obs-1'), { tab: 'search', q: 'true' })const logic = replayObservationLogic({ id: 'obs-1' })logic.mount()try {@@ -207,16 +209,39 @@ describe('replayObservationLogic', () => {}})- // The watch feed lives on the home scene, not the scanner that owns the row, so an observation- // opened from it (carrying `from=watch`) must send back to the feed rather than the scanner.- it('back returns to the watch feed when the observation was opened from it', async () => {- router.actions.push('/replay-vision/observations/obs-1', { from: 'watch', t: 12 })+ // A `from` origin sends back to where the reader was, not to the scanner that owns the row. `return_to`+ // must stay on this site: anything else falls back to the origin's own page.+ test.each([+ { label: 'the watch feed', params: { from: 'watch', t: 12 }, expected: '/replay-vision?tab=watch' },+ { label: 'the recording', params: { from: 'recording' }, expected: '/replay/sess-1' },+ {+ label: 'the playlist it was opened from',+ params: { from: 'recording', return_to: '/replay/home?filters=x#panel=a' },+ expected: '/replay/home?filters=x#panel=a',+ },+ {+ label: 'the page under the PostHog AI panel',+ params: { from: 'ai', return_to: '/dashboard/1' },+ expected: '/dashboard/1',+ },+ {+ label: 'PostHog AI, not a protocol-relative host',+ params: { from: 'ai', return_to: '//example.com/x' },+ expected: '/ai',+ },+ {+ label: 'PostHog AI, not a backslash host',+ params: { from: 'ai', return_to: '/\\example.com' },+ expected: '/ai',+ },+ ])('back returns to $label', async ({ params, expected }) => {+ router.actions.push(urls.replayVisionObservation('obs-1'), params)const logic = replayObservationLogic({ id: 'obs-1' })logic.mount()try {await expectLogic(logic).toDispatchActions(['loadObservationSuccess'])const { breadcrumbs } = sceneLogic.values- expect(breadcrumbs[breadcrumbs.length - 2].path).toBe('/replay-vision?tab=watch')+ expect(breadcrumbs[breadcrumbs.length - 2].path).toBe(expected)} finally {logic.unmount()}@@ -225,7 +250,7 @@ describe('replayObservationLogic', () => {// Retry deletes the row and mints a pending replacement with no verdict, so the redirect must// drop the reader's filters and page — a filtered list would hide the row it promises "shortly".it('retry lands on the unfiltered scanner page, not the reader saved list view', async () => {- router.actions.push('/replay-vision/observation/obs-1', { tab: 'observations', verdict: 'yes', page: 2 })+ router.actions.push(urls.replayVisionObservation('obs-1'), { tab: 'observations', verdict: 'yes', page: 2 })const logic = replayObservationLogic({ id: 'obs-1' })logic.mount()try {@@ -240,6 +265,22 @@ describe('replayObservationLogic', () => {}})+ it('retry leaves the reader where they went while the request was pending', async () => {+ router.actions.push(urls.replayVisionObservation('obs-1'))+ const logic = replayObservationLogic({ id: 'obs-1' })+ logic.mount()+ try {+ await expectLogic(logic).toDispatchActions(['loadObservationSuccess'])+ await expectLogic(logic, () => {+ logic.actions.retryObservation()+ router.actions.push(urls.replayVision())+ }).toDispatchActions(['retryObservationSuccess'])+ expect(router.values.location.pathname).toMatch(/\/replay-vision$/)+ } finally {+ logic.unmount()+ }+ })+const row = (id: string): ReplayObservationApi =>({id,@@ -277,7 +318,7 @@ describe('replayObservationLogic', () => {lastObservationsPage.current = page(['a', 'obs-1', 'c'], {filterParams: { verdict: 'yes' } as VisionObservationsRetrieveParams,})- router.actions.push('/replay-vision/observation/obs-1', { verdict: 'yes' })+ router.actions.push(urls.replayVisionObservation('obs-1'), { verdict: 'yes' })const logic = replayObservationLogic({ id: 'obs-1' })logic.mount()try {@@ -294,7 +335,7 @@ describe('replayObservationLogic', () => {})it('falls back to the filtered read when the page cannot answer prev/next', async () => {- router.actions.push('/replay-vision/observation/obs-1', { verdict: 'yes' })+ router.actions.push(urls.replayVisionObservation('obs-1'), { verdict: 'yes' })const logic = replayObservationLogic({ id: 'obs-1' })logic.mount()try {@@ -309,7 +350,7 @@ describe('replayObservationLogic', () => {// A pending or running observation reloads every few seconds. The reload re-enters the loading// state, so prev/next must not fall back to a spinner that rejects clicks on every tick.it('keeps prev/next clickable while a background reload runs', async () => {- router.actions.push('/replay-vision/observation/obs-1', { verdict: 'yes' })+ router.actions.push(urls.replayVisionObservation('obs-1'), { verdict: 'yes' })const logic = replayObservationLogic({ id: 'obs-1' })logic.mount()try {@@ -328,7 +369,7 @@ describe('replayObservationLogic', () => {it('drops the row from the table page and reports the error when its first read fails', async () => {retrieveStatus = 500lastObservationsPage.current = page(['a', 'obs-1', 'c'])- router.actions.push('/replay-vision/observation/obs-1')+ router.actions.push(urls.replayVisionObservation('obs-1'))const logic = replayObservationLogic({ id: 'obs-1' })logic.mount()try {@@ -345,7 +386,7 @@ describe('replayObservationLogic', () => {lastObservationsPage.current = page(['a', 'obs-1', 'c'])sceneLogic.unmount()sceneLogic.mount()- router.actions.push('/replay-vision/observation/obs-1')+ router.actions.push(urls.replayVisionObservation('obs-1'))const logic = replayObservationLogic({ id: 'obs-1' })logic.mount()try {diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.ts b/products/replay_vision/frontend/observations/replayObservationLogic.tsindex 2042b2753ca3..4e349eefd2e2 100644--- a/products/replay_vision/frontend/observations/replayObservationLogic.ts+++ b/products/replay_vision/frontend/observations/replayObservationLogic.ts@@ -2,6 +2,7 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path,import { combineUrl, router } from 'kea-router'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -16,7 +17,12 @@ import { OBSERVATION_LIST_FILTER_KEYS, OBSERVATION_LIST_URL_PARAM_KEYS } from '.import { searchBreadcrumb } from '../search/observationQueries'import {OBSERVATION_ORIGIN_PARAM,+ OBSERVATION_RETURN_PATH_PARAM,+ POSTHOG_AI_ORIGIN,+ RECORDING_ORIGIN,WATCH_FEED_ORIGIN,+ isObservationOrigin,+ safeReturnPath,scannerBreadcrumb,watchFeedBreadcrumb,} from '../utils/breadcrumbs'@@ -83,14 +89,45 @@ export function scannerReturnParams(searchParams: Record<string, unknown>): Recoreturn params}-/**- * Carries the home-view origin (`from`) across prev/next, so back keeps returning to the feed the- * reader came from even after they page through neighbors within the scene.- */+/** Carries the origin across prev/next, so back still returns where the reader came from. */export function observationOriginParams(searchParams: Record<string, unknown>): Record<string, string> {- return searchParams[OBSERVATION_ORIGIN_PARAM] === WATCH_FEED_ORIGIN- ? { [OBSERVATION_ORIGIN_PARAM]: WATCH_FEED_ORIGIN }- : {}+ const origin = searchParams[OBSERVATION_ORIGIN_PARAM]+ if (!isObservationOrigin(origin)) {+ return {}+ }+ const returnPath = safeReturnPath(searchParams[OBSERVATION_RETURN_PATH_PARAM])+ return {+ [OBSERVATION_ORIGIN_PARAM]: origin,+ ...(returnPath ? { [OBSERVATION_RETURN_PATH_PARAM]: returnPath } : {}),+ }+}++function recordingBreadcrumb(observation: ReplayObservationApi, returnPath: string | null = null): Breadcrumb {+ return {+ key: `recording-${observation.session_id}`,+ name: 'Recording',+ path: returnPath ?? urls.replaySingle(observation.session_id),+ iconType: 'session_replay',+ }+}++/** Back returns to the `from` origin when there is one, else to whatever owns the observation. */+function parentBreadcrumbFor(observation: ReplayObservationApi, searchParams: Record<string, unknown>): Breadcrumb {+ const origin = searchParams[OBSERVATION_ORIGIN_PARAM]+ const returnPath = safeReturnPath(searchParams[OBSERVATION_RETURN_PATH_PARAM])+ if (origin === WATCH_FEED_ORIGIN) {+ return watchFeedBreadcrumb()+ }+ if (origin === RECORDING_ORIGIN) {+ return recordingBreadcrumb(observation, returnPath)+ }+ if (origin === POSTHOG_AI_ORIGIN) {+ return { key: 'replay-vision-posthog-ai', name: 'PostHog AI', path: returnPath ?? urls.ai() }+ }+ const returnParams = scannerReturnParams(searchParams)+ return returnParams.tab === ReplayScannerTab.Search+ ? searchBreadcrumb(returnParams)+ : observationParentBreadcrumb(observation, returnParams)}/** The crumb the observation page's back button returns to. */@@ -101,12 +138,7 @@ export function observationParentBreadcrumb(if (hasScannerPage(observation)) {return scannerBreadcrumb(observation.scanner_id, scannerLabel(observation), returnParams)}- return {- key: `recording-${observation.session_id}`,- name: 'Recording',- path: observationParentUrl(observation),- iconType: 'session_replay',- }+ return recordingBreadcrumb(observation)}/** Canonical link to an observation's detail page, carrying list filters so prev/next honors them. */@@ -317,18 +349,9 @@ export const replayObservationLogic = kea<replayObservationLogicType>([const inFlight = values.observation?.status === 'pending' || values.observation?.status === 'running'scheduleObservationPoll(cache.disposables, inFlight, actions.loadObservation)}- // Point the breadcrumb at whatever owns this observation, so "back" returns there instead of the- // vision home. The watch feed is the exception: it opens rows from the home scene, so back returns- // 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()- : returnParams.tab === ReplayScannerTab.Search- ? searchBreadcrumb(returnParams)- : observationParentBreadcrumb(observation, returnParams)+ parentBreadcrumbFor(observation, router.values.searchParams))}return {@@ -393,13 +416,16 @@ export const replayObservationLogic = kea<replayObservationLogicType>([return}actions.retryObservationSuccess()- if (!observation) {+ // The reader may have left while the retry request was in flight.+ const stillHere =+ removeProjectIdIfPresent(router.values.location.pathname) === urls.replayVisionObservation(props.id)+ if (!observation || !stillHere) {return}// Land on the unfiltered parent, not the reader's saved list view: the replacement is// pending with no verdict yet, so a filtered or paged list would hide the row we just- // promised appears "shortly".- router.actions.push(observationParentUrl(observation))+ // promised appears "shortly". Replace, because the retry deletes this observation.+ router.actions.replace(observationParentUrl(observation))},// When the stream reports the observation has settled, reload once to render the final result.diff --git a/products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget.tsx b/products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget.tsxindex a1fb4cab3be8..83f42cf1aca8 100644--- a/products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget.tsx+++ b/products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget.tsx@@ -1,10 +1,10 @@import { useValues } from 'kea'+import { router } from 'kea-router'import { LemonBanner, Link, Spinner } from '@posthog/lemon-ui'-import { urls } from 'scenes/urls'-import type { ReplayObservationApi } from '../generated/api.schemas'+import { POSTHOG_AI_ORIGIN, currentReturnPath, observationFromOriginUrl } from '../utils/breadcrumbs'import { flattenMarkdownToLine } from '../utils/markdown'import { readErrorMessage, readReasoning, readSummary, readTitle } from '../utils/observation'import { replayVisionScanWidgetLogic } from './replayVisionScanWidgetLogic'@@ -25,6 +25,9 @@ const SKIP_MESSAGES: Record<string, string> = {export function ReplayVisionScanWidget({ scanId, sessionIds, skipped }: ReplayVisionScanWidgetProps): JSX.Element {const { gaveUp, latestPerSession, pendingCount } = useValues(replayVisionScanWidgetLogic({ scanId, sessionIds }))+ // Read once per widget, not per row; the thread can stay open in the side panel across scenes.+ const { location } = useValues(router)+ const returnPath = currentReturnPath(location)const skippedByReason = Object.entries(skipped.reduce<Record<string, number>>((counts, entry) => {counts[entry.reason] = (counts[entry.reason] ?? 0) + 1@@ -58,7 +61,7 @@ export function ReplayVisionScanWidget({ scanId, sessionIds, skipped }: ReplayVi<div className="divide-y">{latestPerSession.map((observation) => (- <ObservationRow key={observation.id} observation={observation} />+ <ObservationRow key={observation.id} observation={observation} returnPath={returnPath} />))}{pendingCount > 0 && gaveUp && (<p className="m-0 px-3 py-3 text-sm text-secondary">@@ -74,7 +77,13 @@ export function ReplayVisionScanWidget({ scanId, sessionIds, skipped }: ReplayVi)}-function ObservationRow({ observation }: { observation: ReplayObservationApi }): JSX.Element {+function ObservationRow({+ observation,+ returnPath,+}: {+ observation: ReplayObservationApi+ returnPath: string+}): JSX.Element {if (observation.status === 'pending' || observation.status === 'running') {return (<div className="flex items-center gap-2 px-3 py-2 text-sm text-secondary">@@ -104,7 +113,7 @@ function ObservationRow({ observation }: { observation: ReplayObservationApi }):{body && <p className="m-0 mt-0.5 text-secondary">{body}</p>}<Linkdata-attr="vision-scan-widget-open-observation"- to={urls.replayVisionObservation(observation.id)}+ to={observationFromOriginUrl(observation.id, POSTHOG_AI_ORIGIN, returnPath)}className="text-xs">View detailsdiff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsxindex c1a298290ce6..569c0cbebeb2 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx@@ -8,7 +8,6 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { lazyWithRetry } from 'lib/utils/retryImport'import { SceneExport } from 'scenes/sceneTypes'-import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'@@ -24,6 +23,7 @@ import { ScannerObservationsTable } from './components/ScannerObservationsTable'import { ScannerOverview } from './components/ScannerOverview'import { replayScannerLogic } from './replayScannerLogic'import { ReplayScannerTab, replayScannerSceneLogic } from './replayScannerSceneLogic'+import { scannerEditUrl } from './scannerEditorSceneLogic'const ScannerAlertsTab = lazyWithRetry(() =>import('./components/ScannerAlertsTab').then((module) => ({ default: module.ScannerAlertsTab }))@@ -45,7 +45,7 @@ export const scene: SceneExport = {}export function ReplayScannerSceneComponent(): JSX.Element {- const { scannerId, activeTab } = useValues(replayScannerSceneLogic)+ const { scannerId, activeTab, defaultTab } = useValues(replayScannerSceneLogic)const { setActiveTab, setDefaultTab } = useActions(replayScannerSceneLogic)const scannerLogic = replayScannerLogic({ id: scannerId })@@ -82,7 +82,7 @@ export function ReplayScannerSceneComponent(): JSX.Element {<LemonButtontype="primary"size="small"- to={urls.replayVisionScannerConfigure(scannerId)}+ to={scannerEditUrl(scannerId, activeTab === defaultTab ? null : activeTab)}disabledReason={getReplayVisionEditDisabledReason(scanner.user_access_level)}data-attr="vision-scanner-edit"data-ph-capture-attribute-scanner-type={scanner.scanner_type}diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsxindex 3c266a34a33f..c406714ad36f 100644--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx@@ -53,7 +53,7 @@ import { ScannerTemplatePicker } from './components/ScannerTemplatePicker'import { ScannerTriggers } from './components/ScannerTriggers'import { ScannerTypeConfigEditor } from './components/ScannerTypeConfigEditor'import { parseExperimentScannerParams } from './experimentTargeting'-import { replayScannerLogic } from './replayScannerLogic'+import { leaveScannerEditor, replayScannerLogic } from './replayScannerLogic'import {SCANNER_EDITOR_STEPS,SCANNER_EDITOR_STEP_ORDER,@@ -515,7 +515,7 @@ function EditorFooter({const cancel = (): void => {// Resetting first leaves nothing unsaved, so the leave guard can't prompt on top of this.discardScannerDraft()- router.actions.push(isNew ? urls.replayVision() : urls.replayVision(scannerId))+ leaveScannerEditor(scannerId, isNew ? urls.replayVision() : urls.replayVision(scannerId))}const handleCancel = (): void => {if (!hasUnsavedChanges) {diff --git a/products/replay_vision/frontend/replay_scanners/components/BatchScanRecordings.tsx b/products/replay_vision/frontend/replay_scanners/components/BatchScanRecordings.tsxindex 9196530bab6b..7abbbd667e61 100644--- a/products/replay_vision/frontend/replay_scanners/components/BatchScanRecordings.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/BatchScanRecordings.tsx@@ -15,17 +15,18 @@ import {SessionRecordingPlaylistLogicProps,sessionRecordingsPlaylistLogic,} from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'-import { urls } from 'scenes/urls'import { SessionRecordingType } from '~/types'import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'import { ObservationStatusTag } from '../../components/ObservationCard'+import { observationDetailUrl } from '../../observations/replayObservationLogic'import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { formatCreditCount } from '../../utils/credits'import { recordingScanBlock } from '../../utils/scanEligibility'import { replayScannerLogic } from '../replayScannerLogic'+import { ReplayScannerTab } from '../replayScannerSceneLogic'import { IN_PROGRESS_STATUSES, scannerRunTabLogic } from '../scannerRunTabLogic'function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {@@ -134,7 +135,7 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {size="small"type="secondary"icon={<IconEye />}- to={urls.replayVisionObservation(observation.id)}+ to={observationDetailUrl(observation.id, { tab: ReplayScannerTab.Run })}data-attr="vision-run-view-observation">View observationdiff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsxindex ebc4ca1dae89..97a869842cf0 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerSetupCard.tsx@@ -12,6 +12,8 @@ import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { formatCreditCount } from '../../utils/credits'import { scannerExperimentScope, scopeVariantsLabel } from '../experimentTargeting'import { replayScannerLogic } from '../replayScannerLogic'+import { ReplayScannerTab } from '../replayScannerSceneLogic'+import { scannerEditUrl } from '../scannerEditorSceneLogic'import { SCANNER_TYPE_OPTIONS, modelName, scannerTypeLabel } from '../types'import { PromptPreview } from './PromptPreview'import { ScannerRecordingFilters } from './ScannerRecordingFilters'@@ -38,7 +40,7 @@ export function ScannerSetupCard({ scannerId }: { scannerId: string }): JSX.Elem<LemonButtonsize="xsmall"type="secondary"- to={urls.replayVisionScannerConfigure(scannerId)}+ to={scannerEditUrl(scannerId, ReplayScannerTab.Overview)}disabledReason={getReplayVisionEditDisabledReason(scanner.user_access_level)}data-attr="vision-setup-edit">diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsxindex 59f77d15b4d6..d1a70942b115 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsx@@ -13,8 +13,10 @@ import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { formatCreditsRange } from '../../utils/credits'import { quotaBannerState } from '../../utils/quotaProjection'import { replayScannerLogic } from '../replayScannerLogic'+import { ReplayScannerTab } from '../replayScannerSceneLogic'import { scanDrought } from '../scanDrought'import { LIMIT_REACHED_TOOLTIP } from '../scannerCopy'+import { scannerEditUrl } from '../scannerEditorSceneLogic'import { ScannerStatus, SWEEP_INTERVAL_MINUTES, scannerStatus, spendAgainstLimit } from '../scannerStatus'type StatusTone = 'success' | 'warning' | 'danger' | 'muted'@@ -200,7 +202,7 @@ export function ScannerStatusStrip({ scannerId }: { scannerId: string }): JSX.ElNo limit set. This scanner keeps scanning until your organization's credits run out.{' '}{!editDisabledReason && (<Link- to={urls.replayVisionScannerConfigure(scannerId)}+ to={scannerEditUrl(scannerId, ReplayScannerTab.Overview)}data-attr="vision-scanner-status-set-limit">Set a limitdiff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex e2d0655fbffd..1bb9d381ae82 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -7,6 +7,7 @@ import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -20,6 +21,7 @@ import {ObservationStatusValue,ObservationTriggeredByValue,ObservationVerdictValue,+ leaveScannerEditor,replayScannerLogic,shouldGuardScannerNavigation,} from './replayScannerLogic'@@ -1516,6 +1518,17 @@ describe('replayScannerLogic', () => {})})+ describe('leaveScannerEditor', () => {+ it.each([+ ['the saved scanner’s editor is open', 'scanner-a', urls.replayVision('scanner-a')],+ ['another scanner’s editor is open', 'scanner-b', urls.replayVisionScannerConfigure('scanner-b')],+ ])('when %s', (_, openScannerId, expectedPathname) => {+ router.actions.push(urls.replayVisionScannerConfigure(openScannerId))+ leaveScannerEditor('scanner-a', urls.replayVision('scanner-a'))+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(expectedPathname)+ })+ })+describe('shouldGuardScannerNavigation', () => {const scannerId = 'abc-123'const configure = urls.replayVisionScannerConfigure(scannerId)@@ -1544,6 +1557,13 @@ describe('replayScannerLogic', () => {['out to the detail page', { ...base, nextPathname: detail }, true],['out to an unrelated scene', { ...base, nextPathname: '/insights' }, true],['closing the tab (no next location)', { ...base, nextPathname: undefined }, true],+ [+ 'browser back to the previous step',+ { ...base, currentPathname: triggers, browserPathname: `/project/123${configure}` },+ false,+ ],+ ['browser back out to the detail page', { ...base, browserPathname: detail }, true],+ ['closing the tab while the window still shows the step', { ...base, browserPathname: configure }, true],['over to a different scanner’s editor',{ ...base, nextPathname: urls.replayVisionScannerConfigure('other-id') },diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex 7cda2c590588..aed5ec48d858 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -1091,7 +1091,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([scannerToApiBody({ ...body, creation_method: values.creationMethod }))actions.scannerSaved(scanner)- router.actions.replace(urls.replayVision(response.id))+ leaveScannerEditor(props.id, urls.replayVision(response.id))// First scheduled results are minutes away, so the copy matches the Overview's// pending panel and the button hands off to the instant on-demand tab.lemonToast.success('Scanner created. First scan in progress.', {@@ -1105,7 +1105,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([await visionScannersPartialUpdate(String(teamId), props.id, scannerToPatchedApiBody(body))actions.scannerSaved(scanner)lemonToast.success('Scanner saved')- router.actions.push(urls.replayVision(props.id))+ leaveScannerEditor(props.id, urls.replayVision(props.id))}} catch (error: any) {// A duplicate name is the one field error the details step can fix, so route back to it.@@ -2192,9 +2192,13 @@ export const replayScannerLogic = kea<replayScannerLogicType>([draftScannerFromGoalFailure: ({ errorObject }) => {lemonToast.error(errorObject?.detail ?? "Couldn't draft a scanner. Try again in a moment.")// The goal flow moved to the overview skeleton on request; with no draft to show,- // send the user back to the questions to try again.+ // send the user back to the questions, dropping the empty overview from history when it was pushed.if (router.values.location.pathname.endsWith(urls.replayVisionScannerOverview('new'))) {- router.actions.push(urls.replayVisionScannerTemplate('new'))+ if (router.values.lastMethod === 'PUSH') {+ window.history.back()+ } else {+ router.actions.replace(urls.replayVisionScannerTemplate('new'))+ }}},@@ -2678,6 +2682,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([scannerId: props.id,currentPathname: router.values.location.pathname,nextPathname: newLocation?.pathname,+ browserPathname: window.location.pathname,}),message: 'Leave scanner editor?\nChanges you made will be discarded.',onConfirm: () => {@@ -2721,6 +2726,19 @@ export const replayScannerLogic = kea<replayScannerLogicType>([}),])+export function leaveScannerEditor(scannerId: string, destination: string): void {+ // A save can finish after the user has left this scanner's editor, and must not pull them away from where they are.+ if (!scannerEditorPaths(scannerId).includes(removeProjectIdIfPresent(router.values.location.pathname))) {+ return+ }+ const editor = scannerEditorSceneLogic.findMounted()+ if (editor) {+ editor.actions.leaveEditor(destination)+ } else {+ router.actions.replace(destination)+ }+}+/** The step URLs of a scanner's editor wizard. */function scannerEditorPaths(scannerId: string): string[] {return [@@ -2743,11 +2761,18 @@ export function shouldGuardScannerNavigation(params: {scannerId: stringcurrentPathname: stringnextPathname?: string+ browserPathname?: string}): boolean {- const { hasUnsavedChanges, isSubmitting, hasSavedDraft, scannerId, currentPathname, nextPathname } = params+ const { hasUnsavedChanges, isSubmitting, hasSavedDraft, scannerId, currentPathname, browserPathname } = paramsif (!hasUnsavedChanges || isSubmitting || hasSavedDraft) {return false}+ // kea-router passes no destination on browser back/forward, but by then the window already shows it.+ const nextPathname =+ params.nextPathname ??+ (browserPathname && removeProjectIdIfPresent(browserPathname) !== removeProjectIdIfPresent(currentPathname)+ ? browserPathname+ : undefined)// The router's stored pathname carries the `/project/:id` prefix, while `urls.*` never do,// so both sides must be normalized before comparing or the guard never engages.const editorPaths = scannerEditorPaths(scannerId)diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.tsindex 240eb2afd359..c19dea9cf4ba 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts@@ -132,7 +132,7 @@ export const replayScannerSceneLogic = kea<replayScannerSceneLogicType>([} else {searchParams.tab = values.activeTab}- return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]+ return [router.values.location.pathname, searchParams, router.values.hashParams]},})),diff --git a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.tsindex 421c3f1b9771..24cce6890e3f 100644--- a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts@@ -5,7 +5,14 @@ import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'-import { firstErroredScannerStep, scannerEditorSceneLogic, scannerStepErrors } from './scannerEditorSceneLogic'+import {+ SCANNER_EDITOR_STEPS,+ firstErroredScannerStep,+ isScannerEditorPath,+ scannerEditorSceneLogic,+ scannerStepErrors,+ scannerStepUrl,+} from './scannerEditorSceneLogic'describe('firstErroredScannerStep', () => {it.each([@@ -47,9 +54,44 @@ describe('scannerEditorSceneLogic', () => {})afterEach(() => {+ jest.restoreAllMocks()logic?.unmount()})+ describe('isScannerEditorPath', () => {+ it.each<[string, boolean]>([+ ...SCANNER_EDITOR_STEPS.map((step): [string, boolean] => [scannerStepUrl(step, 'abc'), true]),+ [scannerStepUrl('overview', 'new'), true],+ [`/project/123${urls.replayVisionScannerBudget('abc')}`, true],+ [urls.replayVision('abc'), false],+ [urls.replayVisionObservation('abc'), false],+ [urls.replayVision(), false],+ ])('%s → %s', (pathname, expected) => {+ expect(isScannerEditorPath(pathname)).toBe(expected)+ })+ })++ describe('leaveEditor', () => {+ it('pushes the destination when the unwind lands on a fresh tab’s first entry', () => {+ // A fresh tab's first entry has no history state, so the first push gets count 1.+ let count = 0+ jest.spyOn(window.history, 'state', 'get').mockImplementation(() => (count ? { count } : null))+ jest.spyOn(window.history, 'go').mockImplementation((delta = 0) => {+ count += delta+ window.dispatchEvent(new PopStateEvent('popstate'))+ })+ count = 1+ router.actions.push(urls.replayVisionScannerTemplate('new'))+ count = 2+ router.actions.push(urls.replayVisionScannerConfigure('new'))+ const push = jest.spyOn(router.actions, 'push')++ logic.actions.leaveEditor(urls.replayVision('created'))++ expect(push).toHaveBeenCalledWith(urls.replayVision('created'))+ })+ })+describe('URL → state', () => {it('reflects the template step for a new scanner', async () => {router.actions.push(urls.replayVisionScannerTemplate('new'))diff --git a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.tsindex b4587c7f8a25..06d682b2724c 100644--- a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts@@ -1,7 +1,9 @@-import { MakeLogicType, actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { combineUrl, router, urlToAction } from 'kea-router'+import type { LocationChangedPayload } from 'kea-router/lib/types'import { GuidedWizardStep } from 'lib/components/GuidedWizard/GuidedWizardStepper'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { urls } from 'scenes/urls'import { tagsModel } from '~/models/tagsModel'@@ -99,6 +101,15 @@ export function scannerStepUrlWithParams(return combineUrl(scannerStepUrl(step, scannerId), searchParams).url}+export const EDITOR_RETURN_TAB_PARAM = 'return_tab'++export function scannerEditUrl(scannerId: string, returnTab: string | null): string {+ return combineUrl(+ urls.replayVisionScannerConfigure(scannerId),+ returnTab ? { [EDITOR_RETURN_TAB_PARAM]: returnTab } : {}+ ).url+}+export function scannerStepUrl(step: ScannerEditorStep, scannerId: string): string {switch (step) {case 'template':@@ -116,6 +127,59 @@ export function scannerStepUrl(step: ScannerEditorStep, scannerId: string): stri}}+/** The history entries one editor visit occupies, by kea-router's per-entry `count`. */+interface EditorHistory {+ scannerId: string+ counts: number[]+ enteredFromApp: boolean+}++interface RouterPayload {+ method?: string+ initial?: boolean+}++const LEAVE_EDITOR_POPSTATE_TIMEOUT_MS = 10000++// The goal flow's overview sits outside the manual stepper.+const EDITOR_PATH_SEGMENTS = new Set<string>([...SCANNER_EDITOR_STEPS, 'overview'])++export function isScannerEditorPath(pathname: string): boolean {+ const [root, , segment, ...rest] = removeProjectIdIfPresent(pathname).split('/').slice(1)+ return root === 'replay-vision' && rest.length === 0 && EDITOR_PATH_SEGMENTS.has(segment)+}++function currentHistoryCount(): number | null {+ const count = window.history.state?.count+ return typeof count === 'number' ? count : null+}++function trackEditorHistory(+ previous: EditorHistory | null,+ scannerId: string,+ payload: RouterPayload+): EditorHistory | null {+ const count = currentHistoryCount()+ if (count === null) {+ return null+ }+ // On mount kea-router reports an initial POP, so the router's last method says how we got here.+ const method = payload.initial ? router.values.lastMethod : payload.method+ if (!previous || previous.scannerId !== scannerId) {+ return { scannerId, counts: [count], enteredFromApp: method === 'PUSH' }+ }+ if (method === 'PUSH') {+ return { ...previous, counts: [...previous.counts, count] }+ }+ if (method === 'REPLACE') {+ return { ...previous, counts: [...previous.counts.slice(0, -1), count] }+ }+ const index = previous.counts.indexOf(count)+ return index === -1+ ? { scannerId, counts: [count], enteredFromApp: false }+ : { ...previous, counts: previous.counts.slice(0, index + 1) }+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scannerEditorSceneLogicValues {breadcrumbs: Breadcrumb[]@@ -129,6 +193,9 @@ export interface scannerEditorSceneLogicActions {loadTags: () => {value: true} // tagsModel+ leaveEditor: (destination: string) => {+ destination: string+ }setScannerId: (scannerId: string) => {scannerId: string}@@ -148,6 +215,32 @@ export interface scannerEditorSceneLogicMeta {searchParams: Record<string, any>) => Breadcrumb[]}+ __keaTypeGenInternalReducerActions: {+ 'location changed (kea.router)': ({+ method,+ pathname,+ search,+ searchParams,+ hash,+ hashParams,+ initial,+ url,+ routerState,+ }: LocationChangedPayload) => {+ payload: {+ hash: string+ hashParams: Record<string, any>+ initial: boolean+ method: 'POP' | 'PUSH' | 'REPLACE'+ pathname: string+ routerState: Record<string, any>+ search: string+ searchParams: Record<string, any>+ url: string+ }+ type: 'location changed (kea.router)'+ }+ }}export type scannerEditorSceneLogicType = MakeLogicType<@@ -167,6 +260,7 @@ export const scannerEditorSceneLogic = kea<scannerEditorSceneLogicType>([actions({setScannerId: (scannerId: string) => ({ scannerId }),setStep: (step: ScannerEditorStep) => ({ step }),+ leaveEditor: (destination: string) => ({ destination }),}),reducers({@@ -218,79 +312,91 @@ export const scannerEditorSceneLogic = kea<scannerEditorSceneLogicType>([}return crumbs}- // Editing an existing scanner: surface the detail page (its Overview, where the Setup card's- // Edit link lives) as an intermediate crumb so the back arrow returns there, not to the list.- crumbs.push(scannerBreadcrumb(scannerId, null, { tab: 'overview' }), {- key: `scanner-${scannerId}-edit`,- name: 'Edit',- path: urls.replayVisionScannerConfigure(scannerId),- })+ // Editing an existing scanner: the back arrow returns to the scanner tab the edit started from.+ const returnTab = searchParams[EDITOR_RETURN_TAB_PARAM]+ crumbs.push(+ scannerBreadcrumb(scannerId, null, typeof returnTab === 'string' ? { tab: returnTab } : {}),+ {+ key: `scanner-${scannerId}-edit`,+ name: 'Edit',+ path: urls.replayVisionScannerConfigure(scannerId),+ }+ )return crumbs},],}),- urlToAction(({ actions, values }) => ({- [urls.replayVisionScannerTemplate(':id')]: ({ id }) => {- const scannerId = id || 'new'- if (scannerId !== 'new') {- router.actions.replace(urls.replayVisionScannerDetails(scannerId))+ listeners(({ cache }) => ({+ // Unwind the editor's history entries so browser back skips the finished wizard; replace when nothing known precedes it.+ leaveEditor: ({ destination }) => {+ const history: EditorHistory | null = cache.editorHistory+ cache.editorHistory = null+ if (!history?.enteredFromApp || history.counts[history.counts.length - 1] !== currentHistoryCount()) {+ router.actions.replace(destination)return}- if (scannerId !== values.scannerId) {- actions.setScannerId(scannerId)- }- if (values.step !== 'template') {- actions.setStep('template')- }- },- [urls.replayVisionScannerOverview(':id')]: ({ id }) => {- const scannerId = id || 'new'- if (scannerId !== values.scannerId) {- actions.setScannerId(scannerId)- }- if (values.step !== 'overview') {- actions.setStep('overview')- }- },- [urls.replayVisionScannerDetails(':id')]: ({ id }) => {- const scannerId = id || 'new'- if (scannerId !== values.scannerId) {- actions.setScannerId(scannerId)- }- if (values.step !== 'details') {- actions.setStep('details')- }- },- [urls.replayVisionScannerConfigure(':id')]: ({ id }) => {- const scannerId = id || 'new'- if (scannerId !== values.scannerId) {- actions.setScannerId(scannerId)- }- if (values.step !== 'configure') {- actions.setStep('configure')- }- },- [urls.replayVisionScannerTriggers(':id')]: ({ id }) => {- const scannerId = id || 'new'- if (scannerId !== values.scannerId) {- actions.setScannerId(scannerId)- }- if (values.step !== 'triggers') {- actions.setStep('triggers')- }+ const depth = history.counts.length+ // Not a disposable, because the scene unmounts during this popstate and would remove it first.+ // The timeout drops the listener if the popstate never comes, so it can't fire on a later back.+ const landed = new AbortController()+ // The entry before the editor holds the count just below the editor's first entry.+ const preEditorCount = history.counts[0] - 1+ window.addEventListener(+ 'popstate',+ () => {+ landed.abort()+ const target = combineUrl(destination)+ const landedAt = removeProjectIdIfPresent(window.location.pathname) + window.location.search+ // kea-router stores no count on a tab's first entry and numbers the next push 1, so null means 0.+ if (+ (currentHistoryCount() ?? 0) === preEditorCount &&+ landedAt !== target.pathname + target.search+ ) {+ router.actions.push(destination)+ }+ },+ { signal: landed.signal }+ )+ setTimeout(() => landed.abort(), LEAVE_EDITOR_POPSTATE_TIMEOUT_MS)+ window.history.go(-depth)},- [urls.replayVisionScannerBudget(':id')]: ({ id }) => {- const scannerId = id || 'new'- if (scannerId !== values.scannerId) {- actions.setScannerId(scannerId)- }- if (values.step !== 'budget') {- actions.setStep('budget')+ [router.actionTypes.locationChanged]: ({ pathname }) => {+ if (!isScannerEditorPath(pathname)) {+ cache.editorHistory = null}},})),+ urlToAction(({ actions, values, cache }) => {+ const openStep =+ (step: ScannerEditorStep) =>+ ({ id }: Record<string, string | undefined>, _: unknown, __: unknown, payload: RouterPayload): void => {+ const scannerId = id || 'new'+ cache.editorHistory = trackEditorHistory(cache.editorHistory, scannerId, payload)+ if (scannerId !== values.scannerId) {+ actions.setScannerId(scannerId)+ }+ if (values.step !== step) {+ actions.setStep(step)+ }+ }+ return {+ [urls.replayVisionScannerTemplate(':id')]: (params, searchParams, hashParams, payload) => {+ if (params.id && params.id !== 'new') {+ router.actions.replace(urls.replayVisionScannerDetails(params.id))+ return+ }+ openStep('template')(params, searchParams, hashParams, payload)+ },+ [urls.replayVisionScannerOverview(':id')]: openStep('overview'),+ [urls.replayVisionScannerDetails(':id')]: openStep('details'),+ [urls.replayVisionScannerConfigure(':id')]: openStep('configure'),+ [urls.replayVisionScannerTriggers(':id')]: openStep('triggers'),+ [urls.replayVisionScannerBudget(':id')]: openStep('budget'),+ }+ }),+afterMount(({ actions }) => {// tagsModel is lazy; load it here so a direct visit doesn't start with an empty tags autocomplete.actions.loadTags()diff --git a/products/replay_vision/frontend/search/observationSearchLogic.ts b/products/replay_vision/frontend/search/observationSearchLogic.tsindex 5c4f59240055..3cdb389a5640 100644--- a/products/replay_vision/frontend/search/observationSearchLogic.ts+++ b/products/replay_vision/frontend/search/observationSearchLogic.ts@@ -562,7 +562,8 @@ export const observationSearchLogic = kea<observationSearchLogicType>([actionToUrl(({ values }) => {const withScope = (- q: string | undefined+ q: string | undefined,+ replace: boolean = true): [string, Record<string, unknown>, Record<string, unknown>, { replace: boolean }] => [router.values.location.pathname,{@@ -574,11 +575,13 @@ export const observationSearchLogic = kea<observationSearchLogicType>([similar: values.pendingSourceObservationId ?? undefined,},router.values.hashParams,- { replace: true },+ { replace },]return {// Observation prose stays out of the URL (see markSimilarSearchIntent).- search: () => withScope(values.pendingSourceObservationId ? undefined : values.query.trim() || undefined),+ // A submitted query pushes, so browser back returns to the previous search.+ search: () =>+ withScope(values.pendingSourceObservationId ? undefined : values.query.trim() || undefined, false),clearSearch: () => withScope(undefined),setScannerId: () => withScope(router.values.searchParams.q),setDateRange: () => withScope(router.values.searchParams.q),diff --git a/products/replay_vision/frontend/utils/breadcrumbs.ts b/products/replay_vision/frontend/utils/breadcrumbs.tsindex d6b4e50dc948..e141b4fa7d67 100644--- a/products/replay_vision/frontend/utils/breadcrumbs.ts+++ b/products/replay_vision/frontend/utils/breadcrumbs.ts@@ -1,5 +1,7 @@import { combineUrl } from 'kea-router'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { getRelativeNextPath } from 'lib/utils/url'import { urls } from 'scenes/urls'import { Breadcrumb } from '~/types'@@ -19,6 +21,36 @@ export const VISION_ROOT_BREADCRUMB: Breadcrumb = {*/export const OBSERVATION_ORIGIN_PARAM = 'from'export const WATCH_FEED_ORIGIN = 'watch'+export const RECORDING_ORIGIN = 'recording'+export const POSTHOG_AI_ORIGIN = 'ai'+/** The in-app page the reader left, such as a playlist or the scene a PostHog AI side panel was open over. */+export const OBSERVATION_RETURN_PATH_PARAM = 'return_to'++export type ReturnOrigin = typeof RECORDING_ORIGIN | typeof POSTHOG_AI_ORIGIN++const OBSERVATION_ORIGINS: readonly string[] = [WATCH_FEED_ORIGIN, RECORDING_ORIGIN, POSTHOG_AI_ORIGIN]++export function isObservationOrigin(value: unknown): value is string {+ return typeof value === 'string' && OBSERVATION_ORIGINS.includes(value)+}++/** Accepts only a same-origin path, so a crafted link can't point the back button at another site. */+export function safeReturnPath(value: unknown): string | null {+ return typeof value === 'string' ? getRelativeNextPath(value, window.location) : null+}++/** The current in-app path, without the project prefix, for an observation link's `return_to`. */+export function currentReturnPath(location: { pathname: string; search: string; hash: string }): string {+ // The hash matters: the player modal keeps the open recording there.+ return removeProjectIdIfPresent(location.pathname) + location.search + location.hash+}++export function observationFromOriginUrl(observationId: string, origin: ReturnOrigin, returnPath?: string): string {+ return combineUrl(urls.replayVisionObservation(observationId), {+ [OBSERVATION_ORIGIN_PARAM]: origin,+ ...(returnPath ? { [OBSERVATION_RETURN_PATH_PARAM]: returnPath } : {}),+ }).url+}/** The crumb the back button returns to for an observation opened from the "What to watch" feed. */export function watchFeedBreadcrumb(): Breadcrumb {