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.

feat(conversations): sync support ticket filters to URL query params (#72398)

Radu Raicea27481d4a1a86
diff --git a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts
index 1cf114828ee6..73cd2de2661b 100644
--- a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts
+++ b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts
@@ -1,13 +1,38 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { urls } from 'scenes/urls'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { MAX_ASSIGNEE_FILTER_ENTRIES } from '../../components/Assignee'
-import { normalizeAssigneeFilter } from '../../types'
+import { normalizeAssigneeFilter, type SavedTicketView, type TicketViewFilters } from '../../types'
import { supportTicketsSceneLogic } from './supportTicketsSceneLogic'
+function makeSavedView(shortId: string, filters: TicketViewFilters = {}): SavedTicketView {
+ return {
+ id: shortId,
+ short_id: shortId,
+ name: `View ${shortId}`,
+ filters,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ is_favorited: false,
+ }
+}
+
+async function waitUntilPending(pending: Record<string, unknown>, shortId: string): Promise<void> {
+ for (let i = 0; i < 20 && !pending[shortId]; i++) {
+ await Promise.resolve()
+ }
+}
+
describe('supportTicketsSceneLogic', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ })
+
describe('normalizeAssigneeFilter', () => {
it.each([
['legacy "all"', 'all', []],
@@ -70,4 +95,127 @@ describe('supportTicketsSceneLogic', () => {
expect(lastAssigneeParam).toBe('unassigned')
})
})
+
+ describe('URL sync', () => {
+ let logic: ReturnType<typeof supportTicketsSceneLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/conversations/tickets/': () => [200, { count: 0, results: [] }],
+ '/api/projects/:team_id/conversations/views/:short_id/': () => [404, { detail: 'Not found' }],
+ },
+ })
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('writes active filters to the URL so links are shareable', async () => {
+ router.actions.push(urls.supportTickets())
+ logic = supportTicketsSceneLogic()
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.setStatusFilter(['open', 'new'])
+ logic.actions.setChannelFilter('slack')
+ logic.actions.setAssigneeFilter([{ type: 'user', id: 1 }])
+ logic.actions.setSorting({ columnKey: 'created_at', order: 1 })
+ logic.actions.setSearchQuery('[email protected]')
+ }).toFinishAllListeners()
+
+ expect(router.values.searchParams.status).toEqual(['open', 'new'])
+ expect(router.values.searchParams.channel).toBe('slack')
+ expect(router.values.searchParams.assignee).toEqual(['user:1'])
+ expect(router.values.searchParams.order_by).toBe('created_at')
+ expect(router.values.searchParams.search).toBeUndefined()
+ })
+
+ it('applies shareable filters from the URL but removes free-text search', async () => {
+ router.actions.push(urls.supportTickets(), {
+ status: ['pending'],
+ channel: 'email',
+ order_by: 'created_at',
+ assignee: ['unassigned'],
+ search: '[email protected]',
+ })
+ logic = supportTicketsSceneLogic()
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.statusFilter).toEqual(['pending'])
+ expect(logic.values.channelFilter).toBe('email')
+ expect(logic.values.sorting).toEqual({ columnKey: 'created_at', order: 1 })
+ expect(logic.values.assigneeFilterEntries).toEqual(['unassigned'])
+ expect(logic.values.searchQuery).toBe('')
+ expect(router.values.searchParams.search).toBeUndefined()
+ })
+
+ it('detaches an active view when the URL changes to explicit filters', async () => {
+ router.actions.push(urls.supportTickets())
+ logic = supportTicketsSceneLogic()
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.applyView(makeSavedView('view-a', { status: ['open'], dateFrom: '-24h' }))
+ }).toFinishAllListeners()
+
+ router.actions.push(urls.supportTickets(), { status: ['pending'] })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.activeView).toBeNull()
+ expect(logic.values.statusFilter).toEqual(['pending'])
+ expect(logic.values.dateFrom).toBe('-7d')
+ expect(router.values.searchParams).toMatchObject({ status: ['pending'] })
+ expect(router.values.searchParams.view).toBeUndefined()
+ })
+
+ it('ignores a saved view response after navigating to explicit filters', async () => {
+ const pending: Record<string, { resolve: (view: SavedTicketView) => void }> = {}
+ useMocks({
+ get: {
+ '/api/projects/:team_id/conversations/views/:short_id/': ({ request }) => {
+ const pathParts = new URL(request.url).pathname.split('/')
+ const shortId = pathParts[pathParts.length - 2]
+ return new Promise((resolve) => {
+ pending[shortId] = { resolve: (view) => resolve([200, view]) }
+ })
+ },
+ },
+ })
+ router.actions.push(urls.supportTickets(), { view: 'view-a' })
+ logic = supportTicketsSceneLogic()
+ logic.mount()
+ await waitUntilPending(pending, 'view-a')
+
+ router.actions.push(urls.supportTickets(), { status: ['pending'] })
+ pending['view-a'].resolve(makeSavedView('view-a', { status: ['open'] }))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.activeView).toBeNull()
+ expect(logic.values.statusFilter).toEqual(['pending'])
+ expect(router.values.searchParams).toMatchObject({ status: ['pending'] })
+ expect(router.values.searchParams.view).toBeUndefined()
+ })
+
+ it('resets stale view filters when a linked view is missing', async () => {
+ router.actions.push(urls.supportTickets())
+ logic = supportTicketsSceneLogic()
+ logic.mount()
+ await expectLogic(logic, () => {
+ logic.actions.applyView(makeSavedView('view-a', { status: ['open'], dateFrom: '-24h' }))
+ }).toFinishAllListeners()
+
+ router.actions.push(urls.supportTickets(), { view: 'deadbeef' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.activeView).toBeNull()
+ expect(logic.values.statusFilter).toEqual([])
+ expect(logic.values.dateFrom).toBe('-7d')
+ expect(router.values.searchParams.view).toBeUndefined()
+ })
+ })
})
diff --git a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts
index 43366c0391f9..6146fd576da6 100644
--- a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts
+++ b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts
@@ -1,14 +1,16 @@
import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
-import { router } from 'kea-router'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
+import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { TeamType } from '~/types'
+import { conversationsViewsRetrieve } from '../../generated/api'
import { normalizeAssigneeFilter } from '../../types'
import type {
AITriageFilterValue,
@@ -42,6 +44,136 @@ const DEFAULT_TICKET_FILTERS: TicketViewFilters = {
search: '',
}
+const DEFAULT_SORTING: Sorting = { columnKey: 'updated_at', order: -1 }
+const DEFAULT_ORDER_BY = '-updated_at'
+
+// Shareable ticket-filter query params. Date range stays a personal preference,
+// while free-text search stays out of URLs because it can contain customer data.
+const FILTER_URL_PARAM_KEYS = [
+ 'status',
+ 'priority',
+ 'ai_triage_result',
+ 'channel',
+ 'sla',
+ 'assignee',
+ 'tags',
+ 'tags_match',
+ 'tags_exclude',
+ 'order_by',
+] as const
+
+function sortingToOrderBy(sorting: Sorting | null | undefined): string {
+ if (!sorting) {
+ return DEFAULT_ORDER_BY
+ }
+ return `${sorting.order === 1 ? '' : '-'}${sorting.columnKey}`
+}
+
+function orderByToSorting(orderBy: string): Sorting {
+ return { columnKey: orderBy.replace(/^-/, ''), order: orderBy.startsWith('-') ? -1 : 1 }
+}
+
+function encodeAssigneeEntry(entry: AssigneeFilterEntry): string {
+ return entry === 'unassigned' ? 'unassigned' : `${entry.type}:${entry.id}`
+}
+
+// kea-router hands back arrays for multi-value params, but a hand-typed single
+// value can arrive as a bare string — coerce both to a string array.
+function toStringArray(value: unknown): string[] {
+ if (Array.isArray(value)) {
+ return value.map(String)
+ }
+ if (typeof value === 'string' && value !== '') {
+ return [value]
+ }
+ return []
+}
+
+function decodeAssignee(value: unknown): AssigneeFilterEntry[] {
+ const entries = toStringArray(value).map((token): AssigneeFilterEntry | null => {
+ if (token === 'unassigned') {
+ return 'unassigned'
+ }
+ const separator = token.indexOf(':')
+ const type = token.slice(0, separator)
+ const id = token.slice(separator + 1)
+ return (type === 'user' || type === 'role') && id ? { type, id } : null
+ })
+ return normalizeAssigneeFilter(entries.filter((entry): entry is AssigneeFilterEntry => entry !== null))
+}
+
+// Canonical URL representation of the filters. Only non-default values are
+// emitted so shared links stay readable.
+function filtersToUrlParams(filters: TicketViewFilters): Record<string, any> {
+ const params: Record<string, any> = {}
+ if (filters.status?.length) {
+ params.status = filters.status
+ }
+ if (filters.priority?.length) {
+ params.priority = filters.priority
+ }
+ if (filters.aiTriageResult?.length) {
+ params.ai_triage_result = filters.aiTriageResult
+ }
+ if (filters.channel && filters.channel !== 'all') {
+ params.channel = filters.channel
+ }
+ if (filters.sla && filters.sla !== 'all') {
+ params.sla = filters.sla
+ }
+ const assignee = normalizeAssigneeFilter(filters.assignee)
+ if (assignee.length) {
+ params.assignee = assignee.map(encodeAssigneeEntry)
+ }
+ if (filters.tags?.length) {
+ params.tags = filters.tags
+ if (filters.tagsMatch === 'all') {
+ params.tags_match = 'all'
+ }
+ }
+ if (filters.tagsExclude?.length) {
+ params.tags_exclude = filters.tagsExclude
+ }
+ const orderBy = sortingToOrderBy(filters.sorting)
+ if (orderBy !== DEFAULT_ORDER_BY) {
+ params.order_by = orderBy
+ }
+ return params
+}
+
+// A shared link fully determines the filter set, so params absent from the URL
+// reset to their defaults rather than keeping persisted state. Date range is
+// omitted so the recipient's own window is preserved.
+function urlParamsToFilters(searchParams: Record<string, any>): TicketViewFilters {
+ return {
+ status: toStringArray(searchParams.status) as TicketStatus[],
+ priority: toStringArray(searchParams.priority) as TicketPriority[],
+ aiTriageResult: toStringArray(searchParams.ai_triage_result) as AITriageFilterValue[],
+ channel: (searchParams.channel as TicketChannel) ?? 'all',
+ sla: (searchParams.sla as TicketSlaState) ?? 'all',
+ assignee: decodeAssignee(searchParams.assignee),
+ tags: toStringArray(searchParams.tags),
+ tagsMatch: searchParams.tags_match === 'all' ? 'all' : 'any',
+ tagsExclude: toStringArray(searchParams.tags_exclude),
+ search: '',
+ sorting: searchParams.order_by ? orderByToSorting(String(searchParams.order_by)) : { ...DEFAULT_SORTING },
+ }
+}
+
+function hasFilterParams(searchParams: Record<string, any>): boolean {
+ return FILTER_URL_PARAM_KEYS.some((paramKey) => searchParams[paramKey] !== undefined)
+}
+
+// Compare a URL against the current filters via their canonical encodings, so
+// non-canonical inputs (single-value strings, redundant defaults) don't read as
+// a difference and trigger a needless re-apply loop.
+function urlFiltersMatchState(searchParams: Record<string, any>, currentFilters: TicketViewFilters): boolean {
+ return (
+ !currentFilters.search &&
+ objectsEqual(filtersToUrlParams(urlParamsToFilters(searchParams)), filtersToUrlParams(currentFilters))
+ )
+}
+
export interface SupportTicketsSceneLogicProps {
key?: string
distinctIds?: string[]
@@ -83,6 +215,9 @@ export interface supportTicketsSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface supportTicketsSceneLogicActions {
+ applyUrlFilters: (filters: TicketViewFilters) => {
+ filters: TicketViewFilters
+ }
applyView: (view: SavedTicketView) => {
view: SavedTicketView
}
@@ -105,6 +240,9 @@ export interface supportTicketsSceneLogicActions {
clearSelectedTickets: () => {
value: true
}
+ loadSavedView: (shortId: string) => {
+ shortId: string
+ }
loadTickets: () => {
value: true
}
@@ -249,7 +387,9 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([
setTotalCount: (count: number) => ({ count }),
setTicketsLoading: (loading: boolean) => ({ loading }),
applyViewFilters: (filters: TicketViewFilters) => ({ filters }),
+ applyUrlFilters: (filters: TicketViewFilters) => ({ filters }),
applyView: (view: SavedTicketView) => ({ view }),
+ loadSavedView: (shortId: string) => ({ shortId }),
setActiveView: (view: SavedTicketView | null) => ({ view }),
clearActiveView: true,
resetFilters: true,
@@ -531,7 +671,7 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([
}),
],
}),
- listeners(({ actions, values, props }) => ({
+ listeners(({ actions, values, props, cache }) => ({
loadTickets: async (_, breakpoint) => {
await breakpoint(300)
const params: Record<string, any> = {}
@@ -591,6 +731,19 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([
applyViewFilters: () => {
actions.setCurrentPage(1)
},
+ applyUrlFilters: ({ filters }) => {
+ cache.applyingUrlFilters = true
+ cache.latestViewShortId = null
+ try {
+ actions.clearActiveView()
+ actions.applyViewFilters({
+ ...filters,
+ ...(values.dateRangeBeforeView ?? { dateFrom: values.dateFrom, dateTo: values.dateTo }),
+ })
+ } finally {
+ cache.applyingUrlFilters = false
+ }
+ },
setCurrentPage: () => {
actions.loadTickets()
},
@@ -653,6 +806,32 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([
actions.applyViewFilters(view.filters || {})
actions.setActiveView(view)
},
+ loadSavedView: async ({ shortId }) => {
+ // Track the view the URL currently names. Rapidly switching views leaves
+ // several requests in flight; only the latest one may touch state, so a
+ // slow earlier response can't clobber the view the user actually landed on.
+ cache.latestViewShortId = shortId
+ const inFlight: Set<string> = (cache.inFlightViewShortIds ??= new Set())
+ // De-dupe the concurrent afterMount + urlToAction mount triggers for the same view.
+ if (inFlight.has(shortId)) {
+ return
+ }
+ inFlight.add(shortId)
+ const teamId = teamLogic.values.currentTeamId
+ try {
+ const view = (await conversationsViewsRetrieve(String(teamId), shortId)) as unknown as SavedTicketView
+ if (cache.latestViewShortId === shortId) {
+ actions.applyView(view)
+ }
+ } catch {
+ if (cache.latestViewShortId === shortId) {
+ lemonToast.error('Failed to load saved view')
+ actions.applyUrlFilters(DEFAULT_TICKET_FILTERS)
+ }
+ } finally {
+ inFlight.delete(shortId)
+ }
+ },
resetFilters: () => {
const dateRangeBeforeView = values.dateRangeBeforeView
actions.clearActiveView()
@@ -672,19 +851,6 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([
dateTo: null,
})
},
- setActiveView: ({ view }) => {
- if (view) {
- const { searchParams } = router.values
- router.actions.replace(router.values.location.pathname, { ...searchParams, view: view.short_id })
- }
- },
- clearActiveView: () => {
- const { searchParams } = router.values
- if (searchParams.view) {
- const { view: _, ...rest } = searchParams
- router.actions.replace(router.values.location.pathname, rest)
- }
- },
bulkUpdateStatus: async ({ ids, status }) => {
actions.setBulkUpdating(true)
try {
@@ -699,22 +865,98 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([
}
},
})),
- afterMount(({ actions }) => {
+ actionToUrl(({ values, props, cache }) => {
+ const buildUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] | undefined => {
+ if (cache.applyingUrlFilters) {
+ return
+ }
+ const searchParams = { ...router.values.searchParams }
+ // Embedded instances (e.g. the person side panel) must never touch the page URL.
+ if (props.distinctIds?.length) {
+ return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
+ }
+ for (const paramKey of FILTER_URL_PARAM_KEYS) {
+ delete searchParams[paramKey]
+ }
+ delete searchParams.search
+ delete searchParams.view
+ if (values.activeView) {
+ // A saved view is a compact stand-in for its filters.
+ searchParams.view = values.activeView.short_id
+ } else {
+ Object.assign(searchParams, filtersToUrlParams(values.currentFilters))
+ }
+ return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
+ }
+ return {
+ setStatusFilter: buildUrl,
+ setPriorityFilter: buildUrl,
+ setChannelFilter: buildUrl,
+ setSlaFilter: buildUrl,
+ setAiTriageResultFilter: buildUrl,
+ setAssigneeFilter: buildUrl,
+ setTagsFilter: buildUrl,
+ setTagsMatch: buildUrl,
+ setTagsExcludeFilter: buildUrl,
+ setSorting: buildUrl,
+ setSearchQuery: buildUrl,
+ applyViewFilters: buildUrl,
+ applyUrlFilters: buildUrl,
+ setActiveView: buildUrl,
+ clearActiveView: buildUrl,
+ }
+ }),
+ urlToAction(({ actions, values, props, cache }) => ({
+ '/support/tickets': (_, searchParams) => {
+ if (props.distinctIds?.length) {
+ return
+ }
+ if (searchParams.search !== undefined) {
+ const sanitizedSearchParams = { ...searchParams }
+ delete sanitizedSearchParams.search
+ router.actions.replace(router.values.location.pathname, sanitizedSearchParams, router.values.hashParams)
+ return
+ }
+ if (searchParams.view) {
+ if (values.activeView?.short_id !== searchParams.view) {
+ actions.loadSavedView(String(searchParams.view))
+ }
+ return
+ }
+ const leavingSavedView = !!values.activeView || !!cache.latestViewShortId
+ if (
+ leavingSavedView ||
+ (hasFilterParams(searchParams) && !urlFiltersMatchState(searchParams, values.currentFilters))
+ ) {
+ actions.applyUrlFilters(urlParamsToFilters(searchParams))
+ }
+ },
+ })),
+ afterMount(({ actions, values, props }) => {
+ const embedded = !!props.distinctIds?.length
const { searchParams } = router.values
- const viewShortId = searchParams.view
- if (viewShortId) {
- const teamId = teamLogic.values.currentTeamId
- // nosemgrep: prefer-codegen-api
- api.get(`api/environments/${teamId}/conversations/views/${viewShortId}`)
- .then((view: SavedTicketView) => {
- actions.applyView(view)
- })
- .catch(() => {
- lemonToast.error('Failed to load saved view')
- actions.loadTickets()
- })
+ if (!embedded && searchParams.view) {
+ actions.loadSavedView(String(searchParams.view))
return
}
+ if (!embedded) {
+ if (hasFilterParams(searchParams)) {
+ if (!urlFiltersMatchState(searchParams, values.currentFilters)) {
+ // A shared/bookmarked link overrides the persisted selection.
+ actions.applyUrlFilters(urlParamsToFilters(searchParams))
+ return
+ }
+ } else {
+ // No filters in the URL — reflect the persisted selection so the page is shareable on open.
+ const currentFilterParams = filtersToUrlParams(values.currentFilters)
+ if (Object.keys(currentFilterParams).length > 0) {
+ router.actions.replace(router.values.location.pathname, {
+ ...searchParams,
+ ...currentFilterParams,
+ })
+ }
+ }
+ }
actions.loadTickets()
}),
])