Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Rank every palette block by its best match (PRD-9598) (#6764)
Andrew Mikofalvyec9dfe93f058
diff --git a/.changeset/prd-9598-palette-command-ranking.md b/.changeset/prd-9598-palette-command-ranking.mdindex 5e0150cc8..09a98e4c9 100644--- a/.changeset/prd-9598-palette-command-ranking.md+++ b/.changeset/prd-9598-palette-command-ranking.md@@ -2,4 +2,4 @@"@inkeep/open-knowledge": patch----Command palette searches now list commands whose names match before commands that match only a related term, so typing "check" leads with **Check for updates** rather than **Switch worktree**.+Command palette searches now list commands whose names match before commands that match only a related term, and Enter runs the top row. Typing "check" leads with **Check for updates** rather than **Switch worktree**.diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsxindex 28f8907cf..68740720e 100644--- a/packages/app/src/components/CommandPalette.dom.test.tsx+++ b/packages/app/src/components/CommandPalette.dom.test.tsx@@ -132,6 +132,7 @@ vi.doMock('@/components/ui/command', () => ({CommandShortcut: ({ children }: { children?: ReactNode }) => (<span data-testid="command-shortcut">{children}</span>),+ useSelectFirstItemOn: () => {},}));vi.doMock('@/components/doc-panel-events', () => ({@@ -991,6 +992,97 @@ describe('CommandPalette DOM behavior', () => {expect(screen.queryByTestId('command-palette-search-hint-empty')).toBeNull();});+ test('a label match in a later group leads a keyword-only match in an earlier group', async () => {+ await renderPalette({ bridge: createBridge() });++ await setQuery('show');++ const commandIds = screen+ .getAllByRole('option')+ .map((option) => option.getAttribute('data-testid'));+ expect(commandIds).toContain('command-palette-open-graph');+ expect(commandIds.indexOf('command-palette-toggle-show-hidden-files')).toBeLessThan(+ commandIds.indexOf('command-palette-open-graph'),+ );+ expect(commandIds[0]).not.toBe('command-palette-open-graph');+ });++ test('a dynamic block leads with its strongest row, not its source order', async () => {+ worktreeModelMock = {+ mainRoot: '/projects/current',+ currentBranch: 'main',+ remoteBranches: [],+ entries: [+ {+ branch: 'dev',+ worktreePath: '/projects/current/.ok/worktrees/dev',+ isCurrent: false,+ isMain: false,+ locked: false,+ },+ {+ branch: 'worktree-cleanup',+ worktreePath: '/projects/current/.ok/worktrees/worktree-cleanup',+ isCurrent: false,+ isMain: false,+ locked: false,+ },+ ],+ };+ await renderPalette({ bridge: createBridge() });++ await setQuery('worktree');++ const commandIds = screen+ .getAllByRole('option')+ .map((option) => option.getAttribute('data-testid'));+ expect(commandIds).toContain('command-palette-worktree-dev');+ expect(commandIds[0]).toBe('command-palette-worktree-worktree-cleanup');+ });++ test('a dynamic block whose rows match only by keyword follows a label-matching command group', async () => {+ worktreeModelMock = {+ mainRoot: '/projects/current',+ currentBranch: 'main',+ remoteBranches: [],+ entries: [+ {+ branch: 'dev',+ worktreePath: '/projects/current/.ok/worktrees/dev',+ isCurrent: false,+ isMain: false,+ locked: false,+ },+ ],+ };+ await renderPalette({ bridge: createBridge() });++ await setQuery('worktree');++ const commandIds = screen+ .getAllByRole('option')+ .map((option) => option.getAttribute('data-testid'));+ expect(commandIds).toContain('command-palette-worktree-dev');+ expect(commandIds.indexOf('command-palette-new-worktree')).toBeLessThan(+ commandIds.indexOf('command-palette-worktree-dev'),+ );+ });++ test('within a group, label matches lead keyword-only matches', async () => {+ await renderPalette({ bridge: createBridge() });++ await setQuery('copy');++ const commandIds = screen+ .getAllByRole('option')+ .map((option) => option.getAttribute('data-testid'));+ expect(commandIds[0]).toBe('command-palette-copy-full-path');+ expect(commandIds).toContain('command-palette-duplicate');+ expect(commandIds.indexOf('command-palette-copy-relative-path')).toBeLessThan(+ commandIds.indexOf('command-palette-duplicate'),+ );+ });+test('a rejected worktree scope shows its cause, refreshes, and never opens', async () => {worktreeModelMock = {mainRoot: '/projects/current',diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsxindex 83f61de39..4cc5f9d9c 100644--- a/packages/app/src/components/CommandPalette.tsx+++ b/packages/app/src/components/CommandPalette.tsx@@ -13,6 +13,7 @@ import { Plural, Trans, useLingui } from '@lingui/react/macro';import { Check, FileText, Folder, GitBranch, Hash, Sparkles } from 'lucide-react';import {type Dispatch,+ Fragment,lazy,type KeyboardEvent as ReactKeyboardEvent,type SetStateAction,@@ -42,8 +43,7 @@ import {buildWorkspaceEntries,classifyOmnibarSearchHint,fetchWorkspaceSearchEntries,- matchesCommandQuery,- rankCommandQuery,+ rankRows,SEMANTIC_RESULT_LIMIT,searchWorkspaceEntries,splitTextByQueryMatches,@@ -79,6 +79,7 @@ import {CommandItem,CommandList,CommandShortcut,+ useSelectFirstItemOn,} from '@/components/ui/command';import { Kbd } from '@/components/ui/kbd';import { Spinner } from '@/components/ui/spinner';@@ -299,6 +300,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal);const tagsListFetchedRef = useRef(false);const listRef = useRef<HTMLDivElement>(null);+ useSelectFirstItemOn(listRef, deferredQuery);const inputRef = useRef<HTMLInputElement>(null);const semanticAbortRef = useRef<AbortController | null>(null);const semanticTimerRef = useRef<number | null>(null);@@ -650,20 +652,16 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPalsearchStatus === 'loading' &&!showNavigation &&!showSearchPreparing;- const showProjectRecents =- !inExclusiveMode &&- bridge !== null &&- switchableProjects.length > 0 &&- (trimmedDeferredQuery === '' ||- switchableProjects.some((row) =>- matchesCommandQuery(`${row.name} ${row.path}`, deferredQuery, ['open recent project']),- ));- const matchedWorktrees = switchableWorktrees.filter(- (entry) =>- trimmedDeferredQuery === '' ||- matchesCommandQuery(entry.branch ?? '', deferredQuery, ['worktree branch']),- );- const showWorktrees = !inExclusiveMode && bridge !== null && matchedWorktrees.length > 0;+ const rankedProjects = rankRows(switchableProjects, deferredQuery, (row) => ({+ label: `${row.name} ${row.path}`,+ keywords: ['open recent project'],+ })).slice(0, 10);+ const showProjectRecents = !inExclusiveMode && bridge !== null && rankedProjects.length > 0;+ const rankedWorktrees = rankRows(switchableWorktrees, deferredQuery, (entry) => ({+ label: entry.branch ?? '',+ keywords: ['worktree branch'],+ })).slice(0, 10);+ const showWorktrees = !inExclusiveMode && bridge !== null && rankedWorktrees.length > 0;const isEmbedded = useIsEmbedded();const hostAgentTargets = VISIBLE_TARGETS.filter((target) =>isTargetOfferedOnHost(target, {@@ -671,19 +669,15 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPalinstalled: installStates[target.id]?.installed,}),);+ const rankedAgentTargets = rankRows(hostAgentTargets, deferredQuery, (target) => {+ const displayName = target.displayName;+ return {+ label: t`Open with AI ${displayName} Desktop`,+ keywords: [target.id, 'agent handoff', 'open in'],+ };+ });const showAgentGroup =- !inExclusiveMode &&- !isEmbedded &&- handoffInput !== null &&- ((trimmedDeferredQuery === '' && hostAgentTargets.length > 0) ||- hostAgentTargets.some((target) => {- const displayName = target.displayName;- return matchesCommandQuery(t`Open with AI ${displayName} Desktop`, deferredQuery, [- target.id,- 'agent handoff',- 'open in',- ]);- }));+ !inExclusiveMode && !isEmbedded && handoffInput !== null && rankedAgentTargets.length > 0;const tagListItems =paletteMode.kind === 'tag-list' ? filterTagList(tagsList, paletteMode.query) : [];const showTagListEmpty =@@ -727,18 +721,15 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal};const visibleFixedCommands = inExclusiveMode? []- : PALETTE_COMMANDS.flatMap((cmd) => {- if (!cmd.available(paletteCtx)) return [];- if (cmd.visibility === 'search-only' && trimmedDeferredQuery === '') return [];- const label = cmd.label(paletteCtx);- const rank = rankCommandQuery(label, deferredQuery, cmd.keywords);- return rank === null ? [] : [{ cmd, label, rank }];- }).sort((a, b) => a.rank - b.rank);- const bestCommandRank = (group: PaletteCommandGroup) =>- visibleFixedCommands.find((row) => row.cmd.group === group)?.rank ?? Number.POSITIVE_INFINITY;- const trailingCommandGroups = (['file', 'view', 'terminal', 'app'] as const)- .slice()- .sort((a, b) => bestCommandRank(a) - bestCommandRank(b));+ : rankRows(+ PALETTE_COMMANDS.flatMap((cmd) => {+ if (!cmd.available(paletteCtx)) return [];+ if (cmd.visibility === 'search-only' && trimmedDeferredQuery === '') return [];+ return [{ cmd, label: cmd.label(paletteCtx) }];+ }),+ deferredQuery,+ ({ cmd, label }) => ({ label, keywords: cmd.keywords }),+ ).map(({ row, rank }) => ({ ...row, rank }));const hasVisibleFixedCommand = visibleFixedCommands.length > 0;const commandGroupHeading = (group: PaletteCommandGroup): string => {switch (group) {@@ -932,6 +923,161 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPalexitSemanticMode();}+ const firstRank = (rows: readonly { rank: number }[]) =>+ rows[0]?.rank ?? Number.POSITIVE_INFINITY;+ const commandGroupBlock = (group: PaletteCommandGroup) => ({+ key: group,+ rank: firstRank(visibleFixedCommands.filter((row) => row.cmd.group === group)),+ node: renderCommandGroup(group),+ });+ const rankedCommandBlocks = [+ commandGroupBlock('commands'),+ {+ key: 'open-with-ai',+ rank: firstRank(rankedAgentTargets),+ node: showAgentGroup ? (+ <CommandGroup heading={t`Open with AI`}>+ {rankedAgentTargets.map(({ row: target }) => {+ const installState = installStates[target.id];+ const enabled = installState.installed === true && handoffInput !== null;+ const displayName = target.displayName;+ const hint =+ installState.installed === null+ ? t`Detecting`+ : installState.installed === false+ ? t`Not installed`+ : null;+ const accessibleLabel = hint+ ? t`Open with AI ${displayName} Desktop, ${hint}`+ : t`Open with AI ${displayName} Desktop`;++ return (+ <CommandItem+ key={target.id}+ value={`send to ai ${target.displayName} desktop ${target.id} agent open in`}+ disabled={!enabled}+ onSelect={() => {+ if (!enabled || !handoffInput) return;+ onOpenChange(false);+ void dispatchHandoff(target.id, handoffInput, { installState });+ }}+ data-testid={`command-palette-open-in-${target.id}`}+ aria-label={accessibleLabel}+ >+ <span className="flex-1">+ <Trans>Open with AI {displayName} Desktop</Trans>+ </span>+ {hint ? (+ <span aria-hidden="true" className="ml-auto text-muted-foreground text-xs">+ {hint}+ </span>+ ) : null}+ </CommandItem>+ );+ })}+ </CommandGroup>+ ) : null,+ },+ commandGroupBlock('project'),+ {+ key: 'recent-projects',+ rank: firstRank(rankedProjects),+ node:+ showProjectRecents && bridge ? (+ <CommandGroup heading={t`Open recent project`}>+ {rankedProjects.map(({ row }) => {+ const isWorktree = row.isLinkedWorktree === true;+ const RowIcon = isWorktree ? GitBranch : Folder;+ const worktreeOf =+ isWorktree && row.mainRoot !== undefined ? basenameOf(row.mainRoot) : null;+ return (+ <RecentItemContextMenu+ key={row.path}+ path={row.path}+ onRemoveRecent={onRemoveRecent}+ testIdPrefix="command-palette-recent"+ >+ <div className="group/recent relative flex items-center">+ <CommandItem+ value={`${row.name} ${row.path} recent project`}+ onSelect={() =>+ runAction(+ () =>+ bridge.project.open({+ path: row.path,+ target: 'new-window',+ entryPoint: 'recents',+ }),+ t`Failed to open project.`,+ )+ }+ data-testid={`command-palette-recent-${row.path}`}+ className="flex-1 items-start pr-8"+ >+ <RowIcon className="mt-0.5" />+ <div className="flex min-w-0 flex-col gap-1">+ <UserText className="truncate font-medium">{row.name}</UserText>+ {worktreeOf !== null ? (+ <span className="truncate text-muted-foreground text-xs">+ <Trans>worktree of {worktreeOf}</Trans>+ </span>+ ) : null}+ <UserText className="truncate text-muted-foreground text-xs">+ {row.path}+ </UserText>+ </div>+ </CommandItem>+ <RecentRemoveButton+ path={row.path}+ name={row.name}+ onRemoveRecent={onRemoveRecent}+ testIdPrefix="command-palette-recent"+ />+ </div>+ </RecentItemContextMenu>+ );+ })}+ </CommandGroup>+ ) : null,+ },+ {+ key: 'worktrees',+ rank: firstRank(rankedWorktrees),+ node:+ showWorktrees && bridge ? (+ <CommandGroup heading={t`Worktrees`}>+ {rankedWorktrees.map(({ row: entry }) => (+ <CommandItem+ key={entry.branch}+ value={`${entry.branch} worktree branch`}+ onSelect={() => openWorktreeEntry(entry)}+ data-testid={`command-palette-worktree-${entry.branch}`}+ className="items-start"+ >+ <GitBranch className="mt-0.5" />+ <div className="flex min-w-0 flex-col gap-1">+ <UserText className="truncate font-medium">{entry.branch}</UserText>+ {entry.worktreePath === null ? (+ <span className="truncate text-muted-foreground text-xs">+ {t`Create worktree`}+ </span>+ ) : (+ <UserText className="truncate text-muted-foreground text-xs">+ {entry.worktreePath}+ </UserText>+ )}+ </div>+ </CommandItem>+ ))}+ </CommandGroup>+ ) : null,+ },+ commandGroupBlock('file'),+ commandGroupBlock('view'),+ commandGroupBlock('terminal'),+ commandGroupBlock('app'),+ ].sort((a, b) => a.rank - b.rank);+return (<><CommandDialog@@ -1282,155 +1428,9 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal</CommandGroup>) : null}- {renderCommandGroup('commands')}-- {showAgentGroup ? (- <CommandGroup heading={t`Open with AI`}>- {hostAgentTargets- .filter((target) => {- const displayName = target.displayName;- return matchesCommandQuery(- t`Open with AI ${displayName} Desktop`,- deferredQuery,- [target.id, 'agent handoff', 'open in'],- );- })- .map((target) => {- const installState = installStates[target.id];- const enabled = installState.installed === true && handoffInput !== null;- const displayName = target.displayName;- const hint =- installState.installed === null- ? t`Detecting`- : installState.installed === false- ? t`Not installed`- : null;- const accessibleLabel = hint- ? t`Open with AI ${displayName} Desktop, ${hint}`- : t`Open with AI ${displayName} Desktop`;-- return (- <CommandItem- key={target.id}- value={`send to ai ${target.displayName} desktop ${target.id} agent open in`}- disabled={!enabled}- onSelect={() => {- if (!enabled || !handoffInput) return;- onOpenChange(false);- void dispatchHandoff(target.id, handoffInput, { installState });- }}- data-testid={`command-palette-open-in-${target.id}`}- aria-label={accessibleLabel}- >- <span className="flex-1">- <Trans>Open with AI {displayName} Desktop</Trans>- </span>- {hint ? (- <span aria-hidden="true" className="ml-auto text-muted-foreground text-xs">- {hint}- </span>- ) : null}- </CommandItem>- );- })}- </CommandGroup>- ) : null}-- {renderCommandGroup('project')}-- {showProjectRecents && bridge ? (- <CommandGroup heading={t`Open recent project`}>- {switchableProjects- .filter((row) =>- matchesCommandQuery(`${row.name} ${row.path}`, deferredQuery, [- 'open recent project',- ]),- )- .slice(0, 10)- .map((row) => {- const isWorktree = row.isLinkedWorktree === true;- const RowIcon = isWorktree ? GitBranch : Folder;- const worktreeOf =- isWorktree && row.mainRoot !== undefined ? basenameOf(row.mainRoot) : null;- return (- <RecentItemContextMenu- key={row.path}- path={row.path}- onRemoveRecent={onRemoveRecent}- testIdPrefix="command-palette-recent"- >- <div className="group/recent relative flex items-center">- <CommandItem- value={`${row.name} ${row.path} recent project`}- onSelect={() =>- runAction(- () =>- bridge.project.open({- path: row.path,- target: 'new-window',- entryPoint: 'recents',- }),- t`Failed to open project.`,- )- }- data-testid={`command-palette-recent-${row.path}`}- className="flex-1 items-start pr-8"- >- <RowIcon className="mt-0.5" />- <div className="flex min-w-0 flex-col gap-1">- <UserText className="truncate font-medium">{row.name}</UserText>- {worktreeOf !== null ? (- <span className="truncate text-muted-foreground text-xs">- <Trans>worktree of {worktreeOf}</Trans>- </span>- ) : null}- <UserText className="truncate text-muted-foreground text-xs">- {row.path}- </UserText>- </div>- </CommandItem>- <RecentRemoveButton- path={row.path}- name={row.name}- onRemoveRecent={onRemoveRecent}- testIdPrefix="command-palette-recent"- />- </div>- </RecentItemContextMenu>- );- })}- </CommandGroup>- ) : null}-- {showWorktrees && bridge ? (- <CommandGroup heading={t`Worktrees`}>- {matchedWorktrees.slice(0, 10).map((entry) => (- <CommandItem- key={entry.branch}- value={`${entry.branch} worktree branch`}- onSelect={() => openWorktreeEntry(entry)}- data-testid={`command-palette-worktree-${entry.branch}`}- className="items-start"- >- <GitBranch className="mt-0.5" />- <div className="flex min-w-0 flex-col gap-1">- <UserText className="truncate font-medium">{entry.branch}</UserText>- {entry.worktreePath === null ? (- <span className="truncate text-muted-foreground text-xs">- {t`Create worktree`}- </span>- ) : (- <UserText className="truncate text-muted-foreground text-xs">- {entry.worktreePath}- </UserText>- )}- </div>- </CommandItem>- ))}- </CommandGroup>- ) : null}-- {trailingCommandGroups.map((groupKey) => renderCommandGroup(groupKey))}+ {rankedCommandBlocks.map((block) => (+ <Fragment key={block.key}>{block.node}</Fragment>+ ))}{showNavigation ? (<CommandGroup heading={t`Search`}>diff --git a/packages/app/src/components/command-palette-search.test.ts b/packages/app/src/components/command-palette-search.test.tsindex cc0cc59b6..c93b9ec6b 100644--- a/packages/app/src/components/command-palette-search.test.ts+++ b/packages/app/src/components/command-palette-search.test.ts@@ -7,6 +7,7 @@ import {fetchWorkspaceSearchEntries,matchesCommandQuery,rankCommandQuery,+ rankRows,searchWorkspaceEntries,splitTextByQueryMatches,type WorkspaceEntry,@@ -328,6 +329,10 @@ describe('rankCommandQuery', () => {expect(midWord as number).toBeLessThan(keywordOnly as number);});+ test('a term after a combining mark inside a word is not a word start', () => {+ expect(rankCommandQuery('किताब', 'ताब')).toBe(rankCommandQuery('Show Terminal', 'min'));+ });+test('a multi-word query ranks by its weakest term', () => {expect(rankCommandQuery('Report a bug', 'report bug', ['bug report issue'])).toBe(rankCommandQuery('Report a bug', 'bug'),@@ -338,6 +343,29 @@ describe('rankCommandQuery', () => {});});+describe('rankRows', () => {+ const rows = [+ { label: 'dev', keywords: ['worktree branch'] },+ { label: 'Open graph', keywords: [] },+ { label: 'worktree-cleanup', keywords: ['worktree branch'] },+ { label: 'main', keywords: ['worktree branch'] },+ ];++ test('drops unmatched rows and orders the rest by rank, keeping source order on ties', () => {+ expect(rankRows(rows, 'worktree', (row) => row).map(({ row }) => row.label)).toEqual([+ 'worktree-cleanup',+ 'dev',+ 'main',+ ]);+ });++ test('keeps every row in source order on an empty query', () => {+ expect(rankRows(rows, '', (row) => row).map(({ row }) => row.label)).toEqual(+ rows.map((row) => row.label),+ );+ });+});+describe('splitTextByQueryMatches', () => {test('marks query words case-insensitively', () => {expect(splitTextByQueryMatches('Homepage content on the home page', 'homepage home')).toEqual([diff --git a/packages/app/src/components/command-palette-search.ts b/packages/app/src/components/command-palette-search.tsindex 8aae2047a..cc95efb47 100644--- a/packages/app/src/components/command-palette-search.ts+++ b/packages/app/src/components/command-palette-search.ts@@ -295,11 +295,11 @@ const COMMAND_RANK_LABEL_INSIDE_WORD = 1;const COMMAND_RANK_KEYWORD_ONLY = 2;function commandTermRank(label: string, keywordText: string, term: string): number | null {- if (new RegExp(`(?:^|[^\\p{L}\\p{N}])${escapeRegExp(term)}`, 'u').test(label)) {+ if (new RegExp(`(?:^|[^\\p{L}\\p{M}\\p{N}])${escapeRegExp(term)}`, 'u').test(label)) {return COMMAND_RANK_LABEL_WORD_START;}if (label.includes(term)) return COMMAND_RANK_LABEL_INSIDE_WORD;- if (`${label} ${keywordText}`.includes(term)) return COMMAND_RANK_KEYWORD_ONLY;+ if (keywordText.includes(term)) return COMMAND_RANK_KEYWORD_ONLY;return null;}@@ -321,6 +321,20 @@ export function rankCommandQuery(return rank;}+export function rankRows<T>(+ rows: readonly T[],+ query: string,+ matchText: (row: T) => { label: string; keywords: readonly string[] },+): { row: T; rank: number }[] {+ return rows+ .flatMap((row) => {+ const { label, keywords } = matchText(row);+ const rank = rankCommandQuery(label, query, keywords);+ return rank === null ? [] : [{ row, rank }];+ })+ .sort((a, b) => a.rank - b.rank);+}+export function matchesCommandQuery(label: string,query: string,diff --git a/packages/app/src/components/ui/command.dom.test.tsx b/packages/app/src/components/ui/command.dom.test.tsxindex 447bc8f5d..f8ba61c72 100644--- a/packages/app/src/components/ui/command.dom.test.tsx+++ b/packages/app/src/components/ui/command.dom.test.tsx@@ -159,6 +159,55 @@ describe('CommandDialog runtime contracts', () => {expect(onRun).toHaveBeenCalledExactlyOnceWith('Report a bug');});+ test('a query that moves a better row above the surviving selection selects the new top row, and Enter runs it', async () => {+ const { Command, CommandInput, CommandItem, CommandList, useSelectFirstItemOn } = await import(+ './command'+ );+ const { useDeferredValue, useRef, useState } = await import('react');+ const onRun = vi.fn();+ const rows = [+ { label: 'Open graph', keywords: 'show' },+ { label: 'Show hidden files', keywords: '' },+ ];+ function RankedCommand() {+ const [query, setQuery] = useState('');+ const deferredQuery = useDeferredValue(query).toLowerCase();+ const ranked = rows+ .filter((row) => `${row.label} ${row.keywords}`.toLowerCase().includes(deferredQuery))+ .map((row) => ({ row, rank: row.label.toLowerCase().includes(deferredQuery) ? 0 : 1 }))+ .sort((a, b) => a.rank - b.rank);+ const listRef = useRef<HTMLDivElement>(null);+ useSelectFirstItemOn(listRef, deferredQuery);+ return (+ <Command shouldFilter={false}>+ <CommandInput value={query} onValueChange={setQuery} placeholder="Search" />+ <CommandList ref={listRef}>+ {ranked.map(({ row }) => (+ <CommandItem key={row.label} value={row.label} onSelect={() => onRun(row.label)}>+ {row.label}+ </CommandItem>+ ))}+ </CommandList>+ </Command>+ );+ }+ render(<RankedCommand />);+ const input = document.querySelector('[data-slot="command-input"]') as HTMLInputElement;+ expect(selectedValue()).toBe('Open graph');++ await act(async () => {+ fireEvent.change(input, { target: { value: 'show' } });+ });++ expect(selectedValue()).toBe('Show hidden files');+ expect(input.getAttribute('aria-activedescendant')).toBe(selectedItemId());+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onRun).toHaveBeenCalledExactlyOnceWith('Show hidden files');++ fireEvent.keyDown(input, { key: 'ArrowDown' });+ expect(selectedValue()).toBe('Open graph');+ });+test('removing rows around a selected row that survives leaves the selection where it was', async () => {const { Command, CommandInput, CommandItem, CommandList } = await import('./command');function RowList({ rows }: { rows: readonly string[] }) {diff --git a/packages/app/src/components/ui/command.tsx b/packages/app/src/components/ui/command.tsxindex 80962d3a0..ef1bf59a7 100644--- a/packages/app/src/components/ui/command.tsx+++ b/packages/app/src/components/ui/command.tsx@@ -1,6 +1,6 @@import { Command as CommandPrimitive } from 'cmdk';import { SearchIcon } from 'lucide-react';-import type { ComponentProps } from 'react';+import { type ComponentProps, type RefObject, useLayoutEffect, useRef } from 'react';import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';import { cn } from '@/lib/utils';@@ -149,6 +149,17 @@ function CommandShortcut({ className, ...props }: ComponentProps<'span'>) {);}+function useSelectFirstItemOn(listRef: RefObject<HTMLElement | null>, key: unknown) {+ const handledKeyRef = useRef<{ key: unknown } | null>(null);+ useLayoutEffect(() => {+ const previous = handledKeyRef.current;+ if (previous && Object.is(previous.key, key)) return;+ handledKeyRef.current = { key };+ if (previous === null) return;+ listRef.current?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Home', bubbles: true }));+ });+}+export {Command,CommandDialog,@@ -159,4 +170,5 @@ export {CommandList,CommandSeparator,CommandShortcut,+ useSelectFirstItemOn,};diff --git a/packages/app/tests/stress/command-palette-parity.e2e.ts b/packages/app/tests/stress/command-palette-parity.e2e.tsindex dc1a7f605..b5060524a 100644--- a/packages/app/tests/stress/command-palette-parity.e2e.ts+++ b/packages/app/tests/stress/command-palette-parity.e2e.ts@@ -69,6 +69,37 @@ test.describe('command-palette — menu-parity backfill (real cmdk)', () => {});test.describe('command-palette — selection follows the query (real cmdk)', () => {+ test('a query that ranks a better row above the still-matching selection moves the selection to the top', async ({+ page,+ api,+ }) => {+ await api.seedDocs(SEED_DOCS);+ await page.goto('/');+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });++ const list = await openPalette(page);+ const input = page.locator('[data-slot="command-input"]');+ const sidebarRow = page.getByTestId('command-palette-toggle-sidebar');++ await input.fill('sidebar');+ await expect(list.locator('[cmdk-item]').first()).toHaveAttribute(+ 'data-testid',+ 'command-palette-toggle-sidebar',+ );+ await expect(sidebarRow).toHaveAttribute('aria-selected', 'true');++ await input.fill('show');+ await expect(sidebarRow).toBeVisible({ timeout: 5_000 });+ const topRow = list.locator('[cmdk-item]').first();+ await expect(topRow).not.toHaveAttribute('data-testid', 'command-palette-toggle-sidebar');+ await expect(topRow).toHaveAttribute('aria-selected', 'true');+ await expect(sidebarRow).toHaveAttribute('aria-selected', 'false');+ await expect(input).toHaveAttribute(+ 'aria-activedescendant',+ (await topRow.getAttribute('id')) ?? '',+ );+ });+test('typing a query that hides the selected row selects the first remaining row, and Enter runs it', async ({page,api,