Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(search): one command palette answers a keypress (#1157)
Swati Ahujaa8817df6e2ef
diff --git a/packages/ui/__tests__/docs/command-palette.test.tsx b/packages/ui/__tests__/docs/command-palette.test.tsxindex 3203e0d4a..210ee70ef 100644--- a/packages/ui/__tests__/docs/command-palette.test.tsx+++ b/packages/ui/__tests__/docs/command-palette.test.tsx@@ -2,6 +2,7 @@ import { describe, it, expect, vi, afterEach } from "vitest";import { render, screen, cleanup, waitFor, fireEvent } from "@testing-library/react";import { DocsCommandPalette } from "../../src/docs/command-palette.js";import type { DocPage, DocPageSummary } from "@repowise-dev/types/docs";+import { commandPaletteShortcutIsClaimed } from "../../src/lib/command-palette-scope.js";afterEach(cleanup);@@ -92,3 +93,39 @@ describe("DocsCommandPalette", () => {await waitFor(() => expect(screen.getByText("Config")).toBeInTheDocument());});});++describe("DocsCommandPalette shortcut ownership", () => {+ it("owns the shortcut while mounted so the app-wide palette stands down", () => {+ expect(commandPaletteShortcutIsClaimed()).toBe(false);++ const view = render(+ <DocsCommandPalette pages={PAGES} onSelect={() => {}} />,+ );+ expect(commandPaletteShortcutIsClaimed()).toBe(true);++ view.unmount();+ expect(commandPaletteShortcutIsClaimed()).toBe(false);+ });++ it("one keypress opens this palette and not a second listener", () => {+ // Stands in for the app-wide palette, which uses exactly this guard.+ let appWideOpened = false;+ const appWide = (e: KeyboardEvent) => {+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {+ if (commandPaletteShortcutIsClaimed()) return;+ appWideOpened = true;+ }+ };+ window.addEventListener("keydown", appWide);++ try {+ render(<DocsCommandPalette pages={PAGES} onSelect={() => {}} />);+ fireEvent.keyDown(window, { key: "k", metaKey: true });++ expect(screen.getByRole("combobox")).toBeInTheDocument();+ expect(appWideOpened).toBe(false);+ } finally {+ window.removeEventListener("keydown", appWide);+ }+ });+});diff --git a/packages/ui/__tests__/lib/command-palette-scope.test.ts b/packages/ui/__tests__/lib/command-palette-scope.test.tsnew file mode 100644index 000000000..0a9aa277f--- /dev/null+++ b/packages/ui/__tests__/lib/command-palette-scope.test.ts@@ -0,0 +1,64 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ claimCommandPaletteShortcut,+ commandPaletteShortcutIsClaimed,+} from "../../src/lib/command-palette-scope.js";++afterEach(() => {+ document.body.removeAttribute("data-command-palette-scope");+ document.body.removeAttribute("data-command-palette-holders");+ vi.restoreAllMocks();+});++describe("commandPaletteShortcutIsClaimed", () => {+ it("is unclaimed until something claims it", () => {+ expect(commandPaletteShortcutIsClaimed()).toBe(false);+ });++ it("is claimed while a scoped palette is mounted", () => {+ claimCommandPaletteShortcut("docs");+ expect(commandPaletteShortcutIsClaimed()).toBe(true);+ });++ it("is released when that palette unmounts", () => {+ const release = claimCommandPaletteShortcut("docs");+ release();+ expect(commandPaletteShortcutIsClaimed()).toBe(false);+ });++ it("stays claimed until the last of several holders releases", () => {+ const a = claimCommandPaletteShortcut("docs");+ const b = claimCommandPaletteShortcut("docs");+ a();+ expect(commandPaletteShortcutIsClaimed()).toBe(true);+ b();+ expect(commandPaletteShortcutIsClaimed()).toBe(false);+ });++ it("survives a remount that releases out of order", () => {+ const first = claimCommandPaletteShortcut("docs");+ const second = claimCommandPaletteShortcut("docs");+ second();+ first();+ expect(commandPaletteShortcutIsClaimed()).toBe(false);+ });+});++describe("claimCommandPaletteShortcut noise", () => {+ it("warns when two different scopes hold the shortcut at once", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ claimCommandPaletteShortcut("docs");+ claimCommandPaletteShortcut("graph");+ expect(warn).toHaveBeenCalledOnce();+ expect(String(warn.mock.calls[0]?.[0])).toContain("graph");+ });++ it("warns when a release runs twice rather than going negative", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const release = claimCommandPaletteShortcut("docs");+ release();+ release();+ expect(commandPaletteShortcutIsClaimed()).toBe(false);+ expect(warn).toHaveBeenCalledOnce();+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 2cdde66f5..fc164cc3a 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -106,6 +106,7 @@"./ui": "./src/ui/index.ts","./ui/*": "./src/ui/*.tsx","./lib/cn": "./src/lib/cn.ts",+ "./lib/command-palette-scope": "./src/lib/command-palette-scope.ts","./lib/confidence": "./src/lib/confidence.ts","./lib/errors": "./src/lib/errors.ts","./lib/fix-history": "./src/lib/fix-history.ts",diff --git a/packages/ui/src/docs/command-palette.tsx b/packages/ui/src/docs/command-palette.tsxindex 57013796a..0d37c8c61 100644--- a/packages/ui/src/docs/command-palette.tsx+++ b/packages/ui/src/docs/command-palette.tsx@@ -4,6 +4,7 @@ import { useEffect, useId, useMemo, useRef, useState } from "react";import { Search, CornerDownLeft } from "lucide-react";import { cn } from "../lib/cn";import { getPageTypeIcon, getPageTypeLabel } from "../lib/page-types";+import { claimCommandPaletteShortcut } from "../lib/command-palette-scope";import { useDebounce } from "../hooks/use-debounce";import type { DocPageSummary } from "@repowise-dev/types/docs";@@ -93,8 +94,10 @@ export function DocsCommandPalette({const listboxId = useId();const optionId = (pageId: string) => `${listboxId}-opt-${pageId}`;- // Global ⌘K / Ctrl-K toggle.+ // ⌘K / Ctrl-K toggle. Claimed for as long as this palette is mounted, so the+ // app-wide palette stands down and one keypress opens one dialog.useEffect(() => {+ const release = claimCommandPaletteShortcut("docs");function onKey(e: KeyboardEvent) {if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {e.preventDefault();@@ -104,7 +107,10 @@ export function DocsCommandPalette({}}window.addEventListener("keydown", onKey);- return () => window.removeEventListener("keydown", onKey);+ return () => {+ window.removeEventListener("keydown", onKey);+ release();+ };}, []);useEffect(() => {diff --git a/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts b/packages/ui/src/graph/use-graph-keyboard-shortcuts.tsindex 7a481bfde..c94efc3b7 100644--- a/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts+++ b/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts@@ -2,6 +2,7 @@ import { useEffect, type Dispatch, type SetStateAction } from "react";import type { ColorMode } from "./graph-toolbar";import type { SigmaCanvasHandle } from "./sigma/sigma-canvas";import type { GraphCtxMenu } from "./use-graph-context-menu";+import { claimCommandPaletteShortcut } from "../lib/command-palette-scope";interface GraphKeyboardShortcutOptions {sigmaRef: { current: SigmaCanvasHandle | null };@@ -41,6 +42,9 @@ export function useGraphKeyboardShortcuts(opts: GraphKeyboardShortcutOptions): v} = opts;useEffect(() => {+ // The graph binds ⌘K to its own node search, so it owns the shortcut while+ // it is on screen and the app-wide palette stands down.+ const release = claimCommandPaletteShortcut("graph");const handleKeyDown = (e: KeyboardEvent) => {const target = e.target as HTMLElement;if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)@@ -93,7 +97,10 @@ export function useGraphKeyboardShortcuts(opts: GraphKeyboardShortcutOptions): v};window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);+ return () => {+ window.removeEventListener("keydown", handleKeyDown);+ release();+ };// Setters and the ref object are stable identities, so this binds once.}, [sigmaRef,diff --git a/packages/ui/src/lib/command-palette-scope.ts b/packages/ui/src/lib/command-palette-scope.tsnew file mode 100644index 000000000..24e4e275e--- /dev/null+++ b/packages/ui/src/lib/command-palette-scope.ts@@ -0,0 +1,76 @@+/**+ * Which command palette owns ⌘K.+ *+ * Two palettes can be on screen at once: the app-wide one, mounted by the root+ * layout on every route, and a scoped one that searches only what the current+ * surface holds. Both used to bind ⌘K on `window`, so on a surface with a+ * scoped palette the shortcut opened both dialogs stacked on top of each other.+ *+ * A scoped palette claims the shortcut while it is mounted; the app-wide one+ * stands down while the claim is held. Ownership follows what is mounted rather+ * than the URL, so a surface that grows or loses its own palette needs no+ * change here.+ *+ * The claim lives on `document.body` rather than in a module variable+ * deliberately. The two palettes are in different packages, and a bundler that+ * gave them separate copies of this module would leave the app-wide palette+ * reading a counter the scoped one never incremented — the shortcut would+ * silently break again, in exactly the way that is hardest to notice. The DOM+ * is one instance no matter how the modules are resolved.+ */++const ATTR = "data-command-palette-scope";+const COUNT_ATTR = "data-command-palette-holders";++function holders(): number {+ const raw = document.body.getAttribute(COUNT_ATTR);+ const n = raw === null ? 0 : Number.parseInt(raw, 10);+ return Number.isFinite(n) && n > 0 ? n : 0;+}++function setHolders(n: number, scope: string | null): void {+ if (n <= 0) {+ document.body.removeAttribute(COUNT_ATTR);+ document.body.removeAttribute(ATTR);+ return;+ }+ document.body.setAttribute(COUNT_ATTR, String(n));+ if (scope !== null) document.body.setAttribute(ATTR, scope);+}++/**+ * Claim ⌘K for a scoped palette. Returns the release function to call on+ * unmount.+ *+ * Counted rather than boolean because React can mount the next instance before+ * unmounting the previous one, and a boolean would leave the shortcut released+ * while a palette was still on screen.+ */+export function claimCommandPaletteShortcut(scope: string): () => void {+ const held = holders();+ const previous = document.body.getAttribute(ATTR);+ if (held > 0 && previous !== null && previous !== scope) {+ // Two different surfaces both think they own the shortcut. Whichever+ // claimed last wins, and the other one's palette becomes unreachable by+ // keyboard — worth a line in the console rather than a silent surprise.+ console.warn(+ `[command-palette] "${scope}" claimed the shortcut while "${previous}" still holds it`,+ );+ }+ setHolders(held + 1, scope);++ let released = false;+ return () => {+ if (released) {+ console.warn(`[command-palette] "${scope}" released the shortcut twice`);+ return;+ }+ released = true;+ setHolders(holders() - 1, document.body.getAttribute(ATTR));+ };+}++/** Whether a scoped palette currently owns ⌘K. */+export function commandPaletteShortcutIsClaimed(): boolean {+ return holders() > 0;+}diff --git a/packages/web/src/components/search/command-palette.tsx b/packages/web/src/components/search/command-palette.tsxindex 443156b09..b957f882a 100644--- a/packages/web/src/components/search/command-palette.tsx+++ b/packages/web/src/components/search/command-palette.tsx@@ -7,6 +7,7 @@ import useSWR from "swr";import { Search, LayoutDashboard, Settings, BookOpen, FileCode, Layers, Link2, GitMerge, MessageSquare } from "lucide-react";import { useSearch } from "@/lib/hooks/use-search";import { truncatePath } from "@repowise-dev/ui/lib/format";+import { commandPaletteShortcutIsClaimed } from "@repowise-dev/ui/lib/command-palette-scope";import { getFilesIndex } from "@/lib/api/files";import { repoNavItems } from "@/components/layout/nav-items";import { pageHref } from "@/lib/utils/page-href";@@ -67,7 +68,12 @@ export function CommandPalette({ repos, workspace }: CommandPaletteProps) {useEffect(() => {const handler = (e: KeyboardEvent) => {- if ((e.metaKey || e.ctrlKey) && e.key === "k") {+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {+ // A surface with its own palette owns the shortcut while it is+ // mounted. Without this both dialogs opened on one keypress, stacked.+ // The sidebar and mobile nav still reach this palette by event, so it+ // stays available where the scoped one cannot answer.+ if (commandPaletteShortcutIsClaimed()) return;e.preventDefault();setOpen((o) => !o);}