: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(conversations): find support tickets from Cmd+K search (#95130)
Arthur Moreira de Deusd7018569e2fd
diff --git a/frontend/src/lib/components/Search/searchLogic.test.ts b/frontend/src/lib/components/Search/searchLogic.test.tsindex ed2eca64f2a8..be760fc230f7 100644--- a/frontend/src/lib/components/Search/searchLogic.test.ts+++ b/frontend/src/lib/components/Search/searchLogic.test.ts@@ -1,12 +1,25 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { searchLogic } from './searchLogic'+/** Poll until a condition holds. The searches settle in no fixed order, so an ordered+ * `toDispatchActions` list would wait on an action that had already gone past. */+const waitFor = async (condition: () => boolean, timeoutMs = 4000): Promise<void> => {+ const deadline = Date.now() + timeoutMs+ while (!condition()) {+ if (Date.now() > deadline) {+ throw new Error('Timed out waiting for the other searches to settle')+ }+ await new Promise((resolve) => setTimeout(resolve, 25))+ }+}+describe('searchLogic', () => {let logic: ReturnType<typeof searchLogic.build>let personSearchCalls: { clientQueryId?: string; signal?: AbortSignal }[]@@ -29,6 +42,7 @@ describe('searchLogic', () => {get: {'/api/environments/:team_id/search/': { results: [], counts: {} },'/api/projects/:team_id/file_system/': { results: [], count: 0 },+ '/api/projects/:team_id/conversations/tickets/': { results: [], count: 0 },},})initKeaTests()@@ -84,6 +98,120 @@ describe('searchLogic', () => {expect(logic.values.personSearchResultsLoading).toBe(true)})+ it('maps matching support tickets into their own category', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/conversations/tickets/': {+ count: 1,+ results: [+ {+ id: '01890a1b-2c3d-4e5f-8a9b-0c1d2e3f4a5b',+ ticket_number: 4321,+ status: 'on_hold',+ email_subject: 'Invoice looks wrong',+ last_message_text: 'We were charged twice',+ },+ ],+ },+ },+ })++ await expectLogic(logic, () => logic.actions.setSearch('invoice')).toDispatchActions([+ 'loadTicketSearchResultsSuccess',+ ])++ expect(logic.values.ticketItems).toEqual([+ expect.objectContaining({+ name: '#4321 Invoice looks wrong',+ category: 'tickets',+ href: urls.supportTicketDetail(4321),+ productCategory: 'On hold',+ }),+ ])+ expect(logic.values.allCategories.find((category) => category.key === 'tickets')?.items).toHaveLength(1)+ })++ // A Slack or widget ticket has no email subject, so the first message stands in as the title.+ it('falls back to the last message when a ticket has no subject', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/conversations/tickets/': {+ count: 1,+ results: [+ {+ id: '01890a1b-2c3d-4e5f-8a9b-0c1d2e3f4a5c',+ ticket_number: 77,+ status: 'open',+ email_subject: null,+ last_message_text: 'Session replay is not recording',+ },+ ],+ },+ },+ })++ await expectLogic(logic, () => logic.actions.setSearch('replay')).toDispatchActions([+ 'loadTicketSearchResultsSuccess',+ ])++ expect(logic.values.ticketItems[0].name).toBe('#77 Session replay is not recording')+ })++ // Free-text ticket search scans message content, so the palette must not send one per+ // keystroke while a query is still a letter or two long.+ it('does not search tickets until the query is long enough', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/conversations/tickets/': {+ count: 1,+ results: [{ id: 'ticket-uuid', ticket_number: 12, status: 'open', email_subject: 'Billing' }],+ },+ },+ })++ await expectLogic(logic, () => logic.actions.setSearch('bi')).toDispatchActions([+ 'loadTicketSearchResultsSuccess',+ ])+ expect(logic.values.ticketItems).toEqual([])++ await expectLogic(logic, () => logic.actions.setSearch('bill')).toDispatchActions([+ 'loadTicketSearchResultsSuccess',+ ])+ expect(logic.values.ticketItems).toHaveLength(1)+ })++ // Ticket search scans message content, so it is the slowest query in the palette and the one+ // most likely to still be in flight when the others settle. Leaving it out of `isSearching`+ // let the status line read "No results found" over a search that had not finished.+ it('still counts as searching while only tickets are in flight', async () => {+ personListMock.mockResolvedValue({ results: [] })+ // The mock team has group types, so the groups query would otherwise stay in flight and+ // hold `isSearching` true on its own, hiding the very thing under test.+ jest.spyOn(api.groups, 'listClickhouse').mockResolvedValue({ results: [], columns: [] } as any)+ useMocks({+ get: {+ '/api/projects/:team_id/conversations/tickets/': () => new Promise(() => {}),+ },+ })++ logic.actions.setSearch('billing')++ // Every other search has to have settled, or `isSearching` would be true for a reason+ // other than the one under test. They finish in no fixed order, so wait on the values.+ await waitFor(+ () =>+ !logic.values.searchPending &&+ !logic.values.searchedRecentsLoading &&+ !logic.values.unifiedSearchResultsLoading &&+ !logic.values.groupSearchResultsLoading &&+ !logic.values.personSearchResultsLoading &&+ !logic.values.playlistSearchResultsLoading+ )++ expect(logic.values.ticketSearchResultsLoading).toBe(true)+ expect(logic.values.isSearching).toBe(true)+ })+it('does not cancel a person search that already returned', async () => {personListMock.mockResolvedValue({ results: [] })diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsxindex c8e4bbe9227a..b4452bf74fb0 100644--- a/frontend/src/lib/components/Search/searchLogic.tsx+++ b/frontend/src/lib/components/Search/searchLogic.tsx@@ -15,7 +15,7 @@ import { uuid } from 'lib/utils/dom'import { GroupQueryResult, mapGroupQueryResponse } from 'lib/utils/groups'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { newInternalTab } from 'lib/utils/newInternalTab'-import { toSentenceCase } from 'lib/utils/strings'+import { capitalizeFirstLetter, toSentenceCase } from 'lib/utils/strings'import { billingLogic } from 'scenes/billing/billingLogic'import { organizationIntegrationsLogic } from 'scenes/settings/organization/organizationIntegrationsLogic'import { teamLogic } from 'scenes/teamLogic'@@ -34,6 +34,8 @@ import { getTitleText } from '~/scenes/settings/settingsSearch'import { Setting, SettingSection, SettingSectionId } from '~/scenes/settings/types'import { ActivityTab, FileSystemIconColor, GroupTypeIndex, PersonType, SearchResponse } from '~/types'+import { conversationsTicketsList } from 'products/conversations/frontend/generated/api'+import type { TicketApi } from 'products/conversations/frontend/generated/api.schemas'import { accountsList } from 'products/customer_analytics/frontend/generated/api'import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'@@ -41,7 +43,7 @@ import type { Noun } from '../../../models/groupsModel'import type { FileSystemImport } from '../../../queries/schema/schema-general'import type { GroupType, IntegrationType, UserType } from '../../../types'import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'-import { filterSearchItems } from './utils'+import { filterSearchItems, shouldSearchTickets } from './utils'let cachedProductIconColorByType: Map<string, FileSystemIconColor> | null = nulllet cachedProductDisplayLabelByPath: Map<string, string> | null = null@@ -208,6 +210,10 @@ export interface searchLogicValues {accountSearchResults: AccountApi[]accountSearchResultsLoading: booleanallCategories: SearchCategory[]+ customerItems: {+ accountItems: SearchItem[]+ ticketItems: SearchItem[]+ }dataManagementItems: SearchItem[]groupItems: SearchItem[]groupSearchResults: Partial<Record<GroupTypeIndex, GroupQueryResult[]>>@@ -224,6 +230,7 @@ export interface searchLogicValues {recentsLoading: booleanstarredHasLoaded: booleanstarredLoading: boolean+ ticketSearchResultsLoading: booleanunifiedSearchResultsLoading: boolean}miscItems: SearchItem[]@@ -243,6 +250,9 @@ export interface searchLogicValues {settingsItems: SearchItem[]settingsSections: SettingsSectionSummary[]starredItems: SearchItem[]+ ticketItems: SearchItem[]+ ticketSearchResults: TicketApi[]+ ticketSearchResultsLoading: booleantoolsItems: SearchItem[]unifiedSearchItems: Record<string, SearchItem[]>unifiedSearchResults: SearchResponse | null@@ -335,6 +345,27 @@ export interface searchLogicActions {searchTerm: string}}+ loadTicketSearchResults: ({ searchTerm }: { searchTerm: string }) => {+ searchTerm: string+ }+ loadTicketSearchResultsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTicketSearchResultsSuccess: (+ ticketSearchResults: TicketApi[],+ payload?: {+ searchTerm: string+ }+ ) => {+ ticketSearchResults: TicketApi[]+ payload?: {+ searchTerm: string+ }+ }loadUnifiedSearchResults: ({ searchTerm }: { searchTerm: string }) => {searchTerm: string}@@ -395,6 +426,7 @@ export interface searchLogicMeta {groupSearchResultsLoading: boolean,personSearchResultsLoading: boolean,accountSearchResultsLoading: boolean,+ ticketSearchResultsLoading: boolean,playlistSearchResultsLoading: boolean,searchPending: boolean,search: string@@ -430,6 +462,14 @@ export interface searchLogicMeta {) => SearchItem[]personItems: (personSearchResults: PersonType[]) => SearchItem[]accountItems: (accountSearchResults: AccountApi[]) => SearchItem[]+ ticketItems: (ticketSearchResults: TicketApi[]) => SearchItem[]+ customerItems: (+ accountItems: SearchItem[],+ ticketItems: SearchItem[]+ ) => {+ accountItems: SearchItem[]+ ticketItems: SearchItem[]+ }playlistItems: (playlistSearchResults: FileSystemEntry[]) => SearchItem[]healthItems: (sceneLogViewsByRef: Record<string, string>) => SearchItem[]miscItems: (sceneLogViewsByRef: Record<string, string>) => SearchItem[]@@ -448,6 +488,7 @@ export interface searchLogicMeta {personSearchResultsLoading: boolean,groupSearchResultsLoading: boolean,accountSearchResultsLoading: boolean,+ ticketSearchResultsLoading: boolean,playlistSearchResultsLoading: boolean) => {accountSearchResultsLoading: boolean@@ -459,6 +500,7 @@ export interface searchLogicMeta {recentsLoading: booleanstarredHasLoaded: booleanstarredLoading: boolean+ ticketSearchResultsLoading: booleanunifiedSearchResultsLoading: boolean}allCategories: (@@ -473,7 +515,10 @@ export interface searchLogicMeta {newItems: SearchItem[],personItems: SearchItem[],groupItems: SearchItem[],- accountItems: SearchItem[],+ customerItems: {+ accountItems: SearchItem[]+ ticketItems: SearchItem[]+ },playlistItems: SearchItem[],unifiedSearchItems: Record<string, SearchItem[]>,loadingStates: {@@ -486,6 +531,7 @@ export interface searchLogicMeta {recentsLoading: booleanstarredHasLoaded: booleanstarredLoading: boolean+ ticketSearchResultsLoading: booleanunifiedSearchResultsLoading: boolean},search: string@@ -681,6 +727,41 @@ export const searchLogic = kea<searchLogicType>([},},],+ // Support tickets come from the Conversations list endpoint rather than the unified+ // search API: that endpoint already resolves a bare number to one ticket and matches the+ // customer's name and email, the subject, and message content, none of which the+ // full-text `ENTITY_MAP` entry over ticket columns would cover. It answers newest-active+ // first (`-updated_at`), which is the order a support lookup wants.+ ticketSearchResults: [+ [] as TicketApi[],+ {+ loadTicketSearchResults: async ({ searchTerm }: { searchTerm: string }, breakpoint) => {+ const trimmed = searchTerm.trim()++ // Returning early also clears the rows a longer query left behind, so a query+ // too short to search never shows results that no longer match what is typed.+ if (!shouldSearchTickets(trimmed) || !values.currentTeamId) {+ return []+ }++ try {+ const response = await conversationsTicketsList(+ String(values.currentTeamId),+ {+ search: trimmed,+ limit: SEARCH_LIMIT,+ },+ { signal: cache.searchAbortController?.signal }+ )+ breakpoint()++ return response.results+ } catch (error) {+ return rethrowSearchError(error, breakpoint)+ }+ },+ },+ ],playlistSearchResults: [[] as FileSystemEntry[],{@@ -738,6 +819,7 @@ export const searchLogic = kea<searchLogicType>([s.groupSearchResultsLoading,s.personSearchResultsLoading,s.accountSearchResultsLoading,+ s.ticketSearchResultsLoading,s.playlistSearchResultsLoading,s.searchPending,s.search,@@ -748,6 +830,7 @@ export const searchLogic = kea<searchLogicType>([groupSearchResultsLoading: boolean,personSearchResultsLoading: boolean,accountSearchResultsLoading: boolean,+ ticketSearchResultsLoading: boolean,playlistSearchResultsLoading: boolean,searchPending: boolean,search: string@@ -757,6 +840,7 @@ export const searchLogic = kea<searchLogicType>([groupSearchResultsLoading ||personSearchResultsLoading ||accountSearchResultsLoading ||+ ticketSearchResultsLoading ||playlistSearchResultsLoading ||searchPending) &&search.trim() !== '',@@ -1106,6 +1190,43 @@ export const searchLogic = kea<searchLogicType>([})},],+ ticketItems: [+ (s) => [s.ticketSearchResults],+ (ticketSearchResults: TicketApi[]): SearchItem[] => {+ return ticketSearchResults.map((ticket) => {+ // Only email tickets carry a subject, so a Slack or widget ticket falls back to+ // its latest message — the only line of it that reads as a title. The number+ // leads either way: it is how support refers to a ticket everywhere else, and+ // it is what someone who typed a number is looking to confirm.+ const subject = ticket.email_subject || ticket.last_message_text || 'Untitled ticket'+ const displayName = `#${ticket.ticket_number} ${subject}`+ return {+ id: `ticket-${ticket.id}`,+ name: displayName,+ displayName,+ category: 'tickets',+ // The detail scene redirects a UUID to the ticket-number URL, so linking+ // there directly saves the row a redirect.+ href: urls.supportTicketDetail(ticket.ticket_number),+ itemType: 'conversations',+ // Rendered as the row's muted trailing text: which tickets are still open+ // is the first thing a support agent reads off a list of matches.+ productCategory: ticket.status ? capitalizeFirstLetter(ticket.status.replace(/_/g, ' ')) : null,+ record: { type: 'conversations', id: ticket.id, ticketNumber: ticket.ticket_number },+ }+ })+ },+ ],+ // Accounts and support tickets, handed to allCategories as one value. kea types a+ // selector's dependency list up to 16 entries and allCategories sits on that limit, so the+ // two customer-scoped lists ride in together rather than one of them being dropped.+ customerItems: [+ (s) => [s.accountItems, s.ticketItems],+ (+ accountItems: SearchItem[],+ ticketItems: SearchItem[]+ ): { accountItems: SearchItem[]; ticketItems: SearchItem[] } => ({ accountItems, ticketItems }),+ ],playlistItems: [(s) => [s.playlistSearchResults],(playlistSearchResults: FileSystemEntry[]): SearchItem[] => {@@ -1395,6 +1516,7 @@ export const searchLogic = kea<searchLogicType>([s.personSearchResultsLoading,s.groupSearchResultsLoading,s.accountSearchResultsLoading,+ s.ticketSearchResultsLoading,s.playlistSearchResultsLoading,],(@@ -1405,6 +1527,7 @@ export const searchLogic = kea<searchLogicType>([personSearchResultsLoading: boolean,groupSearchResultsLoading: boolean,accountSearchResultsLoading: boolean,+ ticketSearchResultsLoading: boolean,playlistSearchResultsLoading: boolean) => ({unifiedSearchResultsLoading,@@ -1416,6 +1539,7 @@ export const searchLogic = kea<searchLogicType>([personSearchResultsLoading,groupSearchResultsLoading,accountSearchResultsLoading,+ ticketSearchResultsLoading,playlistSearchResultsLoading,}),],@@ -1432,7 +1556,7 @@ export const searchLogic = kea<searchLogicType>([s.newItems,s.personItems,s.groupItems,- s.accountItems,+ s.customerItems,s.playlistItems,s.unifiedSearchItems,s.loadingStates,@@ -1450,7 +1574,7 @@ export const searchLogic = kea<searchLogicType>([newItems: SearchItem[],personItems: SearchItem[],groupItems: SearchItem[],- accountItems: SearchItem[],+ customerItems: { accountItems: SearchItem[]; ticketItems: SearchItem[] },playlistItems: SearchItem[],unifiedSearchItems: Record<string, SearchItem[]>,loadingStates: {@@ -1463,6 +1587,7 @@ export const searchLogic = kea<searchLogicType>([personSearchResultsLoading: booleangroupSearchResultsLoading: booleanaccountSearchResultsLoading: boolean+ ticketSearchResultsLoading: booleanplaylistSearchResultsLoading: boolean},search: string@@ -1477,9 +1602,12 @@ export const searchLogic = kea<searchLogicType>([personSearchResultsLoading,groupSearchResultsLoading,accountSearchResultsLoading,+ ticketSearchResultsLoading,playlistSearchResultsLoading,} = loadingStates+ const { accountItems, ticketItems } = customerItems+const categories: SearchCategory[] = []const hasSearch = search.trim() !== ''@@ -1661,6 +1789,15 @@ export const searchLogic = kea<searchLogicType>([})}+ // Add support tickets+ if (ticketItems.length > 0 || ticketSearchResultsLoading) {+ categories.push({+ key: 'tickets',+ items: ticketItems,+ isLoading: ticketSearchResultsLoading,+ })+ }+// Add personsif (personItems.length > 0 || personSearchResultsLoading) {categories.push({@@ -1731,6 +1868,7 @@ export const searchLogic = kea<searchLogicType>([if (values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {actions.loadAccountSearchResults({ searchTerm: search })}+ actions.loadTicketSearchResults({ searchTerm: search })actions.loadPlaylistSearchResults({ searchTerm: search })},})),diff --git a/frontend/src/lib/components/Search/utils.test.ts b/frontend/src/lib/components/Search/utils.test.tsindex 30a617f2f276..5cf0e6f068be 100644--- a/frontend/src/lib/components/Search/utils.test.ts+++ b/frontend/src/lib/components/Search/utils.test.ts@@ -1,4 +1,4 @@-import { SETTINGS_THEME_ITEM_ID, canOpenInNewTab, filterSearchItems } from './utils'+import { SETTINGS_THEME_ITEM_ID, canOpenInNewTab, filterSearchItems, shouldSearchTickets } from './utils'interface TestItem {name: string@@ -128,3 +128,27 @@ describe('canOpenInNewTab', () => {expect(canOpenInNewTab(item)).toBe(expected)})})++describe('shouldSearchTickets', () => {+ it('waits for a query worth scanning message content for', () => {+ expect(shouldSearchTickets('')).toBe(false)+ expect(shouldSearchTickets('b')).toBe(false)+ expect(shouldSearchTickets('bi')).toBe(false)+ expect(shouldSearchTickets('bil')).toBe(true)+ expect(shouldSearchTickets(' billing ')).toBe(true)+ })++ // A number resolves to an indexed lookup by ticket number, so it is never too short.+ it('always searches a ticket number', () => {+ expect(shouldSearchTickets('7')).toBe(true)+ expect(shouldSearchTickets('#7')).toBe(true)+ expect(shouldSearchTickets('#')).toBe(false)+ })++ // The server drops an over-long search term, so sending one would answer a pasted log line+ // with unfiltered tickets.+ it('does not send a query the server would drop', () => {+ expect(shouldSearchTickets('x'.repeat(200))).toBe(true)+ expect(shouldSearchTickets('x'.repeat(201))).toBe(false)+ })+})diff --git a/frontend/src/lib/components/Search/utils.ts b/frontend/src/lib/components/Search/utils.tsindex 7dfd0f7de896..72a26fae5653 100644--- a/frontend/src/lib/components/Search/utils.ts+++ b/frontend/src/lib/components/Search/utils.ts@@ -52,6 +52,32 @@ interface NewTabCandidate {export const canOpenInNewTab = (item: NewTabCandidate): boolean =>!!item.href && !item.onSelect && item.id !== SETTINGS_THEME_ITEM_ID+/** Optional leading `#` and nothing but digits — the shape the ticket endpoint resolves with an+ * exact ticket-number lookup rather than a text scan (`is_ticket_number_search` server-side). */+const TICKET_NUMBER_QUERY = /^#?\d+$/++/** Below this, a free-text ticket search is not worth sending. */+const TICKET_SEARCH_MIN_LENGTH = 3++/** The ticket endpoint drops a `search` longer than this rather than rejecting it+ * (`MAX_SEARCH_LENGTH` in products/conversations/backend/api/ticket_filters.py), and would answer+ * an over-long query with unfiltered tickets — rows presented as matches that match nothing. */+const TICKET_SEARCH_MAX_LENGTH = 200++/**+ * Whether a query is worth sending to the ticket endpoint. Free-text ticket search scans message+ * content, which is the most expensive lookup in the palette, and one or two characters match most+ * of a support inbox anyway. A ticket number is exempt from the lower bound in both directions: it+ * is an indexed lookup, and "#7" is a complete query rather than the start of a longer one.+ */+export const shouldSearchTickets = (query: string): boolean => {+ const trimmed = query.trim()+ if (trimmed.length > TICKET_SEARCH_MAX_LENGTH) {+ return false+ }+ return trimmed.length >= TICKET_SEARCH_MIN_LENGTH || TICKET_NUMBER_QUERY.test(trimmed)+}+export const getCategoryDisplayName = (category: string): string => {const displayNames: Record<string, string> = {create: 'Create new',@@ -67,6 +93,7 @@ export const getCategoryDisplayName = (category: string): string => {persons: 'Persons',groups: 'Groups',accounts: 'Accounts',+ tickets: 'Support tickets',eventDefinitions: 'Events',propertyDefinitions: 'Properties',ai: 'PostHog AI',