: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(signals): persist scout roster filters in the URL (#87575)
posthog[bot]68b0327de009
diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.tsindex d6dcc77c055a..bd90198e8762 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts@@ -6,6 +6,7 @@ import posthog from 'posthog-js'import { organizationLogic } from 'scenes/organizationLogic'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'@@ -291,7 +292,7 @@ describe('scoutFleetLogic', () => {expect(mockSignalsScoutChatTasksCreate).not.toHaveBeenCalled()})- it('reports roster filtering without leaking the search term', async () => {+ it('reports roster filtering with the search length, not the term', async () => {jest.useFakeTimers()try {const capture = posthog.capture as jest.Mock@@ -321,6 +322,181 @@ describe('scoutFleetLogic', () => {}})+ it('drops the delayed search write when the user navigates before the debounce settles', async () => {+ jest.useFakeTimers()+ try {+ router.actions.push(urls.inbox('scouts'))+ logic.actions.setScoutSearch('rev')+ // Open a scout's detail before the debounce elapses; the roster logic stays mounted beside it.+ router.actions.push(urls.inboxScout('signals-scout-revenue'))+ await jest.advanceTimersByTimeAsync(600)++ // The stale roster filter must not land on the detail route it does not own.+ expect(router.values.location.pathname).toContain('signals-scout-revenue')+ expect(router.values.searchParams.scoutSearch).toBeUndefined()+ } finally {+ jest.useRealTimers()+ }+ })++ it('writes non-default roster filters to the URL and keeps the bare view clean', async () => {+ jest.useFakeTimers()+ try {+ // The URL only carries tags the fleet still uses, so the roster needs a scout wearing one.+ logic.actions.loadScoutConfigsSuccess([{ ...BASE_CONFIG, tags: ['revenue'] }])+ logic.actions.setScoutEnabledFilter('disabled')+ logic.actions.setScoutTagFilter(['revenue'])+ logic.actions.setScoutSearch('rev')+ // The search param is written on a debounce, so let its pause elapse.+ await jest.advanceTimersByTimeAsync(600)++ expect(router.values.searchParams).toMatchObject({+ scoutEnabled: 'disabled',+ scoutTags: 'revenue',+ scoutSearch: 'rev',+ })++ logic.actions.setScoutEnabledFilter('all')+ logic.actions.setScoutTagFilter([])+ logic.actions.setScoutSearch('')+ await jest.advanceTimersByTimeAsync(600)++ expect(router.values.searchParams.scoutEnabled).toBeUndefined()+ expect(router.values.searchParams.scoutTags).toBeUndefined()+ expect(router.values.searchParams.scoutSearch).toBeUndefined()+ } finally {+ jest.useRealTimers()+ }+ })++ it('restores roster filters from a shared URL', async () => {+ router.actions.push(urls.inbox('scouts'), {+ scoutEnabled: 'enabled',+ scoutTags: 'revenue,on-call',+ scoutSearch: 'rev',+ })+ await expectLogic(logic).toDispatchActions(['hydrateRosterFilters'])++ expect(logic.values.scoutEnabledFilter).toEqual('enabled')+ expect(logic.values.selectedScoutTags).toEqual(['revenue', 'on-call'])+ expect(logic.values.scoutSearch).toEqual('rev')+ })++ it('resets the roster filters when Back or Forward reaches a bare URL', async () => {+ // A filtered roster, reached by a shared link or by toggling the controls.+ router.actions.push(urls.inbox('scouts'), { scoutEnabled: 'enabled', scoutTags: 'revenue' })+ await expectLogic(logic).toDispatchActions(['hydrateRosterFilters'])+ expect(logic.values.scoutEnabledFilter).toEqual('enabled')+ expect(logic.values.selectedScoutTags).toEqual(['revenue'])++ // Back or Forward onto the bare entry arrives as a POP carrying no roster params.+ await expectLogic(logic, () => {+ router.actions.locationChanged({+ method: 'POP',+ pathname: urls.inbox('scouts'),+ search: '',+ searchParams: {},+ hash: '',+ hashParams: {},+ url: urls.inbox('scouts'),+ })+ }).toDispatchActions(['hydrateRosterFilters'])++ expect(logic.values.scoutEnabledFilter).toEqual('all')+ expect(logic.values.selectedScoutTags).toEqual([])+ expect(logic.values.scoutSearch).toEqual('')+ // The bare entry is left as-is, so a second Back still reaches the entries beneath it.+ expect(router.values.searchParams.scoutEnabled).toBeUndefined()+ expect(router.values.searchParams.scoutTags).toBeUndefined()+ })++ it('reflects a persisted filter back into a bare roster URL on fresh navigation', async () => {+ // The user filtered the roster, then opened the bare roster URL afresh (a PUSH, not Back).+ router.actions.push(urls.inbox('scouts'), { scoutEnabled: 'enabled' })+ await expectLogic(logic).toDispatchActions(['hydrateRosterFilters'])+ expect(logic.values.scoutEnabledFilter).toEqual('enabled')++ router.actions.push(urls.inbox('scouts'))+ await expectLogic(logic).toFinishAllListeners()++ // The filter persists and is written back so the restored view stays shareable.+ expect(logic.values.scoutEnabledFilter).toEqual('enabled')+ expect(router.values.searchParams.scoutEnabled).toEqual('enabled')+ })++ it('drops a typed search that a URL hydration has already replaced', async () => {+ jest.useFakeTimers()+ try {+ const capture = posthog.capture as jest.Mock+ router.actions.push(urls.inbox('scouts'))+ logic.actions.setScoutSearch('reve')+ capture.mockClear()++ // A shared link or Back reaches the same route with a different search before the+ // debounce settles. Hydration does not abort the breakpoint, so the stale query must+ // not report itself or write itself back over the hydrated URL.+ router.actions.push(urls.inbox('scouts'), { scoutSearch: 'rev' })+ await jest.advanceTimersByTimeAsync(600)++ expect(capture.mock.calls.filter(([event]) => event === 'Scout action')).toEqual([])+ expect(router.values.searchParams.scoutSearch).toEqual('rev')+ } finally {+ jest.useRealTimers()+ }+ })++ it('keeps the roster filters out of a bare URL that a sibling logic replaces', async () => {+ router.actions.push(urls.inbox('scouts'), { scoutEnabled: 'enabled' })+ await expectLogic(logic).toDispatchActions(['hydrateRosterFilters'])++ // A sibling inbox logic restores its own params by replacing the bare URL, which happens+ // while a Back onto that bare entry is still being handled.+ await expectLogic(logic, () => {+ router.actions.locationChanged({+ method: 'REPLACE',+ pathname: urls.inbox('scouts'),+ search: '?scope=all',+ searchParams: { scope: 'all' },+ hash: '',+ hashParams: {},+ url: `${urls.inbox('scouts')}?scope=all`,+ })+ }).toFinishAllListeners()++ // Riding along here would leave the URL filtered once the Back resets the controls.+ expect(router.values.searchParams.scoutEnabled).toBeUndefined()+ })++ it('restores a search that the router parsed as a number', async () => {+ // Opening the link parses the query string, and kea-router turns `scoutSearch=123` into the+ // number 123, which a string-only read drops.+ router.actions.push(`${urls.inbox('scouts')}?scoutSearch=123`)+ await expectLogic(logic).toDispatchActions(['hydrateRosterFilters'])++ expect(logic.values.scoutSearch).toEqual('123')+ })++ it('drops a tag from the URL once no scout uses it', async () => {+ jest.useFakeTimers()+ try {+ const revenueScout = { ...BASE_CONFIG, tags: ['revenue'] }+ logic.actions.loadScoutConfigsSuccess([revenueScout])+ logic.actions.setScoutTagFilter(['revenue'])+ expect(router.values.searchParams.scoutTags).toEqual('revenue')++ // Retagging the last scout empties the tag control, so the roster is visibly unfiltered.+ // A URL that still carries the tag would re-filter on refresh if the tag came back.+ logic.actions.patchScoutConfigLocally(revenueScout.id, { tags: [] })+ logic.actions.setScoutSearch('rev')+ await jest.advanceTimersByTimeAsync(600)++ expect(logic.values.activeScoutTags).toEqual([])+ expect(router.values.searchParams.scoutTags).toBeUndefined()+ } finally {+ jest.useRealTimers()+ }+ })+it('resets the in-flight chat type when the kickoff fails', async () => {mockSignalsScoutChatTasksCreate.mockRejectedValue(new Error('over the usage limit'))diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.tsindex 7163fa3e6fa8..dc4dff022342 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts@@ -1,6 +1,6 @@import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import { router } from 'kea-router'+import { actionToUrl, router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'@@ -93,6 +93,79 @@ const RUNS_REFETCH_INTERVAL_MS = 60_000const RUNS_PAGE_LIMIT = 100const MAX_RUNS_PAGES = 15+// Roster filter state also lives in the URL so a filtered view survives a refresh and is shareable.+// The search param is written on this debounce, so typing does not rewrite the URL per keystroke.+const ROSTER_SEARCH_DEBOUNCE_MS = 600++interface RosterFilterState {+ scoutSearch: string+ scoutEnabledFilter: ScoutEnabledFilter+ selectedScoutTags: string[]+}++// Merge the roster filters into `base`, writing only params that differ from the default so the bare+// `/inbox/scouts` URL stays clean.+function rosterFilterSearchParams(base: Record<string, any>, filters: RosterFilterState): Record<string, any> {+ const params = { ...base }+ const search = filters.scoutSearch.trim()+ if (search) {+ params.scoutSearch = search+ } else {+ delete params.scoutSearch+ }+ if (filters.scoutEnabledFilter !== 'all') {+ params.scoutEnabled = filters.scoutEnabledFilter+ } else {+ delete params.scoutEnabled+ }+ if (filters.selectedScoutTags.length > 0) {+ params.scoutTags = filters.selectedScoutTags.join(',')+ } else {+ delete params.scoutTags+ }+ return params+}++// kea-router parses `?scoutSearch=123` into a number and `?scoutSearch=true` into a boolean, so a+// string-only check would drop searches and tags that a person can type. Read a scalar back as the+// text it came from, and reject the array and object forms, which no roster param ever takes.+function readTextParam(value: unknown): string {+ if (typeof value === 'string') {+ return value+ }+ if (typeof value === 'number' || typeof value === 'boolean') {+ return String(value)+ }+ return ''+}++function parseRosterFilterSearchParams(searchParams: Record<string, any>): RosterFilterState {+ const tags = readTextParam(searchParams.scoutTags)+ return {+ scoutSearch: readTextParam(searchParams.scoutSearch),+ scoutEnabledFilter:+ searchParams.scoutEnabled === 'enabled' || searchParams.scoutEnabled === 'disabled'+ ? searchParams.scoutEnabled+ : 'all',+ selectedScoutTags: tags ? tags.split(',').filter(Boolean) : [],+ }+}++// The URL mirrors what the tag control shows, and that control only lists tags the fleet still uses.+// Until the configs load there is nothing to check a selection against, so the raw selection stands+// and a shared link keeps its tags.+function rosterFilterUrlState(values: scoutFleetLogicValues): RosterFilterState {+ return {+ scoutSearch: values.scoutSearch,+ scoutEnabledFilter: values.scoutEnabledFilter,+ selectedScoutTags: values.scoutConfigs === null ? values.selectedScoutTags : values.activeScoutTags,+ }+}++function sameTags(a: string[], b: string[]): boolean {+ return a.length === b.length && a.every((tag, index) => tag === b[index])+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scoutFleetLogicValues {dataProcessingAccepted: boolean // aiConsentLogic@@ -153,6 +226,15 @@ export interface scoutFleetLogicActions {deleteScoutFinished: (configId: string) => {configId: string}+ hydrateRosterFilters: (+ search: string,+ filter: ScoutEnabledFilter,+ tags: string[]+ ) => {+ filter: ScoutEnabledFilter+ search: string+ tags: string[]+ }loadFleetFindingsSummary: () => anyloadFleetFindingsSummaryFailure: (error: string,@@ -367,6 +449,13 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([setScoutSearch: (search: string) => ({ search }),setRosterEvaluatedAt: (evaluatedAt: number) => ({ evaluatedAt }),setScoutEnabledFilter: (filter: ScoutEnabledFilter) => ({ filter }),+ // Bulk-applies the roster filters from the URL. Kept out of `actionToUrl` so hydrating from a+ // link does not echo the same URL back as a fresh history entry.+ hydrateRosterFilters: (search: string, filter: ScoutEnabledFilter, tags: string[]) => ({+ search,+ filter,+ tags,+ }),runScoutNow: (configId: string) => ({ configId }),runScoutNowFinished: (configId: string) => ({ configId }),// Started/stopped by the fleet-list component so the always-mounted setup widget@@ -534,18 +623,21 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([[] as string[],{setScoutTagFilter: (_, { tags }) => tags,+ hydrateRosterFilters: (_, { tags }) => tags,},],scoutSearch: ['',{setScoutSearch: (_, { search }) => search,+ hydrateRosterFilters: (_, { search }) => search,},],scoutEnabledFilter: ['all' as ScoutEnabledFilter,{setScoutEnabledFilter: (_, { filter }) => filter,+ hydrateRosterFilters: (_, { filter }) => filter,},],rosterEvaluatedAt: [@@ -769,14 +861,35 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([extra: { filter, filter_match_count: values.rosterScouts.length },})},- // Debounced so a typed query fires once per pause, not per keystroke; clearing fires nothing.- // The term itself is not sent — it can name a customer's own scouts — only its length.+ // Debounced so a burst of keystrokes settles once, on pause. The URL is rewritten through+ // `replace`, so Back does not step through every partial query. Analytics ride the same pause:+ // a typed query reports once, clearing reports nothing. The event payload carries only the+ // length, not the term. That is no longer a privacy boundary: the term is in the URL, so+ // `$current_url` carries it on this event and on every later one from the same page.setScoutSearch: async ({ search }, breakpoint) => {+ const searchedPathname = router.values.location.pathname+ await breakpoint(ROSTER_SEARCH_DEBOUNCE_MS)+ // Hydrating from the URL replaces the search without aborting this breakpoint, so the+ // typed query can be stale by now. Drop it: the hydrated search owns the URL, and+ // reporting the abandoned query here would pair its length with the new match count.+ if (values.scoutSearch !== search) {+ return+ }+ // The logic stays mounted across a master-detail navigation, so the breakpoint does not+ // abort on a same-scene route change. Only write the roster filter if the user is still on+ // the route they searched from — otherwise the delayed write lands a roster param on a+ // route it does not own (e.g. an open scout's detail URL).+ if (router.values.location.pathname === searchedPathname) {+ router.actions.replace(+ router.values.location.pathname,+ rosterFilterSearchParams(router.values.searchParams, rosterFilterUrlState(values)),+ router.values.hashParams+ )+ }const query = search.trim()if (!query) {return}- await breakpoint(600)captureScoutAction({actionType: 'search_scouts',surface: 'fleet_list',@@ -1020,6 +1133,79 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([},})),+ // Enabled and tag filters push, so Back and Forward step through them. Search is written by its+ // own debounced listener via `replace`, so it is not registered here.+ actionToUrl(({ values }) => {+ const toUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => [+ router.values.location.pathname,+ rosterFilterSearchParams(router.values.searchParams, rosterFilterUrlState(values)),+ router.values.hashParams,+ { replace: false },+ ]+ return {+ setScoutEnabledFilter: toUrl,+ setScoutTagFilter: toUrl,+ }+ }),++ urlToAction(({ actions, values }) => {+ const applyFromUrl = (+ _: unknown,+ searchParams: Record<string, any>,+ __: unknown,+ { method }: { method: 'PUSH' | 'REPLACE' | 'POP' }+ ): void => {+ const hasRosterParams =+ 'scoutSearch' in searchParams || 'scoutEnabled' in searchParams || 'scoutTags' in searchParams+ if (!hasRosterParams) {+ // Back or Forward onto a bare roster URL asks for the default, unfiltered view: reset+ // the filters and leave the URL bare so a second Back can still reach the entries+ // beneath it. Reflecting the persisted filters back here would undo the navigation.+ if (method === 'POP') {+ if (+ values.scoutSearch !== '' ||+ values.scoutEnabledFilter !== 'all' ||+ values.selectedScoutTags.length > 0+ ) {+ actions.hydrateRosterFilters('', 'all', [])+ }+ return+ }+ // Only a fresh navigation reflects the persisted filters back, so the current view+ // is immediately shareable. A replace is not a navigation: a sibling inbox logic+ // replaces the bare URL to restore its own params while a Back is still being+ // handled, and writing the roster filters there would leave the URL filtered after+ // that Back resets the controls.+ if (method !== 'PUSH') {+ return+ }+ const desired = rosterFilterSearchParams({}, rosterFilterUrlState(values))+ if (Object.keys(desired).length > 0) {+ router.actions.replace(+ router.values.location.pathname,+ { ...router.values.searchParams, ...desired },+ router.values.hashParams+ )+ }+ return+ }+ // A shared link is authoritative: apply what it carries and reset the rest to defaults.+ // Guarded so plain navigation onto the roster does not re-dispatch an unchanged state.+ const parsed = parseRosterFilterSearchParams(searchParams)+ if (+ parsed.scoutSearch === values.scoutSearch &&+ parsed.scoutEnabledFilter === values.scoutEnabledFilter &&+ sameTags(parsed.selectedScoutTags, values.selectedScoutTags)+ ) {+ return+ }+ actions.hydrateRosterFilters(parsed.scoutSearch, parsed.scoutEnabledFilter, parsed.selectedScoutTags)+ }+ return {+ [urls.inbox('scouts')]: applyFromUrl,+ }+ }),+events(({ actions }) => ({afterMount: () => {// Configs are cheap and the always-mounted setup widget needs them. The paginated