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(search): add alert and ticket is: filters to command k (#128428)

Shy Alterf4550e0228f3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 61c10c2d8a7a..e2f581968b69 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -717,9 +717,9 @@ snapshots:
components-chart-legend-series-menu--single-series--light:
hash: v1.k794b7964.45544c43c187fd1d1fc7b204e7c33c7e422c5c56838cac44e5d63318c7f5e283.phbzfcS5A5m2LHaspjABfv-I6FPQ1-LnsCFRwyX81uQ
components-command-k-search--chip-and-value-suggestions--dark:
- hash: v1.k794b7964.ced343446b982f961f849c3c21b0291456454a8bdabbffb4c40bc2465c38b705.vVQJg_pcOqsFUbRrIZOaZz2gMa8IBYTJQKsMPbfUGJ0
+ hash: v1.k794b7964.4698f43606173e0e7750e871c6bc9325c59eecee7017d067a883450ffa46f5b0.J9AxIDVeIF92h2t-LEXQw421jwYIf6uT99zfTKyk9mk
components-command-k-search--chip-and-value-suggestions--light:
- hash: v1.k794b7964.ccb298dc4076c600a145a31a044963cef3118ca4843fa8ff894a3ef90c79d808.8qYvuh3gupAupj16CkZQvwzrc2fANTy_rRWfxckuleI
+ hash: v1.k794b7964.fab6a2dc783e398b656611696a3f92fa3ee4149433cc08596a755283e28446f6.FgzMAj2ctr7DvlMN6s4-zTb6y_SsSIeQ2WT7IwbrBbE
components-command-k-search--empty--dark:
hash: v1.k794b7964.f3260178d12c5e4e9a6b52804d25e9682b65d51d6fb097d2cfff69b6e124bdfb.5cMrbH5cW9Vi0zRIEfsr36NFl_6gFKU9xPbhprCc3Po
components-command-k-search--empty--light:
diff --git a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
index 1be17b32dd76..c2f6cbc94111 100644
--- a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
+++ b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
@@ -126,6 +126,13 @@ Results for a search with words follow ordered tie-breaking rules: words matched
- Results with the same name show as one row with a "+N with this name" badge.
- A short list (8 or fewer) or a list of one type shows flat, under one **Results** header.
- With an `is:` chip, results show as one flat list. The creator shows on rows that share a name.
+- Some `is:` types are not file system objects, so the file system search cannot find them. `is:alert`, `is:ticket`, `is:workflow`, `is:endpoint`, and `is:product_tour` search their own API instead (`TYPE_SEARCHES` in `commandKSources.ts`): alerts, support tickets, and product tours through their list endpoint's `search=`, workflows and endpoints through the unified search API. Results keep the order the API returns, and the ranking keeps a result the API matched outside its name.
+ - `is:ticket` lists the most recently updated tickets with no search text. With text, it follows the **Support tickets** rule: 3+ characters or a ticket number (`42`, `#42`), because the ticket search also scans message text. The ticket API reads a numeric search as a ticket number, so a numeric `name:` value (`name:42`) is not sent. Command K sends the other words, or none, and keeps the tickets whose subject contains the value. With no other words it checks only the 20 most recently updated tickets. A ticket row shows its subject, then the number, the customer's name or email, and the status.
+ - These APIs cannot apply `createdBy:`, `in:`, or excluded words, so a query with any of them finds nothing for these types. A search that ignored the filter would show objects the filter excludes. Quoted exclusions (`"-legacy"`) count too.
+ - Some of these APIs also match descriptions, customers, or message text, so Command K keeps only the results whose name contains the `name:` value.
+ - `is:workflow name:venue` finds "Revenue". With no other words, the `name:` value goes to the workflows list `name=` filter, which matches inside workflow names on the server and never reads step content. With other words, only those words go to the unified search, and the `name:` value filters its results.
+ - `is:endpoint name:` still goes to the unified full-text search, which matches the start of words, so `name:venue` does not find "revenue". The endpoints list has no search to use instead.
+ - These searches wait 150 ms after the last keystroke, like the other remote lists, instead of the 50 ms of the file system search. Alerts load 5 at a time, because the alerts list also loads each alert's fired checks.
- Rows show the folder (when not Unfiled) and "viewed 3 days ago" when the person opened the item, otherwise "created 2 mos ago". Type labels show only in Best matches, where types mix.
## Smart filters
@@ -146,6 +153,9 @@ Quote values with spaces: `createdBy:"Ada Lovelace"`, `in:"Team Growth"`.
The backend tokenizes these in `FileSystemViewSet._apply_search_to_queryset` (`posthog/api/file_system/file_system.py`), including `-` negation and quotes.
The frontend maps friendly keys to backend keys (`is:` → `type:`, `createdBy:` → `user:`) and sends one `search` string.
+`is:` also offers insight alert, ticket, destination, and transformation, which no manifest lists (`EXTRA_TYPES` in `commandKFilterOptions.tsx`). Types that the file system does not hold search their own API (see [Ranked results](#ranked-results)).
+`is:alert` covers insight alerts only, because the log alerts list has no search, and its **View all** row opens the insight alerts tab.
+`is:destination` covers server and browser destinations (`hog_function/destination` and `hog_function/site_destination`), like the Destinations page. The file system search takes one `type:` value, so Command K sends one search per type with the other filters kept, and merges the results. `-is:destination` excludes both types in one search.
### Suggested next filters
diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx
index f36ae946948d..4e7d8085127e 100644
--- a/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx
+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx
@@ -28,7 +28,9 @@ function rankedContext(
) : item.record?.created_at ? (
<CommandKSearchTime time={String(item.record.created_at)} prefix="created" tooltipLabel="Created" />
) : null
- const detail = [userFolder(item), showCreator ? item.createdByName : null].filter(Boolean).join(' · ')
+ const detail = [item.productCategory, userFolder(item), showCreator ? item.createdByName : null]
+ .filter(Boolean)
+ .join(' · ')
return { detail: detail || null, tail: age }
}
diff --git a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.test.ts b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.test.ts
index e7a0105f5507..0f22ee7d4a09 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.test.ts
@@ -1,4 +1,4 @@
-import { viewAllFor } from './commandKFilterOptions'
+import { buildFilterOptions, viewAllFor } from './commandKFilterOptions'
import { FilterOptions, QueryChip, ResolvedQuery, resolveQuery } from './commandKQuery'
const chip = (value: string, label: string, overrides: Partial<QueryChip> = {}): QueryChip => ({
@@ -134,6 +134,23 @@ describe('viewAllFor', () => {
expect(viewAllFor(resolved(chips, freeText))?.item).toMatchObject({ name, href })
})
+ test.each([
+ ['alert', 'alert', 'View all insight alerts', '/alerts?alert_type=insights'],
+ ['ticket', 'ticket', 'View all tickets', '/support/tickets'],
+ ['destination', 'hog_function/destination', 'View all destinations', '/data-management/destinations'],
+ [
+ 'transformation',
+ 'hog_function/transformation',
+ 'View all transformations',
+ '/data-management/transformations',
+ ],
+ ['endpoint', 'endpoints', 'View all endpoints', '/endpoints'],
+ ])('resolves is:%s to its type and names its list page', (typed, value, name, href) => {
+ const typedQuery = resolveQuery(`is:${typed}`, [], buildFilterOptions([], null, []))
+ expect(typedQuery.filters).toEqual([expect.objectContaining({ key: 'is', value, negated: false })])
+ expect(viewAllFor(typedQuery)?.item).toMatchObject({ name, href })
+ })
+
test.each([
['leads with only filters', '', 'lead'],
['trails once there is search text', 'beta', 'trail'],
diff --git a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx
index 1594e621a19f..4c9e9bf5fff6 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx
+++ b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx
@@ -4,6 +4,7 @@ import { IconArrowRight } from '@posthog/icons'
import { SearchItem } from 'lib/components/Search/searchItems'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { urls } from 'scenes/urls'
import { isFileSystemEntryTypeEnabled } from '~/layout/panel-layout/ProjectTree/utils'
import { fileSystemTypes } from '~/products'
@@ -20,6 +21,11 @@ const TYPE_ALIASES: Record<string, string[]> = {
early_access_feature: ['eaf', 'beta'],
workflows: ['workflow'],
notebook: ['doc'],
+ alert: ['alerts'],
+ ticket: ['tickets', 'support'],
+ endpoints: ['endpoint'],
+ 'hog_function/destination': ['destinations'],
+ 'hog_function/transformation': ['transformations'],
}
interface FileSystemTypeDefinition {
@@ -27,12 +33,38 @@ interface FileSystemTypeDefinition {
iconType?: string
listHref?: () => string
listSearchParam?: 'search'
+ fileSystemTypes?: string[]
}
-const FILE_SYSTEM_TYPES = fileSystemTypes as Record<string, FileSystemTypeDefinition>
+const EXTRA_TYPES: Record<string, FileSystemTypeDefinition> = {
+ alert: {
+ name: 'Insight alert',
+ iconType: 'inbox',
+ listHref: () => combineUrl(urls.alerts(), { alert_type: 'insights' }).url,
+ },
+ ticket: { name: 'Ticket', iconType: 'conversations', listHref: () => urls.supportTickets() },
+ 'hog_function/destination': {
+ name: 'Destination',
+ iconType: 'data_destination',
+ listHref: () => urls.destinations(),
+ fileSystemTypes: ['hog_function/destination', 'hog_function/site_destination'],
+ },
+ 'hog_function/transformation': {
+ name: 'Transformation',
+ iconType: 'data_transformation',
+ listHref: () => urls.transformations(),
+ },
+}
+
+const COMMAND_K_TYPES: Record<string, FileSystemTypeDefinition> = {
+ ...(fileSystemTypes as Record<string, FileSystemTypeDefinition>),
+ ...EXTRA_TYPES,
+}
const typeDefinition = (type: string): FileSystemTypeDefinition | undefined =>
- Object.hasOwn(FILE_SYSTEM_TYPES, type) ? FILE_SYSTEM_TYPES[type] : undefined
+ Object.hasOwn(COMMAND_K_TYPES, type) ? COMMAND_K_TYPES[type] : undefined
+
+export const fileSystemTypesFor = (type: string): string[] => typeDefinition(type)?.fileSystemTypes ?? [type]
// Some manifest names are already plural, such as "Tasks".
export const pluralTypeName = (label: string): string => {
@@ -42,10 +74,10 @@ export const pluralTypeName = (label: string): string => {
let cachedTypeOptions: ValueOption[] | null = null
-/** Every file system type from the product manifests, alphabetized. The manifests never change at runtime. */
+/** Every type from the product manifests plus the extra types, alphabetized. The manifests never change at runtime. */
const typeOptions = (): ValueOption[] => {
if (cachedTypeOptions === null) {
- cachedTypeOptions = Object.entries(FILE_SYSTEM_TYPES)
+ cachedTypeOptions = Object.entries(COMMAND_K_TYPES)
.flatMap(([type, definition]) =>
definition.name
? [
@@ -109,6 +141,7 @@ interface ListPage {
const LIST_PAGE_FALLBACKS: Record<string, ListPage> = {
dashboard: { href: '/dashboard', searchParam: 'search' },
notebook: { href: '/notebooks' },
+ endpoints: { href: urls.endpoints() },
}
function listPageFor(type: string): ListPage | null {
diff --git a/frontend/src/lib/components/CommandKSearch/commandKQuery.ts b/frontend/src/lib/components/CommandKSearch/commandKQuery.ts
index ec2648b67ffa..641c9c01f40a 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKQuery.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKQuery.ts
@@ -416,22 +416,53 @@ const BACKEND_FILTER_FIELDS = new Set(['path', 'name', 'user', 'author', 'type',
// Reads `backendSearch` like the file system search does, so the list searches the words Cmd+K matched.
// List pages match one phrase, which cannot exclude, so excluded words and filters other than `name:` stay out.
-export function listSearchText({ backendSearch }: ResolvedQuery): string {
- const words: string[] = []
+interface SearchTerms {
+ words: string[]
+ freeWords: string[]
+ name: string | null
+ excludes: boolean
+}
+
+function searchTerms(backendSearch: string): SearchTerms {
+ const terms: SearchTerms = { words: [], freeWords: [], name: null, excludes: false }
for (const raw of tokenizeSearch(backendSearch)) {
if (raw.startsWith('-') || raw.startsWith('!')) {
+ terms.excludes ||= raw.length > 1
continue
}
const token = stripQuotes(raw)
const colonIndex = token.indexOf(':')
const field = colonIndex === -1 ? null : token.slice(0, colonIndex).toLowerCase()
if (field === 'name') {
- words.push(stripQuotes(token.slice(colonIndex + 1).trim()))
+ terms.name = stripQuotes(token.slice(colonIndex + 1).trim())
+ terms.words.push(terms.name)
} else if (field === null || !BACKEND_FILTER_FIELDS.has(field)) {
- words.push(token)
+ terms.words.push(token)
+ terms.freeWords.push(token)
}
}
- return words.filter(Boolean).join(' ')
+ return terms
+}
+
+export function listSearchText({ backendSearch }: Pick<ResolvedQuery, 'backendSearch'>): string {
+ return searchTerms(backendSearch).words.filter(Boolean).join(' ')
+}
+
+export interface TypeSearchTerms {
+ text: string
+ name: string | null
+ freeText: string
+ excludes: boolean
+}
+
+export function typeSearchTerms({ backendSearch }: Pick<ResolvedQuery, 'backendSearch'>): TypeSearchTerms {
+ const { words, freeWords, name, excludes } = searchTerms(backendSearch)
+ return {
+ text: words.filter(Boolean).join(' '),
+ name: name || null,
+ freeText: freeWords.filter(Boolean).join(' '),
+ excludes,
+ }
}
/** The raw query as a person would type it, chips included. Used when copying the input. */
diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts
index dc1d459d7cd6..4cf02a89c2a5 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts
@@ -138,6 +138,7 @@ function candidateFor(item: SearchItem, groupKey: string, query: string): RankCa
context: [...path, groupKey.replace(/[_/]/g, ' ')],
frecency: -(item.rankKey?.[SERVER_FRECENCY_INDEX] ?? 0) / 1000,
createdAt: -(item.rankKey?.[SERVER_CREATED_INDEX] ?? 0),
+ matchesQuery: !item.rankKey,
}
}
@@ -300,8 +301,8 @@ export function buildRankedResults({
const capped = !!results[0]?.searchMatch?.countsCapped
const mostWordsMatched = candidates[0].rank[0]
const fullest = candidates.filter((entry) => entry.rank[0] === mostWordsMatched)
- const fewestTypos = Math.min(...fullest.map((entry) => entry.rank[1]))
- const matching = fullest.filter((entry) => entry.rank[1] === fewestTypos)
+ const fewestTypos = Math.min(...fullest.map((entry) => entry.rank[1] ?? 0))
+ const matching = fullest.filter((entry) => (entry.rank[1] ?? 0) === fewestTypos)
const notices =
state === 'stale'
? []
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx
index 454d62080e8a..f568ec1c6b6b 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx
+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx
@@ -80,11 +80,14 @@ import {
resultsSettled,
themeSearchItem,
} from './commandKSections'
-import { REMOTE_REQUESTS, RemoteContext, RemoteResults, RemoteSource, settleRequest } from './commandKSources'
-
-const REMOTE_DEBOUNCE_MS = 150
-const OBJECTS_DEBOUNCE_MS = 50
-const FAST_REQUESTS = ['objects', 'persons']
+import {
+ REMOTE_REQUESTS,
+ RemoteContext,
+ RemoteResults,
+ RemoteSource,
+ requestDebounceMs,
+ settleRequest,
+} from './commandKSources'
const INPUT_HIGHLIGHT_KEY = 'input'
@@ -936,7 +939,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
)
continue
}
- const debounceMs = FAST_REQUESTS.includes(request.id) ? OBJECTS_DEBOUNCE_MS : REMOTE_DEBOUNCE_MS
+ const debounceMs = requestDebounceMs(request, query)
// One disposable per request covers the debounce and the fetch, so a newer query
// cancels both, and unmounting cancels everything.
cache.disposables.add(
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
index 1f20f3b5f05b..28c6391b86b1 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
@@ -119,25 +119,50 @@ describe('buildSections', () => {
expect(rowKeys(loaded)).toEqual(onceLoaded)
})
- it('keeps the View all row on ranked results of one type', () => {
+ const alerts: SearchItem[] = [
+ { id: 'alert-2', name: 'Revenue drop', category: 'results', record: { type: 'alert', id: '2' } },
+ { id: 'alert-1', name: 'Weekly revenue', category: 'results', record: { type: 'alert', id: '1' } },
+ ]
+ const ticketMatchedInMessage: SearchItem = {
+ id: 'ticket-1',
+ name: 'Card declined',
+ category: 'results',
+ record: { type: 'ticket', id: '1' },
+ }
+ test.each<[string, string, SearchItem[], string[], boolean]>([
+ [
+ 'file system results with a server rank',
+ 'type:dashboard revenue',
+ [{ ...dashboard('a', '1'), rankKey: [-1, 0, 0, 0, -1, 0, 2, 0, 0] }],
+ ['results/a'],
+ false,
+ ],
+ [
+ 'results from a type API that sends no rank, in the order it sent them',
+ 'type:alert revenue',
+ alerts,
+ ['results/alert-2', 'results/alert-1'],
+ false,
+ ],
+ [
+ 'a type API result that matched outside its name, with unified ranking',
+ 'type:ticket revenue',
+ [ticketMatchedInMessage],
+ ['results/ticket-1'],
+ true,
+ ],
+ ])('keeps the View all row after ranked %s', (_, results, items, rowKeys, unifiedRanking) => {
const viewAll: ViewAll = {
- item: { id: 'view-all', name: 'View all dashboards', category: 'results', href: '/dashboard' },
+ item: { id: 'view-all', name: 'View all', category: 'results', href: '/list' },
placement: 'trail',
}
const remote = emptyRemoteSlots()
- remote.results = {
- cache: { 'type:dashboard revenue': [{ ...dashboard('a', '1'), rankKey: [-1, 0, 0, 0, -1, 0, 2, 0, 0] }] },
- }
+ remote.results = { cache: { [results]: items } }
const sections = buildSections(
- input('search', {
- remote,
- remoteQueries: { results: 'type:dashboard revenue' },
- localQuery: 'revenue',
- viewAll,
- })
+ input('search', { remote, remoteQueries: { results }, localQuery: 'revenue', viewAll, unifiedRanking })
)
expect(sections.find((section) => section.key === 'results')?.rows.map((row) => row.key)).toEqual([
- 'results/a',
+ ...rowKeys,
'results/view-all',
])
})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSources.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSources.test.ts
index fe02ac5f23d6..5e48c449b336 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSources.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSources.test.ts
@@ -1,8 +1,23 @@
import api from 'lib/api'
-import { GroupTypeIndex } from '~/types'
+import { fileSystemSearchRetrieve } from '~/generated/core/api'
+import { GroupTypeIndex, SearchResponse, SearchableEntity } from '~/types'
-import { REMOTE_REQUESTS, RemoteContext, RemoteRequest, settleRequest } from './commandKSources'
+import { alertsList } from 'products/alerts/frontend/generated/api'
+import { conversationsTicketsList } from 'products/conversations/frontend/generated/api'
+import { productToursList } from 'products/product_tours/frontend/generated/api'
+import { hogFlowsList } from 'products/workflows/frontend/generated/api'
+
+import { REMOTE_REQUESTS, RemoteContext, RemoteRequest, requestDebounceMs, settleRequest } from './commandKSources'
+
+jest.mock('products/alerts/frontend/generated/api', () => ({ alertsList: jest.fn() }))
+jest.mock('products/conversations/frontend/generated/api', () => ({ conversationsTicketsList: jest.fn() }))
+jest.mock('products/product_tours/frontend/generated/api', () => ({ productToursList: jest.fn() }))
+jest.mock('products/workflows/frontend/generated/api', () => ({ hogFlowsList: jest.fn() }))
+jest.mock('~/generated/core/api', () => ({
+ ...jest.requireActual('~/generated/core/api'),
+ fileSystemSearchRetrieve: jest.fn(),
+}))
const context: RemoteContext = {
currentTeamId: 1,
@@ -73,4 +88,294 @@ describe('settleRequest', () => {
expect(result?.failed).toBe(true)
expect(result?.results.groups?.map((item) => item.id)).toEqual(['group-0-acme'])
})
+
+ describe('an is: type the file system does not hold', () => {
+ const objects = REMOTE_REQUESTS.find((request) => request.id === 'objects')!
+ const unified = (type: SearchableEntity, id: string, name: string): SearchResponse['results'][number] => ({
+ type,
+ result_id: id,
+ extra_fields: { name },
+ rank: null,
+ })
+
+ beforeEach(() => {
+ jest.useRealTimers()
+ jest.mocked(alertsList).mockResolvedValue({
+ count: 1,
+ results: [{ id: 'a1', name: 'Revenue drop', insight_display_name: 'Revenue' }],
+ } as any)
+ jest.mocked(conversationsTicketsList).mockResolvedValue({
+ count: 1,
+ results: [
+ {
+ id: 'ticket-uuid',
+ ticket_number: 42,
+ email_subject: 'Refund not received',
+ status: 'on_hold',
+ anonymous_traits: { name: 'Jane Doe', email: '[email protected]' },
+ },
+ ],
+ } as any)
+ jest.mocked(productToursList).mockResolvedValue({
+ count: 1,
+ results: [{ id: 't1', name: 'Revenue tour' }],
+ } as any)
+ jest.spyOn(api.search, 'list').mockImplementation(async ({ entities }) => ({
+ results: entities?.includes('hog_flow')
+ ? [unified('hog_flow', 'w1', 'Revenue nudge')]
+ : [unified('endpoint', 'e1', 'revenue-daily')],
+ }))
+ jest.spyOn(api.fileSystem, 'list').mockResolvedValue({ results: [], count: 0 } as any)
+ jest.mocked(fileSystemSearchRetrieve).mockResolvedValue({
+ results: [],
+ type_counts: [],
+ matched_all_words: true,
+ matched_words: [],
+ counts_capped: false,
+ matched_with_typos: false,
+ } as any)
+ })
+
+ test.each([
+ ['type:alert revenue', '/alerts?alert_type=insights&alert_id=a1'],
+ ['type:alert', '/alerts?alert_type=insights&alert_id=a1'],
+ ['type:product_tour revenue', '/product_tours/t1'],
+ ['type:workflows revenue', '/workflows/w1/workflow'],
+ ['type:endpoints name:revenue', '/endpoints/revenue-daily'],
+ ['type:ticket refund', '/support/tickets/42'],
+ ])('searches its own API for %s', async (query, href) => {
+ const result = await settleRequest(objects, query, new AbortController().signal, context)
+ expect(result?.results.results?.map((item) => item.href)).toEqual([href])
+ })
+
+ test.each([
+ ['type:alert user:me revenue', 'its API cannot apply createdBy'],
+ ['type:alert path:Growth', 'its API cannot apply in'],
+ ['type:alert revenue -legacy', 'its API cannot exclude words'],
+ ['type:alert "-legacy"', 'a quoted exclusion is still an exclusion'],
+ ["type:alert revenue '-legacy'", 'a single-quoted exclusion is still an exclusion'],
+ ['type:ticket re', 'two letters would scan every ticket message'],
+ ])('finds nothing for %s without a request, because %s', async (query) => {
+ const result = await settleRequest(objects, query, new AbortController().signal, context)
+ expect(result?.results.results).toEqual([])
+ expect(alertsList).not.toHaveBeenCalled()
+ expect(conversationsTicketsList).not.toHaveBeenCalled()
+ expect(fileSystemSearchRetrieve).not.toHaveBeenCalled()
+ expect(api.fileSystem.list).not.toHaveBeenCalled()
+ })
+
+ test.each([
+ [
+ 'type:ticket name:refund',
+ () =>
+ jest.mocked(conversationsTicketsList).mockResolvedValue({
+ count: 2,
+ results: [
+ { id: 't-1', ticket_number: 1, email_subject: 'Refund not received' },
+ { id: 't-2', ticket_number: 2, email_subject: 'Card declined' },
+ ],
+ } as any),
+ ['/support/tickets/1'],
+ ],
+ [
+ 'type:product_tour name:"revenue tour"',
+ () =>
+ jest.mocked(productToursList).mockResolvedValue({
+ count: 2,
+ results: [
+ { id: 'p1', name: 'Revenue tour' },
+ { id: 'p2', name: 'Onboarding', description: 'A revenue tour for new users' },
+ ],
+ } as any),
+ ['/product_tours/p1'],
+ ],
+ ])('keeps only the results whose name matches for %s', async (query, mockResults, hrefs) => {
+ mockResults()
+ const result = await settleRequest(objects, query, new AbortController().signal, context)
+ expect(result?.results.results?.map((item) => item.href)).toEqual(hrefs)
+ })
+
+ test.each([
+ ['type:alert revenue', () => alertsList, ['1', { search: 'revenue', limit: 5 }, expect.anything()]],
+ [
+ 'type:workflows',
+ () => api.search.list,
+ [{ q: undefined, entities: ['hog_flow'], include_counts: false }, expect.anything()],
+ ],
+ [
+ 'type:endpoints',
+ () => api.search.list,
+ [{ q: undefined, entities: ['endpoint'], include_counts: false }, expect.anything()],
+ ],
+ ])('requests %s with only the parameters it needs', async (query, endpoint, params) => {
+ await settleRequest(objects, query, new AbortController().signal, context)
+ expect(endpoint()).toHaveBeenCalledWith(...params)
+ })
+
+ test.each([
+ ['type:ticket refund', 150],
+ ['type:alert', 150],
+ ['type:dashboard revenue', 50],
+ ['revenue', 50],
+ ])('waits for typing to pause before searching %s', (query, debounceMs) => {
+ expect(requestDebounceMs(objects, query)).toBe(debounceMs)
+ })
+
+ test.each([
+ ['type:ticket refund', 'refund'],
+ ['type:ticket #42', '#42'],
+ ['type:ticket', undefined],
+ ])('sends %s to the ticket list as search %s', async (query, search) => {
+ const result = await settleRequest(objects, query, new AbortController().signal, context)
+ expect(conversationsTicketsList).toHaveBeenCalledWith('1', { search, limit: 20 }, expect.anything())
+ expect(result?.results.results).toEqual([
+ expect.objectContaining({
+ name: 'Refund not received',
+ productCategory: '#42 · Jane Doe · On hold',
+ href: '/support/tickets/42',
+ }),
+ ])
+ })
+
+ test.each([
+ ['type:workflows name:venue', () => hogFlowsList, ['1', { name: 'venue', limit: 20 }, expect.anything()]],
+ [
+ 'type:workflows name:venue nudge',
+ () => api.search.list,
+ [{ q: 'nudge', entities: ['hog_flow'], include_counts: false }, expect.anything()],
+ ],
+ ])('keeps name: apart from the full-text search for %s', async (query, endpoint, params) => {
+ jest.mocked(hogFlowsList).mockResolvedValue({
+ count: 1,
+ results: [{ id: 'w1', name: 'Revenue nudge', created_at: '2026-01-01T00:00:00Z' }],
+ } as any)
+ const result = await settleRequest(objects, query, new AbortController().signal, context)
+ expect(endpoint()).toHaveBeenCalledWith(...params)
+ expect(result?.results.results?.map((item) => item.href)).toEqual(['/workflows/w1/workflow'])
+ })
+
+ test.each([
+ ['type:ticket name:42', undefined],
+ ['type:ticket name:#42', undefined],
+ ])('searches subjects rather than ticket numbers for %s', async (query, search) => {
+ jest.mocked(conversationsTicketsList).mockResolvedValue({
+ count: 2,
+ results: [
+ { id: 't-7', ticket_number: 7, email_subject: 'Refund for order #42' },
+ { id: 't-42', ticket_number: 42, email_subject: 'Card declined' },
+ ],
+ } as any)
+ const result = await settleRequest(objects, query, new AbortController().signal, context)
+ expect(conversationsTicketsList).toHaveBeenCalledWith('1', { search, limit: 20 }, expect.anything())
+ expect(result?.results.results?.map((item) => item.href)).toEqual(['/support/tickets/7'])
+ })
+
+ test.each([
+ [
+ 'the identified person before older traits',
+ { properties: { name: 'Jane Smith', email: '[email protected]' } },
+ { name: 'Jane Doe' },
+ '#42 · Jane Smith · On hold',
+ ],
+ [
+ "the person's email when traits are empty",
+ { properties: { email: '[email protected]' } },
+ {},
+ '#42 · [email protected] · On hold',
+ ],
+ ])('labels the ticket customer with %s', async (_, person, traits, productCategory) => {
+ jest.mocked(conversationsTicketsList).mockResolvedValue({
+ count: 1,
+ results: [
+ {
+ id: 'ticket-uuid',
+ ticket_number: 42,
+ email_subject: 'Refund not received',
+ status: 'on_hold',
+ person,
+ anonymous_traits: traits,
+ },
+ ],
+ } as any)
+ const result = await settleRequest(objects, 'type:ticket refund', new AbortController().signal, context)
+ expect(result?.results.results).toEqual([expect.objectContaining({ productCategory })])
+ })
+ })
+
+ describe('an is: type that covers several file system types', () => {
+ const objects = REMOTE_REQUESTS.find((request) => request.id === 'objects')!
+ const entry = (type: string, id: string, created_at: string): object => ({
+ id,
+ path: `Unfiled/Destinations/${id}`,
+ type,
+ ref: id,
+ created_at,
+ })
+ const searchesSent = (mock: jest.Mock | jest.SpyInstance, argIndex: number): string[] =>
+ mock.mock.calls.map((call: any[]) => call[argIndex].search).sort()
+
+ beforeEach(() => {
+ jest.useRealTimers()
+ jest.spyOn(api.fileSystem, 'list').mockImplementation(
+ async ({ search }) =>
+ ({
+ count: 1,
+ results: String(search).includes('site_destination')
+ ? [entry('hog_function/site_destination', 'browser', '2026-01-02T00:00:00Z')]
+ : [entry('hog_function/destination', 'webhook', '2026-01-01T00:00:00Z')],
+ }) as any
+ )
+ jest.mocked(fileSystemSearchRetrieve).mockResolvedValue({
+ results: [],
+ type_counts: [],
+ matched_all_words: true,
+ matched_words: [],
+ counts_capped: false,
+ matched_with_typos: false,
+ } as any)
+ })
+
+ test.each([
+ [
+ 'type:hog_function/destination user:me',
+ ['type:hog_function/destination user:me', 'type:hog_function/site_destination user:me'],
+ [],
+ ],
+ [
+ 'type:hog_function/destination slack',
+ [],
+ ['type:hog_function/destination slack', 'type:hog_function/site_destination slack'],
+ ],
+ [
+ '-type:hog_function/destination slack',
+ [],
+ ['-type:hog_function/destination -type:hog_function/site_destination slack'],
+ ],
+ ])('searches every type the scope covers for %s', async (query, listSearches, rankedSearches) => {
+ await settleRequest(objects, query, new AbortController().signal, context)
+ expect(searchesSent(jest.mocked(api.fileSystem.list), 0)).toEqual(listSearches)
+ expect(searchesSent(jest.mocked(fileSystemSearchRetrieve), 1)).toEqual(rankedSearches)
+ })
+
+ it('asks each type for its newest entries before merging them', async () => {
+ await settleRequest(objects, 'type:hog_function/destination', new AbortController().signal, context)
+ expect(jest.mocked(api.fileSystem.list).mock.calls.map(([params]) => params.orderBy)).toEqual([
+ '-created_at',
+ '-created_at',
+ ])
+ })
+
+ it('merges the types newest first', async () => {
+ const result = await settleRequest(
+ objects,
+ 'type:hog_function/destination',
+ new AbortController().signal,
+ context
+ )
+ expect(result?.results.results?.map((item) => item.record?.type)).toEqual([
+ 'hog_function/site_destination',
+ 'hog_function/destination',
+ ])
+ })
+ })
})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSources.ts b/frontend/src/lib/components/CommandKSearch/commandKSources.ts
index f69bf0c02a7e..a30bef394acb 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSources.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSources.ts
@@ -2,13 +2,17 @@ import api, { isAbortError } from 'lib/api'
import {
SearchItem,
accountToSearchItem,
+ alertToSearchItem,
+ hogFlowToSearchItem,
fileSystemEntryToSearchItem,
groupToSearchItem,
personToSearchItem,
+ productTourToSearchItem,
+ ticketResultToSearchItem,
ticketToSearchItem,
unifiedSearchResultToSearchItem,
} from 'lib/components/Search/searchItems'
-import { shouldSearchTickets } from 'lib/components/Search/utils'
+import { isTicketNumberQuery, shouldSearchTickets } from 'lib/components/Search/utils'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { uuid } from 'lib/utils/dom'
import { mapGroupQueryResponse } from 'lib/utils/groups'
@@ -18,15 +22,23 @@ import type { FileSystemApi } from '~/generated/core/api.schemas'
import { isFileSystemEntryTypeEnabled } from '~/layout/panel-layout/ProjectTree/utils'
import type { Noun } from '~/models/groupsModel'
import type { FileSystemEntry } from '~/queries/schema/schema-general'
-import { GroupType, GroupTypeIndex } from '~/types'
+import { GroupType, GroupTypeIndex, SearchableEntity } from '~/types'
+import { alertsList } from 'products/alerts/frontend/generated/api'
import { conversationsTicketsList } from 'products/conversations/frontend/generated/api'
import { accountsList } from 'products/customer_analytics/frontend/generated/api'
import { personsList } from 'products/persons/frontend/generated/api'
+import { productToursList } from 'products/product_tours/frontend/generated/api'
+import { hogFlowsList } from 'products/workflows/frontend/generated/api'
-import { freeWords } from './commandKRanking'
+import { fileSystemTypesFor } from './commandKFilterOptions'
+import { TypeSearchTerms, parseToken, tokenize, typeSearchTerms } from './commandKQuery'
+import { compareRanks, freeWords } from './commandKRanking'
export const RESULTS_LIMIT = 20
+export const REMOTE_DEBOUNCE_MS = 150
+export const OBJECTS_DEBOUNCE_MS = 50
+const FAST_REQUESTS = ['objects', 'persons']
export const REQUEST_DEADLINE_MS = 3000
// An AbortError, so the API layer treats it like any cancelled request and reports nothing.
const DEADLINE_PASSED = new DOMException('The request deadline passed', 'AbortError')
@@ -171,21 +183,171 @@ const UNIFIED_TYPES: Record<string, RemoteSource> = {
hog_flow: 'workflows',
}
+type TypeSearch = (terms: TypeSearchTerms, signal: AbortSignal, context: RemoteContext) => Promise<SearchItem[]>
+
+const unifiedTypeSearch =
+ (entity: SearchableEntity, type: string): TypeSearch =>
+ async ({ text }, signal) => {
+ const response = await api.search.list(
+ { q: text || undefined, entities: [entity], include_counts: false },
+ { signal }
+ )
+ return response.results.map((result) => {
+ const item = unifiedSearchResultToSearchItem(result)
+ return { ...item, category: 'results', record: { ...item.record, type } }
+ })
+ }
+
+const TYPE_SEARCHES: Record<string, TypeSearch> = {
+ alert: async ({ text }, signal, context) => {
+ const response = await alertsList(
+ String(context.currentTeamId),
+ { search: text || undefined, limit: SECONDARY_LIMIT },
+ { signal }
+ )
+ return response.results.map(alertToSearchItem)
+ },
+ endpoints: unifiedTypeSearch('endpoint', 'endpoints'),
+ product_tour: async ({ text }, signal, context) => {
+ const response = await productToursList(
+ String(context.currentTeamId),
+ { search: text || undefined, limit: RESULTS_LIMIT },
+ { signal }
+ )
+ return response.results.map(productTourToSearchItem)
+ },
+ ticket: async ({ text, name, freeText }, signal, context) => {
+ const search = name && isTicketNumberQuery(text) ? freeText : text
+ if (search && !shouldSearchTickets(search)) {
+ return []
+ }
+ const response = await conversationsTicketsList(
+ String(context.currentTeamId),
+ { search: search || undefined, limit: RESULTS_LIMIT },
+ { signal }
+ )
+ return response.results.map(ticketResultToSearchItem)
+ },
+ workflows: async (terms, signal, context) => {
+ if (!terms.name) {
+ return unifiedTypeSearch('hog_flow', 'workflows')(terms, signal, context)
+ }
+ if (terms.freeText) {
+ return unifiedTypeSearch('hog_flow', 'workflows')({ ...terms, text: terms.freeText }, signal, context)
+ }
+ const response = await hogFlowsList(
+ String(context.currentTeamId),
+ { name: terms.name, limit: RESULTS_LIMIT },
+ { signal }
+ )
+ return response.results.map(hogFlowToSearchItem)
+ },
+}
+
+const PHRASE_FILTER_KEYS = new Set(['is', 'name'])
+
+function typeSearchFor(search: string): TypeSearch | null {
+ const type = tokenize(search)
+ .map((token) => parseToken(token.raw))
+ .find((token) => token.filter?.key === 'is' && !token.negated)?.value
+ return type && Object.hasOwn(TYPE_SEARCHES, type) ? TYPE_SEARCHES[type] : null
+}
+
+const nameOf = (item: SearchItem): string => String(item.displayName || item.name).toLowerCase()
+
+async function fetchTypeResults(
+ search: string,
+ signal: AbortSignal,
+ context: RemoteContext
+): Promise<SearchItem[] | null> {
+ const typeSearch = typeSearchFor(search)
+ if (!typeSearch) {
+ return null
+ }
+ const terms = typeSearchTerms({ backendSearch: search })
+ const otherFilters = tokenize(search)
+ .map((token) => parseToken(token.raw))
+ .some((token) => token.filter && !PHRASE_FILTER_KEYS.has(token.filter.key))
+ if (terms.excludes || otherFilters) {
+ return []
+ }
+ const items = await typeSearch(terms, signal, context)
+ const name = terms.name?.toLowerCase()
+ return name ? items.filter((item) => nameOf(item).includes(name)) : items
+}
+
+export function requestDebounceMs(request: RemoteRequest, query: string): number {
+ const fast = FAST_REQUESTS.includes(request.id) && !(request.id === 'objects' && typeSearchFor(query))
+ return fast ? OBJECTS_DEBOUNCE_MS : REMOTE_DEBOUNCE_MS
+}
+
+function fileSystemSearches(search: string): string[] {
+ const raws = tokenize(search).map((token) => token.raw)
+ const index = raws.findIndex((raw) => {
+ const token = parseToken(raw)
+ return token.filter?.key === 'is' && fileSystemTypesFor(token.value).length > 1
+ })
+ if (index === -1) {
+ return [search]
+ }
+ const token = parseToken(raws[index])
+ const replaced = (replacement: string): string =>
+ [...raws.slice(0, index), replacement, ...raws.slice(index + 1)].join(' ')
+ const types = fileSystemTypesFor(token.value)
+ return token.negated
+ ? [replaced(types.map((type) => `-type:${type}`).join(' '))]
+ : types.map((type) => replaced(`type:${type}`))
+}
+
+async function fetchFileSystemResults(
+ search: string,
+ signal: AbortSignal,
+ context: RemoteContext,
+ featureFlags: Record<string, unknown>,
+ merged: boolean
+): Promise<SearchItem[]> {
+ if (freeWords(search).length > 0) {
+ return await fetchRankedResults(search, signal, context, featureFlags)
+ }
+ const response = await api.fileSystem.list({
+ search,
+ limit: RESULTS_LIMIT,
+ notType: 'folder',
+ orderBy: merged ? '-created_at' : undefined,
+ signal,
+ })
+ return response.results
+ .filter((entry) => isFileSystemEntryTypeEnabled(entry, featureFlags))
+ .map((entry) => fileSystemEntryToSearchItem(entry, { id: entry.id, category: 'results' }))
+}
+
+const createdAtOf = (item: SearchItem): string => String(item.record?.created_at ?? '')
+
+function mergeFileSystemResults(batches: SearchItem[][], ranked: boolean): SearchItem[] {
+ const items = batches.flat()
+ return ranked
+ ? items.sort((a, b) => compareRanks(a.rankKey ?? [], b.rankKey ?? []))
+ : items.sort((a, b) => createdAtOf(b).localeCompare(createdAtOf(a))).slice(0, RESULTS_LIMIT)
+}
+
export const REMOTE_REQUESTS: RemoteRequest[] = [
{
id: 'objects',
query: 'objects',
sources: ['results'],
fetch: async (search, signal, context) => {
- const featureFlags = featureFlagLogic.findMounted()?.values.featureFlags ?? {}
- if (freeWords(search).length > 0) {
- return { results: await fetchRankedResults(search, signal, context, featureFlags) }
+ const typeResults = await fetchTypeResults(search, signal, context)
+ if (typeResults) {
+ return { results: typeResults }
}
- const response = await api.fileSystem.list({ search, limit: RESULTS_LIMIT, notType: 'folder', signal })
+ const featureFlags = featureFlagLogic.findMounted()?.values.featureFlags ?? {}
+ const searches = fileSystemSearches(search)
+ const batches = await Promise.all(
+ searches.map((each) => fetchFileSystemResults(each, signal, context, featureFlags, searches.length > 1))
+ )
return {
- results: response.results
- .filter((entry) => isFileSystemEntryTypeEnabled(entry, featureFlags))
- .map((entry) => fileSystemEntryToSearchItem(entry, { id: entry.id, category: 'results' })),
+ results:
+ batches.length === 1 ? batches[0] : mergeFileSystemResults(batches, freeWords(search).length > 0),
}
},
},
diff --git a/frontend/src/lib/components/Search/searchItemDisplay.tsx b/frontend/src/lib/components/Search/searchItemDisplay.tsx
index da629d27f150..d0d9ca1859fa 100644
--- a/frontend/src/lib/components/Search/searchItemDisplay.tsx
+++ b/frontend/src/lib/components/Search/searchItemDisplay.tsx
@@ -75,6 +75,8 @@ export const getIconForItem = (item: SearchItem): ReactNode => {
itemType = 'persons'
} else if (itemType === 'hog_flow') {
itemType = 'workflows'
+ } else if (itemType === 'alert') {
+ itemType = 'inbox'
}
if (itemType) {
// Handle iconColor which may be a single-element array or tuple
diff --git a/frontend/src/lib/components/Search/searchItems.tsx b/frontend/src/lib/components/Search/searchItems.tsx
index 6fbab7bed74c..5801e7a2e921 100644
--- a/frontend/src/lib/components/Search/searchItems.tsx
+++ b/frontend/src/lib/components/Search/searchItems.tsx
@@ -12,9 +12,12 @@ import { getTreeItemsProducts } from '~/products'
import { FileSystemEntry } from '~/queries/schema/schema-general'
import { FileSystemIconColor, GroupTypeIndex, SearchResponse } from '~/types'
+import type { AlertApi } from 'products/alerts/frontend/generated/api.schemas'
import type { TicketApi } from 'products/conversations/frontend/generated/api.schemas'
import { getAccountStatusTags } from 'products/customer_analytics/frontend/components/Accounts/accountStatusTags'
import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type { ProductTourApi } from 'products/product_tours/frontend/generated/api.schemas'
+import type { HogFlowMinimalApi } from 'products/workflows/frontend/generated/api.schemas'
import { filterSearchItems } from './utils'
@@ -241,13 +244,18 @@ export const accountToSearchItem = (account: AccountApi): SearchItem => {
}
}
+// 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.
+const ticketSubject = (ticket: TicketApi): string =>
+ ticket.email_subject || ticket.last_message_text || 'Untitled ticket'
+
+const ticketStatus = (ticket: TicketApi): string | null =>
+ ticket.status ? capitalizeFirstLetter(ticket.status.replace(/_/g, ' ')) : null
+
export const ticketToSearchItem = (ticket: TicketApi): SearchItem => {
- // 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
+ // 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}`
+ const displayName = `#${ticket.ticket_number} ${ticketSubject(ticket)}`
return {
id: `ticket-${ticket.id}`,
name: displayName,
@@ -259,11 +267,69 @@ export const ticketToSearchItem = (ticket: TicketApi): SearchItem => {
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,
+ productCategory: ticketStatus(ticket),
record: { type: 'conversations', id: ticket.id, ticketNumber: ticket.ticket_number },
}
}
+export const ticketResultToSearchItem = (ticket: TicketApi): SearchItem => {
+ const person = (ticket.person?.properties ?? {}) as Record<string, unknown>
+ const traits = (ticket.anonymous_traits ?? {}) as Record<string, unknown>
+ const subject = ticketSubject(ticket)
+ return {
+ id: `ticket-${ticket.id}`,
+ name: subject,
+ displayName: subject,
+ category: 'results',
+ href: urls.supportTicketDetail(ticket.ticket_number),
+ itemType: 'conversations',
+ productCategory: [
+ `#${ticket.ticket_number}`,
+ safeString(person.name) || safeString(person.email) || safeString(traits.name) || safeString(traits.email),
+ ticketStatus(ticket),
+ ]
+ .filter(Boolean)
+ .join(' · '),
+ record: { type: 'ticket', id: ticket.id, ticketNumber: ticket.ticket_number, created_at: ticket.created_at },
+ }
+}
+
+export const alertToSearchItem = (alert: AlertApi): SearchItem => {
+ const displayName = alert.name || `Alert for ${alert.insight_display_name}`
+ return {
+ id: `alert-${alert.id}`,
+ name: displayName,
+ displayName,
+ category: 'results',
+ href: urls.alert(alert.id),
+ itemType: 'alert',
+ record: { type: 'alert', id: alert.id },
+ }
+}
+
+export const hogFlowToSearchItem = (flow: HogFlowMinimalApi): SearchItem => {
+ const name = flow.name || 'Untitled workflow'
+ return {
+ id: `hog_flow-${flow.id}`,
+ name,
+ displayName: name,
+ category: 'results',
+ href: urls.workflow(flow.id, 'workflow'),
+ itemType: 'hog_flow',
+ record: { type: 'workflows', id: flow.id, created_at: flow.created_at },
+ }
+}
+
+export const productTourToSearchItem = (tour: ProductTourApi): SearchItem => ({
+ id: `product_tour-${tour.id}`,
+ name: tour.name,
+ displayName: tour.name,
+ category: 'results',
+ href: urls.productTour(tour.id),
+ itemType: 'product_tour',
+ record: { type: 'product_tour', id: tour.id },
+})
+
/** "Create new" items match when every word is "new"/"create" or appears in the item's name, type, or path. */
const LEADING_CREATE_WORD = /^\s*create\b/i
diff --git a/frontend/src/lib/components/Search/utils.ts b/frontend/src/lib/components/Search/utils.ts
index 46c93fa4617e..57950742af85 100644
--- a/frontend/src/lib/components/Search/utils.ts
+++ b/frontend/src/lib/components/Search/utils.ts
@@ -103,6 +103,8 @@ const TICKET_SEARCH_MAX_LENGTH = 200
* 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 isTicketNumberQuery = (query: string): boolean => TICKET_NUMBER_QUERY.test(query.trim())
+
export const shouldSearchTickets = (query: string): boolean => {
const trimmed = query.trim()
if (trimmed.length > TICKET_SEARCH_MAX_LENGTH) {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 58daa3ead04b..61ea1c9dbe7a 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -1768,7 +1768,7 @@ export type SearchableEntity =
| 'survey'
export type SearchListParams = {
- q: string
+ q?: string
entities?: SearchableEntity[]
include_counts?: boolean
}
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 8458e4692d51..2cf04f938642 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -18634,6 +18634,7 @@ export namespace Endpoints {
id: string;
latest_send_first: boolean;
limit: number;
+ name: string;
offset: number;
optimization_enabled: boolean;
origin_product: "broadcasts" | "loops" | "transactional_emails";
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index a5aeb0397ae4..6777f40b158c 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -732,7 +732,7 @@ class WorkflowArchived(Exception):
class WorkflowListQuery:
"""What a workflow list asks for. The view validates each value before it builds one.
- ``field_filters`` holds the raw exact-match and ``optimization_enabled`` query parameters. The
+ ``field_filters`` holds the raw exact-match, ``name`` and ``optimization_enabled`` query parameters. The
service validates them and raises WorkflowListFiltersInvalid when one does not parse.
"""
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index c041ffabee48..243925de57c8 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -4999,6 +4999,11 @@ class HogFlowVersionMetricsRequestSerializer(AppMetricsRequestSerializer):
OpenApiTypes.BOOL,
description="Only workflows someone turned suggestions on for.",
),
+ OpenApiParameter(
+ "name",
+ OpenApiTypes.STR,
+ description="Only workflows whose name contains this text, ignoring case. Unlike `search`, it never reads descriptions, tags or step content.",
+ ),
OpenApiParameter(
"search",
OpenApiTypes.STR,
diff --git a/products/workflows/backend/services/hog_flow_reads.py b/products/workflows/backend/services/hog_flow_reads.py
index f4f5510d038f..04c7f4215141 100644
--- a/products/workflows/backend/services/hog_flow_reads.py
+++ b/products/workflows/backend/services/hog_flow_reads.py
@@ -12,7 +12,7 @@ from django.db.models import Count, F, OuterRef, Prefetch, Q, QuerySet, Subquery
from django.db.models.expressions import RawSQL
from django.db.models.functions import Coalesce
-from django_filters import BooleanFilter, FilterSet
+from django_filters import BooleanFilter, CharFilter, FilterSet
from posthog.api.tagged_item import current_tag_names
from posthog.models import TaggedItem
@@ -206,6 +206,7 @@ WORKFLOW_FIELD_FILTER_PARAMS: Final[tuple[str, ...]] = (
"origin_product",
"source_record",
"optimization_enabled",
+ "name",
)
@@ -489,6 +490,11 @@ class _WorkflowFilterSet(FilterSet):
method="filter_optimization_enabled",
label="Only workflows someone turned suggestions on for.",
)
+ name = CharFilter(
+ field_name="name",
+ lookup_expr="icontains",
+ label="Only workflows whose name contains this text, ignoring case.",
+ )
class Meta:
model = HogFlow
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index 6b57a5e13c61..869112244d3c 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -383,6 +383,9 @@ class TestHogFlowAPI(APIBaseTest):
("tier_decision_respects_status_filter", "search=march&status=draft", {"Billing"}),
("tier_decision_respects_type_filter", "search=march&type=messaging", {"Billing"}),
("no_match", "search=nonexistent", set()),
+ ("name_filter_matches_inside_words", "name=ELCOME", {"Welcome email"}),
+ ("name_filter_skips_description_and_tags", "name=quarterly", set()),
+ ("name_filter_never_reads_step_content", "name=for march", set()),
]
)
def test_list_search_matches_name_description_and_step_content(self, _name, query, expected_names):
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 47c9d6af1c70..634b2988bc91 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -3152,6 +3152,10 @@ export type HogFlowsListParams = {
* @maximum 500
*/
limit?: number
+ /**
+ * Only workflows whose name contains this text, ignoring case. Unlike `search`, it never reads descriptions, tags or step content.
+ */
+ name?: string
/**
* The initial index from which to return the results.
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1943ad85f308..4198f8d774fe 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -127342,6 +127342,10 @@ export namespace Schemas {
* @maximum 500
*/
limit?: number;
+ /**
+ * Only workflows whose name contains this text, ignoring case. Unlike `search`, it never reads descriptions, tags or step content.
+ */
+ name?: string;
/**
* The initial index from which to return the results.
*/
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index 67bd5962f3c0..abf4e1122464 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -41,6 +41,12 @@ export const HogFlowsListQueryParams = () => zod.object({
"Pass `true` to order by when each workflow's newest completed or partially_failed run finished, newest first. Workflows that never finished such a run come last."
),
limit: zod.number().max(hogFlowsListQueryLimitMax).optional().describe('Number of results to return per page.'),
+ name: zod
+ .string()
+ .optional()
+ .describe(
+ 'Only workflows whose name contains this text, ignoring case. Unlike `search`, it never reads descriptions, tags or step content.'
+ ),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
optimization_enabled: zod.boolean().optional().describe('Only workflows someone turned suggestions on for.'),
origin_product: zod
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index 46fda93b509f..ce8336514d0d 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -505,6 +505,7 @@ const workflowsList = (): ToolBase<
id: params.id,
latest_send_first: params.latest_send_first,
limit: params.limit,
+ name: params.name,
offset: params.offset,
optimization_enabled: params.optimization_enabled,
origin_product: params.origin_product,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json
index 0bd1fd77e164..beb9ba8ca545 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json
@@ -30,6 +30,10 @@
"maximum": 500,
"type": "number"
},
+ "name": {
+ "description": "Only workflows whose name contains this text, ignoring case. Unlike `search`, it never reads descriptions, tags or step content.",
+ "type": "string"
+ },
"offset": {
"description": "The initial index from which to return the results.",
"type": "number"