Skip to content

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

feat(search): show settings levels, sections and settings in cmd+k (#128037)

Shy Alter0fadcaa0da46
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f116627efb87..ed364fd4ed3d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2677,9 +2677,9 @@ snapshots:
components-search--product-recents-and-starred--light:
hash: v1.k794b7964.b4341fc26c099d3e62aacbd6273249487b1a190273edae9c6e2d6448dbba5aff.IOJTS2PvP9IC17AmGQ4kVnbrTyYv4S-zOBFCyEheZYM
components-search--searching--dark:
- hash: v1.k794b7964.ed4e2cf61e6843b34f6587a88d3a6d9528c63b3d38cc2d1e8ff4cb8a65d3f167.eWt0RKzJ0ys-GMJudG5IAKfZNgJ9fD_sxNZncIhLC3U
+ hash: v1.k794b7964.9ac703d6fea03dc43c60358fc9cd97890b2509c8fa675ad2c740fa77041055c6.pCBWpIKgltqafErzPq58lKggrlWy8YSNi7_GYOoK6ts
components-search--searching--light:
- hash: v1.k794b7964.5e52b7c3813256e14dbc9153507b1672c7942366cbeac296cd9e63ddb5d1f2f2.28bYbXg87E0YO8xd3wAKnw-luPTtjFQ8E2qPb7kh_pI
+ hash: v1.k794b7964.72b497e3dd8fd183f78e8758d83df63a10ae039a9092e2651e96f246595cff9d.NOcM-3a7bdZQ6b5y9m-SLQGX7zfLrzkRjeet2Ci-mDI
components-sentencelist--full-sentence--dark:
hash: v1.k794b7964.7e8e5dd2e09d246cc3668f362f2391fe67618bd1143aa393832297f5dc30e558.yptEWKc5RAUY613Fwd5cQ0VIinMvpdoI6cuKgagAGxk
components-sentencelist--full-sentence--light:
diff --git a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
index c2f6cbc94111..4efd03fe39e4 100644
--- a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
+++ b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
@@ -25,7 +25,7 @@ When a change disagrees with this file, change this file in the same PR or don't
- `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 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. Settings are the exception: Command K reads `commandKSettingsItems` (levels, sections, and single settings, with their context), and the current palette keeps one row per section.
- 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
@@ -94,7 +94,9 @@ The input is always in exactly one mode, decided from the token under the cursor
- A search with words goes to the ranked search endpoint (`file_system/search/`). A search made only of filters goes to the list endpoint, because there are no words to rank.
- Sections, in this fixed order, covering everything the current palette finds:
1. **Results**: file system objects (insights, dashboards, feature flags, experiments, surveys, notebooks, cohorts, actions, early access features, replay playlists, data pipelines), and products. For a search with words, see [Ranked results](#ranked-results).
- 2. In-memory lists, filtered on every keystroke: **Data management**, **People**, **Health**, **Actions** (Log out, and Toggle terminal when the terminal is on), **Shortcuts** (with their key bindings), **Settings** (with a Dark mode / Light mode row for "dark", "light", "theme", "appearance"), **Create new**. For a search with words they keep only items that match every word with no typo. Products rank with the results instead. Settings that match every word with no typo also rank with the results, unless a product has the same name, and the **Settings** section lists only the ones that did not.
+ 2. In-memory lists, filtered on every keystroke: **Data management**, **People**, **Health**, **Actions** (Log out, and Toggle terminal when the terminal is on), **Shortcuts** (with their key bindings), **Settings** (with a Dark mode / Light mode row for "dark", "light", "theme", "appearance"), **Create new**. For a search with words they keep only items that match every word with no typo. Products rank with the results instead. Settings that match every word with no typo also rank with the results, unless a product has the same name and opens the same page. A setting can match a word in its name, a keyword, or its level and section (`rename project`, `project timezone`), as long as its name or a keyword holds one of the words. Matching settings rank with the results, and the **Settings** section lists only the ones that did not. When any setting ranks, the **Settings** section does not render, so a search shows one Settings group. The Dark mode / Light mode row ranks with the settings, and when the ranking leaves it out it still shows, at the top of the Settings group or in the **Settings** section. The Settings group count includes the settings held back for sharing a product's name. When the Settings group holds more settings than it shows, it ends with a **Show all N settings** row that expands the group in place and moves the highlight to the first new row. Any change to the query collapses the group again. A product tab with the same name (Workflows › Settings) does not hold a setting back, so "settings" finds the **Settings** page first.
+ - The settings rows come from the settings scene's own map (`SETTINGS_MAP`) and the same gates the scene applies (feature flags, realm, team, admin-only, staff-only, billing access, integrations), so search never shows a setting the scene hides. Sections hidden from the settings navigation stay out of search too.
+ - Rows: **Settings**, one landing row per level (**Project settings**, **Organization settings**, **User settings**), one row per section ("Billing" in Organization settings), and one row per setting with a readable title ("Date & time" in Project settings › Customization) that opens the section at that setting's anchor. A setting whose title matches its section's title, or whose section links to another page, folds into the section row.
3. Remote lists that the file system does not hold: **Events**, **Properties**, **Workflows** (one unified search request), **Accounts** (behind the customer analytics flag, excluding accounts already shown in ranked results), **Support tickets** (3+ characters or a ticket number).
4. **Ask PostHog AI**.
5. **Persons**, **Groups**. Person and group searches can take seconds, so they usually come last. The person search starts with the file system search, after 50 ms. A search that contains "@" waits for the person search and ranks the persons it finds with **Results** / **Best matches**. A person who matches every word comes first. Persons that do not rank stay in **Persons** below, with no duplicates. Other searches do not wait for persons or groups.
@@ -124,7 +126,7 @@ Results for a search with words follow ordered tie-breaking rules: words matched
- **Best matches** comes first: the three best results of different types.
- The other results follow in groups by type, each with its total count and up to three rows. A group ends with a **See all N <types>** row that adds the `is:` chip and keeps the words. A one-word search that starts a type name (`dash`, `flag`) moves that type's group up.
- Results with the same name show as one row with a "+N with this name" badge.
-- A short list (8 or fewer) or a list of one type shows flat, under one **Results** header.
+- A short list (8 or fewer) or a list of one type shows flat, under one **Results** header. A flat list of saved objects shows at most 20 rows and ends with its **See all N <types>** row. Products, settings, persons, and accounts have no **See all** row, so a flat list of one of those types shows every match.
- With an `is:` chip, results show as one flat list. The creator shows on rows that share a name.
- Some `is:` types are not file system objects, so the file system search cannot find them. `is:alert`, `is:ticket`, `is:workflow`, `is:endpoint`, and `is:product_tour` search their own API instead (`TYPE_SEARCHES` in `commandKSources.ts`): alerts, support tickets, and product tours through their list endpoint's `search=`, workflows and endpoints through the unified search API. Results keep the order the API returns, and the ranking keeps a result the API matched outside its name.
- `is:ticket` lists the most recently updated tickets with no search text. With text, it follows the **Support tickets** rule: 3+ characters or a ticket number (`42`, `#42`), because the ticket search also scans message text. The ticket API reads a numeric search as a ticket number, so a numeric `name:` value (`name:42`) is not sent. Command K sends the other words, or none, and keeps the tickets whose subject contains the value. With no other words it checks only the 20 most recently updated tickets. A ticket row shows its subject, then the number, the customer's name or email, and the status.
diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx
index 4f7f91b62d31..9e5d5ad8e785 100644
--- a/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx
+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchRow.tsx
@@ -1,7 +1,7 @@
import { useActions } from 'kea'
import { memo } from 'react'
-import { IconArrowRight, IconFilter, IconFolder, IconPerson, IconSparkles } from '@posthog/icons'
+import { IconArrowRight, IconChevronDown, IconFilter, IconFolder, IconPerson, IconSparkles } from '@posthog/icons'
import { Button, Skeleton, cn } from '@posthog/quill'
import { getIconForItem, getItemTypeDisplayName } from 'lib/components/Search/searchItemDisplay'
@@ -104,6 +104,13 @@ function RowContent({ row }: { row: CommandKRow }): JSX.Element | null {
<span className="truncate text-muted-foreground">{row.label}</span>
</>
)
+ case 'expand':
+ return (
+ <>
+ <IconChevronDown className="size-4 shrink-0 text-muted-foreground" />
+ <span className="truncate text-muted-foreground">{row.label}</span>
+ </>
+ )
default:
return null
}
@@ -126,6 +133,7 @@ const rowContent = (row: CommandKRow): unknown => {
case 'ask-ai':
return row.question
case 'scope':
+ case 'expand':
return row.label
case 'notice':
return row.key
diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts
index dfb488a8c7fe..b39d98b6bb14 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts
@@ -2,6 +2,7 @@ import { SearchItem } from 'lib/components/Search/searchItems'
import { buildRankedResults } from './commandKRankedResults'
import type { CommandKSection } from './commandKSections'
+import { RESULTS_LIMIT } from './commandKSources'
const result = (
id: string,
@@ -230,6 +231,21 @@ describe('buildRankedResults', () => {
],
},
+ {
+ name: 'with unified ranking, the app Settings row ranks above a product tab with the same name',
+ query: 'settings',
+ results: [],
+ products: [
+ {
+ ...product('Workflows Settings'),
+ displayName: 'Settings',
+ parentName: 'Workflows',
+ },
+ ],
+ settings: [{ id: 'settings', name: 'Settings', category: 'settings' }],
+ unifiedRanking: true,
+ expected: ['Results: Settings, Workflows Settings'],
+ },
{
name: 'with unified ranking, an account that matches only inside a word ranks below a name match',
query: 'stripe',
@@ -352,21 +368,90 @@ describe('buildRankedResults', () => {
unifiedRanking: true,
expected: ['Results: Metrics, Data catalog'],
},
- ])('$name', ({ query, results, products, persons = [], accounts = [], unifiedRanking = false, expected }) => {
- expect(
- summary(
- buildRankedResults({
- query,
- highlightWords: query.split(' '),
- results,
- products,
- persons,
- accounts,
- state: 'ready',
- scoped: false,
- unifiedRanking,
+ {
+ name: 'a flat list of one saved-object type that hits the cap ends with its see-all row',
+ query: 'revenue',
+ results: Array.from({ length: RESULTS_LIMIT + 5 }, (_, n) =>
+ result(`dashboard-${n}`, `Revenue ${n}`, 'dashboard', exactWordRank(100 - n), {
+ typeCount: RESULTS_LIMIT + 5,
+ })
+ ),
+ products: [],
+ expected: [
+ `Results: ${Array.from({ length: RESULTS_LIMIT }, (_, n) => `Revenue ${n}`).join(', ')}, (See all ${RESULTS_LIMIT + 5} dashboards)`,
+ ],
+ },
+ {
+ name: 'with unified ranking, a flat list of one saved-object type that hits the cap ends with its see-all row',
+ query: 'revenue',
+ results: Array.from({ length: RESULTS_LIMIT + 5 }, (_, n) =>
+ result(`dashboard-${n}`, `Revenue ${n}`, 'dashboard', exactWordRank(100 - n), {
+ typeCount: RESULTS_LIMIT + 5,
})
- )
- ).toEqual(expected)
- })
+ ),
+ products: [],
+ unifiedRanking: true,
+ expected: [
+ `Results: ${Array.from({ length: RESULTS_LIMIT }, (_, n) => `Revenue ${n}`).join(', ')}, (See all ${RESULTS_LIMIT + 5} dashboards)`,
+ ],
+ },
+ {
+ name: 'every product shows when products are the only match, past the flat list cap',
+ query: 'pricing',
+ results: [],
+ products: Array.from({ length: RESULTS_LIMIT + 2 }, (_, n) => product(`Pricing ${n}`)),
+ expected: [`Results: ${Array.from({ length: RESULTS_LIMIT + 2 }, (_, n) => `Pricing ${n}`).join(', ')}`],
+ },
+ {
+ name: 'with unified ranking, every product shows when products are the only match, past the flat list cap',
+ query: 'pricing',
+ results: [],
+ unifiedRanking: true,
+ products: Array.from({ length: RESULTS_LIMIT + 2 }, (_, n) => product(`Pricing ${n}`)),
+ expected: [`Results: ${Array.from({ length: RESULTS_LIMIT + 2 }, (_, n) => `Pricing ${n}`).join(', ')}`],
+ },
+ {
+ name: 'a broad query that matches only settings lists every match with no see-all row',
+ query: 'project settings',
+ results: [],
+ products: [],
+ settings: Array.from({ length: RESULTS_LIMIT + 5 }, (_, n) => ({
+ id: `settings-${n}`,
+ name: `Project settings ${n}`,
+ category: 'settings',
+ })),
+ expected: [
+ `Results: ${Array.from({ length: RESULTS_LIMIT + 5 }, (_, n) => `Project settings ${n}`).join(', ')}`,
+ ],
+ },
+ ])(
+ '$name',
+ ({
+ query,
+ results,
+ products,
+ persons = [],
+ accounts = [],
+ settings = [],
+ unifiedRanking = false,
+ expected,
+ }) => {
+ expect(
+ summary(
+ buildRankedResults({
+ query,
+ highlightWords: query.split(' '),
+ results,
+ products,
+ persons,
+ accounts,
+ settings,
+ state: 'ready',
+ scoped: false,
+ unifiedRanking,
+ })
+ )
+ ).toEqual(expected)
+ }
+ )
})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts
index 4cf02a89c2a5..cc0057d5e5d2 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts
@@ -16,6 +16,7 @@ import {
tokenTypos,
} from './commandKRanking'
import type { CommandKRow, CommandKSection } from './commandKSections'
+import { RESULTS_LIMIT } from './commandKSources'
const BEST_MATCHES_LIMIT = 3
const GROUP_LIMIT = 3
@@ -65,16 +66,27 @@ function rankLocalItems(items: SearchItem[], query: string, groupKey: string): R
function rankItems(items: SearchItem[], query: string, groupKey: string): RankedItem[] {
return items.flatMap((item) => {
- const ranked = rankLocalItem(
- query,
- String(item.displayName || item.name),
- item.searchKeywords,
- !!item.parentName
- )
+ const name = String(item.displayName || item.name)
+ const aliases =
+ groupKey === 'settings'
+ ? [
+ ...(item.searchKeywords ?? []),
+ [
+ name,
+ ...(item.searchKeywords ?? []),
+ item.parentName ?? '',
+ ...(item.contextKeywords ?? []),
+ ].join(' '),
+ ]
+ : item.searchKeywords
+ const ranked = rankLocalItem(query, name, aliases, !!item.parentName, groupKey === 'settings')
return ranked
? [
{
- item: ranked.matchedAlias ? { ...item, matchedSearchKeyword: ranked.matchedAlias } : item,
+ item:
+ ranked.matchedAlias && !item.hideMatchedKeyword
+ ? { ...item, matchedSearchKeyword: ranked.matchedAlias }
+ : item,
rank: ranked.rank,
groupKey,
},
@@ -117,18 +129,19 @@ function tierBoostFor(item: SearchItem, groupKey: string, query: string): number
}
function candidateFor(item: SearchItem, groupKey: string, query: string): RankCandidate {
+ const productTab = groupKey === 'products' && !!item.parentName
const common = {
name: displayName(item),
- typePrior: typePriorFor(groupKey, query),
+ typePrior: typePriorFor(productTab ? 'tabs' : groupKey, query),
identity: item.identityFields,
}
if (item.category !== 'results') {
return {
...common,
aliases: item.searchKeywords,
- context: item.parentName ? [item.parentName] : [],
+ context: [...(item.parentName ? [item.parentName] : []), ...(item.contextKeywords ?? [])],
indirect: !!item.parentName,
- tierBoost: tierBoostFor(item, groupKey, query),
+ tierBoost: productTab ? 0 : tierBoostFor(item, groupKey, query),
matchesQuery: IDENTITY_GROUPS.includes(groupKey),
}
}
@@ -151,7 +164,10 @@ function rankUnified(items: SearchItem[], query: string, groupKey: (item: Search
}
return [
{
- item: ranked.matchedAlias ? { ...item, matchedSearchKeyword: ranked.matchedAlias } : item,
+ item:
+ ranked.matchedAlias && !item.hideMatchedKeyword
+ ? { ...item, matchedSearchKeyword: ranked.matchedAlias }
+ : item,
rank: ranked.rank,
groupKey: key,
},
@@ -252,6 +268,40 @@ function noticeSection(
]
}
+const scopeSeeAll = (
+ groupKey: string,
+ total: number,
+ covered: number,
+ capped: boolean,
+ section: string
+): CommandKRow[] =>
+ !LOCAL_GROUPS.includes(groupKey) && total > covered
+ ? [
+ {
+ kind: 'scope',
+ key: `${section}/see-all`,
+ type: groupKey,
+ label: capped
+ ? `See all ${groupLabel(groupKey).toLowerCase()}`
+ : `See all ${total.toLocaleString()} ${groupLabel(groupKey).toLowerCase()}`,
+ },
+ ]
+ : []
+
+const nestingDepth = (item: SearchItem): number => (item.parentName ? item.parentName.split(' › ').length : 0)
+
+const shallowestFirst = <T extends RankedItem>(entries: T[]): T[] =>
+ entries
+ .map((entry, index) => ({ entry, index }))
+ .sort(
+ (a, b) =>
+ a.entry.rank[0] - b.entry.rank[0] ||
+ a.entry.rank[1] - b.entry.rank[1] ||
+ nestingDepth(a.entry.item) - nestingDepth(b.entry.item) ||
+ a.index - b.index
+ )
+ .map(({ entry }) => entry)
+
interface RankedResultsInput {
query: string
highlightWords: string[]
@@ -259,6 +309,8 @@ interface RankedResultsInput {
products: SearchItem[]
persons?: SearchItem[]
settings?: SearchItem[]
+ unrankedSettings?: SearchItem[]
+ expandedGroups?: string[]
accounts?: SearchItem[]
state: CommandKSection['state']
scoped: boolean
@@ -272,6 +324,8 @@ export function buildRankedResults({
products,
persons = [],
settings = [],
+ unrankedSettings = [],
+ expandedGroups = [],
accounts = [],
state,
scoped,
@@ -338,14 +392,37 @@ export function buildRankedResults({
const pool = collapseSameName(matching)
const groupCount = new Set(pool.map((entry) => entry.groupKey)).size
if (pool.length <= FLAT_LIST_LIMIT || groupCount === 1) {
+ const hasContinuation = !LOCAL_GROUPS.includes(pool[0].groupKey)
+ const shownPool = groupCount === 1 && !hasContinuation ? pool : pool.slice(0, RESULTS_LIMIT)
return [
...notices,
{
key: 'best-matches',
label: 'Results',
- rows: pool.map((entry) =>
- itemRow('flat', entry.item, highlightWords, entry.duplicates, entry.duplicates > 0, groupCount > 1)
- ),
+ rows: [
+ ...shownPool.map((entry) =>
+ itemRow(
+ 'flat',
+ entry.item,
+ highlightWords,
+ entry.duplicates,
+ entry.duplicates > 0,
+ groupCount > 1
+ )
+ ),
+ ...(groupCount === 1
+ ? scopeSeeAll(
+ pool[0].groupKey,
+ Math.max(
+ pool[0].item.searchMatch?.typeCount ?? 0,
+ pool.reduce((sum, entry) => sum + 1 + entry.duplicates, 0)
+ ),
+ shownPool.reduce((sum, entry) => sum + 1 + entry.duplicates, 0),
+ capped,
+ 'flat'
+ )
+ : []),
+ ],
state,
},
]
@@ -390,25 +467,31 @@ export function buildRankedResults({
groupKey !== 'products' &&
searchWords(groupLabel(groupKey)).some((word) => tokenTypos(queryWords[0], word) !== null)
const orderedGroups = [...groups].sort(([a], [b]) => Number(typeIntent(b)) - Number(typeIntent(a)))
- for (const [groupKey, entries] of orderedGroups) {
- const shown = entries.slice(0, GROUP_LIMIT)
+ for (const [groupKey, groupEntries] of orderedGroups) {
+ const expandable = groupKey === 'settings'
+ const entries = expandable ? shallowestFirst(groupEntries) : groupEntries
+ const expanded = expandable && expandedGroups.includes(groupKey)
+ const shown = expanded ? entries : entries.slice(0, GROUP_LIMIT)
const inBest = best.filter((entry) => entry.groupKey === groupKey)
const sample = entries[0] ?? inBest[0]
- const total = Math.max(sample.item.searchMatch?.typeCount ?? 0, entries.length + inBest.length)
- const rows: CommandKRow[] = shown.map((entry) =>
- itemRow(`group-${groupKey}`, entry.item, highlightWords, entry.duplicates, entry.duplicates > 0)
- )
+ const extra = expandable ? unrankedSettings : []
+ const total = Math.max(sample.item.searchMatch?.typeCount ?? 0, entries.length + inBest.length) + extra.length
+ const rows: CommandKRow[] = [
+ ...shown.map((entry) =>
+ itemRow(`group-${groupKey}`, entry.item, highlightWords, entry.duplicates, entry.duplicates > 0)
+ ),
+ ...(expanded ? extra.map((item) => itemRow(`group-${groupKey}`, item, highlightWords)) : []),
+ ]
const covered = inBest.length + shown.reduce((sum, entry) => sum + 1 + entry.duplicates, 0)
- if (!LOCAL_GROUPS.includes(groupKey) && total > covered) {
+ if (expandable && !expanded && total > covered) {
rows.push({
- kind: 'scope',
- key: `group-${groupKey}/see-all`,
- type: groupKey,
- label: capped
- ? `See all ${groupLabel(groupKey).toLowerCase()}`
- : `See all ${total.toLocaleString()} ${groupLabel(groupKey).toLowerCase()}`,
+ kind: 'expand',
+ key: `group-${groupKey}/expand`,
+ group: groupKey,
+ label: `Show all ${total.toLocaleString()} ${groupLabel(groupKey).toLowerCase()}`,
})
}
+ rows.push(...scopeSeeAll(groupKey, total, covered, capped, `group-${groupKey}`))
if (!rows.length) {
continue
}
diff --git a/frontend/src/lib/components/CommandKSearch/commandKRanking.ts b/frontend/src/lib/components/CommandKSearch/commandKRanking.ts
index 3680d9b0738f..e16e85311f4b 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKRanking.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKRanking.ts
@@ -3,7 +3,7 @@ const WORD = /[\p{L}\p{N}_]+/gu
export type RankKey = number[]
const MIN_ALIAS_QUERY_LENGTH = 3
-const MAX_LOCAL_QUERY_LENGTH = 200
+export const MAX_LOCAL_QUERY_LENGTH = 200
const STARTS_WITH = 1
export const searchWords = (text: string): string[] => text.toLowerCase().match(WORD) ?? []
@@ -165,7 +165,13 @@ interface LocalRank {
matchedAlias: string | null
}
-export function rankLocalItem(query: string, name: string, aliases: string[] = [], isTab = false): LocalRank | null {
+export function rankLocalItem(
+ query: string,
+ name: string,
+ aliases: string[] = [],
+ isTab = false,
+ shortQueryAliases = false
+): LocalRank | null {
const normalized = query.trim().toLowerCase().replace(/\s+/g, ' ').slice(0, MAX_LOCAL_QUERY_LENGTH)
const tokens = searchWords(normalized)
if (!tokens.length) {
@@ -176,7 +182,7 @@ export function rankLocalItem(query: string, name: string, aliases: string[] = [
if (byName) {
best = { rank: byName, matchedAlias: null }
}
- for (const alias of normalized.length >= MIN_ALIAS_QUERY_LENGTH ? aliases : []) {
+ for (const alias of shortQueryAliases || normalized.length >= MIN_ALIAS_QUERY_LENGTH ? aliases : []) {
const byAlias = rankName(normalized, tokens, alias, isTab ? 2 : 1)
if (byAlias && (!best || compareRanks(byAlias, best.rank) < 0)) {
best = { rank: byAlias, matchedAlias: alias }
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts
index a22103f840d4..28414ff93750 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts
@@ -1,6 +1,10 @@
+import { router } from 'kea-router'
+
+import { searchListsLogic } from 'lib/components/Search/searchListsLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import type { SettingSectionId } from '~/scenes/settings/types'
import { initKeaTests } from '~/test/init'
import { commandKSearchLogic } from './commandKSearchLogic'
@@ -21,13 +25,20 @@ describe('commandKSearchLogic', () => {
['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) => {
+ ])('a new query from %s drops the remembered highlight and collapses expanded groups', (_, changeQuery) => {
logic.actions.setChipsAndText([{ key: 'is', value: 'dashboard', label: 'Dashboard', negated: false }], 'rev', 3)
logic.actions.setHighlightedKey('recents/dashboard:1')
+ logic.actions.activateRow(
+ { kind: 'expand', key: 'group-settings/expand', group: 'settings', label: 'Show all 11 settings' },
+ false,
+ 'enter'
+ )
+ expect(logic.values.expandedGroups).toEqual(['settings'])
changeQuery()
expect(logic.values.highlightedKey).toBeNull()
+ expect(logic.values.expandedGroups).toEqual([])
})
test.each([
@@ -107,4 +118,66 @@ describe('commandKSearchLogic', () => {
expect(logic.values.chips).toEqual([expect.objectContaining({ key: 'is', value: 'insight', negated: false })])
expect(logic.values.text).toEqual('revenue')
})
+
+ it('moves the highlight to the first new setting when a Show all row from an earlier render is clicked', () => {
+ searchListsLogic({ commandPalette: true }).actions.setSettingsMap(
+ Array.from({ length: 10 }, (_, index) => ({
+ id: `user-zebra-${index}` as SettingSectionId,
+ level: 'user' as const,
+ title: `Zebra ${index}`,
+ settings: [],
+ }))
+ )
+ logic.actions.inputChanged('zebra', 5, false)
+ const query = logic.values.remoteQueries.results as string
+ logic.actions.remoteLoaded(query, {
+ results: [
+ {
+ id: 'dashboard-1',
+ name: 'Zebra board',
+ category: 'results',
+ record: { type: 'dashboard', ref: '1' },
+ rankKey: [-1, 0, 0, 0, -1, 0, 1, 0, 0],
+ },
+ ],
+ })
+ const renderedRow = logic.values.selectableRows.find((row) => row.kind === 'expand')
+ expect(renderedRow).toBeTruthy()
+ const index = logic.values.selectableRows.indexOf(renderedRow!)
+
+ logic.actions.remoteLoaded(query, { persons: [] })
+ expect(logic.values.selectableRows).not.toContain(renderedRow)
+ logic.actions.activateRow(renderedRow!, false, 'click')
+
+ const revealed = logic.values.selectableRows[index]
+ expect(revealed).toMatchObject({ kind: 'item', item: { category: 'settings' } })
+ expect(logic.values.highlightedKey).toBe(revealed.key)
+ })
+
+ it('scrolls back to a setting when its result is opened on the page that already shows it', () => {
+ router.actions.push('/settings/project-customization#base-currency')
+ const heading = document.createElement('h2')
+ heading.id = 'base-currency'
+ heading.scrollIntoView = jest.fn()
+ document.body.appendChild(heading)
+
+ logic.actions.activateRow(
+ {
+ kind: 'item',
+ key: 'group-settings/settings-project-customization-base-currency',
+ section: 'settings',
+ item: {
+ id: 'settings-project-customization-base-currency',
+ name: 'Base currency',
+ category: 'settings',
+ href: '/settings/project-customization#base-currency',
+ },
+ },
+ false,
+ 'enter'
+ )
+
+ expect(heading.scrollIntoView).toHaveBeenCalled()
+ heading.remove()
+ })
})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx
index f568ec1c6b6b..f9e37511344b 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx
+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx
@@ -10,6 +10,7 @@ import {
reducers,
selectors,
} from 'kea'
+import { router } from 'kea-router'
import api from 'lib/api'
import { commandLogic } from 'lib/components/Command/commandLogic'
@@ -21,6 +22,7 @@ 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 { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { navigateToHref } from 'lib/utils/navigateToHref'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { teamLogic } from 'scenes/teamLogic'
@@ -125,6 +127,7 @@ export interface commandKSearchLogicValues {
query: SectionsQuery
stale: boolean
}
+ expandedGroups: string[]
filterOptions: FilterOptions
folders: FileSystemEntry[] | null
highlightIsFilterRow: boolean
@@ -227,6 +230,9 @@ export interface commandKSearchLogicActions {
editChip: (index: number) => {
index: number
}
+ expandGroup: (group: string) => {
+ group: string
+ }
foldersLoaded: (folders: FileSystemEntry[]) => {
folders: FileSystemEntry[]
}
@@ -371,7 +377,8 @@ export interface commandKSearchLogicMeta {
stale: boolean
},
featureFlags: FeatureFlagsSet,
- searchCorrection: SearchCorrection | null
+ searchCorrection: SearchCorrection | null,
+ expandedGroups: string[]
) => CommandKSection[]
selectableRows: (sections: CommandKSection[]) => CommandKRow[]
highlightedRow: (selectableRows: CommandKRow[], highlightedKey: string | null) => CommandKRow | null
@@ -395,6 +402,14 @@ const asLiteralPanelPrompt = (question: string): string => ` ${question}`
* 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.
*/
+const scrollToAnchorOnCurrentPage = (href: string): void => {
+ const [path, anchor] = href.split('#')
+ const { pathname, hash } = router.values.location
+ if (anchor && hash === `#${anchor}` && removeProjectIdIfPresent(pathname) === removeProjectIdIfPresent(path)) {
+ document.getElementById(anchor)?.scrollIntoView()
+ }
+}
+
export const commandKSearchLogic = kea<commandKSearchLogicType>([
path(['lib', 'components', 'CommandKSearch', 'commandKSearchLogic']),
connect(() => ({
@@ -405,7 +420,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
[
'starredItems',
'productsItems',
- 'settingsItems',
+ 'commandKSettingsItems as settingsItems',
'newItems',
'dataManagementItems',
'peopleItems',
@@ -453,6 +468,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
applyKeyIntent: (intent: KeyIntent) => ({ intent }),
moveHighlight: (direction: 1 | -1) => ({ direction }),
setHighlightedKey: (key: string | null) => ({ key }),
+ expandGroup: (group: string) => ({ group }),
activateRow: (row: CommandKRow, newTab: boolean, via: CommitVia) => ({ row, newTab, via }),
completeHighlighted: true,
askAi: true,
@@ -500,6 +516,13 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
setChipsAndText: () => null,
},
],
+ expandedGroups: [
+ [] as string[],
+ {
+ expandGroup: (state, { group }) => (state.includes(group) ? state : [...state, group]),
+ setChipsAndText: () => [],
+ },
+ ],
// The query each request last asked for. No selector reads it, so starting a request never re-renders.
requestedQueries: [
{} as Record<string, string>,
@@ -754,6 +777,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
s.displayedQuery,
s.featureFlags,
s.searchCorrection,
+ s.expandedGroups,
],
(
mode: CommandKMode,
@@ -763,7 +787,8 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
remote: RemoteSlots,
displayed: { query: SectionsQuery; stale: boolean },
featureFlags: FeatureFlagsSet,
- searchCorrection: SearchCorrection | null
+ searchCorrection: SearchCorrection | null,
+ expandedGroups: string[]
): CommandKSection[] => {
const unifiedRanking =
freeWords(displayed.query.remoteQueries.results ?? '').length > 0 &&
@@ -778,6 +803,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
stale: displayed.stale,
personsFirst: !!displayed.query.remoteQueries.persons?.includes('@'),
unifiedRanking,
+ expandedGroups,
searchCorrection:
searchCorrection &&
(displayed.query.remoteQueries.results ?? displayed.query.localQuery).endsWith(
@@ -895,6 +921,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
} else if (item?.href && newTab) {
newInternalTab(item.href)
} else if (item?.href) {
+ scrollToAnchorOnCurrentPage(item.href)
navigateToHref(item.href)
}
}
@@ -1097,6 +1124,13 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([
context.kind === 'value' ? context.token : null,
via
)
+ } else if (row.kind === 'expand') {
+ const index = values.selectableRows.findIndex((candidate) => candidate.key === row.key)
+ actions.expandGroup(row.group)
+ const next = values.selectableRows[index]
+ if (next) {
+ actions.setHighlightedKey(next.key)
+ }
} else if (row.kind === 'scope') {
const option = values.filterOptions.is.find((candidate) => candidate.value === row.type)
actions.commitChip(
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
index 28c6391b86b1..8f62c668159c 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
@@ -11,6 +11,7 @@ import {
emptyRemoteSlots,
pickDisplayedQuery,
resultsSettled,
+ themeSearchItem,
} from './commandKSections'
import { RESULTS_LIMIT } from './commandKSources'
@@ -420,37 +421,308 @@ describe('buildSections', () => {
})
test.each([
- ['no product shares its name', 'Personal API keys', ['best-matches'], 'Personal API keys'],
- ['a product has its name', 'API keys', ['best-matches', 'settings'], 'API keys'],
- ])('ranks an exact-match setting with the results when %s', (_, settingName, keys, first) => {
- const setting: SearchItem = {
- id: 'settings-api-keys',
- name: `User: ${settingName} (api keys)`,
- displayName: settingName,
- category: 'settings',
+ ['no product shares its name', 'api keys', 'Personal API keys', [], ['best-matches'], 'settings-item'],
+ [
+ 'a product has its name',
+ 'api keys',
+ 'API keys',
+ [{ id: 'product-api-keys', name: 'API keys', category: 'products' }],
+ ['best-matches', 'settings'],
+ 'product-api-keys',
+ ],
+ [
+ 'only a product tab has its name',
+ 'settings',
+ 'Settings',
+ [
+ {
+ id: 'product-Workflows-tab-Settings',
+ name: 'Workflows Settings',
+ displayName: 'Settings',
+ parentName: 'Workflows',
+ category: 'tabs',
+ },
+ ],
+ ['best-matches'],
+ 'settings-item',
+ ],
+ ] as [string, string, string, SearchItem[], string[], string][])(
+ 'ranks an exact-match setting with the results when %s',
+ (_, search, settingName, products, keys, first) => {
+ const setting: SearchItem = {
+ id: 'settings-item',
+ name: settingName,
+ displayName: settingName,
+ category: 'settings',
+ }
+ const remote = emptyRemoteSlots()
+ remote.results = {
+ cache: {
+ [search]: [{ ...dashboard('a', '1'), name: 'Ada board', rankKey: [-1, 0, 0, 0, -1, 0, 1, 0, 0] }],
+ },
+ }
+ const sections = buildSections(
+ input('search', {
+ local: { ...emptyLocal(), settings: [setting], products },
+ remote,
+ remoteQueries: { results: search },
+ localQuery: search,
+ })
+ )
+
+ expect(sections.map((section) => section.key)).toEqual(keys)
+ const firstItem = sections[0].rows[0]
+ expect(firstItem.kind === 'item' ? firstItem.item.id : null).toBe(first)
}
- const products: SearchItem[] =
- settingName === 'API keys' ? [{ id: 'product-api-keys', name: 'API keys', category: 'products' }] : []
- const remote = emptyRemoteSlots()
- remote.results = {
- cache: {
- 'api keys': [{ ...dashboard('a', '1'), name: 'Ada board', rankKey: [-1, 0, 0, 0, -1, 0, 1, 0, 0] }],
- },
+ )
+
+ test.each([
+ [false, []],
+ [true, []],
+ [false, ['Theme']],
+ [true, ['Theme']],
+ ] as [boolean, string[]][])(
+ 'keeps the theme shortcut next to a dashboard that matches every word, unified ranking %s, settings %j',
+ (unifiedRanking, settingNames) => {
+ const themeItem = themeSearchItem('dark theme', false, { setTheme: jest.fn(), toggleTheme: jest.fn() })
+ const settings: SearchItem[] = settingNames.map((name) => ({
+ id: `settings-${name}`,
+ name,
+ category: 'settings',
+ searchKeywords: ['dark theme'],
+ }))
+ const remote = emptyRemoteSlots()
+ remote.results = {
+ cache: {
+ 'dark theme': [
+ { ...dashboard('a', '1'), name: 'Dark theme adoption', rankKey: [-2, 0, 0, 0, -2, 0, 1, 0, 0] },
+ ],
+ },
+ }
+ const sections = buildSections(
+ input('search', {
+ local: { ...emptyLocal(), settings },
+ remote,
+ remoteQueries: { results: 'dark theme' },
+ localQuery: 'dark theme',
+ themeItem,
+ unifiedRanking,
+ })
+ )
+
+ const rows = sections.flatMap((section) => section.rows)
+ expect(rows.some((row) => row.kind === 'item' && row.item.id === themeItem?.id)).toBe(true)
+ expect(sections.filter((section) => section.label === 'Settings').length).toBeLessThanOrEqual(1)
+ }
+ )
+
+ test.each([
+ [false, false],
+ [true, false],
+ [false, true],
+ [true, true],
+ ])(
+ 'shows one Settings group that expands to every match, unified ranking %s, expanded %s',
+ (unifiedRanking, expanded) => {
+ const settings: SearchItem[] = [
+ ...Array.from({ length: 10 }, (_, index) => ({
+ id: `settings-${index}`,
+ name: `Settings ${index}`,
+ displayName: `Settings ${index}`,
+ category: 'settings',
+ })),
+ { id: 'settings-shared', name: 'Shared settings', category: 'settings' },
+ ]
+ const products: SearchItem[] = [{ id: 'product-shared', name: 'Shared settings', category: 'products' }]
+ const remote = emptyRemoteSlots()
+ remote.results = {
+ cache: {
+ settings: [
+ { ...dashboard('a', '1'), name: 'Settings board', rankKey: [-1, 0, 0, 0, -1, 0, 1, 0, 0] },
+ ],
+ },
+ }
+ const sections = buildSections(
+ input('search', {
+ local: { ...emptyLocal(), settings, products },
+ remote,
+ remoteQueries: { results: 'settings' },
+ localQuery: 'settings',
+ unifiedRanking,
+ expandedGroups: expanded ? ['settings'] : [],
+ })
+ )
+
+ const settingsSections = sections.filter((section) => section.label === 'Settings')
+ expect(settingsSections).toHaveLength(1)
+ expect(settingsSections[0].count).toBe(11)
+ const settingRowIds = sections.flatMap((section) =>
+ section.rows.flatMap((row) =>
+ row.kind === 'item' && row.item.category === 'settings' ? [row.item.id] : []
+ )
+ )
+ const expandRows = settingsSections[0].rows.filter((row) => row.kind === 'expand')
+ expect([settingRowIds.length, expandRows]).toEqual(
+ expanded
+ ? [11, []]
+ : [
+ 4,
+ [
+ {
+ kind: 'expand',
+ key: 'group-settings/expand',
+ group: 'settings',
+ label: 'Show all 11 settings',
+ },
+ ],
+ ]
+ )
}
+ )
+
+ const SETTING_ROWS: SearchItem[] = [
+ {
+ id: 'settings-level-user',
+ name: 'User settings',
+ category: 'settings',
+ searchKeywords: ['account settings', 'personal settings', 'my settings'],
+ href: '/settings/user',
+ },
+ {
+ id: 'settings-user-api-keys',
+ name: 'Personal API keys',
+ category: 'settings',
+ parentName: 'User settings',
+ href: '/settings/user-api-keys',
+ },
+ {
+ id: 'settings-project-max',
+ name: 'PostHog AI',
+ category: 'settings',
+ parentName: 'Project settings',
+ href: '/settings/project-max',
+ },
+ {
+ id: 'settings-project-customization-custom-bots',
+ name: 'Custom bots',
+ category: 'settings',
+ parentName: 'Project settings › Customization',
+ searchKeywords: ['ai', 'user agent'],
+ href: '/settings/project-customization#custom-bots',
+ },
+ {
+ id: 'settings-project-surveys',
+ name: 'Surveys',
+ category: 'settings',
+ parentName: 'Project settings',
+ href: '/settings/project-surveys',
+ },
+ {
+ id: 'settings-project-surveys-appearance',
+ name: 'Default survey appearance',
+ category: 'settings',
+ parentName: 'Project settings › Surveys',
+ href: '/settings/project-surveys#appearance',
+ },
+ {
+ id: 'settings-project-customization-display-name',
+ name: 'Project details',
+ category: 'settings',
+ parentName: 'Project settings › Customization',
+ searchKeywords: ['rename'],
+ href: '/settings/project-customization#display-name',
+ },
+ {
+ id: 'settings-project-customization-date-and-time',
+ name: 'Date & time',
+ category: 'settings',
+ parentName: 'Project settings › Customization',
+ searchKeywords: ['timezone'],
+ href: '/settings/project-customization#date-and-time',
+ },
+ ]
+
+ test.each(
+ [
+ ['surveys', 'settings-project-surveys'],
+ ['rename project', 'settings-project-customization-display-name'],
+ ['project timezone', 'settings-project-customization-date-and-time'],
+ ['ai', 'settings-project-customization-custom-bots'],
+ ['personal user settings', 'settings-level-user'],
+ ].flatMap(([query, id]) => [
+ [query, id, false],
+ [query, id, true],
+ ]) as [string, string, boolean][]
+ )('finds the setting for %s (%s), unified ranking %s', (query, id, unifiedRanking) => {
+ const products: SearchItem[] = [
+ { id: 'product-surveys', name: 'Surveys', category: 'products', href: '/surveys' },
+ ]
+ const remote = emptyRemoteSlots()
+ remote.results = { cache: { [query]: [] } }
const sections = buildSections(
input('search', {
- local: { ...emptyLocal(), settings: [setting], products },
+ local: { ...emptyLocal(), settings: SETTING_ROWS, products },
remote,
- remoteQueries: { results: 'api keys' },
- localQuery: 'api keys',
+ remoteQueries: { results: query },
+ localQuery: query,
+ unifiedRanking,
})
)
- expect(sections.map((section) => section.key)).toEqual(keys)
- const firstItem = sections[0].rows[0]
- expect(firstItem.kind === 'item' ? String(firstItem.item.displayName || firstItem.item.name) : null).toBe(first)
+ const ids = sections.flatMap((section) =>
+ section.rows.flatMap((row) => (row.kind === 'item' ? [row.item.id] : []))
+ )
+ expect(ids).toContain(id)
+ expect(sections.filter((section) => section.label === 'Settings').length).toBeLessThanOrEqual(1)
})
+ test.each([false, true])(
+ 'lists the level landing rows before a nested setting named Settings, unified ranking %s',
+ (unifiedRanking) => {
+ const setting = (id: string, name: string, parentName?: string): SearchItem => ({
+ id,
+ name,
+ displayName: name,
+ category: 'settings',
+ ...(parentName ? { parentName } : {}),
+ })
+ const settings: SearchItem[] = [
+ setting('settings', 'Settings'),
+ setting('settings-activity', 'Settings', 'Project settings › Activity logs'),
+ setting('settings-level-user', 'User settings'),
+ setting('settings-level-project', 'Project settings'),
+ setting('settings-level-organization', 'Organization settings'),
+ ...['Alpha', 'Beta', 'Gamma', 'Delta'].map((name) =>
+ setting(`settings-${name}`, `${name} settings`, 'Project settings')
+ ),
+ ]
+ const remote = emptyRemoteSlots()
+ remote.results = {
+ cache: {
+ settings: [
+ { ...dashboard('a', '1'), name: 'Settings board', rankKey: [-1, 0, 0, 0, -1, 0, 1, 0, 0] },
+ ],
+ },
+ }
+ const sections = buildSections(
+ input('search', {
+ local: { ...emptyLocal(), settings },
+ remote,
+ remoteQueries: { results: 'settings' },
+ localQuery: 'settings',
+ unifiedRanking,
+ })
+ )
+
+ const group = sections.find((section) => section.key === 'group-settings')
+ expect(group?.rows.slice(0, 3).map((row) => (row.kind === 'item' ? row.item.id : row.kind))).toEqual([
+ 'settings-level-user',
+ 'settings-level-project',
+ 'settings-level-organization',
+ ])
+ }
+ )
+
it('with unified ranking, a pasted snake_case name ranks its matching setting first', () => {
const setting: SearchItem = {
id: 'settings-api-keys',
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.ts
index 6d4d4ada8565..e18c173e90ad 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSections.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.ts
@@ -4,7 +4,14 @@ import { SETTINGS_THEME_ITEM_ID, filterSearchItems } from 'lib/components/Search
import type { SearchCorrection } from './commandKCorrection'
import { CursorContext, FilterDefinition, FilterOptions, ValueOption, matchValueOptions } from './commandKQuery'
import { buildRankedResults } from './commandKRankedResults'
-import { FILTER_TOKEN, freeWords, strictLocalMatches } from './commandKRanking'
+import {
+ FILTER_TOKEN,
+ MAX_LOCAL_QUERY_LENGTH,
+ freeWords,
+ searchWords,
+ strictLocalMatches,
+ tokenTypos,
+} from './commandKRanking'
import { REMOTE_SOURCES, RESULTS_LIMIT, RemoteSource, SECONDARY_LIMIT } from './commandKSources'
export const RECENTS_LIMIT = 5
@@ -59,6 +66,7 @@ export type CommandKRow =
}
| { kind: 'ask-ai'; key: string; question: string }
| { kind: 'scope'; key: string; type: string; label: string }
+ | { kind: 'expand'; key: string; group: string; label: string }
| { kind: 'notice'; key: string; reason: 'partial' | 'typos' | 'corrected'; missing: string[]; shown: string[] }
| { kind: 'loading-more'; key: string }
@@ -237,6 +245,7 @@ export interface SectionsInput extends SectionsQuery {
personsFirst: boolean
unifiedRanking: boolean
searchCorrection: SearchCorrection | null
+ expandedGroups?: string[]
}
const isRanked = (query: SectionsQuery): boolean =>
@@ -263,6 +272,29 @@ export function pickDisplayedQuery(
const exactSettingsMatches = (settings: SearchItem[], localQuery: string): SearchItem[] =>
localQuery ? matchLocal('settings', settings, localQuery, true) : []
+const matchesWord = (words: string[]) => (token: string) => words.some((word) => tokenTypos(token, word) === 0)
+
+function settingsMatches(items: SearchItem[], fullQuery: string): SearchItem[] {
+ const query = fullQuery.trim().replace(/\s+/g, ' ').slice(0, MAX_LOCAL_QUERY_LENGTH)
+ const tokens = searchWords(query)
+ if (!tokens.length) {
+ return []
+ }
+ const byNameOrAlias = strictLocalMatches(items, query)
+ const named = new Set(byNameOrAlias.map((item) => item.id))
+ const acrossFields = items.filter((item) => {
+ if (named.has(item.id)) {
+ return false
+ }
+ const own = matchesWord(
+ [String(item.displayName || item.name), ...(item.searchKeywords ?? [])].flatMap(searchWords)
+ )
+ const context = matchesWord([item.parentName ?? '', ...(item.contextKeywords ?? [])].flatMap(searchWords))
+ return tokens.some(own) && tokens.every((token) => own(token) || context(token))
+ })
+ return [...byNameOrAlias, ...acrossFields]
+}
+
const LOCAL_MATCH_CACHE_SIZE = 50
const localMatchCache = new WeakMap<SearchItem[], Map<string, SearchItem[]>>()
@@ -278,8 +310,14 @@ function matchLocal(source: LocalSource, items: SearchItem[], query: string, ran
if (cached) {
return cached
}
- const fuzzy = source === 'create' ? filterNewItems(items, query) : filterSearchItems(items, query)
- const matches = strict ? strictLocalMatches(fuzzy, query) : fuzzy
+ const fuzzy = (): SearchItem[] =>
+ source === 'create' ? filterNewItems(items, query) : filterSearchItems(items, query)
+ const matches =
+ strict && source === 'settings'
+ ? settingsMatches(items, query)
+ : strict
+ ? strictLocalMatches(fuzzy(), query)
+ : fuzzy()
if (byQuery.size >= LOCAL_MATCH_CACHE_SIZE) {
byQuery.delete(byQuery.keys().next().value!)
}
@@ -310,8 +348,12 @@ export const settingsQuery = (localQuery: string, unifiedRanking: boolean): stri
unifiedRanking ? localQuery.replace(/_/g, ' ') : localQuery
export function rankableSettings(local: LocalLists, localQuery: string): SearchItem[] {
- const productNames = new Set(local.products.map(plainName))
- return exactSettingsMatches(local.settings, localQuery).filter((item) => !productNames.has(plainName(item)))
+ const productDestinations = new Set(
+ local.products.filter((item) => !item.parentName).map((item) => `${plainName(item)}|${item.href ?? ''}`)
+ )
+ return exactSettingsMatches(local.settings, localQuery).filter(
+ (item) => !productDestinations.has(`${plainName(item)}|${item.href ?? ''}`)
+ )
}
function rankedResultsSections(
@@ -322,15 +364,23 @@ function rankedResultsSections(
state: CommandKSection['state'],
persons: SearchItem[],
accounts: SearchItem[],
- unifiedRanking: boolean
+ unifiedRanking: boolean,
+ themeItem: SearchItem | null,
+ expandedGroups: string[]
): CommandKSection[] {
const words = freeWords(query)
+ const rankedSettingsQuery = settingsQuery(localQuery, unifiedRanking)
+ const rankable = rankableSettings(local, rankedSettingsQuery)
// The unified scorer reads punctuation, so a domain or an email address keeps it.
const freeText = query.replace(FILTER_TOKEN, ' ').replace(/\s+/g, ' ').trim()
return buildRankedResults({
persons,
accounts,
- settings: rankableSettings(local, settingsQuery(localQuery, unifiedRanking)),
+ settings: [...(themeItem ? [themeItem] : []), ...rankable],
+ unrankedSettings: exactSettingsMatches(local.settings, rankedSettingsQuery).filter(
+ (item) => !rankable.some((ranked) => ranked.id === item.id)
+ ),
+ expandedGroups,
query: unifiedRanking ? freeText : words.join(' '),
highlightWords: words,
results,
@@ -345,7 +395,8 @@ function lowerSections(
input: SectionsInput,
ranked: boolean,
state: CommandKSection['state'],
- shown: Set<string>
+ shown: Set<string>,
+ settingsRanked: boolean
): CommandKSection[] {
const { local, remote, remoteQueries, localQuery } = input
const sections: (CommandKSection | null)[] = []
@@ -374,11 +425,15 @@ function lowerSections(
}
if (localQuery) {
for (const source of LOCAL_SOURCES) {
- if (ranked && source === 'products') {
+ const themeItem =
+ source === 'settings' && input.themeItem && !shown.has(input.themeItem.id) ? input.themeItem : null
+ if (ranked && (source === 'products' || (source === 'settings' && settingsRanked && !themeItem))) {
continue
}
- const filtered = matchLocal(source, local[source], localQuery, ranked).filter((item) => !shown.has(item.id))
- const themeItem = source === 'settings' ? input.themeItem : null
+ const filtered =
+ ranked && source === 'settings' && settingsRanked
+ ? []
+ : matchLocal(source, local[source], localQuery, ranked).filter((item) => !shown.has(item.id))
const rows = themeItem
? itemRows(source, [themeItem, ...filtered], SECONDARY_LIMIT + 1)
: itemRows(source, filtered, SECONDARY_LIMIT)
@@ -488,7 +543,9 @@ function buildSectionsForQuery(input: SectionsInput): CommandKSection[] {
state,
leadingPersons,
accountsQuery ? remote.accounts.cache[accountsQuery] : [],
- input.unifiedRanking
+ input.unifiedRanking,
+ input.themeItem,
+ input.expandedGroups ?? []
)
sections.push(
...(rankedSections.some((section) => section.key === 'results')
@@ -501,12 +558,41 @@ function buildSectionsForQuery(input: SectionsInput): CommandKSection[] {
sections.push(withViewAll(results ? remoteSection('results', results, state) : null, input.viewAll))
}
if (mode !== 'value') {
+ const themeItem = input.themeItem
+ const settingsGroupIndex = sections.findIndex((section) => section?.key === 'group-settings')
+ const settingsGroup = sections[settingsGroupIndex]
+ if (
+ ranked &&
+ themeItem &&
+ settingsGroup &&
+ !sections.some((section) =>
+ section?.rows.some((row) => row.kind === 'item' && row.item.id === themeItem.id)
+ )
+ ) {
+ sections[settingsGroupIndex] = {
+ ...settingsGroup,
+ rows: [
+ {
+ kind: 'item',
+ key: `group-settings/${themeItem.id}`,
+ item: themeItem,
+ section: 'settings',
+ ranked: true,
+ highlightWords: freeWords(localQuery),
+ },
+ ...settingsGroup.rows,
+ ],
+ }
+ }
const shown = new Set(
sections.flatMap(
(section) => section?.rows.flatMap((row) => (row.kind === 'item' ? [row.item.id] : [])) ?? []
)
)
- sections.push(...lowerSections(input, ranked, state, shown))
+ const settingsRanked = sections.some(
+ (section) => section?.rows.some((row) => row.kind === 'item' && row.item.category === 'settings') ?? false
+ )
+ sections.push(...lowerSections(input, ranked, state, shown, settingsRanked))
}
return sections.filter((section): section is CommandKSection => section !== null)
}
diff --git a/frontend/src/lib/components/Search/searchItems.tsx b/frontend/src/lib/components/Search/searchItems.tsx
index 5801e7a2e921..128bf13d0b72 100644
--- a/frontend/src/lib/components/Search/searchItems.tsx
+++ b/frontend/src/lib/components/Search/searchItems.tsx
@@ -45,7 +45,9 @@ export interface SearchItem {
identityFields?: string[]
isCurated?: boolean
matchedSearchKeyword?: string | null
+ hideMatchedKeyword?: boolean
parentName?: string
+ contextKeywords?: string[]
record?: Record<string, unknown>
rank?: number | null // PostgreSQL full-text search rank (from unified search API)
rankKey?: number[]
diff --git a/frontend/src/lib/components/Search/searchListItems.tsx b/frontend/src/lib/components/Search/searchListItems.tsx
index fa6db1e1e662..ea0f12f0a1a3 100644
--- a/frontend/src/lib/components/Search/searchListItems.tsx
+++ b/frontend/src/lib/components/Search/searchListItems.tsx
@@ -16,7 +16,7 @@ import { isDefinitionsTabHref } from '~/layout/panel-layout/navbar/tabs/navProdu
import { getDefaultTreePersons } from '~/layout/panel-layout/ProjectTree/defaultTree'
import { getTreeItemsMetadata, getTreeItemsNew, getTreeItemsProducts } from '~/products'
import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'
-import type { SettingSection, SettingSectionId } from '~/scenes/settings/types'
+import type { SettingId, SettingLevelId, SettingSection, SettingSectionId } from '~/scenes/settings/types'
import { ActivityTab } from '~/types'
import { SearchItem, fileSystemEntryToSearchItem } from './searchItems'
@@ -425,3 +425,149 @@ export const settingsSearchItems = (sections: SettingsSectionSummary[], gates: S
}
return [...items.values()]
}
+
+export interface CommandKSettingsSection {
+ id: SettingSectionId
+ level: Exclude<SettingLevelId, 'environment'>
+ titleString: string | null
+ to?: string
+ keywords?: string[]
+ settings: {
+ id: SettingId
+ titleString: string | null
+ descriptionString: string | null
+ keywords?: string[]
+ }[]
+}
+
+const LEVEL_SEARCH_KEYWORDS: Partial<Record<CommandKSettingsSection['level'], string[]>> = {
+ user: ['account settings', 'personal settings', 'my settings'],
+}
+
+const settingsItem = (
+ id: string,
+ name: string,
+ href: string,
+ record: Record<string, unknown>,
+ fields: Partial<SearchItem> = {}
+): SearchItem => ({
+ id,
+ name,
+ displayName: name,
+ category: 'settings',
+ href,
+ itemType: 'settings',
+ hideMatchedKeyword: true,
+ record: { type: 'settings', ...record },
+ ...fields,
+})
+
+const settingsLevelName = (level: SettingLevelId): string =>
+ `${toSentenceCase(level === 'environment' ? 'project' : level)} settings`
+
+const settingsContextText = (level: SettingLevelId, sectionTitle: string): string =>
+ `${settingsLevelName(level)} ${sectionTitle}`
+
+interface SettingSearchTextSetting {
+ id: string
+ title: string | null
+ keywords?: string[]
+ description?: string | null
+}
+
+const settingsSearchText = (
+ level: SettingLevelId,
+ sectionTitle: string,
+ sectionKeywords: string[] | undefined,
+ settings: SettingSearchTextSetting[]
+): string =>
+ [
+ settingsContextText(level, sectionTitle),
+ ...(sectionKeywords ?? []),
+ ...settings.flatMap((setting) => [
+ setting.title ?? sentenceCaseId(setting.id),
+ sentenceCaseId(setting.id),
+ ...(setting.keywords ?? []),
+ setting.description ?? '',
+ ]),
+ ]
+ .filter(Boolean)
+ .join(' ')
+
+type SettingSummary = CommandKSettingsSection['settings'][number]
+
+const textSetting = (setting: SettingSummary): SettingSearchTextSetting => ({
+ id: setting.id,
+ title: setting.titleString,
+ keywords: setting.keywords,
+ description: setting.descriptionString,
+})
+
+const commandKSectionSearchItems = (section: CommandKSettingsSection, billingEntryUrl: string | null): SearchItem[] => {
+ const levelName = settingsLevelName(section.level)
+ const title = section.titleString ?? sentenceCaseId(section.id)
+ const context = settingsContextText(section.level, title)
+ const ownsSettings = !section.to
+ const settingTitle = (setting: SettingSummary): string => setting.titleString ?? sentenceCaseId(setting.id)
+ const isOwnItem = (setting: SettingSummary): boolean =>
+ ownsSettings && settingTitle(setting).toLowerCase() !== title.toLowerCase()
+ const folded = section.settings.filter((setting) => !isOwnItem(setting))
+ const sectionItem = settingsItem(
+ `settings-${section.id}`,
+ title,
+ (section.id === 'organization-billing' && billingEntryUrl) || section.to || urls.settings(section.id),
+ { level: section.level, sectionId: section.id },
+ {
+ parentName: levelName,
+ searchKeywords: [
+ context,
+ ...(section.keywords ?? []),
+ ...folded.flatMap((setting) => [sentenceCaseId(setting.id), ...(setting.keywords ?? [])]),
+ ],
+ hiddenSearchText: settingsSearchText(section.level, title, section.keywords, folded.map(textSetting)),
+ }
+ )
+ return [
+ sectionItem,
+ ...section.settings.filter(isOwnItem).map((setting) =>
+ settingsItem(
+ `settings-${section.id}-${setting.id}`,
+ settingTitle(setting),
+ urls.settings(section.id, setting.id),
+ { level: section.level, sectionId: section.id, settingId: setting.id },
+ {
+ parentName: `${levelName} › ${title}`,
+ contextKeywords: section.keywords,
+ searchKeywords: [sentenceCaseId(setting.id), ...(setting.keywords ?? [])],
+ hiddenSearchText: settingsSearchText(section.level, title, section.keywords, [
+ textSetting(setting),
+ ]),
+ }
+ )
+ ),
+ ]
+}
+
+export const commandKSettingsSearchItems = (
+ sections: CommandKSettingsSection[],
+ billingEntryUrl: string | null
+): SearchItem[] => {
+ if (!sections.length) {
+ return []
+ }
+ const levels = [...new Set(sections.map((section) => section.level))]
+ const items = [
+ settingsItem('settings', 'Settings', urls.settings(), {}, { searchKeywords: ['preferences', 'configuration'] }),
+ ...levels.map((level) =>
+ settingsItem(
+ `settings-level-${level}`,
+ settingsLevelName(level),
+ urls.settings(level),
+ { level },
+ { searchKeywords: LEVEL_SEARCH_KEYWORDS[level] }
+ )
+ ),
+ ...sections.flatMap((section) => commandKSectionSearchItems(section, billingEntryUrl)),
+ ]
+ return [...new Map(items.map((item) => [item.id, item])).values()]
+}
diff --git a/frontend/src/lib/components/Search/searchListsLogic.test.ts b/frontend/src/lib/components/Search/searchListsLogic.test.ts
index 11a0ffedcb84..72fe3c35009e 100644
--- a/frontend/src/lib/components/Search/searchListsLogic.test.ts
+++ b/frontend/src/lib/components/Search/searchListsLogic.test.ts
@@ -1,8 +1,12 @@
+import { buildRankedResults } from 'lib/components/CommandKSearch/commandKRankedResults'
+import { strictLocalMatches } from 'lib/components/CommandKSearch/commandKRanking'
+import { buildSections, emptyRemoteSlots } from 'lib/components/CommandKSearch/commandKSections'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'
import { urls } from 'scenes/urls'
+import type { Setting } from '~/scenes/settings/types'
import { initKeaTests } from '~/test/init'
import { ActivityTab } from '~/types'
@@ -149,6 +153,72 @@ describe('searchListsLogic', () => {
expect(terminalDockLogic.values.dockOpen).toBe(false)
})
+ it.each([false, true])(
+ 'finds a setting through its section keyword next to a dashboard named like the search, unified ranking %s',
+ (unifiedRanking) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TODAY_RAIL_NAV]: true })
+ const component = {} as JSX.Element
+ logic.actions.setSettingsMap([
+ {
+ id: 'environment-ai-cloud-environments',
+ level: 'environment',
+ title: 'Cloud environments',
+ flag: 'TODAY_RAIL_NAV',
+ keywords: ['desktop'],
+ settings: [
+ { id: 'ai-cloud-environments', title: 'Environments', component },
+ { id: 'ai-cloud-custom-images', title: 'Custom images', keywords: ['dependencies'], component },
+ ],
+ },
+ ])
+ const remote = emptyRemoteSlots()
+ remote.results = {
+ cache: {
+ 'desktop images': [
+ {
+ id: 'dashboard-1',
+ name: 'Desktop images board',
+ category: 'results',
+ record: { type: 'dashboard', ref: '1' },
+ rankKey: [-2, 0, 0, 0, -2, 0, 1, 0, 0],
+ },
+ ],
+ },
+ }
+ const sections = buildSections({
+ mode: 'search',
+ context: { kind: 'text', token: null },
+ suggestions: null,
+ local: {
+ products: [],
+ 'data-management': [],
+ people: [],
+ health: [],
+ actions: [],
+ shortcuts: [],
+ settings: logic.values.commandKSettingsItems,
+ create: [],
+ recents: [],
+ starred: [],
+ },
+ remote,
+ remoteQueries: { results: 'desktop images' },
+ localQuery: 'desktop images',
+ themeItem: null,
+ askAiQuestion: null,
+ viewAll: null,
+ stale: false,
+ personsFirst: false,
+ unifiedRanking,
+ searchCorrection: null,
+ })
+
+ expect(
+ sections.flatMap((section) => section.rows.flatMap((row) => (row.kind === 'item' ? [row.item.id] : [])))
+ ).toContain('settings-project-ai-cloud-environments-ai-cloud-custom-images')
+ }
+ )
+
it.each([
['off', false, 'Model preferences', false],
['on', true, 'Agent preferences', true],
@@ -194,4 +264,155 @@ describe('searchListsLogic', () => {
expect(items[0].name.includes('zebra')).toBe(expectsGatedKeyword)
}
)
+
+ it('keeps one row per settings section for the search list', () => {
+ logic.actions.setSettingsSections([
+ {
+ id: 'environment-details',
+ level: 'environment',
+ titleString: 'General',
+ settings: [
+ {
+ id: 'variables',
+ hasTitle: true,
+ titleString: 'Project token & ID',
+ descriptionString: null,
+ keywords: ['api key'],
+ },
+ ],
+ },
+ { id: 'organization-members', level: 'organization', titleString: 'Members', settings: [] },
+ ])
+
+ expect(logic.values.settingsItems).toEqual([
+ {
+ id: 'settings-project-details',
+ name: 'Project: General (Variables,Project token & ID,api key)',
+ displayName: 'General (Project)',
+ category: 'settings',
+ href: urls.settings('project-details'),
+ itemType: 'settings',
+ record: { type: 'settings', level: 'project', sectionId: 'project-details' },
+ },
+ {
+ id: 'settings-organization-members',
+ name: 'Organization: Members ()',
+ displayName: 'Members',
+ category: 'settings',
+ href: urls.settings('organization-members'),
+ itemType: 'settings',
+ record: { type: 'settings', level: 'organization', sectionId: 'organization-members' },
+ },
+ ])
+ })
+
+ it.each([
+ ['project general', 'settings-project-details', true],
+ ['2fa', 'settings-user-profile-2fa', true],
+ ['rename project', 'settings-project-customization-display-name', false],
+ ['desktop images', 'settings-project-ai-cloud-environments-ai-cloud-custom-images', false],
+ ['password', 'settings-user-profile-change-password', true],
+ ])('finds the Command K setting row %s', (query, id, ranked) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TODAY_RAIL_NAV]: true })
+ const component = {} as JSX.Element
+ logic.actions.setSettingsMap([
+ {
+ id: 'environment-ai-cloud-environments',
+ level: 'environment',
+ title: 'Cloud environments',
+ flag: 'TODAY_RAIL_NAV',
+ keywords: ['desktop'],
+ settings: [
+ { id: 'ai-cloud-environments', title: 'Environments', component },
+ { id: 'ai-cloud-custom-images', title: 'Custom images', keywords: ['dependencies'], component },
+ ],
+ },
+ {
+ id: 'environment-details',
+ level: 'environment',
+ title: 'General',
+ settings: [{ id: 'variables', title: 'Project token & ID', component }],
+ },
+ {
+ id: 'environment-customization',
+ level: 'environment',
+ title: 'Customization',
+ settings: [{ id: 'display-name', title: 'Project details', keywords: ['rename'], component }],
+ },
+ {
+ id: 'user-profile',
+ level: 'user',
+ title: 'Profile',
+ settings: [
+ { id: '2fa', title: 'Two-factor authentication', component },
+ { id: 'change-password', title: component, keywords: ['password'], component },
+ ],
+ },
+ ])
+ const items = logic.values.commandKSettingsItems
+
+ const fuzzy = filterSearchItems(items, query)
+ expect(fuzzy.map((item) => item.id)).toContain(id)
+ const strictIds = strictLocalMatches(items, query).map((item) => item.id)
+ expect(ranked ? strictIds : [id]).toContain(id)
+ const rankedRows = buildRankedResults({
+ query,
+ highlightWords: [],
+ results: [],
+ products: [],
+ settings: strictLocalMatches(fuzzy, query),
+ state: 'ready',
+ scoped: false,
+ }).flatMap((section) => section.rows)
+ expect(
+ [...fuzzy, ...rankedRows.flatMap((row) => (row.kind === 'item' ? [row.item] : []))]
+ .map((item) => item.matchedSearchKeyword ?? null)
+ .filter(Boolean)
+ ).toEqual([])
+ })
+
+ it.each([
+ ['off', false, 'Model preferences', false],
+ ['on', true, 'Agent preferences', true],
+ ])(
+ 'gives Command K one copy of a section gated on a flag and its negation, with the flag %s',
+ (_state, flagOn, expectedName, expectsGatedSetting) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TODAY_RAIL_NAV]: flagOn })
+ const settings: Setting[] = [
+ { id: 'task-agent-my-preference', title: 'My default model', component: {} as JSX.Element },
+ {
+ id: 'task-comments-slack-dm',
+ title: 'Gated setting',
+ component: {} as JSX.Element,
+ keywords: ['zebra'],
+ flag: 'TODAY_RAIL_NAV',
+ },
+ ]
+ logic.actions.setSettingsMap([
+ {
+ id: 'environment-task-agents',
+ level: 'environment',
+ title: 'Agent preferences',
+ flag: 'TODAY_RAIL_NAV',
+ settings,
+ },
+ {
+ id: 'environment-task-agents',
+ level: 'environment',
+ title: 'Model preferences',
+ flag: '!TODAY_RAIL_NAV',
+ settings,
+ },
+ ])
+
+ const sections = logic.values.commandKSettingsItems.filter(
+ (item) => item.id === 'settings-project-task-agents'
+ )
+ expect(sections.map((item) => [item.displayName, item.parentName])).toEqual([
+ [expectedName, 'Project settings'],
+ ])
+ const gated = filterSearchItems(logic.values.commandKSettingsItems, 'zebra').map((item) => item.href)
+ expect(gated).toEqual(expectsGatedSetting ? ['/settings/project-task-agents#task-comments-slack-dm'] : [])
+ }
+ )
})
diff --git a/frontend/src/lib/components/Search/searchListsLogic.tsx b/frontend/src/lib/components/Search/searchListsLogic.tsx
index 7ac295609a2e..159d9a30a4e0 100644
--- a/frontend/src/lib/components/Search/searchListsLogic.tsx
+++ b/frontend/src/lib/components/Search/searchListsLogic.tsx
@@ -5,21 +5,30 @@ import { billingLogic } from 'lib/logic/billing/billingLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { organizationIntegrationsLogic } from 'scenes/settings/organization/organizationIntegrationsLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'
import { userLogic } from 'scenes/userLogic'
import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { recentItemsModel } from '~/models/recentItemsModel'
import { FileSystemEntry, FileSystemImport } from '~/queries/schema/schema-general'
-import { matchesFlagDefinition } from '~/scenes/settings/flagGating'
+import {
+ SettingsVisibilityGates,
+ isSettingVisible,
+ matchesFlagDefinition,
+ visibleSettingsSections,
+} from '~/scenes/settings/flagGating'
import { getTitleText } from '~/scenes/settings/settingsSearch'
import type { SettingSection } from '~/scenes/settings/types'
-import { IntegrationType, UserType } from '~/types'
+import { IntegrationType, OrganizationType, PreflightStatus, TeamPublicType, TeamType, UserType } from '~/types'
import { SearchItem } from './searchItems'
import {
+ CommandKSettingsSection,
SettingsSectionSummary,
+ commandKSettingsSearchItems,
actionSearchItems,
dataManagementSearchItems,
healthSearchItems,
@@ -52,6 +61,30 @@ const summarizeSettingsSection = (section: SettingSection): SettingsSectionSumma
})),
})
+const summarizeCommandKSettingsSections = (
+ sections: SettingSection[],
+ gates: SettingsVisibilityGates
+): CommandKSettingsSection[] =>
+ visibleSettingsSections(sections, gates)
+ .filter((section) => !section.hideFromNavigation)
+ .map((section) => ({
+ id: section.id,
+ level: section.level === 'environment' ? 'project' : section.level,
+ titleString: getTitleText(section.title) || null,
+ to: section.to,
+ keywords: section.keywords,
+ settings: section.settings
+ .filter((setting) => !!setting.title && isSettingVisible(setting, gates))
+ .map((setting) => ({
+ id: setting.id,
+ titleString: getTitleText(setting.title) || null,
+ descriptionString:
+ setting.searchDescription ??
+ (typeof setting.description === 'string' ? setting.description : null),
+ keywords: setting.keywords,
+ })),
+ }))
+
export interface SearchListsLogicProps {
/** The command palette runs `onSelect` items, so it gets rows other search surfaces cannot use. */
commandPalette: boolean
@@ -62,12 +95,18 @@ export interface searchListsLogicValues {
billingEntryUrl: string | null // billingLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
organizationIntegrations: IntegrationType[] | null // organizationIntegrationsLogic
+ currentOrganization: OrganizationType | null // organizationLogic
+ isAdminOrOwner: boolean | null // organizationLogic
+ isCloudOrDev: boolean | undefined // preflightLogic
isDev: boolean | undefined // preflightLogic
+ preflight: PreflightStatus | null // preflightLogic
cachedStarred: FileSystemEntry[] // projectTreeDataLogic
treeGroupItems: FileSystemImport[] // projectTreeDataLogic
sceneLogViewsByRef: Record<string, string> // recentItemsModel
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
user: UserType | null // userLogic
actionItems: SearchItem[]
+ commandKSettingsItems: SearchItem[]
dataManagementItems: SearchItem[]
hasOrganizationIntegrations: boolean
healthItems: SearchItem[]
@@ -75,6 +114,7 @@ export interface searchListsLogicValues {
peopleItems: SearchItem[]
productsItems: SearchItem[]
settingsItems: SearchItem[]
+ settingsMap: SettingSection[]
settingsSections: SettingsSectionSummary[]
showTerminal: boolean
showUnreleased: boolean
@@ -86,6 +126,9 @@ export interface searchListsLogicActions {
toggleTerminal: () => {
value: true
} // terminalDockLogic
+ setSettingsMap: (sections: SettingSection[]) => {
+ sections: SettingSection[]
+ }
setSettingsSections: (sections: SettingsSectionSummary[]) => {
sections: SettingsSectionSummary[]
}
@@ -119,6 +162,18 @@ export interface searchListsLogicMeta {
hasOrganizationIntegrations: boolean,
billingEntryUrl: string | null
) => SearchItem[]
+ commandKSettingsItems: (
+ settingsMap: SettingSection[],
+ featureFlags: FeatureFlagsSet,
+ isCloudOrDev: boolean | undefined,
+ preflight: PreflightStatus | null,
+ currentTeam: TeamPublicType | TeamType | null,
+ currentOrganization: OrganizationType | null,
+ hasOrganizationIntegrations: boolean,
+ billingEntryUrl: string | null,
+ isAdminOrOwner: boolean | null,
+ user: UserType | null
+ ) => SearchItem[]
}
}
@@ -144,7 +199,11 @@ export const searchListsLogic = kea<searchListsLogicType>([
featureFlagLogic,
['featureFlags'],
preflightLogic,
- ['isDev'],
+ ['isDev', 'isCloudOrDev', 'preflight'],
+ teamLogic,
+ ['currentTeam'],
+ organizationLogic,
+ ['currentOrganization', 'isAdminOrOwner'],
userLogic,
['user'],
recentItemsModel,
@@ -159,6 +218,7 @@ export const searchListsLogic = kea<searchListsLogicType>([
})),
actions({
setSettingsSections: (sections: SettingsSectionSummary[]) => ({ sections }),
+ setSettingsMap: (sections: SettingSection[]) => ({ sections }),
}),
reducers({
settingsSections: [
@@ -167,6 +227,12 @@ export const searchListsLogic = kea<searchListsLogicType>([
setSettingsSections: (_, { sections }) => sections,
},
],
+ settingsMap: [
+ [] as SettingSection[],
+ {
+ setSettingsMap: (_, { sections }) => sections,
+ },
+ ],
}),
selectors({
showUnreleased: [
@@ -235,10 +301,53 @@ export const searchListsLogic = kea<searchListsLogicType>([
billingEntryUrl,
}),
],
+ commandKSettingsItems: [
+ (s) => [
+ s.settingsMap,
+ s.featureFlags,
+ s.isCloudOrDev,
+ s.preflight,
+ s.currentTeam,
+ s.currentOrganization,
+ s.hasOrganizationIntegrations,
+ s.billingEntryUrl,
+ s.isAdminOrOwner,
+ s.user,
+ ],
+ (
+ settingsMap: SettingSection[],
+ featureFlags: FeatureFlagsSet,
+ isCloudOrDev: boolean | undefined,
+ preflight: PreflightStatus | null,
+ currentTeam: TeamType | TeamPublicType | null,
+ currentOrganization: OrganizationType | null,
+ hasOrganizationIntegrations: boolean,
+ billingEntryUrl: string | null,
+ isAdminOrOwner: boolean | null,
+ user: UserType | null
+ ): SearchItem[] =>
+ commandKSettingsSearchItems(
+ summarizeCommandKSettingsSections(settingsMap, {
+ featureFlags,
+ isCloudOrDev,
+ realm: preflight?.realm,
+ currentTeam,
+ currentOrganization,
+ hasOrganizationIntegrations,
+ billingEntryUrl,
+ isAdminOrOwner,
+ isStaff: !!user?.is_staff,
+ }),
+ billingEntryUrl
+ ),
+ ],
}),
afterMount(({ actions }) => {
import('~/scenes/settings/SettingsMap')
- .then(({ SETTINGS_MAP }) => actions.setSettingsSections(SETTINGS_MAP.map(summarizeSettingsSection)))
+ .then(({ SETTINGS_MAP }) => {
+ actions.setSettingsSections(SETTINGS_MAP.map(summarizeSettingsSection))
+ actions.setSettingsMap(SETTINGS_MAP)
+ })
.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.ts
index 57950742af85..bd38be524b5d 100644
--- a/frontend/src/lib/components/Search/utils.ts
+++ b/frontend/src/lib/components/Search/utils.ts
@@ -13,6 +13,7 @@ interface FuseSearchable {
searchKeywords?: string[]
hiddenSearchText?: string
matchedSearchKeyword?: string | null
+ hideMatchedKeyword?: boolean
}
export const SEARCH_TAB_CATEGORY = 'tabs'
@@ -64,7 +65,7 @@ export function filterSearchItems<T extends FuseSearchable>(items: T[], query: s
}
return fuse.search(trimmed).map((result) => ({
...(result.item as T),
- matchedSearchKeyword: keywordOnlyMatch(result.matches),
+ matchedSearchKeyword: result.item.hideMatchedKeyword ? null : keywordOnlyMatch(result.matches),
}))
}
diff --git a/frontend/src/scenes/settings/Settings.tsx b/frontend/src/scenes/settings/Settings.tsx
index eb9c1cdb02dd..d474093c8b3b 100644
--- a/frontend/src/scenes/settings/Settings.tsx
+++ b/frontend/src/scenes/settings/Settings.tsx
@@ -406,7 +406,10 @@ function SettingsRenderer(props: SettingsLogicProps & { handleLocally: boolean }
settings.map((x, index) => (
<div key={`${x.id}-${index}`} className="relative last:mb-4">
{!settingsInSidebar && x.title && (
- <h2 id={x.id} className="flex gap-2 items-center text-base font-semibold mb-0">
+ <h2
+ id={x.id}
+ className="flex gap-2 items-center text-base font-semibold mb-0 scroll-mt-[calc(var(--scene-layout-header-height)+var(--spacing)*4)]"
+ >
{x.title}
{props.logicKey === 'settingsScene' && (
<LemonButton
diff --git a/frontend/src/scenes/settings/flagGating.ts b/frontend/src/scenes/settings/flagGating.ts
index e6e2eca59c2b..cbc947fabb12 100644
--- a/frontend/src/scenes/settings/flagGating.ts
+++ b/frontend/src/scenes/settings/flagGating.ts
@@ -1,7 +1,9 @@
import { FEATURE_FLAGS } from 'lib/constants'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
-import { Setting } from '~/scenes/settings/types'
+import { ADMIN_ONLY_SECTION_IDS } from '~/scenes/settings/sectionGating'
+import { Setting, SettingId, SettingSection, SettingSectionId } from '~/scenes/settings/types'
+import type { OrganizationType, Realm, TeamPublicType, TeamType } from '~/types'
/**
* Kept apart from settingsLogic so consumers (e.g. command palette search) can gate on
@@ -43,3 +45,65 @@ export const matchesFlagDefinition = (
}
return true
}
+
+export interface SettingsVisibilityGates {
+ featureFlags: FeatureFlagsSet
+ isCloudOrDev: boolean | undefined
+ realm: Realm | null | undefined
+ currentTeam: TeamType | TeamPublicType | null
+ currentOrganization: OrganizationType | null
+ hasOrganizationIntegrations: boolean
+ billingEntryUrl: string | null
+ isAdminOrOwner: boolean | null
+ isStaff: boolean
+}
+
+export const isSettingVisible = (setting: Setting, gates: SettingsVisibilityGates): boolean =>
+ matchesFlagDefinition(setting.flag, gates.featureFlags) &&
+ !(gates.realm && setting.hideOn?.includes(gates.realm)) &&
+ (!setting.allowForTeam || setting.allowForTeam(gates.currentTeam)) &&
+ (!setting.organizationAdminOnly || !!gates.isAdminOrOwner) &&
+ (!setting.staffOnly || gates.isStaff)
+
+export const visibleSettingsSections = (source: SettingSection[], gates: SettingsVisibilityGates): SettingSection[] => {
+ const sections = source.filter(
+ (section) =>
+ matchesFlagDefinition(section.flag, gates.featureFlags) &&
+ !(section.hideSelfHost && !gates.isCloudOrDev) &&
+ // Explicit gates to avoid showing this in the sidebar when the use doesn't have access to it
+ (section.id !== 'organization-integrations' || gates.hasOrganizationIntegrations) &&
+ (section.id !== 'organization-billing' || !!gates.billingEntryUrl) &&
+ (!ADMIN_ONLY_SECTION_IDS.includes(section.id) || !!gates.isAdminOrOwner)
+ )
+
+ // If there's no current organization, hide everything except user sections
+ if (!gates.currentOrganization) {
+ return sections.filter((section) => section.level === 'user')
+ }
+
+ // If there's no current team, hide project and environment sections entirely
+ if (!gates.currentTeam) {
+ return sections.filter((section) => section.level !== 'environment' && section.level !== 'project')
+ }
+
+ // Convert environment sections to project sections
+ return sections
+ .filter((section) => section.level !== 'project')
+ .map((section) => ({
+ ...section,
+ id: section.id.replace('environment-', 'project-') as SettingSectionId,
+ level: section.level === 'environment' ? 'project' : section.level,
+ settings: section.settings.map((setting) => ({
+ ...setting,
+ title:
+ typeof setting.title === 'string' ? setting.title.replace('environment', 'project') : setting.title,
+ id: setting.id.replace('environment-', 'project-') as SettingId,
+ })),
+ }))
+ .filter(
+ (section) =>
+ section.to ||
+ section.settings.length === 0 ||
+ section.settings.some((setting) => isSettingVisible(setting, gates))
+ )
+}
diff --git a/frontend/src/scenes/settings/settingsLogic.ts b/frontend/src/scenes/settings/settingsLogic.ts
index dd5f9f19bc44..d57994f9c3d8 100644
--- a/frontend/src/scenes/settings/settingsLogic.ts
+++ b/frontend/src/scenes/settings/settingsLogic.ts
@@ -17,8 +17,8 @@ import { userLogic } from 'scenes/userLogic'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { IntegrationType, PreflightStatus, TeamPublicType, TeamType } from '../../types'
import type { AvailableFeature, OrganizationType, UserType } from '../../types'
-import { matchesFlagDefinition } from './flagGating'
-import { ADMIN_ONLY_SECTION_IDS, findUnavailableSection } from './sectionGating'
+import { matchesFlagDefinition, visibleSettingsSections } from './flagGating'
+import { findUnavailableSection } from './sectionGating'
import { SETTINGS_MAP } from './SettingsMap'
import {
FUSE_THRESHOLD,
@@ -170,7 +170,7 @@ export interface settingsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
levels: (sections: SettingSection[]) => SettingLevelId[]
sections: (
- doesMatchFlags: (flagDefinition: Pick<Setting, 'flag'>) => boolean,
+ featureFlags: FeatureFlagsSet,
isCloudOrDev: boolean | undefined,
currentTeam: TeamPublicType | TeamType | null,
currentOrganization: OrganizationType | null,
@@ -178,7 +178,6 @@ export interface settingsLogicMeta {
preflight: PreflightStatus | null,
billingEntryUrl: string | null,
isAdminOrOwner: boolean | null,
- featureFlags: FeatureFlagsSet,
user: UserType | null
) => SettingSection[]
selectedLevel: (
@@ -392,6 +391,12 @@ export const settingsLogic = kea<settingsLogicType>([
actions.expandGroup(`${level}-${sectionObj.group}`)
}
setTimeout(() => {
+ const anchorId = router.values.location.hash.slice(1)
+ const anchorElement = anchorId ? document.getElementById(anchorId) : null
+ if (anchorElement) {
+ anchorElement.scrollIntoView()
+ return
+ }
const mainElement = document.querySelector('main')
if (mainElement) {
mainElement.scrollTo({ top: 0, behavior: 'smooth' })
@@ -449,7 +454,7 @@ export const settingsLogic = kea<settingsLogicType>([
],
sections: [
(s) => [
- s.doesMatchFlags,
+ s.featureFlags,
s.isCloudOrDev,
s.currentTeam,
s.currentOrganization,
@@ -457,11 +462,10 @@ export const settingsLogic = kea<settingsLogicType>([
s.preflight,
s.billingEntryUrl,
s.isAdminOrOwner,
- s.featureFlags,
s.user,
],
(
- doesMatchFlags: (flagDefinition: Pick<Setting, 'flag'>) => boolean,
+ featureFlags: FeatureFlagsSet,
isCloudOrDev: boolean | undefined,
currentTeam: null | import('../../types').TeamPublicType | import('../../types').TeamType,
currentOrganization: null | import('../../types').OrganizationType,
@@ -469,84 +473,24 @@ export const settingsLogic = kea<settingsLogicType>([
preflight: null | import('../../types').PreflightStatus,
billingEntryUrl: string | null,
isAdminOrOwner: boolean | null,
- featureFlags: FeatureFlagsSet,
user: UserType | null
- ): SettingSection[] => {
- const isSettingVisible = (setting: Setting): boolean => {
- if (!doesMatchFlags(setting)) {
- return false
- }
- if (preflight?.realm && setting.hideOn?.includes(preflight.realm)) {
- return false
- }
- if (setting.allowForTeam && !setting.allowForTeam(currentTeam)) {
- return false
- }
- if (setting.organizationAdminOnly && !isAdminOrOwner) {
- return false
+ ): SettingSection[] =>
+ visibleSettingsSections(
+ featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]
+ ? SETTINGS_MAP.map(withRailNavigationLink)
+ : SETTINGS_MAP,
+ {
+ featureFlags,
+ isCloudOrDev,
+ realm: preflight?.realm,
+ currentTeam,
+ currentOrganization,
+ hasOrganizationIntegrations: !!organizationIntegrations?.length,
+ billingEntryUrl,
+ isAdminOrOwner,
+ isStaff: !!user?.is_staff,
}
- if (setting.staffOnly && !user?.is_staff) {
- return false
- }
- return true
- }
-
- const source = featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]
- ? SETTINGS_MAP.map(withRailNavigationLink)
- : SETTINGS_MAP
- const sections = source.filter(doesMatchFlags).filter((section) => {
- if (section.hideSelfHost && !isCloudOrDev) {
- return false
- }
- if (
- section.id === 'organization-integrations' &&
- (!organizationIntegrations || organizationIntegrations.length === 0)
- ) {
- return false
- }
-
- // Explicit gates to avoid showing this in the sidebar when the use doesn't have access to it
- if (section.id === 'organization-billing' && !billingEntryUrl) {
- return false
- }
- if (ADMIN_ONLY_SECTION_IDS.includes(section.id) && !isAdminOrOwner) {
- return false
- }
-
- return true
- })
-
- // If there's no current organization, hide everything except user sections
- if (!currentOrganization) {
- return sections.filter((section) => section.level === 'user')
- }
-
- // If there's no current team, hide project and environment sections entirely
- if (!currentTeam) {
- return sections.filter((section) => section.level !== 'environment' && section.level !== 'project')
- }
-
- // Convert environment sections to project sections
- return sections
- .filter((section) => section.level !== 'project')
- .map((section) => ({
- ...section,
- id: section.id.replace('environment-', 'project-') as SettingSectionId,
- level: section.level === 'environment' ? 'project' : section.level,
- settings: section.settings.map((setting) => ({
- ...setting,
- title:
- typeof setting.title === 'string'
- ? setting.title.replace('environment', 'project')
- : setting.title,
- id: setting.id.replace('environment-', 'project-') as SettingId,
- })),
- }))
- .filter(
- (section) =>
- section.to || section.settings.length === 0 || section.settings.some(isSettingVisible)
- )
- },
+ ),
],
selectedLevel: [
(s) => [s.selectedLevelRaw, s.selectedSectionIdRaw, s.currentTeam],
diff --git a/frontend/src/scenes/settings/settingsSceneLogic.test.ts b/frontend/src/scenes/settings/settingsSceneLogic.test.ts
index d0ec582b6475..7bc894a9fda3 100644
--- a/frontend/src/scenes/settings/settingsSceneLogic.test.ts
+++ b/frontend/src/scenes/settings/settingsSceneLogic.test.ts
@@ -35,6 +35,28 @@ describe('settingsSceneLogic', () => {
expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe(pathname)
})
+ it.each([
+ [
+ 'keeps the setting anchor when the URL opens a section',
+ (): void => router.actions.push('/settings/project-details', {}, { 'date-and-time': true }),
+ { 'date-and-time': true },
+ ],
+ [
+ 'drops the setting anchor when the sidebar opens another section',
+ (): void => logic.actions.selectSection('project-details', 'project'),
+ {},
+ ],
+ ])('%s', async (_, openSection, expectedHash) => {
+ router.actions.push('/settings/project-customization', {}, { 'date-and-time': true })
+ await expectLogic(logic).toMatchValues({ selectedSectionId: 'project-customization' })
+
+ openSection()
+
+ await expectLogic(logic).toMatchValues({ selectedSectionId: 'project-details' })
+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe('/settings/project-details')
+ expect(router.values.hashParams).toEqual(expectedHash)
+ })
+
it('reads filters from the URL', async () => {
router.actions.push('/settings/project-product-analytics', {}, { 'person-display-name': true })
diff --git a/frontend/src/scenes/settings/settingsSceneLogic.ts b/frontend/src/scenes/settings/settingsSceneLogic.ts
index e847d008e9b6..9ffc5005a83b 100644
--- a/frontend/src/scenes/settings/settingsSceneLogic.ts
+++ b/frontend/src/scenes/settings/settingsSceneLogic.ts
@@ -2,6 +2,7 @@ import { MakeLogicType, connect, kea, listeners, path, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { Scene } from 'scenes/sceneTypes'
import type { Params } from 'scenes/sceneTypes'
@@ -289,7 +290,9 @@ export const settingsSceneLogic = kea<settingsSceneLogicType>([
return [urls.settings(level), router.values.searchParams, router.values.hashParams, { replace: true }]
},
selectSection({ section }) {
- return [urls.settings(section), router.values.searchParams, router.values.hashParams]
+ const sectionUrl = urls.settings(section)
+ const sameSection = removeProjectIdIfPresent(router.values.location.pathname) === sectionUrl
+ return [sectionUrl, router.values.searchParams, sameSection ? router.values.hashParams : {}]
},
selectSetting({ setting }) {
return [