: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(search): rank command k results by relevance and group by type (#119600)
Shy Alter9d56c95a86b0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4cfc399acbb3..fe030cae2cce 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -704,6 +704,14 @@ snapshots:hash: v1.k794b7964.4484e7d68af11aaef170ca21b18f643a52c0450fcccf7145858f42058f3a7274.o3_BNw21CY4AJQQyiGz6hgboSFv6n16lHhQwWdI6SA4components-command-k-search--empty--light:hash: v1.k794b7964.fad5dab496146f2d1b2d91797627e8fb1561aa7ebfa136e797405d6e4ffc0a7f.XWb09o2rM_vyj5XpvqH59nnKZIdGRyV1LuxMzax6oLg+ components-command-k-search-notice--close-spellings--dark:+ hash: v1.k794b7964.ffa192d267350a8866038659a7415aed68505662d35ae38774d58f83d5836c77.mHzLJfwxAGLcu-XeF7aGcByPBoDWki0HcQVfD-vHjos+ components-command-k-search-notice--close-spellings--light:+ hash: v1.k794b7964.7a81581812a843af47069f7a86d3982f2a0ba8b9e4fec8804cb1a91779443e4a.Z8uer5AZh-Zy1wS_zU6OZUoaWYWb2GZrMRDM4sDzVU8+ components-command-k-search-notice--dropped-words--dark:+ hash: v1.k794b7964.259e4c3562a18454623215ebe36100a6129dc1c30987e6fe20cc0d6d43f24b60.Twr-9LR3ttpqe9iltZFbYAfhNlo0zNxq4xN-0FdGTfs+ components-command-k-search-notice--dropped-words--light:+ hash: v1.k794b7964.1fcbca111172c8a7ddfb791761d4d493d323a4412303c2c31f768791a024a8a7.zdSy2g93nROxW1XpRUe84P5EzQ0lPROjGfeFudKYEWEcomponents-compact-list--compact-list--dark:hash: v1.k794b7964.59d9b22dc4c1fabb38cfa1c8072b3f6e3e4140bfddef6160e568f935c0ba7f29.aeZmv2PM9H27yaixZr0lFX-5hBEr1ET0-8F-DJP_QS4components-compact-list--compact-list--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 73130e348e34..7dc761ca3697 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -5072,6 +5072,35 @@ export interface FileSystemHomeFolderApi {readonly path: string | null}+export interface FileSystemRankedSearchItemApi {+ /** The matching file system entry. */+ entry: FileSystemApi+ /** Sort key of the match. Lower sorts first. Compare element by element with other results. */+ rank: number[]+}++export interface FileSystemRankedSearchTypeCountApi {+ /** File system type, for example insight or dashboard. */+ type: string+ /** Number of matches of this type. */+ count: number+}++export interface FileSystemRankedSearchResponseApi {+ /** Matches, best first. */+ results: FileSystemRankedSearchItemApi[]+ /** True when every result contains every search word. False when no entry matched every word and the results match only some words. */+ matched_all_words: boolean+ /** Search words that the best result matched. Use it to tell the user which words were dropped when matched_all_words is false. */+ matched_words: string[]+ /** Number of matches for each type, largest first. */+ type_counts: FileSystemRankedSearchTypeCountApi[]+ /** True when no entry matched the words as typed, so every result is a close spelling. */+ matched_with_typos: boolean+ /** True when the search stopped at its candidate limit, so type_counts are lower bounds. */+ counts_capped: boolean+}+export interface FileSystemShortcutApi {readonly id: string/** Display path of the shortcut in the sidebar. */@@ -6973,6 +7002,27 @@ export type FileSystemDestroyParams = {recursive?: boolean}+export type FileSystemSearchRetrieveParams = {+ /**+ * Maximum number of results to return, best first.+ * @minimum 1+ * @maximum 100+ */+ limit?: number+ /**+ * Also include the best matches of every type, up to this many per type, so each type can show a preview.+ * @minimum 0+ * @maximum 10+ */+ per_type?: number+ /**+ * Search text. Supports the same field filters as the list search (type:, user:, path:, name:, negation with - or !). Free words are ranked by relevance.+ * @minLength 1+ * @maxLength 200+ */+ search: string+}+export type FileSystemShortcutListParams = {/*** Number of results to return per page.diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 508e722923bf..f10262f8a804 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -38,6 +38,8 @@ import type {FileSystemDestroyParams,FileSystemHomeFolderApi,FileSystemListParams,+ FileSystemRankedSearchResponseApi,+ FileSystemSearchRetrieveParams,FileSystemShortcutApi,FileSystemShortcutBulkUpdateApi,FileSystemShortcutListParams,@@ -1986,6 +1988,37 @@ export const fileSystemLogViewCreate = async (})}+export const getFileSystemSearchRetrieveUrl = (projectId: string, params: FileSystemSearchRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/file_system/search/?${stringifiedParams}`+ : `/api/projects/${projectId}/file_system/search/`+}++/**+ * Ranks entries by words matched, typos, word proximity, name before folder, exact words, word position, exactness, the user's recent views, and recency.+ * @summary Search files by relevance+ */+export const fileSystemSearchRetrieve = async (+ projectId: string,+ params: FileSystemSearchRetrieveParams,+ options?: RequestInit+): Promise<FileSystemRankedSearchResponseApi> => {+ return apiMutator<FileSystemRankedSearchResponseApi>(getFileSystemSearchRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getFileSystemUndoDeleteCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/file_system/undo_delete/`}diff --git a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.mdindex 70137fface00..cb1cac66b005 100644--- a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md+++ b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md@@ -91,14 +91,27 @@ The input is always in exactly one mode, decided from the token under the cursor### Search mode- Free text plus all committed chips go to the file system endpoint in one request. Typing a value that names exactly one option (`is:dashboard`) commits it as a chip without Space, as if its suggestion were picked.+- A search with words goes to the ranked search endpoint (`file_system/search/`). A search made only of filters goes to the list endpoint, because there are no words to rank.- Sections, in this fixed order, covering everything the current palette finds:- 1. **Results**: file system objects (insights, dashboards, feature flags, experiments, surveys, notebooks, cohorts, actions, early access features, replay playlists, data pipelines).- 2. In-memory lists, filtered on every keystroke: **Products**, **Data management**, **People**, **Health**, **Misc**, **Settings** (with a Dark mode / Light mode row for "dark", "light", "theme", "appearance"), **Create new**.+ 1. **Results**: file system objects (insights, dashboards, feature flags, experiments, surveys, notebooks, cohorts, actions, early access features, replay playlists, data pipelines), and products. For a search with words, see [Ranked results](#ranked-results).+ 2. In-memory lists, filtered on every keystroke: **Data management**, **People**, **Health**, **Misc**, **Settings** (with a Dark mode / Light mode row for "dark", "light", "theme", "appearance"), **Create new**. For a search with words they keep only items that match every word with no typo. Products rank with the results instead.3. Remote lists that the file system does not hold: **Events**, **Properties**, **Workflows** (one unified search request), **Accounts** (behind the customer analytics flag), **Support tickets** (3+ characters or a ticket number), **Persons**, **Groups**.4. **Ask PostHog AI**.- With any filter (a chip, or a valid `key:value` still being typed), only **Results** and **Ask PostHog AI** show, because filters apply only to objects.- With an `is:` chip (not negated), **Results** holds a **View all <types>** row (`View all feature flags`) that opens the list page of that type. With no search text it is the first row; once you type a search it moves below the results. It shows only for types with a list page.+### Ranked results++Results for a search with words follow ordered tie-breaking rules: words matched, typos, word proximity, name before folder, exact words, word position, exactness, the person's recent views, then recency. Products rank with the same rules through their name and search keywords, so "recordings" finds Session replay.++- When no result has every word, results use the words that matched. A callout above the results names the dropped word ("No matches for **xyzzy**. Showing results for **report**."). When every match needs a typo, it says "No exact matches for **dashbord**. Showing close spellings." The callout is not selectable.+- **Best matches** comes first: the three best results of different types.+- The other results follow in groups by type, each with its total count and up to three rows. A group ends with a **See all N <types>** row that adds the `is:` chip and keeps the words. A one-word search that starts a type name (`dash`, `flag`) moves that type's group up.+- 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.+- 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 filtersKeys are case-insensitive. `createdby:` and `createdBy:` are the same token.@@ -139,13 +152,13 @@ Rule for adding a filter: it ships only when its values can be suggested (staticThese are the rules reviewers check. Breaking one is a bug.-1. **Fixed section order.** Sections render in the order in this doc for a given mode. A section never moves above another because its data arrived first.+1. **Fixed section order.** Sections render in the order in this doc for a given mode. A section never moves above another because its data arrived first. Ranked groups are ordered by their best result for each query, and do not move while that query's rows stay on screen.2. **Reserve space while loading.** The Results section renders skeleton rows at its last known height (or 3 on its first load) while it loads. It does not collapse to zero and then expand. Sections below Results that usually come back empty (Events, Properties, Workflows, Accounts, Support tickets, Persons, Groups) reserve nothing on their first load and appear only once they have rows, so skeletons never show up just to collapse.3. **Never blank on keystroke.** Keep the previous result set visible (dimmed slightly after 150 ms) until the new set arrives. Swap in one commit.4. **No mid-query re-rank.** Once rows for a query string are painted, later responses for the same query append to their own section. They never reorder rows above them.5. **Highlight follows identity, not index.** The highlighted row is tracked by item key (`section/type:ref`). Once the person moves the highlight (arrow keys or pointer), it stays on that item through result swaps for the same query while the item still exists. If it is gone, or the person never moved it, the first row is highlighted. Any change to the query (typing, clearing, adding or removing a chip) starts again at the first row.6. **Fixed row height.** Every row is one line, same height. Long names truncate with an ellipsis; the type label and timestamp never wrap.-7. **Instant local, deferred remote.** Local sources (recents, starred, products, filter keys, type values, cached members) filter synchronously on every keystroke. Remote search debounces at 150 ms.+7. **Instant local, deferred remote.** Local sources (recents, starred, products, filter keys, type values, cached members) filter synchronously on every keystroke. Remote search debounces at 150 ms, except the file system search, which debounces at 50 ms.8. **Latest wins.** Each remote request is aborted when a newer one starts (`AbortController`). A late response for an older query is dropped, never painted.9. **Chips don't reflow the list.** Committing a chip changes the query but follows rules 3 to 5 like any other edit.@@ -153,7 +166,7 @@ These are the rules reviewers check. Breaking one is a bug.- Keystroke to paint: under 16 ms for local filtering. Measure in the React profiler before merging.- Remote result under 300 ms p95 for `file_system` search with filters.-- Per-section caps: Filters 3, Suggestions 8 (`is:` lists every type, since that list is short and fixed), Results 20, Recents 5, Products, Settings, Persons and Groups 5 each in Search mode. No virtualization needed at these sizes.+- Per-section caps: Filters 3, Suggestions 8 (`is:` lists every type, since that list is short and fixed), Results 20 (a ranked search fetches 40 and shows up to 3 per group), Recents 5, Products, Settings, Persons and Groups 5 each in Search mode. No virtualization needed at these sizes.- Cache remote responses by normalized query string (sorted chips + trimmed text) for the life of the palette. Backspacing to an earlier query paints from cache with zero network.- Org members for `createdBy:` and folders for `in:` load the first time that filter is used, then filter locally. Opening the palette sends no request.- The parser and the local filters are pure and memoized on input text.@@ -193,6 +206,6 @@ These are the rules reviewers check. Breaking one is a bug.Every step emits an event so we can see adoption and drop-off:- `command k search opened` (source: shortcut, button)-- `command k filter suggested` / `command k filter committed` (key, value kind, via: tab, enter, space, paste)-- `command k result opened` (section, position, has_filters, filter_keys, query_length)+- `command k filter suggested` / `command k filter committed` (key, value kind, via: tab, enter, space, paste, see-all)+- `command k result opened` (section, position, has_filters, filter_keys, query_length, ranked_section: `best-matches`, `group-<type>`, or the local section)- `command k search abandoned` (closed with no result opened; last mode, had_filters)diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchNotice.stories.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchNotice.stories.tsxnew file mode 100644index 000000000000..71a5eaadcd47--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchNotice.stories.tsx@@ -0,0 +1,26 @@+import { Meta, StoryObj } from '@storybook/react'++import { CommandKSearchNotice } from './CommandKSearchNotice'++const meta: Meta<typeof CommandKSearchNotice> = {+ title: 'Components/Command K search/Notice',+ component: CommandKSearchNotice,+ decorators: [+ (Story) => (+ <div data-quill className="w-160 bg-card p-1">+ <Story />+ </div>+ ),+ ],+}+export default meta++type Story = StoryObj<typeof CommandKSearchNotice>++export const DroppedWords: Story = {+ args: { row: { kind: 'notice', key: 'notice/partial', reason: 'partial', missing: ['xyzzy'], shown: ['report'] } },+}++export const CloseSpellings: Story = {+ args: { row: { kind: 'notice', key: 'notice/typos', reason: 'typos', missing: ['dashbord'], shown: ['dashbord'] } },+}diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchNotice.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchNotice.tsxnew file mode 100644index 000000000000..a392dcfdf0fd--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchNotice.tsx@@ -0,0 +1,37 @@+import { IconInfo } from '@posthog/icons'+import { Item, ItemContent, ItemMedia } from '@posthog/quill'++import { CommandKRow } from './commandKSections'++type NoticeRow = Extract<CommandKRow, { kind: 'notice' }>++const Words = ({ words }: { words: string[] }): JSX.Element => (+ <span className="font-medium text-foreground">{words.join(' ')}</span>+)++export function CommandKSearchNotice({ row }: { row: NoticeRow }): JSX.Element {+ return (+ <Item+ size="xs"+ variant="outline"+ className="min-h-8 gap-1.5 rounded-md px-2 py-1.5"+ data-attr={`command-k-notice-${row.reason}`}+ role="status"+ >+ <ItemMedia variant="icon" className="text-muted-foreground">+ <IconInfo className="size-3.5" />+ </ItemMedia>+ <ItemContent className="text-xs text-muted-foreground">+ {row.reason === 'partial' ? (+ <span>+ No matches for <Words words={row.missing} />. Showing results for <Words words={row.shown} />.+ </span>+ ) : (+ <span>+ No exact matches for <Words words={row.missing} />. Showing close spellings.+ </span>+ )}+ </ItemContent>+ </Item>+ )+}diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsxnew file mode 100644index 000000000000..5ccc04814d7e--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx@@ -0,0 +1,75 @@+import { getIconForItem, getItemTypeDisplayName } from 'lib/components/Search/searchItemDisplay'+import { SearchItem } from 'lib/components/Search/searchItems'+import { formatRelativeTimeShort } from 'lib/components/Search/utils'+import { capitalizeFirstLetter } from 'lib/utils/strings'++import { splitPath } from '~/layout/panel-layout/ProjectTree/utils'++import { highlightSegments } from './commandKRanking'+import { CommandKRow } from './commandKSections'++const userFolder = (item: SearchItem): string | null => {+ const segments = splitPath(String(item.record?.path ?? '')).slice(0, -1)+ return segments.length === 0 || segments[0] === 'Unfiled' ? null : segments.join(' › ')+}++function rankedContext(item: SearchItem, showCreator: boolean): { detail: string | null; tail: string | null } {+ if (item.category !== 'results') {+ return {+ detail: item.parentName ? `in ${item.parentName}` : null,+ tail: item.matchedSearchKeyword ? `Matches "${item.matchedSearchKeyword}"` : null,+ }+ }+ const age = item.lastViewedAt+ ? `viewed ${formatRelativeTimeShort(item.lastViewedAt)}`+ : item.record?.created_at+ ? `created ${formatRelativeTimeShort(String(item.record.created_at))}`+ : null+ const detail = [userFolder(item), showCreator ? item.createdByName : null].filter(Boolean).join(' · ')+ return { detail: detail || null, tail: age }+}++export function CommandKSearchRankedItem({ row }: { row: Extract<CommandKRow, { kind: 'item' }> }): JSX.Element {+ const { item } = row+ const typeLabel = !row.showType+ ? null+ : item.category === 'results'+ ? getItemTypeDisplayName(item.itemType)+ : 'Product'+ const context = rankedContext(item, !!row.showCreator)+ return (+ <>+ {getIconForItem(item)}+ <span className="truncate" translate="no">+ {highlightSegments(String(item.displayName || item.name), row.highlightWords ?? []).map(+ (segment, index) =>+ segment.match ? (+ <span key={index} className="font-semibold">+ {segment.text}+ </span>+ ) : (+ segment.text+ )+ )}+ </span>+ {typeLabel && (+ <span className="shrink-0 text-xs text-muted-foreground">{capitalizeFirstLetter(typeLabel)}</span>+ )}+ {row.duplicates ? (+ <span+ className="shrink-0 rounded-sm border border-input px-1 text-xxs text-muted-foreground"+ title="Items with the same name are combined. Open the type to see them all."+ >+ {`+${row.duplicates} with this name`}+ </span>+ ) : null}+ {(context.detail || context.tail) && (+ <span className="ml-auto flex max-w-1/2 shrink-0 items-center gap-1 whitespace-nowrap pl-2 text-xs text-muted-foreground">+ {context.detail && <span className="min-w-0 truncate">{context.detail}</span>}+ {context.detail && context.tail && <span className="shrink-0">·</span>}+ {context.tail && <span className="shrink-0">{context.tail}</span>}+ </span>+ )}+ </>+ )+}diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsxindex b0c474e29b8d..20047fbfc6e2 100644--- a/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx@@ -1,7 +1,7 @@import { useActions } from 'kea'import { memo } from 'react'-import { IconFilter, IconFolder, IconPerson, IconSparkles } from '@posthog/icons'+import { IconArrowRight, IconFilter, IconFolder, IconPerson, IconSparkles } from '@posthog/icons'import { Button, Skeleton, cn } from '@posthog/quill'import { getIconForItem, getItemTypeDisplayName } from 'lib/components/Search/searchItemDisplay'@@ -12,6 +12,7 @@ import { ProductIconWrapper, iconForType } from '~/layout/panel-layout/ProjectTrimport { FileSystemIconType } from '~/queries/schema/schema-general'import { commandKSearchLogic } from './commandKSearchLogic'+import { CommandKSearchRankedItem } from './CommandKSearchRankedItem'import { CommandKRow } from './commandKSections'export const rowDomId = (key: string): string => `command-k-row-${key.replace(/[^a-zA-Z0-9_-]/g, '_')}`@@ -66,6 +67,9 @@ function RowContent({ row }: { row: CommandKRow }): JSX.Element | null {)case 'item': {const { item } = row+ if (row.ranked) {+ return <CommandKSearchRankedItem row={row} />+ }const typeLabel = SECTIONS_WITH_TYPE_LABEL.has(row.section)? item.groupNoun || getItemTypeDisplayName(item.itemType): null@@ -102,6 +106,13 @@ function RowContent({ row }: { row: CommandKRow }): JSX.Element | null {</>)}+ case 'scope':+ return (+ <>+ <IconArrowRight className="size-4 shrink-0 text-muted-foreground" />+ <span className="truncate text-muted-foreground">{row.label}</span>+ </>+ )default:return null}@@ -123,6 +134,10 @@ const rowContent = (row: CommandKRow): unknown => {return row.filtercase 'ask-ai':return row.question+ case 'scope':+ return row.label+ case 'notice':+ return row.keycase 'message':return row.textcase 'skeleton':@@ -130,12 +145,18 @@ const rowContent = (row: CommandKRow): unknown => {}}+const rowDisplay = (row: CommandKRow): string | null =>+ row.kind === 'item'+ ? [row.highlightWords?.join(' '), row.duplicates, row.showType, row.showCreator].join('|')+ : null+export const CommandKSearchRow = memo(CommandKSearchRowInner,(prev: CommandKSearchRowProps, next: CommandKSearchRowProps) =>prev.highlighted === next.highlighted &&prev.row.key === next.row.key &&- rowContent(prev.row) === rowContent(next.row)+ rowContent(prev.row) === rowContent(next.row) &&+ rowDisplay(prev.row) === rowDisplay(next.row))function CommandKSearchRowInner({ row, highlighted }: CommandKSearchRowProps): JSX.Element {diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsxindex f2f8dcad14e6..eb419a02acf2 100644--- a/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsx+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsx@@ -1,5 +1,6 @@import { MenuLabel, cn } from '@posthog/quill'+import { CommandKSearchNotice } from './CommandKSearchNotice'import { CommandKSearchRow } from './CommandKSearchRow'import { CommandKSection } from './commandKSections'@@ -10,6 +11,15 @@ export function CommandKSearchSection({section: CommandKSectionhighlightedKey: string | null}): JSX.Element {+ if (section.key === 'notice') {+ return (+ <div className="px-1 pt-1.5 pb-0.5" data-attr="command-k-section-notice">+ {section.rows.map((row) =>+ row.kind === 'notice' ? <CommandKSearchNotice key={row.key} row={row} /> : null+ )}+ </div>+ )+ }return (<divrole="group"@@ -18,6 +28,11 @@ export function CommandKSearchSection({><MenuLabel id={`command-k-section-${section.key}`} className="sticky top-0 z-10 bg-card px-2 pb-0">{section.label}+ {section.count !== undefined && (+ <span className="ml-1.5 font-normal tracking-normal tabular-nums">+ {`${section.count.toLocaleString()}${section.countIsLowerBound ? '+' : ''}`}+ </span>+ )}</MenuLabel><divclassName={cn(diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.tsnew file mode 100644index 000000000000..1f5c0d2bf911--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts@@ -0,0 +1,157 @@+import { SearchItem } from 'lib/components/Search/searchItems'++import { buildRankedResults } from './commandKRankedResults'+import type { CommandKSection } from './commandKSections'++const result = (+ id: string,+ name: string,+ type: string,+ rankKey: number[],+ match: Partial<NonNullable<SearchItem['searchMatch']>> = {}+): SearchItem => ({+ id,+ name,+ category: 'results',+ record: { type, ref: id, path: `Unfiled/${name}` },+ rankKey,+ searchMatch: {+ matchedAllWords: true,+ matchedWords: [],+ typeCount: 1,+ countsCapped: false,+ withTypos: false,+ ...match,+ },+})++const product = (name: string, searchKeywords: string[] = []): SearchItem => ({+ id: `product-${name}`,+ name,+ category: 'products',+ searchKeywords,+})++const exactWordRank = (created: number): number[] => [-1, 0, 0, 0, -1, 0, 2, 0, -created]++const summary = (sections: CommandKSection[]): string[] =>+ sections.map((section) => {+ const rows = section.rows.map((row) => {+ if (row.kind === 'item') {+ return `${row.item.name}${row.duplicates ? ` +${row.duplicates}` : ''}`+ }+ if (row.kind === 'notice') {+ return `(${row.reason}: ${row.missing.join(' ')} -> ${row.shown.join(' ')})`+ }+ return row.kind === 'scope' || row.kind === 'message'+ ? `(${row.kind === 'scope' ? row.label : row.text})`+ : row.kind+ })+ return `${section.label || section.key}: ${rows.join(', ')}`+ })++describe('buildRankedResults', () => {+ test.each([+ {+ name: 'a product matched by an alias leads the best matches',+ query: 'recordings',+ results: [result('1', 'Recordings funnel', 'insight', exactWordRank(2))],+ products: [product('Session replay', ['recordings']), product('Surveys')],+ expected: ['Results: Session replay, Recordings funnel'],+ },+ {+ name: 'a product that matches fewer words than the saved objects stays out',+ query: 'flags billing',+ results: [result('1', 'Feature flags billing', 'insight', [-2, 0, 0, 0, -2, 0, 3, 0, -1])],+ products: [product('Feature flags')],+ expected: ['Results: Feature flags billing'],+ },+ {+ name: 'same-name rows collapse and the see-all count covers what is hidden',+ query: 'retention',+ results: [+ result('1', 'Retention', 'insight', exactWordRank(9), { typeCount: 10 }),+ result('2', 'Retention', 'insight', exactWordRank(8), { typeCount: 10 }),+ result('3', 'Retention by plan', 'insight', exactWordRank(7), { typeCount: 10 }),+ result('4', 'Retention weekly', 'insight', exactWordRank(6), { typeCount: 10 }),+ result('5', 'Retention (copy)', 'insight', exactWordRank(5), { typeCount: 10 }),+ result('6', 'Retention daily', 'insight', exactWordRank(4), { typeCount: 10 }),+ result('7', 'Retention monthly', 'insight', exactWordRank(3), { typeCount: 10 }),+ result('10', 'Retention by country', 'insight', exactWordRank(3), { typeCount: 10 }),+ result('11', 'Retention by device', 'insight', exactWordRank(3), { typeCount: 10 }),+ result('12', 'Retention by browser', 'insight', exactWordRank(3), { typeCount: 10 }),+ result('8', 'Retention board', 'dashboard', exactWordRank(2), { typeCount: 2 }),+ result('9', 'Retention deep dive', 'dashboard', exactWordRank(1), { typeCount: 2 }),+ ],+ products: [],+ expected: [+ 'Best matches: Retention +2, Retention board',+ 'Insights: Retention by plan, Retention weekly, Retention daily, (See all 10 insights)',+ 'Dashboards: Retention deep dive',+ ],+ },+ {+ name: 'a type whose results collapse into one best match keeps its see-all row',+ query: 'revenue',+ results: [+ ...[30, 29, 28].map((created) =>+ result(`insight-${created}`, 'Revenue', 'insight', exactWordRank(created), { typeCount: 50 })+ ),+ ...['a', 'b', 'c', 'd', 'e'].map((suffix, index) =>+ result(`dashboard-${suffix}`, `Revenue board ${suffix}`, 'dashboard', exactWordRank(20 - index), {+ typeCount: 5,+ })+ ),+ ...['a', 'b', 'c', 'd'].map((suffix, index) =>+ result(`notebook-${suffix}`, `Revenue notes ${suffix}`, 'notebook', exactWordRank(10 - index), {+ typeCount: 4,+ })+ ),+ ],+ products: [],+ expected: [+ 'Best matches: Revenue +2, Revenue board a, Revenue notes a',+ 'Dashboards: Revenue board b, Revenue board c, Revenue board d, (See all 5 dashboards)',+ 'Notebooks: Revenue notes b, Revenue notes c, Revenue notes d',+ 'Insights: (See all 50 insights)',+ ],+ },+ {+ name: 'a product that matches every word hides the dropped-words notice',+ query: 'session replay',+ results: [+ result('1', 'Replay notes', 'notebook', [-1, 0, 0, 0, -1, 0, 2, 0, -1], {+ matchedAllWords: false,+ matchedWords: ['replay'],+ }),+ ],+ products: [product('Session replay')],+ expected: ['Results: Session replay'],+ },+ {+ name: 'results that match only some words say which words were used',+ query: 'xyzzy report',+ results: [+ result('1', 'Weekly report', 'insight', [-1, 0, 0, 1, -1, 1, 5, 0, -1], {+ matchedAllWords: false,+ matchedWords: ['report'],+ }),+ ],+ products: [],+ expected: ['notice: (partial: xyzzy -> report)', 'Results: Weekly report'],+ },+ ])('$name', ({ query, results, products, expected }) => {+ expect(+ summary(+ buildRankedResults({+ query,+ highlightWords: query.split(' '),+ results,+ products,+ state: 'ready',+ scoped: false,+ })+ )+ ).toEqual(expected)+ })+})diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.tsnew file mode 100644index 000000000000..895ebebbd9fb--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts@@ -0,0 +1,277 @@+import { getItemTypeDisplayName } from 'lib/components/Search/searchItemDisplay'+import { SearchItem } from 'lib/components/Search/searchItems'+import { capitalizeFirstLetter } from 'lib/utils/strings'++import { pluralTypeName } from './commandKFilterOptions'+import { RankKey, compareRanks, rankLocalItem, searchWords, tokenTypos } from './commandKRanking'+import type { CommandKRow, CommandKSection } from './commandKSections'++const BEST_MATCHES_LIMIT = 3+const GROUP_LIMIT = 3+const FLAT_LIST_LIMIT = 8++interface RankedItem {+ item: SearchItem+ rank: RankKey+ groupKey: string+}++const groupKeyFor = (item: SearchItem): string =>+ item.category === 'results' ? String(item.record?.type ?? item.itemType ?? 'other') : item.category++function groupLabel(groupKey: string): string {+ if (groupKey === 'products') {+ return 'Products'+ }+ return capitalizeFirstLetter(pluralTypeName(getItemTypeDisplayName(groupKey) ?? groupKey.replace(/_/g, ' ')))+}++function rankProducts(products: SearchItem[], query: string): RankedItem[] {+ return products.flatMap((item) => {+ const ranked = rankLocalItem(query, String(item.displayName || item.name), item.searchKeywords)+ return ranked+ ? [+ {+ item: ranked.matchedAlias ? { ...item, matchedSearchKeyword: ranked.matchedAlias } : item,+ rank: ranked.rank,+ groupKey: 'products',+ },+ ]+ : []+ })+}++const itemRow = (+ section: string,+ item: SearchItem,+ highlightWords: string[],+ duplicates = 0,+ showCreator = false,+ showType = section === 'best-matches'+): CommandKRow => ({+ kind: 'item',+ key: `${section}/${item.id}`,+ item,+ section: item.category === 'results' ? 'results' : 'products',+ highlightWords,+ ranked: true,+ showType,+ ...(duplicates ? { duplicates } : {}),+ ...(showCreator ? { showCreator } : {}),+})++const normalizedName = (item: SearchItem): string =>+ String(item.displayName || item.name)+ .toLowerCase()+ .replace(/\s*\((copy|duplicate)( \d+)?\)\s*$/, '')+ .replace(/\s+/g, ' ')+ .trim()++interface CollapsedItem extends RankedItem {+ duplicates: number+}++function collapseSameName(entries: RankedItem[]): CollapsedItem[] {+ const byName = new Map<string, CollapsedItem>()+ const collapsed: CollapsedItem[] = []+ for (const entry of entries) {+ const key = `${entry.groupKey}|${normalizedName(entry.item)}`+ const existing = byName.get(key)+ if (existing) {+ existing.duplicates+++ continue+ }+ const kept = { ...entry, duplicates: 0 }+ byName.set(key, kept)+ collapsed.push(kept)+ }+ return collapsed+}++function noticeSection(+ match: SearchItem['searchMatch'],+ words: string[],+ shown: { allWords: boolean; withTypos: boolean },+ state: CommandKSection['state']+): CommandKSection[] {+ if (!match || !words.length) {+ return []+ }+ const missing = words.filter((word) => !match.matchedWords.includes(word))+ const reason =+ !match.matchedAllWords && !shown.allWords && missing.length > 0+ ? 'partial'+ : match.withTypos && shown.withTypos+ ? 'typos'+ : null+ if (!reason) {+ return []+ }+ return [+ {+ key: 'notice',+ label: '',+ rows: [+ {+ kind: 'notice',+ key: `notice/${reason}`,+ reason,+ missing: reason === 'partial' ? missing : words,+ shown: match.matchedWords,+ },+ ],+ state,+ },+ ]+}++interface RankedResultsInput {+ query: string+ highlightWords: string[]+ results: SearchItem[]+ products: SearchItem[]+ state: CommandKSection['state']+ scoped: boolean+}++export function buildRankedResults({+ query,+ highlightWords,+ results,+ products,+ state,+ scoped,+}: RankedResultsInput): CommandKSection[] {+ const candidates: RankedItem[] = [+ ...results.map((item) => ({ item, rank: item.rankKey ?? [], groupKey: groupKeyFor(item) })),+ ...rankProducts(products, query),+ ].sort((a, b) => compareRanks(a.rank, b.rank))+ if (!candidates.length) {+ return []+ }+ const queryWords = searchWords(query)+ 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 notices =+ state === 'stale'+ ? []+ : noticeSection(+ results[0]?.searchMatch,+ highlightWords,+ { allWords: -mostWordsMatched >= new Set(queryWords).size, withTypos: fewestTypos > 0 },+ state+ )+ if (scoped) {+ const nameCounts = new Map<string, number>()+ for (const entry of matching) {+ nameCounts.set(normalizedName(entry.item), (nameCounts.get(normalizedName(entry.item)) ?? 0) + 1)+ }+ return [+ ...notices,+ {+ key: 'results',+ label: 'Results',+ rows: matching.map((entry) =>+ itemRow(+ 'results',+ entry.item,+ highlightWords,+ 0,+ (nameCounts.get(normalizedName(entry.item)) ?? 0) > 1+ )+ ),+ state,+ },+ ]+ }+ const pool = collapseSameName(matching)+ const groupCount = new Set(pool.map((entry) => entry.groupKey)).size+ if (pool.length <= FLAT_LIST_LIMIT || groupCount === 1) {+ return [+ ...notices,+ {+ key: 'best-matches',+ label: 'Results',+ rows: pool.map((entry) =>+ itemRow('flat', entry.item, highlightWords, entry.duplicates, entry.duplicates > 0, groupCount > 1)+ ),+ state,+ },+ ]+ }+ const best: CollapsedItem[] = []+ const seenGroups = new Set<string>()+ for (const entry of pool) {+ if (best.length === BEST_MATCHES_LIMIT) {+ break+ }+ if (!seenGroups.has(entry.groupKey)) {+ best.push(entry)+ seenGroups.add(entry.groupKey)+ }+ }+ const groups = new Map<string, CollapsedItem[]>()+ for (const entry of pool) {+ if (best.includes(entry)) {+ continue+ }+ groups.set(entry.groupKey, [...(groups.get(entry.groupKey) ?? []), entry])+ }+ for (const entry of best) {+ if (!groups.has(entry.groupKey)) {+ groups.set(entry.groupKey, [])+ }+ }+ const sections: CommandKSection[] = [+ ...notices,+ {+ key: 'best-matches',+ label: 'Best matches',+ rows: best.map((entry) =>+ itemRow('best-matches', entry.item, highlightWords, entry.duplicates, entry.duplicates > 0)+ ),+ state,+ },+ ]+ const typeIntent = (groupKey: string): boolean =>+ queryWords.length === 1 &&+ queryWords[0].length >= 3 &&+ groupKey !== 'products' &&+ searchWords(groupLabel(groupKey)).some((word) => tokenTypos(queryWords[0], word) !== null)+ const orderedGroups = [...groups].sort(([a], [b]) => Number(typeIntent(b)) - Number(typeIntent(a)))+ for (const [groupKey, entries] of orderedGroups) {+ const shown = entries.slice(0, GROUP_LIMIT)+ const inBest = best.filter((entry) => entry.groupKey === groupKey)+ const sample = entries[0] ?? inBest[0]+ const total = Math.max(sample.item.searchMatch?.typeCount ?? 0, entries.length + inBest.length)+ const rows: CommandKRow[] = shown.map((entry) =>+ itemRow(`group-${groupKey}`, entry.item, highlightWords, entry.duplicates, entry.duplicates > 0)+ )+ const covered = inBest.length + shown.reduce((sum, entry) => sum + 1 + entry.duplicates, 0)+ if (groupKey !== 'products' && total > covered) {+ rows.push({+ kind: 'scope',+ key: `group-${groupKey}/see-all`,+ type: groupKey,+ label: capped+ ? `See all ${groupLabel(groupKey).toLowerCase()}`+ : `See all ${total.toLocaleString()} ${groupLabel(groupKey).toLowerCase()}`,+ })+ }+ if (!rows.length) {+ continue+ }+ sections.push({+ key: `group-${groupKey}`,+ label: groupLabel(groupKey),+ count: total,+ countIsLowerBound: capped && groupKey !== 'products',+ rows,+ state,+ })+ }+ return sections+}diff --git a/frontend/src/lib/components/CommandKSearch/commandKRanking.test.ts b/frontend/src/lib/components/CommandKSearch/commandKRanking.test.tsnew file mode 100644index 000000000000..468fe6135fe9--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKRanking.test.ts@@ -0,0 +1,39 @@+import { compareRanks, highlightSegments, rankLocalItem, strictLocalMatches } from './commandKRanking'++const marked = (name: string, words: string[]): string =>+ highlightSegments(name, words)+ .map((segment) => (segment.match ? `[${segment.text}]` : segment.text))+ .join('')++describe('commandKRanking', () => {+ test.each([+ {+ name: 'Revenue: signup to first paid invoice',+ words: ['rev', 'sign'],+ expected: '[Rev]enue: [sign]up to first paid invoice',+ },+ { name: 'Weekly retention', words: ['retension'], expected: 'Weekly [retention]' },+ { name: 'web-revenue-tracking', words: ['revenue'], expected: 'web-[revenue]-tracking' },+ { name: 'Pageviews', words: [], expected: 'Pageviews' },+ ])('highlights $words in $name', ({ name, words, expected }) => {+ expect(marked(name, words)).toEqual(expected)+ })++ test.each([+ { query: 'recordings', name: 'Session replay', aliases: ['recordings'], alias: 'recordings' },+ { query: 'survey', name: 'Surveys', aliases: ['feedback'], alias: null },+ ])('ranks $name for $query by its best name or alias', ({ query, name, aliases, alias }) => {+ expect(rankLocalItem(query, name, aliases)?.matchedAlias).toEqual(alias)+ })++ it('matches a plural query to a singular name without a typo', () => {+ expect(strictLocalMatches([{ name: 'Survey' }, { name: 'Surveyed users' }], 'surveys')).toEqual([+ { name: 'Survey' },+ ])+ })++ it('gives a repeated word no proximity bonus', () => {+ const rank = (name: string): number[] => rankLocalItem('sign signup', name)?.rank ?? []+ expect(compareRanks(rank('Sign signup'), rank('Signup'))).toBeLessThan(0)+ })+})diff --git a/frontend/src/lib/components/CommandKSearch/commandKRanking.ts b/frontend/src/lib/components/CommandKSearch/commandKRanking.tsnew file mode 100644index 000000000000..fbc4a1f3549f--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKRanking.ts@@ -0,0 +1,226 @@+const WORD = /[\p{L}\p{N}_]+/gu++export type RankKey = number[]++const MIN_ALIAS_QUERY_LENGTH = 3+const STARTS_WITH = 1++export const searchWords = (text: string): string[] => text.toLowerCase().match(WORD) ?? []++export const FILTER_TOKEN = /(^|\s)([-!]\S+|(path|name|user|author|type|ref):("[^"]*"|\S*))/gi++export const freeWords = (query: string): string[] => searchWords(query.replace(FILTER_TOKEN, ' '))++function osaDistance(a: string, b: string): number {+ if (!a.length) {+ return b.length+ }+ if (!b.length) {+ return a.length+ }+ let previousPrevious: number[] = []+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j)+ for (let i = 1; i <= a.length; i++) {+ const current = [i]+ for (let j = 1; j <= b.length; j++) {+ let value = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {+ value = Math.min(value, previousPrevious[j - 2] + 1)+ }+ current.push(value)+ }+ previousPrevious = previous+ previous = current+ }+ return previous[b.length]+}++const singular = (word: string): string =>+ word.length > 3 && word.endsWith('s') && !word.endsWith('ss') ? word.slice(0, -1) : word++const singularText = (text: string): string => searchWords(text).map(singular).join(' ')++const allowedTypos = (token: string): number => (token.length < 5 ? 0 : token.length < 9 ? 1 : 2)++export function tokenTypos(token: string, word: string): number | null {+ if (word.startsWith(token) || word === singular(token)) {+ return 0+ }+ const budget = allowedTypos(token)+ if (!budget) {+ return null+ }+ const distance = Math.min(+ osaDistance(token, word.slice(0, token.length)),+ osaDistance(token, word),+ osaDistance(token, singular(word))+ )+ return distance <= budget ? distance : null+}++function bestMatch(token: string, words: string[]): [number, number] | null {+ let best: [number, number] | null = null+ for (let position = 0; position < words.length; position++) {+ const typos = tokenTypos(token, words[position])+ if (typos !== null && (!best || typos < best[0])) {+ best = [typos, position]+ if (typos === 0) {+ break+ }+ }+ }+ return best+}++const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')++function exactness(query: string, name: string, nameWords: string[]): number {+ if (name === query || singularText(name) === singularText(query)) {+ return 0+ }+ if (name.startsWith(query)) {+ return 1+ }+ if (nameWords.some((word) => word.startsWith(query)) || new RegExp(`(^|\\W)${escapeRegExp(query)}`).test(name)) {+ return 2+ }+ if (name.includes(query)) {+ return 3+ }+ if (+ nameWords+ .map((word) => word[0])+ .join('')+ .startsWith(query.replace(/ /g, ''))+ ) {+ return 4+ }+ return 5+}++function rankName(query: string, tokens: string[], name: string): RankKey | null {+ const lowerName = name.toLowerCase()+ const nameWords = searchWords(lowerName)+ let matched = 0+ let typos = 0+ let exactWords = 0+ const positions: number[] = []+ for (const token of tokens) {+ const hit = bestMatch(token, nameWords)+ if (!hit) {+ continue+ }+ matched+++ typos += hit[0]+ positions.push(hit[1])+ if (tokens.length > 1 && nameWords.some((word) => singular(word) === singular(token))) {+ exactWords+++ }+ }+ if (!matched) {+ return null+ }+ if (tokens.length === 1 && singularText(lowerName) === singularText(query)) {+ exactWords = 1+ }+ let proximity = 0+ for (let i = 1; i < positions.length; i++) {+ proximity +=+ Math.max(Math.abs(positions[i] - positions[i - 1]) - 1, 0) + (positions[i] < positions[i - 1] ? 1 : 0)+ }+ return [+ -matched,+ typos,+ proximity,+ matched === tokens.length ? 0 : 1,+ -exactWords,+ 0,+ Math.min(exactness(query, lowerName, nameWords), STARTS_WITH),+ 0,+ -Number.MAX_SAFE_INTEGER,+ ]+}++export const compareRanks = (a: RankKey, b: RankKey): number => {+ for (let i = 0; i < Math.min(a.length, b.length); i++) {+ if (a[i] !== b[i]) {+ return a[i] - b[i]+ }+ }+ return a.length - b.length+}++interface LocalRank {+ rank: RankKey+ matchedAlias: string | null+}++export function rankLocalItem(query: string, name: string, aliases: string[] = []): LocalRank | null {+ const normalized = query.trim().toLowerCase().replace(/\s+/g, ' ')+ const tokens = searchWords(normalized)+ if (!tokens.length) {+ return null+ }+ let best: LocalRank | null = null+ const byName = rankName(normalized, tokens, name)+ if (byName) {+ best = { rank: byName, matchedAlias: null }+ }+ for (const alias of normalized.length >= MIN_ALIAS_QUERY_LENGTH ? aliases : []) {+ const byAlias = rankName(normalized, tokens, alias)+ if (byAlias && (!best || compareRanks(byAlias, best.rank) < 0)) {+ best = { rank: byAlias, matchedAlias: alias }+ }+ }+ return best+}++interface HighlightSegment {+ text: string+ match: boolean+}++export function highlightSegments(name: string, words: string[]): HighlightSegment[] {+ if (!words.length) {+ return [{ text: name, match: false }]+ }+ const segments: HighlightSegment[] = []+ let cursor = 0+ for (const found of name.matchAll(WORD)) {+ const word = found[0].toLowerCase()+ const start = found.index ?? 0+ const prefix = words.find((token) => word.startsWith(token))+ const length = prefix+ ? prefix.length+ : words.some((token) => tokenTypos(token, word) !== null)+ ? word.length+ : 0+ if (!length) {+ continue+ }+ if (start > cursor) {+ segments.push({ text: name.slice(cursor, start), match: false })+ }+ segments.push({ text: name.slice(start, start + length), match: true })+ cursor = start + length+ }+ if (cursor < name.length) {+ segments.push({ text: name.slice(cursor), match: false })+ }+ return segments+}++export function strictLocalMatches<T extends { name: string; displayName?: string; searchKeywords?: string[] }>(+ items: T[],+ query: string+): T[] {+ const words = searchWords(query).length+ return items+ .map((item) => ({+ item,+ ranked: rankLocalItem(query, String(item.displayName || item.name), item.searchKeywords),+ }))+ .filter(({ ranked }) => ranked !== null && -ranked.rank[0] === words && ranked.rank[1] === 0)+ .sort((a, b) => compareRanks(a.ranked!.rank, b.ranked!.rank))+ .map(({ item }) => item)+}diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.tsindex 9ec7da4c5797..6f8f24974fda 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts@@ -25,4 +25,17 @@ describe('commandKSearchLogic', () => {expect(logic.values.highlightedKey).toBeNull()})++ it('a See all row narrows the search to its type and keeps the words', () => {+ logic.actions.inputChanged('revenue', 7, false)++ logic.actions.activateRow(+ { kind: 'scope', key: 'group-insight/see-all', type: 'insight', label: 'See all insights' },+ false,+ 'click'+ )++ expect(logic.values.chips).toEqual([expect.objectContaining({ key: 'is', value: 'insight', negated: false })])+ expect(logic.values.text).toEqual('revenue')+ })})diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsxindex 9fa99dd196dd..9d0a302bde0d 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx@@ -74,8 +74,9 @@ import {import { REMOTE_REQUESTS, RemoteContext, RemoteResults, RemoteSource, settleSources } from './commandKSources'const REMOTE_DEBOUNCE_MS = 150+const OBJECTS_DEBOUNCE_MS = 50-export type CommitVia = 'tab' | 'enter' | 'space' | 'paste' | 'click' | 'typed'+export type CommitVia = 'tab' | 'enter' | 'space' | 'paste' | 'click' | 'typed' | 'see-all'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface commandKSearchLogicValues {@@ -702,6 +703,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([actions.markResultOpened()posthog.capture('command k result opened', {section: row.kind === 'item' ? row.section : 'ask-ai',+ ranked_section: row.key.split('/')[0],position: values.selectableRows.findIndex((candidate) => candidate.key === row.key),has_filters: values.chips.length > 0,filter_keys: values.chips.map((chip) => chip.key),@@ -852,6 +854,13 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([context.kind === 'value' ? context.token : null,via)+ } else if (row.kind === 'scope') {+ const option = values.filterOptions.is.find((candidate) => candidate.value === row.type)+ actions.commitChip(+ { key: 'is', value: row.type, label: option?.label ?? row.type, negated: false },+ null,+ 'see-all'+ )} else {openRow(row, newTab)}@@ -893,6 +902,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([)continue}+ const debounceMs = request.id === 'objects' ? OBJECTS_DEBOUNCE_MS : REMOTE_DEBOUNCE_MS// One disposable per request covers the debounce and the fetch, so a newer query// cancels both, and unmounting cancels everything.cache.disposables.add(@@ -909,7 +919,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([actions.remoteLoaded(query, results)}})- }, REMOTE_DEBOUNCE_MS)+ }, debounceMs)return () => {clearTimeout(timer)controller.abort()diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.test.tsindex 15907034a31e..d96041b3eda0 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts@@ -53,8 +53,8 @@ const input = (mode: CommandKMode, overrides: Partial<SectionsInput>): SectionsIconst remoteResults = (items: SearchItem[]): Partial<SectionsInput> => {const remote = emptyRemoteSlots()- remote.results = { cache: { revenue: items }, displayedKey: 'revenue' }- return { remote, remoteQueries: { results: 'revenue' } }+ remote.results = { cache: { 'type:dashboard': items }, displayedKey: 'type:dashboard' }+ return { remote, remoteQueries: { results: 'type:dashboard' } }}describe('buildSections', () => {@@ -82,7 +82,7 @@ describe('buildSections', () => {item: { id: 'view-all', name: 'View all feature flags', category: 'results', href: '/feature_flags' },placement,}- const loading = buildSections(input('search', { remoteQueries: { results: 'x' }, viewAll }))+ const loading = buildSections(input('search', { remoteQueries: { results: 'type:dashboard' }, viewAll }))const loaded = buildSections(input('search', { ...remoteResults([dashboard('a', '1')]), viewAll }))const rowKeys = (sections: ReturnType<typeof buildSections>): string[] =>sections.find((section) => section.key === 'results')?.rows.map((row) => row.key.replace('results/', '')) ??@@ -90,4 +90,114 @@ describe('buildSections', () => {expect(rowKeys(loading)).toEqual(whileLoading)expect(rowKeys(loaded)).toEqual(onceLoaded)})++ it('keeps the View all row on ranked results of one type', () => {+ const viewAll: ViewAll = {+ item: { id: 'view-all', name: 'View all dashboards', category: 'results', href: '/dashboard' },+ placement: 'trail',+ }+ const remote = emptyRemoteSlots()+ remote.results = {+ cache: { 'type:dashboard revenue': [{ ...dashboard('a', '1'), rankKey: [-1, 0, 0, 0, -1, 0, 2, 0, 0] }] },+ displayedKey: null,+ }+ const sections = buildSections(+ input('search', {+ remote,+ remoteQueries: { results: 'type:dashboard revenue' },+ localQuery: 'revenue',+ viewAll,+ })+ )+ expect(sections.find((section) => section.key === 'results')?.rows.map((row) => row.key)).toEqual([+ 'results/a',+ 'results/view-all',+ ])+ })++ it('lists filter-only results without ranking them', () => {+ const remote = emptyRemoteSlots()+ remote.results = {+ cache: { 'type:dashboard': [{ ...dashboard('a', '1'), rankKey: [] }] },+ displayedKey: 'type:dashboard',+ }+ const sections = buildSections(input('search', { remote, remoteQueries: { results: 'type:dashboard' } }))+ expect(sections.find((section) => section.key === 'results')?.rows.map((row) => row.key)).toEqual([+ 'results/dashboard:1',+ ])+ })++ it('ranks product tabs with the products', () => {+ const tab: SearchItem = {+ id: 'product-collections',+ name: 'Collections',+ category: 'products',+ parentName: 'Session replay',+ searchKeywords: ['playlists'],+ }+ const sections = buildSections(+ input('search', {+ local: { ...emptyLocal(), products: [tab] },+ remoteQueries: { results: 'playlists' },+ localQuery: 'playlists',+ })+ )+ expect(sections[0].rows.map((row) => (row.kind === 'item' ? row.item.name : row.kind))).toEqual(['Collections'])+ })++ it('shows skeletons instead of unranked filter-only rows while ranked results load', () => {+ const remote = emptyRemoteSlots()+ remote.results = { cache: { 'type:dashboard': [dashboard('a', '1')] }, displayedKey: 'type:dashboard' }+ const sections = buildSections(+ input('search', { remote, remoteQueries: { results: 'type:dashboard revenue' }, localQuery: 'revenue' })+ )+ expect(sections.find((section) => section.key === 'results')?.rows.map((row) => row.kind)).toEqual([+ 'skeleton',+ 'skeleton',+ 'skeleton',+ ])+ })++ it('says which words were dropped when a filter is active', () => {+ const remote = emptyRemoteSlots()+ remote.results = {+ cache: {+ 'type:dashboard xyzzy report': [+ {+ ...dashboard('a', '1'),+ rankKey: [-1, 0, 0, 1, -1, 1, 5, 0, -1],+ searchMatch: {+ matchedAllWords: false,+ matchedWords: ['report'],+ typeCount: 1,+ countsCapped: false,+ withTypos: false,+ },+ },+ ],+ },+ displayedKey: 'type:dashboard xyzzy report',+ }+ const sections = buildSections(+ input('search', { remote, remoteQueries: { results: 'type:dashboard xyzzy report' }, localQuery: '' })+ )+ expect(sections.map((section) => section.key)).toContain('notice')+ })++ it('shows ranked products while saved objects load', () => {+ const sections = buildSections(+ input('search', {+ local: {+ ...emptyLocal(),+ products: [{ id: 'product-surveys', name: 'Surveys', category: 'products' }],+ },+ remoteQueries: { results: 'surv' },+ localQuery: 'surv',+ })+ )+ expect(sections.map((section) => [section.key, section.rows.map((row) => row.kind)])).toEqual([+ ['best-matches', ['item']],+ ['results', ['skeleton', 'skeleton', 'skeleton']],+ ])+ })})diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.tsindex cfa15420b5f5..5b3d6f580c24 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSections.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.ts@@ -2,6 +2,8 @@ import { SearchItem, filterNewItems } from 'lib/components/Search/searchItems'import { SETTINGS_THEME_ITEM_ID, filterSearchItems } from 'lib/components/Search/utils'import { CursorContext, FilterDefinition, FilterOptions, ValueOption, matchValueOptions } from './commandKQuery'+import { buildRankedResults } from './commandKRankedResults'+import { FILTER_TOKEN, freeWords, strictLocalMatches } from './commandKRanking'import { REMOTE_SOURCES, RESULTS_LIMIT, RemoteSource, SECONDARY_LIMIT } from './commandKSources'export const RECENTS_LIMIT = 5@@ -22,19 +24,36 @@ export type CommandKSectionKey =| LocalSource| RemoteSource| 'ask-ai'+ | 'notice'+ | 'best-matches'+ | `group-${string}`export type CommandKRow =| { kind: 'filter-key'; key: string; filter: FilterDefinition; negated: boolean }| { kind: 'filter-value'; key: string; filter: FilterDefinition; option: ValueOption; negated: boolean }| { kind: 'message'; key: string; text: string }| { kind: 'skeleton'; key: string }- | { kind: 'item'; key: string; item: SearchItem; section: CommandKSectionKey }+ | {+ kind: 'item'+ key: string+ item: SearchItem+ section: CommandKSectionKey+ duplicates?: number+ highlightWords?: string[]+ ranked?: boolean+ showCreator?: boolean+ showType?: boolean+ }| { kind: 'ask-ai'; key: string; question: string }+ | { kind: 'scope'; key: string; type: string; label: string }+ | { kind: 'notice'; key: string; reason: 'partial' | 'typos'; missing: string[]; shown: string[] }export interface CommandKSection {key: CommandKSectionKeylabel: stringrows: CommandKRow[]+ count?: number+ countIsLowerBound?: boolean/** `stale` keeps the previous query's rows on screen until the new ones land. */state: 'ready' | 'loading' | 'stale'}@@ -55,7 +74,7 @@ export type RemoteSlots = Record<RemoteSource, RemoteSlot>export const emptyRemoteSlots = (): RemoteSlots =>Object.fromEntries(REMOTE_SOURCES.map((source) => [source, { cache: {}, displayedKey: null }])) as RemoteSlots-const SECTION_LABELS: Record<CommandKSectionKey, string> = {+const SECTION_LABELS: Record<Exclude<CommandKSectionKey, `group-${string}`>, string> = {filters: 'Filters',suggestions: 'Suggestions',recents: 'Recents',@@ -76,9 +95,12 @@ const SECTION_LABELS: Record<CommandKSectionKey, string> = {persons: 'Persons',groups: 'Groups','ask-ai': 'PostHog AI',+ 'best-matches': 'Best matches',+ notice: '',}-export const isSelectable = (row: CommandKRow): boolean => row.kind !== 'message' && row.kind !== 'skeleton'+export const isSelectable = (row: CommandKRow): boolean =>+ row.kind !== 'message' && row.kind !== 'skeleton' && row.kind !== 'notice'const itemIdentity = (item: SearchItem): string => {const type = item.record?.type@@ -107,17 +129,17 @@ const itemRows = (section: CommandKSectionKey, items: SearchItem[], limit = Infireturn rows}-const readySection = (key: CommandKSectionKey, rows: CommandKRow[]): CommandKSection => ({+const readySection = (key: Exclude<CommandKSectionKey, `group-${string}`>, rows: CommandKRow[]): CommandKSection => ({key,label: SECTION_LABELS[key],rows,state: 'ready',})-const skeletonRows = (key: CommandKSectionKey): CommandKRow[] =>+const skeletonRows = (key: Exclude<CommandKSectionKey, `group-${string}`>): CommandKRow[] =>Array.from({ length: DEFAULT_SKELETON_ROWS }, (_, index) => ({ kind: 'skeleton', key: `${key}/skeleton-${index}` }))-const loadingSection = (key: CommandKSectionKey): CommandKSection => ({+const loadingSection = (key: Exclude<CommandKSectionKey, `group-${string}`>): CommandKSection => ({...readySection(key, skeletonRows(key)),state: 'loading',})@@ -219,6 +241,27 @@ function withViewAll(results: CommandKSection | null, viewAll: ViewAll | null):}}+function rankedResultsSections(+ slot: RemoteSlot,+ query: string,+ local: LocalLists,+ localQuery: string+): CommandKSection[] {+ const current = slot.cache[query]+ const previous = slot.displayedKey !== null ? slot.cache[slot.displayedKey] : undefined+ const displayed = current ?? (previous?.every((item) => item.rankKey?.length) ? previous : undefined)+ const words = freeWords(query)+ const ranked = buildRankedResults({+ query: words.join(' '),+ highlightWords: words,+ results: displayed ?? [],+ products: localQuery ? local.products : [],+ state: !displayed || current ? 'ready' : 'stale',+ scoped: (query.match(FILTER_TOKEN) ?? []).some((token) => token.trim().startsWith('type:')),+ })+ return displayed ? ranked : [...ranked, loadingSection('results')]+}+export function buildSections(input: SectionsInput): CommandKSection[] {const { mode, context, local, remote, remoteQueries, localQuery } = inputif (mode === 'empty') {@@ -254,10 +297,29 @@ export function buildSections(input: SectionsInput): CommandKSection[] {))}- sections.push(input.suggestions, withViewAll(remoteSectionFor('results'), input.viewAll))+ const ranked = !!remoteQueries.results && freeWords(remoteQueries.results).length > 0+ if (ranked) {+ const rankedSections = rankedResultsSections(remote.results, remoteQueries.results ?? '', local, localQuery)+ sections.push(+ input.suggestions,+ ...(rankedSections.some((section) => section.key === 'results')+ ? rankedSections.map((section) =>+ section.key === 'results' ? withViewAll(section, input.viewAll) : section+ )+ : [...rankedSections, withViewAll(null, input.viewAll)])+ )+ } else {+ sections.push(input.suggestions, withViewAll(remoteSectionFor('results'), input.viewAll))+ }if (mode !== 'value' && localQuery) {for (const source of LOCAL_SOURCES) {- const filtered = filterLocal(source, local[source], localQuery)+ if (ranked && source === 'products') {+ continue+ }+ const filtered =+ ranked && source !== 'create'+ ? strictLocalMatches(filterLocal(source, local[source], localQuery), localQuery)+ : filterLocal(source, local[source], localQuery)const themeItem = source === 'settings' ? input.themeItem : nullconst rows = themeItem? itemRows(source, [themeItem, ...filtered], SECONDARY_LIMIT + 1)diff --git a/frontend/src/lib/components/CommandKSearch/commandKSources.ts b/frontend/src/lib/components/CommandKSearch/commandKSources.tsindex 049f8dca1698..b94ba32845bc 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSources.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSources.ts@@ -13,16 +13,23 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { uuid } from 'lib/utils/dom'import { mapGroupQueryResponse } from 'lib/utils/groups'+import { fileSystemSearchRetrieve } from '~/generated/core/api'+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 { 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 { freeWords } from './commandKRanking'+export const RESULTS_LIMIT = 20export const SECONDARY_LIMIT = 5+const RANKED_RESULTS_LIMIT = 40+const RANKED_PER_TYPE = 4/*** Remote sections, in render order. Results holds the objects that filters apply to. The rest@@ -107,6 +114,51 @@ const fetchGroups = async (term: string, signal: AbortSignal, context: RemoteCon}}+const toFileSystemEntry = (entry: FileSystemApi): FileSystemEntry => ({+ id: entry.id,+ path: entry.path,+ type: entry.type,+ ref: entry.ref ?? undefined,+ href: entry.href ?? undefined,+ created_at: entry.created_at,+ last_viewed_at: entry.last_viewed_at,+ shortcut: entry.shortcut ?? undefined,+ user_access_level: entry.user_access_level,+})++const withCreator = (item: SearchItem, entry: FileSystemApi): SearchItem =>+ entry.created_by?.first_name ? { ...item, createdByName: entry.created_by.first_name } : item++const fetchRankedResults = async (+ search: string,+ signal: AbortSignal,+ context: RemoteContext,+ featureFlags: Record<string, unknown>+): Promise<SearchItem[]> => {+ const response = await fileSystemSearchRetrieve(+ String(context.currentTeamId),+ { search, limit: RANKED_RESULTS_LIMIT, per_type: RANKED_PER_TYPE },+ { signal }+ )+ const typeCounts = new Map(response.type_counts.map(({ type, count }) => [type, count]))+ return response.results+ .filter(({ entry }) => isFileSystemEntryTypeEnabled(entry, featureFlags))+ .map(({ entry, rank }) => ({+ ...withCreator(+ fileSystemEntryToSearchItem(toFileSystemEntry(entry), { id: entry.id, category: 'results' }),+ entry+ ),+ rankKey: rank,+ searchMatch: {+ matchedAllWords: response.matched_all_words,+ matchedWords: response.matched_words,+ typeCount: typeCounts.get(entry.type ?? '') ?? 0,+ countsCapped: response.counts_capped,+ withTypos: response.matched_with_typos,+ },+ }))+}+const UNIFIED_TYPES: Record<string, RemoteSource> = {event_definition: 'events',property_definition: 'properties',@@ -118,9 +170,12 @@ export const REMOTE_REQUESTS: RemoteRequest[] = [id: 'objects',query: 'objects',sources: ['results'],- fetch: async (search, signal) => {- const response = await api.fileSystem.list({ search, limit: RESULTS_LIMIT, notType: 'folder', signal })+ 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 response = await api.fileSystem.list({ search, limit: RESULTS_LIMIT, notType: 'folder', signal })return {results: response.results.filter((entry) => isFileSystemEntryTypeEnabled(entry, featureFlags))diff --git a/frontend/src/lib/components/Search/searchItemDisplay.tsx b/frontend/src/lib/components/Search/searchItemDisplay.tsxindex 489a2bf96fed..da629d27f150 100644--- a/frontend/src/lib/components/Search/searchItemDisplay.tsx+++ b/frontend/src/lib/components/Search/searchItemDisplay.tsx@@ -1,5 +1,7 @@import { ReactNode } from 'react'+import { capitalizeFirstLetter } from 'lib/utils/strings'+import { ProductIconWrapper, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { fileSystemTypes } from '~/products'import { FileSystemIconType } from '~/queries/schema/schema-general'@@ -57,8 +59,10 @@ export const getItemTypeDisplayName = (type: string | null | undefined): stringalert: 'Alert',folder: 'Folder',hog_flow: 'Workflow',+ 'hog_function/internal_destination': 'Alert destination',}- return fallbackDisplayNames[type] ?? null+ const subtype = type.includes('/') ? type.split('/').pop()?.replace(/_/g, ' ') : null+ return fallbackDisplayNames[type] ?? (subtype ? capitalizeFirstLetter(subtype) : null)}export const getIconForItem = (item: SearchItem): ReactNode => {diff --git a/frontend/src/lib/components/Search/searchItems.tsx b/frontend/src/lib/components/Search/searchItems.tsxindex c817a5b77cc0..a0914e6ca60d 100644--- a/frontend/src/lib/components/Search/searchItems.tsx+++ b/frontend/src/lib/components/Search/searchItems.tsx@@ -42,6 +42,15 @@ export interface SearchItem {parentName?: stringrecord?: Record<string, unknown>rank?: number | null // PostgreSQL full-text search rank (from unified search API)+ rankKey?: number[]+ createdByName?: string+ searchMatch?: {+ matchedAllWords: boolean+ matchedWords: string[]+ typeCount: number+ countsCapped: boolean+ withTypos: boolean+ }/** When set, the item is shown greyed out and non-clickable, with this reason as tooltip* (e.g. the user has no access to the product or resource). */disabledReason?: stringdiff --git a/posthog/api/file_system/file_system.py b/posthog/api/file_system/file_system.pyindex 56ba960bbaa2..1afb1a259e88 100644--- a/posthog/api/file_system/file_system.py+++ b/posthog/api/file_system/file_system.py@@ -24,8 +24,9 @@ from django.db.models import (When,)from django.db.models.functions import Concat, Lower+from django.utils import timezone-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import filters, pagination, serializers, status, viewsetsfrom rest_framework.exceptions import PermissionDeniedfrom rest_framework.request import Request@@ -45,12 +46,15 @@ from posthog.api.file_system.deletion import (undo_delete as undo_delete_object,)from posthog.api.file_system.file_system_logging import log_api_file_system_view+from posthog.api.file_system.ranked_search import FileRef, FileSystemRankedSearch, search_sessionfrom posthog.api.file_system.visibility import apply_file_system_visibility_filters+from posthog.api.mixins import validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.decorators import disallow_if_impersonatedfrom posthog.exceptions import Conflict+from posthog.helpers.trigram_search import MAX_SEARCH_LENGTHfrom posthog.models.file_system.constants import RETIRED_FILE_SYSTEM_TYPESfrom posthog.models.file_system.file_system import (DEFAULT_SURFACE,@@ -253,6 +257,63 @@ class FileSystemViewLogListQuerySerializer(serializers.Serializer):limit = serializers.IntegerField(required=False, min_value=1)+SEARCH_FILTER_FIELDS = {"path", "name", "user", "author", "type", "ref"}+++class FileSystemRankedSearchQuerySerializer(serializers.Serializer):+ search = serializers.CharField(+ max_length=MAX_SEARCH_LENGTH,+ help_text="Search text. Supports the same field filters as the list search (type:, user:, path:, name:, negation with - or !). Free words are ranked by relevance.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=50,+ min_value=1,+ max_value=100,+ help_text="Maximum number of results to return, best first.",+ )+ per_type = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ max_value=10,+ help_text="Also include the best matches of every type, up to this many per type, so each type can show a preview.",+ )+++class FileSystemRankedSearchItemSerializer(serializers.Serializer):+ entry = FileSystemSerializer(help_text="The matching file system entry.")+ rank = serializers.ListField(+ child=serializers.IntegerField(),+ help_text="Sort key of the match. Lower sorts first. Compare element by element with other results.",+ )+++class FileSystemRankedSearchTypeCountSerializer(serializers.Serializer):+ type = serializers.CharField(help_text="File system type, for example insight or dashboard.")+ count = serializers.IntegerField(help_text="Number of matches of this type.")+++class FileSystemRankedSearchResponseSerializer(serializers.Serializer):+ results = FileSystemRankedSearchItemSerializer(many=True, help_text="Matches, best first.")+ matched_all_words = serializers.BooleanField(+ help_text="True when every result contains every search word. False when no entry matched every word and the results match only some words."+ )+ matched_words = serializers.ListField(+ child=serializers.CharField(),+ help_text="Search words that the best result matched. Use it to tell the user which words were dropped when matched_all_words is false.",+ )+ type_counts = FileSystemRankedSearchTypeCountSerializer(+ many=True, help_text="Number of matches for each type, largest first."+ )+ matched_with_typos = serializers.BooleanField(+ help_text="True when no entry matched the words as typed, so every result is a close spelling."+ )+ counts_capped = serializers.BooleanField(+ help_text="True when the search stopped at its candidate limit, so type_counts are lower bounds."+ )++class UndoDeleteItemSerializer(serializers.Serializer):type = serializers.CharField()ref = serializers.CharField()@@ -305,6 +366,7 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object_read_actions = ["list","retrieve",+ "search","unfiled","count","count_by_path",@@ -1289,6 +1351,68 @@ class FileSystemViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):status=status.HTTP_200_OK,)+ @validated_request(+ query_serializer=FileSystemRankedSearchQuerySerializer,+ responses={200: OpenApiResponse(response=FileSystemRankedSearchResponseSerializer)},+ summary="Search files by relevance",+ description="Ranks entries by words matched, typos, word proximity, name before folder, exact words, word position, exactness, the user's recent views, and recency.",+ )+ @action(methods=["GET"], detail=False, pagination_class=None)+ def search(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ params = request.validated_query_data+ filter_tokens: list[str] = []+ free_tokens: list[str] = []+ for token in tokenize_search(params["search"]):+ bare = token.lstrip("-!")+ field, has_colon, _ = bare.partition(":")+ is_filter = bare != token or (has_colon and field.lower() in SEARCH_FILTER_FIELDS)+ (filter_tokens if is_filter else free_tokens).append(token)+ queryset = self._scope_by_project_and_environment(FileSystem.objects.select_related("created_by"))+ queryset = queryset.exclude(type__in=[*RETIRED_FILE_SYSTEM_TYPES, "folder"])+ if filter_tokens:+ queryset = self._apply_search_to_queryset(queryset, " ".join(shlex.quote(t) for t in filter_tokens))+ queryset = self._filter_by_access_control(queryset)+ ranker = FileSystemRankedSearch(+ " ".join(free_tokens),+ user_id=cast(User, request.user).id,+ team_id=self.team.id,+ today=timezone.now().date(),+ )+ with search_session(queryset.db):+ if ranker.tokens:+ result = ranker.search(queryset)+ entries = result.top(params["limit"], per_type=params["per_type"])+ matched_all_words = result.matched_all_words+ matched_words = list(entries[0].matched_tokens) if entries else []+ type_counts = sorted(result.type_counts.items(), key=lambda item: -item[1])+ counts_capped = result.counts_capped+ matched_with_typos = result.matched_with_typos+ full_entries = queryset.in_bulk([ranked_entry.entry.id for ranked_entry in entries])+ items = []+ for ranked_entry in entries:+ entry = full_entries.get(ranked_entry.entry.id)+ if entry is None:+ continue+ entry.last_viewed_at = ranker.last_viewed.get(FileRef(type=entry.type, ref=entry.ref or ""))+ items.append((entry, list(ranked_entry.rank)))+ else:+ items = [(entry, []) for entry in queryset.order_by("-created_at")[: params["limit"]]]+ matched_all_words, matched_words = True, []+ type_counts = []+ counts_capped = False+ matched_with_typos = False+ serialized = self.get_serializer([entry for entry, _ in items], many=True).data+ return Response(+ {+ "results": [{"entry": data, "rank": rank} for data, (_, rank) in zip(serialized, items)],+ "matched_all_words": matched_all_words,+ "matched_words": matched_words,+ "type_counts": [{"type": t, "count": c} for t, c in type_counts],+ "counts_capped": counts_capped,+ "matched_with_typos": matched_with_typos,+ }+ )+@action(methods=["POST"], detail=True)def count(self, request: Request, *args: Any, **kwargs: Any) -> Response:"""Get count of all files in a folder."""diff --git a/posthog/api/file_system/ranked_search.py b/posthog/api/file_system/ranked_search.pynew file mode 100644index 000000000000..a7942ee54bdb--- /dev/null+++ b/posthog/api/file_system/ranked_search.py@@ -0,0 +1,294 @@+import re+import math+from collections import Counter+from collections.abc import Iterable, Iterator, Sequence+from contextlib import contextmanager+from datetime import date, datetime+from typing import Any++from django.db import connections, transaction+from django.db.models import Case, Q, QuerySet, Value, When++from rapidfuzz.distance import OSA++from posthog.dataclasses import frozen+from posthog.models.file_system.file_system import SEARCH_NAME, SEARCH_TEXT, FileSystem, split_path+from posthog.models.file_system.file_system_view_log import FileSystemViewLog++WORD_RE = re.compile(r"\w+", re.UNICODE)+CANDIDATE_LIMIT = 2000+TYPO_TOKENS_THRESHOLD = 50+MIN_WORD_SIMILARITY = 0.4+FRECENCY_HALF_LIFE_DAYS = 14+MAX_TOKENS = 8+MIN_NAME_ORDER_TOKEN_LENGTH = 3+CANDIDATE_FIELDS = ("id", "path", "type", "ref", "created_at")++EQUAL, STARTS_WITH, WORD_STARTS_WITH, CONTAINS, ACRONYM, NO_MATCH = range(6)+++def words(text: str) -> list[str]:+ return WORD_RE.findall(text.lower())+++def path_segments(path: str) -> list[str]:+ if "\\" in path:+ return split_path(path)+ return [segment for segment in path.split("/") if segment]+++def basename(path: str) -> str:+ segments = path_segments(path)+ return segments[-1] if segments else ""+++def singular(word: str) -> str:+ return word[:-1] if len(word) > 3 and word.endswith("s") and not word.endswith("ss") else word+++def singular_text(text: str) -> str:+ return " ".join(singular(word) for word in words(text))+++def allowed_typos(token: str) -> int:+ if len(token) < 5:+ return 0+ return 1 if len(token) < 9 else 2+++def token_typos(token: str, word: str) -> int | None:+ if word.startswith(token) or word == singular(token):+ return 0+ budget = allowed_typos(token)+ if not budget:+ return None+ distance = min(+ OSA.distance(token, word[: len(token)]), OSA.distance(token, word), OSA.distance(token, singular(word))+ )+ return distance if distance <= budget else None+++@frozen+class WordMatch:+ typos: int+ position: int+++@frozen+class FileRef:+ type: str+ ref: str+++def best_match(token: str, candidates: Sequence[str]) -> WordMatch | None:+ best: WordMatch | None = None+ for position, word in enumerate(candidates):+ typos = token_typos(token, word)+ if typos is not None and (best is None or typos < best.typos):+ best = WordMatch(typos=typos, position=position)+ if typos == 0:+ break+ return best+++def exactness(query: str, singular_query: str, name: str, singular_name: str, name_words: Sequence[str]) -> int:+ if name == query or singular_name == singular_query:+ return EQUAL+ if name.startswith(query):+ return STARTS_WITH+ if any(word.startswith(query) for word in name_words) or re.search(r"(^|\W)" + re.escape(query), name):+ return WORD_STARTS_WITH+ if query in name:+ return CONTAINS+ if "".join(word[0] for word in name_words).startswith(query.replace(" ", "")):+ return ACRONYM+ return NO_MATCH+++@frozen+class RankedEntry:+ entry: FileSystem+ rank: tuple[int, ...]+ matched_tokens: tuple[str, ...]+++@frozen+class RankedSearchResult:+ entries: list[RankedEntry]+ matched_all_words: bool+ matched_with_typos: bool+ type_counts: dict[str, int]+ counts_capped: bool++ def top(self, limit: int, *, per_type: int = 0) -> list[RankedEntry]:+ kept = set(range(min(limit, len(self.entries))))+ if per_type:+ names: dict[str, set[str]] = {}+ for index, ranked in enumerate(self.entries):+ type_names = names.setdefault(ranked.entry.type, set())+ name = singular_text(basename(ranked.entry.path))+ if name not in type_names and len(type_names) < per_type:+ type_names.add(name)+ kept.add(index)+ return [self.entries[index] for index in sorted(kept)]+++@contextmanager+def search_session(using: str) -> Iterator[None]:+ with transaction.atomic(using=using), connections[using].cursor() as cursor:+ cursor.execute(+ "SELECT set_config('jit', 'off', true), set_config('pg_trgm.word_similarity_threshold', %s, true)",+ [str(MIN_WORD_SIMILARITY)],+ )+ yield+++class FileSystemRankedSearch:+ def __init__(self, query: str, *, user_id: int, team_id: int, today: date) -> None:+ self.query = " ".join(query.lower().split())+ self.tokens = tuple(dict.fromkeys(words(self.query)))[:MAX_TOKENS]+ self.singular_query = singular_text(self.query)+ self.user_id = user_id+ self.team_id = team_id+ self.today = today+ self.last_viewed: dict[FileRef, datetime] = {}+ self.capped = False++ def word_match(self, token: str, typos: bool) -> Q:+ match = Q(search_text__contains=singular(token))+ if typos and allowed_typos(token):+ match |= Q(search_name__trigram_word_similar=token)+ return match++ @property+ def filter_tokens(self) -> tuple[str, ...]:+ return tuple(token for token in self.tokens if len(token) > 1) or self.tokens++ def every_word(self, typos: bool) -> Q:+ return Q(*(self.word_match(token, typos) for token in self.filter_tokens))++ def any_word(self, typos: bool) -> Q:+ match = Q()+ for token in self.filter_tokens:+ match |= self.word_match(token, typos)+ return match++ def fetch(self, queryset: QuerySet[FileSystem], match: Q, seen: list[FileSystem]) -> list[FileSystem]:+ ordering: list[Any] = ["-created_at"]+ name_tokens = [token for token in self.filter_tokens if len(token) >= MIN_NAME_ORDER_TOKEN_LENGTH]+ if name_tokens:+ word_starts = Q(*(Q(search_name__regex=r"\m" + re.escape(singular(token))) for token in name_tokens))+ ordering.insert(0, Case(When(word_starts, then=Value(0)), default=Value(1)))+ found = list(+ queryset.filter(match).exclude(id__in=[entry.id for entry in seen]).order_by(*ordering)[:CANDIDATE_LIMIT]+ )+ self.capped = self.capped or len(found) >= CANDIDATE_LIMIT+ return seen + found++ def search(self, queryset: QuerySet[FileSystem]) -> RankedSearchResult:+ queryset = (+ queryset.select_related(None)+ .only(*CANDIDATE_FIELDS)+ .alias(search_text=SEARCH_TEXT, search_name=SEARCH_NAME)+ )+ found = self.fetch(queryset, self.every_word(typos=False), [])+ result = self.rank(found)+ if len(result.entries) >= TYPO_TOKENS_THRESHOLD:+ return result+ if any(allowed_typos(token) for token in self.tokens):+ found = self.fetch(queryset, self.every_word(typos=True), found)+ result = self.rank(found)+ if result.matched_all_words or len(self.tokens) == 1:+ return result+ found = self.fetch(queryset, self.any_word(typos=False), found)+ result = self.rank(found)+ if not result.entries:+ found = self.fetch(queryset, self.any_word(typos=True), found)+ result = self.rank(found)+ return result++ def frecency(self, entries: Iterable[FileSystem]) -> dict[FileRef, float]:+ keys = {FileRef(type=entry.type, ref=entry.ref) for entry in entries if entry.ref}+ if not keys:+ return {}+ logs = FileSystemViewLog.objects.filter(+ team_id=self.team_id,+ user_id=self.user_id,+ type__in={key.type for key in keys},+ ref__in={key.ref for key in keys},+ ).values_list("type", "ref", "view_days", "viewed_at")+ scores: dict[FileRef, float] = {}+ for type_, ref, view_days, viewed_at in logs:+ key = FileRef(type=type_, ref=ref)+ self.last_viewed[key] = viewed_at+ days = view_days or [viewed_at.date()]+ scores[key] = sum(math.pow(0.5, max((self.today - day).days, 0) / FRECENCY_HALF_LIFE_DAYS) for day in days)+ return scores++ def rank_entry(self, entry: FileSystem, frecency: float) -> RankedEntry | None:+ segments = path_segments(entry.path)+ name = segments[-1].lower() if segments else ""+ name_words = words(name)+ singular_name = " ".join(singular(word) for word in name_words)+ other_words = words(" ".join([*segments[:-1], entry.type]))+ singular_words = {singular(word) for word in (*name_words, *other_words)}+ matched, typos, in_name, exact_words = 0, 0, 0, 0+ positions: list[int] = []+ matched_tokens: list[str] = []+ for token in self.tokens:+ name_hit = best_match(token, name_words)+ other_hit = None if name_hit and not name_hit.typos else best_match(token, other_words)+ if name_hit and (other_hit is None or name_hit.typos <= other_hit.typos):+ hit: WordMatch | None = name_hit+ in_name += 1+ positions.append(name_hit.position)+ else:+ hit = other_hit+ if hit is None:+ continue+ matched += 1+ typos += hit.typos+ matched_tokens.append(token)+ if len(self.tokens) > 1 and singular(token) in singular_words:+ exact_words += 1+ if len(self.tokens) == 1 and singular_name == self.singular_query:+ exact_words = 1+ if not matched:+ return None+ proximity = sum(max(abs(b - a) - 1, 0) + (1 if b < a else 0) for a, b in zip(positions, positions[1:]))+ attribute = 0 if in_name == len(self.tokens) else 1 if in_name else 2+ rank = (+ -matched,+ typos,+ proximity,+ attribute,+ -exact_words,+ min(positions) if positions else 99,+ exactness(self.query, self.singular_query, name, singular_name, name_words),+ -int(frecency * 1000),+ -int(entry.created_at.timestamp()),+ )+ return RankedEntry(entry=entry, rank=rank, matched_tokens=tuple(matched_tokens))++ def rank(self, candidates: list[FileSystem]) -> RankedSearchResult:+ frecency = self.frecency(candidates)+ ranked = [+ ranked_entry+ for entry in candidates+ if (+ ranked_entry := self.rank_entry(entry, frecency.get(FileRef(type=entry.type, ref=entry.ref or ""), 0.0))+ )+ is not None+ ]+ most_words = max((-r.rank[0] for r in ranked), default=0)+ matching = [r for r in ranked if -r.rank[0] == most_words]+ fewest_typos = min((r.rank[1] for r in matching), default=0)+ pool = [r for r in matching if r.rank[1] == fewest_typos]+ pool.sort(key=lambda r: r.rank)+ return RankedSearchResult(+ entries=pool,+ matched_all_words=bool(matching) and most_words == len(self.tokens),+ matched_with_typos=fewest_typos > 0,+ type_counts=dict(Counter(r.entry.type for r in pool)),+ counts_capped=self.capped,+ )diff --git a/posthog/api/file_system/test/test_ranked_search.py b/posthog/api/file_system/test/test_ranked_search.pynew file mode 100644index 000000000000..53e1e1987af1--- /dev/null+++ b/posthog/api/file_system/test/test_ranked_search.py@@ -0,0 +1,188 @@+from datetime import date, timedelta++from posthog.test.base import APIBaseTest++from django.test import SimpleTestCase+from django.utils import timezone++from parameterized import parameterized+from rest_framework import status++from posthog.api.file_system.ranked_search import MAX_TOKENS, FileSystemRankedSearch+from posthog.models import Team+from posthog.models.file_system.file_system import FileSystem, split_path+from posthog.models.file_system.file_system_view_log import FileSystemViewLog+++class TestFileSystemRankedSearch(APIBaseTest):+ def _create(self, path: str, type: str = "insight", days_ago: int = 0, ref: str | None = None) -> FileSystem:+ return FileSystem.objects.create(+ team=self.team,+ path=path,+ type=type,+ ref=ref,+ created_by=self.user,+ created_at=timezone.now() - timedelta(days=days_ago),+ )++ def _search(self, search: str, **params: int) -> dict:+ data: dict[str, str | int] = {"search": search, **params}+ response = self.client.get(f"/api/projects/{self.team.id}/file_system/search/", data)+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ return response.json()++ def _names(self, data: dict) -> list[str]:+ return [split_path(item["entry"]["path"])[-1] for item in data["results"]]++ @parameterized.expand(+ [+ (+ "exact_name_before_prefix_and_substring",+ "revenue",+ ["Unfiled/Insights/Monthly revenue", "Unfiled/Insights/Revenue forecast", "Unfiled/Insights/Revenue"],+ ["Revenue", "Revenue forecast", "Monthly revenue"],+ ),+ (+ "every_word_must_match_when_possible",+ "signup funnel",+ ["Unfiled/Insights/Signup funnel", "Unfiled/Insights/Signup count", "Unfiled/Insights/Checkout funnel"],+ ["Signup funnel"],+ ),+ (+ "plural_name_counts_as_exact",+ "survey",+ ["Unfiled/Feature Flags/survey-targeting-abc", "Unfiled/Dashboards/Surveys"],+ ["Surveys", "survey-targeting-abc"],+ ),+ (+ "typo_still_finds_the_word",+ "retension",+ ["Unfiled/Insights/Weekly retention", "Unfiled/Insights/Pageviews"],+ ["Weekly retention"],+ ),+ (+ "typo_in_a_name_with_an_escaped_slash",+ "retension",+ ["Unfiled/Insights/Retention \\/ Weekly", "Unfiled/Insights/Pageviews"],+ ["Retention / Weekly"],+ ),+ (+ "name_match_before_folder_match",+ "growth",+ ["Growth team/Signups", "Unfiled/Insights/Growth weekly"],+ ["Growth weekly", "Signups"],+ ),+ (+ "plural_query_matches_singular_name",+ "surveys",+ ["Unfiled/Insights/Survey results", "Unfiled/Insights/Surveys archive"],+ ["Surveys archive", "Survey results"],+ ),+ (+ "repeated_word_gets_no_proximity_bonus",+ "sign signup",+ ["Unfiled/Insights/Signup", "Unfiled/Insights/Sign signup"],+ ["Sign signup", "Signup"],+ ),+ (+ "exact_folder_word_beats_name_typo",+ "growth",+ ["Growth/Growht", "Unfiled/Insights/Growth report"],+ ["Growth report", "Growht"],+ ),+ ]+ )+ def test_ranks_matches(self, _name: str, search: str, paths: list[str], expected: list[str]) -> None:+ for days_ago, path in enumerate(paths):+ self._create(path, type="dashboard" if "/Dashboards/" in path else "insight", days_ago=days_ago)++ self.assertEqual(self._names(self._search(search)), expected)++ @parameterized.expand(+ [+ ("unknown_word", "xyzzy report", ["Weekly report"], ["Weekly report"], ["report"]),+ ("word_with_a_colon", "revenue: xyzzy", ["Revenue - Q1"], ["Revenue - Q1"], ["revenue"]),+ (+ "close_spelling_the_ranker_rejects",+ "addon journey",+ ["Journey: platform add-on trial", "Journey funnel"],+ ["Journey: platform add-on trial", "Journey funnel"],+ ["journey"],+ ),+ (+ "more_words_beat_fewer_typos",+ "signup retension xyzzy",+ ["Signup retention", "Signup"],+ ["Signup retention"],+ ["signup", "retension"],+ ),+ (+ "rejected_candidate_does_not_stop_the_typo_fallback",+ "xyzzy retension",+ ["prexyzzyabc", "Weekly retention"],+ ["Weekly retention"],+ ["retension"],+ ),+ ]+ )+ def test_falls_back_to_some_words_and_says_which(+ self, _name: str, search: str, names: list[str], expected: list[str], matched_words: list[str]+ ) -> None:+ for days_ago, name in enumerate(names):+ self._create(f"Unfiled/Insights/{name}", days_ago=days_ago)++ data = self._search(search)++ self.assertEqual(self._names(data), expected)+ self.assertFalse(data["matched_all_words"])+ self.assertEqual(data["matched_words"], matched_words)++ def test_frecency_breaks_ties_between_equal_matches(self) -> None:+ self._create("Unfiled/Dashboards/Home", type="dashboard", ref="1", days_ago=1)+ self._create("Unfiled/Dashboards/Home", type="dashboard", ref="2", days_ago=2)+ FileSystemViewLog.objects.create(+ team=self.team, user=self.user, type="dashboard", ref="2", view_days=[timezone.now().date()]+ )++ data = self._search("home")++ self.assertEqual([item["entry"]["ref"] for item in data["results"]], ["2", "1"])++ def test_applies_filters_and_never_returns_other_projects(self) -> None:+ self._create("Unfiled/Insights/Revenue", type="insight")+ self._create("Unfiled/Dashboards/Revenue", type="dashboard")+ other_team = Team.objects.create(organization=self.organization, name="Other project")+ FileSystem.objects.create(team=other_team, path="Unfiled/Dashboards/Revenue elsewhere", type="dashboard")++ data = self._search("type:dashboard revenue")++ self.assertEqual([item["entry"]["type"] for item in data["results"]], ["dashboard"])+ self.assertEqual(data["type_counts"], [{"type": "dashboard", "count": 1}])++ def test_per_type_previews_include_lower_ranked_types(self) -> None:+ for index in range(5):+ self._create(f"Unfiled/Insights/Revenue {index}", type="insight")+ self._create("Unfiled/Dashboards/Old revenue board", type="dashboard", days_ago=30)++ data = self._search("revenue", limit=2, per_type=1)++ self.assertIn("Old revenue board", self._names(data))+ self.assertEqual(len(data["results"]), 3)++ def test_per_type_previews_skip_names_already_previewed(self) -> None:+ for index in range(4):+ self._create("Unfiled/Insights/Revenue", type="insight", days_ago=index)+ self._create("Unfiled/Insights/Revenue by plan", type="insight", days_ago=10)++ data = self._search("revenue", limit=1, per_type=2)++ self.assertEqual(self._names(data), ["Revenue", "Revenue by plan"])+++class TestFileSystemRankedSearchTokens(SimpleTestCase):+ def test_repeated_and_extra_words_are_dropped(self) -> None:+ ranker = FileSystemRankedSearch(+ " ".join(["the"] * 200 + [f"word{index}" for index in range(20)]), user_id=1, team_id=1, today=date.today()+ )++ self.assertEqual(ranker.tokens, ("the", *(f"word{index}" for index in range(MAX_TOKENS - 1))))diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex da5bcd525aad..b83218923f12 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53351,6 +53351,35 @@ export namespace Schemas {readonly path: string | null;}+ export interface FileSystemRankedSearchItem {+ /** The matching file system entry. */+ entry: FileSystem;+ /** Sort key of the match. Lower sorts first. Compare element by element with other results. */+ rank: number[];+ }++ export interface FileSystemRankedSearchTypeCount {+ /** File system type, for example insight or dashboard. */+ type: string;+ /** Number of matches of this type. */+ count: number;+ }++ export interface FileSystemRankedSearchResponse {+ /** Matches, best first. */+ results: FileSystemRankedSearchItem[];+ /** True when every result contains every search word. False when no entry matched every word and the results match only some words. */+ matched_all_words: boolean;+ /** Search words that the best result matched. Use it to tell the user which words were dropped when matched_all_words is false. */+ matched_words: string[];+ /** Number of matches for each type, largest first. */+ type_counts: FileSystemRankedSearchTypeCount[];+ /** True when no entry matched the words as typed, so every result is a close spelling. */+ matched_with_typos: boolean;+ /** True when the search stopped at its candidate limit, so type_counts are lower bounds. */+ counts_capped: boolean;+ }+export interface FileSystemShortcut {readonly id: string;/** Display path of the shortcut in the sidebar. */@@ -128905,6 +128934,27 @@ export namespace Schemas {recursive?: boolean;};+ export type FileSystemSearchRetrieveParams = {+ /**+ * Maximum number of results to return, best first.+ * @minimum 1+ * @maximum 100+ */+ limit?: number;+ /**+ * Also include the best matches of every type, up to this many per type, so each type can show a preview.+ * @minimum 0+ * @maximum 10+ */+ per_type?: number;+ /**+ * Search text. Supports the same field filters as the list search (type:, user:, path:, name:, negation with - or !). Free words are ranked by relevance.+ * @minLength 1+ * @maxLength 200+ */+ search: string;+ };+export type FileSystemShortcutListParams = {/*** Number of results to return per page.