From 5629976ea0503c4b89bb1d08cda3df541286a8a8 Mon Sep 17 00:00:00 2001 From: Bersabel Tadesse Date: Mon, 31 Aug 2026 15:51:28 -0700 Subject: [PATCH 1/7] Move thread search into the command palette --- .../commands/CommandPalette.test.tsx | 796 +++++++++++------- .../components/commands/CommandPalette.tsx | 428 +++++----- .../src/components/commands/PaletteShell.tsx | 91 ++ .../commands/ThreadSearchPaletteMode.tsx | 470 +++++++++++ .../AppLayout.root-compose-project.test.tsx | 1 + .../layout/AppLayout.sidebar-resize.test.tsx | 1 + .../src/lib/command-palette/palette-action.ts | 9 + .../palette-app-commands.test.ts | 10 + .../command-palette/palette-app-commands.ts | 1 + .../src/lib/command-palette/palette-mode.ts | 27 + .../src/lib/command-palette/palette-modes.ts | 22 + .../palette-plugin-actions.test.ts | 41 +- .../command-palette/palette-plugin-actions.ts | 4 +- .../command-palette/palette-ranking.test.ts | 9 +- .../palette-thread-search-window.test.ts | 139 +++ .../palette-thread-search-window.ts | 165 ++++ .../palette-thread-search.test.ts | 181 ++++ .../command-palette/palette-thread-search.ts | 212 +++++ apps/app/src/lib/plugin-logos.ts | 4 + .../split-layout/openThreadInSplit.test.ts | 63 ++ .../src/lib/split-layout/openThreadInSplit.ts | 16 +- .../plugin-api-map/src/anatomy-manifest.json | 8 +- .../test/scaffold-surface-entry.test.ts | 8 + plans/bb-mobile-research/ui-inventory.md | 4 +- 24 files changed, 2193 insertions(+), 517 deletions(-) create mode 100644 apps/app/src/components/commands/PaletteShell.tsx create mode 100644 apps/app/src/components/commands/ThreadSearchPaletteMode.tsx create mode 100644 apps/app/src/lib/command-palette/palette-mode.ts create mode 100644 apps/app/src/lib/command-palette/palette-modes.ts create mode 100644 apps/app/src/lib/command-palette/palette-thread-search-window.test.ts create mode 100644 apps/app/src/lib/command-palette/palette-thread-search-window.ts create mode 100644 apps/app/src/lib/command-palette/palette-thread-search.test.ts create mode 100644 apps/app/src/lib/command-palette/palette-thread-search.ts create mode 100644 apps/app/src/lib/split-layout/openThreadInSplit.test.ts diff --git a/apps/app/src/components/commands/CommandPalette.test.tsx b/apps/app/src/components/commands/CommandPalette.test.tsx index f0419f7aa1..8a3f1bbda0 100644 --- a/apps/app/src/components/commands/CommandPalette.test.tsx +++ b/apps/app/src/components/commands/CommandPalette.test.tsx @@ -6,22 +6,31 @@ import { render, screen, waitFor, + within, } from "@testing-library/react"; -import { MemoryRouter, useLocation } from "react-router-dom"; +import { MemoryRouter } from "react-router-dom"; import { afterEach, describe, expect, it, vi } from "vitest"; import { defaultAppSettings, type AppCommandId, type AppDefaultKeybinding, type AppKeybinding, + type ThreadListEntry, } from "@bb/domain"; -import { CompactViewportOverrideProvider } from "@bb/shared-ui/hooks/use-compact-viewport"; +import { emptyPromptDraftState } from "@bb/client-core"; +import type { ThreadSearchResponse } from "@bb/server-contract"; +import { CHROME_SECTION_LABEL_CLASS } from "@bb/shared-ui/chrome-style-tokens"; import { AppCommandProvider, useAppCommandHandler } from "./AppCommandProvider"; import { removePluginSlotRegistrations, setPluginSlotRegistrations, } from "@/lib/plugin-slots"; +import { + resetPluginLogoStoreForTest, + setPluginLogoUrls, +} from "@/lib/plugin-logos"; import { CommandPalette } from "./CommandPalette"; +import type { NewThreadDraftRow } from "@/hooks/useNewThreadDraftSlots"; const PALETTE_SHORTCUT = { key: "p", @@ -41,30 +50,30 @@ const PALETTE_BINDING: AppKeybinding = { when: { all: ["mainSurface"], none: ["modalOpen"] }, }; -const THREAD_SEARCH_BINDING: AppKeybinding = { - command: "thread.search", +const THREAD_NEW_BINDING: AppKeybinding = { + command: "thread.new", desktopOnly: false, shortcut: { - key: "k", + key: "o", mod: true, meta: false, control: false, alt: false, - shift: false, + shift: true, }, when: { all: ["mainSurface"], none: ["modalOpen"] }, }; -const THREAD_NEW_BINDING: AppKeybinding = { - command: "thread.new", +const THREAD_SEARCH_BINDING: AppKeybinding = { + command: "thread.search", desktopOnly: false, shortcut: { - key: "o", + key: "k", mod: true, meta: false, control: false, alt: false, - shift: true, + shift: false, }, when: { all: ["mainSurface"], none: ["modalOpen"] }, }; @@ -78,17 +87,15 @@ function defaults(...commands: AppCommandId[]): AppDefaultKeybinding[] { })); } -const testState = vi.hoisted(() => ({ - calls: [] as string[], - filesAvailable: false, - plugins: [] as Array<{ - enabled: boolean; - hasSettings: boolean; - icon: string | null; - id: string; - name: string | null; - }>, +const testState = vi.hoisted(() => ({ calls: [] as string[] })); +const modeState = vi.hoisted(() => ({ + activeRecents: [] as ThreadListEntry[], + archivedRecents: [] as ThreadListEntry[], + drafts: [] as NewThreadDraftRow[], + searchResponse: undefined as ThreadSearchResponse | undefined, })); +const openThreadInSplitMock = vi.hoisted(() => vi.fn()); +const routeNavigateMock = vi.hoisted(() => vi.fn()); vi.mock("@/hooks/queries/system-queries", () => ({ useSystemConfig: () => ({ @@ -97,7 +104,7 @@ vi.mock("@/hooks/queries/system-queries", () => ({ ...defaultAppSettings, showKeyboardHints: false, }, - keybindings: [PALETTE_BINDING, THREAD_SEARCH_BINDING, THREAD_NEW_BINDING], + keybindings: [PALETTE_BINDING, THREAD_NEW_BINDING, THREAD_SEARCH_BINDING], defaultKeybindings: [ PALETTE_BINDING, THREAD_SEARCH_BINDING, @@ -116,62 +123,58 @@ vi.mock("@/lib/bb-desktop", () => ({ getBbDesktopInfo: () => null, })); -vi.mock("@/hooks/useHostDaemon", () => ({ - useHostDaemon: () => ({ hasDaemon: false }), - useLocalHostDaemonAccess: () => ({ - accessState: testState.filesAvailable - ? "permission-required" - : "unavailable", - }), +vi.mock("@bb/shared-ui/hooks/use-compact-viewport", () => ({ + useIsCompactViewport: () => false, })); -vi.mock("@/lib/app-query-client", () => ({ - appQueryClient: { - fetchQuery: () => Promise.resolve(testState.plugins), - }, +vi.mock("@/lib/split-layout/openThreadInSplit", () => ({ + openThreadInSplit: openThreadInSplitMock, })); -vi.mock("./ThreadPaletteResults", () => ({ - ThreadPaletteResults: ({ - onSelect, - query, - }: { - onSelect: (item: { - id: string; - optionId: string; - projectId: string; - threadId: string; - messageSeq: number | null; - }) => void; - query: string; - }) => ( - - ), +vi.mock("@/components/ui/app-route-anchor", () => ({ + useRouteNavigate: () => routeNavigateMock, })); -function LocationProbe() { - const location = useLocation(); - return ( - - {JSON.stringify({ pathname: location.pathname, state: location.state })} - - ); -} +vi.mock("@/hooks/useNewThreadDraftSlots", () => ({ + useNewThreadDraftSlots: () => modeState.drafts, +})); + +vi.mock("@/hooks/queries/sidebar-navigation-query", () => ({ + useSidebarNavigation: () => ({ + data: { + projects: [ + { + id: "project-1", + name: "Palette project", + threads: modeState.activeRecents, + }, + ], + personalProject: { id: "proj_personal", name: "Personal", threads: [] }, + }, + isLoading: false, + }), +})); + +vi.mock("@/hooks/queries/thread-queries", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + useArchivedThreads: () => ({ + data: { pages: [modeState.archivedRecents] }, + isLoading: false, + }), + useThreadSearch: ({ query }: { query: string }) => ({ + data: modeState.searchResponse, + debouncedQuery: query.trim(), + hasSearchableQuery: query.trim().length >= 2, + isDebouncing: false, + isError: false, + isFetching: false, + isLoading: false, + }), + }; +}); function Handler({ command }: { command: AppCommandId }) { useAppCommandHandler(command, () => { @@ -181,7 +184,50 @@ function Handler({ command }: { command: AppCommandId }) { return null; } -function renderPalette(isCompactViewport = false) { +function makeThread( + id: string, + overrides: Partial = {}, +): ThreadListEntry { + return { + id, + projectId: "project-1", + environmentId: null, + providerId: "codex", + title: `Title ${id}`, + titleFallback: `Title ${id}`, + sectionId: null, + status: "idle", + parentThreadId: null, + sourceThreadId: null, + originKind: null, + originPluginId: null, + visibility: "visible", + archivedAt: null, + pinnedAt: null, + pinSortKey: null, + deletedAt: null, + lastReadAt: null, + latestAttentionAt: 1, + createdAt: 1, + updatedAt: Date.now(), + activity: { + activeWorkflowCount: 0, + activeBackgroundAgentCount: 0, + activeBackgroundCommandCount: 0, + activePlanModeCount: 0, + activeGoalCount: 0, + }, + hasPendingInteraction: false, + environmentHostId: null, + environmentName: null, + environmentBranchName: null, + environmentWorkspaceDisplayKind: "other", + runtime: { displayStatus: "idle", hostReconnectGraceExpiresAt: null }, + ...overrides, + }; +} + +function renderPalette({ onSplit }: { onSplit?: () => void } = {}) { const result = render( @@ -189,20 +235,13 @@ function renderPalette(isCompactViewport = false) { origin + - - + , - { - wrapper: ({ children }) => ( - - {children} - - ), - }, ); screen.getByTestId("origin").focus(); return result; @@ -232,8 +271,11 @@ function openThreadSearch(): KeyboardEvent { } const searchField = () => screen.getByRole("combobox"); +const commandList = () => screen.getByRole("listbox", { name: "Commands" }); +const bucketGroup = (name: string) => + within(commandList()).getByRole("group", { name }); const optionTitles = () => - screen.queryAllByRole("option").map((option) => option.textContent); + screen.getAllByRole("option").map((option) => option.textContent); const selectedOption = () => screen .getAllByRole("option") @@ -242,10 +284,14 @@ const selectedOption = () => afterEach(() => { cleanup(); removePluginSlotRegistrations("linear"); - removePluginSlotRegistrations("automations"); + resetPluginLogoStoreForTest(); testState.calls.length = 0; - testState.filesAvailable = false; - testState.plugins.length = 0; + modeState.activeRecents = []; + modeState.archivedRecents = []; + modeState.drafts = []; + modeState.searchResponse = undefined; + openThreadInSplitMock.mockReset(); + routeNavigateMock.mockReset(); window.localStorage.clear(); }); @@ -255,10 +301,340 @@ describe("CommandPalette", () => { const event = openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); expect(event.defaultPrevented).toBe(true); - expect((searchField() as HTMLInputElement).value).toBe(">"); const titles = optionTitles(); expect(titles?.[0]).toContain("New thread"); - expect(titles).toHaveLength(16); + expect(titles).toHaveLength(5); + }); + + it("groups the resting root into three text buckets with producer metadata", async () => { + renderPalette(); + openPalette(); + await waitFor(() => expect(searchField()).toBeTruthy()); + + const groups = within(commandList()).getAllByRole("group"); + expect( + groups.map((group) => group.getAttribute("data-palette-bucket")), + ).toEqual(["Threads", "Actions", "Plugins"]); + for (const [index, label] of ["Threads", "Actions", "Plugins"].entries()) { + const header = within(groups[index] as HTMLElement).getByText(label, { + selector: "div", + }); + for (const className of CHROME_SECTION_LABEL_CLASS.split(" ")) { + expect(header.classList.contains(className)).toBe(true); + } + expect(header.classList.contains("px-2")).toBe(true); + } + + const threadRows = within(bucketGroup("Threads")).getAllByRole("option"); + expect(threadRows.map((row) => row.textContent)).toEqual([ + expect.stringContaining("New thread"), + expect.stringContaining("Search threads"), + expect.stringContaining("Next thread"), + ]); + for (const row of threadRows) { + expect(within(row).queryByText("Threads")).toBeNull(); + } + expect(threadRows[1]?.querySelector("kbd")).not.toBeNull(); + + const actionRows = within(bucketGroup("Actions")).getAllByRole("option"); + expect(actionRows[0]?.textContent).toContain("Window and layout"); + expect(actionRows[1]?.textContent).toContain("Workspace"); + for (const row of [...threadRows, ...actionRows]) { + expect(row.classList.contains("px-2")).toBe(true); + } + expect(commandList().querySelector("[data-icon]")).toBeNull(); + expect( + screen.getByTestId("command-palette").querySelector("svg"), + ).toBeNull(); + }); + + it("enters the registered thread mode from its existing command and pops one level per Escape", async () => { + renderPalette(); + const event = openThreadSearch(); + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search threads" }), + ).toBeTruthy(), + ); + expect(event.defaultPrevented).toBe(true); + expect( + screen.getByText("Threads").closest("[data-palette-mode-chip]"), + ).not.toBeNull(); + expect( + screen.getByRole("button", { name: "Thread scope" }).textContent, + ).toContain("All"); + + fireEvent.keyDown(screen.getByRole("combobox"), { key: "Escape" }); + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search commands" }), + ).toBeTruthy(), + ); + expect(screen.queryByRole("button", { name: "Thread scope" })).toBeNull(); + + fireEvent.keyDown(screen.getByRole("combobox"), { key: "Escape" }); + await waitFor(() => expect(screen.queryByRole("combobox")).toBeNull()); + }); + + it("enters the same registered mode by running Search threads from the root", async () => { + renderPalette(); + openPalette(); + await waitFor(() => expect(searchField()).toBeTruthy()); + + const searchCommand = within(bucketGroup("Threads")) + .getAllByRole("option") + .find((row) => row.textContent?.includes("Search threads")); + expect(searchCommand).toBeDefined(); + fireEvent.click(searchCommand as HTMLElement); + + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search threads" }), + ).toBeTruthy(), + ); + expect(testState.calls).toEqual([]); + }); + + it("cycles the thread scope and resets it after leaving the mode", async () => { + renderPalette(); + openThreadSearch(); + await waitFor(() => + expect(screen.getByRole("button", { name: "Thread scope" })).toBeTruthy(), + ); + const scope = screen.getByRole("button", { name: "Thread scope" }); + scope.focus(); + fireEvent.keyDown(scope, { key: "ArrowDown" }); + expect(scope.textContent).toContain("Active"); + expect( + screen.getByRole("listbox", { name: "Thread scope options" }), + ).toBeTruthy(); + fireEvent.keyDown(scope, { key: "Escape" }); + expect(document.activeElement).toBe(screen.getByRole("combobox")); + + fireEvent.keyDown(screen.getByRole("combobox"), { key: "Escape" }); + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search commands" }), + ).toBeTruthy(), + ); + const searchCommand = within(bucketGroup("Threads")) + .getAllByRole("option") + .find((row) => row.textContent?.includes("Search threads")); + fireEvent.click(searchCommand as HTMLElement); + await waitFor(() => + expect( + screen.getByRole("button", { name: "Thread scope" }).textContent, + ).toContain("All"), + ); + }); + + it("makes scope the input's only sibling tab stop and applies every keyboard choice immediately", async () => { + modeState.searchResponse = { + active: { + total: 1, + results: [{ thread: makeThread("matching-active"), matches: [] }], + }, + archived: { + total: 1, + results: [ + { + thread: makeThread("matching-archived", { + archivedAt: Date.now(), + }), + matches: [], + }, + ], + }, + }; + modeState.drafts = [ + { + id: "matching-draft", + title: "matching draft", + draft: { ...emptyPromptDraftState(), text: "matching draft" }, + lastEditedAt: Date.now(), + destination: { projectId: "project-1", sectionId: null }, + delete: vi.fn(), + }, + ]; + renderPalette(); + openThreadSearch(); + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search threads" }), + ).toBeTruthy(), + ); + const input = screen.getByRole("combobox", { name: "Search threads" }); + const scope = screen.getByRole("button", { name: "Thread scope" }); + const palette = screen.getByTestId("command-palette"); + expect( + Array.from( + palette.querySelectorAll( + 'input:not([disabled]), button:not([disabled]), [tabindex]:not([tabindex="-1"])', + ), + ), + ).toEqual([input, scope]); + + fireEvent.change(input, { target: { value: "match" } }); + const results = screen.getByRole("listbox", { name: "Threads" }); + await waitFor(() => + expect(within(results).getAllByRole("option")).toHaveLength(3), + ); + + scope.focus(); + fireEvent.keyDown(scope, { key: "ArrowDown" }); + expect(scope.textContent).toContain("Active"); + const scopeOptions = screen.getByRole("listbox", { + name: "Thread scope options", + }); + expect( + within(scopeOptions) + .getAllByRole("option") + .map((option) => option.textContent), + ).toEqual(["All", "Active", "Drafts", "Archived"]); + expect(within(results).getAllByRole("option")).toHaveLength(1); + expect(within(results).getByRole("option").textContent).toContain( + "matching-active", + ); + fireEvent.keyDown(scope, { key: "Enter" }); + expect(document.activeElement).toBe(input); + expect( + screen.queryByRole("listbox", { name: "Thread scope options" }), + ).toBeNull(); + + scope.focus(); + fireEvent.keyDown(scope, { key: "ArrowDown" }); + expect(scope.textContent).toContain("Drafts"); + expect(within(results).getAllByRole("option")).toHaveLength(1); + expect(within(results).getByRole("option").textContent).toContain( + "matching draft", + ); + fireEvent.keyDown(scope, { key: "Escape" }); + expect(document.activeElement).toBe(input); + + fireEvent.click(within(results).getByRole("option")); + await waitFor(() => expect(screen.queryByRole("combobox")).toBeNull()); + openThreadSearch(); + await waitFor(() => + expect( + screen.getByRole("button", { name: "Thread scope" }).textContent, + ).toContain("All"), + ); + }); + + it("renders the resting thread mode as one unlabelled active, draft, archived list", async () => { + modeState.activeRecents = [makeThread("recent-active")]; + modeState.archivedRecents = [ + makeThread("recent-archived", { archivedAt: Date.now() }), + ]; + modeState.drafts = [ + { + id: "recent-draft", + title: "recent draft", + draft: { ...emptyPromptDraftState(), text: "recent draft" }, + lastEditedAt: Date.now(), + destination: { projectId: "project-1", sectionId: null }, + delete: vi.fn(), + }, + ]; + renderPalette(); + openThreadSearch(); + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search threads" }), + ).toBeTruthy(), + ); + + const results = screen.getByRole("listbox", { name: "Threads" }); + await waitFor(() => + expect(within(results).getAllByRole("option")).toHaveLength(3), + ); + const rows = within(results).getAllByRole("option"); + expect(rows[0]?.textContent).toContain("Title recent-active"); + expect(rows[0]?.textContent).not.toContain("Active"); + expect(rows[1]?.textContent).toContain("recent draft"); + expect(rows[1]?.textContent).toContain("Draft"); + expect(rows[2]?.textContent).toContain("Title recent-archived"); + expect(rows[2]?.textContent).toContain("Archived"); + expect(within(results).queryAllByRole("group")).toHaveLength(0); + expect(within(results).queryByText("Recent")).toBeNull(); + }); + + it("renders search matches as one unlabelled active, draft, archived list", async () => { + const active = makeThread("active"); + const archived = makeThread("archived", { archivedAt: Date.now() }); + modeState.searchResponse = { + active: { total: 1, results: [{ thread: active, matches: [] }] }, + archived: { total: 1, results: [{ thread: archived, matches: [] }] }, + }; + modeState.drafts = [ + { + id: "draft-1", + title: "matching draft", + draft: { ...emptyPromptDraftState(), text: "matching draft" }, + lastEditedAt: Date.now(), + destination: { projectId: "project-1", sectionId: null }, + delete: vi.fn(), + }, + ]; + renderPalette(); + openThreadSearch(); + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search threads" }), + ).toBeTruthy(), + ); + fireEvent.change(screen.getByRole("combobox"), { + target: { value: "match" }, + }); + + const results = screen.getByRole("listbox", { name: "Threads" }); + await waitFor(() => + expect(within(results).getAllByRole("option")).toHaveLength(3), + ); + const rows = within(results).getAllByRole("option"); + expect(rows[0]?.textContent).toContain("Title active"); + expect(rows[1]?.textContent).toContain("matching draft"); + expect(rows[1]?.textContent).toContain("Draft"); + expect(rows[2]?.textContent).toContain("Title archived"); + expect(rows[2]?.textContent).toContain("Archived"); + expect(rows[0]?.textContent).not.toContain("Active"); + expect(within(results).queryAllByRole("group")).toHaveLength(0); + expect(within(results).queryByText("Recent")).toBeNull(); + expect(results.textContent).not.toContain("1/1"); + expect( + screen.getByTestId("command-palette").querySelectorAll("svg"), + ).toHaveLength(1); + }); + + it("opens a persisted thread result in a split with Command-Enter", async () => { + modeState.searchResponse = { + active: { + total: 1, + results: [{ thread: makeThread("matching-split"), matches: [] }], + }, + archived: { total: 0, results: [] }, + }; + renderPalette(); + openThreadSearch(); + const input = await screen.findByRole("combobox", { + name: "Search threads", + }); + fireEvent.change(input, { target: { value: "match" } }); + await waitFor(() => + expect(screen.getByRole("option").textContent).toContain( + "matching-split", + ), + ); + + fireEvent.keyDown(input, { key: "Enter", metaKey: true }); + + await waitFor(() => expect(openThreadInSplitMock).toHaveBeenCalledTimes(1)); + expect(openThreadInSplitMock).toHaveBeenCalledWith( + expect.objectContaining({ + projectId: "project-1", + threadId: "matching-split", + }), + ); }); it("filters as the user types and keeps the selection on a live row", async () => { @@ -268,23 +644,24 @@ describe("CommandPalette", () => { fireEvent.keyDown(searchField(), { key: "ArrowDown" }); fireEvent.keyDown(searchField(), { key: "ArrowDown" }); - fireEvent.change(searchField(), { target: { value: ">terminal" } }); + fireEvent.change(searchField(), { target: { value: "terminal" } }); await waitFor(() => expect(optionTitles()).toHaveLength(1)); expect(selectedOption()?.textContent).toContain("Open terminal"); + expect(selectedOption()?.textContent).toContain("Workspace"); + expect(within(commandList()).queryAllByRole("group")).toHaveLength(0); }); it("wraps at both ends of the list", async () => { renderPalette(); openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); - const titles = optionTitles(); fireEvent.keyDown(searchField(), { key: "ArrowUp" }); - expect(selectedOption()?.textContent).toBe(titles.at(-1)); + expect(selectedOption()?.textContent).toContain("Open terminal"); fireEvent.keyDown(searchField(), { key: "ArrowDown" }); - expect(selectedOption()?.textContent).toBe(titles[0]); + expect(selectedOption()?.textContent).toContain("New thread"); }); it("runs the highlighted command, closes, and restores focus", async () => { @@ -292,7 +669,7 @@ describe("CommandPalette", () => { openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); - fireEvent.change(searchField(), { target: { value: ">toggle panel" } }); + fireEvent.change(searchField(), { target: { value: "toggle panel" } }); await waitFor(() => expect(selectedOption()?.textContent).toContain("Toggle panel"), ); @@ -303,23 +680,32 @@ describe("CommandPalette", () => { expect(document.activeElement).toBe(screen.getByTestId("origin")); }); - it("runs a compact selection once after restoring focus", async () => { - renderPalette(true); + it("runs Split as an internal palette action without an app command", async () => { + const onSplit = vi.fn(); + renderPalette({ onSplit }); openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); - fireEvent.change(searchField(), { target: { value: ">toggle panel" } }); + const splitRow = within(bucketGroup("Actions")) + .getAllByRole("option") + .find((row) => row.textContent?.includes("Split")); + expect(splitRow?.textContent).toContain("Window and layout"); + + fireEvent.change(searchField(), { target: { value: "split" } }); + await waitFor(() => + expect(selectedOption()?.textContent).toContain("Split"), + ); fireEvent.keyDown(searchField(), { key: "Enter" }); - await waitFor(() => expect(testState.calls).toEqual(["panel.toggle"])); - expect(document.activeElement).toBe(screen.getByTestId("origin")); + await waitFor(() => expect(onSplit).toHaveBeenCalledOnce()); + expect(testState.calls).toEqual([]); }); - it("offers the last command run first the next time it opens", async () => { + it("offers the last command run first within its resting bucket", async () => { renderPalette(); openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); - fireEvent.change(searchField(), { target: { value: ">toggle panel" } }); + fireEvent.change(searchField(), { target: { value: "toggle panel" } }); await waitFor(() => expect(selectedOption()?.textContent).toContain("Toggle panel"), ); @@ -328,7 +714,8 @@ describe("CommandPalette", () => { openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); - expect(optionTitles()?.[0]).toContain("Toggle panel"); + const actionRows = within(bucketGroup("Actions")).getAllByRole("option"); + expect(actionRows[0]?.textContent).toContain("Toggle panel"); }); it("closes on Escape without running anything", async () => { @@ -390,6 +777,21 @@ describe("CommandPalette", () => { }); it("lists a plugin's commandPaletteAction and runs it", async () => { + setPluginLogoUrls( + new Map([ + [ + "linear", + { + displayName: "Linear", + icon: null, + compactIconUrl: null, + logoUrl: null, + logoDarkUrl: null, + icons: new Map(), + }, + ], + ]), + ); setPluginSlotRegistrations("linear", { homepageSections: [], settingsSections: [], @@ -401,7 +803,7 @@ describe("CommandPalette", () => { commandPaletteActions: [ { id: "open-issue", - title: "Linear: open issue", + title: "Open issue", run: () => { testState.calls.push("plugin-ran"); }, @@ -412,9 +814,15 @@ describe("CommandPalette", () => { openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); - fireEvent.change(searchField(), { target: { value: ">linear" } }); + const pluginRow = within(bucketGroup("Plugins")).getByRole("option"); + expect(pluginRow.textContent).toContain("Open issue"); + expect(pluginRow.textContent).toContain("Linear"); + + fireEvent.change(searchField(), { target: { value: "linear" } }); await waitFor(() => expect(optionTitles()).toHaveLength(1)); - expect(optionTitles()?.[0]).toContain("Linear: open issue"); + expect(optionTitles()?.[0]).toContain("Open issue"); + expect(optionTitles()?.[0]).toContain("Linear"); + expect(within(commandList()).queryAllByRole("group")).toHaveLength(0); fireEvent.keyDown(searchField(), { key: "Enter" }); await waitFor(() => expect(testState.calls).toEqual(["plugin-ran"])); @@ -425,7 +833,7 @@ describe("CommandPalette", () => { openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); - fireEvent.change(searchField(), { target: { value: ">zzzzz" } }); + fireEvent.change(searchField(), { target: { value: "zzzzz" } }); await waitFor(() => expect(screen.getByText("No matching commands")).toBeTruthy(), @@ -433,184 +841,4 @@ describe("CommandPalette", () => { fireEvent.keyDown(searchField(), { key: "Enter" }); expect(testState.calls).toEqual([]); }); - - it("opens thread search without a prefix", async () => { - renderPalette(); - const event = openThreadSearch(); - - await waitFor(() => - expect( - screen.getByRole("combobox", { name: "Search threads" }), - ).toBeTruthy(), - ); - expect(event.defaultPrevented).toBe(true); - expect((searchField() as HTMLInputElement).value).toBe(""); - expect(screen.getByRole("listbox").getAttribute("aria-label")).toBe( - "Thread search results", - ); - }); - - it("switches the open command palette to thread search", async () => { - renderPalette(); - openPalette(); - await waitFor(() => expect(searchField()).toBeTruthy()); - - fireEvent.change(searchField(), { target: { value: ">search threads" } }); - await waitFor(() => - expect(selectedOption()?.textContent).toContain("Search threads"), - ); - fireEvent.keyDown(searchField(), { key: "Enter" }); - - expect( - ( - screen.getByRole("combobox", { - name: "Search threads", - }) as HTMLInputElement - ).value, - ).toBe(""); - }); - - it("opens a specific settings page from Cmd-K", async () => { - renderPalette(); - openThreadSearch(); - await waitFor(() => expect(searchField()).toBeTruthy()); - - fireEvent.change(searchField(), { - target: { value: ">keyboard settings" }, - }); - await waitFor(() => - expect(selectedOption()?.textContent).toContain("Keyboard"), - ); - fireEvent.keyDown(searchField(), { key: "Enter" }); - - await waitFor(() => - expect(screen.getByTestId("location").textContent).toContain( - "/settings/keyboard", - ), - ); - }); - - it.each([false, true])( - "excludes Files settings when Settings has no local opener (compact: %s)", - async (compact) => { - renderPalette(compact); - openThreadSearch(); - await waitFor(() => expect(searchField()).toBeTruthy()); - - fireEvent.change(searchField(), { - target: { value: ">files settings" }, - }); - - await waitFor(() => - expect(optionTitles()).not.toContainEqual( - expect.stringContaining("Files settings"), - ), - ); - }, - ); - - it("keeps Files settings when local helper access can be enabled", async () => { - testState.filesAvailable = true; - renderPalette(); - openThreadSearch(); - await waitFor(() => expect(searchField()).toBeTruthy()); - - fireEvent.change(searchField(), { - target: { value: ">files settings" }, - }); - - await waitFor(() => - expect(selectedOption()?.textContent).toContain("Files settings"), - ); - }); - - it("opens a plugin settings page from Cmd-K", async () => { - testState.plugins.push({ - enabled: true, - hasSettings: true, - icon: null, - id: "linear", - name: "Linear", - }); - renderPalette(); - openThreadSearch(); - await waitFor(() => expect(searchField()).toBeTruthy()); - - fireEvent.change(searchField(), { - target: { value: ">linear settings" }, - }); - await waitFor(() => - expect(selectedOption()?.textContent).toContain("Linear settings"), - ); - fireEvent.keyDown(searchField(), { key: "Enter" }); - - await waitFor(() => - expect(screen.getByTestId("location").textContent).toContain( - "/settings/plugins/linear", - ), - ); - }); - - it("opens a plugin page from Cmd-K", async () => { - setPluginSlotRegistrations("automations", { - homepageSections: [], - settingsSections: [], - navPanels: [ - { - id: "automations", - title: "Automations", - icon: "Calendar", - path: "automations", - component: () => null, - }, - ], - threadPanelActions: [], - sidebarFooterActions: [], - fileOpeners: [], - messageDirectives: [], - }); - renderPalette(); - openThreadSearch(); - await waitFor(() => expect(searchField()).toBeTruthy()); - - fireEvent.change(searchField(), { - target: { value: ">automations" }, - }); - await waitFor(() => - expect(selectedOption()?.textContent).toContain("Automations"), - ); - fireEvent.keyDown(searchField(), { key: "Enter" }); - - await waitFor(() => - expect(screen.getByTestId("location").textContent).toContain( - "/plugins/automations/automations", - ), - ); - }); - - it("opens a matched thread at its matched message", async () => { - renderPalette(); - openThreadSearch(); - await waitFor(() => - expect( - screen.getByRole("option", { name: /Matched thread/u }), - ).toBeTruthy(), - ); - - fireEvent.click(screen.getByRole("option", { name: /Matched thread/u })); - - await waitFor(() => - expect(screen.getByTestId("location").textContent).toContain( - "thr_message", - ), - ); - const location = JSON.parse( - screen.getByTestId("location").textContent ?? "{}", - ) as { pathname: string; state: Record }; - expect(location.pathname).toContain("thr_message"); - expect(location.state).toEqual({ - searchMessageSeq: 7, - searchThreadId: "thr_message", - }); - }); }); diff --git a/apps/app/src/components/commands/CommandPalette.tsx b/apps/app/src/components/commands/CommandPalette.tsx index 6bcd03d081..56dbfab381 100644 --- a/apps/app/src/components/commands/CommandPalette.tsx +++ b/apps/app/src/components/commands/CommandPalette.tsx @@ -7,22 +7,27 @@ import { useState, } from "react"; import type { KeyboardEvent as ReactKeyboardEvent } from "react"; -import { useNavigate } from "react-router-dom"; import { Dialog, DialogContent, DialogTitle } from "@bb/shared-ui/dialog"; -import { Icon } from "@bb/shared-ui/icon"; import { cn } from "@bb/shared-ui/lib/utils"; import { COARSE_POINTER_TEXT_SM_CLASS } from "@bb/shared-ui/coarse-pointer-sizing"; +import { CHROME_SECTION_LABEL_CLASS } from "@bb/shared-ui/chrome-style-tokens"; import { LAUNCHER_ACTION_ROW_BASE_CLASS } from "@/components/secondary-panel/launcherRow"; import { useAppCommandHandler, + useAppCommandShortcut, useAppCommandRunner, useAppCommandShortcuts, + useIndexedAppCommandHandlers, } from "./AppCommandProvider"; import { AppCommandShortcutPill } from "./AppCommandShortcutHint"; -import type { PaletteAction } from "@/lib/command-palette/palette-action"; +import { + PALETTE_ACTION_BUCKETS, + type PaletteAction, +} from "@/lib/command-palette/palette-action"; import { buildAppCommandActions, PALETTE_COMMAND_IDS, + paletteActionIdForCommand, } from "@/lib/command-palette/palette-app-commands"; import { rankPaletteActions, @@ -33,24 +38,22 @@ import { recordPaletteRecent, } from "@/lib/command-palette/palette-recents"; import { buildPluginPaletteActions } from "@/lib/command-palette/palette-plugin-actions"; -import { buildSettingsPaletteActions } from "@/lib/command-palette/palette-settings-actions"; -import { buildPluginPagePaletteActions } from "@/lib/command-palette/palette-plugin-page-actions"; -import { usePluginSlots } from "@/lib/plugin-slots"; +import { getPluginSlotSnapshot } from "@/lib/plugin-slots"; import { getActiveThreadPanelOpener } from "@/components/plugin/plugin-thread-panel-navigation"; -import { getThreadRoutePath } from "@/lib/route-paths"; -import { pluginListQueryOptions } from "@/hooks/queries/plugin-settings-queries"; -import { - buildPluginSettingsEntries, - type PluginSettingsCandidate, -} from "@/components/settings/plugin-settings-entries"; -import { useSettingsNavSections } from "@/components/settings/settings-nav"; -import { appQueryClient } from "@/lib/app-query-client"; import { - ThreadPaletteResults, - type ThreadPaletteNavigationItem, -} from "./ThreadPaletteResults"; + PALETTE_MODE_ENTRY_COMMANDS, + PALETTE_MODES, +} from "@/lib/command-palette/palette-modes"; +import { PaletteShell } from "./PaletteShell"; -type PaletteMode = "commands" | "threads"; +const PALETTE_PLACEHOLDER = "Search commands"; +const MODE_ENTRY_HANDLER_PRIORITY = 100; +const MODE_BY_ACTION_ID = new Map( + PALETTE_MODES.map((mode) => [ + paletteActionIdForCommand(mode.entryCommand), + mode, + ]), +); export interface CommandPaletteProps { threadId: string | null; @@ -58,65 +61,23 @@ export interface CommandPaletteProps { } export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { - const navigate = useNavigate(); const runner = useAppCommandRunner(); const shortcuts = useAppCommandShortcuts(PALETTE_COMMAND_IDS); + const paletteShortcut = useAppCommandShortcut("palette.open"); const listId = useId(); const optionIdPrefix = useId(); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const [actions, setActions] = useState([]); - const [threadItems, setThreadItems] = useState< - readonly ThreadPaletteNavigationItem[] - >([]); const [highlightedIndex, setHighlightedIndex] = useState(0); + const [activeModeId, setActiveModeId] = useState(null); const [recents, setRecents] = useState(() => readPaletteRecents(), ); - const [installedPlugins, setInstalledPlugins] = useState< - readonly PluginSettingsCandidate[] - >([]); - const pluginSlots = usePluginSlots(); - const sections = useSettingsNavSections(pluginSlots.fileOpeners); - const pluginSettingsEntries = useMemo( - () => - buildPluginSettingsEntries({ - installedPlugins, - settingsSections: pluginSlots.settingsSections, - }), - [installedPlugins, pluginSlots.settingsSections], - ); - const settingsActions = useMemo( - () => - buildSettingsPaletteActions({ - navigate: (path) => { - void navigate(path); - }, - pluginEntries: pluginSettingsEntries, - sections, - }), - [navigate, pluginSettingsEntries, sections], - ); - const pluginPageActions = useMemo( - () => - buildPluginPagePaletteActions({ - navigate: (path) => { - void navigate(path); - }, - panels: pluginSlots.navPanels, - }), - [navigate, pluginSlots.navPanels], - ); const openTargetRef = useRef(null); const pendingRunRef = useRef<(() => void) | null>(null); - const loadInstalledPlugins = useCallback(() => { - void appQueryClient - .fetchQuery(pluginListQueryOptions({ enabled: true })) - .then(setInstalledPlugins, () => {}); - }, []); - const buildActions = useCallback( (target: EventTarget | null) => [ ...buildAppCommandActions({ @@ -126,7 +87,7 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { shortcuts, }), ...buildPluginPaletteActions({ - slots: pluginSlots.commandPaletteActions, + slots: getPluginSlotSnapshot().commandPaletteActions, threadId, projectId, openThreadPanel: getActiveThreadPanelOpener(), @@ -134,7 +95,6 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { ], [ projectId, - pluginSlots.commandPaletteActions, runner.dispatch, runner.isCommandAvailable, shortcuts, @@ -142,54 +102,68 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { ], ); - const openPalette = useCallback( - (mode: PaletteMode, target: EventTarget | null) => { + const prepareOpen = useCallback( + (target: EventTarget | null) => { openTargetRef.current = target; setActions(buildActions(target)); - setThreadItems([]); - setQuery(mode === "commands" ? ">" : ""); + setQuery(""); setHighlightedIndex(0); - setOpen(true); - loadInstalledPlugins(); }, - [buildActions, loadInstalledPlugins], + [buildActions], ); useAppCommandHandler("palette.open", (invocation) => { const target = invocation.target ?? (typeof document === "undefined" ? null : document.activeElement); - openPalette("commands", target); + prepareOpen(target); + setActiveModeId(null); + setOpen(true); return true; }); - useAppCommandHandler("thread.search", (invocation) => { - const target = - invocation.target ?? - (typeof document === "undefined" ? null : document.activeElement); - openPalette("threads", target); - return true; - }); + useIndexedAppCommandHandlers( + PALETTE_MODE_ENTRY_COMMANDS, + (index, invocation) => { + const mode = PALETTE_MODES[index]; + if (mode === undefined) return false; + const target = + invocation.target ?? + (typeof document === "undefined" ? null : document.activeElement); + prepareOpen(target); + setActiveModeId(mode.id); + setOpen(true); + return true; + }, + MODE_ENTRY_HANDLER_PRIORITY, + ); - const mode: PaletteMode = query.startsWith(">") ? "commands" : "threads"; - const modeQuery = mode === "commands" ? query.slice(1) : query; - const commandActions = useMemo( - () => [...actions, ...settingsActions, ...pluginPageActions], - [actions, pluginPageActions, settingsActions], + const ranked = useMemo( + () => rankPaletteActions({ actions, query, recentIds: recents }), + [actions, query, recents], ); - const rankedCommands = useMemo( + const isGroupedRoot = query.trim() === ""; + const rootGroups = useMemo(() => { + const groups = PALETTE_ACTION_BUCKETS.map((bucket) => ({ + bucket, + entries: ranked.filter((entry) => entry.action.bucket === bucket), + })); + return groups.map((group, index) => ({ + ...group, + startIndex: groups + .slice(0, index) + .reduce((total, prior) => total + prior.entries.length, 0), + })); + }, [ranked]); + const visibleEntries = useMemo( () => - rankPaletteActions({ - actions: commandActions, - query: modeQuery, - recentIds: recents, - }), - [commandActions, modeQuery, recents], + isGroupedRoot ? rootGroups.flatMap((group) => group.entries) : ranked, + [isGroupedRoot, ranked, rootGroups], ); - const resultCount = - mode === "commands" ? rankedCommands.length : threadItems.length; const activeIndex = - resultCount === 0 ? -1 : Math.min(highlightedIndex, resultCount - 1); + visibleEntries.length === 0 + ? -1 + : Math.min(highlightedIndex, visibleEntries.length - 1); const listRef = useRef(null); const scrollOnNextHighlightRef = useRef(false); @@ -202,58 +176,48 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { }, [activeIndex]); const chooseAction = useCallback((action: PaletteAction) => { - if (action.id === "app:thread.search") { - setQuery(""); - setHighlightedIndex(0); - if (listRef.current !== null) listRef.current.scrollTop = 0; + setRecents((current) => recordPaletteRecent(current, action.id)); + if (MODE_BY_ACTION_ID.has(action.id)) { + action.run(); return; } pendingRunRef.current = action.run; - setRecents((current) => recordPaletteRecent(current, action.id)); setOpen(false); }, []); - const chooseThread = useCallback( - (item: ThreadPaletteNavigationItem) => { - pendingRunRef.current = () => { - void navigate( - getThreadRoutePath({ - projectId: item.projectId, - threadId: item.threadId, - }), - item.messageSeq === null - ? undefined - : { - state: { - searchMessageSeq: item.messageSeq, - searchThreadId: item.threadId, - }, - }, - ); - }; - setOpen(false); - }, - [navigate], - ); + const runAfterClose = useCallback((run: () => void) => { + pendingRunRef.current = run; + setOpen(false); + }, []); - const handleAfterCloseAutoFocus = useCallback(() => { + const handleCloseAutoFocus = useCallback((event: Event) => { const pending = pendingRunRef.current; pendingRunRef.current = null; const target = openTargetRef.current; if (target instanceof HTMLElement && target.isConnected) { + event.preventDefault(); target.focus({ preventScroll: true }); } pending?.(); }, []); + const handleOpenChange = useCallback((nextOpen: boolean) => { + setOpen(nextOpen); + if (!nextOpen) { + setActiveModeId(null); + setQuery(""); + setHighlightedIndex(0); + } + }, []); + const handleKeyDown = useCallback( (event: ReactKeyboardEvent) => { - if (resultCount === 0) return; + if (visibleEntries.length === 0) return; if (event.key === "ArrowDown") { event.preventDefault(); scrollOnNextHighlightRef.current = true; setHighlightedIndex((current) => - current + 1 >= resultCount ? 0 : current + 1, + current + 1 >= visibleEntries.length ? 0 : current + 1, ); return; } @@ -261,7 +225,7 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { event.preventDefault(); scrollOnNextHighlightRef.current = true; setHighlightedIndex((current) => - current <= 0 ? resultCount - 1 : current - 1, + current <= 0 ? visibleEntries.length - 1 : current - 1, ); return; } @@ -274,113 +238,125 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { if (event.key === "End") { event.preventDefault(); scrollOnNextHighlightRef.current = true; - setHighlightedIndex(resultCount - 1); + setHighlightedIndex(visibleEntries.length - 1); return; } if (event.key === "Enter") { + const choice = visibleEntries[activeIndex]; + if (choice === undefined) return; event.preventDefault(); - if (mode === "commands") { - const choice = rankedCommands[activeIndex]; - if (choice !== undefined) chooseAction(choice.action); - return; - } - const choice = threadItems[activeIndex]; - if (choice !== undefined) chooseThread(choice); + chooseAction(choice.action); } }, - [ - activeIndex, - chooseAction, - chooseThread, - mode, - rankedCommands, - resultCount, - threadItems, - ], + [activeIndex, chooseAction, visibleEntries], ); - - const activeDescendant = - activeIndex === -1 + const activeMode = + activeModeId === null ? undefined - : mode === "commands" - ? `${optionIdPrefix}-${activeIndex}` - : threadItems[activeIndex]?.optionId; - const inputLabel = mode === "commands" ? "Search commands" : "Search threads"; + : PALETTE_MODES.find((mode) => mode.id === activeModeId); return ( - + { + if (activeMode !== undefined) event.preventDefault(); + }} data-testid="command-palette" > - - {mode === "commands" ? "Quick palette" : "Search threads"} - -
- - { - const nextQuery = event.target.value; - setQuery(nextQuery); - if (!nextQuery.startsWith(">")) setThreadItems([]); + Quick palette + {activeMode === undefined ? ( + + ) + } + inputLabel={PALETTE_PLACEHOLDER} + listId={listId} + listLabel="Commands" + listRef={listRef} + onInputChange={(value) => { + setQuery(value); setHighlightedIndex(0); if (listRef.current !== null) listRef.current.scrollTop = 0; }} - onKeyDown={handleKeyDown} + onInputKeyDown={handleKeyDown} + placeholder={PALETTE_PLACEHOLDER} + value={query} + > + {!isGroupedRoot && visibleEntries.length === 0 ? ( +

+ No matching commands +

+ ) : isGroupedRoot ? ( + rootGroups.map((group, groupIndex) => { + const labelId = `${optionIdPrefix}-${group.bucket.toLowerCase()}-label`; + return ( +
+
+ {group.bucket} +
+ {group.entries.map((entry, index) => { + const visibleIndex = group.startIndex + index; + return ( + setHighlightedIndex(visibleIndex)} + onSelect={() => chooseAction(entry.action)} + /> + ); + })} +
+ ); + }) + ) : ( + visibleEntries.map((entry, index) => ( + setHighlightedIndex(index)} + onSelect={() => chooseAction(entry.action)} + /> + )) + )} +
+ ) : ( + { + setActiveModeId(null); + setQuery(""); + setHighlightedIndex(0); + }} + runAfterClose={runAfterClose} /> -
-
- {mode === "commands" && rankedCommands.length === 0 ? ( -

- No matching commands -

- ) : mode === "commands" ? ( - rankedCommands.map((entry, index) => ( - setHighlightedIndex(index)} - onSelect={() => chooseAction(entry.action)} - /> - )) - ) : ( - - )} -
+ )}
); @@ -399,6 +375,9 @@ function PaletteRow({ onActivate: () => void; onSelect: () => void; }) { + const metadataGroup = + entry.action.group === entry.action.bucket ? null : entry.action.group; + const hasTrailing = metadataGroup !== null || entry.action.shortcut !== null; return (
- - - {entry.action.group} + {hasTrailing ? ( + + {metadataGroup === null ? null : ( + + {metadataGroup} + + )} + {entry.action.shortcut === null ? null : ( + + )} - {entry.action.shortcut === null ? null : ( - - )} - + ) : null}
); } diff --git a/apps/app/src/components/commands/PaletteShell.tsx b/apps/app/src/components/commands/PaletteShell.tsx new file mode 100644 index 0000000000..ecfc8e7cc8 --- /dev/null +++ b/apps/app/src/components/commands/PaletteShell.tsx @@ -0,0 +1,91 @@ +import type { KeyboardEventHandler, ReactNode, Ref } from "react"; +import { Icon } from "@bb/shared-ui/icon"; + +interface PaletteShellProps { + activeDescendantId?: string; + accessory?: ReactNode; + children: ReactNode; + footerKeys?: readonly { keys: string; label: string }[]; + inputLabel: string; + inputRef?: Ref; + listId: string; + listLabel: string; + listRef?: Ref; + modeChip?: { icon: Parameters[0]["name"]; label: string }; + onInputChange: (value: string) => void; + onInputKeyDown: KeyboardEventHandler; + placeholder: string; + value: string; +} + +export function PaletteShell({ + activeDescendantId, + accessory, + children, + footerKeys = [], + inputLabel, + inputRef, + listId, + listLabel, + listRef, + modeChip, + onInputChange, + onInputKeyDown, + placeholder, + value, +}: PaletteShellProps) { + return ( + <> +
+ {modeChip === undefined ? null : ( + + + {modeChip.label} + + )} + onInputChange(event.target.value)} + onKeyDown={onInputKeyDown} + /> + {accessory} +
+
+ {children} +
+ {footerKeys.length === 0 ? null : ( +
+ {footerKeys.map((hint) => ( + + {hint.keys} + {hint.label} + + ))} +
+ )} + + ); +} diff --git a/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx b/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx new file mode 100644 index 0000000000..e3de6ba888 --- /dev/null +++ b/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx @@ -0,0 +1,470 @@ +import { + useCallback, + useEffect, + useId, + useLayoutEffect, + useMemo, + useRef, + useState, + type KeyboardEvent as ReactKeyboardEvent, + type ReactNode, +} from "react"; +import { useStore } from "jotai"; +import { useIsCompactViewport } from "@bb/shared-ui/hooks/use-compact-viewport"; +import { cn } from "@bb/shared-ui/lib/utils"; +import { COARSE_POINTER_TEXT_SM_CLASS } from "@bb/shared-ui/coarse-pointer-sizing"; +import type { ThreadSearchHighlightRange } from "@bb/server-contract"; +import { useNewThreadDraftSlots } from "@/hooks/useNewThreadDraftSlots"; +import { useSidebarNavigation } from "@/hooks/queries/sidebar-navigation-query"; +import { + hasThreadSearchableQuery, + useArchivedThreads, + useThreadSearch, +} from "@/hooks/queries/thread-queries"; +import { useRouteNavigate } from "@/components/ui/app-route-anchor"; +import { getRootComposeRoutePath, getThreadRoutePath } from "@/lib/route-paths"; +import { withRootComposeDraftSlotId } from "@/lib/root-compose-location-state"; +import { openThreadInSplit } from "@/lib/split-layout/openThreadInSplit"; +import { + buildPaletteThreadSearchRows, + PALETTE_THREAD_SEARCH_SCOPES, + type PaletteThreadSearchRow, + type PaletteThreadSearchScope, +} from "@/lib/command-palette/palette-thread-search"; +import { windowPaletteThreadSearchText } from "@/lib/command-palette/palette-thread-search-window"; +import type { PaletteModeViewProps } from "@/lib/command-palette/palette-mode"; +import { PaletteShell } from "./PaletteShell"; + +export function ThreadSearchPaletteMode({ + onExit, + presentation, + runAfterClose, +}: PaletteModeViewProps) { + const listId = useId(); + const optionIdPrefix = useId(); + const inputRef = useRef(null); + const listRef = useRef(null); + const store = useStore(); + const navigate = useRouteNavigate(); + const isCompact = useIsCompactViewport(); + const [query, setQuery] = useState(""); + const [scope, setScope] = useState("all"); + const [highlightedIndex, setHighlightedIndex] = useState(0); + const [now] = useState(() => Date.now()); + const drafts = useNewThreadDraftSlots(); + const navigation = useSidebarNavigation(); + const archivedThreads = useArchivedThreads({}); + const threadSearch = useThreadSearch({ active: true, query }); + const trimmedQuery = query.trim(); + const searchable = hasThreadSearchableQuery(trimmedQuery); + const searchResultsAreCurrent = + !searchable || threadSearch.debouncedQuery === trimmedQuery; + + const projectNamesById = useMemo(() => { + const entries = [ + ...(navigation.data?.projects ?? []), + ...(navigation.data === undefined + ? [] + : [navigation.data.personalProject]), + ].map((project) => [project.id, project.name] as const); + return new Map(entries); + }, [navigation.data]); + const recentThreads = useMemo( + () => [ + ...(navigation.data?.projects.flatMap((project) => project.threads) ?? + []), + ...(navigation.data?.personalProject.threads ?? []), + ], + [navigation.data], + ); + const recentArchivedThreads = useMemo( + () => archivedThreads.data?.pages.flatMap((page) => page) ?? [], + [archivedThreads.data], + ); + const result = useMemo( + () => + buildPaletteThreadSearchRows({ + drafts, + now, + projectNamesById, + query, + recentArchivedThreads, + recentThreads, + scope, + searchResponse: threadSearch.data, + searchResultsAreCurrent, + }), + [ + drafts, + now, + projectNamesById, + query, + recentArchivedThreads, + recentThreads, + scope, + searchResultsAreCurrent, + threadSearch.data, + ], + ); + const activeIndex = + result.rows.length === 0 + ? -1 + : Math.min(highlightedIndex, result.rows.length - 1); + const activeDescendantId = + activeIndex < 0 ? undefined : `${optionIdPrefix}-${activeIndex}`; + + const scrollOnNextHighlightRef = useRef(false); + useEffect(() => { + if (!scrollOnNextHighlightRef.current) return; + scrollOnNextHighlightRef.current = false; + listRef.current + ?.querySelector('[aria-selected="true"]') + ?.scrollIntoView({ block: "nearest" }); + }, [activeIndex]); + + const openRow = useCallback( + (row: PaletteThreadSearchRow, split: boolean) => { + runAfterClose(() => { + if (row.threadId !== null) { + const state = + row.messageSeq === null + ? undefined + : { + searchMessageSeq: row.messageSeq, + searchThreadId: row.threadId, + }; + if (split) { + openThreadInSplit({ + store, + navigate, + projectId: row.projectId, + threadId: row.threadId, + isCompact, + state, + }); + return; + } + navigate( + getThreadRoutePath({ + projectId: row.projectId, + threadId: row.threadId, + }), + { state }, + ); + return; + } + if (row.draftSlotId !== null) { + navigate(getRootComposeRoutePath(), { + state: withRootComposeDraftSlotId( + { focusPrompt: true }, + row.draftSlotId, + ), + }); + } + }); + }, + [isCompact, navigate, runAfterClose, store], + ); + + const handleInputKeyDown = useCallback( + (event: ReactKeyboardEvent) => { + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + onExit(); + return; + } + if (result.rows.length === 0) return; + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault(); + scrollOnNextHighlightRef.current = true; + setHighlightedIndex((current) => { + if (event.key === "ArrowDown") { + return current + 1 >= result.rows.length ? 0 : current + 1; + } + return current <= 0 ? result.rows.length - 1 : current - 1; + }); + return; + } + if (event.key === "Home" || event.key === "End") { + event.preventDefault(); + scrollOnNextHighlightRef.current = true; + setHighlightedIndex(event.key === "Home" ? 0 : result.rows.length - 1); + return; + } + if (event.key === "Enter") { + const row = result.rows[activeIndex]; + if (row === undefined) return; + event.preventDefault(); + openRow(row, event.metaKey || event.ctrlKey); + } + }, + [activeIndex, onExit, openRow, result.rows], + ); + + const isLoading = + searchable && + (!searchResultsAreCurrent || + threadSearch.isDebouncing || + threadSearch.isLoading); + let emptyMessage: string | null = null; + if (result.rows.length === 0) { + emptyMessage = isLoading + ? "Searching threads" + : trimmedQuery.length === 1 + ? "Type at least 2 characters" + : (navigation.isLoading || archivedThreads.isLoading) && + result.isRecent + ? "Loading recent threads" + : result.isRecent + ? "No recent threads" + : "No matching threads"; + } + + return ( + { + setScope(nextScope); + setHighlightedIndex(0); + if (listRef.current !== null) listRef.current.scrollTop = 0; + }} + /> + } + footerKeys={presentation.footerKeys} + inputLabel={presentation.placeholder} + inputRef={inputRef} + listId={listId} + listLabel="Threads" + listRef={listRef} + modeChip={presentation.chip} + onInputChange={(value) => { + setQuery(value); + setHighlightedIndex(0); + if (listRef.current !== null) listRef.current.scrollTop = 0; + }} + onInputKeyDown={handleInputKeyDown} + placeholder={presentation.placeholder} + value={query} + > + {emptyMessage === null ? ( + result.rows.map((row, index) => ( + setHighlightedIndex(index)} + onSelect={() => openRow(row, false)} + /> + )) + ) : ( +

+ {emptyMessage} +

+ )} +
+ ); +} + +function ThreadSearchScopeFilter({ + inputRef, + onScopeChange, + scope, +}: { + inputRef: React.RefObject; + onScopeChange: (scope: PaletteThreadSearchScope) => void; + scope: PaletteThreadSearchScope; +}) { + const [open, setOpen] = useState(false); + const currentIndex = PALETTE_THREAD_SEARCH_SCOPES.findIndex( + (candidate) => candidate.id === scope, + ); + const current = PALETTE_THREAD_SEARCH_SCOPES[currentIndex]; + const returnToInput = () => { + setOpen(false); + inputRef.current?.focus({ preventScroll: true }); + }; + const cycle = (direction: 1 | -1) => { + const nextIndex = + (currentIndex + direction + PALETTE_THREAD_SEARCH_SCOPES.length) % + PALETTE_THREAD_SEARCH_SCOPES.length; + const next = PALETTE_THREAD_SEARCH_SCOPES[nextIndex]; + if (next !== undefined) onScopeChange(next.id); + setOpen(true); + }; + + return ( +
+ + {open ? ( +
+ {PALETTE_THREAD_SEARCH_SCOPES.map((option) => ( +
event.preventDefault()} + onClick={() => { + onScopeChange(option.id); + returnToInput(); + }} + > + {option.label} +
+ ))} +
+ ) : null} +
+ ); +} + +function ThreadSearchPaletteRow({ + id, + isActive, + onActivate, + onSelect, + row, +}: { + id: string; + isActive: boolean; + onActivate: () => void; + onSelect: () => void; + row: PaletteThreadSearchRow; +}) { + const primaryRef = useRef(null); + const matchKey = `${row.primaryText}\u0000${row.highlightRanges + .map((range) => `${range.start}:${range.end}`) + .join(",")}`; + const [windowedMatchKey, setWindowedMatchKey] = useState(null); + const shouldWindowMatch = windowedMatchKey === matchKey; + const primary = shouldWindowMatch + ? windowPaletteThreadSearchText({ + text: row.primaryText, + highlightRanges: row.highlightRanges, + }) + : { text: row.primaryText, highlightRanges: row.highlightRanges }; + + useLayoutEffect(() => { + if (shouldWindowMatch || row.highlightRanges.length === 0) return; + const container = primaryRef.current; + if (container === null) return; + const firstMatch = container.querySelector("mark"); + if (firstMatch === null) return; + const containerRect = container.getBoundingClientRect(); + const matchRect = firstMatch.getBoundingClientRect(); + if ( + matchRect.left < containerRect.left || + matchRect.right > containerRect.right + ) { + setWindowedMatchKey(matchKey); + } + }, [matchKey, row.highlightRanges.length, shouldWindowMatch]); + + const stateLabel = + row.lifecycle === "active" + ? null + : row.lifecycle === "draft" + ? "Draft" + : "Archived"; + return ( +
+ + + + + + {row.metadataText} + + + {stateLabel === null ? null : ( + + {stateLabel} + + )} +
+ ); +} + +function HighlightedText({ + ranges, + text, +}: { + ranges: readonly ThreadSearchHighlightRange[]; + text: string; +}) { + if (ranges.length === 0) return <>{text}; + const nodes: ReactNode[] = []; + let cursor = 0; + for (const range of ranges) { + const start = Math.max(cursor, Math.min(range.start, text.length)); + const end = Math.max(start, Math.min(range.end, text.length)); + if (end <= start) continue; + if (start > cursor) nodes.push(text.slice(cursor, start)); + nodes.push( + + {text.slice(start, end)} + , + ); + cursor = end; + } + if (cursor < text.length) nodes.push(text.slice(cursor)); + return nodes; +} diff --git a/apps/app/src/components/layout/AppLayout.root-compose-project.test.tsx b/apps/app/src/components/layout/AppLayout.root-compose-project.test.tsx index 1839a45e95..87f131a54e 100644 --- a/apps/app/src/components/layout/AppLayout.root-compose-project.test.tsx +++ b/apps/app/src/components/layout/AppLayout.root-compose-project.test.tsx @@ -16,6 +16,7 @@ vi.mock("@/components/commands/AppCommandProvider", () => ({ useAppCommandHandler: (command: string, handler: () => boolean) => { commandHandlers.set(command, handler); }, + useIndexedAppCommandHandlers: () => {}, useAppCommandShortcut: () => null, useAppCommandShortcuts: () => new Map(), useAppCommandRunner: () => ({ diff --git a/apps/app/src/components/layout/AppLayout.sidebar-resize.test.tsx b/apps/app/src/components/layout/AppLayout.sidebar-resize.test.tsx index a9fe9b2272..f2f2fc6249 100644 --- a/apps/app/src/components/layout/AppLayout.sidebar-resize.test.tsx +++ b/apps/app/src/components/layout/AppLayout.sidebar-resize.test.tsx @@ -10,6 +10,7 @@ const SIDEBAR_WIDTH_STORAGE_KEY = "bb.sidebar.width"; vi.mock("@/components/commands/AppCommandProvider", () => ({ useAppCommandHandler: () => {}, + useIndexedAppCommandHandlers: () => {}, useAppCommandShortcut: () => null, useAppCommandShortcuts: () => new Map(), useAppCommandRunner: () => ({ diff --git a/apps/app/src/lib/command-palette/palette-action.ts b/apps/app/src/lib/command-palette/palette-action.ts index 0212e93d2e..1736a78599 100644 --- a/apps/app/src/lib/command-palette/palette-action.ts +++ b/apps/app/src/lib/command-palette/palette-action.ts @@ -1,7 +1,16 @@ import type { AppShortcutPresentation } from "@/lib/app-keybindings"; +export const PALETTE_ACTION_BUCKETS = [ + "Threads", + "Actions", + "Plugins", +] as const; + +export type PaletteActionBucket = (typeof PALETTE_ACTION_BUCKETS)[number]; + export interface PaletteAction { id: string; + bucket: PaletteActionBucket; group: string; title: string; shortcut: AppShortcutPresentation | null; diff --git a/apps/app/src/lib/command-palette/palette-app-commands.test.ts b/apps/app/src/lib/command-palette/palette-app-commands.test.ts index ca90f7d23c..495515276e 100644 --- a/apps/app/src/lib/command-palette/palette-app-commands.test.ts +++ b/apps/app/src/lib/command-palette/palette-app-commands.test.ts @@ -71,11 +71,21 @@ describe("buildAppCommandActions", () => { ); expect(actions[0]).toMatchObject({ id: "app:thread.new", + bucket: "Threads", group: "Threads", shortcut: SHORTCUT, }); }); + it("buckets non-thread commands as actions without replacing their metadata group", () => { + const { actions } = build(["panel.toggle"]); + expect(actions[0]).toMatchObject({ + id: "app:panel.toggle", + bucket: "Actions", + group: "Window and layout", + }); + }); + it("leaves the shortcut null for a command the user has not bound", () => { const { actions } = build(["thread.rename"]); expect(actions[0]?.shortcut).toBeNull(); diff --git a/apps/app/src/lib/command-palette/palette-app-commands.ts b/apps/app/src/lib/command-palette/palette-app-commands.ts index 79c6cccfe7..d3815e76d1 100644 --- a/apps/app/src/lib/command-palette/palette-app-commands.ts +++ b/apps/app/src/lib/command-palette/palette-app-commands.ts @@ -35,6 +35,7 @@ export function buildAppCommandActions( if (!args.isCommandAvailable(command, args.target)) continue; actions.push({ id: paletteActionIdForCommand(command), + bucket: group.label === "Threads" ? "Threads" : "Actions", group: group.label, title: metadata.label, shortcut: args.shortcuts.get(command) ?? null, diff --git a/apps/app/src/lib/command-palette/palette-mode.ts b/apps/app/src/lib/command-palette/palette-mode.ts new file mode 100644 index 0000000000..b9ae2e7055 --- /dev/null +++ b/apps/app/src/lib/command-palette/palette-mode.ts @@ -0,0 +1,27 @@ +import type { ComponentType } from "react"; +import type { AppCommandId } from "@bb/domain"; +import type { IconName } from "@bb/shared-ui/icon"; + +export interface PaletteModePresentation { + chip: { + icon: IconName; + label: string; + }; + footerKeys: readonly { + keys: string; + label: string; + }[]; + placeholder: string; +} + +export interface PaletteModeViewProps { + onExit: () => void; + runAfterClose: (run: () => void) => void; + presentation: PaletteModePresentation; +} + +export interface PaletteModeRegistration extends PaletteModePresentation { + id: string; + entryCommand: AppCommandId; + View: ComponentType; +} diff --git a/apps/app/src/lib/command-palette/palette-modes.ts b/apps/app/src/lib/command-palette/palette-modes.ts new file mode 100644 index 0000000000..637bdf73d2 --- /dev/null +++ b/apps/app/src/lib/command-palette/palette-modes.ts @@ -0,0 +1,22 @@ +import type { PaletteModeRegistration } from "./palette-mode"; +import { ThreadSearchPaletteMode } from "@/components/commands/ThreadSearchPaletteMode"; + +export const PALETTE_MODES: readonly PaletteModeRegistration[] = [ + { + id: "thread-search", + entryCommand: "thread.search", + chip: { icon: "Search", label: "Threads" }, + placeholder: "Search threads", + footerKeys: [ + { keys: "↑↓", label: "Select" }, + { keys: "↵", label: "Open" }, + { keys: "⌘↵", label: "Open in split" }, + { keys: "Esc", label: "Back" }, + ], + View: ThreadSearchPaletteMode, + }, +]; + +export const PALETTE_MODE_ENTRY_COMMANDS = PALETTE_MODES.map( + (mode) => mode.entryCommand, +); diff --git a/apps/app/src/lib/command-palette/palette-plugin-actions.test.ts b/apps/app/src/lib/command-palette/palette-plugin-actions.test.ts index 407bdce73a..9efe95d8a9 100644 --- a/apps/app/src/lib/command-palette/palette-plugin-actions.test.ts +++ b/apps/app/src/lib/command-palette/palette-plugin-actions.test.ts @@ -1,6 +1,10 @@ -import { describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import type { PluginThreadPanelOpenHandler } from "@/components/plugin/plugin-thread-panel-navigation"; import type { PluginCommandPaletteActionSlot } from "@/lib/plugin-slots"; +import { + resetPluginLogoStoreForTest, + setPluginLogoUrls, +} from "@/lib/plugin-logos"; import { buildPluginPaletteActions } from "./palette-plugin-actions"; function slot( @@ -27,7 +31,42 @@ function build( }); } +afterEach(() => { + resetPluginLogoStoreForTest(); + vi.restoreAllMocks(); +}); + describe("buildPluginPaletteActions", () => { + it("buckets plugin actions together and attributes them to the manifest name", () => { + setPluginLogoUrls( + new Map([ + [ + "linear", + { + displayName: "Linear", + icon: null, + compactIconUrl: null, + logoUrl: null, + logoDarkUrl: null, + icons: new Map(), + }, + ], + ]), + ); + + expect(build([slot({ id: "listed" })])[0]).toMatchObject({ + bucket: "Plugins", + group: "Linear", + }); + }); + + it("uses the stable plugin id when the manifest name is unavailable", () => { + expect(build([slot({ id: "listed" })])[0]).toMatchObject({ + bucket: "Plugins", + group: "linear", + }); + }); + it("drops a row whose isAvailable declines or throws", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const rows = build([ diff --git a/apps/app/src/lib/command-palette/palette-plugin-actions.ts b/apps/app/src/lib/command-palette/palette-plugin-actions.ts index a271871a2f..43af2fea64 100644 --- a/apps/app/src/lib/command-palette/palette-plugin-actions.ts +++ b/apps/app/src/lib/command-palette/palette-plugin-actions.ts @@ -1,6 +1,7 @@ import type { PluginCommandPaletteActionContext } from "@get-bb/plugin-sdk"; import type { PluginThreadPanelOpenHandler } from "@/components/plugin/plugin-thread-panel-navigation"; import type { PluginCommandPaletteActionSlot } from "@/lib/plugin-slots"; +import { getPluginDisplayName } from "@/lib/plugin-logos"; import type { PaletteAction } from "./palette-action"; export interface BuildPluginPaletteActionsArgs { @@ -53,7 +54,8 @@ export function buildPluginPaletteActions( } actions.push({ id: `plugin:${slot.pluginId}/${slot.id}`, - group: "Plugins", + bucket: "Plugins", + group: getPluginDisplayName(slot.pluginId), title: slot.title, shortcut: null, run: () => { diff --git a/apps/app/src/lib/command-palette/palette-ranking.test.ts b/apps/app/src/lib/command-palette/palette-ranking.test.ts index b6ed514918..f4bdd81b26 100644 --- a/apps/app/src/lib/command-palette/palette-ranking.test.ts +++ b/apps/app/src/lib/command-palette/palette-ranking.test.ts @@ -3,7 +3,14 @@ import type { PaletteAction } from "./palette-action"; import { rankPaletteActions } from "./palette-ranking"; function action(id: string, title: string, group: string): PaletteAction { - return { id, title, group, shortcut: null, run: () => {} }; + return { + id, + bucket: group === "Threads" ? "Threads" : "Actions", + title, + group, + shortcut: null, + run: () => {}, + }; } const ACTIONS: readonly PaletteAction[] = [ diff --git a/apps/app/src/lib/command-palette/palette-thread-search-window.test.ts b/apps/app/src/lib/command-palette/palette-thread-search-window.test.ts new file mode 100644 index 0000000000..30826b15ea --- /dev/null +++ b/apps/app/src/lib/command-palette/palette-thread-search-window.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from "vitest"; +import { windowPaletteThreadSearchText } from "./palette-thread-search-window"; + +function highlightedText( + result: ReturnType, +): string[] { + return result.highlightRanges.map((range) => + result.text.slice(range.start, range.end), + ); +} + +describe("windowPaletteThreadSearchText", () => { + it("returns short text whole without ellipses", () => { + expect( + windowPaletteThreadSearchText({ + text: "A short matched message", + highlightRanges: [{ start: 8, end: 15 }], + }), + ).toEqual({ + text: "A short matched message", + highlightRanges: [{ start: 8, end: 15 }], + }); + }); + + it("marks both real cuts and preserves the first match", () => { + const text = `${"left".repeat(12)} needle ${"right".repeat(12)}`; + const matchStart = text.indexOf("needle"); + const result = windowPaletteThreadSearchText({ + text, + highlightRanges: [{ start: matchStart, end: matchStart + 6 }], + }); + + expect(result.text.startsWith("…")).toBe(true); + expect(result.text.endsWith("…")).toBe(true); + expect(highlightedText(result)).toEqual(["needle"]); + }); + + it("moves hard targets inward to whitespace word boundaries", () => { + const text = + "prefix alpha beta gamma delta MATCH one two three four five six seven trailing"; + const matchStart = text.indexOf("MATCH"); + const result = windowPaletteThreadSearchText({ + text, + highlightRanges: [{ start: matchStart, end: matchStart + 5 }], + }); + + expect(result.text).toBe( + "…gamma delta MATCH one two three four five six seven…", + ); + }); + + it("rebases every retained range and merges overlapping input", () => { + const text = `${"x".repeat(24)} first middle second ${"y".repeat(50)}`; + const firstStart = text.indexOf("first"); + const secondStart = text.indexOf("second"); + const result = windowPaletteThreadSearchText({ + text, + highlightRanges: [ + { start: secondStart + 3, end: secondStart + 6 }, + { start: firstStart + 2, end: firstStart + 5 }, + { start: firstStart, end: firstStart + 3 }, + { start: secondStart, end: secondStart + 4 }, + ], + }); + + expect(highlightedText(result)).toEqual(["first", "second"]); + expect(result.highlightRanges[0]?.start).toBe( + result.text.indexOf("first"), + ); + expect(result.highlightRanges[1]?.start).toBe( + result.text.indexOf("second"), + ); + }); + + it("clamps finite out-of-range input and drops malformed ranges", () => { + const result = windowPaletteThreadSearchText({ + text: "match remains", + highlightRanges: [ + { start: Number.NaN, end: 3 }, + { start: 9, end: 4 }, + { start: 100, end: 200 }, + { start: -20, end: 5.9 }, + ], + }); + + expect(result).toEqual({ + text: "match remains", + highlightRanges: [{ start: 0, end: 5 }], + }); + }); + + it("adds an ellipsis only on the side actually cut near either edge", () => { + const nearStartText = `match ${"tail".repeat(20)}`; + const nearStart = windowPaletteThreadSearchText({ + text: nearStartText, + highlightRanges: [{ start: 0, end: 5 }], + }); + expect(nearStart.text.startsWith("…")).toBe(false); + expect(nearStart.text.endsWith("…")).toBe(true); + + const nearEndText = `${"lead".repeat(20)} match`; + const matchStart = nearEndText.indexOf("match"); + const nearEnd = windowPaletteThreadSearchText({ + text: nearEndText, + highlightRanges: [{ start: matchStart, end: nearEndText.length }], + }); + expect(nearEnd.text.startsWith("…")).toBe(true); + expect(nearEnd.text.endsWith("…")).toBe(false); + }); + + it("never leaves either hard cut inside an emoji surrogate pair", () => { + const emoji = "\u{1f600}"; + const text = `${"a".repeat(15)}${emoji}${"b".repeat(15)}MATCH${"c".repeat( + 39, + )}${emoji}${"d".repeat(20)}`; + const matchStart = text.indexOf("MATCH"); + const result = windowPaletteThreadSearchText({ + text, + highlightRanges: [{ start: matchStart, end: matchStart + 5 }], + }); + + expect(result.text).not.toMatch(/[\uD800-\uDFFF]/u); + expect(highlightedText(result)).toEqual(["MATCH"]); + }); + + it("keeps a first match longer than the normal tail window in full", () => { + const match = "m".repeat(60); + const text = `${"lead".repeat(10)}${match}${"tail".repeat(20)}`; + const matchStart = text.indexOf(match); + const result = windowPaletteThreadSearchText({ + text, + highlightRanges: [ + { start: matchStart, end: matchStart + match.length }, + ], + }); + + expect(highlightedText(result)).toEqual([match]); + }); +}); diff --git a/apps/app/src/lib/command-palette/palette-thread-search-window.ts b/apps/app/src/lib/command-palette/palette-thread-search-window.ts new file mode 100644 index 0000000000..ee2e12708e --- /dev/null +++ b/apps/app/src/lib/command-palette/palette-thread-search-window.ts @@ -0,0 +1,165 @@ +import type { ThreadSearchHighlightRange } from "@bb/server-contract"; + +const THREAD_SEARCH_WINDOW_LEAD_CHARS = 16; +const THREAD_SEARCH_WINDOW_TAIL_CHARS = 40; +const THREAD_SEARCH_WINDOW_ELLIPSIS = "…"; + +export interface WindowPaletteThreadSearchTextArgs { + text: string; + highlightRanges: readonly ThreadSearchHighlightRange[]; +} + +export interface WindowedPaletteThreadSearchText { + text: string; + highlightRanges: ThreadSearchHighlightRange[]; +} + +function isHighSurrogate(text: string, index: number): boolean { + const code = text.charCodeAt(index); + return code >= 0xd800 && code <= 0xdbff; +} + +function isLowSurrogate(text: string, index: number): boolean { + const code = text.charCodeAt(index); + return code >= 0xdc00 && code <= 0xdfff; +} + +function isInsideSurrogatePair(text: string, index: number): boolean { + return ( + index > 0 && + index < text.length && + isHighSurrogate(text, index - 1) && + isLowSurrogate(text, index) + ); +} + +function clampInteger(value: number, maximum: number): number | null { + if (!Number.isFinite(value)) { + return null; + } + return Math.max(0, Math.min(Math.trunc(value), maximum)); +} + +function normalizeHighlightRanges( + text: string, + ranges: readonly ThreadSearchHighlightRange[], +): ThreadSearchHighlightRange[] { + const normalized: ThreadSearchHighlightRange[] = []; + + for (const range of ranges) { + let start = clampInteger(range.start, text.length); + let end = clampInteger(range.end, text.length); + if (start === null || end === null || end <= start) { + continue; + } + + if (isInsideSurrogatePair(text, start)) { + start -= 1; + } + if (isInsideSurrogatePair(text, end)) { + end += 1; + } + + normalized.push({ start, end }); + } + + normalized.sort( + (left, right) => left.start - right.start || left.end - right.end, + ); + + const merged: ThreadSearchHighlightRange[] = []; + for (const range of normalized) { + const previous = merged.at(-1); + if (previous !== undefined && range.start < previous.end) { + previous.end = Math.max(previous.end, range.end); + continue; + } + merged.push({ ...range }); + } + return merged; +} + +function moveStartToWordBoundary( + text: string, + start: number, + firstMatchStart: number, +): number { + if (start === 0) { + return start; + } + const firstWhitespace = text.slice(start, firstMatchStart).search(/\s/u); + if (firstWhitespace === -1) { + return start; + } + + let boundary = start + firstWhitespace + 1; + while (boundary < firstMatchStart && /\s/u.test(text[boundary] ?? "")) { + boundary += 1; + } + return boundary; +} + +function moveEndToWordBoundary( + text: string, + firstMatchEnd: number, + end: number, +): number { + if (end === text.length) { + return end; + } + const lastWhitespace = text + .slice(firstMatchEnd, end) + .search(/\s\S*$/u); + return lastWhitespace > 0 ? firstMatchEnd + lastWhitespace : end; +} + +export function windowPaletteThreadSearchText({ + text, + highlightRanges, +}: WindowPaletteThreadSearchTextArgs): WindowedPaletteThreadSearchText { + const normalizedRanges = normalizeHighlightRanges(text, highlightRanges); + const firstMatch = normalizedRanges[0]; + if (firstMatch === undefined) { + return { text, highlightRanges: [] }; + } + + let start = Math.max( + 0, + firstMatch.start - THREAD_SEARCH_WINDOW_LEAD_CHARS, + ); + let end = Math.min( + text.length, + firstMatch.end + THREAD_SEARCH_WINDOW_TAIL_CHARS, + ); + + start = moveStartToWordBoundary(text, start, firstMatch.start); + end = moveEndToWordBoundary(text, firstMatch.end, end); + + if (isInsideSurrogatePair(text, start)) { + start += 1; + } + if (isInsideSurrogatePair(text, end)) { + end -= 1; + } + + const prefix = start > 0 ? THREAD_SEARCH_WINDOW_ELLIPSIS : ""; + const suffix = end < text.length ? THREAD_SEARCH_WINDOW_ELLIPSIS : ""; + const rebasedRanges: ThreadSearchHighlightRange[] = []; + + for (const range of normalizedRanges) { + const rangeStart = Math.max(range.start, start); + const rangeEnd = Math.min(range.end, end); + if (rangeEnd <= rangeStart) { + continue; + } + rebasedRanges.push({ + start: rangeStart - start + prefix.length, + end: rangeEnd - start + prefix.length, + }); + } + + return { + text: `${prefix}${text.slice(start, end)}${suffix}`, + highlightRanges: rebasedRanges, + }; +} diff --git a/apps/app/src/lib/command-palette/palette-thread-search.test.ts b/apps/app/src/lib/command-palette/palette-thread-search.test.ts new file mode 100644 index 0000000000..f35a6e00a5 --- /dev/null +++ b/apps/app/src/lib/command-palette/palette-thread-search.test.ts @@ -0,0 +1,181 @@ +import { emptyPromptDraftState } from "@bb/client-core"; +import type { ThreadListEntry } from "@bb/domain"; +import type { ThreadSearchResponse } from "@bb/server-contract"; +import { describe, expect, it, vi } from "vitest"; +import type { NewThreadDraftRow } from "@/hooks/useNewThreadDraftSlots"; +import { buildPaletteThreadSearchRows } from "./palette-thread-search"; + +const NOW = 1_000_000; + +function makeThread( + id: string, + overrides: Partial = {}, +): ThreadListEntry { + return { + id, + projectId: "project-1", + environmentId: null, + providerId: "codex", + title: `Title ${id}`, + titleFallback: `Fallback ${id}`, + sectionId: null, + status: "idle", + parentThreadId: null, + sourceThreadId: null, + originKind: null, + originPluginId: null, + visibility: "visible", + archivedAt: null, + pinnedAt: null, + pinSortKey: null, + deletedAt: null, + lastReadAt: null, + latestAttentionAt: 1, + createdAt: 1, + updatedAt: NOW, + activity: { + activeWorkflowCount: 0, + activeBackgroundAgentCount: 0, + activeBackgroundCommandCount: 0, + activePlanModeCount: 0, + activeGoalCount: 0, + }, + hasPendingInteraction: false, + environmentHostId: null, + environmentName: null, + environmentBranchName: null, + environmentWorkspaceDisplayKind: "other", + runtime: { displayStatus: "idle", hostReconnectGraceExpiresAt: null }, + ...overrides, + }; +} + +function makeDraft(id: string, title: string): NewThreadDraftRow { + return { + id, + title, + draft: { ...emptyPromptDraftState(), text: title }, + lastEditedAt: NOW, + destination: { projectId: "project-1", sectionId: null }, + delete: vi.fn(), + }; +} + +function build( + overrides: Partial[0]> = {}, +) { + return buildPaletteThreadSearchRows({ + drafts: [], + now: NOW, + projectNamesById: new Map([["project-1", "Palette project"]]), + query: "match", + recentArchivedThreads: [], + recentThreads: [], + scope: "all", + searchResponse: { + active: { results: [], total: 0 }, + archived: { results: [], total: 0 }, + }, + searchResultsAreCurrent: true, + ...overrides, + }); +} + +describe("buildPaletteThreadSearchRows", () => { + it("builds one active, draft, archived list with a local draft total", () => { + const active = makeThread("active"); + const archived = makeThread("archived", { archivedAt: NOW - 1 }); + const searchResponse: ThreadSearchResponse = { + active: { + total: 1, + results: [{ thread: active, matches: [] }], + }, + archived: { + total: 1, + results: [{ thread: archived, matches: [] }], + }, + }; + + const result = build({ + drafts: [makeDraft("draft", "A matching local draft")], + searchResponse, + }); + + expect(result.rows.map((row) => row.lifecycle)).toEqual([ + "active", + "draft", + "archived", + ]); + expect(result.draftMatchCount).toBe(1); + }); + + it("narrows lifecycle immediately without changing row anatomy", () => { + const result = build({ + drafts: [makeDraft("draft", "A matching local draft")], + scope: "draft", + }); + + expect(result.rows).toMatchObject([ + { + lifecycle: "draft", + metadataText: "Palette project · just now", + projectId: "project-1", + draftSlotId: "draft", + }, + ]); + }); + + it("uses the matched message as primary while retaining title, project, and time metadata", () => { + const thread = makeThread("message", { title: "Original title" }); + const result = build({ + searchResponse: { + active: { + total: 1, + results: [ + { + thread, + matches: [ + { + sourceKind: "user_message", + text: "the matching message", + highlightRanges: [{ start: 4, end: 12 }], + sourceSeq: 42, + }, + ], + }, + ], + }, + archived: { results: [], total: 0 }, + }, + }); + + expect(result.rows[0]).toMatchObject({ + primaryText: "the matching message", + metadataText: "Original title · Palette project · just now", + messageSeq: 42, + }); + }); + + it("orders active, draft, and archived recents and does not reuse them for a one-character query", () => { + const active = makeThread("recent-active"); + const archived = makeThread("recent-archived", { archivedAt: NOW - 1 }); + const recents = build({ + drafts: [makeDraft("recent-draft", "Recent draft")], + query: "", + recentArchivedThreads: [archived], + recentThreads: [active], + }); + expect(recents).toMatchObject({ + isRecent: true, + rows: [ + { id: "active:recent-active" }, + { id: "draft:recent-draft" }, + { id: "archived:recent-archived" }, + ], + }); + expect(build({ query: "m", recentThreads: [active] })).toMatchObject({ + isRecent: false, + rows: [], + }); + }); +}); diff --git a/apps/app/src/lib/command-palette/palette-thread-search.ts b/apps/app/src/lib/command-palette/palette-thread-search.ts new file mode 100644 index 0000000000..11c54d341e --- /dev/null +++ b/apps/app/src/lib/command-palette/palette-thread-search.ts @@ -0,0 +1,212 @@ +import { PERSONAL_PROJECT_ID, type ThreadListEntry } from "@bb/domain"; +import { fuzzyMatchText } from "@bb/fuzzy-match"; +import type { + ThreadSearchHighlightRange, + ThreadSearchMatch, + ThreadSearchResponse, +} from "@bb/server-contract"; +import type { NewThreadDraftRow } from "@/hooks/useNewThreadDraftSlots"; +import { formatRelativeTime } from "@/lib/relative-time"; +import { getThreadDisplayTitle } from "@/lib/thread-title"; + +export const PALETTE_THREAD_SEARCH_SCOPES = [ + { id: "all", label: "All" }, + { id: "active", label: "Active" }, + { id: "draft", label: "Drafts" }, + { id: "archived", label: "Archived" }, +] as const; + +export type PaletteThreadSearchScope = + (typeof PALETTE_THREAD_SEARCH_SCOPES)[number]["id"]; +export type PaletteThreadLifecycle = "active" | "draft" | "archived"; + +export interface PaletteThreadSearchRow { + id: string; + lifecycle: PaletteThreadLifecycle; + primaryText: string; + highlightRanges: readonly ThreadSearchHighlightRange[]; + metadataText: string; + projectId: string; + threadId: string | null; + draftSlotId: string | null; + messageSeq: number | null; +} + +interface BuildPaletteThreadSearchRowsArgs { + drafts: readonly NewThreadDraftRow[]; + now: number; + projectNamesById: ReadonlyMap; + query: string; + recentArchivedThreads: readonly ThreadListEntry[]; + recentThreads: readonly ThreadListEntry[]; + scope: PaletteThreadSearchScope; + searchResponse: ThreadSearchResponse | undefined; + searchResultsAreCurrent: boolean; +} + +export interface PaletteThreadSearchRowsResult { + draftMatchCount: number; + isRecent: boolean; + rows: PaletteThreadSearchRow[]; +} + +const RECENT_THREAD_LIMIT = 20; + +function isTitleMatch(match: ThreadSearchMatch): boolean { + return match.sourceKind === "title" || match.sourceKind === "title_fallback"; +} + +function projectMetadata( + projectId: string, + projectNamesById: ReadonlyMap, +): string | null { + return projectId === PERSONAL_PROJECT_ID + ? null + : (projectNamesById.get(projectId) ?? null); +} + +function metadataText(parts: readonly (string | null)[]): string { + return parts.filter((part): part is string => Boolean(part)).join(" · "); +} + +function serverRow( + thread: ThreadListEntry, + matches: readonly ThreadSearchMatch[], + lifecycle: "active" | "archived", + projectNamesById: ReadonlyMap, + now: number, +): PaletteThreadSearchRow { + const title = getThreadDisplayTitle(thread); + const titleMatch = matches.find( + (match) => isTitleMatch(match) && match.text === title, + ); + const snippetMatch = matches.find((match) => !isTitleMatch(match)); + const primaryMatch = snippetMatch ?? titleMatch; + return { + id: `${lifecycle}:${thread.id}`, + lifecycle, + primaryText: primaryMatch?.text ?? title, + highlightRanges: primaryMatch?.highlightRanges ?? [], + metadataText: metadataText([ + snippetMatch === undefined ? null : title, + projectMetadata(thread.projectId, projectNamesById), + formatRelativeTime({ timestamp: thread.updatedAt, now }), + ]), + projectId: thread.projectId, + threadId: thread.id, + draftSlotId: null, + messageSeq: snippetMatch?.sourceSeq ?? null, + }; +} + +function draftHighlightRanges( + text: string, + positions: readonly number[], +): ThreadSearchHighlightRange[] { + const offsets = [0]; + for (const character of text) { + offsets.push((offsets.at(-1) ?? 0) + character.length); + } + const ranges: ThreadSearchHighlightRange[] = []; + for (const position of [...positions].sort((left, right) => left - right)) { + const start = offsets[position]; + const end = offsets[position + 1]; + if (start === undefined || end === undefined) continue; + const prior = ranges.at(-1); + if (prior !== undefined && prior.end === start) { + prior.end = end; + } else { + ranges.push({ start, end }); + } + } + return ranges; +} + +function includesLifecycle( + scope: PaletteThreadSearchScope, + lifecycle: PaletteThreadLifecycle, +): boolean { + return scope === "all" || scope === lifecycle; +} + +export function buildPaletteThreadSearchRows({ + drafts, + now, + projectNamesById, + query, + recentArchivedThreads, + recentThreads, + scope, + searchResponse, + searchResultsAreCurrent, +}: BuildPaletteThreadSearchRowsArgs): PaletteThreadSearchRowsResult { + const trimmedQuery = query.trim(); + const isRecent = trimmedQuery.length === 0; + const isSearchable = trimmedQuery.length >= 2; + const activeRows = isRecent + ? recentThreads + .slice(0, RECENT_THREAD_LIMIT) + .map((thread) => serverRow(thread, [], "active", projectNamesById, now)) + : isSearchable && searchResultsAreCurrent + ? (searchResponse?.active.results ?? []).map((result) => + serverRow( + result.thread, + result.matches, + "active", + projectNamesById, + now, + ), + ) + : []; + + const draftMatches = + isRecent || isSearchable + ? fuzzyMatchText({ + items: drafts, + query: trimmedQuery, + getText: (draft) => draft.title, + limit: drafts.length, + }) + : []; + const draftRows = draftMatches.map(({ item, positions }) => ({ + id: `draft:${item.id}`, + lifecycle: "draft" as const, + primaryText: item.title, + highlightRanges: draftHighlightRanges(item.title, positions), + metadataText: metadataText([ + projectMetadata(item.destination.projectId, projectNamesById), + formatRelativeTime({ timestamp: item.lastEditedAt, now }), + ]), + projectId: item.destination.projectId, + threadId: null, + draftSlotId: item.id, + messageSeq: null, + })); + const archivedRows = isRecent + ? recentArchivedThreads + .slice(0, RECENT_THREAD_LIMIT) + .map((thread) => + serverRow(thread, [], "archived", projectNamesById, now), + ) + : isSearchable && searchResultsAreCurrent + ? (searchResponse?.archived.results ?? []).map((result) => + serverRow( + result.thread, + result.matches, + "archived", + projectNamesById, + now, + ), + ) + : []; + + return { + draftMatchCount: draftMatches.length, + isRecent, + rows: [ + ...(includesLifecycle(scope, "active") ? activeRows : []), + ...(includesLifecycle(scope, "draft") ? draftRows : []), + ...(includesLifecycle(scope, "archived") ? archivedRows : []), + ], + }; +} diff --git a/apps/app/src/lib/plugin-logos.ts b/apps/app/src/lib/plugin-logos.ts index cba055f43f..9ead7a00cb 100644 --- a/apps/app/src/lib/plugin-logos.ts +++ b/apps/app/src/lib/plugin-logos.ts @@ -31,6 +31,10 @@ function getPluginLogoUrls(): ReadonlyMap { return logoUrls; } +export function getPluginDisplayName(pluginId: string): string { + return getPluginLogoUrls().get(pluginId)?.displayName ?? pluginId; +} + export function usePluginCompactBranding( pluginId: string, ): Pick | null { diff --git a/apps/app/src/lib/split-layout/openThreadInSplit.test.ts b/apps/app/src/lib/split-layout/openThreadInSplit.test.ts new file mode 100644 index 0000000000..46534055d3 --- /dev/null +++ b/apps/app/src/lib/split-layout/openThreadInSplit.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it, vi } from "vitest"; +import { openThreadInSplit } from "./openThreadInSplit"; +import type { SplitLayout } from "./index"; + +function layout(threadId = "thread-1"): SplitLayout { + return { + root: { + type: "pane", + paneId: "pane-1", + content: { kind: "thread", projectId: "project-1", threadId }, + }, + focusedPaneId: "pane-1", + }; +} + +describe("openThreadInSplit", () => { + it("preserves search deep-link state when creating a split", () => { + let current = layout(); + const navigate = vi.fn(); + openThreadInSplit({ + store: { + get: () => current, + set: (_atom, value) => { + current = value; + }, + }, + navigate, + projectId: "project-1", + threadId: "thread-2", + isCompact: false, + state: { searchMessageSeq: 42, searchThreadId: "thread-2" }, + }); + + expect(current.root.type).toBe("split"); + expect(navigate).toHaveBeenCalledWith( + "/projects/project-1/threads/thread-2", + { + state: { searchMessageSeq: 42, searchThreadId: "thread-2" }, + }, + ); + }); + + it("keeps replace semantics and state when the result is already open", () => { + const current = layout("thread-2"); + const navigate = vi.fn(); + openThreadInSplit({ + store: { get: () => current, set: vi.fn() }, + navigate, + projectId: "project-1", + threadId: "thread-2", + isCompact: false, + state: { searchMessageSeq: 7, searchThreadId: "thread-2" }, + }); + + expect(navigate).toHaveBeenCalledWith( + "/projects/project-1/threads/thread-2", + { + replace: true, + state: { searchMessageSeq: 7, searchThreadId: "thread-2" }, + }, + ); + }); +}); diff --git a/apps/app/src/lib/split-layout/openThreadInSplit.ts b/apps/app/src/lib/split-layout/openThreadInSplit.ts index 2504b894e3..5dfce7cb68 100644 --- a/apps/app/src/lib/split-layout/openThreadInSplit.ts +++ b/apps/app/src/lib/split-layout/openThreadInSplit.ts @@ -19,10 +19,14 @@ interface SplitLayoutStore { interface OpenThreadInSplitArgs { store: SplitLayoutStore; - navigate: (route: string, options?: { replace?: boolean }) => void; + navigate: ( + route: string, + options?: { replace?: boolean; state?: Record }, + ) => void; projectId: string; threadId: string; isCompact: boolean; + state?: Record; } export function openThreadInSplit({ @@ -31,11 +35,12 @@ export function openThreadInSplit({ projectId, threadId, isCompact, + state, }: OpenThreadInSplitArgs): void { const route = getThreadRoutePath({ projectId, threadId }); const layout = store.get(splitLayoutAtom); if (isCompact || layout === null) { - navigate(route); + navigate(route, state === undefined ? undefined : { state }); return; } const existing = findPaneByThread(layout.root, projectId, threadId); @@ -44,7 +49,10 @@ export function openThreadInSplit({ if (next !== layout) { store.set(splitLayoutAtom, next); } - navigate(route, { replace: true }); + navigate(route, { + replace: true, + ...(state === undefined ? {} : { state }), + }); return; } const decision = decideThreadDrop({ @@ -60,5 +68,5 @@ export function openThreadInSplit({ if (next !== layout) { store.set(splitLayoutAtom, next); } - navigate(route); + navigate(route, state === undefined ? undefined : { state }); } diff --git a/packages/plugin-api-map/src/anatomy-manifest.json b/packages/plugin-api-map/src/anatomy-manifest.json index 62097f759e..1a26c071ca 100644 --- a/packages/plugin-api-map/src/anatomy-manifest.json +++ b/packages/plugin-api-map/src/anatomy-manifest.json @@ -39,16 +39,18 @@ "path": "apps/app/src/components/commands/CommandPalette.tsx", "anchors": [ "top-[12%] max-w-xl translate-y-0 gap-0 p-0", - "aria-label={inputLabel}", - "role=\"listbox\"", "aria-selected={isActive}", "LAUNCHER_ACTION_ROW_BASE_CLASS", "bg-state-hover text-foreground" ] }, + { + "path": "apps/app/src/components/commands/PaletteShell.tsx", + "anchors": ["aria-label={inputLabel}", "role=\"listbox\""] + }, { "path": "apps/app/src/lib/command-palette/palette-plugin-actions.ts", - "anchors": ["group: \"Plugins\"", "run: () =>"] + "anchors": ["bucket: \"Plugins\"", "run: () =>"] }, { "path": "apps/app/src/components/commands/CommandPalette.test.tsx", diff --git a/packages/plugin-api-map/test/scaffold-surface-entry.test.ts b/packages/plugin-api-map/test/scaffold-surface-entry.test.ts index fa825b8534..caa5ff4832 100644 --- a/packages/plugin-api-map/test/scaffold-surface-entry.test.ts +++ b/packages/plugin-api-map/test/scaffold-surface-entry.test.ts @@ -100,6 +100,8 @@ describe("surface-entry scaffold", () => { "apps/app/src/components/commands/CommandPalette.test.tsx", "--source", "apps/app/src/components/commands/CommandPalette.tsx", + "--source", + "apps/app/src/components/commands/PaletteShell.tsx", "--api-symbol", "PluginCommandPaletteActionRegistration", "--api-symbol", @@ -115,6 +117,8 @@ describe("surface-entry scaffold", () => { "--source", "apps/app/src/components/commands/CommandPalette.tsx", "--source", + "apps/app/src/components/commands/PaletteShell.tsx", + "--source", "apps/app/src/components/commands/CommandPalette.test.tsx", "--group", "command-palette", @@ -157,6 +161,10 @@ describe("surface-entry scaffold", () => { path: "apps/app/src/components/commands/CommandPalette.tsx", anchors: ["TODO: Add a stable source anchor"], }, + { + path: "apps/app/src/components/commands/PaletteShell.tsx", + anchors: ["TODO: Add a stable source anchor"], + }, { path: "apps/app/src/lib/command-palette/palette-plugin-actions.ts", anchors: ["TODO: Add a stable source anchor"], diff --git a/plans/bb-mobile-research/ui-inventory.md b/plans/bb-mobile-research/ui-inventory.md index 3d81d29996..65255ca61c 100644 --- a/plans/bb-mobile-research/ui-inventory.md +++ b/plans/bb-mobile-research/ui-inventory.md @@ -20,7 +20,7 @@ Providers, outer→inner: `AppErrorBoundary` (main.tsx:60; class boundary, fallb `SidebarProvider` + `AppLayoutSidebar` (mode app/settings/tools, AppLayoutSidebar.tsx:47-77) + `SidebarInset` + `AppHeader` (hidden on thread/root/plugin-panel routes, AppLayout.tsx:576) + fixed `SidebarTriggerOverlay` (AppLayout.tsx:218) + global `ProjectPathDialog` (AppLayout.tsx:877). Handles commands `sidebar.toggle`, `thread.new`, `settings.open`, `settings.openServers` (AppLayout.tsx:174,481-495), `wsManager.onThreadOpen` navigation, favicon badge, `document.title`. Sidebar width/open persisted (`bb.sidebar.width|open`, AppLayout.tsx:96-144); resize handle desktop-only (`hidden md:block`, AppSidebar.tsx:404); mouse-only resize (AppLayout.tsx:742-812). Compact viewport = `(max-width: 767px)` (`useIsCompactViewport`, shared-ui hooks/use-compact-viewport.tsx:10); sidebar becomes swipe-open/drag-close overlay drawer (`SidebarMobilePanel`, components/ui/sidebar.tsx:20,732-754,1065). iOS keyboard viewport fixups: `useMobileVisualViewportHeight` (AppLayout.tsx:410). ## App sidebar (components/sidebar/AppSidebar.tsx) -Rows: history back/forward (top reserve), "New thread" (+ split mini-map desktop) + thread search (AppSidebar.tsx:314-327; `useSidebarThreadSearch`), `PluginNavSidebarItems` (Extensions row + plugin navPanels, reorder/hide via `bb.sidebar.pluginPanelOrder|hiddenPluginPanels`), `PluginThreadList` → `ProjectList` (org modes project/machine/manual + sort updated/created/alpha via `SidebarDisplayOptionsMenu`, ProjectList.tsx:621-739; section create/rename/delete dialogs ProjectList.tsx:1979-2012; Pinned section; dnd-kit drag reorder), footer: Settings link, plugin footer actions, Report bug (external), `SidebarUpdatesBadge`. ThreadRow kebab hidden on compact+coarse (`max-md:pointer-coarse:hidden`, ThreadRow.tsx:821); Radix ContextMenu (long-press) still wraps rows (ThreadRow.tsx:854). Thread menu items: Open in split, Mark read/unread, Pin/Unpin, Rename, Archive/Unarchive, Delete (ThreadActionsMenu.tsx:175-248). Project menu: Project settings, Rename, Add local path, Remove (ProjectActionsMenu.tsx:130-169). Section header actions: display options, New project, New section, New thread (ProjectList.tsx:566-617). Keyboard: `thread.search`, `thread.jump.N`, `thread.previous/next` handled here (AppSidebar.tsx:221-230). +Rows: history back/forward (top reserve), "New thread" (+ split mini-map desktop), `PluginNavSidebarItems` (Extensions row + plugin navPanels, reorder/hide via `bb.sidebar.pluginPanelOrder|hiddenPluginPanels`), `PluginThreadList` → `ProjectList` (org modes project/machine/manual + sort updated/created/alpha via `SidebarDisplayOptionsMenu`, ProjectList.tsx:621-739; section create/rename/delete dialogs ProjectList.tsx:1979-2012; Pinned section; dnd-kit drag reorder), footer: Settings link, plugin footer actions, Report bug (external), `SidebarUpdatesBadge`. Thread search is a command-palette mode entered by `thread.search`. ThreadRow kebab hidden on compact+coarse (`max-md:pointer-coarse:hidden`, ThreadRow.tsx:821); Radix ContextMenu (long-press) still wraps rows (ThreadRow.tsx:854). Thread menu items: Open in split, Mark read/unread, Pin/Unpin, Rename, Archive/Unarchive, Delete (ThreadActionsMenu.tsx:175-248). Project menu: Project settings, Rename, Add local path, Remove (ProjectActionsMenu.tsx:130-169). Section header actions: display options, New project, New section, New thread (ProjectList.tsx:566-617). Keyboard: `thread.jump.N` and `thread.previous/next` are handled here (AppSidebar.tsx:221-230). ## Root compose `/` (views/RootComposeView.tsx) `NewThreadComposer` (project/env/branch/worktree/machine/model/permission pickers, NewThreadPromptBox.tsx:418-573) with fork/handoff seeds from `location.state`; empty-projects welcome (RootComposeEmptyWelcome.tsx: New thread / Import projects / New project / Learn); `RootComposeMobileRecents` (`md:hidden`, 3 recent threads, RootComposeMobileRecents.tsx:181); `RootComposeSecondaryContent` = same right panel as threads (files, terminal, new-tab, browser[desktop], plugin tabs; no Info/Diff, RootComposeView.tsx:2345-2381) rendered as bottom drawer on compact (SecondaryPanelLayout.tsx:105); pinned panel toggle; `ProjectMachineSetupDialog`; `PluginHomepageSections`. Commands: panel.newTab, file.quickOpen, terminal.open, workspace.openPreferred, panel.toggle/close (RootComposeView.tsx:1471-1908, RootComposePanelCommandHandlers.tsx). @@ -108,7 +108,7 @@ Path params via `useRouteState` (hooks/useRouteState.ts). Query: `?view=browse|i - apps/app/src/components/commands/AppCommandProvider.tsx: **headless-logic-only** — Registers `window.addEventListener('keydown')`, queries `document.querySelector` for open modals (AppCommandProvider.tsx:93-99,179,330), uses `navigator.platform`, `HTMLElement.closest`. The handler registry/dispatch/priority pattern is portable; the key-event plumbing is web-only (RN has no global keydown; only hardware-keyboard events). - apps/app/src/components/layout/AppLayout.tsx: **not-reusable** — Radix-based SidebarProvider, CSS variables (`--sidebar-width`), mouse resize on document.body, `document.title`, `window.requestAnimationFrame`, MutationObserver, Electron chrome classes, env(safe-area-inset) Tailwind classes. - apps/app/src/components/ui/sidebar.tsx: **not-reusable** — DOM touch/pointer swipe implementation writing `panel.style.translate`, `inert`, `aria-modal`, Tailwind group-data variants; must be re-implemented with a native drawer (e.g. react-native-reanimated/gesture-handler). -- apps/app/src/components/sidebar/ProjectList.tsx + ThreadRow.tsx + ProjectRow.tsx: **headless-logic-only** — Heavy on @dnd-kit, Radix DropdownMenu/ContextMenu/Tooltip, CSS hover-action classes (theme.css:259-333). Reusable pieces: projectThreadGroups.ts, machineThreadGroups.ts, sortComparator.ts, threadReadState.ts, pinnedSidebarThreads.ts, sidebarThreadSearch.ts, sidebarSectionOrder.ts (pure TS). +- apps/app/src/components/sidebar/ProjectList.tsx + ThreadRow.tsx + ProjectRow.tsx: **headless-logic-only** — Heavy on @dnd-kit, Radix DropdownMenu/ContextMenu/Tooltip, CSS hover-action classes (theme.css:259-333). Reusable pieces: projectThreadGroups.ts, machineThreadGroups.ts, sortComparator.ts, threadReadState.ts, pinnedSidebarThreads.ts, sidebarSectionOrder.ts (pure TS). - apps/app/src/views/RootComposeView.tsx: **headless-logic-only** — 2400-line DOM view: react-router location.state, react-resizable-panels, `window`, Tiptap composer, xterm terminal, @pierre diffs. Exported pure helpers (readSectionIdFromLocationState, shouldNavigateAfterThreadCreate, buildMobileRecentThreads, canCreateRootComposeTerminal, root-compose-branch-selection.ts, root-compose-environment-selection.ts) are portable. - apps/app/src/views/RootComposeMobileRecents.tsx: **headless-logic-only** — getMobileRecentThreads sort/limit is pure; rendering uses react-router Link + Tailwind + ThreadStatusGlyph (SVG icons). - apps/app/src/views/thread-detail/ThreadDetailView.tsx: **headless-logic-only** — ~3000 lines wiring DOM-only panels (xterm terminal, @pierre/diffs with Web Workers, Tiptap, react-resizable-panels, iframe/BrowserView). Data hooks (thread-queries, timeline controller, useThreadGitActions, threadQueuedMessages.ts, threadDetailPromptSubmission.ts, splitThreadNavigation.ts) are largely portable. From edca6d0905683d01ee65700e01615c1711b44d78 Mon Sep 17 00:00:00 2001 From: Bersabel Tadesse Date: Mon, 31 Aug 2026 16:02:17 -0700 Subject: [PATCH 2/7] Polish command palette hierarchy and footer --- .../commands/AppCommandShortcutHint.tsx | 4 +- .../commands/CommandPalette.test.tsx | 388 ++++++++- .../components/commands/CommandPalette.tsx | 105 ++- .../CommandPalettePrototype.stories.tsx | 741 ++++++++++++++++++ .../src/components/commands/PaletteShell.tsx | 183 +++-- .../commands/ThreadSearchPaletteMode.tsx | 41 +- .../src/lib/command-palette/palette-mode.ts | 2 +- .../src/lib/command-palette/palette-modes.ts | 10 +- .../plugin-api-map/src/anatomy-manifest.json | 4 +- 9 files changed, 1350 insertions(+), 128 deletions(-) create mode 100644 apps/app/src/components/commands/CommandPalettePrototype.stories.tsx diff --git a/apps/app/src/components/commands/AppCommandShortcutHint.tsx b/apps/app/src/components/commands/AppCommandShortcutHint.tsx index e82b45a84e..0efa771011 100644 --- a/apps/app/src/components/commands/AppCommandShortcutHint.tsx +++ b/apps/app/src/components/commands/AppCommandShortcutHint.tsx @@ -13,7 +13,7 @@ interface AppCommandShortcutPillProps { className?: string; } -const APP_COMMAND_SHORTCUT_HINT_CLASS = +export const APP_COMMAND_ACCESSORY_PILL_CLASS = "pointer-events-none inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-sm bg-state-hover px-1.5 py-1 font-sans text-xs font-normal leading-none tabular-nums text-subtle-foreground opacity-60"; export function AppCommandShortcutPill({ @@ -24,7 +24,7 @@ export function AppCommandShortcutPill({ return ( {shortcut.label} diff --git a/apps/app/src/components/commands/CommandPalette.test.tsx b/apps/app/src/components/commands/CommandPalette.test.tsx index 8a3f1bbda0..fbddaf1d63 100644 --- a/apps/app/src/components/commands/CommandPalette.test.tsx +++ b/apps/app/src/components/commands/CommandPalette.test.tsx @@ -94,9 +94,50 @@ const modeState = vi.hoisted(() => ({ drafts: [] as NewThreadDraftRow[], searchResponse: undefined as ThreadSearchResponse | undefined, })); +const openPaneContentInSplitMock = vi.hoisted(() => vi.fn()); const openThreadInSplitMock = vi.hoisted(() => vi.fn()); const routeNavigateMock = vi.hoisted(() => vi.fn()); +function expectClasses( + element: Element | null | undefined, + ...classNames: string[] +): void { + expect(element).toBeTruthy(); + for (const className of classNames) { + expect(element?.classList.contains(className)).toBe(true); + } +} + +function expectNoClasses( + element: Element | null | undefined, + ...classNames: string[] +): void { + expect(element).toBeTruthy(); + for (const className of classNames) { + expect(element?.classList.contains(className)).toBe(false); + } +} + +function expectText( + element: Element | null | undefined, + text: string, +): void { + expect(element?.textContent).toContain(text); +} + +function expectAttribute( + element: Element | null | undefined, + name: string, + value?: string, +): void { + expect(element).toBeTruthy(); + if (value === undefined) { + expect(element?.hasAttribute(name)).toBe(true); + } else { + expect(element?.getAttribute(name)).toBe(value); + } +} + vi.mock("@/hooks/queries/system-queries", () => ({ useSystemConfig: () => ({ data: { @@ -131,6 +172,10 @@ vi.mock("@/lib/split-layout/openThreadInSplit", () => ({ openThreadInSplit: openThreadInSplitMock, })); +vi.mock("@/lib/split-layout/openPaneContentInSplit", () => ({ + openPaneContentInSplit: openPaneContentInSplitMock, +})); + vi.mock("@/components/ui/app-route-anchor", () => ({ useRouteNavigate: () => routeNavigateMock, })); @@ -290,6 +335,7 @@ afterEach(() => { modeState.archivedRecents = []; modeState.drafts = []; modeState.searchResponse = undefined; + openPaneContentInSplitMock.mockReset(); openThreadInSplitMock.mockReset(); routeNavigateMock.mockReset(); window.localStorage.clear(); @@ -306,7 +352,7 @@ describe("CommandPalette", () => { expect(titles).toHaveLength(5); }); - it("groups the resting root into three text buckets with producer metadata", async () => { + it("groups resting commands, hides empty plugins, and distinguishes drill-in rows", async () => { renderPalette(); openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); @@ -314,16 +360,65 @@ describe("CommandPalette", () => { const groups = within(commandList()).getAllByRole("group"); expect( groups.map((group) => group.getAttribute("data-palette-bucket")), - ).toEqual(["Threads", "Actions", "Plugins"]); - for (const [index, label] of ["Threads", "Actions", "Plugins"].entries()) { + ).toEqual(["Threads", "Actions"]); + expect( + within(commandList()).queryByRole("group", { name: "Plugins" }), + ).toBeNull(); + for (const [index, label] of ["Threads", "Actions"].entries()) { const header = within(groups[index] as HTMLElement).getByText(label, { selector: "div", }); for (const className of CHROME_SECTION_LABEL_CLASS.split(" ")) { expect(header.classList.contains(className)).toBe(true); } - expect(header.classList.contains("px-2")).toBe(true); + expectClasses(header, "px-3", "pb-1", "pt-3"); + expectNoClasses(header, "bg-muted/30"); } + expectClasses(commandList(), "p-2"); + expectClasses(commandList().parentElement, "overflow-hidden"); + expectClasses( + screen.getByTestId("command-palette"), + "max-w-[640px]", + "overflow-hidden", + "shadow-lg", + "sm:rounded-xl", + ); + expectClasses( + searchField().closest("[data-palette-input-frame]"), + "h-10", + "px-3", + ); + expectNoClasses( + searchField().closest("[data-palette-input-frame]"), + "border", + "bg-command-palette-search", + "rounded-md", + "shadow-xs", + ); + expectClasses( + searchField().closest("[data-palette-input-band]"), + "border-b", + "bg-background", + "px-3", + "py-2", + ); + expectClasses( + searchField(), + "placeholder:text-subtle-foreground", + "placeholder:font-light", + "placeholder:opacity-70", + ); + expectClasses(commandList().parentElement, "bg-background"); + expect( + commandList().querySelectorAll("[data-palette-scroll-sentinel]"), + ).toHaveLength(2); + + const rootFooter = screen + .getByTestId("command-palette") + .querySelector("[data-palette-footer]"); + expectText(rootFooter, "Select"); + expectText(rootFooter, "Run"); + expect(rootFooter?.textContent).not.toContain("Open"); const threadRows = within(bucketGroup("Threads")).getAllByRole("option"); expect(threadRows.map((row) => row.textContent)).toEqual([ @@ -334,18 +429,38 @@ describe("CommandPalette", () => { for (const row of threadRows) { expect(within(row).queryByText("Threads")).toBeNull(); } - expect(threadRows[1]?.querySelector("kbd")).not.toBeNull(); + const searchThreadsRow = threadRows[1] as HTMLElement; + expect(searchThreadsRow.querySelector("kbd")).not.toBeNull(); + expectAttribute( + searchThreadsRow, + "data-palette-action-kind", + "drill-in", + ); + expectText(searchThreadsRow, "Search threads…"); + expect( + searchThreadsRow.querySelector('[data-icon="ChevronRight"]'), + ).toBeNull(); + expect(searchThreadsRow.textContent).toContain("Opens a search view"); const actionRows = within(bucketGroup("Actions")).getAllByRole("option"); expect(actionRows[0]?.textContent).toContain("Window and layout"); expect(actionRows[1]?.textContent).toContain("Workspace"); for (const row of [...threadRows, ...actionRows]) { - expect(row.classList.contains("px-2")).toBe(true); + expect(row.classList.contains("px-3")).toBe(true); } expect(commandList().querySelector("[data-icon]")).toBeNull(); + expectClasses(threadRows[0], "bg-state-hover", "text-foreground"); + expectAttribute( + actionRows[0], + "data-palette-action-kind", + "terminal", + ); expect( - screen.getByTestId("command-palette").querySelector("svg"), + actionRows[0]?.querySelector('[data-icon="ChevronRight"]'), ).toBeNull(); + + fireEvent.keyDown(searchField(), { key: "ArrowDown" }); + expectClasses(searchThreadsRow, "bg-state-hover", "text-foreground"); }); it("enters the registered thread mode from its existing command and pops one level per Escape", async () => { @@ -357,12 +472,48 @@ describe("CommandPalette", () => { ).toBeTruthy(), ); expect(event.defaultPrevented).toBe(true); - expect( - screen.getByText("Threads").closest("[data-palette-mode-chip]"), - ).not.toBeNull(); + const modeSelect = screen.getByRole("button", { name: "Threads search" }); + expectAttribute(modeSelect, "aria-pressed", "true"); + expect(modeSelect.querySelector('[data-icon="Search"]')).not.toBeNull(); + expectAttribute( + screen.getByRole("button", { name: "Return to commands" }), + "data-tab-pill-close", + ); expect( screen.getByRole("button", { name: "Thread scope" }).textContent, ).toContain("All"); + expectText(screen.getByTestId("command-palette"), "Split"); + const footer = screen + .getByTestId("command-palette") + .querySelector("[data-palette-footer]"); + expectClasses( + footer, + "flex-wrap", + "bg-surface-recessed-soft-solid", + "px-4", + "py-2", + ); + for (const keycap of footer?.querySelectorAll("kbd") ?? []) { + expectClasses( + keycap, + "rounded", + "border-border/70", + "bg-background/70", + "font-mono", + "text-muted-foreground", + "shadow-xs", + ); + } + for (const label of + footer?.querySelectorAll("[data-palette-footer-label]") ?? []) { + expectClasses(label, "opacity-70"); + expectClasses( + label.closest("[data-palette-footer]"), + "text-subtle-foreground", + ); + } + expectText(footer, "Backspace"); + expectText(footer, "Esc"); fireEvent.keyDown(screen.getByRole("combobox"), { key: "Escape" }); await waitFor(() => @@ -376,6 +527,49 @@ describe("CommandPalette", () => { await waitFor(() => expect(screen.queryByRole("combobox")).toBeNull()); }); + it("uses the shared tab-pill clear affordance without running the mode command", async () => { + renderPalette(); + openThreadSearch(); + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search threads" }), + ).toBeTruthy(), + ); + + const clearMode = screen.getByRole("button", { + name: "Return to commands", + }); + expect(clearMode.querySelector('[data-icon="X"]')).not.toBeNull(); + expectClasses( + clearMode, + "opacity-0", + "group-hover/tab-pill:opacity-100", + "focus-visible:opacity-100", + ); + fireEvent.click(clearMode); + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search commands" }), + ).toBeTruthy(), + ); + expect(testState.calls).toEqual([]); + + const searchCommand = within(bucketGroup("Threads")) + .getAllByRole("option") + .find((row) => row.textContent?.includes("Search threads")); + fireEvent.click(searchCommand as HTMLElement); + const clearAfterCommand = await screen.findByRole("button", { + name: "Return to commands", + }); + fireEvent.click(clearAfterCommand); + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search commands" }), + ).toBeTruthy(), + ); + expect(testState.calls).toEqual([]); + }); + it("enters the same registered mode by running Search threads from the root", async () => { renderPalette(); openPalette(); @@ -395,6 +589,23 @@ describe("CommandPalette", () => { expect(testState.calls).toEqual([]); }); + it("returns from an empty thread query with Backspace", async () => { + renderPalette(); + openThreadSearch(); + const input = await screen.findByRole("combobox", { + name: "Search threads", + }); + + fireEvent.keyDown(input, { key: "Backspace" }); + + await waitFor(() => + expect( + screen.getByRole("combobox", { name: "Search commands" }), + ).toBeTruthy(), + ); + expect(testState.calls).toEqual([]); + }); + it("cycles the thread scope and resets it after leaving the mode", async () => { renderPalette(); openThreadSearch(); @@ -428,7 +639,33 @@ describe("CommandPalette", () => { ); }); - it("makes scope the input's only sibling tab stop and applies every keyboard choice immediately", async () => { + it("opens the closed thread scope with Enter and returns to the input on the next Enter", async () => { + renderPalette(); + openThreadSearch(); + const input = await screen.findByRole("combobox", { + name: "Search threads", + }); + const scope = screen.getByRole("button", { name: "Thread scope" }); + + scope.focus(); + fireEvent.keyDown(scope, { key: "Enter" }); + + expect(scope.getAttribute("aria-expanded")).toBe("true"); + expect( + screen.getByRole("listbox", { name: "Thread scope options" }), + ).toBeTruthy(); + expect(document.activeElement).toBe(scope); + + fireEvent.keyDown(scope, { key: "Enter" }); + + expect(scope.getAttribute("aria-expanded")).toBe("false"); + expect( + screen.queryByRole("listbox", { name: "Thread scope options" }), + ).toBeNull(); + expect(document.activeElement).toBe(input); + }); + + it("keeps the mode clear, input, and scope in a predictable tab sequence and applies every keyboard choice immediately", async () => { modeState.searchResponse = { active: { total: 1, @@ -465,6 +702,11 @@ describe("CommandPalette", () => { ); const input = screen.getByRole("combobox", { name: "Search threads" }); const scope = screen.getByRole("button", { name: "Thread scope" }); + expect(scope.querySelector("[data-icon]")).toBeNull(); + const modeSelect = screen.getByRole("button", { name: "Threads search" }); + const clearMode = screen.getByRole("button", { + name: "Return to commands", + }); const palette = screen.getByTestId("command-palette"); expect( Array.from( @@ -472,7 +714,7 @@ describe("CommandPalette", () => { 'input:not([disabled]), button:not([disabled]), [tabindex]:not([tabindex="-1"])', ), ), - ).toEqual([input, scope]); + ).toEqual([modeSelect, clearMode, input, scope]); fireEvent.change(input, { target: { value: "match" } }); const results = screen.getByRole("listbox", { name: "Threads" }); @@ -491,6 +733,7 @@ describe("CommandPalette", () => { .getAllByRole("option") .map((option) => option.textContent), ).toEqual(["All", "Active", "Drafts", "Archived"]); + expect(scopeOptions.querySelector("[data-icon]")).toBeNull(); expect(within(results).getAllByRole("option")).toHaveLength(1); expect(within(results).getByRole("option").textContent).toContain( "matching-active", @@ -555,15 +798,49 @@ describe("CommandPalette", () => { expect(rows[1]?.textContent).toContain("Draft"); expect(rows[2]?.textContent).toContain("Title recent-archived"); expect(rows[2]?.textContent).toContain("Archived"); + expect(results.querySelector("[data-palette-thread-state]")).toBeNull(); + expect(results.querySelector("[data-icon]")).toBeNull(); + for (const row of rows) { + expectClasses( + row.querySelector("[data-palette-thread-metadata]"), + "text-subtle-foreground", + ); + } + expectClasses( + within(rows[1] as HTMLElement).getByText("Draft"), + "text-subtle-foreground", + ); + expectClasses( + within(rows[2] as HTMLElement).getByText("Archived"), + "text-subtle-foreground", + ); expect(within(results).queryAllByRole("group")).toHaveLength(0); expect(within(results).queryByText("Recent")).toBeNull(); }); it("renders search matches as one unlabelled active, draft, archived list", async () => { - const active = makeThread("active"); + const active = makeThread("active", { + title: "Matching active thread", + titleFallback: "Matching active thread", + }); const archived = makeThread("archived", { archivedAt: Date.now() }); modeState.searchResponse = { - active: { total: 1, results: [{ thread: active, matches: [] }] }, + active: { + total: 1, + results: [ + { + thread: active, + matches: [ + { + sourceKind: "title", + text: "Matching active thread", + highlightRanges: [{ start: 0, end: 8 }], + sourceSeq: null, + }, + ], + }, + ], + }, archived: { total: 1, results: [{ thread: archived, matches: [] }] }, }; modeState.drafts = [ @@ -592,18 +869,31 @@ describe("CommandPalette", () => { expect(within(results).getAllByRole("option")).toHaveLength(3), ); const rows = within(results).getAllByRole("option"); - expect(rows[0]?.textContent).toContain("Title active"); + expect(rows[0]?.textContent).toContain("Matching active thread"); expect(rows[1]?.textContent).toContain("matching draft"); expect(rows[1]?.textContent).toContain("Draft"); expect(rows[2]?.textContent).toContain("Title archived"); expect(rows[2]?.textContent).toContain("Archived"); expect(rows[0]?.textContent).not.toContain("Active"); + const activeMatch = rows[0]?.querySelector("mark"); + expectText(activeMatch, "Matching"); + expectClasses( + activeMatch, + "bg-[var(--sidebar-search-match)]", + "text-foreground", + ); + expectClasses(activeMatch?.parentElement, "text-foreground"); + for (const row of rows) { + expectClasses( + row.querySelector("[data-palette-thread-metadata]"), + "text-subtle-foreground", + ); + } + expect(results.querySelector("[data-palette-thread-state]")).toBeNull(); expect(within(results).queryAllByRole("group")).toHaveLength(0); expect(within(results).queryByText("Recent")).toBeNull(); expect(results.textContent).not.toContain("1/1"); - expect( - screen.getByTestId("command-palette").querySelectorAll("svg"), - ).toHaveLength(1); + expect(results.querySelector("svg")).toBeNull(); }); it("opens a persisted thread result in a split with Command-Enter", async () => { @@ -637,6 +927,68 @@ describe("CommandPalette", () => { ); }); + it("opens a persisted draft result in a split with its exact slot id", async () => { + modeState.drafts = [ + { + id: "draft-slot-exact", + title: "split this draft", + draft: { ...emptyPromptDraftState(), text: "split this draft" }, + lastEditedAt: Date.now(), + destination: { projectId: "project-1", sectionId: null }, + delete: vi.fn(), + }, + ]; + renderPalette(); + openThreadSearch(); + const input = await screen.findByRole("combobox", { + name: "Search threads", + }); + await screen.findByRole("option", { name: /split this draft/i }); + + fireEvent.keyDown(input, { key: "Enter", metaKey: true }); + + await waitFor(() => + expect(openPaneContentInSplitMock).toHaveBeenCalledTimes(1), + ); + expect(openPaneContentInSplitMock).toHaveBeenCalledWith( + expect.objectContaining({ + content: { kind: "new-thread", draftSlotId: "draft-slot-exact" }, + enabled: true, + }), + ); + expect(routeNavigateMock).not.toHaveBeenCalled(); + }); + + it("keeps ordinary Enter on a persisted draft as normal navigation", async () => { + modeState.drafts = [ + { + id: "draft-slot-normal", + title: "open this draft", + draft: { ...emptyPromptDraftState(), text: "open this draft" }, + lastEditedAt: Date.now(), + destination: { projectId: "project-1", sectionId: null }, + delete: vi.fn(), + }, + ]; + renderPalette(); + openThreadSearch(); + const input = await screen.findByRole("combobox", { + name: "Search threads", + }); + await screen.findByRole("option", { name: /open this draft/i }); + + fireEvent.keyDown(input, { key: "Enter" }); + + await waitFor(() => expect(routeNavigateMock).toHaveBeenCalledTimes(1)); + expect(openPaneContentInSplitMock).not.toHaveBeenCalled(); + expect(routeNavigateMock).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ + state: expect.objectContaining({ draftSlotId: "draft-slot-normal" }), + }), + ); + }); + it("filters as the user types and keeps the selection on a live row", async () => { renderPalette(); openPalette(); diff --git a/apps/app/src/components/commands/CommandPalette.tsx b/apps/app/src/components/commands/CommandPalette.tsx index 56dbfab381..ed59a1c28f 100644 --- a/apps/app/src/components/commands/CommandPalette.tsx +++ b/apps/app/src/components/commands/CommandPalette.tsx @@ -9,12 +9,9 @@ import { import type { KeyboardEvent as ReactKeyboardEvent } from "react"; import { Dialog, DialogContent, DialogTitle } from "@bb/shared-ui/dialog"; import { cn } from "@bb/shared-ui/lib/utils"; -import { COARSE_POINTER_TEXT_SM_CLASS } from "@bb/shared-ui/coarse-pointer-sizing"; import { CHROME_SECTION_LABEL_CLASS } from "@bb/shared-ui/chrome-style-tokens"; -import { LAUNCHER_ACTION_ROW_BASE_CLASS } from "@/components/secondary-panel/launcherRow"; import { useAppCommandHandler, - useAppCommandShortcut, useAppCommandRunner, useAppCommandShortcuts, useIndexedAppCommandHandlers, @@ -46,7 +43,12 @@ import { } from "@/lib/command-palette/palette-modes"; import { PaletteShell } from "./PaletteShell"; -const PALETTE_PLACEHOLDER = "Search commands"; +const PALETTE_INPUT_LABEL = "Search commands"; +const PALETTE_PLACEHOLDER = "Search commands…"; +const ROOT_FOOTER_KEYS = [ + { keys: ["↑↓"], label: "Select" }, + { keys: ["↵"], label: "Run" }, +] as const; const MODE_ENTRY_HANDLER_PRIORITY = 100; const MODE_BY_ACTION_ID = new Map( PALETTE_MODES.map((mode) => [ @@ -58,12 +60,16 @@ const MODE_BY_ACTION_ID = new Map( export interface CommandPaletteProps { threadId: string | null; projectId: string | null; + onSplit?: () => void; } -export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { +export function CommandPalette({ + threadId, + projectId, + onSplit, +}: CommandPaletteProps) { const runner = useAppCommandRunner(); const shortcuts = useAppCommandShortcuts(PALETTE_COMMAND_IDS); - const paletteShortcut = useAppCommandShortcut("palette.open"); const listId = useId(); const optionIdPrefix = useId(); @@ -86,6 +92,18 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { dispatch: runner.dispatch, shortcuts, }), + ...(onSplit === undefined + ? [] + : [ + { + id: "internal:thread.split", + bucket: "Actions", + group: "Window and layout", + title: "Split", + shortcut: null, + run: onSplit, + } satisfies PaletteAction, + ]), ...buildPluginPaletteActions({ slots: getPluginSlotSnapshot().commandPaletteActions, threadId, @@ -99,6 +117,7 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { runner.isCommandAvailable, shortcuts, threadId, + onSplit, ], ); @@ -147,7 +166,9 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { const groups = PALETTE_ACTION_BUCKETS.map((bucket) => ({ bucket, entries: ranked.filter((entry) => entry.action.bucket === bucket), - })); + })).filter( + (group) => group.bucket !== "Plugins" || group.entries.length > 0, + ); return groups.map((group, index) => ({ ...group, startIndex: groups @@ -175,15 +196,18 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { ?.scrollIntoView({ block: "nearest" }); }, [activeIndex]); - const chooseAction = useCallback((action: PaletteAction) => { - setRecents((current) => recordPaletteRecent(current, action.id)); - if (MODE_BY_ACTION_ID.has(action.id)) { - action.run(); - return; - } - pendingRunRef.current = action.run; - setOpen(false); - }, []); + const chooseAction = useCallback( + (action: PaletteAction) => { + setRecents((current) => recordPaletteRecent(current, action.id)); + if (MODE_BY_ACTION_ID.has(action.id)) { + action.run(); + return; + } + pendingRunRef.current = action.run; + setOpen(false); + }, + [], + ); const runAfterClose = useCallback((run: () => void) => { pendingRunRef.current = run; @@ -260,7 +284,7 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { { if (activeMode !== undefined) event.preventDefault(); @@ -275,12 +299,8 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { ? undefined : `${optionIdPrefix}-${activeIndex}` } - accessory={ - paletteShortcut === null ? null : ( - - ) - } - inputLabel={PALETTE_PLACEHOLDER} + footerKeys={ROOT_FOOTER_KEYS} + inputLabel={PALETTE_INPUT_LABEL} listId={listId} listLabel="Commands" listRef={listRef} @@ -294,11 +314,11 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { value={query} > {!isGroupedRoot && visibleEntries.length === 0 ? ( -

+

No matching commands

) : isGroupedRoot ? ( - rootGroups.map((group, groupIndex) => { + rootGroups.map((group) => { const labelId = `${optionIdPrefix}-${group.bucket.toLowerCase()}-label`; return (
{group.bucket} @@ -325,7 +344,10 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { entry={entry} id={`${optionIdPrefix}-${visibleIndex}`} isActive={visibleIndex === activeIndex} - onActivate={() => setHighlightedIndex(visibleIndex)} + isDrillIn={MODE_BY_ACTION_ID.has(entry.action.id)} + onActivate={() => { + setHighlightedIndex(visibleIndex); + }} onSelect={() => chooseAction(entry.action)} /> ); @@ -340,7 +362,10 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { entry={entry} id={`${optionIdPrefix}-${index}`} isActive={index === activeIndex} - onActivate={() => setHighlightedIndex(index)} + isDrillIn={MODE_BY_ACTION_ID.has(entry.action.id)} + onActivate={() => { + setHighlightedIndex(index); + }} onSelect={() => chooseAction(entry.action)} /> )) @@ -366,26 +391,30 @@ function PaletteRow({ entry, id, isActive, + isDrillIn, onActivate, onSelect, }: { entry: RankedPaletteAction; id: string; isActive: boolean; + isDrillIn: boolean; onActivate: () => void; onSelect: () => void; }) { const metadataGroup = entry.action.group === entry.action.bucket ? null : entry.action.group; - const hasTrailing = metadataGroup !== null || entry.action.shortcut !== null; + const title = isDrillIn ? `${entry.action.title}…` : entry.action.title; + const hasTrailing = + metadataGroup !== null || entry.action.shortcut !== null || isDrillIn; return (
{hasTrailing ? ( {metadataGroup === null ? null : ( - + {metadataGroup} )} {entry.action.shortcut === null ? null : ( )} + {isDrillIn ? ( + Opens a search view + ) : null} ) : null}
diff --git a/apps/app/src/components/commands/CommandPalettePrototype.stories.tsx b/apps/app/src/components/commands/CommandPalettePrototype.stories.tsx new file mode 100644 index 0000000000..76946b1b4b --- /dev/null +++ b/apps/app/src/components/commands/CommandPalettePrototype.stories.tsx @@ -0,0 +1,741 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import type { KeyboardEvent as ReactKeyboardEvent } from "react"; +import { useComposedRefs } from "@radix-ui/react-compose-refs"; +import { CHROME_SECTION_LABEL_CLASS } from "@bb/shared-ui/chrome-style-tokens"; +import { Icon } from "@bb/shared-ui/icon"; +import { cn } from "@bb/shared-ui/lib/utils"; +import { useScrollOverflowState } from "@/components/thread/timeline/useScrollOverflowState"; +import { TabPill } from "@/components/ui/tab-pill"; + +export default { + title: "commands/Command palette prototype", +}; + +type Mode = "commands" | "threads"; +type ThreadScope = "all" | "active" | "draft" | "archived"; +type ThreadState = Exclude; + +interface CommandRow { + bucket: "Threads" | "Actions" | "Plugins"; + group: string; + label: string; + shortcut?: string; + drillIn?: boolean; +} + +interface ThreadRow { + id: string; + title: string; + metadata: string; + state: ThreadState; +} + +const COMMANDS = [ + { + bucket: "Threads", + group: "Threads", + label: "New thread", + shortcut: "⇧ ⌘ O", + }, + { + bucket: "Threads", + group: "Threads", + label: "Search threads…", + shortcut: "⌘ K", + drillIn: true, + }, + { + bucket: "Threads", + group: "Threads", + label: "Rename thread", + }, + { + bucket: "Threads", + group: "Threads", + label: "Archive thread", + }, + { + bucket: "Threads", + group: "Threads", + label: "Previous thread", + shortcut: "⇧ ⌘ [", + }, + { + bucket: "Threads", + group: "Threads", + label: "Next thread", + shortcut: "⇧ ⌘ ]", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "New window", + shortcut: "⇧ ⌘ N", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Open settings", + shortcut: "⌘ ,", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Open server settings", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Toggle sidebar", + shortcut: "⌘ \\", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "New panel tab", + shortcut: "⌘ T", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Close panel tab", + shortcut: "⌘ W", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Toggle panel", + shortcut: "⌘ J", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Focus previous chat pane", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Focus next chat pane", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Toggle focused chat pane size", + shortcut: "⇧ ⌘ E", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Close focused chat pane", + shortcut: "⇧ ⌘ X", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Open server and daemon logs", + }, + { + bucket: "Actions", + group: "Workspace", + label: "Quick open file", + shortcut: "⌘ P", + }, + { + bucket: "Actions", + group: "Workspace", + label: "Toggle diff", + shortcut: "⌘ D", + }, + { + bucket: "Actions", + group: "Workspace", + label: "Open terminal", + shortcut: "⇧ ⌘ ↵", + }, + { + bucket: "Actions", + group: "Workspace", + label: "Open in preferred app", + shortcut: "⌘ O", + }, + { + bucket: "Actions", + group: "Composer and models", + label: "Focus composer", + shortcut: "⇧ ⌘ C", + }, + { + bucket: "Actions", + group: "Composer and models", + label: "Toggle model picker", + shortcut: "⇧ ⌘ M", + }, + { + bucket: "Actions", + group: "Browser", + label: "Focus location", + shortcut: "⌘ L", + }, + { + bucket: "Actions", + group: "Browser", + label: "Reload page", + shortcut: "⌘ R", + }, + { + bucket: "Actions", + group: "Browser", + label: "Find in page", + shortcut: "⌘ F", + }, + { + bucket: "Actions", + group: "Window and layout", + label: "Split", + }, + { + bucket: "Plugins", + group: "Design Doctrine", + label: "Open Design Doctrine", + }, + { + bucket: "Plugins", + group: "GitHub Activity", + label: "Open GitHub Activity", + }, +] as const satisfies readonly CommandRow[]; + +const THREADS = [ + { + id: "palette-redesign", + title: "Redesign the command palette", + metadata: "bb · just now", + state: "active", + }, + { + id: "sidebar-evidence", + title: "Replace sidebar stack screenshot evidence", + metadata: "bb · 12m ago", + state: "active", + }, + { + id: "filter-states", + title: "Review thread filter states", + metadata: "bb · Yesterday", + state: "draft", + }, + { + id: "mobile-drawer", + title: "Investigate mobile drawer performance", + metadata: "Mobile · Yesterday", + state: "active", + }, + { + id: "project-grouping", + title: "Confirm project grouping hierarchy", + metadata: "Sidebar polish · 3d ago", + state: "active", + }, + { + id: "legacy-navigation", + title: "Legacy navigation audit", + metadata: "1w ago", + state: "archived", + }, +] as const satisfies readonly ThreadRow[]; + +const THREAD_STATE: Record = { + active: { label: "Active" }, + draft: { label: "Draft" }, + archived: { label: "Archived" }, +}; + +const SCOPES = [ + { id: "all", label: "All" }, + { id: "active", label: "Active" }, + { id: "draft", label: "Drafts" }, + { id: "archived", label: "Archived" }, +] as const satisfies readonly { id: ThreadScope; label: string }[]; + +function Shortcut({ children }: { children: string }) { + return ( + + {children} + + ); +} + +function PaletteFrame({ children }: { children: React.ReactNode }) { + return ( +
+
+ {children} +
+
+ ); +} + +function CommandPalettePrototype() { + const [mode, setMode] = useState("commands"); + const [query, setQuery] = useState(""); + const [selectedIndex, setSelectedIndex] = useState(0); + const [scope, setScope] = useState("all"); + const [scopeOpen, setScopeOpen] = useState(false); + const inputRef = useRef(null); + const resultsRef = useRef(null); + const scrollOnNextSelectionRef = useRef(false); + const overflow = useScrollOverflowState({ + measureOverflow: true, + }); + const composedResultsRef = useComposedRefs(resultsRef, overflow.scrollRef); + const resultsMask = + overflow.aboveOverflow && overflow.belowOverflow + ? "linear-gradient(to bottom, transparent 0, black 1.5rem, black calc(100% - 1.5rem), transparent 100%)" + : overflow.aboveOverflow + ? "linear-gradient(to bottom, transparent 0, black 1.5rem, black 100%)" + : overflow.belowOverflow + ? "linear-gradient(to bottom, black 0, black calc(100% - 1.5rem), transparent 100%)" + : undefined; + + const commandRows = useMemo(() => { + const normalized = query.trim().toLocaleLowerCase(); + if (normalized.length === 0) return COMMANDS; + return COMMANDS.filter((command) => + [command.label, command.group, command.bucket] + .join(" ") + .toLocaleLowerCase() + .includes(normalized), + ); + }, [query]); + + const threadRows = useMemo(() => { + const normalized = query.trim().toLocaleLowerCase(); + return THREADS.filter( + (thread) => + (scope === "all" || thread.state === scope) && + (normalized.length === 0 || + `${thread.title} ${thread.metadata}` + .toLocaleLowerCase() + .includes(normalized)), + ); + }, [query, scope]); + + const visibleCount = + mode === "commands" ? commandRows.length : threadRows.length; + + useEffect(() => { + setSelectedIndex(0); + }, [mode, query, scope]); + + useEffect(() => { + if (!scrollOnNextSelectionRef.current) return; + scrollOnNextSelectionRef.current = false; + resultsRef.current + ?.querySelector('[aria-selected="true"]') + ?.scrollIntoView({ block: "nearest" }); + }, [selectedIndex]); + + const enterThreads = () => { + setMode("threads"); + setQuery(""); + setScope("all"); + setScopeOpen(false); + requestAnimationFrame(() => inputRef.current?.focus()); + }; + + const exitThreads = () => { + setMode("commands"); + setQuery(""); + setScopeOpen(false); + requestAnimationFrame(() => inputRef.current?.focus()); + }; + + const activateSelected = () => { + if (mode !== "commands") return; + if (commandRows[selectedIndex]?.drillIn) enterThreads(); + }; + + const handleKeyDown = (event: ReactKeyboardEvent) => { + if (event.key === "Backspace" && mode === "threads" && query.length === 0) { + event.preventDefault(); + exitThreads(); + return; + } + if (event.key === "Escape") { + if (mode === "threads") { + event.preventDefault(); + exitThreads(); + } + return; + } + if (visibleCount === 0) return; + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault(); + scrollOnNextSelectionRef.current = true; + setSelectedIndex((current) => { + if (event.key === "ArrowDown") { + return current + 1 >= visibleCount ? 0 : current + 1; + } + return current === 0 ? visibleCount - 1 : current - 1; + }); + return; + } + if (event.key === "Home" || event.key === "End") { + event.preventDefault(); + scrollOnNextSelectionRef.current = true; + setSelectedIndex(event.key === "Home" ? 0 : visibleCount - 1); + return; + } + if (event.key === "Enter") { + event.preventDefault(); + activateSelected(); + } + }; + + return ( + +
+
+ {mode === "threads" ? ( + + ) : null} + setQuery(event.target.value)} + onKeyDown={handleKeyDown} + /> + {mode === "threads" ? ( + { + setScope(nextScope); + setScopeOpen(false); + requestAnimationFrame(() => inputRef.current?.focus()); + }} + /> + ) : null} +
+
+ +
+
+
+ {mode === "commands" ? ( + + ) : ( + + )} +
+
+
+ + + + ); +} + +function ModeChip({ onClear }: { onClear: () => void }) { + return ( + undefined} + leadingVisual={} + closeAction={{ + onClose: onClear, + closeLabel: "Return to commands", + }} + /> + ); +} + +function ScopePicker({ + onOpenChange, + onScopeChange, + open, + scope, +}: { + onOpenChange: (open: boolean) => void; + onScopeChange: (scope: ThreadScope) => void; + open: boolean; + scope: ThreadScope; +}) { + const current = SCOPES.find((candidate) => candidate.id === scope); + return ( +
+ + {open ? ( +
+ {SCOPES.map((option) => ( + + ))} +
+ ) : null} +
+ ); +} + +function CommandResults({ + grouped, + onActivate, + onEnterThreads, + rows, + selectedIndex, +}: { + grouped: boolean; + onActivate: (index: number) => void; + onEnterThreads: () => void; + rows: readonly CommandRow[]; + selectedIndex: number; +}) { + if (rows.length === 0) return No matching commands; + + if (!grouped) { + return rows.map((row, index) => ( + onActivate(index)} + onSelect={row.drillIn ? onEnterThreads : undefined} + /> + )); + } + + let visibleIndex = 0; + return (["Threads", "Actions", "Plugins"] as const).map((bucket) => { + const bucketRows = rows.filter((row) => row.bucket === bucket); + if (bucketRows.length === 0) return null; + const startIndex = visibleIndex; + visibleIndex += bucketRows.length; + return ( +
+
+ {bucket} +
+ {bucketRows.map((row, index) => { + const indexInList = startIndex + index; + return ( + onActivate(indexInList)} + onSelect={row.drillIn ? onEnterThreads : undefined} + /> + ); + })} +
+ ); + }); +} + +function CommandOption({ + id, + onActivate, + onSelect, + row, + selected, +}: { + id: string; + onActivate: () => void; + onSelect?: () => void; + row: CommandRow; + selected: boolean; +}) { + const metadata = row.group === row.bucket ? null : row.group; + return ( +
+ {row.label} + + {metadata === null ? null : ( + {metadata} + )} + {row.shortcut === undefined ? null : ( + {row.shortcut} + )} + + {row.drillIn ? ( + Opens a search view + ) : null} +
+ ); +} + +function ThreadResults({ + onActivate, + rows, + selectedIndex, +}: { + onActivate: (index: number) => void; + rows: readonly ThreadRow[]; + selectedIndex: number; +}) { + if (rows.length === 0) return No matching threads; + return rows.map((row, index) => { + const presentation = THREAD_STATE[row.state]; + return ( +
onActivate(index)} + > + + {row.title} + + {row.metadata} + + + {row.state === "active" ? null : ( + + {presentation.label} + + )} +
+ ); + }); +} + +function EmptyMessage({ children }: { children: React.ReactNode }) { + return ( +

+ {children} +

+ ); +} + +function PaletteFooter({ mode }: { mode: Mode }) { + const hints = + mode === "threads" + ? ([ + { keys: ["↑↓"], label: "Select" }, + { keys: ["↵"], label: "Open" }, + { keys: ["⌘↵"], label: "Split" }, + { keys: ["Backspace", "Esc"], label: "Back" }, + ] as const) + : ([ + { keys: ["↑↓"], label: "Select" }, + { keys: ["↵"], label: "Run" }, + ] as const); + return ( +
+ {hints.map((hint) => ( + + + {hint.keys.map((keys, index) => ( + + {index === 0 ? null : ( + + )} + + {keys} + + + ))} + + {hint.label} + + ))} +
+ ); +} + +export function Review() { + return ; +} diff --git a/apps/app/src/components/commands/PaletteShell.tsx b/apps/app/src/components/commands/PaletteShell.tsx index ecfc8e7cc8..89eeddadb7 100644 --- a/apps/app/src/components/commands/PaletteShell.tsx +++ b/apps/app/src/components/commands/PaletteShell.tsx @@ -1,17 +1,27 @@ import type { KeyboardEventHandler, ReactNode, Ref } from "react"; +import { useComposedRefs } from "@radix-ui/react-compose-refs"; import { Icon } from "@bb/shared-ui/icon"; +import { useScrollOverflowState } from "@/components/thread/timeline/useScrollOverflowState"; +import { TabPill } from "@/components/ui/tab-pill"; + +interface PaletteModeChipProps { + clearLabel: string; + icon: Parameters[0]["name"]; + label: string; + onClear: () => void; +} interface PaletteShellProps { activeDescendantId?: string; accessory?: ReactNode; children: ReactNode; - footerKeys?: readonly { keys: string; label: string }[]; + footerKeys: readonly { keys: readonly string[]; label: string }[]; inputLabel: string; inputRef?: Ref; listId: string; listLabel: string; listRef?: Ref; - modeChip?: { icon: Parameters[0]["name"]; label: string }; + modeChip?: PaletteModeChipProps; onInputChange: (value: string) => void; onInputKeyDown: KeyboardEventHandler; placeholder: string; @@ -22,7 +32,7 @@ export function PaletteShell({ activeDescendantId, accessory, children, - footerKeys = [], + footerKeys, inputLabel, inputRef, listId, @@ -34,58 +44,135 @@ export function PaletteShell({ placeholder, value, }: PaletteShellProps) { + const overflow = useScrollOverflowState({ + measureOverflow: true, + }); + const composedListRef = useComposedRefs(listRef, overflow.scrollRef); + const resultsMask = + overflow.aboveOverflow && overflow.belowOverflow + ? "linear-gradient(to bottom, transparent 0, black 1.5rem, black calc(100% - 1.5rem), transparent 100%)" + : overflow.aboveOverflow + ? "linear-gradient(to bottom, transparent 0, black 1.5rem, black 100%)" + : overflow.belowOverflow + ? "linear-gradient(to bottom, black 0, black calc(100% - 1.5rem), transparent 100%)" + : undefined; + return ( <> -
- {modeChip === undefined ? null : ( - - - {modeChip.label} - - )} - onInputChange(event.target.value)} - onKeyDown={onInputKeyDown} - /> - {accessory} +
+
+ {modeChip === undefined ? null : ( + + )} + onInputChange(event.target.value)} + onKeyDown={onInputKeyDown} + /> + {accessory} +
- {children} +
+
+ {children} +
+
- {footerKeys.length === 0 ? null : ( -
- {footerKeys.map((hint) => ( - - {hint.keys} - {hint.label} +
+ {footerKeys.map((hint) => ( + + + {hint.keys.map((keys, index) => ( + + {index === 0 ? null : ( + + / + + )} + + {keys} + + + ))} - ))} -
- )} + + {hint.label} + +
+ ))} +
); } + +function PaletteModeChip({ + clearLabel, + icon, + label, + onClear, +}: PaletteModeChipProps) { + return ( + + undefined} + leadingVisual={} + closeAction={{ onClose: onClear, closeLabel: clearLabel }} + /> + + ); +} diff --git a/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx b/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx index e3de6ba888..3c466b9dd3 100644 --- a/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx +++ b/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx @@ -168,6 +168,12 @@ export function ThreadSearchPaletteMode({ const handleInputKeyDown = useCallback( (event: ReactKeyboardEvent) => { + if (event.key === "Backspace" && query.length === 0) { + event.preventDefault(); + event.stopPropagation(); + onExit(); + return; + } if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); @@ -199,7 +205,7 @@ export function ThreadSearchPaletteMode({ openRow(row, event.metaKey || event.ctrlKey); } }, - [activeIndex, onExit, openRow, result.rows], + [activeIndex, onExit, openRow, query.length, result.rows], ); const isLoading = @@ -236,12 +242,16 @@ export function ThreadSearchPaletteMode({ /> } footerKeys={presentation.footerKeys} - inputLabel={presentation.placeholder} + inputLabel="Search threads" inputRef={inputRef} listId={listId} listLabel="Threads" listRef={listRef} - modeChip={presentation.chip} + modeChip={{ + ...presentation.chip, + clearLabel: "Return to commands", + onClear: onExit, + }} onInputChange={(value) => { setQuery(value); setHighlightedIndex(0); @@ -263,7 +273,7 @@ export function ThreadSearchPaletteMode({ /> )) ) : ( -

+

{emptyMessage}

)} @@ -305,7 +315,7 @@ function ThreadSearchScopeFilter({ aria-haspopup="listbox" aria-expanded={open} aria-label="Thread scope" - className="rounded-md px-2 py-1 text-xs text-muted-foreground outline-none hover:bg-state-hover focus-visible:ring-2 focus-visible:ring-ring" + className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-subtle-foreground outline-none hover:bg-state-hover hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring" onClick={() => setOpen((value) => !value)} onKeyDown={(event) => { if (event.key === "ArrowDown" || event.key === "ArrowUp") { @@ -320,13 +330,14 @@ function ThreadSearchScopeFilter({ } }} > - {current?.label ?? "All"} + {current?.label ?? "All"} + {open ? (
{PALETTE_THREAD_SEARCH_SCOPES.map((option) => (
event.preventDefault()} @@ -343,7 +354,7 @@ function ThreadSearchScopeFilter({ returnToInput(); }} > - {option.label} + {option.label}
))}
@@ -406,22 +417,26 @@ function ThreadSearchPaletteRow({ role="option" aria-selected={isActive} className={cn( - "flex min-h-11 cursor-pointer items-center gap-3 rounded-md px-2 py-1.5 text-left text-sm", + "flex min-h-11 cursor-pointer items-center gap-3 rounded-md px-3 py-1.5 text-left text-sm", isActive && "bg-state-hover text-foreground", )} onPointerMove={onActivate} onClick={onSelect} > - + {row.metadataText} @@ -429,7 +444,7 @@ function ThreadSearchPaletteRow({ {stateLabel === null ? null : ( diff --git a/apps/app/src/lib/command-palette/palette-mode.ts b/apps/app/src/lib/command-palette/palette-mode.ts index b9ae2e7055..873a54d32e 100644 --- a/apps/app/src/lib/command-palette/palette-mode.ts +++ b/apps/app/src/lib/command-palette/palette-mode.ts @@ -8,7 +8,7 @@ export interface PaletteModePresentation { label: string; }; footerKeys: readonly { - keys: string; + keys: readonly string[]; label: string; }[]; placeholder: string; diff --git a/apps/app/src/lib/command-palette/palette-modes.ts b/apps/app/src/lib/command-palette/palette-modes.ts index 637bdf73d2..b1d20b2330 100644 --- a/apps/app/src/lib/command-palette/palette-modes.ts +++ b/apps/app/src/lib/command-palette/palette-modes.ts @@ -6,12 +6,12 @@ export const PALETTE_MODES: readonly PaletteModeRegistration[] = [ id: "thread-search", entryCommand: "thread.search", chip: { icon: "Search", label: "Threads" }, - placeholder: "Search threads", + placeholder: "Search title, project, or message…", footerKeys: [ - { keys: "↑↓", label: "Select" }, - { keys: "↵", label: "Open" }, - { keys: "⌘↵", label: "Open in split" }, - { keys: "Esc", label: "Back" }, + { keys: ["↑↓"], label: "Select" }, + { keys: ["↵"], label: "Open" }, + { keys: ["⌘↵"], label: "Split" }, + { keys: ["Backspace", "Esc"], label: "Back" }, ], View: ThreadSearchPaletteMode, }, diff --git a/packages/plugin-api-map/src/anatomy-manifest.json b/packages/plugin-api-map/src/anatomy-manifest.json index 1a26c071ca..afda546348 100644 --- a/packages/plugin-api-map/src/anatomy-manifest.json +++ b/packages/plugin-api-map/src/anatomy-manifest.json @@ -38,9 +38,9 @@ { "path": "apps/app/src/components/commands/CommandPalette.tsx", "anchors": [ - "top-[12%] max-w-xl translate-y-0 gap-0 p-0", + "top-[12%] max-w-[640px] translate-y-0 gap-0 overflow-hidden p-0", "aria-selected={isActive}", - "LAUNCHER_ACTION_ROW_BASE_CLASS", + "flex min-h-9 w-full min-w-0 cursor-pointer items-center gap-3 rounded-md px-3 py-2 text-left text-sm outline-none", "bg-state-hover text-foreground" ] }, From f14499ea7c1fc0c8b7877c60cb50142e8d599448 Mon Sep 17 00:00:00 2001 From: Bersabel Tadesse Date: Tue, 1 Sep 2026 14:33:25 -0700 Subject: [PATCH 3/7] Align command palette controls and metadata --- .../commands/CommandPalette.test.tsx | 9 ++++--- .../src/components/commands/PaletteShell.tsx | 24 ++++++++++--------- .../commands/ThreadSearchPaletteMode.tsx | 15 ++++++++---- apps/app/src/components/ui/tab-pill.tsx | 3 +++ 4 files changed, 32 insertions(+), 19 deletions(-) diff --git a/apps/app/src/components/commands/CommandPalette.test.tsx b/apps/app/src/components/commands/CommandPalette.test.tsx index fbddaf1d63..041fd1dc9d 100644 --- a/apps/app/src/components/commands/CommandPalette.test.tsx +++ b/apps/app/src/components/commands/CommandPalette.test.tsx @@ -475,13 +475,14 @@ describe("CommandPalette", () => { const modeSelect = screen.getByRole("button", { name: "Threads search" }); expectAttribute(modeSelect, "aria-pressed", "true"); expect(modeSelect.querySelector('[data-icon="Search"]')).not.toBeNull(); + expectClasses(modeSelect.parentElement, "border-border/70", "bg-background/70"); expectAttribute( screen.getByRole("button", { name: "Return to commands" }), "data-tab-pill-close", ); - expect( - screen.getByRole("button", { name: "Thread scope" }).textContent, - ).toContain("All"); + const scope = screen.getByRole("button", { name: "Thread scope" }); + expect(scope.textContent).toContain("All"); + expectClasses(scope, "text-subtle-foreground", "opacity-70"); expectText(screen.getByTestId("command-palette"), "Split"); const footer = screen .getByTestId("command-palette") @@ -804,6 +805,7 @@ describe("CommandPalette", () => { expectClasses( row.querySelector("[data-palette-thread-metadata]"), "text-subtle-foreground", + "opacity-70", ); } expectClasses( @@ -887,6 +889,7 @@ describe("CommandPalette", () => { expectClasses( row.querySelector("[data-palette-thread-metadata]"), "text-subtle-foreground", + "opacity-70", ); } expect(results.querySelector("[data-palette-thread-state]")).toBeNull(); diff --git a/apps/app/src/components/commands/PaletteShell.tsx b/apps/app/src/components/commands/PaletteShell.tsx index 89eeddadb7..73d6e25048 100644 --- a/apps/app/src/components/commands/PaletteShell.tsx +++ b/apps/app/src/components/commands/PaletteShell.tsx @@ -4,6 +4,11 @@ import { Icon } from "@bb/shared-ui/icon"; import { useScrollOverflowState } from "@/components/thread/timeline/useScrollOverflowState"; import { TabPill } from "@/components/ui/tab-pill"; +export const PALETTE_FOOTER_CONTROL_SURFACE_CLASS = + "border border-border/70 bg-background/70 shadow-xs"; +export const PALETTE_FOOTER_KEYCAP_CLASS = `inline-flex min-w-5 items-center justify-center rounded px-1.5 py-0.5 font-mono text-xs leading-none text-muted-foreground ${PALETTE_FOOTER_CONTROL_SURFACE_CLASS}`; +export const PALETTE_FOOTER_LABEL_CLASS = "text-subtle-foreground opacity-70"; + interface PaletteModeChipProps { clearLabel: string; icon: Parameters[0]["name"]; @@ -67,9 +72,7 @@ export function PaletteShell({ className="flex h-10 items-center gap-2 px-3" data-palette-input-frame > - {modeChip === undefined ? null : ( - - )} + {modeChip === undefined ? null : } ( {index === 0 ? null : ( - + / )} - - {keys} - + {keys} ))} - + {hint.label} @@ -169,6 +170,7 @@ function PaletteModeChip({ label={label} title={label} isActive + className={PALETTE_FOOTER_CONTROL_SURFACE_CLASS} onSelect={() => undefined} leadingVisual={} closeAction={{ onClose: onClear, closeLabel: clearLabel }} diff --git a/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx b/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx index 3c466b9dd3..a40ebceb1e 100644 --- a/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx +++ b/apps/app/src/components/commands/ThreadSearchPaletteMode.tsx @@ -33,7 +33,7 @@ import { } from "@/lib/command-palette/palette-thread-search"; import { windowPaletteThreadSearchText } from "@/lib/command-palette/palette-thread-search-window"; import type { PaletteModeViewProps } from "@/lib/command-palette/palette-mode"; -import { PaletteShell } from "./PaletteShell"; +import { PALETTE_FOOTER_LABEL_CLASS, PaletteShell } from "./PaletteShell"; export function ThreadSearchPaletteMode({ onExit, @@ -219,8 +219,7 @@ export function ThreadSearchPaletteMode({ ? "Searching threads" : trimmedQuery.length === 1 ? "Type at least 2 characters" - : (navigation.isLoading || archivedThreads.isLoading) && - result.isRecent + : (navigation.isLoading || archivedThreads.isLoading) && result.isRecent ? "Loading recent threads" : result.isRecent ? "No recent threads" @@ -315,7 +314,10 @@ function ThreadSearchScopeFilter({ aria-haspopup="listbox" aria-expanded={open} aria-label="Thread scope" - className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-subtle-foreground outline-none hover:bg-state-hover hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring" + className={cn( + "inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs outline-none hover:bg-state-hover hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring", + PALETTE_FOOTER_LABEL_CLASS, + )} onClick={() => setOpen((value) => !value)} onKeyDown={(event) => { if (event.key === "ArrowDown" || event.key === "ArrowUp") { @@ -434,7 +436,10 @@ function ThreadSearchPaletteRow({ /> diff --git a/apps/app/src/components/ui/tab-pill.tsx b/apps/app/src/components/ui/tab-pill.tsx index 99ffdb98d5..7bdc0c4a94 100644 --- a/apps/app/src/components/ui/tab-pill.tsx +++ b/apps/app/src/components/ui/tab-pill.tsx @@ -23,6 +23,7 @@ interface TabPillCloseAction { interface TabPillProps { label: string; + className?: string; ariaLabel?: string; ariaKeyshortcuts?: string; iconOnly?: boolean; @@ -39,6 +40,7 @@ interface TabPillProps { export function TabPill({ label, + className, ariaLabel, ariaKeyshortcuts, iconOnly = false, @@ -72,6 +74,7 @@ export function TabPill({ isActive ? cn(CONTEXT_SELECTION_SURFACE_CLASS, "text-foreground") : "text-muted-foreground hover:bg-state-hover", + className, )} >