diff --git a/apps/app/src/components/commands/CommandPalette.test.tsx b/apps/app/src/components/commands/CommandPalette.test.tsx index 14710012da..6749fbc04a 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,31 +50,31 @@ const PALETTE_BINDING: AppKeybinding = { when: { all: ["mainSurface"], none: ["modalOpen"] }, }; -const THREAD_SEARCH_BINDING: AppKeybinding = { - command: "thread.search", +// A chord that declines while any modal is open, like most app bindings. +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"] }, }; -// A chord that declines while any modal is open, like most app bindings. -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"] }, }; @@ -80,6 +89,14 @@ function defaults(...commands: AppCommandId[]): AppDefaultKeybinding[] { } 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: () => ({ @@ -88,7 +105,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, @@ -107,47 +124,58 @@ vi.mock("@/lib/bb-desktop", () => ({ getBbDesktopInfo: () => null, })); -vi.mock("./ThreadPaletteResults", () => ({ - ThreadPaletteResults: ({ - onSelect, - query, - }: { - onSelect: (item: { - id: string; - optionId: string; - projectId: string; - threadId: string; - messageSeq: number | null; - }) => void; - query: string; - }) => ( - - ), +vi.mock("@bb/shared-ui/hooks/use-compact-viewport", () => ({ + useIsCompactViewport: () => false, })); -function LocationProbe() { - const location = useLocation(); - return ( - - {JSON.stringify({ pathname: location.pathname, state: location.state })} - - ); -} +vi.mock("@/lib/split-layout/openThreadInSplit", () => ({ + openThreadInSplit: openThreadInSplitMock, +})); + +vi.mock("@/components/ui/app-route-anchor", () => ({ + useRouteNavigate: () => routeNavigateMock, +})); + +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, () => { @@ -157,13 +185,50 @@ function Handler({ command }: { command: AppCommandId }) { return null; } -function renderPalette({ - isCompactViewport = false, - onSplit, -}: { - isCompactViewport?: boolean; - onSplit?: () => void; -} = {}) { +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( @@ -171,20 +236,13 @@ function renderPalette({ origin + - , - { - wrapper: ({ children }) => ( - - {children} - - ), - }, ); screen.getByTestId("origin").focus(); return result; @@ -214,6 +272,9 @@ 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.getAllByRole("option").map((option) => option.textContent); const selectedOption = () => @@ -224,7 +285,14 @@ const selectedOption = () => afterEach(() => { cleanup(); removePluginSlotRegistrations("linear"); + resetPluginLogoStoreForTest(); testState.calls.length = 0; + modeState.activeRecents = []; + modeState.archivedRecents = []; + modeState.drafts = []; + modeState.searchResponse = undefined; + openThreadInSplitMock.mockReset(); + routeNavigateMock.mockReset(); window.localStorage.clear(); }); @@ -235,13 +303,345 @@ describe("CommandPalette", () => { await waitFor(() => expect(searchField()).toBeTruthy()); // Chrome maps Mod+Shift+P to print; only preventDefault stops it. expect(event.defaultPrevented).toBe(true); - expect((searchField() as HTMLInputElement).value).toBe(">"); const titles = optionTitles(); expect(titles?.[0]).toContain("New thread"); - // Every mounted handler is listed, including the palette's thread mode. + // Every mounted handler is listed; nothing else is. 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"), + ]); + // The bucket already supplies this context, so rows do not repeat it. + 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); + } + // Root rows and headers remain text-only. + 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 () => { renderPalette(); openPalette(); @@ -249,10 +649,12 @@ 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 () => { @@ -272,7 +674,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"), ); @@ -289,7 +691,12 @@ describe("CommandPalette", () => { openPalette(); await waitFor(() => expect(searchField()).toBeTruthy()); - fireEvent.change(searchField(), { target: { value: ">split" } }); + 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"), ); @@ -299,23 +706,11 @@ describe("CommandPalette", () => { expect(testState.calls).toEqual([]); }); - it("runs a compact selection once after restoring focus", async () => { - renderPalette({ isCompactViewport: true }); - openPalette(); - await waitFor(() => expect(searchField()).toBeTruthy()); - - fireEvent.change(searchField(), { target: { value: ">toggle panel" } }); - fireEvent.keyDown(searchField(), { key: "Enter" }); - - await waitFor(() => expect(testState.calls).toEqual(["panel.toggle"])); - expect(document.activeElement).toBe(screen.getByTestId("origin")); - }); - - 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"), ); @@ -324,7 +719,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 +786,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 +812,7 @@ describe("CommandPalette", () => { commandPaletteActions: [ { id: "open-issue", - title: "Linear: open issue", + title: "Open issue", run: () => { testState.calls.push("plugin-ran"); }, @@ -412,9 +823,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 +842,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,66 +850,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 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 4d93d41df2..03dcef2451 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, @@ -35,13 +40,20 @@ import { import { buildPluginPaletteActions } from "@/lib/command-palette/palette-plugin-actions"; import { getPluginSlotSnapshot } from "@/lib/plugin-slots"; import { getActiveThreadPanelOpener } from "@/components/plugin/plugin-thread-panel-navigation"; -import { getThreadRoutePath } from "@/lib/route-paths"; 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 { /** The surface's thread and project, handed to plugin rows. */ @@ -60,19 +72,17 @@ export function CommandPalette({ projectId, onSplit, }: 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(), ); @@ -94,7 +104,8 @@ export function CommandPalette({ : [ { id: "internal:thread.split", - group: "Threads", + bucket: "Actions", + group: "Window and layout", title: "Split", shortcut: null, run: onSplit, @@ -109,22 +120,20 @@ export function CommandPalette({ ], [ projectId, - onSplit, runner.dispatch, runner.isCommandAvailable, shortcuts, threadId, + onSplit, ], ); - 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); }, [buildActions], ); @@ -133,29 +142,55 @@ export function CommandPalette({ 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 rankedCommands = useMemo( - () => rankPaletteActions({ actions, query: modeQuery, recentIds: recents }), - [actions, modeQuery, recents], + const ranked = useMemo( + () => rankPaletteActions({ actions, query, recentIds: recents }), + [actions, query, recents], + ); + 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( + () => + isGroupedRoot ? rootGroups.flatMap((group) => group.entries) : ranked, + [isGroupedRoot, ranked, rootGroups], ); - const resultCount = - mode === "commands" ? rankedCommands.length : threadItems.length; // Typing can shrink the list under the selection. const activeIndex = - resultCount === 0 ? -1 : Math.min(highlightedIndex, resultCount - 1); + visibleEntries.length === 0 + ? -1 + : Math.min(highlightedIndex, visibleEntries.length - 1); /** * Focus stays in the search field, so nothing scrolls the highlighted row @@ -173,62 +208,52 @@ export function CommandPalette({ }, [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); + }, []); /** * Restore focus before running, so a command that focuses something does not * have it taken back by the dialog's own restoration a tick later. */ - 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; } @@ -236,7 +261,7 @@ export function CommandPalette({ event.preventDefault(); scrollOnNextHighlightRef.current = true; setHighlightedIndex((current) => - current <= 0 ? resultCount - 1 : current - 1, + current <= 0 ? visibleEntries.length - 1 : current - 1, ); return; } @@ -249,116 +274,129 @@ export function CommandPalette({ 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 ( - + { + // A mode owns Escape as a one-level pop. The focused input/filter + // performs that transition; the dialog must not close underneath it. + 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); // `activeIndex` may not change, so the effect above cannot do // this: send the scrolled container back to the first row. 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)} - /> - )) - ) : ( - - )} -
+ )}
); @@ -377,6 +415,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 ( // A listbox option the input points at, not a focusable control.
- - - {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..7ee4bcfc05 --- /dev/null +++ b/apps/app/src/components/commands/PaletteShell.tsx @@ -0,0 +1,92 @@ +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; +} + +/** Shared palette chrome. Command and Mode producers own only list content. */ +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 1f47c8146b..8d29c1ba4a 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 @@ -33,6 +33,7 @@ vi.mock("@/components/commands/AppCommandProvider", () => ({ if (enabled) commandHandlers.set(command, handler); else commandHandlers.delete(command); }, + 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 55b7d18c2f..324eb462f0 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/components/sidebar/AppSidebar.tsx b/apps/app/src/components/sidebar/AppSidebar.tsx index 7e979dbb95..d7d903075e 100644 --- a/apps/app/src/components/sidebar/AppSidebar.tsx +++ b/apps/app/src/components/sidebar/AppSidebar.tsx @@ -147,8 +147,8 @@ export function AppSidebar({ }: AppSidebarProps) { const quickCreateProject = useQuickCreateProjectController(); // The resolved replacement owns the sidebar's scrolling thread list. It never - // replaces the chrome around it: the New-thread button, search action, - // the plugin nav rows, and the footer stay host-rendered in every sidebar. + // replaces the chrome around it: the New-thread button, plugin nav rows, and + // footer stay host-rendered in every sidebar. const threadListReplacement = useThreadListReplacement(); const { threadId: activeThreadId } = useRouteState(); const navigate = useNavigate(); @@ -193,7 +193,6 @@ export function AppSidebar({ state: { focusPrompt: true }, }); }, [closeOnMobile, navigate]); - const showThreadShortcuts = useCallback(() => { const targets = getSidebarThreadShortcutTargets(sidebarRef.current); threadShortcutTargetsRef.current = targets; @@ -345,7 +344,6 @@ export function AppSidebar({ newThreadSplit={newThreadSplit} onNewChat={handleNewChat} onSplit={onSplit} - onSearchThreads={closeOnMobile} /> {toolsRoutePath ? ( void; onSplit?: () => void; - onSearchThreads?: () => void; } interface ProjectListShellProps { @@ -844,12 +840,9 @@ export function ProjectListActionButtons({ newThreadSplit, onNewChat, onSplit, - onSearchThreads, }: ProjectListActionButtonsProps) { - const commandRunner = useAppCommandRunner(); const isNewChatDisabled = !onNewChat; const newThreadShortcut = useAppCommandShortcut("thread.new"); - const threadSearchShortcut = useAppCommandShortcut("thread.search"); const newThreadSplitIndicator = useNewThreadSplitIndicator(splitEnabled); return ( @@ -922,27 +915,6 @@ export function ProjectListActionButtons({ ) : null} - - - - ); diff --git a/apps/app/src/lib/command-palette/palette-action.ts b/apps/app/src/lib/command-palette/palette-action.ts index 131a3d2172..c4ca04db3a 100644 --- a/apps/app/src/lib/command-palette/palette-action.ts +++ b/apps/app/src/lib/command-palette/palette-action.ts @@ -1,5 +1,14 @@ import type { AppShortcutPresentation } from "@/lib/app-keybindings"; +/** Root sections, in their rendered order. Producers choose; the shell groups. */ +export const PALETTE_ACTION_BUCKETS = [ + "Threads", + "Actions", + "Plugins", +] as const; + +export type PaletteActionBucket = (typeof PALETTE_ACTION_BUCKETS)[number]; + /** * One row of the quick palette. Producer-agnostic so ranking and rendering do * not care whether an action came from an app command or elsewhere. @@ -7,7 +16,9 @@ import type { AppShortcutPresentation } from "@/lib/app-keybindings"; export interface PaletteAction { /** Stable across sessions; the recents key. `app:thread.new`. */ id: string; - /** Section label; also matched against the query. */ + /** Root section at rest. */ + bucket: PaletteActionBucket; + /** Producer-owned metadata group; also matched against the query. */ group: string; title: string; /** Drawn as a pill on the row; null when the command has no binding. */ 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 50eb365b40..1babed7f88 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,20 @@ 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("dispatches with the element that was focused before the palette opened", () => { const target = { id: "composer" } as unknown as EventTarget; const dispatch = vi.fn(); 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 7841c867c3..15ac3988f9 100644 --- a/apps/app/src/lib/command-palette/palette-app-commands.ts +++ b/apps/app/src/lib/command-palette/palette-app-commands.ts @@ -41,6 +41,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..4eb7e9af54 --- /dev/null +++ b/apps/app/src/lib/command-palette/palette-mode.ts @@ -0,0 +1,32 @@ +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; + /** Queue work until after the dialog has restored focus and closed. */ + runAfterClose: (run: () => void) => void; + presentation: PaletteModePresentation; +} + +/** + * One content domain hosted by the palette shell. The registry is the only + * place the shell learns which existing command enters a mode. + */ +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 46069c1646..23b729c6e0 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 5956e1b499..a49f0135ad 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 { @@ -61,7 +62,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 a3749ef2bc..5b60a33f44 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..3b84e7d20b --- /dev/null +++ b/apps/app/src/lib/command-palette/palette-thread-search-window.ts @@ -0,0 +1,175 @@ +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; + } + + // Malformed input can point into an astral character. Expand the highlight + // to the complete code point so consumers never receive a slicing boundary + // between its high and low surrogates. + 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; +} + +/** + * Builds the palette's compact display window around the first valid match. + * The caller decides whether its one-line clamp would hide that match; calling + * this helper explicitly requests the 16-character lead and 40-character tail. + */ +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); + + // Prefer dropping the astral character straddling a hard window boundary to + // returning either half of it. Word-boundary moves already land safely. + 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..6cfd3dd629 --- /dev/null +++ b/apps/app/src/lib/command-palette/palette-thread-search.ts @@ -0,0 +1,216 @@ +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; +} + +/** + * Produces the one mode list. Lifecycle rank is structural, so relevance from + * one lifecycle can never move archived content ahead of an active result. + */ +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 e3335a7d9a..b416704380 100644 --- a/apps/app/src/lib/plugin-logos.ts +++ b/apps/app/src/lib/plugin-logos.ts @@ -52,6 +52,11 @@ function getPluginLogoUrls(): ReadonlyMap { return logoUrls; } +/** Manifest display name, with the stable plugin id as the unavailable fallback. */ +export function getPluginDisplayName(pluginId: string): string { + return getPluginLogoUrls().get(pluginId)?.displayName ?? pluginId; +} + /** Compact branding resolved from the latest plugin inventory. */ export function usePluginCompactBranding( pluginId: string, 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 f7d17f1dd6..f03f91bb3b 100644 --- a/apps/app/src/lib/split-layout/openThreadInSplit.ts +++ b/apps/app/src/lib/split-layout/openThreadInSplit.ts @@ -19,11 +19,16 @@ 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; /** Splits are off on compact viewports. */ isCompact: boolean; + /** Optional route state, such as a search-result message deep link. */ + state?: Record; } /** @@ -41,13 +46,14 @@ export function openThreadInSplit({ projectId, threadId, isCompact, + state, }: OpenThreadInSplitArgs): void { const route = getThreadRoutePath({ projectId, threadId }); const layout = store.get(splitLayoutAtom); // No split to grow (compact viewport, or a non-thread route with no layout): // behave like an ordinary open. if (isCompact || layout === null) { - navigate(route); + navigate(route, state === undefined ? undefined : { state }); return; } const existing = findPaneByThread(layout.root, projectId, threadId); @@ -56,7 +62,10 @@ export function openThreadInSplit({ if (next !== layout) { store.set(splitLayoutAtom, next); } - navigate(route, { replace: true }); + navigate(route, { + replace: true, + ...(state === undefined ? {} : { state }), + }); return; } // Same decision as a drag with a default right-edge target. @@ -73,5 +82,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 9a907d2ee7..abe3013403 100644 --- a/packages/plugin-api-map/src/anatomy-manifest.json +++ b/packages/plugin-api-map/src/anatomy-manifest.json @@ -45,16 +45,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 21ca8dcdb0..836e496583 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.