Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(command-k): add a "view all" row and smarter ask ai question (#117565)

Adam Leith68964c854846
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c0040a4c3677..31ea9c9631d5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -13067,7 +13067,7 @@ snapshots:
scenes-app-notebooks-generated-widgets--after-generation--light:
hash: v1.k794b7964.986afdd0b4386ad2fa3f9906179742611beecb535f59eb62e1c1e5b82624e94c.eGNt5HvvSQW7br9YOxNI25E0-stgO3c9zpn1itVnwFk
scenes-app-notebooks-generated-widgets--before-generation--dark:
- hash: v1.k794b7964.170cc8f24367e614fa935570b13f4ce7d5f83f617b567e045032502491a4530b.Z7u0Hvsxpxt0kN-NVXCmvNAunsxT4eu_x18JZOMjbf0
+ hash: v1.k794b7964.6d5dced84e0f5d77eab7bc26c47aa616082c99770c78c96754d472555ccc45f2.BHGHm-Y4KPckvD99tPCQlYdh0TQc7hQUPY0AxV1yJa0
scenes-app-notebooks-generated-widgets--before-generation--light:
hash: v1.k794b7964.f8eabbbe270e16f6db6253fac4ccc1298d6486f4fcc54d086f39b494e32276bb.byEVF2WvcVULWZ_b-qJMNkCK-hCMqS-EcQNFNyVUVd4
scenes-app-notebooks-jupyter-mode--jupyter-mode--dark:
diff --git a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
index a7464dccca6c..70137fface00 100644
--- a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
+++ b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
@@ -45,7 +45,7 @@ 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.
+- **Press Tab to ask AI** shows while Tab would ask AI: there is a question to ask (see **Ask PostHog AI**) 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.
@@ -97,6 +97,7 @@ The input is always in exactly one mode, decided from the token under the cursor
3. Remote lists that the file system does not hold: **Events**, **Properties**, **Workflows** (one unified search request), **Accounts** (behind the customer analytics flag), **Support tickets** (3+ characters or a ticket number), **Persons**, **Groups**.
4. **Ask PostHog AI**.
- With any filter (a chip, or a valid `key:value` still being typed), only **Results** and **Ask PostHog AI** show, because filters apply only to objects.
+- With an `is:` chip (not negated), **Results** holds a **View all <types>** row (`View all feature flags`) that opens the list page of that type. With no search text it is the first row; once you type a search it moves below the results. It shows only for types with a list page.
## Smart filters
@@ -142,7 +143,7 @@ These are the rules reviewers check. Breaking one is a bug.
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.
+5. **Highlight follows identity, not index.** The highlighted row is tracked by item key (`section/type:ref`). Once the person moves the highlight (arrow keys or pointer), it stays on that item through result swaps for the same query while the item still exists. If it is gone, or the person never moved it, the first row is highlighted. Any change to the query (typing, clearing, adding or removing a chip) starts again at the first row.
6. **Fixed row height.** Every row is one line, same height. Long names truncate with an ellipsis; the type label and timestamp never wrap.
7. **Instant local, deferred remote.** Local sources (recents, starred, products, filter keys, type values, cached members) filter synchronously on every keystroke. Remote search debounces at 150 ms.
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.
@@ -179,7 +180,7 @@ These are the rules reviewers check. Breaking one is a bug.
- **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.
+- **Ask PostHog AI**: the last section in Search mode. Without filters, the question is the input text as typed. With filters and free text, the filters read as a sentence around the text (`Find notebooks created by me called "untitled"`). With filters and no free text, the section does not show and Tab does not ask AI.
## Out of scope for v1
diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx
index a3987e76c0b5..b0c474e29b8d 100644
--- a/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx
+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx
@@ -2,7 +2,7 @@ import { useActions } from 'kea'
import { memo } from 'react'
import { IconFilter, IconFolder, IconPerson, IconSparkles } from '@posthog/icons'
-import { Button, cn } from '@posthog/quill'
+import { Button, Skeleton, cn } from '@posthog/quill'
import { getIconForItem, getItemTypeDisplayName } from 'lib/components/Search/searchItemDisplay'
import { formatRelativeTimeShort } from 'lib/components/Search/utils'
@@ -125,6 +125,8 @@ const rowContent = (row: CommandKRow): unknown => {
return row.question
case 'message':
return row.text
+ case 'skeleton':
+ return null
}
}
@@ -139,6 +141,14 @@ export const CommandKSearchRow = memo(
function CommandKSearchRowInner({ row, highlighted }: CommandKSearchRowProps): JSX.Element {
const { activateRow, setHighlightedKey } = useActions(commandKSearchLogic)
+ if (row.kind === 'skeleton') {
+ return (
+ <div className="flex h-8 items-center px-1" role="presentation">
+ <Skeleton className="h-5 w-full" />
+ </div>
+ )
+ }
+
if (row.kind === 'message') {
return (
<div className="flex h-8 items-center px-2 text-sm text-muted-foreground" role="presentation">
diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsx
index 4bdd8570e61c..f2f8dcad14e6 100644
--- a/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsx
+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchSection.tsx
@@ -1,4 +1,4 @@
-import { MenuLabel, Skeleton, cn } from '@posthog/quill'
+import { MenuLabel, cn } from '@posthog/quill'
import { CommandKSearchRow } from './CommandKSearchRow'
import { CommandKSection } from './commandKSections'
@@ -27,15 +27,9 @@ export function CommandKSearchSection({
)}
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} />
- ))}
+ {section.rows.map((row) => (
+ <CommandKSearchRow key={row.key} row={row} highlighted={row.key === highlightedKey} />
+ ))}
</div>
</div>
)
diff --git a/frontend/src/lib/components/CommandKSearch/commandKAskAi.test.ts b/frontend/src/lib/components/CommandKSearch/commandKAskAi.test.ts
new file mode 100644
index 000000000000..10ead0f456b7
--- /dev/null
+++ b/frontend/src/lib/components/CommandKSearch/commandKAskAi.test.ts
@@ -0,0 +1,34 @@
+import { askAiQuestionFor } from './commandKAskAi'
+import { FilterOptions, QueryChip, resolveQuery } from './commandKQuery'
+
+const OPTIONS: FilterOptions = {
+ is: [
+ { value: 'dashboard', label: 'Dashboard' },
+ { value: 'insight', label: 'Insight' },
+ ],
+ createdBy: [
+ { value: 'me', label: 'Me' },
+ { value: '[email protected]', label: 'Mel Ortiz' },
+ ],
+ in: [],
+ name: [],
+}
+
+const chip = (key: QueryChip['key'], value: string): QueryChip => ({ key, value, label: value, negated: false })
+
+describe('askAiQuestionFor', () => {
+ test.each([
+ ['no filters', 'how many signups', [], 'how many signups'],
+ ['a type and no text', '', [chip('is', 'dashboard')], null],
+ ['a type and text', 'is:insight revenue', [], 'Find insights called "revenue"'],
+ ['a creator and text', 'createdBy:me revenue', [], 'Find objects created by me called "revenue"'],
+ [
+ 'several filters and text',
+ 'is:dashboard -createdBy:[email protected] revenue',
+ [],
+ 'Find dashboards not created by Mel Ortiz called "revenue"',
+ ],
+ ])('asks with %s', (_, text, chips, question) => {
+ expect(askAiQuestionFor(text, resolveQuery(text, chips, OPTIONS))).toBe(question)
+ })
+})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKAskAi.ts b/frontend/src/lib/components/CommandKSearch/commandKAskAi.ts
new file mode 100644
index 000000000000..6a68f270656a
--- /dev/null
+++ b/frontend/src/lib/components/CommandKSearch/commandKAskAi.ts
@@ -0,0 +1,32 @@
+import { pluralTypeName } from './commandKFilterOptions'
+import { FilterKey, QueryChip, ResolvedQuery } from './commandKQuery'
+
+const FILTER_PHRASES: Record<Exclude<FilterKey, 'is'>, (chip: QueryChip) => string> = {
+ createdBy: ({ value, label, negated }) =>
+ `${negated ? 'not created' : 'created'} by ${value === 'me' ? 'me' : label}`,
+ in: ({ label, negated }) => `${negated ? 'outside' : 'in'} ${label}`,
+ name: ({ label, negated }) => `with a name ${negated ? 'not containing' : 'containing'} "${label}"`,
+}
+
+function objectNoun(type: QueryChip | undefined): string {
+ if (!type) {
+ return 'objects'
+ }
+ if (type.negated) {
+ return `objects that are not ${pluralTypeName(type.label)}`
+ }
+ return pluralTypeName(type.label)
+}
+
+// Filters with no free text ask nothing: the filters alone already answer the search.
+export function askAiQuestionFor(text: string, { filters, freeText }: ResolvedQuery): string | null {
+ if (filters.length === 0) {
+ return text.trim() || null
+ }
+ const search = freeText.trim()
+ if (!search) {
+ return null
+ }
+ const phrases = filters.flatMap((chip) => (chip.key === 'is' ? [] : [FILTER_PHRASES[chip.key](chip)]))
+ return ['Find', objectNoun(filters.find((chip) => chip.key === 'is')), ...phrases, `called "${search}"`].join(' ')
+}
diff --git a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.test.ts b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.test.ts
new file mode 100644
index 000000000000..351824ab9868
--- /dev/null
+++ b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.test.ts
@@ -0,0 +1,42 @@
+import { viewAllFor } from './commandKFilterOptions'
+import { QueryChip, ResolvedQuery } from './commandKQuery'
+
+const chip = (value: string, label: string, overrides: Partial<QueryChip> = {}): QueryChip => ({
+ key: 'is',
+ value,
+ label,
+ negated: false,
+ ...overrides,
+})
+
+const resolved = (filters: QueryChip[], freeText = ''): ResolvedQuery => ({ filters, freeText, backendSearch: '' })
+
+describe('viewAllFor', () => {
+ test.each([
+ ['a manifest list page', [chip('feature_flag', 'Feature flag')], 'View all feature flags', '/feature_flags'],
+ ['a type with a fallback page', [chip('dashboard', 'Dashboard')], 'View all dashboards', '/dashboard'],
+ [
+ 'other filters alongside',
+ [chip('feature_flag', 'Feature flag'), chip('me', 'Me', { key: 'createdBy' })],
+ 'View all feature flags',
+ '/feature_flags',
+ ],
+ ])('names the list page for %s', (_, chips, name, href) => {
+ expect(viewAllFor(resolved(chips))?.item).toMatchObject({ name, href })
+ })
+
+ test.each([
+ ['leads with only filters', '', 'lead'],
+ ['trails once there is search text', 'beta', 'trail'],
+ ])('%s', (_, freeText, placement) => {
+ expect(viewAllFor(resolved([chip('feature_flag', 'Feature flag')], freeText))?.placement).toBe(placement)
+ })
+
+ test.each([
+ ['no is chip', [chip('me', 'Me', { key: 'createdBy' })]],
+ ['a negated is chip', [chip('feature_flag', 'Feature flag', { negated: true })]],
+ ['a type with no list page', [chip('folder', 'Folder')]],
+ ])('returns nothing for %s', (_, chips) => {
+ expect(viewAllFor(resolved(chips))).toBeNull()
+ })
+})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.ts b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx
similarity index 56%
rename from frontend/src/lib/components/CommandKSearch/commandKFilterOptions.ts
rename to frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx
index 694b7a1dc175..42ecc9b06e15 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKFilterOptions.tsx
@@ -1,8 +1,13 @@
+import { IconArrowRight } from '@posthog/icons'
+
+import { SearchItem } from 'lib/components/Search/searchItems'
+
import { fileSystemTypes } from '~/products'
import { FileSystemEntry } from '~/queries/schema/schema-general'
import { OrganizationMemberType, UserType } from '~/types'
-import { FilterOptions, ValueOption } from './commandKQuery'
+import { FilterOptions, ResolvedQuery, ValueOption } from './commandKQuery'
+import type { ViewAll } from './commandKSections'
/** Short words people type for a type, on top of its name and key. */
const TYPE_ALIASES: Record<string, string[]> = {
@@ -13,12 +18,29 @@ const TYPE_ALIASES: Record<string, string[]> = {
notebook: ['doc'],
}
+interface FileSystemTypeDefinition {
+ name?: string
+ iconType?: string
+ listHref?: () => string
+}
+
+const FILE_SYSTEM_TYPES = fileSystemTypes as Record<string, FileSystemTypeDefinition>
+
+const typeDefinition = (type: string): FileSystemTypeDefinition | undefined =>
+ Object.hasOwn(FILE_SYSTEM_TYPES, type) ? FILE_SYSTEM_TYPES[type] : undefined
+
+// Some manifest names are already plural, such as "Tasks".
+export const pluralTypeName = (label: string): string => {
+ const name = label.toLowerCase()
+ return name.endsWith('s') ? name : `${name}s`
+}
+
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 }>)
+ cachedTypeOptions = Object.entries(FILE_SYSTEM_TYPES)
.flatMap(([type, definition]) =>
definition.name
? [
@@ -67,3 +89,32 @@ export function buildFilterOptions(
name: [],
}
}
+
+/** List pages for types whose manifest registers no `listHref`. */
+const LIST_HREF_FALLBACKS: Record<string, string> = {
+ dashboard: '/dashboard',
+ notebook: '/notebooks',
+}
+
+// With only filters the list page is the likely target; once there is search text, the matches matter more.
+export function viewAllFor({ filters, freeText }: ResolvedQuery): ViewAll | null {
+ const chip = filters.find((candidate) => candidate.key === 'is' && !candidate.negated)
+ if (!chip) {
+ return null
+ }
+ const href = typeDefinition(chip.value)?.listHref?.() ?? LIST_HREF_FALLBACKS[chip.value]
+ if (!href) {
+ return null
+ }
+ const name = `View all ${pluralTypeName(chip.label)}`
+ const item: SearchItem = {
+ id: `view-all-${chip.value}`,
+ name,
+ displayName: name,
+ category: 'results',
+ href,
+ icon: <IconArrowRight className="size-4 shrink-0 text-muted-foreground" />,
+ record: { type: chip.value },
+ }
+ return { item, placement: freeText.trim() ? 'trail' : 'lead' }
+}
diff --git a/frontend/src/lib/components/CommandKSearch/commandKQuery.test.ts b/frontend/src/lib/components/CommandKSearch/commandKQuery.test.ts
index 433086022c6d..c31d3c60e722 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKQuery.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKQuery.test.ts
@@ -141,7 +141,7 @@ describe('commandKQuery', () => {
}
)
- test('ask AI text includes chips as typed text', () => {
+ test('copied text includes chips as typed text', () => {
expect(queryAsText(' revenue ', [chip('is', 'dashboard', true)])).toBe('-is:dashboard revenue')
})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKQuery.ts b/frontend/src/lib/components/CommandKSearch/commandKQuery.ts
index cf149ed5e434..794322080e7b 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKQuery.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKQuery.ts
@@ -363,7 +363,7 @@ export function resolveQuery(text: string, chips: QueryChip[], options: FilterOp
}
}
-/** The raw query as a person would type it, chips included. Used for "Ask PostHog AI". */
+/** The raw query as a person would type it, chips included. Used when copying the input. */
export function queryAsText(text: string, chips: QueryChip[]): string {
return [...chips.map(chipToText), text.trim()].filter(Boolean).join(' ')
}
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts
new file mode 100644
index 000000000000..9ec7da4c5797
--- /dev/null
+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts
@@ -0,0 +1,28 @@
+import { initKeaTests } from '~/test/init'
+
+import { commandKSearchLogic } from './commandKSearchLogic'
+
+describe('commandKSearchLogic', () => {
+ let logic: ReturnType<typeof commandKSearchLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = commandKSearchLogic()
+ logic.mount()
+ })
+
+ afterEach(() => logic.unmount())
+
+ test.each([
+ ['typing', (): void => logic.actions.inputChanged('revenue', 7, false)],
+ ['clearing the input', (): void => logic.actions.clearQuery()],
+ ['removing a chip', (): void => logic.actions.applyKeyIntent({ type: 'remove-chip', index: 0 })],
+ ])('a new query from %s drops the remembered highlight', (_, changeQuery) => {
+ logic.actions.setChipsAndText([{ key: 'is', value: 'dashboard', label: 'Dashboard', negated: false }], 'rev', 3)
+ logic.actions.setHighlightedKey('recents/dashboard:1')
+
+ changeQuery()
+
+ expect(logic.values.highlightedKey).toBeNull()
+ })
+})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx
index ad815582cfb7..9fa99dd196dd 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx
+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx
@@ -35,7 +35,8 @@ 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 { askAiQuestionFor } from './commandKAskAi'
+import { buildFilterOptions, viewAllFor } from './commandKFilterOptions'
import { ChipSelection, KeyIntent } from './commandKKeys'
import {
CursorContext,
@@ -63,6 +64,7 @@ import {
LocalLists,
RECENTS_LIMIT,
RemoteSlots,
+ ViewAll,
buildSections,
buildSuggestions,
emptyRemoteSlots,
@@ -95,7 +97,7 @@ export interface commandKSearchLogicValues {
currentTeamId: number | null // teamLogic
isDarkModeOn: boolean // themeLogic
user: UserType | null // userLogic
- askAiQuestion: string
+ askAiQuestion: string | null
chipSelection: ChipSelection
chips: QueryChip[]
cursor: number
@@ -123,6 +125,7 @@ export interface commandKSearchLogicValues {
tabAsksAi: boolean
text: string
themeItem: SearchItem | null
+ viewAll: ViewAll | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -213,9 +216,6 @@ export interface commandKSearchLogicActions {
>
>
}
- removeChip: (index: number) => {
- index: number
- }
requestStarted: (
requestId: string,
query: string
@@ -241,13 +241,6 @@ export interface commandKSearchLogicActions {
setHighlightedKey: (key: string | null) => {
key: string | null
}
- setInput: (
- text: string,
- cursor: number
- ) => {
- cursor: number
- text: string
- }
syncRemote: () => {
value: true
}
@@ -265,7 +258,7 @@ export interface commandKSearchLogicMeta {
mode: (cursorContext: CursorContext) => CommandKMode
resolvedQuery: (text: string, chips: QueryChip[], filterOptions: FilterOptions) => ResolvedQuery
localQuery: (resolvedQuery: ResolvedQuery, mode: CommandKMode) => string
- askAiQuestion: (text: string, chips: QueryChip[]) => string
+ askAiQuestion: (text: string, resolvedQuery: ResolvedQuery) => string | null
remoteContext: (
currentTeamId: number | null,
groupTypes: Map<GroupTypeIndex, GroupType>,
@@ -298,6 +291,7 @@ export interface commandKSearchLogicMeta {
miscItems: SearchItem[]
) => LocalLists
themeItem: (localQuery: string, isDarkModeOn: boolean) => SearchItem | null
+ viewAll: (resolvedQuery: ResolvedQuery) => ViewAll | null
sections: (
mode: CommandKMode,
cursorContext: CursorContext,
@@ -312,12 +306,13 @@ export interface commandKSearchLogicMeta {
>,
localQuery: string,
themeItem: SearchItem | null,
- askAiQuestion: string
+ askAiQuestion: string | null,
+ viewAll: ViewAll | null
) => CommandKSection[]
selectableRows: (sections: CommandKSection[]) => CommandKRow[]
highlightedRow: (selectableRows: CommandKRow[], highlightedKey: string | null) => CommandKRow | null
highlightIsFilterRow: (highlightedRow: CommandKRow | null) => boolean
- tabAsksAi: (highlightIsFilterRow: boolean, askAiQuestion: string) => boolean
+ tabAsksAi: (highlightIsFilterRow: boolean, askAiQuestion: string | null) => boolean
isPaletteEmpty: (text: string, chips: QueryChip[]) => boolean
}
}
@@ -377,11 +372,9 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
})),
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: ChipSelection) => ({ index }),
editChip: (index: number) => ({ index }),
completeFilterKey: (filter: FilterDefinition, negated: boolean) => ({ filter, negated }),
@@ -403,14 +396,12 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
text: [
'',
{
- setInput: (_, { text }) => text,
setChipsAndText: (_, { text }) => text,
},
],
cursor: [
0,
{
- setInput: (_, { cursor }) => cursor,
setCursor: (_, { cursor }) => cursor,
setChipsAndText: (_, { cursor }) => cursor,
},
@@ -419,22 +410,21 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
[] as QueryChip[],
{
setChipsAndText: (_, { chips }) => chips,
- removeChip: (state, { index }) => state.filter((_, i) => i !== index),
},
],
chipSelection: [
null as ChipSelection,
{
selectChip: (_, { index }) => index,
- setInput: () => null,
setChipsAndText: () => null,
- removeChip: () => null,
},
],
+ // Follows identity through result swaps within one query; a new query starts at the first row.
highlightedKey: [
null as string | null,
{
setHighlightedKey: (_, { key }) => key,
+ setChipsAndText: () => null,
},
],
// The query each request last asked for. No selector reads it, so starting a request never re-renders.
@@ -498,8 +488,8 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
(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),
+ (s) => [s.text, s.resolvedQuery],
+ (text: string, resolved: ResolvedQuery): string | null => askAiQuestionFor(text, resolved),
],
remoteContext: [
(s) => [s.currentTeamId, s.groupTypes, s.aggregationLabel, s.featureFlags],
@@ -614,6 +604,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
toggleTheme: () => themeLogic.actions.toggleTheme(),
}),
],
+ viewAll: [(s) => [s.resolvedQuery], (resolved: ResolvedQuery): ViewAll | null => viewAllFor(resolved)],
sections: [
(s) => [
s.mode,
@@ -625,6 +616,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
s.localQuery,
s.themeItem,
s.askAiQuestion,
+ s.viewAll,
],
(
mode: CommandKMode,
@@ -635,7 +627,8 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
remoteQueries: Partial<Record<RemoteSource, string>>,
localQuery: string,
themeItem: SearchItem | null,
- askAiQuestion: string
+ askAiQuestion: string | null,
+ viewAll: ViewAll | null
): CommandKSection[] =>
buildSections({
mode,
@@ -647,6 +640,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
localQuery,
themeItem,
askAiQuestion,
+ viewAll,
}),
],
selectableRows: [
@@ -665,7 +659,8 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
],
tabAsksAi: [
(s) => [s.highlightIsFilterRow, s.askAiQuestion],
- (highlightIsFilterRow: boolean, askAiQuestion: string): boolean => !!askAiQuestion && !highlightIsFilterRow,
+ (highlightIsFilterRow: boolean, askAiQuestion: string | null): boolean =>
+ askAiQuestion !== null && !highlightIsFilterRow,
],
isPaletteEmpty: [
(s) => [s.text, s.chips],
@@ -710,7 +705,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
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,
+ query_length: queryAsText(values.text, values.chips).length,
})
actions.closeCommand()
if (row.kind === 'ask-ai') {
@@ -778,10 +773,8 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
actions.setChipsAndText(chips, text, cursor)
}
},
- setInput: onQueryChanged,
setCursor: onQueryChanged,
setChipsAndText: onQueryChanged,
- removeChip: onQueryChanged,
commitChip: ({ chip, token, via }) => commit(values.chips, chip, token, values.text, via),
completeFilterKey: ({ filter, negated }) => {
const token = tokenAtCursor(values.text, values.cursor)
@@ -789,7 +782,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
const next = token
? replaceToken(values.text, token, replacement)
: { text: values.text + replacement, cursor: values.text.length + replacement.length }
- actions.setInput(next.text, next.cursor)
+ actions.setChipsAndText(values.chips, next.text, next.cursor)
},
editChip: ({ index }) => {
const chip = values.chips[index]
@@ -823,7 +816,11 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
actions.clearQuery()
break
case 'remove-chip':
- actions.removeChip(intent.index)
+ actions.setChipsAndText(
+ values.chips.filter((_, i) => i !== intent.index),
+ values.text,
+ values.cursor
+ )
break
case 'edit-chip':
actions.editChip(intent.index)
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
index e98413bb7f3e..15907034a31e 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
@@ -5,6 +5,7 @@ import {
LocalLists,
RECENTS_LIMIT,
SectionsInput,
+ ViewAll,
buildSections,
emptyRemoteSlots,
} from './commandKSections'
@@ -45,7 +46,8 @@ const input = (mode: CommandKMode, overrides: Partial<SectionsInput>): SectionsI
remoteQueries: {},
localQuery: '',
themeItem: null,
- askAiQuestion: '',
+ askAiQuestion: null,
+ viewAll: null,
...overrides,
})
@@ -71,4 +73,21 @@ describe('buildSections', () => {
expect(new Set(keys).size).toBe(limit)
expect(keys[0]).toBe(`${sectionKey}/dashboard:1`)
})
+
+ test.each([
+ ['lead', ['view-all', 'skeleton-0', 'skeleton-1', 'skeleton-2'], ['view-all', 'dashboard:1']],
+ ['trail', ['skeleton-0', 'skeleton-1', 'skeleton-2', 'view-all'], ['dashboard:1', 'view-all']],
+ ] as const)('places a %s View all row before and after results load', (placement, whileLoading, onceLoaded) => {
+ const viewAll: ViewAll = {
+ item: { id: 'view-all', name: 'View all feature flags', category: 'results', href: '/feature_flags' },
+ placement,
+ }
+ const loading = buildSections(input('search', { remoteQueries: { results: 'x' }, viewAll }))
+ const loaded = buildSections(input('search', { ...remoteResults([dashboard('a', '1')]), viewAll }))
+ const rowKeys = (sections: ReturnType<typeof buildSections>): string[] =>
+ sections.find((section) => section.key === 'results')?.rows.map((row) => row.key.replace('results/', '')) ??
+ []
+ expect(rowKeys(loading)).toEqual(whileLoading)
+ expect(rowKeys(loaded)).toEqual(onceLoaded)
+ })
})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.ts
index f2df122c4a43..cfa15420b5f5 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSections.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.ts
@@ -27,6 +27,7 @@ export type CommandKRow =
| { kind: 'filter-key'; key: string; filter: FilterDefinition; negated: boolean }
| { kind: 'filter-value'; key: string; filter: FilterDefinition; option: ValueOption; negated: boolean }
| { kind: 'message'; key: string; text: string }
+ | { kind: 'skeleton'; key: string }
| { kind: 'item'; key: string; item: SearchItem; section: CommandKSectionKey }
| { kind: 'ask-ai'; key: string; question: string }
@@ -36,7 +37,11 @@ export interface CommandKSection {
rows: CommandKRow[]
/** `stale` keeps the previous query's rows on screen until the new ones land. */
state: 'ready' | 'loading' | 'stale'
- skeletonCount: number
+}
+
+export interface ViewAll {
+ item: SearchItem
+ placement: 'lead' | 'trail'
}
/** What a remote section can render. Which request is in flight lives elsewhere, so starting one never re-renders. */
@@ -73,7 +78,7 @@ const SECTION_LABELS: Record<CommandKSectionKey, string> = {
'ask-ai': 'PostHog AI',
}
-export const isSelectable = (row: CommandKRow): boolean => row.kind !== 'message'
+export const isSelectable = (row: CommandKRow): boolean => row.kind !== 'message' && row.kind !== 'skeleton'
const itemIdentity = (item: SearchItem): string => {
const type = item.record?.type
@@ -107,13 +112,14 @@ const readySection = (key: CommandKSectionKey, rows: CommandKRow[]): CommandKSec
label: SECTION_LABELS[key],
rows,
state: 'ready',
- skeletonCount: 0,
})
+const skeletonRows = (key: CommandKSectionKey): CommandKRow[] =>
+ Array.from({ length: DEFAULT_SKELETON_ROWS }, (_, index) => ({ kind: 'skeleton', key: `${key}/skeleton-${index}` }))
+
const loadingSection = (key: CommandKSectionKey): CommandKSection => ({
- ...readySection(key, []),
+ ...readySection(key, skeletonRows(key)),
state: 'loading',
- skeletonCount: DEFAULT_SKELETON_ROWS,
})
/**
@@ -194,12 +200,25 @@ export interface SectionsInput {
localQuery: string
/** Leads the Settings section when the query asks about the theme. */
themeItem: SearchItem | null
- askAiQuestion: string
+ askAiQuestion: string | null
+ viewAll: ViewAll | null
}
const filterLocal = (source: LocalSource, items: SearchItem[], query: string): SearchItem[] =>
source === 'create' ? filterNewItems(items, query) : filterSearchItems(items, query)
+function withViewAll(results: CommandKSection | null, viewAll: ViewAll | null): CommandKSection | null {
+ if (!viewAll) {
+ return results
+ }
+ const row: CommandKRow = { kind: 'item', key: `results/${viewAll.item.id}`, item: viewAll.item, section: 'results' }
+ const rows = results?.rows ?? []
+ return {
+ ...(results ?? readySection('results', [])),
+ rows: viewAll.placement === 'lead' ? [row, ...rows] : [...rows, row],
+ }
+}
+
export function buildSections(input: SectionsInput): CommandKSection[] {
const { mode, context, local, remote, remoteQueries, localQuery } = input
if (mode === 'empty') {
@@ -235,7 +254,7 @@ export function buildSections(input: SectionsInput): CommandKSection[] {
)
)
}
- sections.push(input.suggestions, remoteSectionFor('results'))
+ sections.push(input.suggestions, withViewAll(remoteSectionFor('results'), input.viewAll))
if (mode !== 'value' && localQuery) {
for (const source of LOCAL_SOURCES) {
const filtered = filterLocal(source, local[source], localQuery)