Skip to content

: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.

fix(replay-vision): configure test account filters without leaving the wizard (#80147)

coryslater6b9a4e6a1ff6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 38f2a4e9d405..fb6f0aa1a136 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8712,6 +8712,10 @@ snapshots:
hash: v1.k794b7964.adcd33918c09bfe0779ee7a51b77ee173de0cdd74d66300ea01d173280068d48.ib0BfEMTsMIEACC9iavsKKP4h8jNle7YTt9dvkkw4-o
scenes-app-replay-vision--usage-tab--light:
hash: v1.k794b7964.7b90e21b832f5814c53519accdedab8896288bc69795b4d5e1e7b1b1bfee0de4.piIPzkfkOn_qr72FuSJWIOwB8VcVKZg6ryIg44FdsoI
+ scenes-app-replay-vision-test-account-filter-settings-dialog--default--dark:
+ hash: v1.k794b7964.57289f977a42e43a6b70a0718959bc995a7a45245b20fda636e880beec7cc2e8.2CONzn8joR8LZgN9VOcNokIFUUJmtzE-TJTbprVGmt8
+ scenes-app-replay-vision-test-account-filter-settings-dialog--default--light:
+ hash: v1.k794b7964.8276936411550e5ab99aa3d216a442c6328a55434a4bcf273cbef46a39d940b4.asrT7Nd6P9HVchxOoJPfMOOttbQVP6XFXptRAtnXC3k
scenes-app-saved-insights--empty-state--dark:
hash: v1.k794b7964.43545664c9133c8afd354be6a6ed8f808c35b381101325d9605114632fcdc0c9.l8w9uEOEmrH6Xl1kNd9ueRtg_51cJUSjWLdjWDM0Fko
scenes-app-saved-insights--empty-state--light:
diff --git a/frontend/src/lib/components/TestAccountFiltersSwitch.test.tsx b/frontend/src/lib/components/TestAccountFiltersSwitch.test.tsx
index 9c3852b3b5b6..b44265c675ba 100644
--- a/frontend/src/lib/components/TestAccountFiltersSwitch.test.tsx
+++ b/frontend/src/lib/components/TestAccountFiltersSwitch.test.tsx
@@ -1,6 +1,7 @@
import '@testing-library/jest-dom'
import { cleanup, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -27,6 +28,21 @@ describe('TestAccountFilterSwitch', () => {
const gear = screen.getByRole('link')
expect(gear.getAttribute('href')).toMatch(/\/settings\/environment-customization#internal-user-filtering$/)
})
+
+ it('calls onConfigure instead of navigating, and leaves the switch alone', async () => {
+ const onConfigure = jest.fn()
+ const onChange = jest.fn()
+ render(<TestAccountFilterSwitch checked={false} onChange={onChange} onConfigure={onConfigure} />)
+
+ // No link at all: callers that hold unsaved state must not be navigated away from it.
+ expect(screen.queryByRole('link')).not.toBeInTheDocument()
+
+ await userEvent.click(screen.getByRole('button'))
+
+ expect(onConfigure).toHaveBeenCalledTimes(1)
+ // Opening settings must never double as flipping the filter.
+ expect(onChange).not.toHaveBeenCalled()
+ })
})
describe('getUnusedTestAccountFilterReason', () => {
diff --git a/frontend/src/lib/components/TestAccountFiltersSwitch.tsx b/frontend/src/lib/components/TestAccountFiltersSwitch.tsx
index cfd3e610eefe..75ad4849a73c 100644
--- a/frontend/src/lib/components/TestAccountFiltersSwitch.tsx
+++ b/frontend/src/lib/components/TestAccountFiltersSwitch.tsx
@@ -1,4 +1,5 @@
import { useValues } from 'kea'
+import React from 'react'
import { IconGear } from '@posthog/icons'
import { LemonButton, LemonSwitch, LemonSwitchProps } from '@posthog/lemon-ui'
@@ -34,12 +35,16 @@ type TestAccountFilterProps = Partial<LemonSwitchProps> & {
/** When set, the toggle is disabled with an explanatory reason unless the team has at least one
* test account filter of one of these types. Omit to accept every filter type (events etc.). */
applicableFilterTypes?: string[]
+ /** Runs instead of navigating to project settings when the gear is clicked. Surfaces that hold
+ * unsaved state, such as a wizard step, use this to configure the filters without leaving. */
+ onConfigure?: () => void
}
export function TestAccountFilterSwitch({
checked,
onChange,
applicableFilterTypes,
+ onConfigure,
...props
}: TestAccountFilterProps): JSX.Element | null {
const { currentTeam } = useValues(teamLogic)
@@ -61,18 +66,32 @@ export function TestAccountFilterSwitch({
label={
<div className="flex items-center">
<span>Filter out internal and test users</span>
- {/* Opens in a new tab: this switch sits inside forms that hold unsaved work (a
+ {/* Opens in a new tab by default: this switch sits inside forms that hold unsaved work (a
half-built scanner, an unsaved cohort, an insight in progress), and the
- disabledReason below actively sends people here when no filters are set up. */}
+ disabledReason below actively sends people here when no filters are set up.
+ Callers that can configure the filters in place pass onConfigure instead. */}
<LemonButton
icon={<IconGear />}
size="small"
noPadding
className="ml-1"
- to={urls.settings('environment-customization', 'internal-user-filtering')}
- targetBlank
- hideExternalLinkIcon
- tooltip="Configure internal and test users. Opens in a new tab."
+ {...(onConfigure
+ ? {
+ // The gear sits inside the switch's <label htmlFor>, which forwards clicks to the
+ // switch button. Stop it here so opening settings can't also flip the filter.
+ onClick: (e: React.MouseEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+ onConfigure()
+ },
+ tooltip: 'Configure internal and test users.',
+ }
+ : {
+ to: urls.settings('environment-customization', 'internal-user-filtering'),
+ targetBlank: true,
+ hideExternalLinkIcon: true,
+ tooltip: 'Configure internal and test users. Opens in a new tab.',
+ })}
/>
</div>
}
diff --git a/frontend/src/scenes/teamLogic.test.ts b/frontend/src/scenes/teamLogic.test.ts
index 45f0e7ca1998..894746fc02c0 100644
--- a/frontend/src/scenes/teamLogic.test.ts
+++ b/frontend/src/scenes/teamLogic.test.ts
@@ -29,6 +29,32 @@ describe('teamLogic', () => {
await expectLogic(logic).toDispatchActions(['loadCurrentTeamSuccess'])
expect(logic.values.currentProjectId).toBe(MOCK_DEFAULT_TEAM.project_id)
})
+
+ const refreshedFilters = [{ key: 'email', type: 'person', value: 'example.com', operator: 'not_icontains' }]
+ it.each([
+ ['the same team', MOCK_TEAM_ID, refreshedFilters],
+ ['a different team', MOCK_TEAM_ID + 1, MOCK_DEFAULT_TEAM.test_account_filters],
+ ])('refreshCurrentTeam takes a response for %s without a team reload', async (_, id, expectedFilters) => {
+ await expectLogic(logic).toDispatchActions(['loadCurrentTeamSuccess'])
+ useMocks({
+ get: {
+ '/api/environments/@current': () => [
+ 200,
+ { ...MOCK_DEFAULT_TEAM, id, test_account_filters: refreshedFilters },
+ ],
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.refreshCurrentTeam()
+ })
+ .toFinishAllListeners()
+ .toNotHaveDispatchedActions(['loadCurrentTeamSuccess'])
+ .toDispatchActions(['refreshCurrentTeamSuccess'])
+
+ expect(logic.values.currentTeam?.id).toBe(MOCK_TEAM_ID)
+ expect(logic.values.currentTeam?.test_account_filters).toEqual(expectedFilters)
+ })
})
describe('updateCurrentTeam with a name-only payload', () => {
diff --git a/frontend/src/scenes/teamLogic.tsx b/frontend/src/scenes/teamLogic.tsx
index 5773a0daf084..549c77398f46 100644
--- a/frontend/src/scenes/teamLogic.tsx
+++ b/frontend/src/scenes/teamLogic.tsx
@@ -252,6 +252,21 @@ export interface teamLogicActions {
currentTeam: TeamPublicType | TeamType | null
payload?: ProductOnboardingCompleteProperties
}
+ refreshCurrentTeam: () => any
+ refreshCurrentTeamFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ refreshCurrentTeamSuccess: (
+ currentTeam: TeamPublicType | TeamType | null,
+ payload?: any
+ ) => {
+ currentTeam: TeamPublicType | TeamType | null
+ payload?: any
+ }
resetToken: () => any
resetTokenFailure: (
error: string,
@@ -372,6 +387,14 @@ export const teamLogic = kea<teamLogicType>([
return values.currentTeam
}
},
+ refreshCurrentTeam: async () => {
+ try {
+ const team = await api.get('api/environments/@current')
+ return team?.id === values.currentTeam?.id ? team : values.currentTeam
+ } catch {
+ return values.currentTeam
+ }
+ },
updateCurrentTeam: async (payload: Partial<TeamType>, breakpoint) => {
if (!values.currentTeam) {
throw new Error('Current team has not been loaded yet, so it cannot be updated!')
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
index 9bdfe74e512e..9dad89096594 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
@@ -10,6 +10,7 @@ import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/util
import { FEATURE_FLAGS } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonDialog, LemonDialogProps } from 'lib/lemon-ui/LemonDialog'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
import { Link } from 'lib/lemon-ui/Link'
@@ -24,6 +25,7 @@ import {
} from 'scenes/session-recordings/filters/recordingsQueryConversions'
import { RecordingsUniversalFilterAddFilterPopover } from 'scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed'
import { defaultRecordingDurationFilter } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
+import { Settings } from 'scenes/settings/Settings'
import { urls } from 'scenes/urls'
import { groupsModel } from '~/models/groupsModel'
@@ -34,6 +36,30 @@ import { PropertyFilterType, RecordingUniversalFilters, UniversalFiltersGroup }
import { clampDurationFilter, durationFilterError, MAX_ACTIVE_LABEL } from '../durationBounds'
import { replayScannerLogic } from '../replayScannerLogic'
+// The wizard holds an unsaved draft, so sending someone to the settings scene to define their test
+// account filters drops them out of the flow they were told to fix. Configure them in place instead.
+// Exported so the story can snapshot the exact dialog the wizard opens.
+export function testAccountFilterSettingsDialogProps(): LemonDialogProps {
+ return {
+ title: 'Filter out internal and test users',
+ width: '40rem',
+ content: (
+ <Settings
+ logicKey="replay-vision-internal-user-filtering"
+ sectionId="environment-customization"
+ settingId="internal-user-filtering"
+ hideSections
+ handleLocally
+ />
+ ),
+ primaryButton: { children: 'Done' },
+ }
+}
+
+function openTestAccountFilterSettings(): void {
+ LemonDialog.open(testAccountFilterSettingsDialogProps())
+}
+
// Mirrors the recordings list taxonomy, including suggested filters so the search bar surfaces them.
// Group properties are appended per-project from groupsModel (see scannerFilterTypes below).
const SCANNER_BASE_FILTER_TYPES: TaxonomicFilterGroupType[] = [
@@ -204,6 +230,7 @@ export function ScannerTriggers({ scannerId }: { scannerId: string }): JSX.Eleme
onChange={(checked) =>
applyUniversal({ ...universal, filter_test_accounts: checked })
}
+ onConfigure={openTestAccountFilterSettings}
/>
</div>
{/* -ml-2 cancels AndOrFilterSelect's built-in prefix indent so "Match" left-aligns with the rest. */}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggersSettingsDialog.stories.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggersSettingsDialog.stories.tsx
new file mode 100644
index 000000000000..23ba14562e4a
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggersSettingsDialog.stories.tsx
@@ -0,0 +1,37 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { mswDecorator } from '~/mocks/browser'
+import preflightJson from '~/mocks/fixtures/_preflight.json'
+
+import { testAccountFilterSettingsDialogProps } from './ScannerTriggers'
+
+// The scanner wizard opens the internal-user-filtering setting in a dialog instead of navigating
+// to project settings, so the unsaved draft stays mounted. This snapshots that dialog.
+const meta: Meta<typeof LemonDialog> = {
+ title: 'Scenes-App/Replay Vision/Test Account Filter Settings Dialog',
+ component: LemonDialog,
+ parameters: {
+ layout: 'centered',
+ mockDate: '2023-05-25',
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/_preflight': {
+ ...preflightJson,
+ cloud: true,
+ realm: 'cloud',
+ },
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof LemonDialog>
+
+export const Default: Story = {
+ render: () => <LemonDialog {...testAccountFilterSettingsDialogProps()} inline />,
+}
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index 8c3a0cfce745..194ff7f148b9 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -1,4 +1,4 @@
-import { MOCK_TEAM_ID } from 'lib/api.mock'
+import { MOCK_DEFAULT_TEAM, MOCK_TEAM_ID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
@@ -1518,4 +1518,32 @@ describe('replayScannerLogic', () => {
expect(logic.values.experimentContext).toBeNull()
})
})
+
+ describe('team refresh on tab visibility', () => {
+ const setHidden = (hidden: boolean): void => {
+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })
+ document.dispatchEvent(new Event('visibilitychange'))
+ }
+ let teamSpy: jest.Mock
+
+ beforeEach(() => {
+ teamSpy = jest.fn(() => [200, MOCK_DEFAULT_TEAM])
+ useMocks({ get: { '/api/environments/@current': teamSpy } })
+ teamLogic.mount()
+ })
+
+ afterEach(() => {
+ setHidden(false)
+ })
+
+ it('refetches the team when the tab becomes visible again, not on mount', async () => {
+ expect(teamSpy).not.toHaveBeenCalled()
+
+ setHidden(true)
+ setHidden(false)
+ await expectLogic(teamLogic).toDispatchActions(['refreshCurrentTeamSuccess'])
+
+ expect(teamSpy).toHaveBeenCalledTimes(1)
+ })
+ })
})
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 8b740ad98df2..394261480b3c 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -2305,6 +2305,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
actions.loadObservations()
actions.loadObservationStats()
}
+ // Setup re-runs when the tab becomes visible
+ cache.disposables.add(() => {
+ if (cache.teamRefreshArmed && !teamLogic.values.currentTeamLoading) {
+ teamLogic.actions.refreshCurrentTeam()
+ }
+ cache.teamRefreshArmed = true
+ return () => {}
+ }, 'refreshTeamOnVisible')
}),
beforeUnmount(({ values, props, cache }) => {