Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): match ⌘K queries per term, not whole substring (PRD-8189) (#3709)
Andrew Mikofalvy6750aada7466
diff --git a/.changeset/cmdk-multiword-command-search.md b/.changeset/cmdk-multiword-command-search.mdnew file mode 100644index 000000000..8dcad92ba--- /dev/null+++ b/.changeset/cmdk-multiword-command-search.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++Multi-word searches in the command palette and settings search now find commands regardless of word order. Typing "report bug" in ⌘K showed no commands at all, because a command was only offered when everything you typed appeared as one uninterrupted run of text inside its name and keywords. "Report a bug" has a word between the two, so it did not qualify, and neither did "branch switch" for Switch worktree or "project sync" in settings search. The file results in the same dialog already matched word by word, which is why the file half of the list filled in while the command half stayed empty.++A command is now offered when every word you typed appears somewhere in its name or keywords, in any order and not necessarily next to each other. Commands that matched before still match, and rows keep their existing position in the list. Note that because commands are listed above file results, a multi-word query that previously found only files may now preselect a command, so Enter runs the command rather than opening the file.++Searching "close terminal" also offers Hide Terminal, and offers it first. Kill Terminal answers to "close" as well, and it ends a running shell without asking, so leaving it as the only result for a phrase that means "put the panel away" in most editors would have been a trap.diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsxindex ccb2780d0..0e8bfff3a 100644--- a/packages/app/src/components/CommandPalette.dom.test.tsx+++ b/packages/app/src/components/CommandPalette.dom.test.tsx@@ -256,7 +256,7 @@ function createBridge({Promise.resolve([recent('Current', '/projects/current'),recent('Alpha', '/projects/alpha'),- recent('Omega', '/archive/omega-project'),+ recent('Omega', '/archive/proj-7'),]),),open: vi.fn(() => Promise.resolve()),@@ -428,7 +428,7 @@ describe('CommandPalette DOM behavior', () => {await waitFor(() =>expect(screen.queryByTestId('command-palette-recent-/projects/alpha')).toBeNull(),);- expect(screen.queryByTestId('command-palette-recent-/archive/omega-project')).not.toBeNull();+ expect(screen.queryByTestId('command-palette-recent-/archive/proj-7')).not.toBeNull();expect(onOpenChange).not.toHaveBeenCalledWith(false);});@@ -819,6 +819,87 @@ describe('CommandPalette DOM behavior', () => {});expect(refreshWorktreesMock).toHaveBeenCalled();});++ // Multi-word admission, one test per population. Each population hands the+ // shared command matcher its own label + keyword pair, so a boundary-level+ // assertion alone would not prove any of them actually routes through it.+ test('fixed command rows match multi-word queries whose terms are not adjacent', async () => {+ await renderPalette({ bridge: createBridge() });++ // "Report a bug" puts "a" between the two words the user typed, and its+ // keyword string carries them in the opposite order.+ await setQuery('report bug');+ expect(screen.getByTestId('command-palette-report-bug').textContent).toContain('Report a bug');++ // The weaker of the two orderings: this one is contiguous inside the+ // keyword string, so it holds under a contiguity rule too.+ await setQuery('bug report');+ expect(screen.queryByTestId('command-palette-report-bug')).not.toBeNull();++ // A term may land inside a longer word: "work" and "tree" are both in+ // "worktree".+ await setQuery('work tree');+ expect(screen.queryByTestId('command-palette-new-worktree')).not.toBeNull();+ expect(screen.queryByTestId('command-palette-switch-worktree')).not.toBeNull();++ // One unmatched term rejects the row, so the palette cannot degrade into+ // surfacing everything that shares any single word with the query.+ await setQuery('report zzzznomatch');+ expect(screen.queryByTestId('command-palette-report-bug')).toBeNull();+ });++ test('recent-project rows match multi-word queries spanning the name and the path', async () => {+ const { bridge } = await renderPalette();+ await waitFor(() => expect(bridge?.project.listRecent).toHaveBeenCalledTimes(1));++ // The row's searchable text spans two fields: "omega" appears only in the+ // name and "archive" only in the path, so neither field satisfies the query+ // alone.+ await setQuery('omega archive');+ expect(screen.queryByTestId('command-palette-recent-/archive/proj-7')).not.toBeNull();+ expect(screen.queryByTestId('command-palette-recent-/projects/alpha')).toBeNull();+ });++ test('worktree-branch rows match multi-word queries spanning the branch and its keywords', async () => {+ worktreeModelMock = {+ mainRoot: '/projects/current',+ currentBranch: 'main',+ entries: [+ {+ branch: 'dev',+ worktreePath: '/projects/current/.ok/worktrees/dev',+ isCurrent: false,+ isMain: false,+ locked: false,+ },+ {+ branch: 'feature-x',+ worktreePath: null,+ isCurrent: false,+ isMain: false,+ locked: false,+ },+ ],+ };+ await renderPalette();++ // "branch" comes from the row's keywords, "feature" from the branch name.+ await setQuery('branch feature');+ expect(screen.queryByTestId('command-palette-worktree-feature-x')).not.toBeNull();+ // The dev row shares "branch" but not "feature", so it stays out.+ expect(screen.queryByTestId('command-palette-worktree-dev')).toBeNull();+ });++ test('open-with-AI rows match multi-word queries spanning the label and its keywords', async () => {+ await renderPalette({ bridge: createBridge() });++ // "open" heads the label and recurs in the "open in" keyword; "cursor" sits+ // in the middle of the label, so the pair is never contiguous in order.+ await setQuery('open cursor');+ expect(screen.queryByTestId('command-palette-open-in-cursor')).not.toBeNull();+ // Every other target lacks "cursor" and so stays out on "open" alone.+ expect(screen.queryByTestId('command-palette-open-in-claude-code')).toBeNull();+ });});describe('NavigationItem path subtitle', () => {@@ -1318,6 +1399,26 @@ describe('Cmd+K menu-parity backfill', () => {expect(screen.queryByTestId('command-palette-kill-terminal')).toBeNull();});+ test('"close terminal" puts the reversible row ahead of the destructive one', async () => {+ // Kill Terminal ends a live shell with no confirmation and no undo, and it+ // answers to "close" as much as Hide Terminal does. Nothing stops both from+ // matching; what keeps the safe one preselected is that it sits in the view+ // group, which renders before the terminal group. With no filtering of its+ // own, the palette highlights whichever row comes first in the document, so+ // that group ordering is the whole safety property and it is invisible from+ // the keyword data alone.+ setViewMenuState({ terminalLive: true });+ await renderPalette({ bridge: createBridge() });+ await setQuery('close terminal');++ const reversible = screen.getByTestId('command-palette-toggle-terminal');+ const destructive = screen.getByTestId('command-palette-kill-terminal');++ const reversibleComesFirst =+ reversible.compareDocumentPosition(destructive) & Node.DOCUMENT_POSITION_FOLLOWING;+ expect(reversibleComesFirst).toBeTruthy();+ });+test('AC6: the spell-check row toggles via the bridge invoke, not view-menu-state', async () => {const { bridge } = await renderPalette({ bridge: createBridge() });await setQuery('check spelling while typing');diff --git a/packages/app/src/components/command-palette-search.test.ts b/packages/app/src/components/command-palette-search.test.tsindex b2c2243b1..42b32fc1d 100644--- a/packages/app/src/components/command-palette-search.test.ts+++ b/packages/app/src/components/command-palette-search.test.ts@@ -1,3 +1,4 @@+import { COMMAND_IDENTITIES, MENU_LABELS } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test } from 'vitest';import {buildWorkspaceEntries,@@ -265,6 +266,70 @@ describe('matchesCommandQuery', () => {test('returns false when neither label nor keywords include the query', () => {expect(matchesCommandQuery('Open graph', 'cursor')).toBe(false);});++ // A command's searchable text is its label plus its keyword tokens. A query+ // of several words admits the command when EVERY word appears somewhere in+ // that text; where the words sit relative to one another is not part of the+ // contract. "Report a bug" is the canonical shape: the label interposes "a"+ // between the two words a user types, so `report bug` is contiguous nowhere.+ // `bug report` IS contiguous, inside the keyword string, which makes it the+ // weaker of the two cases below — it holds under a contiguity rule as well,+ // so it guards against regression rather than discriminating this contract.+ const REPORT_BUG_KEYWORDS = ['bug report issue feedback problem'];+ const WORKTREE_KEYWORDS = ['worktree', 'branch', 'new'];++ test('matches when every query term is present, whatever their order and spacing', () => {+ expect(matchesCommandQuery('Report a bug', 'report bug', REPORT_BUG_KEYWORDS)).toBe(true);+ expect(matchesCommandQuery('Report a bug', 'bug report', REPORT_BUG_KEYWORDS)).toBe(true);+ expect(+ matchesCommandQuery('Switch worktree', 'branch switch', ['worktree', 'switch', 'branch']),+ ).toBe(true);+ });++ test('matches a term that occurs inside a longer word', () => {+ // "work" and "tree" both land inside "worktree": a term matches by+ // substring, not by whole-token equality.+ expect(matchesCommandQuery('New worktree', 'work tree', WORKTREE_KEYWORDS)).toBe(true);+ });++ test('matches each term case-insensitively', () => {+ expect(matchesCommandQuery('Report a bug', 'REPORT Bug', REPORT_BUG_KEYWORDS)).toBe(true);+ });++ // The counterweight to the cases above: every term has to land. Matching on+ // ANY term would make the palette admit nearly everything a user types.+ test('rejects when a single term is absent, even when the others match', () => {+ expect(matchesCommandQuery('Report a bug', 'report cursor', REPORT_BUG_KEYWORDS)).toBe(false);+ expect(matchesCommandQuery('Report a bug', 'cursor bug', REPORT_BUG_KEYWORDS)).toBe(false);+ expect(matchesCommandQuery('New worktree', 'work tree cursor', WORKTREE_KEYWORDS)).toBe(false);+ });++ // Widening admission can hand a phrase to a destructive command that a+ // narrower matcher kept out of reach. Kill Terminal carries `close` and ends+ // a live shell with no confirmation and no undo, while in most editors+ // "close terminal" means dismiss the panel. The reversible command has to+ // answer that phrasing too, so the destructive one is never the only option.+ test('a destructive phrasing also reaches its reversible sibling', () => {+ const killTerminal = COMMAND_IDENTITIES.find((command) => command.id === 'kill-terminal');+ const toggleTerminal = COMMAND_IDENTITIES.find((command) => command.id === 'toggle-terminal');+ const labelOf = (key: string | undefined) =>+ key ? ((MENU_LABELS as Record<string, string>)[key] ?? '') : '';++ expect(+ matchesCommandQuery(+ labelOf(killTerminal?.labelKey),+ 'close terminal',+ killTerminal?.keywords ?? [],+ ),+ ).toBe(true);+ expect(+ matchesCommandQuery(+ labelOf(toggleTerminal?.labelKey),+ 'close terminal',+ toggleTerminal?.keywords ?? [],+ ),+ ).toBe(true);+ });});describe('splitTextByQueryMatches', () => {diff --git a/packages/app/src/components/command-palette-search.ts b/packages/app/src/components/command-palette-search.tsindex 86373c127..e52a35708 100644--- a/packages/app/src/components/command-palette-search.ts+++ b/packages/app/src/components/command-palette-search.ts@@ -372,6 +372,31 @@ export async function fetchWorkspaceSearchEntries(return { entries, truncated: payload.truncated === true, ready: payload.ready !== false };}+/**+ * Admission predicate for command-shaped rows, shared by the ⌘K palette and+ * the settings dialog. A row matches when EVERY whitespace-separated term of+ * the query appears somewhere in its searchable text (`label` plus+ * `keywords`), case-insensitively, as a substring, in any order. An empty+ * query matches everything.+ *+ * Order-independence is the point: `keywords` holds tokens, and a user typing+ * two words rarely types them adjacently in the order the label happens to+ * use.+ *+ * Terms come from the same `queryTerms` the highlighter tokenizes with. Where a+ * surface both admits and highlights through these two helpers — the settings+ * dialog does — the rows it shows and the spans it marks cannot drift apart.+ * The palette is not such a surface: command rows render their label as plain+ * text, and the rows it does highlight are file and folder hits admitted by the+ * workspace search corpus, not by this predicate. So a keyword-only match+ * legitimately shows no marked span; that is not tokenizer drift.+ *+ * Enabling cmdk's own `commandScore` filter instead is not equivalent and is+ * not a simplification waiting to happen: its model is in-order, so it scores+ * `branch switch` against Switch worktree at zero, and turning the flag on also+ * turns on score-descending sort, which would discard the registry order the+ * groups depend on.+ */export function matchesCommandQuery(label: string,query: string,@@ -380,7 +405,7 @@ export function matchesCommandQuery(const normalizedQuery = normalize(query);if (!normalizedQuery) return true;const haystack = normalize([label, ...keywords].join(' '));- return haystack.includes(normalizedQuery);+ return queryTerms(normalizedQuery).every((term) => haystack.includes(term));}/**diff --git a/packages/app/src/components/settings/settings-search-index.test.ts b/packages/app/src/components/settings/settings-search-index.test.tsindex 5373ba142..a26e3cc4c 100644--- a/packages/app/src/components/settings/settings-search-index.test.ts+++ b/packages/app/src/components/settings/settings-search-index.test.ts@@ -222,4 +222,19 @@ describe('buildSettingsSearchIndex + matchesCommandQuery', () => {test('a query matching nothing returns no entries', () => {expect(find('zzzznomatch')).toHaveLength(0);});++ test('a section is found by a multi-word query spanning its label and its group', () => {+ // "Sync" is the item label and "This project" its group heading, so the two+ // words a user types are both in the searchable text but never adjacent in+ // the order typed.+ expect(find('project sync').some((e) => e.kind === 'section' && e.sectionId === 'sync')).toBe(+ true,+ );+ });++ test('a query whose terms are not ALL present returns no entries', () => {+ // The counterweight: matching on any one term would surface the Sync+ // section here.+ expect(find('sync zzzznomatch')).toHaveLength(0);+ });});diff --git a/packages/app/src/components/settings/settings-search-index.ts b/packages/app/src/components/settings/settings-search-index.tsindex 7a081f7df..6cf947fd8 100644--- a/packages/app/src/components/settings/settings-search-index.ts+++ b/packages/app/src/components/settings/settings-search-index.ts@@ -7,8 +7,9 @@* when the markdownlint panel is a visible sidebar item, which is exactly the* "plugin enabled + project open" predicate. No gating logic is duplicated here.*- * Filtering at render time reuses `matchesCommandQuery` (the same substring- * matcher the ⌘K command palette uses), so this module only shapes the corpus.+ * Filtering at render time reuses `matchesCommandQuery` (the same per-term,+ * order-independent matcher the ⌘K command palette uses), so this module only+ * shapes the corpus.*/import { MARKDOWNLINT_RULE_CATALOG } from '@inkeep/open-knowledge-core';import type { MessageDescriptor } from '@lingui/core';diff --git a/packages/app/tests/stress/command-palette-parity.e2e.ts b/packages/app/tests/stress/command-palette-parity.e2e.tsindex 298e265c1..5335d2dd7 100644--- a/packages/app/tests/stress/command-palette-parity.e2e.ts+++ b/packages/app/tests/stress/command-palette-parity.e2e.ts@@ -61,4 +61,47 @@ test.describe('command-palette — menu-parity backfill (real cmdk)', () => {await expect(rowAfter).toBeVisible({ timeout: 5_000 });await expect(rowAfter).toContainText('Show sidebar');});++ test('a multi-word query admits a row whose terms are never adjacent', async ({ page, api }) => {+ await api.seedDocs(SEED_DOCS);+ await page.goto('/');+ await page.waitForSelector('[role="treeitem"]', { timeout: 15_000 });+ await openPalette(page);++ const row = page.getByTestId('command-palette-toggle-sidebar');+ const input = page.locator('[data-slot="command-input"]');++ // Every case fills the input and asserts the value before asserting the+ // row. This row is search-only, so it is absent for an empty query and+ // unchanged by a query that never landed — without checking the value+ // first, a no-op keystroke leaves the previous result on screen and each+ // assertion below passes without testing what it names.+ const query = async (value: string) => {+ await input.fill(value);+ await expect(input).toHaveValue(value);+ };++ // Control: a single token contained in the label.+ await query('sidebar');+ await expect(row).toBeVisible({ timeout: 5_000 });++ // The subject: "toggle" comes from the keywords and "sidebar" from the+ // label, so the two words are never one uninterrupted run of text.+ await query('toggle sidebar');+ await expect(row).toBeVisible({ timeout: 5_000 });++ // Reversed, to pin order-independence rather than one lucky ordering.+ await query('sidebar toggle');+ await expect(row).toBeVisible({ timeout: 5_000 });++ // The counterweight: one unmatchable term must still exclude the row, so+ // admission stays all-terms rather than degrading to any-term. Paired with+ // a positive control so "the list unmounted" cannot masquerade as "row+ // correctly excluded".+ await query('sidebar zzzznomatch');+ await expect(row).toHaveCount(0);++ await query('sidebar');+ await expect(row).toBeVisible({ timeout: 5_000 });+ });});diff --git a/packages/core/src/commands/command-identity.ts b/packages/core/src/commands/command-identity.tsindex aac18b010..74ffbf070 100644--- a/packages/core/src/commands/command-identity.ts+++ b/packages/core/src/commands/command-identity.ts@@ -638,6 +638,12 @@ export const COMMAND_IDENTITIES: readonly CommandIdentity[] = ['toggle bottom dock','show terminal','hide terminal',+ // In most editors "close terminal" dismisses the panel. Kill Terminal+ // also carries `close`, and it destroys a live shell with no confirm and+ // no undo, so without this the destructive row is the only answer to that+ // phrasing. Both now match, and the view group renders above the terminal+ // group, so the reversible one is preselected.+ 'close',],shortcutId: 'toggle-terminal-panel',stateToggle: {