: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): add command k search with smart filters behind flag (#112700)
Adam Leith4768e370b0a7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b42419a65ac5..2a590233d838 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -648,6 +648,14 @@ snapshots:hash: v1.k794b7964.c5168eae4c3faf5aedbd64a29598f2d0a972f1864d5051dc8f7567a960777c7b.wtf7NrB3yC_1-AcfkjfR33aOe81OdBTQcI3GITUGcC0components-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.bb2146400c33663fe6dcf1bd8ed3b728759ad68c72c676ac86f03d4abb209507.gdnIyse2UFs7BPGXjLG1EJXyF7jtrfDzCNo7LLzCwKM+ components-command-k-search--chip-and-value-suggestions--light:+ hash: v1.k794b7964.7c546a5379c0a5d025630508266a9f40c2e216a45bfa6d894d983ace0c4cae5b.MXIWq8T3Rb_keioh261ukhjJk0E279_P42OuZVDakfA+ components-command-k-search--empty--dark:+ hash: v1.k794b7964.458b55fd345ec31873d513d00258ebe6f6f6e9b1e91c4504ad4f0c16046f5151.wfpwrARigE_uao91HNDgU7NeZN24s2vP9Q3H4W4mEX4+ components-command-k-search--empty--light:+ hash: v1.k794b7964.16a8fc2aa9fe572f42c756f561dec1d929c15e01d0cf52f699cfd8eb2213a117.dQLxyVraHzdQpjon_SuAJml5zKhCoFXSJb8t4odcbj8components-compact-list--compact-list--dark:hash: v1.k794b7964.59d9b22dc4c1fabb38cfa1c8072b3f6e3e4140bfddef6160e568f935c0ba7f29.aeZmv2PM9H27yaixZr0lFX-5hBEr1ET0-8F-DJP_QS4components-compact-list--compact-list--light:diff --git a/frontend/src/lib/components/Command/Command.tsx b/frontend/src/lib/components/Command/Command.tsxindex 8a2b95c55230..74e26aadc584 100644--- a/frontend/src/lib/components/Command/Command.tsx+++ b/frontend/src/lib/components/Command/Command.tsx@@ -1,6 +1,7 @@import { useActions, useValues } from 'kea'import { useCallback } from 'react'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import { DialogPrimitive, DialogPrimitiveTitle } from 'lib/ui/DialogPrimitive/DialogPrimitive'import { cn } from 'lib/utils/css-classes'@@ -9,8 +10,9 @@ import { newInternalTab } from 'lib/utils/newInternalTab'import { todayShellLogic } from '~/layout/today/todayShellLogic'+import { CommandKSearch } from '../CommandKSearch/CommandKSearch'import { Search } from '../Search/Search'-import { SearchItem } from '../Search/searchLogic'+import { SearchItem } from '../Search/searchItems'import { commandLogic } from './commandLogic'const TODAY_PHONE_SHEET =@@ -20,6 +22,7 @@ export function Command(): JSX.Element {const { isCommandOpen } = useValues(commandLogic)const { todayRailEnabled } = useValues(todayShellLogic)const { closeCommand } = useActions(commandLogic)+ const newCommandKSearch = useFeatureFlag('NEW_COMMAND_K_SEARCH')const handleItemSelect = useCallback((item: SearchItem, openInNewTab?: boolean) => {@@ -43,6 +46,20 @@ export function Command(): JSX.Element {closeCommand()}, [closeCommand])+ if (newCommandKSearch) {+ return (+ <DialogPrimitive+ open={isCommandOpen}+ onOpenChange={(open) => !open && closeCommand()}+ className={cn('w-[640px]', todayRailEnabled && TODAY_PHONE_SHEET)}+ >+ <DialogPrimitiveTitle>Command</DialogPrimitiveTitle>+ {/* Mounted only while open, which scopes the search's caches and requests to one use of the palette. */}+ {isCommandOpen && <CommandKSearch />}+ </DialogPrimitive>+ )+ }+return (<DialogPrimitiveopen={isCommandOpen}diff --git a/frontend/src/lib/components/Command/commandLogic.tsx b/frontend/src/lib/components/Command/commandLogic.tsxindex be165dadae09..6830eb15bd88 100644--- a/frontend/src/lib/components/Command/commandLogic.tsx+++ b/frontend/src/lib/components/Command/commandLogic.tsx@@ -8,6 +8,7 @@ export type CommandOpenSource = 'keyboard-shortcut' | 'nav-search-button' | 'nav// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface commandLogicValues {isCommandOpen: boolean+ openSource: CommandOpenSource | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -41,6 +42,13 @@ export const commandLogic = kea<commandLogicType>([toggleCommand: (state) => !state,},],+ openSource: [+ null as CommandOpenSource | null,+ {+ openCommand: (_, { source }) => source,+ toggleCommand: (_, { source }) => source,+ },+ ],}),listeners(({ values }) => ({openCommand: ({ source }) => {diff --git a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.mdnew file mode 100644index 000000000000..193a192dbbfa--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md@@ -0,0 +1,196 @@+# Command K search: UX spec++Source of truth for the new Command K search.+Gated by the `new-command-k-search` feature flag (`FEATURE_FLAGS.NEW_COMMAND_K_SEARCH`).+Flag off keeps the current `Search.tsx` / `searchLogic.tsx` palette untouched.+When a change disagrees with this file, change this file in the same PR or don't ship the change.++## Goals, in priority order++1. **Stable.** Rows never jump, reorder, or blink while the user types. The highlighted row never moves under the cursor.+2. **Fast.** Every keystroke paints in the same frame. Network only adds rows; it never blocks typing or removes what is already visible.+3. **Powerful.** Smart filters (`is:dashboard createdBy:me revenue`) narrow results without leaving the keyboard.+4. **Familiar.** With an empty input, the palette looks and behaves like today's: Recents, Starred, Products.++## Building blocks++- Styled only with quill tokens (`bg-card`, `bg-background`, `text-muted-foreground`, `border-input`, `ring-ring`, `fill-selected`) under a `data-quill` root, never LemonUI tokens such as `bg-surface-primary` or `text-tertiary`.+- Built from quill primitives: `InputGroup` (with `InputGroupInput`, `InputGroupAddon`, `InputGroupButton`) for the field, `Button` rows, `MenuLabel` section headers, `Skeleton`, `Kbd`, `ScrollArea`. One combobox input, one listbox, grouped options, wired with `aria-activedescendant`.+- Not on quill's `Autocomplete`: Base UI tracks the highlight by index and cannot hold it by item identity (stability rule 5), so the logic owns the highlight.+- Committed filters render inline as text, not as boxed chips: the key in the foreground color, the value in the brand color on a light tint (`is:` **Dashboard**). They still behave as chips (select, remove, edit). There is no × on a chip; ⌫ removes it.+- The field has a fixed height. Committing a chip never resizes it; chips that overflow scroll sideways.+- One kea logic (`commandKSearchLogic`) owns state, highlight, and orchestration. Components only render and translate events. The rules live in pure modules with unit tests:+ - `commandKQuery.ts`: tokenizing, cursor context, `resolveQuery` (filters, free text, and the backend search string in one pass), and which edits commit a chip.+ - `commandKKeys.ts`: what each key press means (`keyIntent`).+ - `commandKSections.ts`: section order, suggestions, and the stale/loading rules.+ - `commandKSources.ts`: every remote request in one table (query kind, sections it fills, when it applies, how it fetches).+ - `commandKFilterOptions.ts`: the values each filter key suggests.+- The lists that need no request (products, settings, create new, and the rest) come from `searchListsLogic`, shared with the current palette, so both palettes find the same things.+- The logic mounts with the palette and unmounts when it closes. That is the whole lifecycle: mounting is the "opened" event, unmounting is "abandoned" when nothing was opened, and unmounting drops every cache and cancels every request.++## Anatomy++```text+┌──────────────────────────────────────────────────────────────┐+│ 🔍 is:Dashboard revenue▍ [✨ Press Tab to ask AI] [×] │ input + chips (+ Cancel)+├──────────────────────────────────────────────────────────────┤+│ SUGGESTIONS (only while a filter token is active) │+│ RESULTS / RECENTS / STARRED / PRODUCTS / ... │+├──────────────────────────────────────────────────────────────┤+│ ↑↓ navigate ↵ open ⌘↵ new tab ⇥ complete ⌫ remove filter Esc │ footer+└──────────────────────────────────────────────────────────────┘+```++Placeholder: `Search or ask PostHog AI… try is:dashboard`.++Input controls, carried over from the current palette:++- **Press Tab to ask AI** shows while Tab would ask AI: there is a query and the highlighted row is not a filter row. Clicking it does the same as Tab.+- **Clear (×)** shows whenever there is text or a chip, and clears both.+- **Cancel** closes the palette. It shows only with the `today-rail-nav` UI at narrow widths, where the footer hides, as in the current palette.++## Modes++The input is always in exactly one mode, decided from the token under the cursor.++| Mode | Trigger | Listbox shows |+| ----------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------- |+| **Empty** | Input is empty, no chips | Recents, Starred, Products (today's default list) |+| **Key suggest** | Cursor token is a partial filter key (`cr`, `createdB`, `is`) | Matching filter keys first, then normal results for the text |+| **Value suggest** | Cursor token is `key:` or `key:partial` | Values for that key, then results already narrowed by the other filters |+| **Search** | Cursor token is free text | Results for the free text plus committed filters |++### Empty mode++- Sections in this fixed order: **Recents** (5), **Starred**, **Products**.+- Same data sources as today (`recentItemsModel`, `projectTreeDataLogic` shortcuts, `getTreeItemsProducts()`).+- Zero network requests on open. Everything comes from already-loaded models.+- First row is highlighted.++### Key suggest++- Typing a prefix that matches a filter key or alias shows a **Filters** section at the top.+ - `is` → `is:` "Type, such as dashboard or feature flag"+ - `createdB` → `createdBy:` "Who created it"+ - `c` → `createdBy:` (all keys starting with `c`)+- Match is case-insensitive prefix on key and aliases. Show the canonical key, not the alias.+- The Filters section holds at most 3 rows so it never pushes results far down.+- `Tab` or `↵` on a key row completes it to `key:` and switches to Value suggest. It does not navigate.+- Plain text results still render below, so typing `is` still finds an insight called "Issues".++### Value suggest++- `is:` with no value lists **every** type, grouped and alphabetized, with its icon. No network.+- `is:fe` narrows to types whose label or alias starts with `fe` (`Feature flag`). Prefix match first, then substring.+- `createdBy:` lists `me` first, then org members. `createdBy:Ca` lists members whose first name, last name, or email starts with `Ca`.+ - Results below the suggestions are already filtered to objects created by anyone matching `Ca`, so the user sees the effect before committing.+- `Tab`, `↵`, or typing a space commits the value into a chip. The cursor moves past it, ready for the next token.+- Typing the last letter of a value that names exactly one option commits it too, as if its suggestion were picked. A space typed right after (at the start, or after another space) is dropped, because it would separate nothing.+- If the value matches nothing, show one row: "No match for `Ca`. Press Space to search anyway." Free text values stay valid for `createdBy` (substring on name/email).++### 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.+- 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**.+ 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.++## Smart filters++Keys are case-insensitive. `createdby:` and `createdBy:` are the same token.+Each key holds one value. Committing `is:insight` while an `is:` chip exists replaces that chip in place. Different keys combine with **and**. There is no **or** in v1.+Prefix any token with `-` to negate it: `-is:insight`, `-createdBy:me`.+Quote values with spaces: `createdBy:"Ada Lovelace"`, `in:"Team Growth"`.++### Launch set++| Key | Aliases | Values | Example | Backend today |+| ------------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ---------------------------------------------- |+| `is:` | `type:` | Every type in `fileSystemTypes` from the product manifests (action, cohort, dashboard, experiment, feature flag, insight, notebook, survey, workflow, …) | `is:flag` | ✅ `type:` in `file_system` search |+| `createdBy:` | `by:`, `author:`, `user:` | `me`, org members | `createdBy:me` | ✅ `user:` / `author:` in `file_system` search |+| `in:` | `path:`, `folder:` | Project tree folders | `in:"Growth team"` | ✅ `path:` |+| `name:` | `title:` | Free text, matches name only (not description) | `name:revenue` | ✅ `name:` |++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.++### Suggested next filters++Ordered by usefulness vs. backend cost.++| Key | Values | Example | Why | Backend work |+| -------------------------- | -------------------------------------------------------------- | ------------------------- | --------------------------------------------------------- | ------------------------------------------------------------- |+| `is:starred` / `is:recent` | none | `is:starred revenue` | Search inside my own shortlist | Starred = shortcuts join; recent = `order_by=-last_viewed_at` |+| `updated:` / `created:` | `today`, `7d`, `30d`, `>2026-01-01` | `updated:7d is:dashboard` | "That flag I touched last week" | `created_at__gt` exists; `updated` needs a field |+| `viewed:` | `today`, `7d` | `viewed:7d` | Recents with a time window | `last_viewed_at` exists for current user |+| `tag:` | Project tags | `tag:marketing` | Dashboards, insights, flags already have tags | New: tags not on `FileSystem` |+| `status:` | Per type: `active`, `inactive`, `draft`, `running`, `archived` | `is:flag status:inactive` | Stale flag cleanup, running experiments | New, per-type; only offer after an `is:` chip |+| `key:` | Free text | `key:checkout-v2` | Feature flag key exact match, the most common flag lookup | `ref` / flag key lookup |+| `has:` | `description`, `tags`, `alerts`, `subscriptions` | `is:insight has:alerts` | Find insights with alerts set up | New, per-type |+| `sort:` | `recent`, `name`, `created` | `sort:name` | Overrides default ranking | `order_by` exists |++Rule for adding a filter: it ships only when its values can be suggested (static list or a cached list). A filter the user cannot discover through autocomplete does not ship.++## Stability rules++These 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.+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 while the item still exists. If it is gone, or the person never moved it, the first row is highlighted.+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.+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.++## Performance budget++- 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.+- 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.++## Keyboard++| Key | Action |+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------- |+| `↑` / `↓` | Move highlight. Wraps at ends. Skips section headers. |+| `↵` | Filter key or value row: complete it. Result row: open it. |+| `⌘↵` | Open result in a new tab. |+| `Tab` | Highlighted key or value row: complete it. Any other row, with a query: ask PostHog AI. With neither, focus moves as usual. |+| `Space` | After `key:value`, commits the chip. |+| `⌫` at start of text | First press selects the previous chip. Second press removes it. |+| `↵` on a selected chip | Turns the chip back into editable text (`is:dashboard`) with the cursor after it. |+| `←` / `→` at text edges | Move between chips. |+| `Esc` | Text in the input: clear it. Empty input: close the palette. |++## Edge cases++- **Unknown key** (`foo:bar`): treat the whole token as free text. Don't show an error.+- **Colon inside text** (`error: timeout`): a token is a filter only when the key is a known key or alias. Otherwise it is free text.+- **Pasted query** (`is:flag createdBy:me checkout`): parse into chips immediately.+- **Same key twice** (`is:dashboard is:insight`): the later value replaces the earlier chip. While a value for a key that already has a chip is being typed, results preview the new value instead of the chip.+- **Invalid value** (`is:banana`): keep it as plain text, no chip, and show "No type called banana" in the Suggestions section.+- **Ask PostHog AI**: always the last section in Search mode, with the raw input text (chips included as text) as the question.++## Out of scope for v1++- Saved searches.+- `OR` of any kind, within a key or across keys, and parentheses.+- Natural-language filter inference ("dashboards I made last week" → chips). Good v2 candidate.++## Analytics++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 search abandoned` (closed with no result opened; last mode, had_filters)diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearch.stories.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearch.stories.tsxnew file mode 100644index 000000000000..1fea04c064ff--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearch.stories.tsx@@ -0,0 +1,69 @@+import { Meta, StoryObj } from '@storybook/react'+import { useActions, useMountedLogic } from 'kea'+import { useEffect } from 'react'++import { useStorybookMocks } from '~/mocks/browser'+import { EMPTY_PAGINATED_RESPONSE, toPaginatedResponse } from '~/mocks/handlers'++import { CommandKSearch } from './CommandKSearch'+import { commandKSearchLogic } from './commandKSearchLogic'++const minutesAgo = (minutes: number): string => new Date(Date.now() - 1000 * 60 * minutes).toISOString()++const MOCK_ENTRIES = [+ { id: '1', path: 'Key metrics', type: 'dashboard', ref: '1', href: '/dashboard/1', last_viewed_at: minutesAgo(5) },+ { id: '2', path: 'Signup funnel', type: 'insight', ref: '2', href: '/insights/2', last_viewed_at: minutesAgo(30) },+ {+ id: '3',+ path: 'new-onboarding',+ type: 'feature_flag',+ ref: '3',+ href: '/feature_flags/3',+ last_viewed_at: minutesAgo(120),+ },+]++const fileSystemMock = (): [number, unknown] => [200, toPaginatedResponse(MOCK_ENTRIES)]++const MOCKS = {+ '/api/projects/:team_id/file_system/': fileSystemMock,+ '/api/environments/:team_id/file_system/': fileSystemMock,+ '/api/environments/:team_id/file_system/log_view/': () => [200, []],+ '/api/environments/:team_id/persons/': () => [200, EMPTY_PAGINATED_RESPONSE],+ '/api/environments/:team_id/groups/': () => [200, EMPTY_PAGINATED_RESPONSE],+}++const meta: Meta = {+ title: 'Components/Command K search',+ parameters: {+ layout: 'centered',+ testOptions: { snapshotBrowsers: ['chromium'] },+ },+}+export default meta++type Story = StoryObj<{}>++function Frame({ text }: { text?: string }): JSX.Element {+ useStorybookMocks({ get: MOCKS })+ useMountedLogic(commandKSearchLogic)+ const { inputChanged } = useActions(commandKSearchLogic)+ useEffect(() => {+ if (text) {+ inputChanged(text, text.length, true)+ }+ }, [text, inputChanged])+ return (+ <div className="flex h-[480px] w-[640px] flex-col overflow-hidden rounded-lg border border-border bg-background">+ <CommandKSearch />+ </div>+ )+}++export const Empty: Story = {+ render: () => <Frame />,+}++export const ChipAndValueSuggestions: Story = {+ render: () => <Frame text="is:dashboard is:" />,+}diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearch.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearch.tsxnew file mode 100644index 000000000000..c8935e6a0dab--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearch.tsx@@ -0,0 +1,63 @@+import { useValues } from 'kea'+import { useEffect } from 'react'++import { ScrollArea } from '@posthog/quill'++import { CommandKSearchFooter } from './CommandKSearchFooter'+import { COMMAND_K_LISTBOX_ID, CommandKSearchInput } from './CommandKSearchInput'+import { commandKSearchLogic } from './commandKSearchLogic'+import { rowDomId } from './CommandKSearchRow'+import { CommandKSearchSection } from './CommandKSearchSection'++/** Command K search with smart filters. The UX contract lives in COMMAND_K_SEARCH_UX.md next to this file. */+export function CommandKSearch(): JSX.Element {+ const { sections, highlightedRow } = useValues(commandKSearchLogic)+ const highlightedKey = highlightedRow?.key ?? null++ useEffect(() => {+ const row = highlightedKey ? document.getElementById(rowDomId(highlightedKey)) : null+ const viewport = row?.closest<HTMLElement>('[data-slot="scroll-area-viewport"]')+ if (!row || !viewport) {+ return+ }+ // scrollIntoView also scrolls the dialog, which clips the input, so scroll only the list.+ // The sticky section header covers the top of the viewport, so keep rows below it.+ const header = row.closest('[role="group"]')?.querySelector<HTMLElement>('[data-slot="menu-label"]')+ const headerHeight = header?.offsetHeight ?? 0+ const rowRect = row.getBoundingClientRect()+ const viewportRect = viewport.getBoundingClientRect()+ if (rowRect.top < viewportRect.top + headerHeight) {+ viewport.scrollTop -= viewportRect.top + headerHeight - rowRect.top+ } else if (rowRect.bottom > viewportRect.bottom) {+ viewport.scrollTop += rowRect.bottom - viewportRect.bottom+ }+ }, [highlightedKey])++ return (+ <div+ data-quill+ className="flex min-h-0 flex-1 flex-col bg-background text-foreground"+ data-attr="command-k-search"+ >+ <CommandKSearchInput />+ <ScrollArea+ // Sticky section headers sit at z-10, so lift the scrollbar above them.+ className="flex min-h-0 flex-1 flex-col border-t border-border [&>[data-slot=scroll-area-scrollbar]]:z-20"+ viewportClassName="h-auto min-h-0 flex-1"+ >+ <div+ id={COMMAND_K_LISTBOX_ID}+ role="listbox"+ aria-label="Search results"+ // The colorful-product-icons group turns on each product's brand color, as in the navbar.+ className="group/colorful-product-icons colorful-product-icons-true bg-card pb-1"+ >+ {sections.map((section) => (+ <CommandKSearchSection key={section.key} section={section} highlightedKey={highlightedKey} />+ ))}+ </div>+ </ScrollArea>+ <CommandKSearchFooter />+ </div>+ )+}diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchFooter.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchFooter.tsxnew file mode 100644index 000000000000..8f4bd24f7c95--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchFooter.tsx@@ -0,0 +1,55 @@+import { useValues } from 'kea'++import { Kbd, cn } from '@posthog/quill'++import { todayShellLogic } from '~/layout/today/todayShellLogic'++import { commandKSearchLogic } from './commandKSearchLogic'++export function CommandKSearchFooter(): JSX.Element {+ const { highlightIsFilterRow, chips, mode, selectedChipIndex, tabAsksAi } = useValues(commandKSearchLogic)+ const { todayRailEnabled } = useValues(todayShellLogic)++ return (+ <div+ className={cn(+ todayRailEnabled && 'max-md:hidden',+ 'flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-border px-2 py-1.5 text-xxs text-muted-foreground select-none'+ )}+ >+ <span className="flex items-center gap-1">+ <Kbd>↑</Kbd>+ <Kbd>↓</Kbd> navigate+ </span>+ <span className="flex items-center gap-1">+ <Kbd>↵</Kbd> open+ </span>+ <span className="flex items-center gap-1">+ <Kbd>⌘↵</Kbd> new tab+ </span>+ {highlightIsFilterRow && (+ <span className="flex items-center gap-1">+ <Kbd>⇥</Kbd> complete+ </span>+ )}+ {tabAsksAi && (+ <span className="flex items-center gap-1">+ <Kbd>⇥</Kbd> ask AI+ </span>+ )}+ {chips.length > 0 && (+ <span className="flex items-center gap-1">+ <Kbd>⌫</Kbd> {selectedChipIndex === null ? 'select filter' : 'remove filter'}+ </span>+ )}+ {selectedChipIndex !== null && (+ <span className="flex items-center gap-1">+ <Kbd>↵</Kbd> edit filter+ </span>+ )}+ <span className="flex items-center gap-1">+ <Kbd>Esc</Kbd> {mode === 'empty' ? 'close' : 'clear'}+ </span>+ </div>+ )+}diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchInput.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchInput.tsxnew file mode 100644index 000000000000..8adcb72a8bc2--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchInput.tsx@@ -0,0 +1,170 @@+import { useActions, useValues } from 'kea'+import { useLayoutEffect, useRef } from 'react'++import { IconSearch, IconSparkles, IconX } from '@posthog/icons'+import { Button, InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, cn } from '@posthog/quill'++import { todayShellLogic } from '~/layout/today/todayShellLogic'++import { keyIntent } from './commandKKeys'+import { commandKSearchLogic } from './commandKSearchLogic'+import { rowDomId } from './CommandKSearchRow'++export const COMMAND_K_LISTBOX_ID = 'command-k-listbox'++export function CommandKSearchInput(): JSX.Element {+ const { text, cursor, chips, selectedChipIndex, highlightedRow, highlightIsFilterRow, tabAsksAi, isPaletteEmpty } =+ useValues(commandKSearchLogic)+ const { todayRailEnabled } = useValues(todayShellLogic)+ const { inputChanged, setCursor, applyKeyIntent, selectChip, clearQuery, askAi, closeCommand } =+ useActions(commandKSearchLogic)+ const inputRef = useRef<HTMLInputElement>(null)+ const pastingRef = useRef(false)++ // The logic moves the cursor when it commits or edits a chip, so mirror it onto the field.+ useLayoutEffect(() => {+ const input = inputRef.current+ if (input && document.activeElement === input && input.selectionStart !== cursor) {+ input.setSelectionRange(cursor, cursor)+ }+ }, [text, cursor])++ useLayoutEffect(() => {+ inputRef.current?.focus()+ }, [])++ const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>): void => {+ // Keys confirm or move inside an IME composition, so leave them to the input. Safari reports 229.+ if (event.nativeEvent.isComposing || event.keyCode === 229) {+ return+ }+ const input = event.currentTarget+ const intent = keyIntent(event.key, event, {+ atStart: input.selectionStart === 0 && input.selectionEnd === 0,+ chipCount: chips.length,+ selectedChipIndex,+ tabHasAction: tabAsksAi || highlightIsFilterRow,+ })+ if (!intent) {+ return+ }+ event.preventDefault()+ if (intent.type === 'clear-or-close') {+ // Stop the dialog from closing, so the first press only clears the query.+ event.stopPropagation()+ }+ applyKeyIntent(intent)+ }++ return (+ <div className="flex items-center gap-1 p-2">+ {/* A fixed height, so committing a chip never resizes the field. Chips that overflow scroll sideways. */}+ <InputGroup className="flex-1">+ {/* The scroll container clips, so it gets room on the right for the selected chip's outline and gives it back with a negative margin. */}+ <InputGroupAddon+ align="inline-start"+ className="-mr-1 min-w-0 shrink overflow-x-auto pr-1 [scrollbar-width:none]"+ >+ <IconSearch className="size-4 shrink-0" />+ {chips.map((chip, index) => (+ // Committed filters read as typed text: plain key, brand-tinted value.+ <button+ key={chip.key}+ type="button"+ tabIndex={-1}+ data-attr="command-k-chip"+ aria-label={`${chip.negated ? 'Not ' : ''}${chip.key}: ${chip.label}. Backspace removes it.`}+ className={cn(+ 'flex max-w-60 shrink-0 items-center rounded-xs text-sm leading-none text-foreground',+ selectedChipIndex === index && 'ring-2 ring-ring'+ )}+ onMouseDown={(event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault()}+ onClick={() => selectChip(index)}+ >+ <span className="shrink-0">+ {chip.negated ? '-' : ''}+ {chip.key}:+ </span>+ <span className="truncate rounded-xs bg-[var(--primary)]/10 px-0.5 text-[var(--primary)]">+ {chip.label}+ </span>+ </button>+ ))}+ </InputGroupAddon>+ <InputGroupInput+ ref={inputRef}+ id="command-k-input"+ data-attr="command-k-input"+ role="combobox"+ aria-expanded+ aria-controls={COMMAND_K_LISTBOX_ID}+ aria-autocomplete="list"+ aria-activedescendant={highlightedRow ? rowDomId(highlightedRow.key) : undefined}+ aria-label="Search"+ autoComplete="off"+ spellCheck={false}+ placeholder={chips.length === 0 ? 'Search or ask PostHog AI… try is:dashboard' : undefined}+ className="min-w-24 flex-1"+ value={text}+ onPaste={() => {+ pastingRef.current = true+ }}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => {+ const pasted = pastingRef.current+ pastingRef.current = false+ inputChanged(+ event.target.value,+ event.target.selectionStart ?? event.target.value.length,+ pasted+ )+ }}+ onSelect={(event: React.SyntheticEvent<HTMLInputElement>) => {+ const nextCursor = event.currentTarget.selectionStart ?? 0+ if (nextCursor !== cursor) {+ setCursor(nextCursor)+ }+ }}+ onKeyDown={onKeyDown}+ />+ <InputGroupAddon align="inline-end">+ {tabAsksAi && (+ <InputGroupButton+ size="sm"+ variant="secondary"+ tabIndex={-1}+ data-attr="command-k-ask-ai"+ onMouseDown={(event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault()}+ onClick={() => askAi()}+ >+ <IconSparkles />+ Press Tab to ask AI+ </InputGroupButton>+ )}+ {!isPaletteEmpty && (+ <InputGroupButton+ size="icon-xs"+ tabIndex={-1}+ aria-label="Clear search"+ data-attr="command-k-clear"+ className="mr-1"+ onMouseDown={(event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault()}+ onClick={() => clearQuery()}+ >+ <IconX />+ </InputGroupButton>+ )}+ </InputGroupAddon>+ </InputGroup>+ {todayRailEnabled && (+ <Button+ size="sm"+ className="hidden shrink-0 max-md:flex"+ data-attr="command-phone-cancel"+ onClick={() => closeCommand()}+ >+ Cancel+ </Button>+ )}+ </div>+ )+}diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsxnew file mode 100644index 000000000000..a3987e76c0b5--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx@@ -0,0 +1,180 @@+import { useActions } from 'kea'+import { memo } from 'react'++import { IconFilter, IconFolder, IconPerson, IconSparkles } from '@posthog/icons'+import { Button, cn } from '@posthog/quill'++import { getIconForItem, getItemTypeDisplayName } from 'lib/components/Search/searchItemDisplay'+import { formatRelativeTimeShort } from 'lib/components/Search/utils'+import { capitalizeFirstLetter } from 'lib/utils/strings'++import { ProductIconWrapper, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { FileSystemIconType } from '~/queries/schema/schema-general'++import { commandKSearchLogic } from './commandKSearchLogic'+import { CommandKRow } from './commandKSections'++export const rowDomId = (key: string): string => `command-k-row-${key.replace(/[^a-zA-Z0-9_-]/g, '_')}`++const SECTIONS_WITH_TYPE_LABEL = new Set(['recents', 'starred', 'results', 'groups'])++function RowContent({ row }: { row: CommandKRow }): JSX.Element | null {+ switch (row.kind) {+ case 'filter-key':+ return (+ <>+ <IconFilter className="size-4 shrink-0 text-muted-foreground" />+ <span className="shrink-0 font-semibold">+ {row.negated ? '-' : ''}+ {row.filter.key}:+ </span>+ <span className="truncate text-muted-foreground">{row.filter.description}</span>+ </>+ )+ case 'filter-value': {+ const icon =+ row.filter.key === 'is' && row.option.iconType ? (+ <ProductIconWrapper type={row.option.iconType}>+ {iconForType(row.option.iconType as FileSystemIconType)}+ </ProductIconWrapper>+ ) : row.filter.key === 'createdBy' ? (+ <IconPerson className="size-4 shrink-0 text-muted-foreground" />+ ) : row.filter.key === 'in' ? (+ <IconFolder className="size-4 shrink-0 text-muted-foreground" />+ ) : (+ <IconFilter className="size-4 shrink-0 text-muted-foreground" />+ )+ return (+ <>+ {icon}+ <span className="truncate">+ {row.filter.key === 'name' ? `Name contains "${row.option.label}"` : row.option.label}+ </span>+ {row.filter.key === 'createdBy' && row.option.value !== 'me' && (+ <span className="truncate text-xs text-muted-foreground">{row.option.value}</span>+ )}+ </>+ )+ }+ case 'ask-ai':+ return (+ <>+ <IconSparkles className="size-4 shrink-0 text-primary" />+ <span className="shrink-0">Ask PostHog AI:</span>+ <span className="truncate text-muted-foreground">{row.question}</span>+ </>+ )+ case 'item': {+ const { item } = row+ const typeLabel = SECTIONS_WITH_TYPE_LABEL.has(row.section)+ ? item.groupNoun || getItemTypeDisplayName(item.itemType)+ : null+ return (+ <>+ {getIconForItem(item)}+ <span className="truncate">{String(item.displayName || item.name)}</span>+ {typeLabel && (+ <span className="shrink-0 text-xs text-muted-foreground">+ {capitalizeFirstLetter(typeLabel)}+ </span>+ )}+ {item.parentName && (+ <span className="shrink-0 text-xs text-muted-foreground">in {item.parentName}</span>+ )}+ {item.productCategory && (+ <span className="shrink-0 text-xs text-muted-foreground">{item.productCategory}</span>+ )}+ {item.matchedSearchKeyword && (+ <span className="ml-auto truncate text-xxs text-muted-foreground">+ Matches "{item.matchedSearchKeyword}"+ </span>+ )}+ {item.lastViewedAt && (+ <span+ className={cn(+ 'shrink-0 whitespace-nowrap text-xs text-muted-foreground',+ item.matchedSearchKeyword ? 'ml-2' : 'ml-auto'+ )}+ >+ {formatRelativeTimeShort(item.lastViewedAt)}+ </span>+ )}+ </>+ )+ }+ default:+ return null+ }+}++interface CommandKSearchRowProps {+ row: CommandKRow+ highlighted: boolean+}++/** What a row shows, beyond its key. Row objects are rebuilt on every keystroke, but this rarely changes. */+const rowContent = (row: CommandKRow): unknown => {+ switch (row.kind) {+ case 'item':+ return row.item+ case 'filter-value':+ return row.option+ case 'filter-key':+ return row.filter+ case 'ask-ai':+ return row.question+ case 'message':+ return row.text+ }+}++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)+)++function CommandKSearchRowInner({ row, highlighted }: CommandKSearchRowProps): JSX.Element {+ const { activateRow, setHighlightedKey } = useActions(commandKSearchLogic)++ if (row.kind === 'message') {+ return (+ <div className="flex h-8 items-center px-2 text-sm text-muted-foreground" role="presentation">+ <span className="truncate">{row.text}</span>+ </div>+ )+ }++ const disabledReason = row.kind === 'item' ? row.item.disabledReason : undefined++ return (+ <Button+ id={rowDomId(row.key)}+ role="option"+ aria-selected={highlighted}+ aria-disabled={disabledReason ? true : undefined}+ title={disabledReason}+ tabIndex={-1}+ size="row"+ left+ data-attr={`command-k-row-${row.kind}`}+ className={cn(+ 'h-8 w-full min-w-0 gap-1.5 [&>*]:min-w-0',+ highlighted && 'bg-fill-selected',+ disabledReason && 'opacity-50 cursor-not-allowed'+ )}+ // Keep focus in the input so typing continues after a click.+ onMouseDown={(event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault()}+ onMouseMove={() => !highlighted && setHighlightedKey(row.key)}+ onClick={(event: React.MouseEvent<HTMLButtonElement>) =>+ activateRow(row, event.metaKey || event.ctrlKey, 'click')+ }+ >+ <span className="flex w-full min-w-0 items-center gap-1.5">+ <RowContent row={row} />+ </span>+ </Button>+ )+}diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsxnew file mode 100644index 000000000000..4bdd8570e61c--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsx@@ -0,0 +1,42 @@+import { MenuLabel, Skeleton, cn } from '@posthog/quill'++import { CommandKSearchRow } from './CommandKSearchRow'+import { CommandKSection } from './commandKSections'++export function CommandKSearchSection({+ section,+ highlightedKey,+}: {+ section: CommandKSection+ highlightedKey: string | null+}): JSX.Element {+ return (+ <div+ role="group"+ aria-labelledby={`command-k-section-${section.key}`}+ data-attr={`command-k-section-${section.key}`}+ >+ <MenuLabel id={`command-k-section-${section.key}`} className="sticky top-0 z-10 bg-card px-2 pb-0">+ {section.label}+ </MenuLabel>+ <div+ className={cn(+ 'flex flex-col px-1 py-0.5 transition-opacity motion-reduce:transition-none',+ // Dim only once a response is slow, so fast typing never flickers.+ section.state === 'stale' && 'opacity-60 delay-150'+ )}+ aria-busy={section.state !== 'ready'}+ >+ {section.state === 'loading'+ ? Array.from({ length: section.skeletonCount }, (_, index) => (+ <div key={index} className="flex h-8 items-center px-1">+ <Skeleton className="h-5 w-full" />+ </div>+ ))+ : section.rows.map((row) => (+ <CommandKSearchRow key={row.key} row={row} highlighted={row.key === highlightedKey} />+ ))}+ </div>+ </div>+ )+}diff --git a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.ts b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsnew file mode 100644index 000000000000..694b7a1dc175--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.ts@@ -0,0 +1,69 @@+import { fileSystemTypes } from '~/products'+import { FileSystemEntry } from '~/queries/schema/schema-general'+import { OrganizationMemberType, UserType } from '~/types'++import { FilterOptions, ValueOption } from './commandKQuery'++/** Short words people type for a type, on top of its name and key. */+const TYPE_ALIASES: Record<string, string[]> = {+ feature_flag: ['flag', 'flags'],+ session_recording_playlist: ['playlist', 'replay', 'recording'],+ early_access_feature: ['eaf', 'beta'],+ workflows: ['workflow'],+ notebook: ['doc'],+}++let cachedTypeOptions: ValueOption[] | null = null++/** Every file system type from the product manifests, alphabetized. The manifests never change at runtime. */+const typeOptions = (): ValueOption[] => {+ if (cachedTypeOptions === null) {+ cachedTypeOptions = Object.entries(fileSystemTypes as Record<string, { name?: string; iconType?: string }>)+ .flatMap(([type, definition]) =>+ definition.name+ ? [+ {+ value: type,+ label: definition.name,+ aliases: [+ type,+ definition.name.toLowerCase().replace(/\s+/g, '-'),+ ...(TYPE_ALIASES[type] ?? []),+ ],+ iconType: definition.iconType ?? type,+ },+ ]+ : []+ )+ .sort((a, b) => a.label.localeCompare(b.label))+ }+ return cachedTypeOptions+}++const memberOption = (member: OrganizationMemberType): ValueOption => {+ const { first_name, last_name, email } = member.user+ return {+ value: email,+ label: [first_name, last_name].filter(Boolean).join(' ') || email,+ aliases: [first_name, last_name, email].filter((alias): alias is string => !!alias),+ }+}++/** `me` first, then everyone else in the organization. */+const userOptions = (members: OrganizationMemberType[], user: UserType | null): ValueOption[] => [+ { value: 'me', label: 'Me', aliases: user ? [user.first_name, user.email].filter(Boolean) : [] },+ ...members.filter((member) => member.user.uuid !== user?.uuid).map(memberOption),+]++export function buildFilterOptions(+ members: OrganizationMemberType[],+ user: UserType | null,+ folders: FileSystemEntry[] | null+): FilterOptions {+ return {+ is: typeOptions(),+ createdBy: userOptions(members, user),+ in: (folders ?? []).map((folder) => ({ value: folder.path, label: folder.path })),+ name: [],+ }+}diff --git a/frontend/src/lib/components/CommandKSearch/commandKKeys.test.ts b/frontend/src/lib/components/CommandKSearch/commandKKeys.test.tsnew file mode 100644index 000000000000..b3c155be0580--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKKeys.test.ts@@ -0,0 +1,54 @@+import { KeyIntent, KeyState, keyIntent } from './commandKKeys'++const NO_MODIFIERS = { metaKey: false, ctrlKey: false }+const state = (overrides: Partial<KeyState> = {}): KeyState => ({+ atStart: false,+ chipCount: 0,+ selectedChipIndex: null,+ tabHasAction: false,+ ...overrides,+})++describe('keyIntent', () => {+ test.each<[string, string, KeyState, KeyIntent | null, boolean?]>([+ ['Enter opens the highlighted row', 'Enter', state(), { type: 'activate', newTab: false }],+ ['Cmd+Enter opens in a new tab', 'Enter', state(), { type: 'activate', newTab: true }, true],+ [+ 'Enter on a selected chip edits it',+ 'Enter',+ state({ chipCount: 2, selectedChipIndex: 0 }),+ { type: 'edit-chip', index: 0 },+ ],+ [+ 'first Backspace at the start selects the last chip',+ 'Backspace',+ state({ atStart: true, chipCount: 2 }),+ { type: 'select-chip', index: 1 },+ ],+ [+ 'second Backspace removes it',+ 'Backspace',+ state({ atStart: true, chipCount: 2, selectedChipIndex: 1 }),+ { type: 'remove-chip', index: 1 },+ ],+ ['Backspace inside the text is left to the input', 'Backspace', state({ chipCount: 2 }), null],+ [+ 'ArrowLeft at the start walks back through chips',+ 'ArrowLeft',+ state({ atStart: true, chipCount: 2, selectedChipIndex: 1 }),+ { type: 'select-chip', index: 0 },+ ],+ [+ 'ArrowRight past the last chip returns to the text',+ 'ArrowRight',+ state({ chipCount: 2, selectedChipIndex: 1 }),+ { type: 'select-chip', index: null },+ ],+ ['ArrowRight with no chip selected is left to the input', 'ArrowRight', state({ chipCount: 2 }), null],+ ['typing is left to the input', 'a', state(), null],+ ['Tab completes or asks AI when it has an action', 'Tab', state({ tabHasAction: true }), { type: 'complete' }],+ ['Tab with nothing to do moves focus', 'Tab', state(), null],+ ])('%s', (_, key, keyState, expected, metaKey = false) => {+ expect(keyIntent(key, { ...NO_MODIFIERS, metaKey }, keyState)).toEqual(expected)+ })+})diff --git a/frontend/src/lib/components/CommandKSearch/commandKKeys.ts b/frontend/src/lib/components/CommandKSearch/commandKKeys.tsnew file mode 100644index 000000000000..500a76c54f19--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKKeys.ts@@ -0,0 +1,63 @@+export type KeyIntent =+ | { type: 'move'; direction: 1 | -1 }+ | { type: 'activate'; newTab: boolean }+ | { type: 'complete' }+ | { type: 'select-chip'; index: number | null }+ | { type: 'remove-chip'; index: number }+ | { type: 'edit-chip'; index: number }+ | { type: 'clear-or-close' }++export interface KeyState {+ /** The caret sits at the very start of the text with nothing selected. */+ atStart: boolean+ chipCount: number+ selectedChipIndex: number | null+ /** Tab completes a filter row or asks AI. With neither, it moves focus as usual. */+ tabHasAction: boolean+}++/** What a key press does in the search input, or null to let the input handle it. */+export function keyIntent(+ key: string,+ modifiers: { metaKey: boolean; ctrlKey: boolean },+ state: KeyState+): KeyIntent | null {+ const { atStart, chipCount, selectedChipIndex } = state+ const chipsBeforeCaret = chipCount > 0 && atStart+ switch (key) {+ case 'ArrowDown':+ return { type: 'move', direction: 1 }+ case 'ArrowUp':+ return { type: 'move', direction: -1 }+ case 'Enter':+ return selectedChipIndex !== null+ ? { type: 'edit-chip', index: selectedChipIndex }+ : { type: 'activate', newTab: modifiers.metaKey || modifiers.ctrlKey }+ case 'Tab':+ return state.tabHasAction ? { type: 'complete' } : null+ case 'Escape':+ return { type: 'clear-or-close' }+ case 'Backspace':+ if (!chipsBeforeCaret) {+ return null+ }+ return selectedChipIndex === null+ ? { type: 'select-chip', index: chipCount - 1 }+ : { type: 'remove-chip', index: selectedChipIndex }+ case 'ArrowLeft':+ if (!chipsBeforeCaret) {+ return null+ }+ return {+ type: 'select-chip',+ index: selectedChipIndex === null ? chipCount - 1 : Math.max(0, selectedChipIndex - 1),+ }+ case 'ArrowRight':+ if (selectedChipIndex === null) {+ return null+ }+ return { type: 'select-chip', index: selectedChipIndex + 1 < chipCount ? selectedChipIndex + 1 : null }+ default:+ return null+ }+}diff --git a/frontend/src/lib/components/CommandKSearch/commandKQuery.test.ts b/frontend/src/lib/components/CommandKSearch/commandKQuery.test.tsnew file mode 100644index 000000000000..433086022c6d--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKQuery.test.ts@@ -0,0 +1,153 @@+import {+ FilterKey,+ QueryChip,+ ValueOption,+ FilterOptions,+ chipCommittedByEdit,+ extractChips,+ getCursorContext,+ isRedundantSpace,+ matchValueOptions,+ queryAsText,+ removeToken,+ resolveQuery,+ tokenize,+ unambiguousOption,+} from './commandKQuery'++const TYPE_OPTIONS: ValueOption[] = [+ { value: 'dashboard', label: 'Dashboard' },+ { value: 'early_access_feature', label: 'Early access feature' },+ { value: 'feature_flag', label: 'Feature flag', aliases: ['flag'] },+ { value: 'insight', label: 'Insight' },+]+const USER_OPTIONS: ValueOption[] = [+ { value: 'me', label: 'Me' },+ { value: '[email protected]', label: 'Mel Ortiz', aliases: ['Mel', 'Ortiz', '[email protected]'] },+ { value: '[email protected]', label: 'Carla Diaz', aliases: ['Carla', 'Diaz', '[email protected]'] },+]+const OPTIONS: FilterOptions = { is: TYPE_OPTIONS, createdBy: USER_OPTIONS, in: [], name: [] }++const chip = (key: FilterKey, value: string, negated = false): QueryChip => ({ key, value, label: value, negated })++describe('commandKQuery', () => {+ test('keeps quoted values with spaces as one token', () => {+ expect(tokenize('createdBy:"Ada Lovelace" revenue').map((t) => t.raw)).toEqual([+ 'createdBy:"Ada Lovelace"',+ 'revenue',+ ])+ })++ test.each([+ ['empty input', '', 0, [], 'empty'],+ ['chips but no text is not empty', '', 0, [chip('is', 'insight')], 'text'],+ ['partial key', 'createdB', 8, [], 'key'],+ ['partial key with negation', '-cr', 3, [], 'key'],+ ['key alias is case-insensitive', 'CREATEDBY:ca', 12, [], 'value'],+ ['unknown key is free text', 'error: timeout', 6, [], 'text'],+ ['plain words', 'revenue', 7, [], 'text'],+ ['cursor in whitespace', 'is:insight ', 11, [], 'text'],+ ])('cursor context: %s', (_, text, cursor, chips, kind) => {+ expect(getCursorContext(text, cursor, chips).kind).toBe(kind)+ })++ test('key suggest lists every key that starts with the prefix, by canonical key', () => {+ const context = getCursorContext('c', 1, [])+ expect(context.kind === 'key' && context.matches.map((m) => m.key)).toEqual(['createdBy'])+ })++ test('value matching puts prefix matches before substring matches', () => {+ expect(matchValueOptions(TYPE_OPTIONS, 'fe', { allowSubstring: true }).map((o) => o.value)).toEqual([+ 'feature_flag',+ 'early_access_feature',+ ])+ expect(matchValueOptions(TYPE_OPTIONS, 'ash', { allowSubstring: true }).map((o) => o.value)).toEqual([+ 'dashboard',+ ])+ expect(matchValueOptions(TYPE_OPTIONS, 'ash', { allowSubstring: false })).toEqual([])+ })++ test.each([+ ['exact value with nothing else starting with it', TYPE_OPTIONS, 'dashboard', 'dashboard'],+ ['alias names the option', TYPE_OPTIONS, 'flag', 'feature_flag'],+ ['partial value waits', TYPE_OPTIONS, 'dash', null],+ ['exact value that another option extends waits', USER_OPTIONS, 'me', null],+ ['longer exact value commits', USER_OPTIONS, 'mel', '[email protected]'],+ ])('typed value commits without Space: %s', (_, options, value, expected) => {+ expect(unambiguousOption(options, value)?.value ?? null).toBe(expected)+ })++ test.each([+ ['at the start', '', 0, ' ', 1, true],+ ['after a space', 'a ', 2, 'a ', 3, true],+ ['between words', 'a', 1, 'a ', 2, false],+ ])('a space typed %s is redundant: %s', (_, previousText, previousCursor, text, cursor, expected) => {+ expect(isRedundantSpace({ previousText, previousCursor, text, cursor })).toBe(expected)+ })++ test('pasted query turns valid filters into one chip per key, last value wins, and keeps the rest as text', () => {+ const result = extractChips('is:flag createdBy:me is:insight is:banana checkout', [], OPTIONS)+ expect(result.chips.map((c) => `${c.key}:${c.value}`)).toEqual(['is:insight', 'createdBy:me'])+ expect(result.text).toBe('is:banana checkout')+ })++ test.each([+ [+ 'maps friendly keys, sorts filters, drops invalid values',+ 'createdBy:Ca is:banana revenue',+ [chip('is', 'dashboard', true)],+ '-type:dashboard user:Ca revenue',+ 'revenue',+ 2,+ ],+ [+ "a typed value stands in for that key's chip",+ 'is:flag',+ [chip('is', 'dashboard')],+ 'type:feature_flag',+ '',+ 1,+ ],+ ['quotes values with spaces', '', [chip('createdBy', 'Ada Lovelace')], 'user:"Ada Lovelace"', '', 1],+ ['free text only', 'revenue chart', [], 'revenue chart', 'revenue chart', 0],+ ])('resolves the query: %s', (_, text, chips, backendSearch, freeText, filterCount) => {+ const resolved = resolveQuery(text, chips, OPTIONS)+ expect(resolved).toMatchObject({ backendSearch, freeText })+ expect(resolved.filters).toHaveLength(filterCount)+ })++ test.each([+ ['typed space after a valid value', 'is:insight', 10, 'is:insight ', 11, 'is:insight', 'space'],+ ['typed space inside an open quote', 'createdBy:"Ada', 14, 'createdBy:"Ada ', 15, null, null],+ ['typed space after an invalid value', 'is:banana', 9, 'is:banana ', 10, null, null],+ [+ 'typed the last letter of an unambiguous value',+ 'is:dashboar',+ 11,+ 'is:dashboard',+ 12,+ 'is:dashboard',+ 'typed',+ ],+ ['typed a value another option extends', 'createdBy:m', 11, 'createdBy:me', 12, null, null],+ ['typed the last letter inside an open quote', 'is:"dashboar', 12, 'is:"dashboard', 13, null, null],+ ['typed the closing quote', 'is:"dashboard', 13, 'is:"dashboard"', 14, 'is:dashboard', 'typed'],+ ])(+ 'commits a chip from an edit: %s',+ (_, previousText, previousCursor, text, cursor, expectedChip, expectedVia) => {+ const committed = chipCommittedByEdit({ previousText, previousCursor, text, cursor }, [], OPTIONS)+ expect(committed ? `${committed.chip.key}:${committed.chip.value}` : null).toBe(expectedChip)+ expect(committed?.via ?? null).toBe(expectedVia)+ }+ )++ test('ask AI text includes chips as typed text', () => {+ expect(queryAsText(' revenue ', [chip('is', 'dashboard', true)])).toBe('-is:dashboard revenue')+ })++ test('removing a token keeps one space between neighbours and puts the cursor there', () => {+ const text = 'a is:insight b'+ const token = tokenize(text)[1]+ expect(removeToken(text, token)).toEqual({ text: 'a b', cursor: 2 })+ })+})diff --git a/frontend/src/lib/components/CommandKSearch/commandKQuery.ts b/frontend/src/lib/components/CommandKSearch/commandKQuery.tsnew file mode 100644index 000000000000..cf149ed5e434--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKQuery.ts@@ -0,0 +1,426 @@+export type FilterKey = 'is' | 'createdBy' | 'in' | 'name'++export interface FilterDefinition {+ key: FilterKey+ aliases: string[]+ description: string+ /** Field name the file system search endpoint understands. */+ backendField: 'type' | 'user' | 'path' | 'name'+ /** Whether a value that matches no suggestion is still a valid filter. */+ freeTextValues: boolean+}++export const FILTER_DEFINITIONS: FilterDefinition[] = [+ {+ key: 'is',+ aliases: ['type'],+ description: 'Type, such as dashboard or feature flag',+ backendField: 'type',+ freeTextValues: false,+ },+ {+ key: 'createdBy',+ aliases: ['by', 'author', 'user'],+ description: 'Who created it',+ backendField: 'user',+ freeTextValues: true,+ },+ {+ key: 'in',+ aliases: ['path', 'folder'],+ description: 'Folder it lives in',+ backendField: 'path',+ freeTextValues: true,+ },+ {+ key: 'name',+ aliases: ['title'],+ description: 'Name only, not description',+ backendField: 'name',+ freeTextValues: true,+ },+]++export const MAX_FILTER_KEY_ROWS = 3++export interface ValueOption {+ value: string+ label: string+ /** Extra words a person can type to reach this option, matched by prefix. */+ aliases?: string[]+ /** Icon type for the row, such as a file system type. */+ iconType?: string+}++export interface QueryChip {+ key: FilterKey+ value: string+ label: string+ negated: boolean+}++export interface QueryToken {+ raw: string+ start: number+ end: number+}++export interface ParsedToken {+ negated: boolean+ /** Set only when the token is `key:` with a known key or alias. */+ filter: FilterDefinition | null+ /** Text before the colon, or the whole token without its `-` when there is no colon. */+ keyText: string+ hasColon: boolean+ /** Value after the colon, with surrounding quotes removed. */+ value: string+}++export type CursorContext =+ | { kind: 'empty' }+ | { kind: 'key'; token: QueryToken; partial: string; negated: boolean; matches: FilterDefinition[] }+ | { kind: 'value'; token: QueryToken; filter: FilterDefinition; partial: string; negated: boolean }+ | { kind: 'text'; token: QueryToken | null }++const lower = (value: string): string => value.toLowerCase()++/** Splits on whitespace outside double quotes. An unclosed quote runs to the end of the text. */+export function tokenize(text: string): QueryToken[] {+ const tokens: QueryToken[] = []+ let start = -1+ let inQuote = false+ for (let i = 0; i <= text.length; i++) {+ const char = text[i]+ const atEnd = i === text.length+ if (!atEnd && char === '"') {+ inQuote = !inQuote+ }+ const isBoundary = atEnd || (!inQuote && /\s/.test(char))+ if (isBoundary) {+ if (start !== -1) {+ tokens.push({ raw: text.slice(start, i), start, end: i })+ start = -1+ }+ } else if (start === -1) {+ start = i+ }+ }+ return tokens+}++export function resolveFilterKey(name: string): FilterDefinition | null {+ const needle = lower(name)+ return (+ FILTER_DEFINITIONS.find(+ (definition) => lower(definition.key) === needle || definition.aliases.some((alias) => alias === needle)+ ) ?? null+ )+}++export function unquote(value: string): string {+ let result = value+ if (result.startsWith('"')) {+ result = result.slice(1)+ }+ if (result.endsWith('"')) {+ result = result.slice(0, -1)+ }+ return result+}++export function parseToken(raw: string): ParsedToken {+ const negated = raw.length > 1 && raw.startsWith('-')+ const body = negated ? raw.slice(1) : raw+ const colonIndex = body.indexOf(':')+ if (colonIndex === -1) {+ return { negated, filter: null, keyText: body, hasColon: false, value: '' }+ }+ const keyText = body.slice(0, colonIndex)+ return {+ negated,+ filter: resolveFilterKey(keyText),+ keyText,+ hasColon: true,+ value: unquote(body.slice(colonIndex + 1)),+ }+}++/** Filter definitions whose key or alias starts with the partial text, at most `MAX_FILTER_KEY_ROWS`. */+export function matchFilterKeys(partial: string): FilterDefinition[] {+ const needle = lower(partial)+ if (!needle) {+ return []+ }+ return FILTER_DEFINITIONS.filter(+ (definition) =>+ lower(definition.key).startsWith(needle) || definition.aliases.some((alias) => alias.startsWith(needle))+ ).slice(0, MAX_FILTER_KEY_ROWS)+}++export function tokenAtCursor(text: string, cursor: number): QueryToken | null {+ return tokenize(text).find((token) => token.start <= cursor && cursor <= token.end) ?? null+}++export function getCursorContext(text: string, cursor: number, chips: QueryChip[]): CursorContext {+ if (text.trim() === '' && chips.length === 0) {+ return { kind: 'empty' }+ }+ const token = tokenAtCursor(text, cursor)+ if (!token) {+ return { kind: 'text', token: null }+ }+ const parsed = parseToken(token.raw)+ if (parsed.filter) {+ return { kind: 'value', token, filter: parsed.filter, partial: parsed.value, negated: parsed.negated }+ }+ if (!parsed.hasColon) {+ const matches = matchFilterKeys(parsed.keyText)+ if (matches.length > 0) {+ return { kind: 'key', token, partial: parsed.keyText, negated: parsed.negated, matches }+ }+ }+ return { kind: 'text', token }+}++/** Prefix matches on the label, value, or an alias first, then matches inside a word when allowed. */+export function matchValueOptions(+ options: ValueOption[],+ partial: string,+ { allowSubstring }: { allowSubstring: boolean }+): ValueOption[] {+ const needle = lower(partial)+ if (!needle) {+ return options+ }+ const prefix: ValueOption[] = []+ const substring: ValueOption[] = []+ for (const option of options) {+ const starts = [option.label, option.value, ...(option.aliases ?? [])].map(lower)+ if (starts.some((word) => word.startsWith(needle))) {+ prefix.push(option)+ } else if (allowSubstring && starts.some((word) => word.includes(needle))) {+ substring.push(option)+ }+ }+ return [...prefix, ...substring]+}++/** The exact option a typed value names, if any. */+export function findExactOption(options: ValueOption[], value: string): ValueOption | null {+ const needle = lower(value)+ return (+ options.find(+ (option) =>+ lower(option.value) === needle ||+ lower(option.label) === needle ||+ (option.aliases ?? []).some((alias) => lower(alias) === needle)+ ) ?? null+ )+}++/**+ * The option a fully typed value commits to without a Space: it names the option exactly and no+ * other option starts with it, so typing more could not mean something else.+ */+export function unambiguousOption(options: ValueOption[], value: string): ValueOption | null {+ const exact = findExactOption(options, value)+ if (!exact) {+ return null+ }+ const needle = lower(value)+ const othersStartWith = options.some(+ (option) =>+ option !== exact &&+ [option.label, option.value, ...(option.aliases ?? [])].some((word) => lower(word).startsWith(needle))+ )+ return othersStartWith ? null : exact+}++/** Turns a typed `key:value` into a chip, or returns null when the value is not valid for that key. */+export function resolveChip(+ filter: FilterDefinition,+ value: string,+ negated: boolean,+ options: ValueOption[]+): QueryChip | null {+ const trimmed = value.trim()+ if (!trimmed) {+ return null+ }+ const exact = findExactOption(options, trimmed)+ if (exact) {+ return { key: filter.key, value: exact.value, label: exact.label, negated }+ }+ if (filter.freeTextValues) {+ return { key: filter.key, value: trimmed, label: trimmed, negated }+ }+ return null+}++export function chipId(chip: Pick<QueryChip, 'key' | 'value' | 'negated'>): string {+ return `${chip.negated ? '-' : ''}${chip.key}:${chip.value}`+}++/** Each key holds one chip. A new value for a key replaces the old chip in place. */+export function addChip(chips: QueryChip[], chip: QueryChip): QueryChip[] {+ const index = chips.findIndex((existing) => existing.key === chip.key)+ if (index === -1) {+ return [...chips, chip]+ }+ return chips.map((existing, i) => (i === index ? chip : existing))+}++const quoteIfNeeded = (value: string): string => (/\s/.test(value) ? `"${value}"` : value)++/** The editable text a chip turns back into. */+export function chipToText(chip: QueryChip): string {+ return `${chip.negated ? '-' : ''}${chip.key}:${quoteIfNeeded(chip.value)}`+}++export function filterDefinition(key: FilterKey): FilterDefinition {+ return FILTER_DEFINITIONS.find((definition) => definition.key === key) as FilterDefinition+}++const backendToken = (key: FilterKey, value: string, negated: boolean): string =>+ `${negated ? '-' : ''}${filterDefinition(key).backendField}:${quoteIfNeeded(value)}`++/** Removes a token from the text and returns the new text and where the cursor lands. */+export function removeToken(text: string, token: QueryToken): { text: string; cursor: number } {+ const before = text.slice(0, token.start).replace(/\s+$/, '')+ const after = text.slice(token.end).replace(/^\s+/, '')+ const joined = before && after ? `${before} ${after}` : before || after+ const cursor = before ? before.length + (after ? 1 : 0) : 0+ return { text: joined, cursor }+}++/** Replaces a token with new text and puts the cursor at the end of the replacement. */+export function replaceToken(text: string, token: QueryToken, replacement: string): { text: string; cursor: number } {+ return {+ text: text.slice(0, token.start) + replacement + text.slice(token.end),+ cursor: token.start + replacement.length,+ }+}++/** The values each filter key can suggest. Free-text keys may have none. */+export type FilterOptions = Record<FilterKey, ValueOption[]>++/** Moves every complete, valid filter token in the text into chips. Used for pasted queries. */+export function extractChips(+ text: string,+ chips: QueryChip[],+ options: FilterOptions+): { text: string; chips: QueryChip[] } {+ let nextChips = chips+ const remaining: string[] = []+ for (const token of tokenize(text)) {+ const parsed = parseToken(token.raw)+ const chip = parsed.filter+ ? resolveChip(parsed.filter, parsed.value, parsed.negated, options[parsed.filter.key])+ : null+ if (chip) {+ nextChips = addChip(nextChips, chip)+ } else {+ remaining.push(token.raw)+ }+ }+ return { text: remaining.join(' '), chips: nextChips }+}++export interface ResolvedQuery {+ /** The filters in effect: the chips, with a valid `key:value` still in the text standing in for that key's chip. */+ filters: QueryChip[]+ /** The text that is not a filter token. */+ freeText: string+ /** The `search` string for the file system endpoint. */+ backendSearch: string+}++/**+ * Resolves the input once per change, so every consumer agrees on what applies. A typed value+ * previews what committing it would do, so `createdBy:Ca` narrows results before it is committed.+ * Filters come first in `backendSearch`, sorted, so the same query typed in another order hits the+ * same cache entry.+ */+export function resolveQuery(text: string, chips: QueryChip[], options: FilterOptions): ResolvedQuery {+ const filters = new Map<FilterKey, QueryChip>(chips.map((chip) => [chip.key, chip]))+ const freeTokens: string[] = []+ for (const token of tokenize(text)) {+ const parsed = parseToken(token.raw)+ if (!parsed.filter) {+ freeTokens.push(token.raw)+ continue+ }+ const chip = resolveChip(parsed.filter, parsed.value, parsed.negated, options[parsed.filter.key])+ if (chip) {+ filters.set(chip.key, chip)+ }+ }+ const filterTokens = [...filters.values()].map((chip) => backendToken(chip.key, chip.value, chip.negated)).sort()+ return {+ filters: [...filters.values()],+ freeText: freeTokens.join(' '),+ backendSearch: [...filterTokens, ...freeTokens].join(' '),+ }+}++/** The raw query as a person would type it, chips included. Used for "Ask PostHog AI". */+export function queryAsText(text: string, chips: QueryChip[]): string {+ return [...chips.map(chipToText), text.trim()].filter(Boolean).join(' ')+}++export interface InputEdit {+ previousText: string+ previousCursor: number+ text: string+ cursor: number+}++const typedSpaceAt = (edit: InputEdit): boolean =>+ edit.cursor === edit.previousCursor + 1 &&+ edit.text[edit.previousCursor] === ' ' &&+ edit.text.slice(0, edit.previousCursor) + edit.text.slice(edit.cursor) === edit.previousText++/**+ * A space typed at the start or after another space separates nothing. It mostly follows a value+ * that already committed on its last letter, so it is dropped rather than left as stray text.+ */+export function isRedundantSpace(edit: InputEdit): boolean {+ return typedSpaceAt(edit) && (edit.previousCursor === 0 || /\s/.test(edit.previousText[edit.previousCursor - 1]))+}++/**+ * The chip an edit commits, as if its suggestion were picked: a space typed right after a valid+ * `key:value`, or a value that names exactly one option. Returns the token to remove from `text`.+ */+export function chipCommittedByEdit(+ edit: InputEdit,+ chips: QueryChip[],+ options: FilterOptions+): { chip: QueryChip; token: QueryToken; via: 'space' | 'typed' } | null {+ const { previousText, previousCursor, text, cursor } = edit+ const typedSpace = typedSpaceAt(edit)+ const context = typedSpace+ ? getCursorContext(previousText, previousCursor, chips)+ : getCursorContext(text, cursor, chips)+ const end = typedSpace ? previousCursor : cursor+ if (context.kind !== 'value' || context.token.end !== end) {+ return null+ }+ // A value inside an open quote is still being typed, whether the edit is a space or a letter.+ const rawValue = context.token.raw.slice(context.token.raw.indexOf(':') + 1)+ if (rawValue.startsWith('"') && (rawValue.length === 1 || !rawValue.endsWith('"'))) {+ return null+ }+ if (!typedSpace) {+ const option = unambiguousOption(options[context.filter.key], context.partial)+ return option+ ? {+ chip: { key: context.filter.key, value: option.value, label: option.label, negated: context.negated },+ token: context.token,+ via: 'typed',+ }+ : null+ }+ const chip = resolveChip(context.filter, context.partial, context.negated, options[context.filter.key])+ return chip ? { chip, token: context.token, via: 'space' } : null+}diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsxnew file mode 100644index 000000000000..4c6d73e36b74--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx@@ -0,0 +1,935 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ connect,+ kea,+ listeners,+ path,+ reducers,+ selectors,+} from 'kea'++import api, { isAbortError } from 'lib/api'+import { commandLogic } from 'lib/components/Command/commandLogic'+import { SearchItem, fileSystemEntryToSearchItem } from 'lib/components/Search/searchItems'+import { searchListsLogic } from 'lib/components/Search/searchListsLogic'+import { canOpenInNewTab } from 'lib/components/Search/utils'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { themeLogic } from 'lib/logic/themeLogic'+import posthog from 'lib/posthog-typed'+import { navigateToHref } from 'lib/utils/navigateToHref'+import { newInternalTab } from 'lib/utils/newInternalTab'+import { membersLogic } from 'scenes/organization/membersLogic'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import { groupsModel } from '~/models/groupsModel'+import { recentItemsModel } from '~/models/recentItemsModel'+import { FileSystemEntry } from '~/queries/schema/schema-general'++import type { Noun } from '../../../models/groupsModel'+import type { GroupType, GroupTypeIndex, OrganizationMemberType, UserType } from '../../../types'+import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'+import type { CommandOpenSource } from '../Command/commandLogic'+import { buildFilterOptions } from './commandKFilterOptions'+import { KeyIntent } from './commandKKeys'+import {+ CursorContext,+ FilterDefinition,+ FilterOptions,+ QueryChip,+ QueryToken,+ ResolvedQuery,+ addChip,+ chipCommittedByEdit,+ chipToText,+ extractChips,+ getCursorContext,+ isRedundantSpace,+ queryAsText,+ removeToken,+ replaceToken,+ resolveQuery,+ tokenAtCursor,+} from './commandKQuery'+import {+ CommandKMode,+ CommandKRow,+ CommandKSection,+ LocalLists,+ RECENTS_LIMIT,+ RemoteSlots,+ buildSections,+ buildSuggestions,+ emptyRemoteSlots,+ isSelectable,+ themeSearchItem,+} from './commandKSections'+import { REMOTE_REQUESTS, RemoteContext, RemoteResults, RemoteSource, settleSources } from './commandKSources'++const REMOTE_DEBOUNCE_MS = 150++export type CommitVia = 'tab' | 'enter' | 'space' | 'paste' | 'click' | 'typed'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface commandKSearchLogicValues {+ openSource: CommandOpenSource | null // commandLogic+ featureFlags: FeatureFlagsSet // featureFlagLogic+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel+ groupTypes: Map<GroupTypeIndex, GroupType> // groupsModel+ meFirstMembers: OrganizationMemberType[] // membersLogic+ members: OrganizationMemberType[] | null // membersLogic+ recents: FileSystemEntry[] // recentItemsModel+ dataManagementItems: SearchItem[] // searchListsLogic+ healthItems: SearchItem[] // searchListsLogic+ miscItems: SearchItem[] // searchListsLogic+ newItems: SearchItem[] // searchListsLogic+ peopleItems: SearchItem[] // searchListsLogic+ productsItems: SearchItem[] // searchListsLogic+ settingsItems: SearchItem[] // searchListsLogic+ starredItems: SearchItem[] // searchListsLogic+ currentTeamId: number | null // teamLogic+ isDarkModeOn: boolean // themeLogic+ user: UserType | null // userLogic+ askAiQuestion: string+ chips: QueryChip[]+ cursor: number+ cursorContext: CursorContext+ filterOptions: FilterOptions+ folders: FileSystemEntry[] | null+ highlightIsFilterRow: boolean+ highlightedKey: string | null+ highlightedRow: CommandKRow | null+ isPaletteEmpty: boolean+ localLists: LocalLists+ localQuery: string+ mode: CommandKMode+ recentItems: SearchItem[]+ remote: RemoteSlots+ remoteContext: RemoteContext+ remoteQueries: Partial<Record<RemoteSource, string>>+ requestQueries: Record<string, string>+ requestedQueries: Record<string, string>+ resolvedQuery: ResolvedQuery+ resultOpened: boolean+ sections: CommandKSection[]+ selectableRows: CommandKRow[]+ selectedChipIndex: number | null+ suggestionsSection: CommandKSection | null+ tabAsksAi: boolean+ text: string+ themeItem: SearchItem | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface commandKSearchLogicActions {+ closeCommand: () => {+ value: true+ } // commandLogic+ ensureAllMembersLoaded: () => {+ value: true+ } // membersLogic+ loadCurrentTeamSuccess: (+ currentTeam: null | import('../../../types').TeamPublicType,+ payload?: any+ ) => {+ currentTeam: null | import('../../../types').TeamPublicType+ payload?: any+ } // teamLogic+ activateRow: (+ row: CommandKRow,+ newTab: boolean,+ via: CommitVia+ ) => {+ newTab: boolean+ row: CommandKRow+ via: CommitVia+ }+ applyKeyIntent: (intent: KeyIntent) => {+ intent: KeyIntent+ }+ askAi: () => {+ value: true+ }+ clearQuery: () => {+ value: true+ }+ commitChip: (+ chip: QueryChip,+ token: QueryToken | null,+ via: CommitVia+ ) => {+ chip: QueryChip+ token: QueryToken | null+ via: CommitVia+ }+ completeFilterKey: (+ filter: FilterDefinition,+ negated: boolean+ ) => {+ filter: FilterDefinition+ negated: boolean+ }+ completeHighlighted: () => {+ value: true+ }+ editChip: (index: number) => {+ index: number+ }+ foldersLoaded: (folders: FileSystemEntry[]) => {+ folders: FileSystemEntry[]+ }+ inputChanged: (+ text: string,+ cursor: number,+ pasted: boolean+ ) => {+ cursor: number+ pasted: boolean+ text: string+ }+ loadFolders: () => {+ value: true+ }+ markResultOpened: () => {+ value: true+ }+ moveHighlight: (direction: 1 | -1) => {+ direction: 1 | -1+ }+ remoteLoaded: (+ query: string,+ results: RemoteResults+ ) => {+ query: string+ results: Partial<+ Record<+ 'accounts' | 'events' | 'groups' | 'persons' | 'properties' | 'results' | 'tickets' | 'workflows',+ SearchItem[]+ >+ >+ }+ removeChip: (index: number) => {+ index: number+ }+ requestStarted: (+ requestId: string,+ query: string+ ) => {+ query: string+ requestId: string+ }+ selectChip: (index: number | null) => {+ index: number | null+ }+ setChipsAndText: (+ chips: QueryChip[],+ text: string,+ cursor: number+ ) => {+ chips: QueryChip[]+ cursor: number+ text: string+ }+ setCursor: (cursor: number) => {+ cursor: number+ }+ setHighlightedKey: (key: string | null) => {+ key: string | null+ }+ setInput: (+ text: string,+ cursor: number+ ) => {+ cursor: number+ text: string+ }+ syncRemote: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface commandKSearchLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ filterOptions: (+ meFirstMembers: OrganizationMemberType[],+ user: UserType | null,+ folders: FileSystemEntry[] | null+ ) => FilterOptions+ cursorContext: (text: string, cursor: number, chips: QueryChip[]) => CursorContext+ mode: (cursorContext: CursorContext) => CommandKMode+ resolvedQuery: (text: string, chips: QueryChip[], filterOptions: FilterOptions) => ResolvedQuery+ localQuery: (resolvedQuery: ResolvedQuery, mode: CommandKMode) => string+ askAiQuestion: (text: string, chips: QueryChip[]) => string+ remoteContext: (+ currentTeamId: number | null,+ groupTypes: Map<GroupTypeIndex, GroupType>,+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun, // groupsModel+ featureFlags: FeatureFlagsSet+ ) => RemoteContext+ requestQueries: (+ resolvedQuery: ResolvedQuery,+ localQuery: string,+ mode: CommandKMode,+ remoteContext: RemoteContext+ ) => Record<string, string>+ remoteQueries: (requestQueries: Record<string, string>) => Partial<Record<RemoteSource, string>>+ suggestionsSection: (+ cursorContext: CursorContext,+ filterOptions: FilterOptions,+ members: OrganizationMemberType[] | null,+ folders: FileSystemEntry[] | null+ ) => CommandKSection | null+ recentItems: (recents: FileSystemEntry[]) => SearchItem[]+ localLists: (+ recentItems: SearchItem[],+ starredItems: SearchItem[],+ productsItems: SearchItem[],+ settingsItems: SearchItem[],+ newItems: SearchItem[],+ dataManagementItems: SearchItem[],+ peopleItems: SearchItem[],+ healthItems: SearchItem[],+ miscItems: SearchItem[]+ ) => LocalLists+ themeItem: (localQuery: string, isDarkModeOn: boolean) => SearchItem | null+ sections: (+ mode: CommandKMode,+ cursorContext: CursorContext,+ suggestionsSection: CommandKSection | null,+ localLists: LocalLists,+ remote: RemoteSlots,+ remoteQueries: Partial<+ Record<+ 'accounts' | 'events' | 'groups' | 'persons' | 'properties' | 'results' | 'tickets' | 'workflows',+ string+ >+ >,+ localQuery: string,+ themeItem: SearchItem | null,+ askAiQuestion: string+ ) => CommandKSection[]+ selectableRows: (sections: CommandKSection[]) => CommandKRow[]+ highlightedRow: (selectableRows: CommandKRow[], highlightedKey: string | null) => CommandKRow | null+ highlightIsFilterRow: (highlightedRow: CommandKRow | null) => boolean+ tabAsksAi: (highlightIsFilterRow: boolean, askAiQuestion: string) => boolean+ isPaletteEmpty: (text: string, chips: QueryChip[]) => boolean+ }+}++export type commandKSearchLogicType = MakeLogicType<+ commandKSearchLogicValues,+ commandKSearchLogicActions,+ Record<string, any>,+ commandKSearchLogicMeta+>++/**+ * Command K search: parses the input into filters and free text, builds the sections, owns the+ * highlight, and loads remote results. It mounts with the palette and unmounts when the palette+ * closes, which is what scopes every cache and in-flight request to one use of the palette.+ */+export const commandKSearchLogic = kea<commandKSearchLogicType>([+ path(['lib', 'components', 'CommandKSearch', 'commandKSearchLogic']),+ connect(() => ({+ values: [+ commandLogic,+ ['openSource'],+ searchListsLogic({ commandPalette: true }),+ [+ 'starredItems',+ 'productsItems',+ 'settingsItems',+ 'newItems',+ 'dataManagementItems',+ 'peopleItems',+ 'healthItems',+ 'miscItems',+ ],+ recentItemsModel,+ ['recents'],+ membersLogic,+ ['members', 'meFirstMembers'],+ userLogic,+ ['user'],+ teamLogic,+ ['currentTeamId'],+ featureFlagLogic,+ ['featureFlags'],+ groupsModel,+ ['groupTypes', 'aggregationLabel'],+ themeLogic,+ ['isDarkModeOn'],+ ],+ actions: [+ commandLogic,+ ['closeCommand'],+ membersLogic,+ ['ensureAllMembersLoaded'],+ teamLogic,+ ['loadCurrentTeamSuccess'],+ ],+ })),+ actions({+ inputChanged: (text: string, cursor: number, pasted: boolean) => ({ text, cursor, pasted }),+ setInput: (text: string, cursor: number) => ({ text, cursor }),+ setCursor: (cursor: number) => ({ cursor }),+ setChipsAndText: (chips: QueryChip[], text: string, cursor: number) => ({ chips, text, cursor }),+ commitChip: (chip: QueryChip, token: QueryToken | null, via: CommitVia) => ({ chip, token, via }),+ removeChip: (index: number) => ({ index }),+ selectChip: (index: number | null) => ({ index }),+ editChip: (index: number) => ({ index }),+ completeFilterKey: (filter: FilterDefinition, negated: boolean) => ({ filter, negated }),+ applyKeyIntent: (intent: KeyIntent) => ({ intent }),+ moveHighlight: (direction: 1 | -1) => ({ direction }),+ setHighlightedKey: (key: string | null) => ({ key }),+ activateRow: (row: CommandKRow, newTab: boolean, via: CommitVia) => ({ row, newTab, via }),+ completeHighlighted: true,+ askAi: true,+ clearQuery: true,+ syncRemote: true,+ requestStarted: (requestId: string, query: string) => ({ requestId, query }),+ remoteLoaded: (query: string, results: RemoteResults) => ({ query, results }),+ loadFolders: true,+ foldersLoaded: (folders: FileSystemEntry[]) => ({ folders }),+ markResultOpened: true,+ }),+ reducers({+ text: [+ '',+ {+ setInput: (_, { text }) => text,+ setChipsAndText: (_, { text }) => text,+ },+ ],+ cursor: [+ 0,+ {+ setInput: (_, { cursor }) => cursor,+ setCursor: (_, { cursor }) => cursor,+ setChipsAndText: (_, { cursor }) => cursor,+ },+ ],+ chips: [+ [] as QueryChip[],+ {+ setChipsAndText: (_, { chips }) => chips,+ removeChip: (state, { index }) => state.filter((_, i) => i !== index),+ },+ ],+ selectedChipIndex: [+ null as number | null,+ {+ selectChip: (_, { index }) => index,+ setInput: () => null,+ setChipsAndText: () => null,+ removeChip: () => null,+ },+ ],+ highlightedKey: [+ null as string | null,+ {+ setHighlightedKey: (_, { key }) => key,+ },+ ],+ // The query each request last asked for. No selector reads it, so starting a request never re-renders.+ requestedQueries: [+ {} as Record<string, string>,+ {+ requestStarted: (state, { requestId, query }) => ({ ...state, [requestId]: query }),+ },+ ],+ remote: [+ emptyRemoteSlots(),+ {+ remoteLoaded: (state, { query, results }) => {+ const next = { ...state }+ for (const [source, items] of Object.entries(results) as [RemoteSource, SearchItem[]][]) {+ next[source] = { cache: { ...state[source].cache, [query]: items }, displayedKey: query }+ }+ return next+ },+ },+ ],+ folders: [+ null as FileSystemEntry[] | null,+ {+ foldersLoaded: (_, { folders }) => folders,+ },+ ],+ resultOpened: [+ false,+ {+ markResultOpened: () => true,+ },+ ],+ }),+ selectors({+ filterOptions: [+ (s) => [s.meFirstMembers, s.user, s.folders],+ (+ members: OrganizationMemberType[],+ user: UserType | null,+ folders: FileSystemEntry[] | null+ ): FilterOptions => buildFilterOptions(members, user, folders),+ ],+ cursorContext: [+ (s) => [s.text, s.cursor, s.chips],+ (text: string, cursor: number, chips: QueryChip[]): CursorContext => getCursorContext(text, cursor, chips),+ ],+ mode: [+ (s) => [s.cursorContext],+ (context: CursorContext): CommandKMode => (context.kind === 'text' ? 'search' : context.kind),+ ],+ resolvedQuery: [+ (s) => [s.text, s.chips, s.filterOptions],+ (text: string, chips: QueryChip[], filterOptions: FilterOptions): ResolvedQuery =>+ resolveQuery(text, chips, filterOptions),+ ],+ /** The free text the non-object sections search for. Empty while a filter limits the palette to objects. */+ localQuery: [+ (s) => [s.resolvedQuery, s.mode],+ (resolved: ResolvedQuery, mode: CommandKMode): string =>+ (mode === 'search' || mode === 'key') && resolved.filters.length === 0 ? resolved.freeText.trim() : '',+ ],+ askAiQuestion: [+ (s) => [s.text, s.chips],+ (text: string, chips: QueryChip[]): string => queryAsText(text, chips),+ ],+ remoteContext: [+ (s) => [s.currentTeamId, s.groupTypes, s.aggregationLabel, s.featureFlags],+ (+ currentTeamId: number | null,+ groupTypes: Map<GroupTypeIndex, GroupType>,+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun, // groupsModel+ featureFlags: FeatureFlagsSet+ ): RemoteContext => ({+ currentTeamId,+ groupTypes: Array.from(groupTypes.values()),+ aggregationLabel,+ customerAnalyticsEnabled: !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP],+ }),+ ],+ /** The query each request runs for this input, for the requests that apply to it. */+ requestQueries: [+ (s) => [s.resolvedQuery, s.localQuery, s.mode, s.remoteContext],+ (+ resolved: ResolvedQuery,+ localQuery: string,+ mode: CommandKMode,+ context: RemoteContext+ ): Record<string, string> => {+ const queries: Record<string, string> = {}+ // Every request searches the current project, so none runs before one is known.+ if (context.currentTeamId === null) {+ return queries+ }+ for (const request of REMOTE_REQUESTS) {+ const query =+ request.query === 'objects' ? (mode === 'empty' ? '' : resolved.backendSearch) : localQuery+ if (query && (request.enabled?.(query, context) ?? true)) {+ queries[request.id] = query+ }+ }+ return queries+ },+ ],+ remoteQueries: [+ (s) => [s.requestQueries],+ (requestQueries: Record<string, string>): Partial<Record<RemoteSource, string>> =>+ Object.fromEntries(+ REMOTE_REQUESTS.flatMap((request) =>+ request.id in requestQueries+ ? request.sources.map((source) => [source, requestQueries[request.id]])+ : []+ )+ ),+ ],+ suggestionsSection: [+ (s) => [s.cursorContext, s.filterOptions, s.members, s.folders],+ (+ context: CursorContext,+ filterOptions: FilterOptions,+ members: OrganizationMemberType[] | null,+ folders: FileSystemEntry[] | null+ ): CommandKSection | null =>+ context.kind === 'value'+ ? buildSuggestions(context, filterOptions, {+ members: members === null,+ folders: folders === null,+ })+ : null,+ ],+ recentItems: [+ (s) => [s.recents],+ (recents: FileSystemEntry[]): SearchItem[] =>+ recents+ .slice(0, RECENTS_LIMIT)+ .map((entry) => fileSystemEntryToSearchItem(entry, { id: entry.path, category: 'recents' })),+ ],+ localLists: [+ (s) => [+ s.recentItems,+ s.starredItems,+ s.productsItems,+ s.settingsItems,+ s.newItems,+ s.dataManagementItems,+ s.peopleItems,+ s.healthItems,+ s.miscItems,+ ],+ (+ recents: SearchItem[],+ starred: SearchItem[],+ products: SearchItem[],+ settings: SearchItem[],+ create: SearchItem[],+ dataManagement: SearchItem[],+ people: SearchItem[],+ health: SearchItem[],+ misc: SearchItem[]+ ): LocalLists => ({+ recents,+ starred,+ products,+ settings,+ create,+ 'data-management': dataManagement,+ people,+ health,+ misc,+ }),+ ],+ themeItem: [+ (s) => [s.localQuery, s.isDarkModeOn],+ (localQuery: string, isDarkModeOn: boolean): SearchItem | null =>+ themeSearchItem(localQuery, isDarkModeOn, {+ setTheme: (mode) => userLogic.actions.updateUser({ theme_mode: mode }),+ toggleTheme: () => themeLogic.actions.toggleTheme(),+ }),+ ],+ sections: [+ (s) => [+ s.mode,+ s.cursorContext,+ s.suggestionsSection,+ s.localLists,+ s.remote,+ s.remoteQueries,+ s.localQuery,+ s.themeItem,+ s.askAiQuestion,+ ],+ (+ mode: CommandKMode,+ context: CursorContext,+ suggestions: CommandKSection | null,+ local: LocalLists,+ remote: RemoteSlots,+ remoteQueries: Partial<Record<RemoteSource, string>>,+ localQuery: string,+ themeItem: SearchItem | null,+ askAiQuestion: string+ ): CommandKSection[] =>+ buildSections({+ mode,+ context,+ suggestions,+ local,+ remote,+ remoteQueries,+ localQuery,+ themeItem,+ askAiQuestion,+ }),+ ],+ selectableRows: [+ (s) => [s.sections],+ (sections: CommandKSection[]): CommandKRow[] =>+ sections.flatMap((section) => section.rows).filter(isSelectable),+ ],+ highlightedRow: [+ (s) => [s.selectableRows, s.highlightedKey],+ (rows: CommandKRow[], highlightedKey: string | null): CommandKRow | null =>+ rows.find((row) => row.key === highlightedKey) ?? rows[0] ?? null,+ ],+ highlightIsFilterRow: [+ (s) => [s.highlightedRow],+ (row: CommandKRow | null): boolean => row?.kind === 'filter-key' || row?.kind === 'filter-value',+ ],+ tabAsksAi: [+ (s) => [s.highlightIsFilterRow, s.askAiQuestion],+ (highlightIsFilterRow: boolean, askAiQuestion: string): boolean => !!askAiQuestion && !highlightIsFilterRow,+ ],+ isPaletteEmpty: [+ (s) => [s.text, s.chips],+ (text: string, chips: QueryChip[]): boolean => text === '' && chips.length === 0,+ ],+ }),+ listeners(({ actions, values, cache }) => {+ const trackCommit = (chip: QueryChip, via: CommitVia): void => {+ posthog.capture('command k filter committed', {+ key: chip.key,+ value_kind: values.filterOptions[chip.key].some((option) => option.value === chip.value)+ ? 'option'+ : 'free_text',+ negated: chip.negated,+ via,+ })+ }++ const commit = (chip: QueryChip, token: QueryToken | null, text: string, via: CommitVia): void => {+ const remaining = token ? removeToken(text, token) : { text, cursor: values.cursor }+ actions.setChipsAndText(addChip(values.chips, chip), remaining.text, remaining.cursor)+ trackCommit(chip, via)+ }++ const openRow = (row: CommandKRow, newTab: boolean): void => {+ if (row.kind !== 'item' && row.kind !== 'ask-ai') {+ return+ }+ const item = row.kind === 'item' ? row.item : null+ if (item && (item.disabledReason || (newTab && !canOpenInNewTab(item)))) {+ return+ }+ actions.markResultOpened()+ posthog.capture('command k result opened', {+ section: row.kind === 'item' ? row.section : 'ask-ai',+ position: values.selectableRows.findIndex((candidate) => candidate.key === row.key),+ has_filters: values.chips.length > 0,+ filter_keys: values.chips.map((chip) => chip.key),+ query_length: values.askAiQuestion.length,+ })+ actions.closeCommand()+ if (row.kind === 'ask-ai') {+ navigateToHref(urls.ai(undefined, row.question))+ } else if (item?.onSelect) {+ item.onSelect()+ } else if (item?.href && newTab) {+ newInternalTab(item.href)+ } else if (item?.href) {+ navigateToHref(item.href)+ }+ }++ const onQueryChanged = (): void => {+ const context = values.cursorContext+ const keys =+ context.kind === 'key'+ ? context.matches.map((match) => match.key)+ : context.kind === 'value'+ ? [context.filter.key]+ : null+ const signature = keys ? `${context.kind}:${keys.join(',')}` : null+ if (signature && signature !== cache.lastSuggestion) {+ posthog.capture('command k filter suggested', { stage: context.kind, keys })+ }+ cache.lastSuggestion = signature+ // Value lists load the first time their filter is used, so opening the palette sends no request.+ if (context.kind === 'value' && context.filter.key === 'in') {+ actions.loadFolders()+ }+ if (context.kind === 'value' && context.filter.key === 'createdBy') {+ actions.ensureAllMembersLoaded()+ }+ actions.syncRemote()+ }++ return {+ // Remote searches wait for a project, so a project that loads mid-query starts them.+ loadCurrentTeamSuccess: () => actions.syncRemote(),+ inputChanged: ({ text, cursor, pasted }) => {+ if (pasted) {+ const extracted = extractChips(text, values.chips, values.filterOptions)+ for (const chip of extracted.chips.filter((chip) => !values.chips.includes(chip))) {+ trackCommit(chip, 'paste')+ }+ actions.setChipsAndText(extracted.chips, extracted.text, extracted.text.length)+ return+ }+ const edit = { previousText: values.text, previousCursor: values.cursor, text, cursor }+ if (isRedundantSpace(edit)) {+ return+ }+ const committed = chipCommittedByEdit(edit, values.chips, values.filterOptions)+ if (committed) {+ commit(committed.chip, committed.token, text, committed.via)+ } else {+ actions.setInput(text, cursor)+ }+ },+ setInput: onQueryChanged,+ setCursor: onQueryChanged,+ setChipsAndText: onQueryChanged,+ removeChip: onQueryChanged,+ commitChip: ({ chip, token, via }) => commit(chip, token, values.text, via),+ completeFilterKey: ({ filter, negated }) => {+ const token = tokenAtCursor(values.text, values.cursor)+ const replacement = `${negated ? '-' : ''}${filter.key}:`+ const next = token+ ? replaceToken(values.text, token, replacement)+ : { text: values.text + replacement, cursor: values.text.length + replacement.length }+ actions.setInput(next.text, next.cursor)+ },+ editChip: ({ index }) => {+ const chip = values.chips[index]+ if (!chip) {+ return+ }+ const chipText = chipToText(chip)+ actions.setChipsAndText(+ values.chips.filter((_, i) => i !== index),+ values.text ? `${chipText} ${values.text}` : chipText,+ chipText.length+ )+ },+ applyKeyIntent: ({ intent }) => {+ switch (intent.type) {+ case 'move':+ actions.moveHighlight(intent.direction)+ break+ case 'activate':+ if (values.highlightedRow) {+ actions.activateRow(values.highlightedRow, intent.newTab, 'enter')+ }+ break+ case 'complete':+ actions.completeHighlighted()+ break+ case 'select-chip':+ actions.selectChip(intent.index)+ break+ case 'remove-chip':+ actions.removeChip(intent.index)+ break+ case 'edit-chip':+ actions.editChip(intent.index)+ break+ case 'clear-or-close':+ if (values.isPaletteEmpty) {+ actions.closeCommand()+ } else {+ actions.clearQuery()+ }+ break+ }+ },+ moveHighlight: ({ direction }) => {+ const rows = values.selectableRows+ if (rows.length === 0) {+ return+ }+ const currentIndex = values.highlightedRow ? rows.indexOf(values.highlightedRow) : -1+ actions.setHighlightedKey(rows[(currentIndex + direction + rows.length) % rows.length].key)+ },+ activateRow: ({ row, newTab, via }) => {+ if (row.kind === 'filter-key') {+ actions.completeFilterKey(row.filter, row.negated)+ } else if (row.kind === 'filter-value') {+ const context = values.cursorContext+ actions.commitChip(+ { key: row.filter.key, value: row.option.value, label: row.option.label, negated: row.negated },+ context.kind === 'value' ? context.token : null,+ via+ )+ } else {+ openRow(row, newTab)+ }+ },+ completeHighlighted: () => {+ if (values.highlightIsFilterRow && values.highlightedRow) {+ actions.activateRow(values.highlightedRow, false, 'tab')+ } else {+ actions.askAi()+ }+ },+ askAi: () => {+ if (values.askAiQuestion) {+ openRow({ kind: 'ask-ai', key: 'ask-ai/ask', question: values.askAiQuestion }, false)+ }+ },+ clearQuery: () => actions.setChipsAndText([], '', 0),+ syncRemote: () => {+ for (const request of REMOTE_REQUESTS) {+ const query = values.requestQueries[request.id]+ if (!query) {+ // The request no longer applies, so stop it rather than let it hold a query slot.+ if (values.requestedQueries[request.id]) {+ cache.disposables.dispose(`request-${request.id}`)+ actions.requestStarted(request.id, '')+ }+ continue+ }+ if (query === values.requestedQueries[request.id]) {+ continue+ }+ actions.requestStarted(request.id, query)+ const cached = request.sources.map((source) => values.remote[source].cache[query])+ if (cached.every(Boolean)) {+ cache.disposables.dispose(`request-${request.id}`)+ actions.remoteLoaded(+ query,+ Object.fromEntries(request.sources.map((source, index) => [source, cached[index]]))+ )+ continue+ }+ // One disposable per request covers the debounce and the fetch, so a newer query+ // cancels both, and unmounting cancels everything.+ cache.disposables.add(+ () => {+ const controller = new AbortController()+ const timer = setTimeout(() => {+ request+ .fetch(query, controller.signal, values.remoteContext)+ .then((results) => settleSources(request, results))+ // A failed source settles empty so its section never stays on skeletons.+ .catch((error) => (isAbortError(error) ? null : settleSources(request, {})))+ .then((results) => {+ if (results && values.requestedQueries[request.id] === query) {+ actions.remoteLoaded(query, results)+ }+ })+ }, REMOTE_DEBOUNCE_MS)+ return () => {+ clearTimeout(timer)+ controller.abort()+ }+ },+ `request-${request.id}`,+ // Hiding the tab must not abort a search, or its section would sit on stale rows.+ { pauseOnPageHidden: false }+ )+ }+ },+ loadFolders: async () => {+ if (cache.foldersRequested) {+ return+ }+ cache.foldersRequested = true+ try {+ const response = await api.fileSystem.list({ type: 'folder', limit: 1000 })+ actions.foldersLoaded(response.results)+ } catch {+ actions.foldersLoaded([])+ }+ },+ }+ }),+ afterMount(({ values }) => {+ posthog.capture('command k search opened', { source: values.openSource })+ }),+ beforeUnmount(({ values }) => {+ if (!values.resultOpened) {+ posthog.capture('command k search abandoned', {+ last_mode: values.mode,+ had_filters: values.chips.length > 0,+ })+ }+ }),+])diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.tsnew file mode 100644index 000000000000..c6fecfe0c8f3--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.ts@@ -0,0 +1,267 @@+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 { REMOTE_SOURCES, RESULTS_LIMIT, RemoteSource, SECONDARY_LIMIT } from './commandKSources'++export const RECENTS_LIMIT = 5+export const SUGGESTIONS_LIMIT = 8+export const DEFAULT_SKELETON_ROWS = 3++/** Lists that filter in memory on every keystroke, in the order they render in Search mode. */+const LOCAL_SOURCES = ['products', 'data-management', 'people', 'health', 'misc', 'settings', 'create'] as const+type LocalSource = (typeof LOCAL_SOURCES)[number]++export type CommandKMode = 'empty' | 'key' | 'value' | 'search'++export type CommandKSectionKey =+ | 'filters'+ | 'suggestions'+ | 'recents'+ | 'starred'+ | LocalSource+ | RemoteSource+ | 'ask-ai'++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: 'item'; key: string; item: SearchItem; section: CommandKSectionKey }+ | { kind: 'ask-ai'; key: string; question: string }++export interface CommandKSection {+ key: CommandKSectionKey+ label: string+ rows: CommandKRow[]+ /** `stale` keeps the previous query's rows on screen until the new ones land. */+ state: 'ready' | 'loading' | 'stale'+ skeletonCount: number+}++/** What a remote section can render. Which request is in flight lives elsewhere, so starting one never re-renders. */+export interface RemoteSlot {+ cache: Record<string, SearchItem[]>+ displayedKey: string | null+}++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> = {+ filters: 'Filters',+ suggestions: 'Suggestions',+ recents: 'Recents',+ starred: 'Starred',+ results: 'Results',+ products: 'Products',+ 'data-management': 'Data management',+ people: 'People',+ health: 'Health',+ misc: 'Misc',+ settings: 'Settings',+ create: 'Create new',+ events: 'Events',+ properties: 'Properties',+ workflows: 'Workflows',+ accounts: 'Accounts',+ tickets: 'Support tickets',+ persons: 'Persons',+ groups: 'Groups',+ 'ask-ai': 'PostHog AI',+}++export const isSelectable = (row: CommandKRow): boolean => row.kind !== 'message'++const itemIdentity = (item: SearchItem): string => {+ const type = item.record?.type+ const ref = item.record?.ref+ return typeof type === 'string' && typeof ref === 'string' && ref ? `${type}:${ref}` : item.id+}++const itemRows = (section: CommandKSectionKey, items: SearchItem[]): CommandKRow[] =>+ items.map((item) => ({ kind: 'item', key: `${section}/${itemIdentity(item)}`, item, section }))++const readySection = (key: CommandKSectionKey, rows: CommandKRow[]): CommandKSection => ({+ key,+ label: SECTION_LABELS[key],+ rows,+ state: 'ready',+ skeletonCount: 0,+})++const loadingSection = (key: CommandKSectionKey): CommandKSection => ({+ ...readySection(key, []),+ state: 'loading',+ skeletonCount: DEFAULT_SKELETON_ROWS,+})++/**+ * A remote section shows the rows for the current query when they are cached, and the previous+ * query's rows while the new ones load. On its very first load, Results reserves skeleton rows. The+ * other sources usually come back empty, so they reserve nothing rather than flash skeletons that+ * then collapse.+ */+function remoteSection(source: RemoteSource, slot: RemoteSlot, query: string): CommandKSection | null {+ const limit = source === 'results' ? RESULTS_LIMIT : SECONDARY_LIMIT+ const current = slot.cache[query]+ if (current) {+ return current.length > 0 ? readySection(source, itemRows(source, current.slice(0, limit))) : null+ }+ const displayed = slot.displayedKey !== null ? slot.cache[slot.displayedKey] : undefined+ if (displayed) {+ return displayed.length > 0+ ? { ...readySection(source, itemRows(source, displayed.slice(0, limit))), state: 'stale' }+ : null+ }+ return source === 'results' ? loadingSection(source) : null+}++export interface SuggestionsLoading {+ members: boolean+ folders: boolean+}++/** Value suggestions for the `key:` under the cursor. */+export function buildSuggestions(+ context: Extract<CursorContext, { kind: 'value' }>,+ options: FilterOptions,+ loading: SuggestionsLoading+): CommandKSection {+ const { filter, partial, negated } = context+ const valueRow = (option: ValueOption): CommandKRow => ({+ kind: 'filter-value',+ key: `suggestions/${negated ? '-' : ''}${filter.key}:${option.value}`,+ filter,+ option,+ negated,+ })+ const message = (key: string, text: string): CommandKSection =>+ readySection('suggestions', [{ kind: 'message', key: `suggestions/${key}`, text }])++ if (filter.key === 'name') {+ return partial+ ? readySection('suggestions', [valueRow({ value: partial, label: partial })])+ : message('name-hint', 'Type part of a name')+ }+ if ((filter.key === 'createdBy' && loading.members) || (filter.key === 'in' && loading.folders)) {+ return loadingSection('suggestions')+ }+ const matches = matchValueOptions(options[filter.key], partial, { allowSubstring: filter.key !== 'createdBy' })+ if (matches.length === 0) {+ return filter.key === 'is'+ ? message('no-match', `No type called ${partial}`)+ : message('no-match', `No match for "${partial}". Press Space to search anyway.`)+ }+ // `is:` is a short fixed list, so every type shows. Other keys can have hundreds of values.+ return readySection(+ 'suggestions',+ (filter.key === 'is' ? matches : matches.slice(0, SUGGESTIONS_LIMIT)).map(valueRow)+ )+}++export type LocalLists = Record<LocalSource | 'recents' | 'starred', SearchItem[]>++export interface SectionsInput {+ mode: CommandKMode+ context: CursorContext+ suggestions: CommandKSection | null+ local: LocalLists+ remote: RemoteSlots+ /** The query each remote source searches for this input. Sources missing here do not apply. */+ remoteQueries: Partial<Record<RemoteSource, string>>+ /** The free text the in-memory lists filter on. Empty while a filter limits the palette to objects. */+ localQuery: string+ /** Leads the Settings section when the query asks about the theme. */+ themeItem: SearchItem | null+ askAiQuestion: string+}++const filterLocal = (source: LocalSource, items: SearchItem[], query: string): SearchItem[] =>+ (source === 'create' ? filterNewItems(items, query) : filterSearchItems(items, query)).slice(0, SECONDARY_LIMIT)++export function buildSections(input: SectionsInput): CommandKSection[] {+ const { mode, context, local, remote, remoteQueries, localQuery } = input+ if (mode === 'empty') {+ return [+ readySection('recents', itemRows('recents', local.recents.slice(0, RECENTS_LIMIT))),+ readySection('starred', itemRows('starred', local.starred)),+ // Tab rows ("Dashboards / Templates") only appear for a search, as in the current palette.+ readySection(+ 'products',+ itemRows(+ 'products',+ local.products.filter((item) => !item.parentName)+ )+ ),+ ].filter((section) => section.rows.length > 0)+ }++ const remoteSectionFor = (source: RemoteSource): CommandKSection | null => {+ const query = remoteQueries[source]+ return query ? remoteSection(source, remote[source], query) : null+ }+ const sections: (CommandKSection | null)[] = []+ if (context.kind === 'key') {+ sections.push(+ readySection(+ 'filters',+ context.matches.map((filter) => ({+ kind: 'filter-key',+ key: `filters/${context.negated ? '-' : ''}${filter.key}`,+ filter,+ negated: context.negated,+ }))+ )+ )+ }+ sections.push(input.suggestions, remoteSectionFor('results'))+ if (mode !== 'value' && localQuery) {+ for (const source of LOCAL_SOURCES) {+ const filtered = filterLocal(source, local[source], localQuery)+ const items = source === 'settings' && input.themeItem ? [input.themeItem, ...filtered] : filtered+ sections.push(items.length > 0 ? readySection(source, itemRows(source, items)) : null)+ }+ }+ if (mode !== 'value') {+ sections.push(...REMOTE_SOURCES.filter((source) => source !== 'results').map(remoteSectionFor))+ if (input.askAiQuestion) {+ sections.push(+ readySection('ask-ai', [{ kind: 'ask-ai', key: 'ask-ai/ask', question: input.askAiQuestion }])+ )+ }+ }+ return sections.filter((section): section is CommandKSection => section !== null)+}++const THEME_QUERY_WORDS = ['dark', 'light', 'theme', 'appearance']++/**+ * A settings row that switches the theme straight from search. "dark" or "light" sets that mode;+ * "theme" or "appearance" toggles away from the current one.+ */+export function themeSearchItem(+ query: string,+ isDarkModeOn: boolean,+ { setTheme, toggleTheme }: { setTheme: (mode: 'dark' | 'light') => void; toggleTheme: () => void }+): SearchItem | null {+ const normalized = query.trim().toLowerCase()+ if (!normalized || !THEME_QUERY_WORDS.some((word) => normalized.includes(word))) {+ return null+ }+ const requested = normalized.includes('dark') ? 'dark' : normalized.includes('light') ? 'light' : null+ const target = requested ?? (isDarkModeOn ? 'light' : 'dark')+ const name = target === 'dark' ? 'Dark mode' : 'Light mode'+ return {+ id: SETTINGS_THEME_ITEM_ID,+ name,+ displayName: name,+ category: 'settings',+ itemType: 'settings',+ searchKeywords: THEME_QUERY_WORDS,+ onSelect: requested ? () => setTheme(requested) : toggleTheme,+ record: { type: 'settings', ref: 'theme' },+ }+}diff --git a/frontend/src/lib/components/CommandKSearch/commandKSources.ts b/frontend/src/lib/components/CommandKSearch/commandKSources.tsnew file mode 100644index 000000000000..b2a430439cb3--- /dev/null+++ b/frontend/src/lib/components/CommandKSearch/commandKSources.ts@@ -0,0 +1,185 @@+import api from 'lib/api'+import {+ SearchItem,+ accountToSearchItem,+ fileSystemEntryToSearchItem,+ groupToSearchItem,+ personToSearchItem,+ ticketToSearchItem,+ unifiedSearchResultToSearchItem,+} from 'lib/components/Search/searchItems'+import { shouldSearchTickets } from 'lib/components/Search/utils'+import { uuid } from 'lib/utils/dom'+import { mapGroupQueryResponse } from 'lib/utils/groups'++import type { Noun } from '~/models/groupsModel'+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'++export const RESULTS_LIMIT = 20+export const SECONDARY_LIMIT = 5++/**+ * Remote sections, in render order. Results holds the objects that filters apply to. The rest+ * search free text for what the file system does not hold, and render below everything else.+ */+export const REMOTE_SOURCES = [+ 'results',+ 'events',+ 'properties',+ 'workflows',+ 'accounts',+ 'tickets',+ 'persons',+ 'groups',+] as const+export type RemoteSource = (typeof REMOTE_SOURCES)[number]++export type RemoteResults = Partial<Record<RemoteSource, SearchItem[]>>++export interface RemoteContext {+ currentTeamId: number | null+ groupTypes: GroupType[]+ aggregationLabel: (groupTypeIndex: GroupTypeIndex) => Noun+ customerAnalyticsEnabled: boolean+}++export interface RemoteRequest {+ id: string+ /** `objects` searches with filters applied. `text` searches the free text and runs only while no filter is set. */+ query: 'objects' | 'text'+ /** The sections this request fills. One request can fill several. */+ sources: RemoteSource[]+ enabled?: (query: string, context: RemoteContext) => boolean+ fetch: (query: string, signal: AbortSignal, context: RemoteContext) => Promise<RemoteResults>+}++const fetchPersons = async (term: string, signal: AbortSignal, context: RemoteContext): Promise<RemoteResults> => {+ const clientQueryId = uuid()+ let finished = false+ // Aborting the request does not stop the ClickHouse query, so cancel it by id.+ const cancel = (): void => {+ if (!finished) {+ api.cancelQuery(clientQueryId).catch(() => {})+ }+ }+ signal.addEventListener('abort', cancel, { once: true })+ try {+ const response = await personsList(+ String(context.currentTeamId),+ { search: term, limit: SECONDARY_LIMIT, client_query_id: clientQueryId },+ { signal }+ )+ return { persons: (response.results ?? []).filter((person) => !!person.uuid).map(personToSearchItem) }+ } finally {+ finished = true+ signal.removeEventListener('abort', cancel)+ }+}++const fetchGroups = async (term: string, signal: AbortSignal, context: RemoteContext): Promise<RemoteResults> => {+ const settled = await Promise.allSettled(+ context.groupTypes.map((groupType) =>+ // The generated groupsList is a different endpoint (Postgres REST). This ClickHouse+ // GroupsQuery matches what the current palette searches, so results stay the same.+ // nosemgrep: prefer-codegen-api-namespaced-groups+ api.groups.listClickhouse(+ { group_type_index: groupType.group_type_index, search: term, limit: SECONDARY_LIMIT },+ { signal }+ )+ )+ )+ signal.throwIfAborted()+ return {+ groups: settled.flatMap((result, index) => {+ if (result.status !== 'fulfilled') {+ return []+ }+ const groupTypeIndex = context.groupTypes[index].group_type_index as GroupTypeIndex+ const noun = context.aggregationLabel(groupTypeIndex).singular+ return mapGroupQueryResponse(result.value).map((group) => groupToSearchItem(group, groupTypeIndex, noun))+ }),+ }+}++const UNIFIED_TYPES: Record<string, RemoteSource> = {+ event_definition: 'events',+ property_definition: 'properties',+ hog_flow: 'workflows',+}++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 })+ return {+ results: response.results.map((entry) =>+ fileSystemEntryToSearchItem(entry, { id: entry.id, category: 'results' })+ ),+ }+ },+ },+ {+ id: 'unified',+ query: 'text',+ sources: ['events', 'properties', 'workflows'],+ fetch: async (q, signal) => {+ const response = await api.search.list(+ { q, entities: ['event_definition', 'property_definition', 'hog_flow'], include_counts: false },+ { signal }+ )+ const results: RemoteResults = { events: [], properties: [], workflows: [] }+ for (const result of response.results) {+ const source = UNIFIED_TYPES[result.type]+ results[source]?.push(unifiedSearchResultToSearchItem(result))+ }+ return results+ },+ },+ {+ id: 'accounts',+ query: 'text',+ sources: ['accounts'],+ enabled: (_, context) => context.customerAnalyticsEnabled,+ fetch: async (search, signal, context) => {+ const response = await accountsList(+ String(context.currentTeamId),+ { search, limit: SECONDARY_LIMIT },+ { signal }+ )+ return { accounts: response.results.map(accountToSearchItem) }+ },+ },+ {+ id: 'tickets',+ query: 'text',+ sources: ['tickets'],+ enabled: (term) => shouldSearchTickets(term),+ fetch: async (search, signal, context) => {+ const response = await conversationsTicketsList(+ String(context.currentTeamId),+ { search, limit: SECONDARY_LIMIT },+ { signal }+ )+ return { tickets: response.results.map(ticketToSearchItem) }+ },+ },+ { id: 'persons', query: 'text', sources: ['persons'], fetch: fetchPersons },+ {+ id: 'groups',+ query: 'text',+ sources: ['groups'],+ enabled: (_, context) => context.groupTypes.length > 0,+ fetch: fetchGroups,+ },+]++/** Results for every source of a request, empty where the response held none. */+export const settleSources = (request: RemoteRequest, results: RemoteResults): RemoteResults =>+ Object.fromEntries(request.sources.map((source) => [source, results[source] ?? []]))diff --git a/frontend/src/lib/components/Search/Search.tsx b/frontend/src/lib/components/Search/Search.tsxindex b6d0b72d4665..95cdea8a5ee8 100644--- a/frontend/src/lib/components/Search/Search.tsx+++ b/frontend/src/lib/components/Search/Search.tsx@@ -34,14 +34,14 @@ import { newInternalTab } from 'lib/utils/newInternalTab'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'-import { ProductIconWrapper, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { MenuItems } from '~/layout/panel-layout/ProjectTree/menus/MenuItems'-import { fileSystemTypes } from '~/products'-import { FileSystemIconType } from '~/queries/schema/schema-general'import type { UserTheme } from '~/types'import { ScrollableShadows } from '../ScrollableShadows/ScrollableShadows'-import { RECENTS_LIMIT, STARRED_LIMIT, SearchItem, SearchLogicProps, searchLogic } from './searchLogic'+import { getIconForItem, getItemTypeDisplayName } from './searchItemDisplay'+import { SearchItem } from './searchItems'+import { STARRED_LIMIT } from './searchListsLogic'+import { RECENTS_LIMIT, SearchLogicProps, searchLogic } from './searchLogic'import { SETTINGS_THEME_ITEM_ID, canOpenInNewTab, formatRelativeTimeShort, getCategoryDisplayName } from './utils'// ============================================================================@@ -113,89 +113,6 @@ const useRotatingPlaceholder = (isActive: boolean): { text: string; isVisible: b// Helpers// ============================================================================-const getItemTypeDisplayName = (type: string | null | undefined): string | null => {- if (!type) {- return null- }-- // Check fileSystemTypes manifest first- if (type in fileSystemTypes) {- return (fileSystemTypes as Record<string, { name?: string }>)[type]?.name ?? null- }-- // Handle insight subtypes (e.g., 'insight/funnels' -> 'Funnel')- if (type.startsWith('insight/')) {- const subtype = type.slice(8) // Remove 'insight/' prefix- const insightDisplayNames: Record<string, string> = {- funnels: 'Funnel',- trends: 'Trend',- retention: 'Retention',- paths: 'Paths',- lifecycle: 'Lifecycle',- stickiness: 'Stickiness',- hog: 'SQL insight',- }- return insightDisplayNames[subtype] ?? null- }-- // Fallback for types not in the manifest- const fallbackDisplayNames: Record<string, string> = {- query: 'SQL query',- product_analytics: 'Product analytics',- web_analytics: 'Web analytics',- llm_analytics: 'AI observability',- revenue_analytics: 'Revenue analytics',- marketing_analytics: 'Marketing analytics',- session_replay: 'Session replay',- error_tracking: 'Error tracking',- data_warehouse: 'Data ops',- data_pipeline: 'Data pipeline',- annotation: 'Annotation',- event_definition: 'Event',- property_definition: 'Property',- person: 'Person',- persons: 'Person',- user: 'User',- group: 'Group',- account: 'Account',- heatmap: 'Heatmap',- sql_editor: 'SQL query',- logs: 'Logs',- alert: 'Alert',- folder: 'Folder',- hog_flow: 'Workflow',- }- return fallbackDisplayNames[type] ?? null-}--const getIconForItem = (item: SearchItem): ReactNode => {- if (item.icon) {- return item.icon- }- let itemType = item.itemType || item.record?.type- // Normalize types for icon lookup- if (itemType === 'person') {- itemType = 'persons'- } else if (itemType === 'hog_flow') {- itemType = 'workflows'- }- if (itemType) {- // Handle iconColor which may be a single-element array or tuple- const rawColor = item.record?.iconColor as string[] | undefined- const colorOverride: [string, string] | undefined = rawColor- ? rawColor.length === 1- ? [rawColor[0], rawColor[0]]- : [rawColor[0], rawColor[1]]- : undefined- return (- <ProductIconWrapper type={itemType as string} colorOverride={colorOverride}>- {iconForType(itemType as FileSystemIconType, colorOverride)}- </ProductIconWrapper>- )- }- return null-}-const commandItemToTreeDataItem = (item: SearchItem): TreeDataItem => {return {id: item.id,diff --git a/frontend/src/lib/components/Search/searchItemDisplay.tsx b/frontend/src/lib/components/Search/searchItemDisplay.tsxnew file mode 100644index 000000000000..489a2bf96fed--- /dev/null+++ b/frontend/src/lib/components/Search/searchItemDisplay.tsx@@ -0,0 +1,90 @@+import { ReactNode } from 'react'++import { ProductIconWrapper, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { fileSystemTypes } from '~/products'+import { FileSystemIconType } from '~/queries/schema/schema-general'++import { SearchItem } from './searchItems'++export const getItemTypeDisplayName = (type: string | null | undefined): string | null => {+ if (!type) {+ return null+ }++ // Check fileSystemTypes manifest first+ if (type in fileSystemTypes) {+ return (fileSystemTypes as Record<string, { name?: string }>)[type]?.name ?? null+ }++ // Handle insight subtypes (e.g., 'insight/funnels' -> 'Funnel')+ if (type.startsWith('insight/')) {+ const subtype = type.slice(8) // Remove 'insight/' prefix+ const insightDisplayNames: Record<string, string> = {+ funnels: 'Funnel',+ trends: 'Trend',+ retention: 'Retention',+ paths: 'Paths',+ lifecycle: 'Lifecycle',+ stickiness: 'Stickiness',+ hog: 'SQL insight',+ }+ return insightDisplayNames[subtype] ?? null+ }++ // Fallback for types not in the manifest+ const fallbackDisplayNames: Record<string, string> = {+ query: 'SQL query',+ product_analytics: 'Product analytics',+ web_analytics: 'Web analytics',+ llm_analytics: 'AI observability',+ revenue_analytics: 'Revenue analytics',+ marketing_analytics: 'Marketing analytics',+ session_replay: 'Session replay',+ error_tracking: 'Error tracking',+ data_warehouse: 'Data ops',+ data_pipeline: 'Data pipeline',+ annotation: 'Annotation',+ event_definition: 'Event',+ property_definition: 'Property',+ person: 'Person',+ persons: 'Person',+ user: 'User',+ group: 'Group',+ account: 'Account',+ heatmap: 'Heatmap',+ sql_editor: 'SQL query',+ logs: 'Logs',+ alert: 'Alert',+ folder: 'Folder',+ hog_flow: 'Workflow',+ }+ return fallbackDisplayNames[type] ?? null+}++export const getIconForItem = (item: SearchItem): ReactNode => {+ if (item.icon) {+ return item.icon+ }+ let itemType = item.itemType || item.record?.type+ // Normalize types for icon lookup+ if (itemType === 'person') {+ itemType = 'persons'+ } else if (itemType === 'hog_flow') {+ itemType = 'workflows'+ }+ if (itemType) {+ // Handle iconColor which may be a single-element array or tuple+ const rawColor = item.record?.iconColor as string[] | undefined+ const colorOverride: [string, string] | undefined = rawColor+ ? rawColor.length === 1+ ? [rawColor[0], rawColor[0]]+ : [rawColor[0], rawColor[1]]+ : undefined+ return (+ <ProductIconWrapper type={itemType as string} colorOverride={colorOverride}>+ {iconForType(itemType as FileSystemIconType, colorOverride)}+ </ProductIconWrapper>+ )+ }+ return null+}diff --git a/frontend/src/lib/components/Search/searchItems.tsx b/frontend/src/lib/components/Search/searchItems.tsxnew file mode 100644index 000000000000..f6a4195d7c9e--- /dev/null+++ b/frontend/src/lib/components/Search/searchItems.tsx@@ -0,0 +1,273 @@+import { IconBuilding } from '@posthog/icons'++import { getEntryAccessDisabledReason } from 'lib/utils/accessControlUtils'+import { GroupQueryResult } from 'lib/utils/groups'+import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'+import { capitalizeFirstLetter } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'+import { getTreeItemsProducts } from '~/products'+import { FileSystemEntry } from '~/queries/schema/schema-general'+import { FileSystemIconColor, GroupTypeIndex, SearchResponse } from '~/types'++import type { TicketApi } from 'products/conversations/frontend/generated/api.schemas'+import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { filterSearchItems } from './utils'++/** Safely extract a string — returns undefined for objects/arrays to avoid rendering [object Object]. */+const safeString = (val: unknown): string | undefined => (typeof val === 'string' ? val : undefined)++// Types for command search results+export interface SearchItem {+ id: string+ name: string+ displayName?: string+ category: string+ productCategory?: string | null+ href?: string+ /** Action invoked when the item is selected. Use for items that trigger something+ * other than navigation (e.g. logging out). Consumers should prefer `onSelect` over `href`. */+ onSelect?: () => void+ icon?: React.ReactNode+ lastViewedAt?: string | null+ groupNoun?: string | null+ itemType?: string | null+ searchKeywords?: string[]+ hiddenSearchText?: string+ matchedSearchKeyword?: string | null+ parentName?: string+ record?: Record<string, unknown>+ rank?: number | null // PostgreSQL full-text search rank (from unified search API)+ /** 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?: string+}++let cachedProductIconColorByType: Map<string, FileSystemIconColor> | null = null+let cachedProductDisplayLabelByPath: Map<string, string> | null = null+let cachedProductIconTypeByPath: Map<string, string> | null = null++const getProductIconColorByType = (): Map<string, FileSystemIconColor> => {+ if (cachedProductIconColorByType === null) {+ cachedProductIconColorByType = new Map()+ for (const product of getTreeItemsProducts()) {+ const key = product.type || product.iconType+ if (key && product.iconColor) {+ cachedProductIconColorByType.set(key, product.iconColor)+ }+ }+ }+ return cachedProductIconColorByType+}++const getProductDisplayLabelByPath = (): Map<string, string> => {+ if (cachedProductDisplayLabelByPath === null) {+ cachedProductDisplayLabelByPath = new Map()+ for (const product of getTreeItemsProducts()) {+ if (product.displayLabel) {+ cachedProductDisplayLabelByPath.set(product.path, product.displayLabel)+ }+ }+ }+ return cachedProductDisplayLabelByPath+}++const getProductIconTypeByPath = (): Map<string, string> => {+ if (cachedProductIconTypeByPath === null) {+ cachedProductIconTypeByPath = new Map()+ for (const product of getTreeItemsProducts()) {+ const iconType = product.type || product.iconType+ if (iconType) {+ cachedProductIconTypeByPath.set(product.path, iconType)+ }+ }+ }+ return cachedProductIconTypeByPath+}++export const fileSystemEntryToSearchItem = (+ item: FileSystemEntry,+ overrides: { id: string; category: string; searchKeywords?: string[] }+): SearchItem => {+ const name = splitPath(item.path).pop()+ const itemName = name ? unescapePath(name) : item.path+ const displayName = getProductDisplayLabelByPath().get(itemName)+ // Older starred shortcuts (e.g. Logs, Web analytics) were saved with a blank (empty-string)+ // type because their product only defines `iconType`. The `||` (not `??`) is deliberate: an+ // empty string must fall through to the product registry, keyed by name, so the icon resolves.+ const itemType = item.type || getProductIconTypeByPath().get(itemName) || null+ const productIconColor = itemType ? getProductIconColorByType().get(itemType) : undefined+ return {+ name: itemName,+ displayName,+ href: item.href || PLACEHOLDER_HREF,+ lastViewedAt: item.last_viewed_at ?? null,+ itemType,+ record: { ...item, iconColor: productIconColor },+ disabledReason: getEntryAccessDisabledReason(item),+ ...overrides,+ }+}++/** Maps one unified search result to a search item. */+export const unifiedSearchResultToSearchItem = (result: SearchResponse['results'][number]): SearchItem => {+ let name = result.result_id+ let href = ''++ switch (result.type) {+ case 'insight':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/insights/${result.result_id}`+ break+ case 'dashboard':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/dashboard/${result.result_id}`+ break+ case 'feature_flag':+ name = safeString(result.extra_fields.key) || result.result_id+ href = `/feature_flags/${result.result_id}`+ break+ case 'experiment':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/experiments/${result.result_id}`+ break+ case 'early_access_feature':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/early_access_features/${result.result_id}`+ break+ case 'hog_flow':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/workflows/${result.result_id}/workflow`+ break+ case 'survey':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/surveys/${result.result_id}`+ break+ case 'notebook':+ name = safeString(result.extra_fields.title) || result.result_id+ href = `/notebooks/${result.result_id}`+ break+ case 'cohort':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/cohorts/${result.result_id}`+ break+ case 'action':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/data-management/actions/${result.result_id}`+ break+ case 'event_definition':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/data-management/events/${result.result_id}`+ break+ case 'property_definition':+ name = safeString(result.extra_fields.name) || result.result_id+ href = `/data-management/properties/${result.result_id}`+ break+ }++ return {+ id: `${result.type}-${result.result_id}`,+ name,+ category: result.type,+ href,+ itemType: result.type,+ rank: result.rank,+ disabledReason: getEntryAccessDisabledReason(result),+ record: {+ type: result.type,+ ...result.extra_fields,+ },+ }+}++export const accountToSearchItem = (account: AccountApi): SearchItem => {+ const displayName = account.name || account.external_id || account.id+ return {+ id: `account-${account.id}`,+ name: displayName,+ displayName,+ category: 'accounts',+ href: urls.customerAnalyticsAccount(account.id),+ icon: <IconBuilding />,+ itemType: 'account',+ record: { type: 'account', id: account.id },+ }+}++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+ // it is what someone who typed a number is looking to confirm.+ const subject = ticket.email_subject || ticket.last_message_text || 'Untitled ticket'+ const displayName = `#${ticket.ticket_number} ${subject}`+ return {+ id: `ticket-${ticket.id}`,+ name: displayName,+ displayName,+ category: 'tickets',+ // The detail scene redirects a UUID to the ticket-number URL, so linking+ // there directly saves the row a redirect.+ href: urls.supportTicketDetail(ticket.ticket_number),+ itemType: 'conversations',+ // Rendered as the row's muted trailing text: which tickets are still open+ // is the first thing a support agent reads off a list of matches.+ productCategory: ticket.status ? capitalizeFirstLetter(ticket.status.replace(/_/g, ' ')) : null,+ record: { type: 'conversations', id: ticket.id, ticketNumber: ticket.ticket_number },+ }+}++/** "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++/** "Create new" items match on their name, type and path, with a leading "create" read as "new". */+export const filterNewItems = (newItems: SearchItem[], search: string): SearchItem[] =>+ filterSearchItems(newItems, search.replace(LEADING_CREATE_WORD, 'new'))++/** Structural, so a person from the legacy API and one from the generated client both fit. */+interface SearchablePerson {+ uuid: string+ distinct_ids?: readonly string[]+ properties?: unknown+}++export const personToSearchItem = (person: SearchablePerson): SearchItem => {+ const personId = person.distinct_ids?.[0] || person.uuid+ const properties = (person.properties ?? {}) as Record<string, unknown>+ const displayName = safeString(properties.email) || safeString(properties.name) || String(personId)+ return {+ id: `person-${person.uuid}`,+ name: displayName,+ displayName,+ category: 'persons',+ href: urls.personByUUID(person.uuid),+ itemType: 'person',+ record: { type: 'person', ref: person.uuid, uuid: person.uuid, distinctIds: person.distinct_ids },+ }+}++export const groupToSearchItem = (+ group: GroupQueryResult,+ groupTypeIndex: GroupTypeIndex,+ noun: string+): SearchItem => {+ const display = group.group_properties?.name || group.group_key || String(group.group_key)+ return {+ id: `group-${groupTypeIndex}-${group.group_key}`,+ name: `${noun}: ${display}`,+ displayName: display,+ category: 'groups',+ href: `/groups/${groupTypeIndex}/${encodeURIComponent(group.group_key)}`,+ groupNoun: noun,+ itemType: 'group',+ record: {+ type: 'group',+ ref: `${groupTypeIndex}:${group.group_key}`,+ groupTypeIndex,+ groupKey: group.group_key,+ groupNoun: noun,+ },+ }+}diff --git a/frontend/src/lib/components/Search/searchListsLogic.test.ts b/frontend/src/lib/components/Search/searchListsLogic.test.tsnew file mode 100644index 000000000000..81aad561c789--- /dev/null+++ b/frontend/src/lib/components/Search/searchListsLogic.test.ts@@ -0,0 +1,91 @@+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'++import { initKeaTests } from '~/test/init'++import { searchListsLogic } from './searchListsLogic'++describe('searchListsLogic', () => {+ let logic: ReturnType<typeof searchListsLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = searchListsLogic({ commandPalette: false })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it.each([false, true])('gates the command-menu terminal toggle when enabled=%s', (enabled) => {+ logic.unmount()+ logic = searchListsLogic({ commandPalette: true })+ logic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: enabled })++ const toggle = logic.values.miscItems.find((item) => item.id === 'misc-toggle-terminal')+ expect(!!toggle).toBe(enabled)+ expect(terminalDockLogic.values.dockOpen).toBe(false)+ if (toggle) {+ toggle.onSelect?.()+ expect(terminalDockLogic.values.dockOpen).toBe(true)+ toggle.onSelect?.()+ expect(terminalDockLogic.values.dockOpen).toBe(false)+ toggle.onSelect?.()+ featureFlagLogic.actions.setFeatureFlags([], {})+ expect(terminalDockLogic.values.dockOpen).toBe(false)+ expect(logic.values.miscItems.some((item) => item.id === 'misc-toggle-terminal')).toBe(false)+ }+ featureFlagLogic.actions.setFeatureFlags([], {})+ terminalDockLogic.actions.toggleTerminal()+ expect(terminalDockLogic.values.dockOpen).toBe(false)+ })++ it.each([+ ['off', false, 'Model preferences', false],+ ['on', true, 'Agent preferences', true],+ ])(+ 'shows one copy of a section gated on a flag and its negation, with the flag %s',+ (_state, flagOn, expectedName, expectsGatedKeyword) => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TODAY_RAIL_NAV]: flagOn })+ const settings = [+ {+ id: 'task-agent-my-preference',+ hasTitle: true,+ titleString: 'My default model',+ descriptionString: null,+ },+ {+ id: 'task-comments-slack-dm',+ hasTitle: true,+ titleString: 'Gated setting',+ descriptionString: null,+ keywords: ['zebra'],+ flag: 'TODAY_RAIL_NAV' as const,+ },+ ]+ logic.actions.setSettingsSections([+ {+ id: 'environment-task-agents',+ level: 'environment',+ titleString: 'Agent preferences',+ flag: 'TODAY_RAIL_NAV',+ settings,+ },+ {+ id: 'environment-task-agents',+ level: 'environment',+ titleString: 'Model preferences',+ flag: '!TODAY_RAIL_NAV',+ settings,+ },+ ])++ const items = logic.values.settingsItems.filter((item) => item.id === 'settings-project-task-agents')+ expect(items.map((item) => item.displayName)).toEqual([expectedName])+ expect(items[0].name.includes('zebra')).toBe(expectsGatedKeyword)+ }+ )+})diff --git a/frontend/src/lib/components/Search/searchListsLogic.tsx b/frontend/src/lib/components/Search/searchListsLogic.tsxnew file mode 100644index 000000000000..9f02f4d9413f--- /dev/null+++ b/frontend/src/lib/components/Search/searchListsLogic.tsx@@ -0,0 +1,679 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { router } from 'kea-router'++import { IconBell, IconClock, IconDownload, IconLeave, IconNotification, IconTerminal } from '@posthog/icons'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { preflightLogic } from 'lib/logic/preflightLogic'+import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'+import { newInternalTab } from 'lib/utils/newInternalTab'+import { toSentenceCase } from 'lib/utils/strings'+import { billingLogic } from 'scenes/billing/billingLogic'+import { organizationIntegrationsLogic } from 'scenes/settings/organization/organizationIntegrationsLogic'+import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import { getDefaultTreePersons } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'+import { recentItemsModel } from '~/models/recentItemsModel'+import { getTreeItemsMetadata, getTreeItemsNew, getTreeItemsProducts } from '~/products'+import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'+import { matchesFlagDefinition } from '~/scenes/settings/flagGating'+import { getTitleText } from '~/scenes/settings/settingsSearch'+import { Setting, SettingSection, SettingSectionId } from '~/scenes/settings/types'+import { ActivityTab, IntegrationType, UserType } from '~/types'++import { SearchItem, fileSystemEntryToSearchItem } from './searchItems'++const isEnabledByFlag = (flag: string | undefined, featureFlags: FeatureFlagsSet): boolean =>+ !flag || !!(featureFlags as Record<string, boolean>)[flag]++const displayNameOf = (item: SearchItem): string => item.displayName || item.name++const toSearchTabItems = (+ parents: SearchItem[],+ sources: FileSystemImport[],+ featureFlags: FeatureFlagsSet+): SearchItem[] => {+ const tabsByPath = new Map(sources.map((source) => [source.path, source.searchTabs ?? []]))+ return parents.flatMap((parent) =>+ (tabsByPath.get(parent.name) ?? [])+ .filter((tab) => isEnabledByFlag(tab.flag, featureFlags))+ .map((tab) => ({+ id: `${parent.id}-tab-${tab.name}`,+ name: `${displayNameOf(parent)} ${tab.name}`,+ displayName: tab.name,+ category: parent.category,+ parentName: displayNameOf(parent),+ href: tab.href,+ itemType: parent.itemType,+ searchKeywords: tab.searchKeywords,+ disabledReason: parent.disabledReason,+ record: parent.record,+ }))+ )+}++/** Most recently viewed first. Items never viewed go last, by name. */+const byLastViewed = (a: SearchItem, b: SearchItem): number => {+ if (!a.lastViewedAt && !b.lastViewedAt) {+ return a.name.localeCompare(b.name)+ }+ if (!a.lastViewedAt) {+ return 1+ }+ if (!b.lastViewedAt) {+ return -1+ }+ return new Date(b.lastViewedAt).getTime() - new Date(a.lastViewedAt).getTime()+}++/** Max starred shortcuts shown in quick search (folders excluded). */+export const STARRED_LIMIT = 20++/**+ * Lean projection of SETTINGS_MAP for search. The full map statically imports every+ * settings component (the whole configuration UI graph), so it is loaded dynamically+ * on mount and only the searchable metadata is kept.+ */+export interface SettingsSectionSummary {+ id: SettingSection['id']+ level: SettingSection['level']+ titleString: string | null+ hideFromNavigation?: boolean+ flag?: SettingSection['flag']+ to?: string+ keywords?: string[]+ settings: {+ id: string+ hasTitle: boolean+ titleString: string | null+ descriptionString: string | null+ keywords?: string[]+ flag?: SettingSection['flag']+ }[]+}++export interface SearchListsLogicProps {+ /** The command palette runs `onSelect` items, so it gets rows other search surfaces cannot use. */+ commandPalette: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface searchListsLogicValues {+ billingEntryUrl: string | null // billingLogic+ featureFlags: FeatureFlagsSet // featureFlagLogic+ organizationIntegrations: IntegrationType[] | null // organizationIntegrationsLogic+ isDev: boolean | undefined // preflightLogic+ cachedStarred: FileSystemEntry[] // projectTreeDataLogic+ treeGroupItems: FileSystemImport[] // projectTreeDataLogic+ sceneLogViewsByRef: Record<string, string> // recentItemsModel+ user: UserType | null // userLogic+ dataManagementItems: SearchItem[]+ healthItems: SearchItem[]+ miscItems: SearchItem[]+ newItems: SearchItem[]+ peopleItems: SearchItem[]+ productsItems: SearchItem[]+ settingsItems: SearchItem[]+ settingsSections: SettingsSectionSummary[]+ starredItems: SearchItem[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface searchListsLogicActions {+ toggleTerminal: () => {+ value: true+ } // terminalDockLogic+ setSettingsSections: (sections: SettingsSectionSummary[]) => {+ sections: SettingsSectionSummary[]+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface searchListsLogicMeta {+ key: 'command-palette' | 'page'+ __keaTypeGenInternalSelectorTypes: {+ starredItems: (cachedStarred: FileSystemEntry[]) => SearchItem[]+ productsItems: (+ featureFlags: FeatureFlagsSet,+ isDev: boolean | undefined,+ user: UserType | null,+ sceneLogViewsByRef: Record<string, string>+ ) => SearchItem[]+ dataManagementItems: (+ featureFlags: FeatureFlagsSet,+ isDev: boolean | undefined,+ user: UserType | null,+ sceneLogViewsByRef: Record<string, string>+ ) => SearchItem[]+ newItems: (+ featureFlags: FeatureFlagsSet,+ isDev: boolean | undefined,+ user: UserType | null,+ arg: boolean+ ) => SearchItem[]+ peopleItems: (treeGroupItems: FileSystemImport[], sceneLogViewsByRef: Record<string, string>) => SearchItem[]+ healthItems: (sceneLogViewsByRef: Record<string, string>) => SearchItem[]+ miscItems: (+ sceneLogViewsByRef: Record<string, string>,+ featureFlags: FeatureFlagsSet,+ arg: boolean+ ) => SearchItem[]+ settingsItems: (+ featureFlags: FeatureFlagsSet,+ organizationIntegrations: IntegrationType[] | null,+ settingsSections: SettingsSectionSummary[],+ billingEntryUrl: string | null+ ) => SearchItem[]+ }+}++export type searchListsLogicType = MakeLogicType<+ searchListsLogicValues,+ searchListsLogicActions,+ SearchListsLogicProps,+ searchListsLogicMeta+>++/**+ * The search lists that need no request: products, starred items, settings, and the other fixed+ * destinations. Both the current palette and Command K search filter these in memory.+ */+export const searchListsLogic = kea<searchListsLogicType>([+ props({} as SearchListsLogicProps),+ key((props) => (props.commandPalette ? 'command-palette' : 'page')),+ path((key) => ['lib', 'components', 'Search', 'searchListsLogic', key]),+ connect(() => ({+ // Keeps the terminal dock mounted for the "Toggle terminal" row's onSelect.+ actions: [terminalDockLogic, ['toggleTerminal']],+ values: [+ featureFlagLogic,+ ['featureFlags'],+ preflightLogic,+ ['isDev'],+ userLogic,+ ['user'],+ recentItemsModel,+ ['sceneLogViewsByRef'],+ projectTreeDataLogic,+ ['shortcutData as cachedStarred', 'groupItems as treeGroupItems'],+ organizationIntegrationsLogic,+ ['organizationIntegrations'],+ billingLogic,+ ['billingEntryUrl'],+ ],+ })),+ actions({+ setSettingsSections: (sections: SettingsSectionSummary[]) => ({ sections }),+ }),+ reducers({+ settingsSections: [+ [] as SettingsSectionSummary[],+ {+ setSettingsSections: (_, { sections }) => sections,+ },+ ],+ }),+ selectors({+ starredItems: [+ (s) => [s.cachedStarred],+ (cachedStarred: FileSystemEntry[]): SearchItem[] => {+ return cachedStarred+ .filter((e) => e.type !== 'folder')+ .slice(0, STARRED_LIMIT)+ .map((item) =>+ fileSystemEntryToSearchItem(item, {+ id: `starred-${item.id}`,+ category: 'starred',+ searchKeywords: ['starred', 'favorite', 'favourite', 'shortcut'],+ })+ )+ },+ ],+ productsItems: [+ (s) => [s.featureFlags, s.isDev, s.user, s.sceneLogViewsByRef],+ (+ featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,+ isDev: boolean | undefined,+ user: null | import('~/types').UserType,+ sceneLogViewsByRef: Record<string, string>+ ): SearchItem[] => {+ const allProducts = getTreeItemsProducts()+ const filteredProducts = allProducts.filter((product) => {+ if (!product.href) {+ return false+ }+ if (!isDev && !user?.is_staff && product.category === 'Unreleased') {+ return false+ }+ if (!isEnabledByFlag(product.flag, featureFlags)) {+ return false+ }+ return true+ })++ const items: SearchItem[] = filteredProducts.map((product) => ({+ id: `product-${product.path}`,+ name: product.path,+ displayName: product.displayLabel ?? product.path,+ category: 'tools',+ productCategory: product.category || null,+ href: product.href || PLACEHOLDER_HREF,+ itemType: product.iconType || product.type || null,+ searchKeywords: product.searchKeywords,+ lastViewedAt: product.sceneKey ? (sceneLogViewsByRef[product.sceneKey] ?? null) : null,+ disabledReason: getProductAccessDisabledReason(product),+ record: {+ type: product.type || product.iconType,+ iconType: product.iconType,+ iconColor: product.iconColor,+ },+ }))+ items.push({+ id: 'product-activity',+ name: 'Activity',+ displayName: 'Activity',+ category: 'tools',+ productCategory: null,+ href: urls.activity(ActivityTab.ExploreEvents),+ icon: <IconClock />,+ itemType: null,+ lastViewedAt: sceneLogViewsByRef['Activity'] ?? null,+ record: {+ type: 'activity',+ iconType: undefined,+ iconColor: undefined,+ },+ })+ items.push(...toSearchTabItems(items, filteredProducts, featureFlags))++ return items.sort(byLastViewed)+ },+ ],+ dataManagementItems: [+ (s) => [s.featureFlags, s.isDev, s.user, s.sceneLogViewsByRef],+ (+ featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,+ isDev: boolean | undefined,+ user: null | import('~/types').UserType,+ sceneLogViewsByRef: Record<string, string>+ ): SearchItem[] => {+ const allMetadata = getTreeItemsMetadata()+ const filteredMetadata = allMetadata.filter((item) => {+ if (!isDev && !user?.is_staff && item.category === 'Unreleased') {+ return false+ }+ if (!isEnabledByFlag(item.flag, featureFlags)) {+ return false+ }+ return true+ })++ const categorySearchKeywords: Record<string, string[]> = {+ CDP: ['data pipelines', 'data pipeline', 'pipeline'],+ }++ const items: SearchItem[] = filteredMetadata.map((item) => ({+ id: `data-management-${item.path}`,+ name: item.path,+ displayName: item.path,+ category: 'data-management',+ productCategory: item.category || null,+ href: item.href || PLACEHOLDER_HREF,+ itemType: item.iconType || item.type || null,+ searchKeywords: [+ ...(item.category ? (categorySearchKeywords[item.category] ?? []) : []),+ ...(item.searchKeywords ?? []),+ ],+ lastViewedAt: item.sceneKey ? (sceneLogViewsByRef[item.sceneKey] ?? null) : null,+ disabledReason: getProductAccessDisabledReason(item),+ record: {+ type: item.type || item.iconType,+ iconType: item.iconType,+ iconColor: item.iconColor,+ },+ }))++ items.push(...toSearchTabItems(items, filteredMetadata, featureFlags))++ return items.sort(byLastViewed)+ },+ ],+ newItems: [+ (s) => [s.featureFlags, s.isDev, s.user, (_, props: SearchListsLogicProps) => props.commandPalette],+ (+ featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,+ isDev: boolean | undefined,+ user: null | import('~/types').UserType,+ commandPalette: boolean+ ): SearchItem[] => {+ const allNewItems = getTreeItemsNew()+ const filteredItems = allNewItems.filter((item) => {+ if (!isDev && !user?.is_staff && item.category === 'Unreleased') {+ return false+ }+ if (!isEnabledByFlag(item.flag, featureFlags)) {+ return false+ }+ return true+ })++ const items: SearchItem[] = filteredItems.map((item) => {+ // Format display name:+ // "Insight/Lifecycle" -> "New Lifecycle insight"+ // "Data/Destination" -> "New Destination" (no suffix for Data)+ const pathParts = item.path.split('/')+ let displayName: string+ if (pathParts.length > 1) {+ const suffix = pathParts[0].toLowerCase()+ // Don't append "data" suffix for data pipeline items+ displayName =+ suffix === 'data'+ ? `New ${pathParts.slice(1).join(' ')}`+ : `New ${pathParts.slice(1).join(' ')} ${suffix}`+ } else {+ displayName = `New ${item.path}`+ }++ return {+ id: `new-${item.path}`,+ name: displayName,+ displayName,+ category: 'create',+ productCategory: item.category || null,+ href: item.href || PLACEHOLDER_HREF,+ itemType: item.iconType || item.type || null,+ hiddenSearchText: [displayName, item.path, item.type, item.iconType].filter(Boolean).join(' '),+ record: {+ type: item.type || item.iconType,+ iconType: item.iconType,+ iconColor: item.iconColor,+ },+ }+ })++ // Blank SQL query in a new browser tab (inheriting the active warehouse connection when+ // triggered from within the SQL editor). Scoped to the command palette: it relies on+ // onSelect + newInternalTab, and only the 'command' Search surface honors onSelect —+ // the new-tab scene and AI-first homepage are href-only and would render a dead item.+ if (commandPalette) {+ items.push({+ id: 'new-sql-query-tab',+ name: 'New SQL query',+ displayName: 'New SQL query',+ category: 'create',+ productCategory: null,+ itemType: 'insight/hog',+ searchKeywords: ['sql', 'hogql', 'query', 'blank sql', 'new tab'],+ record: { type: 'insight', iconType: 'insight/hog' },+ onSelect: () => {+ const onSqlEditor =+ removeProjectIdIfPresent(router.values.location.pathname) === urls.sqlEditor()+ const connectionId = onSqlEditor ? router.values.hashParams?.c : undefined+ newInternalTab(urls.sqlEditor(connectionId ? { connectionId } : {}))+ },+ })+ }++ return items+ },+ ],+ peopleItems: [+ (s) => [s.treeGroupItems, s.sceneLogViewsByRef],+ (+ treeGroupItems: import('~/queries/schema/schema-general').FileSystemImport[],+ sceneLogViewsByRef: Record<string, string>+ ): SearchItem[] => {+ const combined = [...getDefaultTreePersons(), ...treeGroupItems]+ return combined.map((item) => ({+ id: `people-${item.path}`,+ name: item.path,+ displayName: item.path,+ category: 'people',+ productCategory: item.category || null,+ href: item.href || PLACEHOLDER_HREF,+ itemType: item.iconType || item.type || null,+ lastViewedAt: item.sceneKey ? (sceneLogViewsByRef[item.sceneKey] ?? null) : null,+ record: {+ type: item.type || item.iconType,+ iconType: item.iconType,+ iconColor: item.iconColor,+ },+ }))+ },+ ],+ healthItems: [+ (s) => [s.sceneLogViewsByRef],+ (sceneLogViewsByRef: Record<string, string>): SearchItem[] => [+ {+ id: 'health-pipeline-status',+ name: 'Pipeline status',+ displayName: 'Pipeline status',+ category: 'health',+ href: urls.pipelineStatus(),+ itemType: 'pipeline_status',+ lastViewedAt: sceneLogViewsByRef['PipelineStatus'] ?? null,+ record: { type: 'pipeline_status', iconType: 'pipeline_status' },+ },+ {+ id: 'health-sdk-health',+ name: 'SDK health',+ displayName: 'SDK health',+ category: 'health',+ href: urls.sdkHealth(),+ itemType: 'sdk_health',+ lastViewedAt: sceneLogViewsByRef['SdkHealth'] ?? null,+ record: { type: 'sdk_health', iconType: 'sdk_health' },+ },+ ],+ ],+ miscItems: [+ (s) => [s.sceneLogViewsByRef, s.featureFlags, (_, props: SearchListsLogicProps) => props.commandPalette],+ (+ sceneLogViewsByRef: Record<string, string>,+ featureFlags: FeatureFlagsSet,+ commandPalette: boolean+ ): SearchItem[] => [+ ...(commandPalette && featureFlags[FEATURE_FLAGS.POSTHOG_TERMINAL]+ ? [+ {+ id: 'misc-toggle-terminal',+ name: 'Toggle terminal',+ displayName: 'Toggle terminal',+ category: 'misc',+ icon: <IconTerminal />,+ itemType: null,+ searchKeywords: ['terminal', 'shell', 'console'],+ onSelect: () => terminalDockLogic.actions.toggleTerminal(),+ record: { type: 'terminal' },+ },+ ]+ : []),+ {+ id: 'misc-exports',+ name: 'Exports',+ displayName: 'Exports',+ category: 'misc',+ href: urls.exports(),+ icon: <IconDownload />,+ itemType: null,+ lastViewedAt: sceneLogViewsByRef['Exports'] ?? null,+ record: { type: 'exports' },+ },+ {+ id: 'misc-alerts',+ name: 'Alerts',+ displayName: 'Alerts',+ category: 'misc',+ href: urls.alerts(),+ icon: <IconBell />,+ itemType: null,+ lastViewedAt: sceneLogViewsByRef['SavedInsights'] ?? null,+ record: { type: 'alerts' },+ },+ {+ id: 'misc-subscriptions',+ name: 'Subscriptions',+ displayName: 'Subscriptions',+ category: 'misc',+ href: urls.subscriptions(),+ icon: <IconNotification />,+ itemType: null,+ lastViewedAt: sceneLogViewsByRef['Subscriptions'] ?? null,+ record: { type: 'subscriptions' },+ },+ {+ id: 'misc-logout',+ name: 'Log out',+ displayName: 'Log out',+ category: 'misc',+ icon: <IconLeave />,+ itemType: null,+ searchKeywords: ['logout', 'log out', 'sign out', 'signout', 'exit'],+ onSelect: () => userLogic.actions.logout(),+ record: { type: 'logout' },+ },+ ],+ ],+ settingsItems: [+ (s) => [s.featureFlags, s.organizationIntegrations, s.settingsSections, s.billingEntryUrl],+ (+ featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,+ organizationIntegrations: import('~/types').IntegrationType[] | null,+ settingsSections: SettingsSectionSummary[],+ billingEntryUrl: string | null+ ): SearchItem[] => {+ const checkFlag = (flagKey: Pick<Setting, 'flag'>['flag']): boolean =>+ matchesFlagDefinition(flagKey, featureFlags)++ const items: SearchItem[] = []++ // Skip project-level sections as they are duplicates of environment sections+ const seenSectionIds = new Set<string>()++ for (const section of settingsSections) {+ // Skip sections hidden from navigation (they are only accessible+ // from their product's own configuration page)+ if (section.hideFromNavigation) {+ continue+ }++ // Mirror sidebar gating: only surface organization integrations when any exist+ if (+ section.id === 'organization-integrations' &&+ (!organizationIntegrations || organizationIntegrations.length === 0)+ ) {+ continue+ }++ // Mirror the sidebar's billing gate. billingEntryUrl is null when the user has no+ // billing access, and for view-only members it points at Usage, which keeps them+ // off the admin-only Overview and the restricted state it renders first.+ let billingHref: string | null = null+ if (section.id === 'organization-billing') {+ if (!billingEntryUrl) {+ continue+ }+ billingHref = billingEntryUrl+ }++ // Map environment sections to project level+ const effectiveLevel = section.level === 'environment' ? 'project' : section.level+ const effectiveSectionId = (+ section.level === 'environment' ? section.id.replace('environment-', 'project-') : section.id+ ) as SettingSectionId++ // Filter by feature flag if required+ if (section.flag) {+ if (!checkFlag(section.flag as Pick<Setting, 'flag'>['flag'])) {+ continue+ }+ }++ // Skip duplicate project sections (environment sections take priority)+ if (seenSectionIds.has(effectiveSectionId)) {+ continue+ }+ seenSectionIds.add(effectiveSectionId)++ // Create a search item for each settings section+ const levelPrefix = toSentenceCase(effectiveLevel)++ const searchTerms = [+ ...(section.keywords ?? []),+ ...section.settings+ .filter((setting) => setting.hasTitle && checkFlag(setting.flag))+ .flatMap((setting) => [+ toSentenceCase(setting.id.replace(/[-]/g, ' ')),+ ...(setting.titleString ? [setting.titleString] : []),+ ...(setting.descriptionString ? [setting.descriptionString] : []),+ ...(setting.keywords ?? []),+ ]),+ ]++ // Create the display name for each settings section+ const displayName = section.titleString ?? toSentenceCase(section.id.replace(/[-]/g, ' '))++ const displayNameSuffix =+ displayName === 'General' || displayName === 'Danger zone' || displayName === 'Integrations'+ ? ` (${toSentenceCase(effectiveLevel)})`+ : ''++ items.push({+ id: `settings-${effectiveSectionId}`,+ name: `${levelPrefix}: ${displayName} (${searchTerms})`,+ displayName: `${displayName}${displayNameSuffix}`,+ category: 'settings',+ href: billingHref || section.to || urls.settings(effectiveSectionId),+ itemType: 'settings',+ record: {+ type: 'settings',+ level: effectiveLevel,+ sectionId: effectiveSectionId,+ },+ })+ }++ return items+ },+ ],+ }),+ afterMount(({ actions }) => {+ import('~/scenes/settings/SettingsMap')+ .then(({ SETTINGS_MAP }) => {+ actions.setSettingsSections(+ SETTINGS_MAP.map((section) => ({+ id: section.id,+ level: section.level,+ titleString: getTitleText(section.title) || null,+ hideFromNavigation: section.hideFromNavigation,+ flag: section.flag,+ to: section.to,+ keywords: section.keywords,+ settings: section.settings.map((setting) => ({+ id: setting.id,+ // A setting can render a title that getTitleText cannot read, such as a+ // whole component, and it must stay findable via its id token.+ // hasTitle preserves that distinction.+ hasTitle: !!setting.title,+ titleString: getTitleText(setting.title) || null,+ descriptionString:+ setting.searchDescription ??+ (typeof setting.description === 'string' ? setting.description : null),+ keywords: setting.keywords,+ flag: setting.flag,+ })),+ }))+ )+ })+ .catch((error) => {+ console.error('Failed to load SETTINGS_MAP for settings search:', error)+ })+ }),+])diff --git a/frontend/src/lib/components/Search/searchLogic.test.ts b/frontend/src/lib/components/Search/searchLogic.test.tsindex 97d23090a397..f9f3d57d870b 100644--- a/frontend/src/lib/components/Search/searchLogic.test.ts+++ b/frontend/src/lib/components/Search/searchLogic.test.ts@@ -3,7 +3,6 @@ import { expectLogic } from 'kea-test-utils'import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'@@ -67,76 +66,6 @@ describe('searchLogic', () => {jest.restoreAllMocks()})- it.each([false, true])('gates the command-menu terminal toggle when enabled=%s', (enabled) => {- logic.unmount()- logic = searchLogic({ logicKey: 'command' })- logic.mount()- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: enabled })-- const toggle = logic.values.miscItems.find((item) => item.id === 'misc-toggle-terminal')- expect(!!toggle).toBe(enabled)- expect(terminalDockLogic.values.dockOpen).toBe(false)- if (toggle) {- toggle.onSelect?.()- expect(terminalDockLogic.values.dockOpen).toBe(true)- toggle.onSelect?.()- expect(terminalDockLogic.values.dockOpen).toBe(false)- toggle.onSelect?.()- featureFlagLogic.actions.setFeatureFlags([], {})- expect(terminalDockLogic.values.dockOpen).toBe(false)- expect(logic.values.miscItems.some((item) => item.id === 'misc-toggle-terminal')).toBe(false)- }- featureFlagLogic.actions.setFeatureFlags([], {})- terminalDockLogic.actions.toggleTerminal()- expect(terminalDockLogic.values.dockOpen).toBe(false)- })-- it.each([- ['off', false, 'Model preferences', false],- ['on', true, 'Agent preferences', true],- ])(- 'shows one copy of a section gated on a flag and its negation, with the flag %s',- (_state, flagOn, expectedName, expectsGatedKeyword) => {- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TODAY_RAIL_NAV]: flagOn })- const settings = [- {- id: 'task-agent-my-preference',- hasTitle: true,- titleString: 'My default model',- descriptionString: null,- },- {- id: 'task-comments-slack-dm',- hasTitle: true,- titleString: 'Gated setting',- descriptionString: null,- keywords: ['zebra'],- flag: 'TODAY_RAIL_NAV' as const,- },- ]- logic.actions.setSettingsSections([- {- id: 'environment-task-agents',- level: 'environment',- titleString: 'Agent preferences',- flag: 'TODAY_RAIL_NAV',- settings,- },- {- id: 'environment-task-agents',- level: 'environment',- titleString: 'Model preferences',- flag: '!TODAY_RAIL_NAV',- settings,- },- ])-- const items = logic.values.settingsItems.filter((item) => item.id === 'settings-project-task-agents')- expect(items.map((item) => item.displayName)).toEqual([expectedName])- expect(items[0].name.includes('zebra')).toBe(expectsGatedKeyword)- }- )-it('aborts and cancels the in-flight person search when the term is cleared', async () => {neverResolvingPersonSearch()diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsxindex a43d30d4dbba..9c7b25b3922c 100644--- a/frontend/src/lib/components/Search/searchLogic.tsx+++ b/frontend/src/lib/components/Search/searchLogic.tsx@@ -1,48 +1,22 @@-import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import type { BreakPointFunction } from 'kea'import { loaders } from 'kea-loaders'-import { router } from 'kea-router'--import {- IconBell,- IconBuilding,- IconClock,- IconDownload,- IconLeave,- IconNotification,- IconTerminal,-} from '@posthog/icons'import api, { isAbortError } from 'lib/api'-import { commandLogic } from 'lib/components/Command/commandLogic'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { preflightLogic } from 'lib/logic/preflightLogic'-import { getEntryAccessDisabledReason, getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'+import { getEntryAccessDisabledReason } from 'lib/utils/accessControlUtils'import { uuid } from 'lib/utils/dom'import { GroupQueryResult, mapGroupQueryResponse } from 'lib/utils/groups'-import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'-import { newInternalTab } from 'lib/utils/newInternalTab'-import { capitalizeFirstLetter, toSentenceCase } from 'lib/utils/strings'-import { billingLogic } from 'scenes/billing/billingLogic'-import { organizationIntegrationsLogic } from 'scenes/settings/organization/organizationIntegrationsLogic'import { teamLogic } from 'scenes/teamLogic'-import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'-import { urls } from 'scenes/urls'-import { userLogic } from 'scenes/userLogic'-import { getDefaultTreePersons } from '~/layout/panel-layout/ProjectTree/defaultTree'import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'import { splitPath, unescapePath } from '~/layout/panel-layout/ProjectTree/utils'import { groupsModel } from '~/models/groupsModel'import { recentItemsModel } from '~/models/recentItemsModel'-import { getTreeItemsMetadata, getTreeItemsNew, getTreeItemsProducts } from '~/products'import { FileSystemEntry, GroupsQueryResponse } from '~/queries/schema/schema-general'-import { matchesFlagDefinition } from '~/scenes/settings/flagGating'-import { getTitleText } from '~/scenes/settings/settingsSearch'-import { Setting, SettingSection, SettingSectionId } from '~/scenes/settings/types'-import { ActivityTab, FileSystemIconColor, GroupTypeIndex, PersonType, SearchResponse } from '~/types'+import { GroupTypeIndex, PersonType, SearchResponse } from '~/types'import { conversationsTicketsList } from 'products/conversations/frontend/generated/api'import type { TicketApi } from 'products/conversations/frontend/generated/api.schemas'@@ -50,132 +24,21 @@ import { accountsList } from 'products/customer_analytics/frontend/generated/apiimport type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'import type { Noun } from '../../../models/groupsModel'-import type { FileSystemImport } from '../../../queries/schema/schema-general'-import type { GroupType, IntegrationType, UserType } from '../../../types'+import type { GroupType } from '../../../types'import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'+import {+ SearchItem,+ accountToSearchItem,+ fileSystemEntryToSearchItem,+ filterNewItems,+ groupToSearchItem,+ personToSearchItem,+ ticketToSearchItem,+ unifiedSearchResultToSearchItem,+} from './searchItems'+import { searchListsLogic } from './searchListsLogic'import { filterSearchItems, shouldSearchTickets } from './utils'-let cachedProductIconColorByType: Map<string, FileSystemIconColor> | null = null-let cachedProductDisplayLabelByPath: Map<string, string> | null = null-let cachedProductIconTypeByPath: Map<string, string> | null = null--const getProductIconColorByType = (): Map<string, FileSystemIconColor> => {- if (cachedProductIconColorByType === null) {- cachedProductIconColorByType = new Map()- for (const product of getTreeItemsProducts()) {- const key = product.type || product.iconType- if (key && product.iconColor) {- cachedProductIconColorByType.set(key, product.iconColor)- }- }- }- return cachedProductIconColorByType-}--const getProductDisplayLabelByPath = (): Map<string, string> => {- if (cachedProductDisplayLabelByPath === null) {- cachedProductDisplayLabelByPath = new Map()- for (const product of getTreeItemsProducts()) {- if (product.displayLabel) {- cachedProductDisplayLabelByPath.set(product.path, product.displayLabel)- }- }- }- return cachedProductDisplayLabelByPath-}--const getProductIconTypeByPath = (): Map<string, string> => {- if (cachedProductIconTypeByPath === null) {- cachedProductIconTypeByPath = new Map()- for (const product of getTreeItemsProducts()) {- const iconType = product.type || product.iconType- if (iconType) {- cachedProductIconTypeByPath.set(product.path, iconType)- }- }- }- return cachedProductIconTypeByPath-}--const fileSystemEntryToSearchItem = (- item: FileSystemEntry,- overrides: { id: string; category: string; searchKeywords?: string[] }-): SearchItem => {- const name = splitPath(item.path).pop()- const itemName = name ? unescapePath(name) : item.path- const displayName = getProductDisplayLabelByPath().get(itemName)- // Older starred shortcuts (e.g. Logs, Web analytics) were saved with a blank (empty-string)- // type because their product only defines `iconType`. The `||` (not `??`) is deliberate: an- // empty string must fall through to the product registry, keyed by name, so the icon resolves.- const itemType = item.type || getProductIconTypeByPath().get(itemName) || null- const productIconColor = itemType ? getProductIconColorByType().get(itemType) : undefined- return {- name: itemName,- displayName,- href: item.href || PLACEHOLDER_HREF,- lastViewedAt: item.last_viewed_at ?? null,- itemType,- record: { ...item, iconColor: productIconColor },- disabledReason: getEntryAccessDisabledReason(item),- ...overrides,- }-}--const isEnabledByFlag = (flag: string | undefined, featureFlags: FeatureFlagsSet): boolean =>- !flag || !!(featureFlags as Record<string, boolean>)[flag]--const displayNameOf = (item: SearchItem): string => item.displayName || item.name--const toSearchTabItems = (- parents: SearchItem[],- sources: FileSystemImport[],- featureFlags: FeatureFlagsSet-): SearchItem[] => {- const tabsByPath = new Map(sources.map((source) => [source.path, source.searchTabs ?? []]))- return parents.flatMap((parent) =>- (tabsByPath.get(parent.name) ?? [])- .filter((tab) => isEnabledByFlag(tab.flag, featureFlags))- .map((tab) => ({- id: `${parent.id}-tab-${tab.name}`,- name: `${displayNameOf(parent)} ${tab.name}`,- displayName: tab.name,- category: parent.category,- parentName: displayNameOf(parent),- href: tab.href,- itemType: parent.itemType,- searchKeywords: tab.searchKeywords,- disabledReason: parent.disabledReason,- record: parent.record,- }))- )-}--// Types for command search results-export interface SearchItem {- id: string- name: string- displayName?: string- category: string- productCategory?: string | null- href?: string- /** Action invoked when the item is selected. Use for items that trigger something- * other than navigation (e.g. logging out). Consumers should prefer `onSelect` over `href`. */- onSelect?: () => void- icon?: React.ReactNode- lastViewedAt?: string | null- groupNoun?: string | null- itemType?: string | null- searchKeywords?: string[]- hiddenSearchText?: string- matchedSearchKeyword?: string | null- parentName?: string- record?: Record<string, unknown>- rank?: number | null // PostgreSQL full-text search rank (from unified search API)- /** 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?: string-}-export interface SearchCategory {key: stringitems: SearchItem[]@@ -187,13 +50,7 @@ export interface SearchLogicProps {}export const RECENTS_LIMIT = 5-/** Max starred shortcuts shown in quick search (folders excluded). */-export const STARRED_LIMIT = 20const SEARCH_LIMIT = 5-const LEADING_CREATE_WORD = /^\s*create\b/i--/** Safely extract a string — returns undefined for objects/arrays to avoid rendering [object Object]. */-const safeString = (val: unknown): string | undefined => (typeof val === 'string' ? val : undefined)/*** Re-throw a search error, first handing a run we aborted over to whatever superseded it. A@@ -208,47 +65,24 @@ const rethrowSearchError = (error: unknown, breakpoint: BreakPointFunction): nevthrow error}-/**- * Lean projection of SETTINGS_MAP for search. The full map statically imports every- * settings component (the whole configuration UI graph), so it is loaded dynamically- * on mount and only the searchable metadata is kept.- */-export interface SettingsSectionSummary {- id: SettingSection['id']- level: SettingSection['level']- titleString: string | null- hideFromNavigation?: boolean- flag?: SettingSection['flag']- to?: string- keywords?: string[]- settings: {- id: string- hasTitle: boolean- titleString: string | null- descriptionString: string | null- keywords?: string[]- flag?: SettingSection['flag']- }[]-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface searchLogicValues {- billingEntryUrl: string | null // billingLogic- isCommandOpen: boolean // commandLogicfeatureFlags: FeatureFlagsSet // featureFlagLogicaggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModelgroupTypes: Map<GroupTypeIndex, GroupType> // groupsModel- organizationIntegrations: IntegrationType[] | null // organizationIntegrationsLogic- isDev: boolean | undefined // preflightLogic- cachedStarred: FileSystemEntry[] // projectTreeDataLogicshortcutDataHasLoaded: boolean // projectTreeDataLogic- treeGroupItems: FileSystemImport[] // projectTreeDataLogiccachedRecents: FileSystemEntry[] // recentItemsModelrecentsHasLoaded: boolean // recentItemsModel- sceneLogViewsByRef: Record<string, string> // recentItemsModelsceneLogViewsHasLoaded: boolean // recentItemsModel+ dataManagementItems: SearchItem[] // searchListsLogic+ healthItems: SearchItem[] // searchListsLogic+ miscItems: SearchItem[] // searchListsLogic+ newItems: SearchItem[] // searchListsLogic+ peopleItems: SearchItem[] // searchListsLogic+ productsItems: SearchItem[] // searchListsLogic+ settingsItems: SearchItem[] // searchListsLogic+ starredItems: SearchItem[] // searchListsLogiccurrentTeamId: number | null // teamLogic- user: UserType | null // userLogicaccountItems: SearchItem[]accountSearchResults: AccountApi[]accountSearchResultsLoading: boolean@@ -257,11 +91,9 @@ export interface searchLogicValues {accountItems: SearchItem[]ticketItems: SearchItem[]}- dataManagementItems: SearchItem[]groupItems: SearchItem[]groupSearchResults: Partial<Record<GroupTypeIndex, GroupQueryResult[]>>groupSearchResultsLoading: boolean- healthItems: SearchItem[]isSearching: booleanloadingStates: {accountSearchResultsLoading: boolean@@ -276,24 +108,17 @@ export interface searchLogicValues {ticketSearchResultsLoading: booleanunifiedSearchResultsLoading: boolean}- miscItems: SearchItem[]- newItems: SearchItem[]- peopleItems: SearchItem[]personItems: SearchItem[]personSearchResults: PersonType[]personSearchResultsLoading: booleanplaylistItems: SearchItem[]playlistSearchResults: FileSystemEntry[]playlistSearchResultsLoading: boolean- productsItems: SearchItem[]recentItems: SearchItem[]search: stringsearchPending: booleansearchedRecents: FileSystemEntry[] | nullsearchedRecentsLoading: boolean- settingsItems: SearchItem[]- settingsSections: SettingsSectionSummary[]- starredItems: SearchItem[]ticketItems: SearchItem[]ticketSearchResults: TicketApi[]ticketSearchResultsLoading: boolean@@ -304,9 +129,6 @@ export interface searchLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface searchLogicActions {- toggleTerminal: () => {- value: true- } // terminalDockLogicloadAccountSearchResults: ({ searchTerm }: { searchTerm: string }) => {searchTerm: string}@@ -457,9 +279,6 @@ export interface searchLogicActions {setSearch: (search: string) => {search: string}- setSettingsSections: (sections: SettingsSectionSummary[]) => {- sections: SettingsSectionSummary[]- }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -482,26 +301,6 @@ export interface searchLogicMeta {cachedRecents: FileSystemEntry[],search: string) => SearchItem[]- starredItems: (cachedStarred: FileSystemEntry[]) => SearchItem[]- productsItems: (- featureFlags: FeatureFlagsSet,- isDev: boolean | undefined,- user: UserType | null,- sceneLogViewsByRef: Record<string, string>- ) => SearchItem[]- dataManagementItems: (- featureFlags: FeatureFlagsSet,- isDev: boolean | undefined,- user: UserType | null,- sceneLogViewsByRef: Record<string, string>- ) => SearchItem[]- newItems: (- featureFlags: FeatureFlagsSet,- isDev: boolean | undefined,- user: UserType | null,- arg: string- ) => SearchItem[]- peopleItems: (treeGroupItems: FileSystemImport[], sceneLogViewsByRef: Record<string, string>) => SearchItem[]groupItems: (groupSearchResults: Partial<Record<GroupTypeIndex, GroupQueryResult[]>>,aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel@@ -517,18 +316,6 @@ export interface searchLogicMeta {ticketItems: SearchItem[]}playlistItems: (playlistSearchResults: FileSystemEntry[]) => SearchItem[]- healthItems: (sceneLogViewsByRef: Record<string, string>) => SearchItem[]- miscItems: (- sceneLogViewsByRef: Record<string, string>,- featureFlags: FeatureFlagsSet,- arg: string- ) => SearchItem[]- settingsItems: (- featureFlags: FeatureFlagsSet,- organizationIntegrations: IntegrationType[] | null,- settingsSections: SettingsSectionSummary[],- billingEntryUrl: string | null- ) => SearchItem[]unifiedSearchItems: (unifiedSearchResults: SearchResponse | null) => Record<string, SearchItem[]>loadingStates: (unifiedSearchResultsLoading: boolean,@@ -595,34 +382,33 @@ export const searchLogic = kea<searchLogicType>([path((logicKey) => ['lib', 'components', 'Search', 'searchLogic', logicKey]),props({} as SearchLogicProps),key((props) => props.logicKey),- connect(() => ({- actions: [terminalDockLogic, ['toggleTerminal']],+ connect((props: SearchLogicProps) => ({values: [+ searchListsLogic({ commandPalette: props.logicKey === 'command' }),+ [+ 'starredItems',+ 'productsItems',+ 'dataManagementItems',+ 'newItems',+ 'peopleItems',+ 'healthItems',+ 'miscItems',+ 'settingsItems',+ ],groupsModel,['groupTypes', 'aggregationLabel'],- commandLogic,- ['isCommandOpen'],featureFlagLogic,['featureFlags'],- preflightLogic,- ['isDev'],- userLogic,- ['user'],teamLogic,['currentTeamId'],recentItemsModel,- ['recents as cachedRecents', 'recentsHasLoaded', 'sceneLogViewsByRef', 'sceneLogViewsHasLoaded'],+ ['recents as cachedRecents', 'recentsHasLoaded', 'sceneLogViewsHasLoaded'],projectTreeDataLogic,- ['shortcutData as cachedStarred', 'shortcutDataHasLoaded', 'groupItems as treeGroupItems'],- organizationIntegrationsLogic,- ['organizationIntegrations'],- billingLogic,- ['billingEntryUrl'],+ ['shortcutDataHasLoaded'],],})),actions({setSearch: (search: string) => ({ search }),- setSettingsSections: (sections: SettingsSectionSummary[]) => ({ sections }),}),loaders(({ values, cache }) => ({searchedRecents: [@@ -855,12 +641,6 @@ export const searchLogic = kea<searchLogicType>([loadUnifiedSearchResultsFailure: () => false,},],- settingsSections: [- [] as SettingsSectionSummary[],- {- setSettingsSections: (_, { sections }) => sections,- },- ],}),selectors({isSearching: [@@ -907,257 +687,6 @@ export const searchLogic = kea<searchLogicType>([return source.map((item) => fileSystemEntryToSearchItem(item, { id: item.path, category: 'recents' }))},],- starredItems: [- (s) => [s.cachedStarred],- (cachedStarred: FileSystemEntry[]): SearchItem[] => {- return cachedStarred- .filter((e) => e.type !== 'folder')- .slice(0, STARRED_LIMIT)- .map((item) =>- fileSystemEntryToSearchItem(item, {- id: `starred-${item.id}`,- category: 'starred',- searchKeywords: ['starred', 'favorite', 'favourite', 'shortcut'],- })- )- },- ],- productsItems: [- (s) => [s.featureFlags, s.isDev, s.user, s.sceneLogViewsByRef],- (- featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,- isDev: boolean | undefined,- user: null | import('~/types').UserType,- sceneLogViewsByRef: Record<string, string>- ): SearchItem[] => {- const allProducts = getTreeItemsProducts()- const filteredProducts = allProducts.filter((product) => {- if (!product.href) {- return false- }- if (!isDev && !user?.is_staff && product.category === 'Unreleased') {- return false- }- if (!isEnabledByFlag(product.flag, featureFlags)) {- return false- }- return true- })-- const items: SearchItem[] = filteredProducts.map((product) => ({- id: `product-${product.path}`,- name: product.path,- displayName: product.displayLabel ?? product.path,- category: 'tools',- productCategory: product.category || null,- href: product.href || PLACEHOLDER_HREF,- itemType: product.iconType || product.type || null,- searchKeywords: product.searchKeywords,- lastViewedAt: product.sceneKey ? (sceneLogViewsByRef[product.sceneKey] ?? null) : null,- disabledReason: getProductAccessDisabledReason(product),- record: {- type: product.type || product.iconType,- iconType: product.iconType,- iconColor: product.iconColor,- },- }))- items.push({- id: 'product-activity',- name: 'Activity',- displayName: 'Activity',- category: 'tools',- productCategory: null,- href: urls.activity(ActivityTab.ExploreEvents),- icon: <IconClock />,- itemType: null,- lastViewedAt: sceneLogViewsByRef['Activity'] ?? null,- record: {- type: 'activity',- iconType: undefined,- iconColor: undefined,- },- })- items.push(...toSearchTabItems(items, filteredProducts, featureFlags))-- // Sort by lastViewedAt (most recent first), items without lastViewedAt go to the end- return items.sort((a, b) => {- if (!a.lastViewedAt && !b.lastViewedAt) {- return a.name.localeCompare(b.name)- }- if (!a.lastViewedAt) {- return 1- }- if (!b.lastViewedAt) {- return -1- }- return new Date(b.lastViewedAt).getTime() - new Date(a.lastViewedAt).getTime()- })- },- ],- dataManagementItems: [- (s) => [s.featureFlags, s.isDev, s.user, s.sceneLogViewsByRef],- (- featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,- isDev: boolean | undefined,- user: null | import('~/types').UserType,- sceneLogViewsByRef: Record<string, string>- ): SearchItem[] => {- const allMetadata = getTreeItemsMetadata()- const filteredMetadata = allMetadata.filter((item) => {- if (!isDev && !user?.is_staff && item.category === 'Unreleased') {- return false- }- if (!isEnabledByFlag(item.flag, featureFlags)) {- return false- }- return true- })-- const categorySearchKeywords: Record<string, string[]> = {- CDP: ['data pipelines', 'data pipeline', 'pipeline'],- }-- const items: SearchItem[] = filteredMetadata.map((item) => ({- id: `data-management-${item.path}`,- name: item.path,- displayName: item.path,- category: 'data-management',- productCategory: item.category || null,- href: item.href || PLACEHOLDER_HREF,- itemType: item.iconType || item.type || null,- searchKeywords: [- ...(item.category ? (categorySearchKeywords[item.category] ?? []) : []),- ...(item.searchKeywords ?? []),- ],- lastViewedAt: item.sceneKey ? (sceneLogViewsByRef[item.sceneKey] ?? null) : null,- disabledReason: getProductAccessDisabledReason(item),- record: {- type: item.type || item.iconType,- iconType: item.iconType,- iconColor: item.iconColor,- },- }))-- items.push(...toSearchTabItems(items, filteredMetadata, featureFlags))-- // Sort by lastViewedAt (most recent first), items without lastViewedAt go to the end- return items.sort((a, b) => {- if (!a.lastViewedAt && !b.lastViewedAt) {- return a.name.localeCompare(b.name)- }- if (!a.lastViewedAt) {- return 1- }- if (!b.lastViewedAt) {- return -1- }- return new Date(b.lastViewedAt).getTime() - new Date(a.lastViewedAt).getTime()- })- },- ],- newItems: [- (s) => [s.featureFlags, s.isDev, s.user, (_, props: SearchLogicProps) => props.logicKey],- (- featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,- isDev: boolean | undefined,- user: null | import('~/types').UserType,- logicKey: string- ): SearchItem[] => {- const allNewItems = getTreeItemsNew()- const filteredItems = allNewItems.filter((item) => {- if (!isDev && !user?.is_staff && item.category === 'Unreleased') {- return false- }- if (!isEnabledByFlag(item.flag, featureFlags)) {- return false- }- return true- })-- const items: SearchItem[] = filteredItems.map((item) => {- // Format display name:- // "Insight/Lifecycle" -> "New Lifecycle insight"- // "Data/Destination" -> "New Destination" (no suffix for Data)- const pathParts = item.path.split('/')- let displayName: string- if (pathParts.length > 1) {- const suffix = pathParts[0].toLowerCase()- // Don't append "data" suffix for data pipeline items- displayName =- suffix === 'data'- ? `New ${pathParts.slice(1).join(' ')}`- : `New ${pathParts.slice(1).join(' ')} ${suffix}`- } else {- displayName = `New ${item.path}`- }-- return {- id: `new-${item.path}`,- name: displayName,- displayName,- category: 'create',- productCategory: item.category || null,- href: item.href || PLACEHOLDER_HREF,- itemType: item.iconType || item.type || null,- hiddenSearchText: [displayName, item.path, item.type, item.iconType].filter(Boolean).join(' '),- record: {- type: item.type || item.iconType,- iconType: item.iconType,- iconColor: item.iconColor,- },- }- })-- // Blank SQL query in a new browser tab (inheriting the active warehouse connection when- // triggered from within the SQL editor). Scoped to the command palette: it relies on- // onSelect + newInternalTab, and only the 'command' Search surface honors onSelect —- // the new-tab scene and AI-first homepage are href-only and would render a dead item.- if (logicKey === 'command') {- items.push({- id: 'new-sql-query-tab',- name: 'New SQL query',- displayName: 'New SQL query',- category: 'create',- productCategory: null,- itemType: 'insight/hog',- searchKeywords: ['sql', 'hogql', 'query', 'blank sql', 'new tab'],- record: { type: 'insight', iconType: 'insight/hog' },- onSelect: () => {- const onSqlEditor =- removeProjectIdIfPresent(router.values.location.pathname) === urls.sqlEditor()- const connectionId = onSqlEditor ? router.values.hashParams?.c : undefined- newInternalTab(urls.sqlEditor(connectionId ? { connectionId } : {}))- },- })- }-- return items- },- ],- peopleItems: [- (s) => [s.treeGroupItems, s.sceneLogViewsByRef],- (- treeGroupItems: import('~/queries/schema/schema-general').FileSystemImport[],- sceneLogViewsByRef: Record<string, string>- ): SearchItem[] => {- const combined = [...getDefaultTreePersons(), ...treeGroupItems]- return combined.map((item) => ({- id: `people-${item.path}`,- name: item.path,- displayName: item.path,- category: 'people',- productCategory: item.category || null,- href: item.href || PLACEHOLDER_HREF,- itemType: item.iconType || item.type || null,- lastViewedAt: item.sceneKey ? (sceneLogViewsByRef[item.sceneKey] ?? null) : null,- record: {- type: item.type || item.iconType,- iconType: item.iconType,- iconColor: item.iconColor,- },- }))- },- ],groupItems: [(s) => [s.groupSearchResults, s.aggregationLabel],(@@ -1171,24 +700,9 @@ export const searchLogic = kea<searchLogicType>([for (const [groupTypeIndexString, groups] of Object.entries(groupSearchResults)) {const groupTypeIndex = parseInt(groupTypeIndexString, 10) as GroupTypeIndexconst noun = aggregationLabel(groupTypeIndex).singular- ;(groups as GroupQueryResult[]).forEach((group) => {- const display = group.group_properties?.name || group.group_key || String(group.group_key)- items.push({- id: `group-${groupTypeIndex}-${group.group_key}`,- name: `${noun}: ${display}`,- displayName: display,- category: 'groups',- href: `/groups/${groupTypeIndex}/${encodeURIComponent(group.group_key)}`,- groupNoun: noun,- itemType: 'group',- record: {- type: 'group',- groupTypeIndex,- groupKey: group.group_key,- groupNoun: noun,- },- })- })+ for (const group of groups as GroupQueryResult[]) {+ items.push(groupToSearchItem(group, groupTypeIndex, noun))+ }}return items},@@ -1197,74 +711,17 @@ export const searchLogic = kea<searchLogicType>([(s) => [s.personSearchResults],(personSearchResults: PersonType[]): SearchItem[] => {return personSearchResults- .filter((person) => person.uuid) // Skip persons without uuid to avoid invalid URLs- .map((person) => {- const personId = person.distinct_ids?.[0] || person.uuid- const displayName =- safeString(person.properties?.email) ||- safeString(person.properties?.name) ||- String(personId)-- return {- id: `person-${person.uuid}`,- name: displayName,- displayName,- category: 'persons',- href: urls.personByUUID(person.uuid!),- itemType: 'person',- record: {- type: 'person',- uuid: person.uuid,- distinctIds: person.distinct_ids,- },- }- })+ .filter((person): person is PersonType & { uuid: string } => !!person.uuid) // Skip persons without uuid to avoid invalid URLs+ .map(personToSearchItem)},],accountItems: [(s) => [s.accountSearchResults],- (accountSearchResults: AccountApi[]): SearchItem[] => {- return accountSearchResults.map((account) => {- const displayName = account.name || account.external_id || account.id- return {- id: `account-${account.id}`,- name: displayName,- displayName,- category: 'accounts',- href: urls.customerAnalyticsAccount(account.id),- icon: <IconBuilding />,- itemType: 'account',- record: { type: 'account', id: account.id },- }- })- },+ (accountSearchResults: AccountApi[]): SearchItem[] => accountSearchResults.map(accountToSearchItem),],ticketItems: [(s) => [s.ticketSearchResults],- (ticketSearchResults: TicketApi[]): SearchItem[] => {- return ticketSearchResults.map((ticket) => {- // Only email tickets carry a subject, so a Slack or widget ticket falls back to- // its latest message — the only line of it that reads as a title. The number- // leads either way: it is how support refers to a ticket everywhere else, and- // it is what someone who typed a number is looking to confirm.- const subject = ticket.email_subject || ticket.last_message_text || 'Untitled ticket'- const displayName = `#${ticket.ticket_number} ${subject}`- return {- id: `ticket-${ticket.id}`,- name: displayName,- displayName,- category: 'tickets',- // The detail scene redirects a UUID to the ticket-number URL, so linking- // there directly saves the row a redirect.- href: urls.supportTicketDetail(ticket.ticket_number),- itemType: 'conversations',- // Rendered as the row's muted trailing text: which tickets are still open- // is the first thing a support agent reads off a list of matches.- productCategory: ticket.status ? capitalizeFirstLetter(ticket.status.replace(/_/g, ' ')) : null,- record: { type: 'conversations', id: ticket.id, ticketNumber: ticket.ticket_number },- }- })- },+ (ticketSearchResults: TicketApi[]): SearchItem[] => ticketSearchResults.map(ticketToSearchItem),],// Accounts and support tickets, handed to allCategories as one value. kea types a// selector's dependency list up to 16 entries and allCategories sits on that limit, so the@@ -1293,201 +750,6 @@ export const searchLogic = kea<searchLogicType>([})},],- healthItems: [- (s) => [s.sceneLogViewsByRef],- (sceneLogViewsByRef: Record<string, string>): SearchItem[] => [- {- id: 'health-pipeline-status',- name: 'Pipeline status',- displayName: 'Pipeline status',- category: 'health',- href: urls.pipelineStatus(),- itemType: 'pipeline_status',- lastViewedAt: sceneLogViewsByRef['PipelineStatus'] ?? null,- record: { type: 'pipeline_status', iconType: 'pipeline_status' },- },- {- id: 'health-sdk-health',- name: 'SDK health',- displayName: 'SDK health',- category: 'health',- href: urls.sdkHealth(),- itemType: 'sdk_health',- lastViewedAt: sceneLogViewsByRef['SdkHealth'] ?? null,- record: { type: 'sdk_health', iconType: 'sdk_health' },- },- ],- ],- miscItems: [- (s) => [s.sceneLogViewsByRef, s.featureFlags, (_, props: SearchLogicProps) => props.logicKey],- (- sceneLogViewsByRef: Record<string, string>,- featureFlags: FeatureFlagsSet,- logicKey: string- ): SearchItem[] => [- ...(logicKey === 'command' && featureFlags[FEATURE_FLAGS.POSTHOG_TERMINAL]- ? [- {- id: 'misc-toggle-terminal',- name: 'Toggle terminal',- displayName: 'Toggle terminal',- category: 'misc',- icon: <IconTerminal />,- itemType: null,- searchKeywords: ['terminal', 'shell', 'console'],- onSelect: () => terminalDockLogic.actions.toggleTerminal(),- record: { type: 'terminal' },- },- ]- : []),- {- id: 'misc-exports',- name: 'Exports',- displayName: 'Exports',- category: 'misc',- href: urls.exports(),- icon: <IconDownload />,- itemType: null,- lastViewedAt: sceneLogViewsByRef['Exports'] ?? null,- record: { type: 'exports' },- },- {- id: 'misc-alerts',- name: 'Alerts',- displayName: 'Alerts',- category: 'misc',- href: urls.alerts(),- icon: <IconBell />,- itemType: null,- lastViewedAt: sceneLogViewsByRef['SavedInsights'] ?? null,- record: { type: 'alerts' },- },- {- id: 'misc-subscriptions',- name: 'Subscriptions',- displayName: 'Subscriptions',- category: 'misc',- href: urls.subscriptions(),- icon: <IconNotification />,- itemType: null,- lastViewedAt: sceneLogViewsByRef['Subscriptions'] ?? null,- record: { type: 'subscriptions' },- },- {- id: 'misc-logout',- name: 'Log out',- displayName: 'Log out',- category: 'misc',- icon: <IconLeave />,- itemType: null,- searchKeywords: ['logout', 'log out', 'sign out', 'signout', 'exit'],- onSelect: () => userLogic.actions.logout(),- record: { type: 'logout' },- },- ],- ],- settingsItems: [- (s) => [s.featureFlags, s.organizationIntegrations, s.settingsSections, s.billingEntryUrl],- (- featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,- organizationIntegrations: import('~/types').IntegrationType[] | null,- settingsSections: SettingsSectionSummary[],- billingEntryUrl: string | null- ): SearchItem[] => {- const checkFlag = (flagKey: Pick<Setting, 'flag'>['flag']): boolean =>- matchesFlagDefinition(flagKey, featureFlags)-- const items: SearchItem[] = []-- // Skip project-level sections as they are duplicates of environment sections- const seenSectionIds = new Set<string>()-- for (const section of settingsSections) {- // Skip sections hidden from navigation (they are only accessible- // from their product's own configuration page)- if (section.hideFromNavigation) {- continue- }-- // Mirror sidebar gating: only surface organization integrations when any exist- if (- section.id === 'organization-integrations' &&- (!organizationIntegrations || organizationIntegrations.length === 0)- ) {- continue- }-- // Mirror the sidebar's billing gate. billingEntryUrl is null when the user has no- // billing access, and for view-only members it points at Usage, which keeps them- // off the admin-only Overview and the restricted state it renders first.- let billingHref: string | null = null- if (section.id === 'organization-billing') {- if (!billingEntryUrl) {- continue- }- billingHref = billingEntryUrl- }-- // Map environment sections to project level- const effectiveLevel = section.level === 'environment' ? 'project' : section.level- const effectiveSectionId = (- section.level === 'environment' ? section.id.replace('environment-', 'project-') : section.id- ) as SettingSectionId-- // Filter by feature flag if required- if (section.flag) {- if (!checkFlag(section.flag as Pick<Setting, 'flag'>['flag'])) {- continue- }- }-- // Skip duplicate project sections (environment sections take priority)- if (seenSectionIds.has(effectiveSectionId)) {- continue- }- seenSectionIds.add(effectiveSectionId)-- // Create a search item for each settings section- const levelPrefix = toSentenceCase(effectiveLevel)-- const searchTerms = [- ...(section.keywords ?? []),- ...section.settings- .filter((setting) => setting.hasTitle && checkFlag(setting.flag))- .flatMap((setting) => [- toSentenceCase(setting.id.replace(/[-]/g, ' ')),- ...(setting.titleString ? [setting.titleString] : []),- ...(setting.descriptionString ? [setting.descriptionString] : []),- ...(setting.keywords ?? []),- ]),- ]-- // Create the display name for each settings section- const displayName = section.titleString ?? toSentenceCase(section.id.replace(/[-]/g, ' '))-- const displayNameSuffix =- displayName === 'General' || displayName === 'Danger zone' || displayName === 'Integrations'- ? ` (${toSentenceCase(effectiveLevel)})`- : ''-- items.push({- id: `settings-${effectiveSectionId}`,- name: `${levelPrefix}: ${displayName} (${searchTerms})`,- displayName: `${displayName}${displayNameSuffix}`,- category: 'settings',- href: billingHref || section.to || urls.settings(effectiveSectionId),- itemType: 'settings',- record: {- type: 'settings',- level: effectiveLevel,- sectionId: effectiveSectionId,- },- })- }-- return items- },- ],unifiedSearchItems: [(s) => [s.unifiedSearchResults],(unifiedSearchResults: SearchResponse | null): Record<string, SearchItem[]> => {@@ -1502,74 +764,7 @@ export const searchLogic = kea<searchLogicType>([if (!categoryItems[category]) {categoryItems[category] = []}-- let name = result.result_id- let href = ''-- switch (result.type) {- case 'insight':- name = safeString(result.extra_fields.name) || result.result_id- href = `/insights/${result.result_id}`- break- case 'dashboard':- name = safeString(result.extra_fields.name) || result.result_id- href = `/dashboard/${result.result_id}`- break- case 'feature_flag':- name = safeString(result.extra_fields.key) || result.result_id- href = `/feature_flags/${result.result_id}`- break- case 'experiment':- name = safeString(result.extra_fields.name) || result.result_id- href = `/experiments/${result.result_id}`- break- case 'early_access_feature':- name = safeString(result.extra_fields.name) || result.result_id- href = `/early_access_features/${result.result_id}`- break- case 'hog_flow':- name = safeString(result.extra_fields.name) || result.result_id- href = `/workflows/${result.result_id}/workflow`- break- case 'survey':- name = safeString(result.extra_fields.name) || result.result_id- href = `/surveys/${result.result_id}`- break- case 'notebook':- name = safeString(result.extra_fields.title) || result.result_id- href = `/notebooks/${result.result_id}`- break- case 'cohort':- name = safeString(result.extra_fields.name) || result.result_id- href = `/cohorts/${result.result_id}`- break- case 'action':- name = safeString(result.extra_fields.name) || result.result_id- href = `/data-management/actions/${result.result_id}`- break- case 'event_definition':- name = safeString(result.extra_fields.name) || result.result_id- href = `/data-management/events/${result.result_id}`- break- case 'property_definition':- name = safeString(result.extra_fields.name) || result.result_id- href = `/data-management/properties/${result.result_id}`- break- }-- categoryItems[category].push({- id: `${result.type}-${result.result_id}`,- name,- category,- href,- itemType: result.type,- rank: result.rank,- disabledReason: getEntryAccessDisabledReason(result),- record: {- type: result.type,- ...result.extra_fields,- },- })+ categoryItems[category].push(unifiedSearchResultToSearchItem(result))}return categoryItems@@ -1768,7 +963,7 @@ export const searchLogic = kea<searchLogicType>([// Show "create" category only when searching and matching "new" or relevant keywordsif (hasSearch) {- const filteredNewItems = filterSearchItems(newItems, search.replace(LEADING_CREATE_WORD, 'new'))+ const filteredNewItems = filterNewItems(newItems, search)if (filteredNewItems.length > 0) {categories.push({@@ -1911,36 +1106,4 @@ export const searchLogic = kea<searchLogicType>([actions.loadPlaylistSearchResults({ searchTerm: search })},})),- afterMount(({ actions }) => {- import('~/scenes/settings/SettingsMap')- .then(({ SETTINGS_MAP }) => {- actions.setSettingsSections(- SETTINGS_MAP.map((section) => ({- id: section.id,- level: section.level,- titleString: getTitleText(section.title) || null,- hideFromNavigation: section.hideFromNavigation,- flag: section.flag,- to: section.to,- keywords: section.keywords,- settings: section.settings.map((setting) => ({- id: setting.id,- // A setting can render a title that getTitleText cannot read, such as a- // whole component, and it must stay findable via its id token.- // hasTitle preserves that distinction.- hasTitle: !!setting.title,- titleString: getTitleText(setting.title) || null,- descriptionString:- setting.searchDescription ??- (typeof setting.description === 'string' ? setting.description : null),- keywords: setting.keywords,- flag: setting.flag,- })),- }))- )- })- .catch((error) => {- console.error('Failed to load SETTINGS_MAP for settings search:', error)- })- }),])diff --git a/frontend/src/lib/components/Search/utils.ts b/frontend/src/lib/components/Search/utils.tsindex b634efd4777b..513f27449764 100644--- a/frontend/src/lib/components/Search/utils.ts+++ b/frontend/src/lib/components/Search/utils.ts@@ -38,18 +38,27 @@ const keywordOnlyMatch = (matches: readonly FuseResultMatch[] = []): string | nureturn matches.find((match) => match.key === SEARCH_KEYWORDS_KEY)?.value ?? null}+// Lists come from memoized selectors, so the same array reaches here on every keystroke.+// Building the index once per array keeps typing to a search, not a rebuild.+const fuseByItems = new WeakMap<FuseSearchable[], ReturnType<typeof createFuse<FuseSearchable>>>()+/*** Filter items using Fuse.js fuzzy search. Searches across name, displayName,* category, and searchKeywords with weighted scoring.*/+export function filterSearchItems<T extends FuseSearchable>(items: T[], query: string): T[] {const trimmed = query.trim()if (!trimmed) {return items}- const fuse = createFuse<T>(items, FUSE_OPTIONS)+ let fuse = fuseByItems.get(items)+ if (!fuse) {+ fuse = createFuse<FuseSearchable>(items, FUSE_OPTIONS)+ fuseByItems.set(items, fuse)+ }return fuse.search(trimmed).map((result) => ({- ...result.item,+ ...(result.item as T),matchedSearchKeyword: keywordOnlyMatch(result.matches),}))}diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 26b8fbb06557..8c1d24f74eb4 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -430,11 +430,12 @@ export const FEATURE_FLAGS = {MEMBER_BILLING_USAGE_SPEND_READ_ACCESS: 'member-billing-usage-spend-read-access', // owner: @pawelcebula #team-billing, grants members read-only access to billing usage/spend tabs; owner-only-billing takes precedenceMESSAGING_SES: 'messaging-ses', // owner #team-workflowsMETRICS: 'metrics', // owner: #team-apm (@jonmcwest, @frankh)+ METRICS_DASHBOARD_CONTROLS: 'metrics-dashboard-controls', // owner: #team-apm — shows each dashboard filter only for the tiles it changes, and adds the metric label filterMETRICS_DASHBOARD_PANELS: 'metrics-dashboard-panels', // owner: #team-apm — gates the stat/gauge/bargauge/table panel picker entriesMETRICS_ERROR_OVERLAYS: 'metrics-error-overlays', // owner: #team-apm — gates the error-spike overlay PoC on metrics charts- METRICS_DASHBOARD_CONTROLS: 'metrics-dashboard-controls', // owner: #team-apm — shows each dashboard filter only for the tiles it changes, and adds the metric label filterMETRICS_INSIGHT_BUILDER: 'metrics-insight-builder', // owner: #team-apm — offers Metrics in the new insight menu and the metrics builder in insight edit modeML_INFERENCE_DECISIONS: 'ml-inference-decisions', // owner: #team-ai-research, gates the decisions playground; the API checks the same flag server side+ NEW_COMMAND_K_SEARCH: 'new-command-k-search', // owner: @adamleithp #team-platform-ux, gates the Command K search with smart filtersNEW_TAB_PROJECT_EXPLORER: 'new-tab-project-explorer', // owner: #team-platform-uxNEW_TEAM_CORE_EVENTS: 'new-team-core-events', // owner: @jabahamondes #team-web-analyticsNOTEBOOK_GENERATED_WIDGETS: 'notebook-generated-widgets', // owner: #team-data-toolsdiff --git a/frontend/src/lib/utils/newInternalTab.test.ts b/frontend/src/lib/utils/newInternalTab.test.tsnew file mode 100644index 000000000000..ad87e22e538a--- /dev/null+++ b/frontend/src/lib/utils/newInternalTab.test.ts@@ -0,0 +1,32 @@+import { newInternalTab } from 'lib/utils/newInternalTab'++describe('newInternalTab', () => {+ let clickedHrefs: string[]++ beforeEach(() => {+ clickedHrefs = []+ jest.spyOn(HTMLAnchorElement.prototype, 'dispatchEvent').mockImplementation(function (this: HTMLAnchorElement) {+ clickedHrefs.push(this.getAttribute('href') ?? '')+ return true+ })+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it('opens an external link as given', () => {+ newInternalTab('https://posthog.com/docs')++ expect(clickedHrefs).toEqual(['https://posthog.com/docs'])+ })++ it.each(['javascript:alert(1)', 'javascript:/api/,alert(document.cookie)', 'JaVaScRiPt:/login/,alert(1)'])(+ 'opens nothing for %p',+ (path) => {+ newInternalTab(path)++ expect(clickedHrefs).toEqual([])+ }+ )+})diff --git a/frontend/src/lib/utils/newInternalTab.tsx b/frontend/src/lib/utils/newInternalTab.tsxindex 65f6b35e3d30..14c8b855fb0e 100644--- a/frontend/src/lib/utils/newInternalTab.tsx+++ b/frontend/src/lib/utils/newInternalTab.tsx@@ -1,4 +1,5 @@import { addProjectIdIfMissing } from 'lib/utils/kea-router'+import { hasDangerousScheme } from 'lib/utils/url'export const NEW_INTERNAL_TAB = 'NEW_INTERNAL_TAB'@@ -10,7 +11,9 @@ export const NEW_INTERNAL_TAB = 'NEW_INTERNAL_TAB'* preference, while plain `window.open` and bare `.click()` can route to a new window.*/export function newInternalTab(path?: string, _source: 'internal_link' | 'unknown' = 'internal_link'): void {- if (!path) {+ // Paths can come from team-writable data, such as search results, so a `javascript:` target+ // must open nothing. `addProjectIdIfMissing` passes `javascript:/api/...` through intact.+ if (!path || hasDangerousScheme(path)) {return}const isExternal = /^(https?:|mailto:)/.test(path)diff --git a/frontend/src/scenes/new-tab/NewTabScene.tsx b/frontend/src/scenes/new-tab/NewTabScene.tsxindex 7e13dd8b0fb4..51573017b912 100644--- a/frontend/src/scenes/new-tab/NewTabScene.tsx+++ b/frontend/src/scenes/new-tab/NewTabScene.tsx@@ -3,7 +3,7 @@ import { router } from 'kea-router'import { useCallback } from 'react'import { Search } from 'lib/components/Search/Search'-import { SearchItem } from 'lib/components/Search/searchLogic'+import { SearchItem } from 'lib/components/Search/searchItems'import { navigateToHref } from 'lib/utils/navigateToHref'import { newInternalTab } from 'lib/utils/newInternalTab'import { SceneExport } from 'scenes/sceneTypes'