:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(search): stop rebuilding command k results several times per keystroke (#123542)
Shy Alter3b383b25d5bc
diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.tsindex 139f3152e070..d21d40d992c0 100644--- a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts@@ -27,7 +27,29 @@ function groupLabel(groupKey: string): string {return capitalizeFirstLetter(pluralTypeName(getItemTypeDisplayName(groupKey) ?? groupKey.replace(/_/g, ' ')))}+const RANKED_LOCAL_CACHE_SIZE = 50+const rankedLocalCache = new WeakMap<SearchItem[], Map<string, RankedItem[]>>()+function rankLocalItems(items: SearchItem[], query: string, groupKey: string): RankedItem[] {+ const key = `${groupKey}:${query}`+ let byQuery = rankedLocalCache.get(items)+ if (!byQuery) {+ byQuery = new Map()+ rankedLocalCache.set(items, byQuery)+ }+ const cached = byQuery.get(key)+ if (cached) {+ return cached+ }+ const ranked = rankItems(items, query, groupKey)+ if (byQuery.size >= RANKED_LOCAL_CACHE_SIZE) {+ byQuery.delete(byQuery.keys().next().value!)+ }+ byQuery.set(key, ranked)+ return ranked+}++function rankItems(items: SearchItem[], query: string, groupKey: string): RankedItem[] {return items.flatMap((item) => {const ranked = rankLocalItem(query,diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.tsindex c5eec99a9ad2..52bb680a3542 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.test.ts@@ -31,10 +31,12 @@ describe('commandKSearchLogic', () => {['reuses a query whose request answered', false, []],])('%s when it is searched again', (_, failed, cached) => {logic.actions.remoteLoaded('ada', { persons: [] }, failed)+ const remoteBefore = logic.values.remote- logic.actions.requestStarted('persons', 'ada')+ logic.actions.requestsStarted({ persons: 'ada', objects: 'ada' })expect(logic.values.remote.persons.cache['ada']).toEqual(cached)+ expect(logic.values.remote === remoteBefore).toBe(!failed)})it('a See all row narrows the search to its type and keeps the words', () => {diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsxindex 44c344f05f8a..90ff21630110 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx@@ -246,12 +246,8 @@ export interface commandKSearchLogicActions {>>}- requestStarted: (- requestId: string,- query: string- ) => {- query: string- requestId: string+ requestsStarted: (queries: Record<string, string>) => {+ queries: Record<string, string>}selectChip: (index: ChipSelection) => {index: ChipSelection@@ -274,9 +270,6 @@ export interface commandKSearchLogicActions {showQuery: (query: SectionsQuery) => {query: SectionsQuery}- syncRemote: () => {- value: true- }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -439,8 +432,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([completeHighlighted: true,askAi: true,clearQuery: true,- syncRemote: true,- requestStarted: (requestId: string, query: string) => ({ requestId, query }),+ requestsStarted: (queries: Record<string, string>) => ({ queries }),remoteLoaded: (query: string, results: RemoteResults, failed: boolean = false) => ({ query, results, failed }),showQuery: (query: SectionsQuery) => ({ query }),loadFolders: true,@@ -486,7 +478,7 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([requestedQueries: [{} as Record<string, string>,{- requestStarted: (state, { requestId, query }) => ({ ...state, [requestId]: query }),+ requestsStarted: (state, { queries }) => ({ ...state, ...queries }),},],remote: [@@ -503,14 +495,20 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([}return next},- requestStarted: (state, { requestId, query }) => {+ requestsStarted: (state, { queries }) => {+ const retried = Object.entries(queries).flatMap(([requestId, query]) =>+ (REMOTE_REQUESTS.find((request) => request.id === requestId)?.sources ?? [])+ .filter((source) => state[source].failed?.[query])+ .map((source) => [source, query] as const)+ )+ if (retried.length === 0) {+ return state+ }const next = { ...state }- for (const source of REMOTE_REQUESTS.find((request) => request.id === requestId)?.sources ?? []) {- if (state[source].failed?.[query]) {- const { [query]: _items, ...cache } = state[source].cache- const { [query]: _failed, ...failed } = state[source].failed ?? {}- next[source] = { cache, failed }- }+ for (const [source, query] of retried) {+ const { [query]: _items, ...cache } = next[source].cache+ const { [query]: _failed, ...failed } = next[source].failed ?? {}+ next[source] = { cache, failed }}return next},@@ -816,6 +814,66 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([}}+ const syncRemote = (): void => {+ const started: Record<string, string> = {}+ for (const request of REMOTE_REQUESTS) {+ const query = values.requestQueries[request.id] ?? ''+ if (query !== (values.requestedQueries[request.id] ?? '')) {+ started[request.id] = query+ }+ }+ if (Object.keys(started).length === 0) {+ showSettledQuery()+ return+ }+ actions.requestsStarted(started)+ for (const request of REMOTE_REQUESTS) {+ if (!(request.id in started)) {+ continue+ }+ const query = started[request.id]+ if (!query) {+ // The request no longer applies, so stop it rather than let it hold a query slot.+ cache.disposables.dispose(`request-${request.id}`)+ continue+ }+ const cached = request.sources.map((source) => values.remote[source].cache[query])+ if (cached.every(Boolean)) {+ cache.disposables.dispose(`request-${request.id}`)+ actions.remoteLoaded(+ query,+ Object.fromEntries(request.sources.map((source, index) => [source, cached[index]]))+ )+ continue+ }+ const debounceMs = FAST_REQUESTS.includes(request.id) ? OBJECTS_DEBOUNCE_MS : REMOTE_DEBOUNCE_MS+ // One disposable per request covers the debounce and the fetch, so a newer query+ // cancels both, and unmounting cancels everything.+ cache.disposables.add(+ () => {+ const controller = new AbortController()+ const timer = setTimeout(() => {+ void settleRequest(request, query, controller.signal, values.remoteContext).then(+ (settled) => {+ if (settled && values.requestedQueries[request.id] === query) {+ actions.remoteLoaded(query, settled.results, settled.failed)+ }+ }+ )+ }, debounceMs)+ return () => {+ clearTimeout(timer)+ controller.abort()+ }+ },+ `request-${request.id}`,+ // Hiding the tab must not abort a search, or its section would sit on stale rows.+ { pauseOnPageHidden: false }+ )+ }+ showSettledQuery()+ }+const onQueryChanged = (): void => {const context = values.cursorContextconst keys =@@ -836,12 +894,12 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([if (context.kind === 'value' && context.filter.key === 'createdBy') {actions.ensureAllMembersLoaded()}- actions.syncRemote()+ syncRemote()}return {// Remote searches wait for a project, so a project that loads mid-query starts them.- loadCurrentTeamSuccess: () => actions.syncRemote(),+ loadCurrentTeamSuccess: () => syncRemote(),inputChanged: ({ text, cursor, pasted }) => {// With everything selected, the edit replaced the chips along with the text.const replacedAll = values.chipSelection === 'all'@@ -973,57 +1031,6 @@ export const commandKSearchLogic = kea<commandKSearchLogicType>([}},clearQuery: () => actions.setChipsAndText([], '', 0),- syncRemote: () => {- for (const request of REMOTE_REQUESTS) {- const query = values.requestQueries[request.id]- if (!query) {- // The request no longer applies, so stop it rather than let it hold a query slot.- if (values.requestedQueries[request.id]) {- cache.disposables.dispose(`request-${request.id}`)- actions.requestStarted(request.id, '')- }- continue- }- if (query === values.requestedQueries[request.id]) {- continue- }- actions.requestStarted(request.id, query)- const cached = request.sources.map((source) => values.remote[source].cache[query])- if (cached.every(Boolean)) {- cache.disposables.dispose(`request-${request.id}`)- actions.remoteLoaded(- query,- Object.fromEntries(request.sources.map((source, index) => [source, cached[index]]))- )- continue- }- const debounceMs = FAST_REQUESTS.includes(request.id) ? OBJECTS_DEBOUNCE_MS : REMOTE_DEBOUNCE_MS- // One disposable per request covers the debounce and the fetch, so a newer query- // cancels both, and unmounting cancels everything.- cache.disposables.add(- () => {- const controller = new AbortController()- const timer = setTimeout(() => {- void settleRequest(request, query, controller.signal, values.remoteContext).then(- (settled) => {- if (settled && values.requestedQueries[request.id] === query) {- actions.remoteLoaded(query, settled.results, settled.failed)- }- }- )- }, debounceMs)- return () => {- clearTimeout(timer)- controller.abort()- }- },- `request-${request.id}`,- // Hiding the tab must not abort a search, or its section would sit on stale rows.- { pauseOnPageHidden: false }- )- }- showSettledQuery()- },remoteLoaded: showSettledQuery,loadFolders: async () => {if (cache.foldersRequested) {diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.tsindex 8b12db5106f4..a4362e29fe24 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSections.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.ts@@ -246,8 +246,29 @@ export function pickDisplayedQuery(export const resultsSettled = (query: SectionsQuery, remote: RemoteSlots): boolean =>isSettled(remote.results, query.remoteQueries.results)-const filterLocal = (source: LocalSource, items: SearchItem[], query: string): SearchItem[] =>- source === 'create' ? filterNewItems(items, query) : filterSearchItems(items, query)+const LOCAL_MATCH_CACHE_SIZE = 50+const localMatchCache = new WeakMap<SearchItem[], Map<string, SearchItem[]>>()++function matchLocal(source: LocalSource, items: SearchItem[], query: string, ranked: boolean): SearchItem[] {+ const strict = ranked && source !== 'create'+ const key = `${strict ? 'strict' : 'fuzzy'}:${query}`+ let byQuery = localMatchCache.get(items)+ if (!byQuery) {+ byQuery = new Map()+ localMatchCache.set(items, byQuery)+ }+ const cached = byQuery.get(key)+ if (cached) {+ return cached+ }+ const fuzzy = source === 'create' ? filterNewItems(items, query) : filterSearchItems(items, query)+ const matches = strict ? strictLocalMatches(fuzzy, query) : fuzzy+ if (byQuery.size >= LOCAL_MATCH_CACHE_SIZE) {+ byQuery.delete(byQuery.keys().next().value!)+ }+ byQuery.set(key, matches)+ return matches+}function withViewAll(results: CommandKSection | null, viewAll: ViewAll | null): CommandKSection | null {if (!viewAll) {@@ -317,10 +338,7 @@ function lowerSections(if (ranked && source === 'products') {continue}- const filtered =- ranked && source !== 'create'- ? strictLocalMatches(filterLocal(source, local[source], localQuery), localQuery)- : filterLocal(source, local[source], localQuery)+ const filtered = matchLocal(source, local[source], localQuery, ranked)const themeItem = source === 'settings' ? input.themeItem : nullconst rows = themeItem? itemRows(source, [themeItem, ...filtered], SECONDARY_LIMIT + 1)