From b8839ed130bf7d3ae8952c7b1671d168c9d28122 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:49:03 -0500 Subject: [PATCH 1/4] feat(web): Add project and Codex import open as their own dialogs Add project and "Bring in Codex conversation" lived inside the command palette, which switched modes on the text in its field: typing a path turned Search into a folder browser that could create a project on Enter. A clone or import that finished after the palette closed could also call the wrong caller back or navigate anyway. Both flows are now their own dialogs, each with a small store that loads at startup and a body that loads on first open. Every opening is a session: an operation's callback, navigation and close happen only if its session is still open, otherwise a notice says what was added with an Open button. A typed path in Search adds an "Add project at " row on top of the results instead of changing modes. App-wide shortcuts stand down while the palette or either dialog is open, and each dialog returns focus to whatever opened it. The plan for the rest of the palette work is in docs/design/command-palette.md. --- apps/web/src/commandPaletteStore.test.ts | 10 +- apps/web/src/commandPaletteStore.ts | 44 +- apps/web/src/commands/shortcutBlock.ts | 24 + apps/web/src/components/AppSidebarLayout.tsx | 5 +- .../ChatView.add-project.browser.tsx | 376 +++- .../components/ChatView.browser-harness.tsx | 9 +- .../ChatView.codex-import.browser.tsx | 245 +++ .../components/ChatView.palette.browser.tsx | 234 --- apps/web/src/components/ChatView.tsx | 4 +- .../components/CommandPalette.logic.test.ts | 20 - .../src/components/CommandPalette.logic.ts | 145 +- apps/web/src/components/CommandPalette.tsx | 9 + .../src/components/CommandPaletteDialog.tsx | 1807 +---------------- .../src/components/NoActiveThreadState.tsx | 4 +- apps/web/src/components/Sidebar.tsx | 13 +- .../addProject/AddProjectDialog.tsx | 45 + .../addProject/OpenAddProjectDialog.tsx | 1635 +++++++++++++++ .../addProject/addProject.logic.test.ts | 22 + .../components/addProject/addProject.logic.ts | 118 ++ .../addProject/addProjectComputers.ts | 112 + .../addProject/addProjectStore.test.ts | 80 + .../components/addProject/addProjectStore.ts | 98 + apps/web/src/components/chat/ChatComposer.tsx | 4 +- .../src/components/chat/ProjectCrumbMenu.tsx | 3 +- .../codexImport/CodexSessionImportDialog.tsx | 46 + .../OpenCodexSessionImportDialog.tsx | 473 +++++ .../codexImport/codexImportStore.test.ts | 58 + .../codexImport/codexImportStore.ts | 97 + .../setup/AgentSetupScreen.browser.tsx | 28 +- .../src/components/setup/AgentSetupScreen.tsx | 19 +- .../components/sidebar/ProjectScopeMenu.tsx | 7 +- .../components/terminals/TerminalsPage.tsx | 4 +- apps/web/src/lib/dialogReturnFocus.ts | 29 + apps/web/src/routes/_chat.tsx | 4 +- apps/web/src/routes/settings.tsx | 6 +- docs/design/command-palette-mockup.html | 1020 ++++++++++ docs/design/command-palette.md | 724 +++++++ 37 files changed, 5373 insertions(+), 2208 deletions(-) create mode 100644 apps/web/src/commands/shortcutBlock.ts create mode 100644 apps/web/src/components/ChatView.codex-import.browser.tsx create mode 100644 apps/web/src/components/addProject/AddProjectDialog.tsx create mode 100644 apps/web/src/components/addProject/OpenAddProjectDialog.tsx create mode 100644 apps/web/src/components/addProject/addProject.logic.test.ts create mode 100644 apps/web/src/components/addProject/addProject.logic.ts create mode 100644 apps/web/src/components/addProject/addProjectComputers.ts create mode 100644 apps/web/src/components/addProject/addProjectStore.test.ts create mode 100644 apps/web/src/components/addProject/addProjectStore.ts create mode 100644 apps/web/src/components/codexImport/CodexSessionImportDialog.tsx create mode 100644 apps/web/src/components/codexImport/OpenCodexSessionImportDialog.tsx create mode 100644 apps/web/src/components/codexImport/codexImportStore.test.ts create mode 100644 apps/web/src/components/codexImport/codexImportStore.ts create mode 100644 apps/web/src/lib/dialogReturnFocus.ts create mode 100644 docs/design/command-palette-mockup.html create mode 100644 docs/design/command-palette.md diff --git a/apps/web/src/commandPaletteStore.test.ts b/apps/web/src/commandPaletteStore.test.ts index 917217bbc..6508e047b 100644 --- a/apps/web/src/commandPaletteStore.test.ts +++ b/apps/web/src/commandPaletteStore.test.ts @@ -10,14 +10,14 @@ describe("command palette store", () => { beforeEach(resetStore); it("advances the open generation once per opening, not per open call", () => { - const { setOpen, openAddProject } = useCommandPaletteStore.getState(); + const { setOpen, openThreadSearch } = useCommandPaletteStore.getState(); setOpen(true); expect(useCommandPaletteStore.getState().openGeneration).toBe(1); // Re-purposing an already-open palette stays in the same session. setOpen(true); - openAddProject(); + openThreadSearch({ projectName: "Docs", memberProjectKeys: [] }); expect(useCommandPaletteStore.getState().openGeneration).toBe(1); setOpen(false); @@ -46,10 +46,10 @@ describe("command palette store", () => { }); it("clears the open intent when a guarded close lands", () => { - const { openAddProject, closeIfGeneration } = useCommandPaletteStore.getState(); + const { openThreadSearch, closeIfGeneration } = useCommandPaletteStore.getState(); - openAddProject(); - expect(useCommandPaletteStore.getState().openIntent?.kind).toBe("add-project"); + openThreadSearch({ projectName: "Docs", memberProjectKeys: [] }); + expect(useCommandPaletteStore.getState().openIntent?.kind).toBe("search-threads"); closeIfGeneration(useCommandPaletteStore.getState().openGeneration); expect(useCommandPaletteStore.getState().openIntent).toBeNull(); diff --git a/apps/web/src/commandPaletteStore.ts b/apps/web/src/commandPaletteStore.ts index eeec7b56c..656179a83 100644 --- a/apps/web/src/commandPaletteStore.ts +++ b/apps/web/src/commandPaletteStore.ts @@ -1,4 +1,3 @@ -import type { EnvironmentId, ScopedProjectRef } from "@threadlines/contracts"; import { create } from "zustand"; export interface CommandPaletteThreadSearchRequest { @@ -8,19 +7,10 @@ export interface CommandPaletteThreadSearchRequest { memberProjectKeys: readonly string[]; } -/** - * An add-project flow opened to pick a folder for someone else (the setup - * screen): the palette reports the project instead of opening a thread in it, - * and stays on the given environment. - */ -export interface CommandPaletteProjectSelection { - readonly environmentId?: EnvironmentId; - readonly onProjectSelected: (projectRef: ScopedProjectRef) => void; -} - -type CommandPaletteOpenIntent = - | { kind: "add-project"; requestId: number } - | ({ kind: "search-threads"; requestId: number } & CommandPaletteThreadSearchRequest); +type CommandPaletteOpenIntent = { + kind: "search-threads"; + requestId: number; +} & CommandPaletteThreadSearchRequest; interface CommandPaletteStore { open: boolean; @@ -33,14 +23,10 @@ interface CommandPaletteStore { */ openGeneration: number; openIntent: CommandPaletteOpenIntent | null; - /** Present while an add-project flow is picking a folder for a caller; cleared on close. */ - projectSelection: CommandPaletteProjectSelection | null; setOpen: (open: boolean) => void; /** Closes only if the palette is still on the given open generation. */ closeIfGeneration: (generation: number) => void; toggleOpen: () => void; - /** Opens the add-project flow; with a selection, it reports the project instead of opening it. */ - openAddProject: (selection?: CommandPaletteProjectSelection) => void; openThreadSearch: (request: CommandPaletteThreadSearchRequest) => void; clearOpenIntent: () => void; } @@ -49,7 +35,6 @@ export const useCommandPaletteStore = create((set) => ({ open: false, openGeneration: 0, openIntent: null, - projectSelection: null, setOpen: (open) => set((state) => ({ open, @@ -57,36 +42,21 @@ export const useCommandPaletteStore = create((set) => ({ ? state.open ? {} : { openGeneration: state.openGeneration + 1 } - : { openIntent: null, projectSelection: null }), + : { openIntent: null }), })), closeIfGeneration: (generation) => set((state) => - state.open && state.openGeneration === generation - ? { open: false, openIntent: null, projectSelection: null } - : state, + state.open && state.openGeneration === generation ? { open: false, openIntent: null } : state, ), toggleOpen: () => set((state) => ({ open: !state.open, - ...(state.open - ? { openIntent: null, projectSelection: null } - : { openGeneration: state.openGeneration + 1 }), - })), - openAddProject: (selection) => - set((state) => ({ - open: true, - ...(state.open ? {} : { openGeneration: state.openGeneration + 1 }), - projectSelection: selection ?? null, - openIntent: { - kind: "add-project", - requestId: (state.openIntent?.requestId ?? 0) + 1, - }, + ...(state.open ? { openIntent: null } : { openGeneration: state.openGeneration + 1 }), })), openThreadSearch: (request) => set((state) => ({ open: true, ...(state.open ? {} : { openGeneration: state.openGeneration + 1 }), - projectSelection: null, openIntent: { kind: "search-threads", requestId: (state.openIntent?.requestId ?? 0) + 1, diff --git a/apps/web/src/commands/shortcutBlock.ts b/apps/web/src/commands/shortcutBlock.ts new file mode 100644 index 000000000..5f40d1671 --- /dev/null +++ b/apps/web/src/commands/shortcutBlock.ts @@ -0,0 +1,24 @@ +import { useCommandPaletteStore } from "../commandPaletteStore"; +import { useAddProjectStore } from "../components/addProject/addProjectStore"; +import { useCodexImportStore } from "../components/codexImport/codexImportStore"; + +/** + * Add project or Bring in Codex conversation is open. The palette's own + * shortcut stands down for these, so it never opens over a clone in progress. + */ +export function isPaletteLaunchedDialogOpen(): boolean { + return ( + useAddProjectStore.getState().session !== null || + useCodexImportStore.getState().session !== null + ); +} + +/** + * A dialog that owns the keyboard is open: the command palette, Add project or + * Bring in Codex conversation. App-wide shortcut listeners stand down while it + * is, so a key pressed in the dialog never acts on the page behind it. Read it + * when the key lands. + */ +export function isKeyboardOwnedByDialog(): boolean { + return useCommandPaletteStore.getState().open || isPaletteLaunchedDialogOpen(); +} diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index c8f9f695d..5fe6a99a3 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -14,6 +14,7 @@ import { useLocation, useNavigate } from "@tanstack/react-router"; import { useAppHistory } from "../appHistory"; import { useCommandPaletteStore } from "../commandPaletteStore"; +import { isKeyboardOwnedByDialog, isPaletteLaunchedDialogOpen } from "../commands/shortcutBlock"; import { isKnownEnvironment } from "../environments/runtime"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { getClientSettings } from "../hooks/useSettings"; @@ -83,7 +84,7 @@ function AppShellCommands({ hasList }: { readonly hasList: boolean }) { useEffect(() => { const onWindowKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented || event.repeat) return; - if (useCommandPaletteStore.getState().open) return; + if (isKeyboardOwnedByDialog()) return; // Read when the key lands, like the sidebar's own shortcuts: a rule // the user scoped to an open terminal must see the terminal as it is. const terminalOpen = routeThreadRef @@ -168,6 +169,8 @@ function AppShellCommands({ hasList }: { readonly hasList: boolean }) { appHistory.forward(); return; case "toggle-command-palette": + // Not over Add project or a Codex import in progress. + if (isPaletteLaunchedDialogOpen()) return; useCommandPaletteStore.getState().toggleOpen(); return; case "open-whats-new": diff --git a/apps/web/src/components/ChatView.add-project.browser.tsx b/apps/web/src/components/ChatView.add-project.browser.tsx index 5f846721d..e3ae9a277 100644 --- a/apps/web/src/components/ChatView.add-project.browser.tsx +++ b/apps/web/src/components/ChatView.add-project.browser.tsx @@ -1,5 +1,5 @@ import { ORCHESTRATION_WS_METHODS, MessageId, WS_METHODS } from "@threadlines/contracts"; -import { page } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; import { __setEnvironmentApiOverrideForTests } from "../environmentApi"; @@ -31,6 +31,8 @@ import { dispatchInputKey, mountChatView, registerChatViewSuiteHooks, + dispatchChatNewShortcut, + waitForLayout, } from "./ChatView.browser-harness"; vi.mock("../lib/gitStatusState", () => ({ @@ -46,6 +48,40 @@ vi.mock("../lib/gitStatusState", () => ({ resetGitStatusStateForTests: () => undefined, })); +const MOD_SHORTCUT = { + metaKey: false, + ctrlKey: false, + altKey: false, + modKey: true, +} as const; +const NOT_IN_TERMINAL = { + type: "not", + node: { type: "identifier", name: "terminalFocus" }, +} as const; +const CHAT_NEW_BINDING = { + command: "chat.new", + shortcut: { ...MOD_SHORTCUT, key: "o", shiftKey: true }, + whenAst: NOT_IN_TERMINAL, +} as const; +const PALETTE_TOGGLE_BINDING = { + command: "commandPalette.toggle", + shortcut: { ...MOD_SHORTCUT, key: "k", shiftKey: false }, + whenAst: NOT_IN_TERMINAL, +} as const; + +function dispatchModShortcut(key: string): void { + const useMetaForMod = isMacPlatform(navigator.platform); + window.dispatchEvent( + new KeyboardEvent("keydown", { + key, + metaKey: useMetaForMod, + ctrlKey: !useMetaForMod, + bubbles: true, + cancelable: true, + }), + ); +} + describe("ChatView (full app): add project", () => { registerChatViewSuiteHooks(); @@ -115,16 +151,15 @@ describe("ChatView (full app): add project", () => { try { await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]); - const palette = page.getByTestId("command-palette"); + const dialog = page.getByTestId("add-project-dialog"); await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); - await palette.getByText("GitHub repository", { exact: true }).click(); + await page.getByTestId("command-palette").getByText("Add project", { exact: true }).click(); + await expect.element(dialog).toBeInTheDocument(); + await dialog.getByText("GitHub repository", { exact: true }).click(); await waitForCommandPaletteInput("Enter GitHub repository (owner/repo)"); - await expect.element(palette.getByText("t3-oss/t3-env", { exact: true })).toBeVisible(); - await palette.getByText("t3-oss/t3-env", { exact: true }).click(); + await expect.element(dialog.getByText("t3-oss/t3-env", { exact: true })).toBeVisible(); + await dialog.getByText("t3-oss/t3-env", { exact: true }).click(); await vi.waitFor( () => { @@ -189,8 +224,8 @@ describe("ChatView (full app): add project", () => { await page.getByTestId("sidebar-add-project-trigger").click(); - const palette = page.getByTestId("command-palette"); - await expect.element(palette).toBeInTheDocument(); + const dialog = page.getByTestId("add-project-dialog"); + await expect.element(dialog).toBeInTheDocument(); await selectLocalFolderAction(); const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); @@ -252,8 +287,8 @@ describe("ChatView (full app): add project", () => { await page.getByTestId("sidebar-add-project-trigger").click(); - const palette = page.getByTestId("command-palette"); - await expect.element(palette).toBeInTheDocument(); + const dialog = page.getByTestId("add-project-dialog"); + await expect.element(dialog).toBeInTheDocument(); await selectLocalFolderAction(); const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); @@ -310,18 +345,18 @@ describe("ChatView (full app): add project", () => { try { await waitForServerConfigToApply(); - const palette = page.getByTestId("command-palette"); + const dialog = page.getByTestId("add-project-dialog"); await page.getByTestId("sidebar-add-project-trigger").click(); - await expect.element(palette).toBeInTheDocument(); + await expect.element(dialog).toBeInTheDocument(); await selectLocalFolderAction(); const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Desktop/fresh-project"); await expect - .element(palette.getByRole("button", { name: "Create & Add (Enter)" })) + .element(dialog.getByRole("button", { name: "Create & Add (Enter)" })) .toBeInTheDocument(); - await expect.element(palette.getByText("Will create this folder")).not.toBeInTheDocument(); + await expect.element(dialog.getByText("Will create this folder")).not.toBeInTheDocument(); await dispatchInputKey(browseInput, { key: "Enter" }); @@ -390,10 +425,10 @@ describe("ChatView (full app): add project", () => { try { await waitForServerConfigToApply(); - const palette = page.getByTestId("command-palette"); + const dialog = page.getByTestId("add-project-dialog"); await page.getByTestId("sidebar-add-project-trigger").click(); - await expect.element(palette).toBeInTheDocument(); + await expect.element(dialog).toBeInTheDocument(); await selectLocalFolderAction(); const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/codex/"); @@ -411,11 +446,9 @@ describe("ChatView (full app): add project", () => { { timeout: 8_000, interval: 16 }, ); + await expect.element(dialog.getByRole("button", { name: "Add (Enter)" })).toBeInTheDocument(); await expect - .element(palette.getByRole("button", { name: "Add (Enter)" })) - .toBeInTheDocument(); - await expect - .element(palette.getByRole("button", { name: "Create & Add (Enter)" })) + .element(dialog.getByRole("button", { name: "Create & Add (Enter)" })) .not.toBeInTheDocument(); await dispatchInputKey(browseInput, { key: "Enter" }); @@ -528,14 +561,13 @@ describe("ChatView (full app): add project", () => { connectedAt: NOW_ISO, }); - const palette = page.getByTestId("command-palette"); + const dialog = page.getByTestId("add-project-dialog"); await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); - await expect.element(palette.getByText("Environments", { exact: true })).toBeInTheDocument(); + await page.getByTestId("command-palette").getByText("Add project", { exact: true }).click(); + await expect.element(dialog).toBeInTheDocument(); + await expect.element(dialog.getByText("Environments", { exact: true })).toBeInTheDocument(); await expect - .element(palette.getByText("This device", { exact: true }).first()) + .element(dialog.getByText("This device", { exact: true }).first()) .toBeInTheDocument(); await clickCommandPaletteAction("Staging"); await selectLocalFolderAction(); @@ -557,10 +589,8 @@ describe("ChatView (full app): add project", () => { }, { timeout: 8_000, interval: 16 }, ); - await expect.element(palette.getByText("codething", { exact: true })).toBeInTheDocument(); - await expect - .element(palette.getByRole("button", { name: "Add (Enter)" })) - .toBeInTheDocument(); + await expect.element(dialog.getByText("codething", { exact: true })).toBeInTheDocument(); + await expect.element(dialog.getByRole("button", { name: "Add (Enter)" })).toBeInTheDocument(); await dispatchInputKey(browseInput, { key: "Enter" }); @@ -630,16 +660,16 @@ describe("ChatView (full app): add project", () => { await page.getByTestId("sidebar-add-project-trigger").click(); - const palette = page.getByTestId("command-palette"); - await expect.element(palette).toBeInTheDocument(); + const dialog = page.getByTestId("add-project-dialog"); + await expect.element(dialog).toBeInTheDocument(); await selectLocalFolderAction(); - const browseInput = palette.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER); + const browseInput = dialog.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER); await browseInput.fill("~/Applications/access"); // Named after the primary computer, which the harness makes a Mac // whatever runs the test. const fileManagerLabel = "Open in Finder"; - await palette.getByRole("button", { name: fileManagerLabel }).click(); + await dialog.getByRole("button", { name: fileManagerLabel }).click(); await vi.waitFor( () => { @@ -743,16 +773,15 @@ describe("ChatView (full app): add project", () => { try { await waitForServerConfigToApply(); await waitForCommandPaletteShortcutLabel(); - const palette = page.getByTestId("command-palette"); + const dialog = page.getByTestId("add-project-dialog"); await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); + await page.getByTestId("command-palette").getByText("Add project", { exact: true }).click(); + await expect.element(dialog).toBeInTheDocument(); await selectLocalFolderAction(); const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/"); - await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument(); + await expect.element(dialog.getByText("alpha", { exact: true })).toBeInTheDocument(); await dispatchInputKey(browseInput, { key: "ArrowDown" }); @@ -767,7 +796,7 @@ describe("ChatView (full app): add project", () => { { timeout: 8_000, interval: 16 }, ); await expect - .element(palette.getByRole("button", { name: addButtonLabel })) + .element(dialog.getByRole("button", { name: addButtonLabel })) .toBeInTheDocument(); await dispatchInputKey(browseInput, { @@ -811,6 +840,269 @@ describe("ChatView (full app): add project", () => { } }); + it("adds a project from browse mode with Enter when no directory is highlighted", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-command-palette-add-project-enter" as MessageId, + targetText: "command palette add project enter", + }), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + keybindings: [ + { + command: "commandPalette.toggle", + shortcut: { + key: "k", + metaKey: false, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: true, + }, + whenAst: { + type: "not", + node: { type: "identifier", name: "terminalFocus" }, + }, + }, + ], + }; + }, + resolveRpc: (body) => { + if (body._tag === WS_METHODS.filesystemBrowse) { + if (body.partialPath === "~/Development/") { + return { + parentPath: "~/Development/", + entries: [ + { name: "alpha", fullPath: "~/Development/alpha" }, + { name: "beta", fullPath: "~/Development/beta" }, + ], + }; + } + + return { + parentPath: "~/", + entries: [{ name: "Development", fullPath: "~/Development" }], + }; + } + + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return { + sequence: fixture.snapshot.snapshotSequence + 1, + }; + } + + return undefined; + }, + }); + + try { + await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]); + const dialog = page.getByTestId("add-project-dialog"); + await openCommandPaletteFromTrigger(); + await page.getByTestId("command-palette").getByText("Add project", { exact: true }).click(); + await expect.element(dialog).toBeInTheDocument(); + await selectLocalFolderAction(); + + const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); + await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/"); + await expect.element(dialog.getByText("alpha", { exact: true })).toBeInTheDocument(); + + await expect.element(dialog.getByRole("button", { name: "Add (Enter)" })).toBeInTheDocument(); + + await dispatchInputKey(browseInput, { key: "Enter" }); + + await vi.waitFor( + () => { + const dispatchRequest = wsRequests.find( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "project.create", + ) as + | { + _tag: string; + type?: string; + workspaceRoot?: string; + title?: string; + } + | undefined; + + expect(dispatchRequest).toMatchObject({ + _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, + type: "project.create", + workspaceRoot: "~/Development", + title: "Development", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + + await waitForURL( + mounted.router, + (path) => UUID_ROUTE_RE.test(path), + "Route should have changed to a new draft thread after adding a project with Enter.", + ); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps shortcuts from acting behind Add project and returns focus to the sidebar button", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-add-project-shortcut-block" as MessageId, + targetText: "add project shortcut block", + }), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + keybindings: [CHAT_NEW_BINDING, PALETTE_TOGGLE_BINDING], + }; + }, + resolveRpc: (body) => { + if (body._tag === WS_METHODS.filesystemBrowse) { + return { parentPath: "~/", entries: [] }; + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + const trigger = page.getByTestId("sidebar-add-project-trigger"); + await trigger.click(); + const dialog = page.getByTestId("add-project-dialog"); + await expect.element(dialog).toBeInTheDocument(); + await selectLocalFolderAction(); + const pathBefore = mounted.router.state.location.pathname; + + // New thread and the palette's own shortcut, pressed mid-browse. + dispatchChatNewShortcut(); + dispatchModShortcut("k"); + await waitForLayout(); + await waitForLayout(); + + expect(mounted.router.state.location.pathname).toBe(pathBefore); + expect(document.querySelector('[data-testid="command-palette"]')).toBeNull(); + await expect.element(dialog).toBeInTheDocument(); + + await userEvent.keyboard("{Escape}"); + await expect.element(dialog).not.toBeInTheDocument(); + await vi.waitFor(() => { + expect(document.activeElement).toBe(trigger.element()); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("offers Add project for a typed path above the search results, and returns focus to the composer", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-add-project-path-row" as MessageId, + targetText: "add project path row", + }), + resolveRpc: (body) => { + if (body._tag === WS_METHODS.filesystemBrowse) { + return { + parentPath: "/repo/", + entries: [{ name: "project", fullPath: "/repo/project" }], + }; + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + const palette = page.getByTestId("command-palette"); + await page + .getByPlaceholder("Search commands, projects, and threads...") + .fill("/repo/project"); + + const pathRow = palette.getByText("Add project at /repo/project", { exact: true }); + await expect.element(pathRow).toBeInTheDocument(); + // The search carries on underneath: the project in that folder is listed. + await expect.element(palette.getByText("Projects", { exact: true })).toBeInTheDocument(); + expect(wsRequests.some((request) => request._tag === WS_METHODS.filesystemBrowse)).toBe( + false, + ); + + await pathRow.click(); + const dialog = page.getByTestId("add-project-dialog"); + await expect.element(dialog).toBeInTheDocument(); + const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); + await expect.element(browseInput).toHaveValue("/repo/project"); + expect(document.querySelector('[data-testid="command-palette"]')).toBeNull(); + + await userEvent.keyboard("{Escape}"); + await expect.element(dialog).not.toBeInTheDocument(); + await vi.waitFor(() => { + const composer = document.querySelector('[contenteditable="true"]'); + expect(composer?.contains(document.activeElement)).toBe(true); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("resolves a relative path against the open project's folder", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-add-project-relative-path" as MessageId, + targetText: "add project relative path", + }), + resolveRpc: (body) => { + if (body._tag === WS_METHODS.filesystemBrowse) { + return { parentPath: "/repo/project/", entries: [] }; + } + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return { sequence: fixture.snapshot.snapshotSequence + 1 }; + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + const palette = page.getByTestId("command-palette"); + await page.getByPlaceholder("Search commands, projects, and threads...").fill("./fresh"); + await palette.getByText("Add project at ./fresh", { exact: true }).click(); + + const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); + await vi.waitFor( + () => { + expect( + wsRequests.find((request) => request._tag === WS_METHODS.filesystemBrowse), + ).toMatchObject({ partialPath: "./", cwd: "/repo/project" }); + }, + { timeout: 8_000, interval: 16 }, + ); + await dispatchInputKey(browseInput, { key: "Enter" }); + + await vi.waitFor( + () => { + expect( + wsRequests.find( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "project.create", + ), + ).toMatchObject({ workspaceRoot: "/repo/project/fresh", title: "fresh" }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("keeps project-context thread matches available when searching by project name", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, diff --git a/apps/web/src/components/ChatView.browser-harness.tsx b/apps/web/src/components/ChatView.browser-harness.tsx index 1a3ce7310..8b2d07121 100644 --- a/apps/web/src/components/ChatView.browser-harness.tsx +++ b/apps/web/src/components/ChatView.browser-harness.tsx @@ -63,6 +63,8 @@ import { afterAll, afterEach, beforeAll, beforeEach, expect, vi } from "vite-plu import { render } from "vitest-browser-react"; import { useCommandPaletteStore } from "../commandPaletteStore"; +import { useAddProjectStore } from "./addProject/addProjectStore"; +import { useCodexImportStore } from "./codexImport/codexImportStore"; import { __resetComputerLinksForTests, type ComputerLinksClient, @@ -3139,9 +3141,12 @@ export async function waitForCommandPaletteInput(placeholder: string): Promise { await waitForElement(() => { - const palette = document.querySelector('[data-testid="command-palette"]'); + const palette = document.querySelector( + '[data-testid="command-palette"], [data-testid="add-project-dialog"], [data-testid="codex-import-dialog"]', + ); if (!palette) return null; const candidates = Array.from( palette.querySelectorAll('[data-slot="command-item"]'), @@ -3469,6 +3474,8 @@ export function registerChatViewSuiteHooks(): void { open: false, openIntent: null, }); + useAddProjectStore.setState({ session: null }); + useCodexImportStore.setState({ session: null }); useStore.setState({ activeEnvironmentId: null, environmentStateById: {}, diff --git a/apps/web/src/components/ChatView.codex-import.browser.tsx b/apps/web/src/components/ChatView.codex-import.browser.tsx new file mode 100644 index 000000000..00479db5f --- /dev/null +++ b/apps/web/src/components/ChatView.codex-import.browser.tsx @@ -0,0 +1,245 @@ +import { MessageId, ProviderInstanceId, type ThreadId, WS_METHODS } from "@threadlines/contracts"; +import { createModelCapabilities } from "@threadlines/shared/model"; +import { page } from "vite-plus/test/browser"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { + PROJECT_ID, + DEFAULT_VIEWPORT, + createSnapshotForTargetUser, + dispatchInputKey, + mountChatView, + openCommandPaletteFromTrigger, + registerChatViewSuiteHooks, + waitForCommandPaletteInput, + waitForServerConfigToApply, + wsRequests, +} from "./ChatView.browser-harness"; + +vi.mock("../lib/gitStatusState", () => ({ + // Read synchronously by the draft seeder to skip a checkout already known + // to be missing; these suites never exercise a deleted checkout. + getGitStatusSnapshot: () => ({ data: null, error: null, cause: null, isPending: false }), + GIT_STATUS_STALE_MESSAGE: "Source control status isn't updating.", + useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }), + useGitStatuses: () => new Map(), + rebuildGitStatusSubscription: () => undefined, + refreshGitStatus: () => Promise.resolve(null), + refreshLocalGitStatus: () => Promise.resolve(null), + resetGitStatusStateForTests: () => undefined, +})); + +describe("ChatView (full app): bring in a Codex conversation", () => { + registerChatViewSuiteHooks(); + + it("opens a project-scoped Codex session browser and imports the selected conversation", async () => { + const externalThreadsResult = { + data: [ + { + providerInstanceId: ProviderInstanceId.make("codex"), + providerThreadId: "native-codex-thread", + sessionId: "native-codex-session", + source: "cli" as const, + name: "Finish parser migration", + preview: "Finish the parser migration and verify its tests", + cwd: "/repo/project", + cliVersion: "0.145.0", + createdAt: "2026-03-01T12:00:00.000Z", + updatedAt: "2026-03-03T12:00:00.000Z", + status: "idle" as const, + canImport: true, + }, + ], + }; + let resolveExternalThreads!: (value: typeof externalThreadsResult) => void; + const externalThreadsPromise = new Promise((resolve) => { + resolveExternalThreads = resolve; + }); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-external-codex-session" as MessageId, + targetText: "external Codex session", + }), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + providers: [ + { + ...nextFixture.serverConfig.providers[0]!, + models: [ + { + slug: "gpt-5.6-sol", + name: "GPT-5.6 Sol", + isCustom: false, + isDefault: true, + capabilities: createModelCapabilities({ optionDescriptors: [] }), + }, + ], + }, + ], + }; + }, + resolveRpc: (body) => { + if (body._tag === WS_METHODS.serverListExternalProviderThreads) { + return externalThreadsPromise; + } + if (body._tag === WS_METHODS.serverImportExternalProviderThread) { + return { + threadId: (body as unknown as { readonly threadId: ThreadId }).threadId, + importedMessageCount: 2, + }; + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + const palette = page.getByTestId("command-palette"); + await expect + .element(palette.getByText("Bring in Codex conversation…", { exact: true })) + .toBeInTheDocument(); + await palette.getByText("Bring in Codex conversation…", { exact: true }).click(); + await waitForCommandPaletteInput("Search other Codex conversations in Project..."); + const dialog = page.getByTestId("codex-import-dialog"); + + await expect + .element(dialog.getByTestId("command-palette-results-skeleton")) + .toBeInTheDocument(); + resolveExternalThreads(externalThreadsResult); + + await expect + .element(dialog.getByText("Finish parser migration", { exact: true })) + .toBeInTheDocument(); + await expect + .element(dialog.getByTestId("command-palette-results-skeleton")) + .not.toBeInTheDocument(); + await expect + .element(dialog.getByText("Codex CLI · Finish the parser migration and verify its tests")) + .toBeInTheDocument(); + const requestedPaths: string[] = []; + const stopRecording = mounted.router.subscribe("onBeforeNavigate", (event) => { + requestedPaths.push(event.toLocation.pathname); + }); + await dialog.getByText("Finish parser migration", { exact: true }).click(); + + await vi.waitFor( + () => { + const listRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.serverListExternalProviderThreads, + ); + expect(listRequest).toMatchObject({ + providerInstanceId: "codex", + cwd: "/repo/project", + limit: 20, + }); + const importRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.serverImportExternalProviderThread, + ); + expect(importRequest).toMatchObject({ + providerInstanceId: "codex", + providerThreadId: "native-codex-thread", + projectId: PROJECT_ID, + modelSelection: { instanceId: "codex", model: "gpt-5.6-sol" }, + runtimeMode: "full-access", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + + // The session that started the import is still open, so it closes and + // asks for the new thread. + const importedThreadId = ( + wsRequests.find( + (request) => request._tag === WS_METHODS.serverImportExternalProviderThread, + ) as unknown as { readonly threadId: ThreadId } + ).threadId; + await expect.element(dialog).not.toBeInTheDocument(); + await vi.waitFor( + () => { + expect(requestedPaths.some((path) => path.endsWith(`/${importedThreadId}`))).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); + stopRecording(); + } finally { + await mounted.cleanup(); + } + }); + + it("asks which Codex account first when there are two, and goes back to the choice", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-codex-import-two-accounts" as MessageId, + targetText: "codex import two accounts", + }), + configureFixture: (nextFixture) => { + const codex = { + ...nextFixture.serverConfig.providers[0]!, + models: [ + { + slug: "gpt-5.6-sol", + name: "GPT-5.6 Sol", + isCustom: false, + isDefault: true, + capabilities: createModelCapabilities({ optionDescriptors: [] }), + }, + ], + }; + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + providers: [ + { ...codex, displayName: "Codex Personal" }, + { + ...codex, + instanceId: ProviderInstanceId.make("codex-work"), + displayName: "Codex Work", + }, + ], + }; + }, + resolveRpc: (body) => { + if (body._tag === WS_METHODS.serverListExternalProviderThreads) { + return { data: [] }; + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + await page + .getByTestId("command-palette") + .getByText("Bring in Codex conversation…", { exact: true }) + .click(); + const dialog = page.getByTestId("codex-import-dialog"); + await waitForCommandPaletteInput("Choose a Codex account..."); + await expect.element(dialog.getByText("Codex Personal", { exact: true })).toBeInTheDocument(); + await dialog.getByText("Codex Work", { exact: true }).click(); + + await waitForCommandPaletteInput("Search other Codex conversations in Project..."); + await vi.waitFor( + () => { + expect( + wsRequests.find( + (request) => request._tag === WS_METHODS.serverListExternalProviderThreads, + ), + ).toMatchObject({ providerInstanceId: "codex-work", cwd: "/repo/project" }); + }, + { timeout: 8_000, interval: 16 }, + ); + + const searchInput = await waitForCommandPaletteInput( + "Search other Codex conversations in Project...", + ); + await dispatchInputKey(searchInput, { key: "Backspace" }); + await waitForCommandPaletteInput("Choose a Codex account..."); + } finally { + await mounted.cleanup(); + } + }); +}); diff --git a/apps/web/src/components/ChatView.palette.browser.tsx b/apps/web/src/components/ChatView.palette.browser.tsx index 77cceeb2e..54bbe125f 100644 --- a/apps/web/src/components/ChatView.palette.browser.tsx +++ b/apps/web/src/components/ChatView.palette.browser.tsx @@ -5,11 +5,9 @@ import { OutsideAgentConnectionId, OutsideAgentRequestId, type OutsideAgentsSnapshot, - ProviderInstanceId, type ThreadId, WS_METHODS, } from "@threadlines/contracts"; -import { createModelCapabilities } from "@threadlines/shared/model"; import { page } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -22,8 +20,6 @@ import { SECOND_PROJECT_ID, LOCAL_ENVIRONMENT_ID, UUID_ROUTE_RE, - ADD_PROJECT_SUBMENU_PLACEHOLDER, - fixture, wsRequests, DEFAULT_VIEWPORT, createSnapshotForTargetUser, @@ -43,9 +39,6 @@ import { triggerChatNewShortcutUntilPath, openCommandPaletteFromTrigger, waitForCommandPaletteShortcutLabel, - waitForCommandPaletteInput, - selectLocalFolderAction, - dispatchInputKey, mountChatView, registerChatViewSuiteHooks, rpcHarness, @@ -329,122 +322,6 @@ describe("ChatView (full app): command palette and search", () => { } }); - it("opens a project-scoped Codex session browser and imports the selected conversation", async () => { - const externalThreadsResult = { - data: [ - { - providerInstanceId: ProviderInstanceId.make("codex"), - providerThreadId: "native-codex-thread", - sessionId: "native-codex-session", - source: "cli" as const, - name: "Finish parser migration", - preview: "Finish the parser migration and verify its tests", - cwd: "/repo/project", - cliVersion: "0.145.0", - createdAt: "2026-03-01T12:00:00.000Z", - updatedAt: "2026-03-03T12:00:00.000Z", - status: "idle" as const, - canImport: true, - }, - ], - }; - let resolveExternalThreads!: (value: typeof externalThreadsResult) => void; - const externalThreadsPromise = new Promise((resolve) => { - resolveExternalThreads = resolve; - }); - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-external-codex-session" as MessageId, - targetText: "external Codex session", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - providers: [ - { - ...nextFixture.serverConfig.providers[0]!, - models: [ - { - slug: "gpt-5.6-sol", - name: "GPT-5.6 Sol", - isCustom: false, - isDefault: true, - capabilities: createModelCapabilities({ optionDescriptors: [] }), - }, - ], - }, - ], - }; - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.serverListExternalProviderThreads) { - return externalThreadsPromise; - } - if (body._tag === WS_METHODS.serverImportExternalProviderThread) { - return { - threadId: (body as unknown as { readonly threadId: ThreadId }).threadId, - importedMessageCount: 2, - }; - } - return undefined; - }, - }); - - try { - await waitForServerConfigToApply(); - await openCommandPaletteFromTrigger(); - const palette = page.getByTestId("command-palette"); - await expect - .element(palette.getByText("Bring in Codex conversation…", { exact: true })) - .toBeInTheDocument(); - await palette.getByText("Bring in Codex conversation…", { exact: true }).click(); - await waitForCommandPaletteInput("Search other Codex conversations in Project..."); - - await expect - .element(palette.getByTestId("command-palette-results-skeleton")) - .toBeInTheDocument(); - resolveExternalThreads(externalThreadsResult); - - await expect - .element(palette.getByText("Finish parser migration", { exact: true })) - .toBeInTheDocument(); - await expect - .element(palette.getByTestId("command-palette-results-skeleton")) - .not.toBeInTheDocument(); - await expect - .element(palette.getByText("Codex CLI · Finish the parser migration and verify its tests")) - .toBeInTheDocument(); - await palette.getByText("Finish parser migration", { exact: true }).click(); - - await vi.waitFor( - () => { - const listRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.serverListExternalProviderThreads, - ); - expect(listRequest).toMatchObject({ - providerInstanceId: "codex", - cwd: "/repo/project", - limit: 20, - }); - const importRequest = wsRequests.find( - (request) => request._tag === WS_METHODS.serverImportExternalProviderThread, - ); - expect(importRequest).toMatchObject({ - providerInstanceId: "codex", - providerThreadId: "native-codex-thread", - projectId: PROJECT_ID, - modelSelection: { instanceId: "codex", model: "gpt-5.6-sol" }, - runtimeMode: "full-access", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - } finally { - await mounted.cleanup(); - } - }); - it("highlights quoted phrase matches in titles and messages and jumps to the message", async () => { const matchedThreadTitle = "Release codename deltafrogs thread"; const searchQuery = `"release codename"`; @@ -851,117 +728,6 @@ describe("ChatView (full app): command palette and search", () => { } }); - it("adds a project from browse mode with Enter when no directory is highlighted", async () => { - const mounted = await mountChatView({ - viewport: DEFAULT_VIEWPORT, - snapshot: createSnapshotForTargetUser({ - targetMessageId: "msg-user-command-palette-add-project-enter" as MessageId, - targetText: "command palette add project enter", - }), - configureFixture: (nextFixture) => { - nextFixture.serverConfig = { - ...nextFixture.serverConfig, - keybindings: [ - { - command: "commandPalette.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - whenAst: { - type: "not", - node: { type: "identifier", name: "terminalFocus" }, - }, - }, - ], - }; - }, - resolveRpc: (body) => { - if (body._tag === WS_METHODS.filesystemBrowse) { - if (body.partialPath === "~/Development/") { - return { - parentPath: "~/Development/", - entries: [ - { name: "alpha", fullPath: "~/Development/alpha" }, - { name: "beta", fullPath: "~/Development/beta" }, - ], - }; - } - - return { - parentPath: "~/", - entries: [{ name: "Development", fullPath: "~/Development" }], - }; - } - - if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { - return { - sequence: fixture.snapshot.snapshotSequence + 1, - }; - } - - return undefined; - }, - }); - - try { - await Promise.all([waitForServerConfigToApply(), waitForCommandPaletteShortcutLabel()]); - const palette = page.getByTestId("command-palette"); - await openCommandPaletteFromTrigger(); - - await expect.element(palette).toBeInTheDocument(); - await palette.getByText("Add project", { exact: true }).click(); - await selectLocalFolderAction(); - - const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); - await page.getByPlaceholder(ADD_PROJECT_SUBMENU_PLACEHOLDER).fill("~/Development/"); - await expect.element(palette.getByText("alpha", { exact: true })).toBeInTheDocument(); - - await expect - .element(palette.getByRole("button", { name: "Add (Enter)" })) - .toBeInTheDocument(); - - await dispatchInputKey(browseInput, { key: "Enter" }); - - await vi.waitFor( - () => { - const dispatchRequest = wsRequests.find( - (request) => - request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "project.create", - ) as - | { - _tag: string; - type?: string; - workspaceRoot?: string; - title?: string; - } - | undefined; - - expect(dispatchRequest).toMatchObject({ - _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, - type: "project.create", - workspaceRoot: "~/Development", - title: "Development", - }); - }, - { timeout: 8_000, interval: 16 }, - ); - - await waitForURL( - mounted.router, - (path) => UUID_ROUTE_RE.test(path), - "Route should have changed to a new draft thread after adding a project with Enter.", - ); - } finally { - await mounted.cleanup(); - } - }); - it("searches projects by path and opens the latest thread for that project", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 3e1b39f7a..1af8b29d2 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -178,7 +178,7 @@ import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; import { useIsMobile, useMediaQuery } from "../hooks/useMediaQuery"; import { useKept, useStableHandlers } from "../hooks/useStableIdentity"; import { useNewThreadHandler } from "../hooks/useHandleNewThread"; -import { useCommandPaletteStore } from "../commandPaletteStore"; +import { isKeyboardOwnedByDialog } from "../commands/shortcutBlock"; import { useChatFindStore } from "../chatFindStore"; import { installFindRegionTracking, resolveFindShortcutOwner } from "../lib/findShortcutOwner"; import { selectedChatText } from "./chat/chatFind/ChatFind"; @@ -4997,7 +4997,7 @@ export default function ChatView(props: ChatViewProps) { useEffect(() => { const handler = (event: globalThis.KeyboardEvent) => { - if (!activeThreadId || useCommandPaletteStore.getState().open || event.defaultPrevented) { + if (!activeThreadId || isKeyboardOwnedByDialog() || event.defaultPrevented) { return; } const shortcutContext = { diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index 3f60a9486..c46a175e5 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -11,7 +11,6 @@ import { applyThreadContentSearchMatches, buildThreadActionItems, filterCommandPaletteGroups, - resolveAddProjectUnavailableGuidance, type CommandPaletteGroup, } from "./CommandPalette.logic"; @@ -358,22 +357,3 @@ describe("buildThreadActionItems", () => { ]); }); }); - -describe("resolveAddProjectUnavailableGuidance", () => { - it("routes an unpaired hosted visitor to Devices instead of reporting a failure", () => { - const guidance = resolveAddProjectUnavailableGuidance({ isHostedStatic: true }); - - expect(guidance.type).toBe("warning"); - expect(guidance.title).toBe("Pair a computer to add projects"); - expect(guidance.action).toEqual({ label: "Open Connections", to: "/settings/connections" }); - }); - - it("keeps the plain error for a desktop session that really has no environment", () => { - expect(resolveAddProjectUnavailableGuidance({ isHostedStatic: false })).toEqual({ - type: "error", - title: "Can't browse projects", - description: "No computer is available.", - action: null, - }); - }); -}); diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 2a20c745b..d6d33e122 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -1,9 +1,4 @@ -import { - type EnvironmentId, - type KeybindingCommand, - type FilesystemBrowseEntry, - type MessageId, -} from "@threadlines/contracts"; +import { type EnvironmentId, type KeybindingCommand, type MessageId } from "@threadlines/contracts"; import { scopedThreadKey, scopeThreadRef } from "@threadlines/client-runtime"; import { analyzeSearchText, @@ -12,10 +7,6 @@ import { } from "@threadlines/shared/searchRanking"; import { type ReactNode } from "react"; import { sortThreads } from "../lib/threadSort"; -import { - CONNECTIONS_SETTINGS_SECTION_PATH, - type SettingsSectionPath, -} from "./settings/settingsPaths"; import { type Project, type SidebarThreadSummary, type Thread } from "../types"; export const RECENT_THREAD_LIMIT = 12; @@ -44,6 +35,8 @@ export interface CommandPaletteItem { export interface CommandPaletteActionItem extends CommandPaletteItem { readonly kind: "action"; readonly keepOpen?: boolean; + /** Closes the palette and opens another dialog, which then owns where focus returns. */ + readonly opensDialog?: boolean; readonly run: () => Promise; } @@ -71,40 +64,6 @@ export interface CommandPaletteView { >; } -export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse"; - -export function filterBrowseEntries(input: { - browseEntries: ReadonlyArray; - browseFilterQuery: string; - highlightedItemValue: string | null; -}): { - filteredEntries: FilesystemBrowseEntry[]; - highlightedEntry: FilesystemBrowseEntry | null; - exactEntry: FilesystemBrowseEntry | null; -} { - const lowerFilter = input.browseFilterQuery.toLowerCase(); - const showHidden = input.browseFilterQuery.startsWith("."); - - const filteredEntries = input.browseEntries.filter( - (entry) => - entry.name.toLowerCase().startsWith(lowerFilter) && - (showHidden || !entry.name.startsWith(".")), - ); - - let highlightedEntry: FilesystemBrowseEntry | null = null; - if (input.highlightedItemValue?.startsWith("browse:")) { - const highlightedPath = input.highlightedItemValue.slice("browse:".length); - highlightedEntry = filteredEntries.find((entry) => entry.fullPath === highlightedPath) ?? null; - } - - const exactEntry = - input.browseFilterQuery.length > 0 - ? (filteredEntries.find((entry) => entry.name === input.browseFilterQuery) ?? null) - : null; - - return { filteredEntries, highlightedEntry, exactEntry }; -} - export function normalizeSearchText(value: string): string { return value.trim().toLowerCase().replace(/\s+/g, " "); } @@ -373,58 +332,6 @@ export function filterCommandPaletteGroups(input: { }); } -export function buildBrowseGroups(input: { - browseEntries: ReadonlyArray; - browseQuery: string; - canBrowseUp: boolean; - upIcon: ReactNode; - directoryIcon: ReactNode; - browseUp: () => void; - browseTo: (name: string) => void; -}): CommandPaletteGroup[] { - const items: CommandPaletteActionItem[] = []; - - if (input.canBrowseUp) { - items.push({ - kind: "action", - value: "browse:up", - searchTerms: [input.browseQuery, ".."], - title: "..", - icon: input.upIcon, - keepOpen: true, - run: async () => { - input.browseUp(); - }, - }); - } - - for (const entry of input.browseEntries) { - items.push({ - kind: "action", - value: `browse:${entry.fullPath}`, - searchTerms: [input.browseQuery, entry.fullPath, entry.name], - title: entry.name, - icon: input.directoryIcon, - keepOpen: true, - run: async () => { - input.browseTo(entry.name); - }, - }); - } - - return [{ value: "directories", label: "Directories", items }]; -} - -export function getCommandPaletteMode(input: { - currentView: CommandPaletteView | null; - isBrowsing: boolean; -}): CommandPaletteMode { - if (input.currentView) { - return input.isBrowsing ? "submenu-browse" : "submenu"; - } - return input.isBrowsing ? "root-browse" : "root"; -} - export function buildRootGroups(input: { actionItems: ReadonlyArray; recentThreadItems: ReadonlyArray; @@ -443,48 +350,6 @@ export function buildRootGroups(input: { return groups; } -export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string { - switch (mode) { - case "root": - return "Search commands, projects, and threads..."; - case "root-browse": - return "Enter project path (e.g. ~/projects/my-app)"; - case "submenu": - return "Search..."; - case "submenu-browse": - return "Enter path (e.g. ~/projects/my-app)"; - } -} - -/** - * Copy for the add-project action when there is no environment to browse. - * - * In the hosted browser that state is not a failure, it is the setup step the - * visitor has not done yet: projects live on the paired computer, so there is - * nothing to browse until one exists. Say that and point at pairing instead of - * reporting a bare "no environment" error. A desktop session that somehow has - * no environment is a real fault, so it keeps the error wording. - */ -export function resolveAddProjectUnavailableGuidance(input: { readonly isHostedStatic: boolean }): { - readonly type: "error" | "warning"; - readonly title: string; - readonly description: string; - readonly action: { readonly label: string; readonly to: SettingsSectionPath } | null; -} { - if (!input.isHostedStatic) { - return { - type: "error", - title: "Can't browse projects", - description: "No computer is available.", - action: null, - }; - } - - return { - type: "warning", - title: "Pair a computer to add projects", - description: - "Threadlines browses projects on the computer running the desktop app. Pair one from Connections, then add a project.", - action: { label: "Open Connections", to: CONNECTIONS_SETTINGS_SECTION_PATH }, - }; +export function getCommandPaletteInputPlaceholder(isSubmenu: boolean): string { + return isSubmenu ? "Search..." : "Search commands, projects, and threads..."; } diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index dbfeb1a4e..9dd5f65fb 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -4,6 +4,7 @@ import { useParams } from "@tanstack/react-router"; import { lazy, Suspense, useEffect, useRef, type ReactNode } from "react"; import { useCommandPaletteStore } from "../commandPaletteStore"; +import { isPaletteLaunchedDialogOpen } from "../commands/shortcutBlock"; import { ComposerHandleContext } from "../composerHandleContext"; import { resolveShortcutCommand } from "../keybindings"; import { isTerminalFocused } from "../lib/terminalFocus"; @@ -11,6 +12,8 @@ import { useServerKeybindings } from "../rpc/serverState"; import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; import { resolveThreadRouteTarget } from "../threadRoutes"; import type { ChatComposerHandle } from "./chat/ChatComposer"; +import { AddProjectDialog } from "./addProject/AddProjectDialog"; +import { CodexSessionImportDialog } from "./codexImport/CodexSessionImportDialog"; import { CommandDialog } from "./ui/command"; const loadCommandPaletteDialog = () => import("./CommandPaletteDialog"); @@ -59,6 +62,8 @@ export function CommandPalette({ children }: { children: ReactNode }) { } event.preventDefault(); event.stopPropagation(); + // Never over Add project or a Codex import: they own the keyboard. + if (isPaletteLaunchedDialogOpen()) return; toggleOpen(); }; window.addEventListener("keydown", onKeyDown); @@ -84,6 +89,10 @@ export function CommandPalette({ children }: { children: ReactNode }) { {children} + {/* Siblings, not children, of the palette's dialog: the palette hands + over to them and closes, so they must not count as nested in it. */} + + ); } diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index 41d076a1e..5b30d4e51 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -12,20 +12,13 @@ import { resolveThreadWorkingCwd } from "@threadlines/shared/threadCwd"; import { DEFAULT_NEW_THREAD_RUNTIME_MODE, type EnvironmentId, - type FilesystemBrowseResult, type KeybindingCommand, - type ProviderExternalThreadCandidate, - type ProviderInstanceId, type ProjectId, - type SourceControlDiscoveryResult, - type SourceControlProviderKind, - type SourceControlRepositoryInfo, } from "@threadlines/contracts"; -import { deriveRepositoryDirectoryName, normalizeGitRemoteUrl } from "@threadlines/shared/git"; -import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"; + +import { useQuery } from "@tanstack/react-query"; import { useDebouncedValue } from "@tanstack/react-pacer"; import { useLocation, useNavigate } from "@tanstack/react-router"; -import * as Option from "effect/Option"; import { ArrowDownIcon, ArrowLeftIcon, @@ -35,16 +28,13 @@ import { CloudIcon, CircleArrowUpIcon, MessageCircleWarningIcon, - CornerLeftUpIcon, EraserIcon, FileTextIcon, - FolderIcon, FolderGitIcon, FolderPlusIcon, GitPullRequestIcon, HomeIcon, LaptopIcon, - LinkIcon, MessageSquareIcon, MessageCirclePlusIcon, MessagesSquareIcon, @@ -82,25 +72,28 @@ import { useEffect, useLayoutEffect, useMemo, + useRef, useState, type KeyboardEvent, type ReactNode, } from "react"; import { useShallow } from "zustand/react/shallow"; import { useCommandPaletteStore } from "../commandPaletteStore"; +import { openAddProject } from "./addProject/addProjectStore"; +import { + useAddProjectEnvironmentOptions, + useEnvironmentBrowsePlatform, +} from "./addProject/addProjectComputers"; +import { openCodexImport } from "./codexImport/codexImportStore"; import { useRoomRecipientStore } from "../rooms"; import { useChatFindStore } from "../chatFindStore"; import { useComposerCommandsStore } from "../composerCommands"; import { type TerminalCommandKind, useTerminalCommandsStore } from "../terminalCommands"; import { derivePendingApprovals } from "../session-logic"; -import { readEnvironmentApi } from "../environmentApi"; -import { readPrimaryEnvironmentDescriptor, usePrimaryEnvironmentId } from "../environments/primary"; + +import { usePrimaryEnvironmentId } from "../environments/primary"; import { openComputerRenameDialog, useComputerNaming } from "./DeviceRenameDialog"; -import { - useSavedEnvironmentRegistryStore, - useSavedEnvironmentRuntimeStore, - requireEnvironmentConnection, -} from "../environments/runtime"; +import { useSavedEnvironmentRuntimeStore } from "../environments/runtime"; import { holdThreadDetailForOpen, prewarmHighlightedThread } from "../environments/runtime/service"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { useGeneralChats } from "./chats/useGeneralChats"; @@ -120,34 +113,15 @@ import { useSettings } from "../hooks/useSettings"; import { selectSidebarListShown, useUiStateStore } from "../uiStateStore"; import { useWorktreePickupStore } from "../worktreePickup"; import { useRoomsEnabled } from "../hooks/useRoomsEnabled"; -import { readLocalApi } from "../localApi"; + import { closeRightPanelSearchParams } from "../diffRouteSearch"; -import { - getSourceControlDiscoverySnapshot, - refreshSourceControlDiscovery, -} from "../lib/sourceControlDiscoveryState"; + import { startNewThreadInProjectFromContext, startNewThreadFromContext, } from "../lib/chatThreadActions"; -import { - appendBrowsePathSegment, - canNavigateUp, - ensureBrowseDirectoryPath, - findProjectByPath, - getBrowseDirectoryPath, - getBrowseLeafPathSegment, - getBrowseParentPath, - hasTrailingPathSeparator, - inferProjectTitleFromPath, - isExplicitRelativeProjectPath, - isFilesystemBrowseQuery, - isUnsupportedWindowsProjectPath, - resolveCloneDestinationPathForDispatch, - resolveProjectPathForDispatch, -} from "../lib/projectPaths"; -import { waitForProjectInStore } from "../lib/waitForProject"; -import { gitCloneRepositoryMutationOptions, runGitMutation } from "../lib/gitReactQuery"; +import { isFilesystemBrowseQuery } from "../lib/projectPaths"; + import { getLatestThreadForProject } from "../lib/threadSort"; import { threadSearchQueryOptions, type ThreadSearchTarget } from "../lib/threadSearchReactQuery"; import { @@ -163,7 +137,7 @@ import { pullRequestTabSearchParams, rightPanelTabSearchParams, } from "../rightPanelTabs"; -import { cn, isMacPlatform, newCommandId, newProjectId, newThreadId } from "../lib/utils"; +import { cn, newCommandId } from "../lib/utils"; import { selectProjectsAcrossEnvironments, selectSidebarThreadsAcrossEnvironments, @@ -174,27 +148,22 @@ import { buildThreadRouteParams } from "../threadRoutes"; import { ADDON_ICON_CLASS, applyThreadContentSearchMatches, - buildBrowseGroups, buildProjectActionItems, buildRootGroups, buildThreadActionItems, type CommandPaletteActionItem, type CommandPaletteSubmenuItem, type CommandPaletteView, - filterBrowseEntries, filterCommandPaletteGroups, getCommandPaletteInputPlaceholder, - getCommandPaletteMode, highlightedThreadKeyOf, ITEM_ICON_CLASS, normalizeSearchText, RECENT_THREAD_LIMIT, - resolveAddProjectUnavailableGuidance, } from "./CommandPalette.logic"; -import { isHostedStaticApp } from "../hostedPairing"; -import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic"; + import { CommandPaletteResults } from "./CommandPaletteResults"; -import { editorLabel } from "./EditorOpenOptions"; + import { openConnectComputerDialog } from "./settings/connections/JoinComputerDialog"; import { openThreadMoveDialog } from "./ThreadMoveDialog"; import { openProjectSetupDialog } from "./ProjectSetupDialog"; @@ -215,11 +184,11 @@ import { useOutsideAgentsSnapshot, } from "../environments/outsideAgents/outsideAgents"; import { threadMoveStatus } from "../threadMove"; -import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons"; + import { ProjectFavicon } from "./ProjectFavicon"; import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators"; import { useServerKeybindings, useServerProviders } from "../rpc/serverState"; -import { resolveAppModelSelectionForInstance } from "../modelSelection"; + import { deriveProviderInstanceEntries } from "../providerInstances"; import { Command, @@ -228,258 +197,16 @@ import { CommandInput, CommandPanel, } from "./ui/command"; -import { Button } from "./ui/button"; + import { Kbd, KbdGroup } from "./ui/kbd"; -import { failureNotice, stackedThreadToast, toastManager } from "./ui/toast"; -import { addComputerNotConnectedNotice } from "./computerConnectionNotices"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { failureNotice, toastManager } from "./ui/toast"; + import { useComposerHandleContext } from "../composerHandleContext"; -const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = []; -const BROWSE_STALE_TIME_MS = 30_000; -const GITHUB_REPOSITORY_LIST_LIMIT = 100; -const GITHUB_REPOSITORY_LIST_STALE_TIME_MS = 60_000; const THREAD_CONTENT_SEARCH_DEBOUNCE_MS = 180; -const EXTERNAL_SESSION_SEARCH_DEBOUNCE_MS = 180; const EMPTY_THREAD_CONTENT_MATCHES = [] as const; -interface CodexSessionBrowserFlow { - readonly environmentId: EnvironmentId; - readonly projectId: ProjectId; - readonly projectName: string; - readonly cwd: string; - readonly providerInstanceId: ProviderInstanceId; -} - const THEME_ITEM_CLASSES = { item: ITEM_ICON_CLASS, addon: ADDON_ICON_CLASS } as const; - -function externalSessionSourceLabel(source: ProviderExternalThreadCandidate["source"]): string { - switch (source) { - case "cli": - return "Codex CLI"; - case "vscode": - return "Codex app / IDE"; - case "exec": - return "Codex exec"; - case "appServer": - return "Codex app"; - case "unknown": - return "Codex"; - } -} - -function getEnvironmentBrowsePlatform(os: string | null | undefined): string { - if (os === "windows") { - return "Win32"; - } - if (os === "darwin") { - return "MacIntel"; - } - if (os === "linux") { - return "Linux"; - } - return typeof navigator === "undefined" ? "" : navigator.platform; -} - -interface AddProjectEnvironmentOption { - readonly environmentId: EnvironmentId; - readonly label: string; - readonly isPrimary: boolean; -} - -type AddProjectRemoteProviderKind = Extract< - SourceControlProviderKind, - "github" | "gitlab" | "bitbucket" | "azure-devops" ->; -type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url"; - -type AddProjectCloneFlow = - | { - readonly step: "repository"; - readonly environmentId: EnvironmentId; - readonly source: AddProjectRemoteSource; - } - | { - readonly step: "confirm"; - readonly environmentId: EnvironmentId; - readonly source: AddProjectRemoteSource; - readonly repositoryInput: string; - readonly repository: SourceControlRepositoryInfo | null; - readonly remoteUrl: string; - }; - -const REMOTE_PROJECT_SOURCES: ReadonlyArray = [ - "url", - "github", - "gitlab", - "bitbucket", - "azure-devops", -]; -const REMOTE_PROJECT_PROVIDER_SOURCES: ReadonlyArray = [ - "github", - "gitlab", - "bitbucket", - "azure-devops", -]; - -function remoteProjectSourceLabel(source: AddProjectRemoteSource): string { - switch (source) { - case "github": - return "GitHub"; - case "gitlab": - return "GitLab"; - case "bitbucket": - return "Bitbucket"; - case "azure-devops": - return "Azure DevOps"; - case "url": - return "Git URL"; - } -} - -function remoteProjectSourcePathHint(source: AddProjectRemoteSource): string { - switch (source) { - case "github": - return "owner/repo"; - case "gitlab": - return "group/project"; - case "bitbucket": - return "workspace/repository"; - case "azure-devops": - return "project/repository"; - case "url": - return "URL"; - } -} - -function remoteProjectSourceProvider( - source: AddProjectRemoteSource, -): AddProjectRemoteProviderKind | null { - return source === "url" ? null : source; -} - -function remoteProjectSourceIcon(source: AddProjectRemoteSource, className: string): ReactNode { - switch (source) { - case "github": - return ; - case "gitlab": - return ; - case "bitbucket": - return ; - case "azure-devops": - return ; - case "url": - return ; - } -} - -function remoteProjectInputPlaceholder(flow: AddProjectCloneFlow | null): string | null { - if (!flow) return null; - if (flow.step === "confirm") return null; - if (flow.source === "url") { - return "Enter Git clone URL"; - } - return `Enter ${remoteProjectSourceLabel(flow.source)} repository (${remoteProjectSourcePathHint(flow.source)})`; -} - -function sourceProviderKind(source: AddProjectRemoteSource): AddProjectRemoteProviderKind | null { - return source === "url" ? null : source; -} - -function sortAddProjectProviderSources( - readinessBySource: AddProjectRemoteSourceReadiness, -): ReadonlyArray { - return REMOTE_PROJECT_PROVIDER_SOURCES.toSorted((left, right) => { - const leftReady = readinessBySource[left].ready; - const rightReady = readinessBySource[right].ready; - if (leftReady !== rightReady) { - return leftReady ? -1 : 1; - } - return remoteProjectSourceLabel(left).localeCompare(remoteProjectSourceLabel(right)); - }); -} - -type AddProjectRemoteSourceReadiness = Record< - AddProjectRemoteSource, - { readonly ready: boolean; readonly hint: string | null } ->; - -function buildAddProjectRemoteSourceReadiness( - discovery: SourceControlDiscoveryResult | null, -): AddProjectRemoteSourceReadiness { - const unavailable = { - ready: false, - hint: "Provider status unavailable. Open Settings -> Source Control and rescan.", - } as const; - const defaultReadiness: AddProjectRemoteSourceReadiness = { - url: { ready: true, hint: null }, - github: unavailable, - gitlab: unavailable, - bitbucket: unavailable, - "azure-devops": unavailable, - }; - - if (!discovery) { - return defaultReadiness; - } - - const providerByKind = new Map( - discovery.sourceControlProviders.map((provider) => [provider.kind, provider]), - ); - const readiness = { ...defaultReadiness }; - - for (const source of REMOTE_PROJECT_SOURCES) { - const kind = sourceProviderKind(source); - if (!kind) continue; - const provider = providerByKind.get(kind); - if (!provider) { - readiness[source] = unavailable; - continue; - } - if (provider.status !== "available") { - readiness[source] = { ready: false, hint: provider.installHint }; - continue; - } - if (provider.auth.status === "unauthenticated") { - readiness[source] = { - ready: false, - hint: - Option.getOrNull(provider.auth.detail) ?? - `${provider.label} is not authenticated. Open Settings -> Source Control for setup guidance.`, - }; - continue; - } - readiness[source] = { ready: true, hint: null }; - } - - return readiness; -} - -function errorMessage(error: unknown): string { - if (error instanceof Error && error.message.trim().length > 0) { - return error.message; - } - return "An error occurred."; -} - -function sourceControlRepositoryComparisonKeys( - repository: SourceControlRepositoryInfo, -): ReadonlyArray { - return [repository.sshUrl, repository.url] - .map((remoteUrl) => normalizeGitRemoteUrl(remoteUrl)) - .filter((key) => key.length > 0); -} - -function getAddProjectCloneDirectoryName( - input: Extract, -): string | null { - return ( - deriveRepositoryDirectoryName(input.repository?.nameWithOwner) ?? - deriveRepositoryDirectoryName(input.remoteUrl) ?? - deriveRepositoryDirectoryName(input.repositoryInput) - ); -} - /** * The open palette: search, actions and the add-project flows. Loaded on * demand by CommandPalette, which owns the open state and the shortcut. @@ -559,22 +286,18 @@ export function OpenCommandPaletteDialog() { const navigate = useNavigate(); const setOpen = useCommandPaletteStore((store) => store.setOpen); const chatFindAvailable = useChatFindStore((store) => store.available); - const closeIfGeneration = useCommandPaletteStore((store) => store.closeIfGeneration); const openIntent = useCommandPaletteStore((store) => store.openIntent); const clearOpenIntent = useCommandPaletteStore((store) => store.clearOpenIntent); const composerHandleRef = useComposerHandleContext(); - // This component mounts once per palette session, so its mount-time - // generation identifies the session every deferred close below belongs to. - // Async flows close via `closeIfGeneration`: if the user closed or reopened - // the palette while a request was in flight, the stale close is a no-op - // instead of slamming a palette it does not own. There is deliberately no - // unmount cleanup here: React StrictMode runs a new effect's cleanup once - // right after mount, which closed the palette the instant it opened in dev. - const [sessionGeneration] = useState(() => useCommandPaletteStore.getState().openGeneration); + // Set when a command hands over to another dialog (Add project, Codex + // import), which then owns where focus returns. + const handingOverToDialogRef = useRef(false); + const focusComposer = useCallback(() => { + composerHandleRef?.current?.focusAtEnd(); + }, [composerHandleRef]); const [query, setQuery] = useState(""); const deferredQuery = useDeferredValue(query); const isActionsOnly = deferredQuery.startsWith(">"); - const queryClient = useQueryClient(); const [highlightedItemValue, setHighlightedItemValue] = useState(null); const settings = useSettings(); const { activeDraftThread, defaultProjectRef, handleNewThread, routeThreadRef } = @@ -596,20 +319,8 @@ export function OpenCommandPaletteDialog() { const sidebarListOpen = useUiStateStore(selectSidebarListShown); const [viewStack, setViewStack] = useState([]); const currentView = viewStack.at(-1) ?? null; - const [browseGeneration, setBrowseGeneration] = useState(0); - const [addProjectEnvironmentId, setAddProjectEnvironmentId] = useState( - null, - ); - const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false); - const [addProjectCloneFlow, setAddProjectCloneFlow] = useState(null); - const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false); - const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false); - const [codexSessionFlow, setCodexSessionFlow] = useState(null); - const [importingProviderThreadId, setImportingProviderThreadId] = useState(null); const primaryEnvironmentId = usePrimaryEnvironmentId(); const primaryServerProviders = useServerProviders(); - const primaryEnvironmentLabel = readPrimaryEnvironmentDescriptor()?.label ?? null; - const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((state) => state.byId); const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId); const pullRequestEnvironments = usePullRequestEnvironments(); const scheduledTaskEnvironments = useScheduledTaskEnvironments(); @@ -682,90 +393,11 @@ export function OpenCommandPaletteDialog() { }) : null; - const addProjectEnvironmentOptions = useMemo(() => { - const options: AddProjectEnvironmentOption[] = []; - const seenEnvironmentIds = new Set(); - - if (primaryEnvironmentId) { - seenEnvironmentIds.add(primaryEnvironmentId); - options.push({ - environmentId: primaryEnvironmentId, - label: resolveEnvironmentOptionLabel({ - isPrimary: true, - environmentId: primaryEnvironmentId, - runtimeLabel: primaryEnvironmentLabel, - }), - isPrimary: true, - }); - } - - for (const record of Object.values(savedEnvironmentRegistry)) { - if (seenEnvironmentIds.has(record.environmentId)) { - continue; - } - - const runtimeState = savedEnvironmentRuntimeById[record.environmentId]; - options.push({ - environmentId: record.environmentId, - label: resolveEnvironmentOptionLabel({ - isPrimary: false, - environmentId: record.environmentId, - runtimeLabel: runtimeState?.descriptor?.label ?? null, - savedLabel: record.label, - }), - isPrimary: false, - }); - } - - options.sort((left, right) => { - if (left.isPrimary !== right.isPrimary) { - return left.isPrimary ? -1 : 1; - } - return left.label.localeCompare(right.label); - }); - - return options; - }, [ - primaryEnvironmentId, - primaryEnvironmentLabel, - savedEnvironmentRegistry, - savedEnvironmentRuntimeById, - ]); + const addProjectEnvironmentOptions = useAddProjectEnvironmentOptions(); + // A typed path offers "Add project at " for the computer Add project + // starts on, read with that computer's idea of a path. const defaultAddProjectEnvironmentId = addProjectEnvironmentOptions[0]?.environmentId ?? null; - const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId; - const browseEnvironmentPlatform = useMemo(() => { - const os = - browseEnvironmentId && primaryEnvironmentId && browseEnvironmentId === primaryEnvironmentId - ? (readPrimaryEnvironmentDescriptor()?.platform.os ?? null) - : browseEnvironmentId - ? (savedEnvironmentRuntimeById[browseEnvironmentId]?.descriptor?.platform.os ?? - savedEnvironmentRuntimeById[browseEnvironmentId]?.serverConfig?.environment.platform - .os ?? - null) - : null; - return getEnvironmentBrowsePlatform(os); - }, [browseEnvironmentId, primaryEnvironmentId, savedEnvironmentRuntimeById]); - const isRemoteProjectCloneFlow = addProjectCloneFlow !== null; - const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository"; - const isBrowsing = - !isRemoteProjectRepositoryStep && isFilesystemBrowseQuery(query, browseEnvironmentPlatform); - const paletteMode = getCommandPaletteMode({ currentView, isBrowsing }); - const getAddProjectInitialQueryForEnvironment = useCallback( - (environmentId: EnvironmentId | null): string => { - const environmentSettings = - environmentId && primaryEnvironmentId && environmentId === primaryEnvironmentId - ? settings - : environmentId - ? savedEnvironmentRuntimeById[environmentId]?.serverConfig?.settings - : null; - const baseDirectory = environmentSettings?.addProjectBaseDirectory?.trim() ?? ""; - if (baseDirectory.length === 0) { - return "~/"; - } - return ensureBrowseDirectoryPath(baseDirectory); - }, - [primaryEnvironmentId, savedEnvironmentRuntimeById, settings], - ); + const addProjectPathPlatform = useEnvironmentBrowsePlatform(defaultAddProjectEnvironmentId); const projectTitleById = useMemo( () => new Map(projects.map((project) => [project.id, project.name])), @@ -781,23 +413,6 @@ export function OpenCommandPaletteDialog() { ), [projects], ); - const existingGitHubRepositoryKeys = useMemo(() => { - const keys = new Set(); - for (const project of projects) { - const canonicalKey = project.repositoryIdentity?.canonicalKey?.trim().toLowerCase() ?? ""; - if (canonicalKey.startsWith("github.com/")) { - keys.add(canonicalKey); - } - const remoteUrl = project.repositoryIdentity?.locator.remoteUrl; - if (remoteUrl) { - const remoteKey = normalizeGitRemoteUrl(remoteUrl); - if (remoteKey.startsWith("github.com/")) { - keys.add(remoteKey); - } - } - } - return keys; - }, [projects]); const activeThreadId = activeThread?.id; const currentProjectEnvironmentId = @@ -841,13 +456,6 @@ export function OpenCommandPaletteDialog() { savedEnvironmentRuntimeById, ], ); - const currentEnvironmentServerSettings = - currentProjectEnvironmentId && currentProjectEnvironmentId !== primaryEnvironmentId - ? savedEnvironmentRuntimeById[currentProjectEnvironmentId]?.serverConfig?.settings - : null; - const currentEnvironmentSettings = currentEnvironmentServerSettings - ? { ...settings, ...currentEnvironmentServerSettings } - : settings; const availableCodexInstances = useMemo( () => deriveProviderInstanceEntries(currentEnvironmentProviders).filter( @@ -860,153 +468,6 @@ export function OpenCommandPaletteDialog() { ), [currentEnvironmentProviders], ); - const currentProjectCwdForBrowse = - browseEnvironmentId && currentProjectEnvironmentId === browseEnvironmentId - ? currentProjectCwd - : null; - const relativePathNeedsActiveProject = - isExplicitRelativeProjectPath(query.trim()) && currentProjectCwdForBrowse === null; - const browseDirectoryPath = isBrowsing ? getBrowseDirectoryPath(query) : ""; - const browseFilterQuery = - isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : ""; - const [externalSessionSearchQuery] = useDebouncedValue( - codexSessionFlow ? deferredQuery : "", - { wait: EXTERNAL_SESSION_SEARCH_DEBOUNCE_MS }, - (debouncerState) => ({ isPending: debouncerState.isPending }), - ); - const externalSessionsQuery = useInfiniteQuery({ - queryKey: [ - "externalCodexSessions", - codexSessionFlow?.environmentId, - codexSessionFlow?.providerInstanceId, - codexSessionFlow?.cwd, - externalSessionSearchQuery.trim(), - ], - queryFn: async ({ pageParam }) => { - if (!codexSessionFlow) { - return { data: [] }; - } - return requireEnvironmentConnection( - codexSessionFlow.environmentId, - ).client.server.listExternalProviderThreads({ - providerInstanceId: codexSessionFlow.providerInstanceId, - cwd: codexSessionFlow.cwd, - limit: 20, - ...(typeof pageParam === "string" ? { cursor: pageParam } : {}), - ...(externalSessionSearchQuery.trim().length > 0 - ? { searchTerm: externalSessionSearchQuery.trim() } - : {}), - }); - }, - initialPageParam: undefined as string | undefined, - getNextPageParam: (lastPage) => lastPage.nextCursor, - enabled: codexSessionFlow !== null, - }); - - const fetchBrowseResult = useCallback( - async (partialPath: string): Promise => { - if (!browseEnvironmentId) return null; - const api = readEnvironmentApi(browseEnvironmentId); - if (!api) return null; - return api.filesystem.browse({ - partialPath, - ...(currentProjectCwdForBrowse ? { cwd: currentProjectCwdForBrowse } : {}), - }); - }, - [browseEnvironmentId, currentProjectCwdForBrowse], - ); - - const { data: browseResult, isPending: isBrowsePending } = useQuery({ - queryKey: [ - "filesystemBrowse", - browseEnvironmentId, - browseDirectoryPath, - currentProjectCwdForBrowse, - ], - queryFn: () => fetchBrowseResult(browseDirectoryPath), - staleTime: BROWSE_STALE_TIME_MS, - enabled: - isBrowsing && - browseDirectoryPath.length > 0 && - browseEnvironmentId !== null && - !relativePathNeedsActiveProject, - }); - const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES; - const { - filteredEntries: filteredBrowseEntries, - highlightedEntry: highlightedBrowseEntry, - exactEntry: exactBrowseEntry, - } = useMemo( - () => filterBrowseEntries({ browseEntries, browseFilterQuery, highlightedItemValue }), - [browseEntries, browseFilterQuery, highlightedItemValue], - ); - const isGitHubRepositorySelectionStep = - addProjectCloneFlow?.step === "repository" && addProjectCloneFlow.source === "github"; - const gitHubRepositorySelectionEnvironmentId = isGitHubRepositorySelectionStep - ? addProjectCloneFlow.environmentId - : null; - const gitHubRepositoriesQuery = useQuery({ - queryKey: [ - "sourceControlRepositories", - gitHubRepositorySelectionEnvironmentId, - "github", - GITHUB_REPOSITORY_LIST_LIMIT, - ], - queryFn: async () => { - if (!gitHubRepositorySelectionEnvironmentId) { - return { repositories: [] }; - } - const api = readEnvironmentApi(gitHubRepositorySelectionEnvironmentId); - if (!api) { - return { repositories: [] }; - } - return api.sourceControl.listRepositories({ - provider: "github", - limit: GITHUB_REPOSITORY_LIST_LIMIT, - }); - }, - staleTime: GITHUB_REPOSITORY_LIST_STALE_TIME_MS, - enabled: gitHubRepositorySelectionEnvironmentId !== null, - }); - - const prefetchBrowsePath = useCallback( - (partialPath: string) => { - void queryClient.prefetchQuery({ - queryKey: [ - "filesystemBrowse", - browseEnvironmentId, - partialPath, - currentProjectCwdForBrowse, - ], - queryFn: () => fetchBrowseResult(partialPath), - staleTime: BROWSE_STALE_TIME_MS, - }); - }, - [browseEnvironmentId, currentProjectCwdForBrowse, fetchBrowseResult, queryClient], - ); - - // Prefetch the parent and the most likely next child so browse navigation - // stays warm without scanning every child directory in large trees. - useEffect(() => { - if (!isBrowsing || filteredBrowseEntries.length === 0) return; - - if (canNavigateUp(query)) { - prefetchBrowsePath(getBrowseParentPath(query)!); - } - - const nextChild = highlightedBrowseEntry ?? exactBrowseEntry; - if (nextChild) { - prefetchBrowsePath(appendBrowsePathSegment(query, nextChild.name)); - } - }, [ - exactBrowseEntry, - filteredBrowseEntries.length, - highlightedBrowseEntry, - isBrowsing, - prefetchBrowsePath, - query, - ]); - const openProjectFromSearch = useMemo( () => async (project: (typeof projects)[number]) => { const latestThread = getLatestThreadForProject( @@ -1180,60 +641,32 @@ export function OpenCommandPaletteDialog() { }); } - function startCodexSessionBrowser(instance: (typeof availableCodexInstances)[number]): void { + // Hands over to the Codex import dialog, which takes the project, its + // accounts and the open thread's mode as they are now. + function openCodexImportDialog(): void { if (!currentProject || currentProject.kind !== "workspace") { return; } - setCodexSessionFlow({ - environmentId: currentProject.environmentId, - projectId: currentProject.id, - projectName: currentProject.name, - cwd: currentProject.cwd, - providerInstanceId: instance.instanceId, - }); - pushPaletteView({ - addonIcon: , - groups: [], - inputPlaceholder: `Search other Codex conversations in ${currentProject.name}...`, - }); - } - - function openCodexSessionBrowser(): void { - if (availableCodexInstances.length === 1) { - startCodexSessionBrowser(availableCodexInstances[0]!); - return; - } - pushPaletteView({ - addonIcon: , - groups: [ - { - value: "codex-accounts", - label: "Codex accounts", - items: availableCodexInstances.map((instance) => ({ - kind: "action" as const, - value: `external-codex-account:${instance.instanceId}`, - searchTerms: [instance.displayName, instance.instanceId, "codex", "account"], - title: instance.displayName, - description: "Sessions stored by this Codex account", - icon: , - keepOpen: true, - run: async () => { - startCodexSessionBrowser(instance); - }, - })), - }, - ], - inputPlaceholder: "Choose a Codex account...", + openCodexImport({ + project: { + environmentId: currentProject.environmentId, + projectId: currentProject.id, + projectName: currentProject.name, + cwd: currentProject.cwd, + }, + accounts: availableCodexInstances.map((instance) => ({ + instanceId: instance.instanceId, + displayName: instance.displayName, + })), + runtimeMode: + activeThread?.runtimeMode ?? + activeDraftThread?.runtimeMode ?? + DEFAULT_NEW_THREAD_RUNTIME_MODE, + returnFocus: focusComposer, }); } function popView(): void { - setAddProjectCloneFlow(null); - setCodexSessionFlow(null); - setImportingProviderThreadId(null); - if (viewStack.length <= 1) { - setAddProjectEnvironmentId(null); - } setViewStack((previousViews) => previousViews.slice(0, -1)); setHighlightedItemValue(null); setQuery(""); @@ -1247,270 +680,6 @@ export function OpenCommandPaletteDialog() { } } - const startAddProjectBrowse = useCallback( - (environmentId: EnvironmentId): void => { - setAddProjectEnvironmentId(environmentId); - setAddProjectCloneFlow(null); - pushPaletteView({ - addonIcon: , - groups: [], - initialQuery: getAddProjectInitialQueryForEnvironment(environmentId), - }); - }, - [getAddProjectInitialQueryForEnvironment], - ); - - const startAddProjectClone = useCallback( - (environmentId: EnvironmentId, source: AddProjectRemoteSource): void => { - setAddProjectEnvironmentId(environmentId); - setAddProjectCloneFlow({ step: "repository", environmentId, source }); - pushPaletteView({ - addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS), - groups: [], - initialQuery: "", - }); - }, - [], - ); - - const openSourceControlSettings = useCallback(() => { - setOpen(false); - void navigate({ to: "/settings/source-control" }); - }, [navigate, setOpen]); - - const buildAddProjectSourceGroups = useCallback( - ( - environmentId: EnvironmentId, - readinessBySource: AddProjectRemoteSourceReadiness, - ): CommandPaletteView["groups"] => { - const sourceItems: Array = [ - { - kind: "action", - value: `action:add-project:${environmentId}:local`, - searchTerms: ["local", "folder", "directory", "browse"], - title: "Local folder", - description: "Browse a folder on disk", - icon: , - keepOpen: true, - run: async () => { - startAddProjectBrowse(environmentId); - }, - }, - ]; - - const orderedSources: ReadonlyArray = [ - "url", - ...sortAddProjectProviderSources(readinessBySource), - ]; - - for (const source of orderedSources) { - const label = remoteProjectSourceLabel(source); - const title = source === "url" ? "Git URL" : `${label} repository`; - const description = - source === "url" - ? "Clone from a remote URL" - : `Clone ${label} ${remoteProjectSourcePathHint(source)}`; - const readiness = readinessBySource[source]; - const disabledHint = readiness.hint; - - const titleTrailingContent = readiness.ready ? undefined : ( - - - { - openSourceControlSettings(); - }} - > - Setup Required - - } - /> - - {disabledHint ?? "Open Settings -> Source Control to configure this provider."} - - - - ); - - if (!readiness.ready) { - sourceItems.push({ - kind: "action", - value: `action:add-project:${environmentId}:${source}:not-ready`, - searchTerms: ["clone", "remote", "repository", "repo", "git", label, "setup required"], - title, - description, - disabled: true, - icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS), - ...(titleTrailingContent ? { titleTrailingContent } : {}), - run: async () => {}, - }); - continue; - } - - sourceItems.push({ - kind: "action", - value: `action:add-project:${environmentId}:${source}`, - searchTerms: ["clone", "remote", "repository", "repo", "git", label], - title, - description, - icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS), - ...(titleTrailingContent ? { titleTrailingContent } : {}), - keepOpen: true, - run: async () => { - startAddProjectClone(environmentId, source); - }, - }); - } - - return [{ value: `sources:${environmentId}`, label: "Sources", items: sourceItems }]; - }, - [openSourceControlSettings, startAddProjectBrowse, startAddProjectClone], - ); - - const startAddProjectSourceSelection = useCallback( - (environmentId: EnvironmentId): void => { - setAddProjectEnvironmentId(environmentId); - setAddProjectCloneFlow(null); - const target = { environmentId }; - const initialDiscovery = getSourceControlDiscoverySnapshot(target).data; - pushPaletteView({ - addonIcon: , - groups: buildAddProjectSourceGroups( - environmentId, - buildAddProjectRemoteSourceReadiness(initialDiscovery), - ), - }); - - if (initialDiscovery) { - return; - } - - void refreshSourceControlDiscovery(target).then((discovery) => { - if (!discovery) { - return; - } - setViewStack((previousViews) => { - const currentTopView = previousViews.at(-1); - if (currentTopView?.groups[0]?.value !== `sources:${environmentId}`) { - return previousViews; - } - return [ - ...previousViews.slice(0, -1), - { - addonIcon: , - groups: buildAddProjectSourceGroups( - environmentId, - buildAddProjectRemoteSourceReadiness(discovery), - ), - }, - ]; - }); - }); - }, - [buildAddProjectSourceGroups], - ); - - const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map( - (option) => ({ - kind: "action", - value: `action:add-project:environment:${option.environmentId}`, - searchTerms: [option.label, option.environmentId, option.isPrimary ? "this device" : ""], - title: option.label, - description: option.isPrimary ? "This device" : option.environmentId, - icon: , - keepOpen: true, - run: async () => { - startAddProjectSourceSelection(option.environmentId); - }, - }), - ); - - const addProjectEnvironmentGroups = useMemo( - () => [ - { - value: "environments", - label: "Environments", - items: addProjectEnvironmentItems, - }, - ], - [addProjectEnvironmentItems], - ); - - const openAddProjectFlow = useCallback(() => { - // A caller picking a folder on a specific computer skips the computer list. - const selectionEnvironmentId = - useCommandPaletteStore.getState().projectSelection?.environmentId; - if (selectionEnvironmentId) { - void startAddProjectSourceSelection(selectionEnvironmentId); - return; - } - if (addProjectEnvironmentOptions.length > 1) { - pushPaletteView({ - addonIcon: , - groups: addProjectEnvironmentGroups, - }); - return; - } - - const environmentId = defaultAddProjectEnvironmentId; - if (!environmentId) { - const guidance = resolveAddProjectUnavailableGuidance({ - isHostedStatic: isHostedStaticApp(), - }); - const guidanceAction = guidance.action; - toastManager.add( - stackedThreadToast({ - type: guidance.type, - title: guidance.title, - description: guidance.description, - ...(guidanceAction - ? { - actionProps: { - children: guidanceAction.label, - onClick: () => { - void navigate({ to: guidanceAction.to }); - }, - }, - actionVariant: "outline" as const, - } - : {}), - }), - ); - return; - } - - void startAddProjectSourceSelection(environmentId); - }, [ - addProjectEnvironmentGroups, - addProjectEnvironmentOptions.length, - defaultAddProjectEnvironmentId, - navigate, - startAddProjectSourceSelection, - ]); - - useLayoutEffect(() => { - if (openIntent?.kind !== "add-project") { - return; - } - // Environments hydrate a beat after the palette can open, and this - // intent is one-shot: consuming it against an empty environment list - // turned an add-project click during startup into a dead end. Hold the - // intent until an environment exists (closing the palette clears it); - // this effect re-runs when the options arrive. Hosted-static tabs know - // immediately that no local environment is coming, so they proceed - // straight to the pairing guidance. - if (addProjectEnvironmentOptions.length === 0 && !isHostedStaticApp()) { - return; - } - clearOpenIntent(); - openAddProjectFlow(); - }, [addProjectEnvironmentOptions.length, clearOpenIntent, openAddProjectFlow, openIntent]); - // Sidebar "Search all N threads" hands off here: a submenu view scoped to // one logical project's threads, searchable with the usual palette ranking. useLayoutEffect(() => { @@ -1559,132 +728,6 @@ export function OpenCommandPaletteDialog() { }); }, [activeThreadId, clearOpenIntent, navigate, openIntent, projectTitleById, threads]); - const importExternalCodexSession = useCallback( - async (candidate: ProviderExternalThreadCandidate): Promise => { - if (!codexSessionFlow || importingProviderThreadId !== null) { - return; - } - const model = resolveAppModelSelectionForInstance( - codexSessionFlow.providerInstanceId, - currentEnvironmentSettings, - currentEnvironmentProviders, - null, - ); - if (!model) { - throw new Error("No usable model is available for this Codex account."); - } - - setImportingProviderThreadId(candidate.providerThreadId); - try { - const connection = requireEnvironmentConnection(codexSessionFlow.environmentId); - const result = await connection.client.server.importExternalProviderThread({ - providerInstanceId: codexSessionFlow.providerInstanceId, - providerThreadId: candidate.providerThreadId, - projectId: codexSessionFlow.projectId, - threadId: newThreadId(), - modelSelection: { - instanceId: codexSessionFlow.providerInstanceId, - model, - }, - runtimeMode: - activeThread?.runtimeMode ?? - activeDraftThread?.runtimeMode ?? - DEFAULT_NEW_THREAD_RUNTIME_MODE, - }); - closeIfGeneration(sessionGeneration); - await navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams( - scopeThreadRef(codexSessionFlow.environmentId, result.threadId), - ), - }); - } finally { - setImportingProviderThreadId(null); - } - }, - [ - activeDraftThread?.runtimeMode, - activeThread?.runtimeMode, - codexSessionFlow, - closeIfGeneration, - currentEnvironmentProviders, - currentEnvironmentSettings, - importingProviderThreadId, - navigate, - sessionGeneration, - ], - ); - - const externalCodexSessionGroups = useMemo(() => { - if (!codexSessionFlow) { - return []; - } - const candidates = externalSessionsQuery.data?.pages.flatMap((page) => page.data) ?? []; - const items: CommandPaletteActionItem[] = candidates.map((candidate) => { - const title = - candidate.name?.trim() || - candidate.preview.trim().split(/\r?\n/, 1)[0] || - "Untitled Codex session"; - const source = externalSessionSourceLabel(candidate.source); - const isImporting = importingProviderThreadId === candidate.providerThreadId; - return { - kind: "action", - value: `external-codex-session:${candidate.providerThreadId}`, - searchTerms: [title, candidate.preview, source, candidate.cliVersion], - title, - description: candidate.unavailableReason ?? `${source} · ${candidate.preview}`, - icon: , - timestampAt: candidate.updatedAt, - disabled: !candidate.canImport || importingProviderThreadId !== null, - ...(isImporting - ? { - titleTrailingContent: ( - Importing… - ), - } - : {}), - keepOpen: true, - run: async () => { - await importExternalCodexSession(candidate); - }, - }; - }); - - if (externalSessionsQuery.hasNextPage) { - items.push({ - kind: "action", - value: "external-codex-session:load-more", - searchTerms: ["load more", "older", "sessions"], - title: externalSessionsQuery.isFetchingNextPage ? "Loading more…" : "Load more sessions", - description: "Fetch the next 20 conversations", - icon: , - disabled: externalSessionsQuery.isFetchingNextPage || importingProviderThreadId !== null, - keepOpen: true, - run: async () => { - await externalSessionsQuery.fetchNextPage(); - }, - }); - } - - return items.length > 0 - ? [ - { - value: "external-codex-sessions", - label: `Other Codex conversations in ${codexSessionFlow.projectName}`, - items, - }, - ] - : []; - }, [ - codexSessionFlow, - externalSessionsQuery.data?.pages, - externalSessionsQuery.fetchNextPage, - externalSessionsQuery.hasNextPage, - externalSessionsQuery.isFetchingNextPage, - importExternalCodexSession, - importingProviderThreadId, - ]); - const actionItems: Array = []; if (projects.length > 0) { @@ -1724,9 +767,9 @@ export function OpenCommandPaletteDialog() { title: "Bring in Codex conversation…", description: "Continue work from Codex app, CLI, or IDE", icon: , - keepOpen: true, + opensDialog: true, run: async () => { - openCodexSessionBrowser(); + openCodexImportDialog(); }, }); } @@ -1809,9 +852,9 @@ export function OpenCommandPaletteDialog() { ], title: "Add project", icon: , - keepOpen: true, + opensDialog: true, run: async () => { - openAddProjectFlow(); + openAddProject({ returnFocus: focusComposer }); }, }); @@ -2480,382 +1523,29 @@ export function OpenCommandPaletteDialog() { threadSearchItems: allThreadSearchItems, }); - const handleAddProject = useCallback( - async (rawCwd: string) => { - if (!browseEnvironmentId) return; - const api = readEnvironmentApi(browseEnvironmentId); - if (!api) return; - - if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) { - toastManager.add( - failureNotice({ - title: "Couldn't add the project", - reason: "Windows-style paths are only supported on Windows.", - }), - ); - return; - } - - if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) { - toastManager.add( - failureNotice({ - title: "Couldn't add the project", - reason: "Relative paths require an active project.", - }), - ); - return; - } - - const cwd = resolveProjectPathForDispatch(rawCwd, currentProjectCwdForBrowse); - if (cwd.length === 0) return; - - const existing = findProjectByPath( - projects.filter((project) => project.environmentId === browseEnvironmentId), - cwd, - ); - // Picking a folder for someone else (the setup screen): report the - // project and close, instead of opening a thread in it. - const projectSelection = useCommandPaletteStore.getState().projectSelection; - if (existing && projectSelection) { - projectSelection.onProjectSelected(scopeProjectRef(existing.environmentId, existing.id)); - closeIfGeneration(sessionGeneration); - return; - } - if (existing) { - const latestThread = getLatestThreadForProject( - threads.filter((thread) => thread.environmentId === existing.environmentId), - existing.id, - ); - if (latestThread) { - await navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams( - scopeThreadRef(latestThread.environmentId, latestThread.id), - ), - }); - } else { - await handleNewThread(scopeProjectRef(existing.environmentId, existing.id)).catch( - () => undefined, - ); - } - closeIfGeneration(sessionGeneration); - return; - } - - try { - const projectId = newProjectId(); - await api.orchestration.dispatchCommand({ - type: "project.create", - commandId: newCommandId(), - projectId, - title: inferProjectTitleFromPath(cwd), - workspaceRoot: cwd, - createWorkspaceRootIfMissing: true, - // Keep newly added projects on the provider's live default until - // the user explicitly chooses a project/thread model. - defaultModelSelection: null, - createdAt: new Date().toISOString(), - }); - const createdProjectRef = scopeProjectRef(browseEnvironmentId, projectId); - // A repository added with worktrees already in it lays them out for - // picking on the screen that opens next (worktree pickup). - useWorktreePickupStore.getState().offer(scopedProjectKey(createdProjectRef)); - // Let the created project reach the store first so the draft is keyed - // to the project's real identity. If it does not arrive in time the - // draft is adopted (re-keyed) on the next new-thread call instead. - await waitForProjectInStore(createdProjectRef); - if (projectSelection) { - projectSelection.onProjectSelected(createdProjectRef); - closeIfGeneration(sessionGeneration); - return; + // A typed path adds one row above the results that opens Add project there. + // The search itself carries on underneath, so the field never turns into a + // form. + const addProjectPathItem: CommandPaletteActionItem | null = + currentView === null && isFilesystemBrowseQuery(deferredQuery, addProjectPathPlatform) + ? { + kind: "action", + value: "action:add-project-at-path", + searchTerms: [], + title: `Add project at ${deferredQuery.trim()}`, + icon: , + opensDialog: true, + run: async () => { + openAddProject({ initialPath: deferredQuery.trim(), returnFocus: focusComposer }); + }, } - await handleNewThread(createdProjectRef).catch(() => undefined); - closeIfGeneration(sessionGeneration); - } catch (error) { - toastManager.add( - failureNotice({ - title: "Couldn't add the project", - error, - }), - ); - } - }, - [ - browseEnvironmentId, - browseEnvironmentPlatform, - closeIfGeneration, - currentProjectCwdForBrowse, - handleNewThread, - navigate, - projects, - sessionGeneration, - threads, - ], - ); - - const continueAddProjectCloneFlowWithRepository = useCallback( - ( - flow: Extract, - input: { - readonly repositoryInput: string; - readonly repository: SourceControlRepositoryInfo | null; - readonly remoteUrl: string; - }, - ): void => { - const destinationPath = getAddProjectInitialQueryForEnvironment(flow.environmentId); - setAddProjectCloneFlow({ - step: "confirm", - environmentId: flow.environmentId, - source: flow.source, - repositoryInput: input.repositoryInput, - repository: input.repository, - remoteUrl: input.remoteUrl, - }); - setHighlightedItemValue(null); - setQuery(destinationPath); - setBrowseGeneration((generation) => generation + 1); - }, - [getAddProjectInitialQueryForEnvironment], - ); - - async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise { - if (!addProjectCloneFlow) { - return; - } - - const api = readEnvironmentApi(addProjectCloneFlow.environmentId); - if (!api) { - addComputerNotConnectedNotice({ - environmentId: addProjectCloneFlow.environmentId, - failure: "Couldn't clone the project", - }); - return; - } - - if (addProjectCloneFlow.step === "repository") { - const rawRepository = query.trim(); - if (rawRepository.length === 0 || isRemoteProjectLookingUp) { - return; - } - - const provider = remoteProjectSourceProvider(addProjectCloneFlow.source); - if (!provider) { - continueAddProjectCloneFlowWithRepository(addProjectCloneFlow, { - repositoryInput: rawRepository, - repository: null, - remoteUrl: rawRepository, - }); - return; - } - - setIsRemoteProjectLookingUp(true); - try { - const repository = await api.sourceControl.lookupRepository({ - provider, - repository: rawRepository, - }); - continueAddProjectCloneFlowWithRepository(addProjectCloneFlow, { - repositoryInput: rawRepository, - repository, - remoteUrl: repository.url, - }); - } catch (error) { - toastManager.add( - failureNotice({ - title: "Couldn't find the repository", - reason: errorMessage(error), - }), - ); - } finally { - setIsRemoteProjectLookingUp(false); - } - return; - } - - const rawDestination = (destinationPathInput ?? query).trim(); - if (rawDestination.length === 0 || isRemoteProjectCloning) { - return; - } - - if (isUnsupportedWindowsProjectPath(rawDestination, browseEnvironmentPlatform)) { - toastManager.add( - failureNotice({ - title: "Couldn't clone the project", - reason: "Windows-style paths are only supported on Windows.", - }), - ); - return; - } - - if (isExplicitRelativeProjectPath(rawDestination) && !currentProjectCwdForBrowse) { - toastManager.add( - failureNotice({ - title: "Couldn't clone the project", - reason: "Relative paths require an active project.", - }), - ); - return; - } - - const cloneDirectoryName = getAddProjectCloneDirectoryName(addProjectCloneFlow); - const destinationPath = resolveCloneDestinationPathForDispatch({ - destinationPath: rawDestination, - repositoryDirectoryName: cloneDirectoryName, - cwd: currentProjectCwdForBrowse, - }); - if (destinationPath.length === 0) { - return; - } - - setIsRemoteProjectCloning(true); - try { - const provider = remoteProjectSourceProvider(addProjectCloneFlow.source); - // As a mutation, so the new folder reads as busy until the clone lands. - const result = await runGitMutation( - queryClient, - gitCloneRepositoryMutationOptions({ environmentId: addProjectCloneFlow.environmentId }), - { - remoteUrl: addProjectCloneFlow.remoteUrl, - destinationPath, - ...(provider ? { provider } : {}), - }, - ); - await handleAddProject(result.cwd); - } catch (error) { - toastManager.add( - failureNotice({ - title: "Couldn't clone the project", - reason: errorMessage(error), - }), - ); - } finally { - setIsRemoteProjectCloning(false); - } - } - - function browseTo(name: string): void { - const nextQuery = appendBrowsePathSegment(query, name); - setHighlightedItemValue(null); - setQuery(nextQuery); - setBrowseGeneration((generation) => generation + 1); - } - - function browseUp(): void { - const parentPath = getBrowseParentPath(query); - if (parentPath === null) { - return; - } - - setHighlightedItemValue(null); - setQuery(parentPath); - setBrowseGeneration((generation) => generation + 1); - } - - // Resolve the add-project path from browse data when available. When the - // query has a trailing separator (e.g. "~/projects/foo/"), parentPath is the - // directory itself. Otherwise the user typed a partial leaf name, so we need - // the exact browse entry's fullPath or fall back to the raw query. - const resolvedAddProjectPath = hasTrailingPathSeparator(query) - ? (browseResult?.parentPath ?? query.trim()) - : (exactBrowseEntry?.fullPath ?? query.trim()); - - const canBrowseUp = - isBrowsing && !relativePathNeedsActiveProject && canNavigateUp(browseDirectoryPath); - - const browseGroups = buildBrowseGroups({ - browseEntries: filteredBrowseEntries, - browseQuery: query, - canBrowseUp, - upIcon: , - directoryIcon: , - browseUp, - browseTo, - }); - const cloneDestinationBrowseGroups = useMemo( - () => - browseGroups.map((group) => - group.value === "directories" ? { ...group, label: "Select where to clone" } : group, - ), - [browseGroups], - ); - const gitHubRepositorySuggestionGroups = useMemo(() => { - if (!isGitHubRepositorySelectionStep || addProjectCloneFlow?.step !== "repository") { - return []; - } - - const repositories = gitHubRepositoriesQuery.data?.repositories ?? []; - const items: CommandPaletteActionItem[] = repositories - .filter((repository) => - sourceControlRepositoryComparisonKeys(repository).every( - (key) => !existingGitHubRepositoryKeys.has(key), - ), - ) - .map((repository) => ({ - kind: "action", - value: `github-repository:${repository.nameWithOwner}`, - searchTerms: [repository.nameWithOwner, repository.url, repository.sshUrl, "github"], - title: repository.nameWithOwner, - description: repository.url, - icon: , - keepOpen: true, - run: async () => { - if (addProjectCloneFlow?.step !== "repository") { - return; - } - continueAddProjectCloneFlowWithRepository(addProjectCloneFlow, { - repositoryInput: repository.nameWithOwner, - repository, - remoteUrl: repository.url, - }); - }, - })); - - return items.length > 0 - ? [{ value: "github-repositories", label: "GitHub repositories", items }] - : []; - }, [ - addProjectCloneFlow, - continueAddProjectCloneFlowWithRepository, - existingGitHubRepositoryKeys, - gitHubRepositoriesQuery.data?.repositories, - isGitHubRepositorySelectionStep, - ]); - const filteredGitHubRepositorySuggestionGroups = useMemo( - () => - filterCommandPaletteGroups({ - activeGroups: gitHubRepositorySuggestionGroups, - query: deferredQuery, - isInSubmenu: true, - projectSearchItems: [], - threadSearchItems: [], - }), - [deferredQuery, gitHubRepositorySuggestionGroups], - ); - - const remoteProjectContext = useMemo(() => { - if (addProjectCloneFlow?.step !== "confirm") { - return null; - } - - return { - title: addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.repositoryInput, - description: addProjectCloneFlow.repository?.url ?? addProjectCloneFlow.remoteUrl, - icon: remoteProjectSourceIcon(addProjectCloneFlow.source, ITEM_ICON_CLASS), - }; - }, [addProjectCloneFlow]); - - let displayedGroups: CommandPaletteView["groups"] = filteredGroups; - if (codexSessionFlow) { - displayedGroups = externalCodexSessionGroups; - } else if (addProjectCloneFlow?.step === "repository") { - displayedGroups = isGitHubRepositorySelectionStep - ? filteredGitHubRepositorySuggestionGroups - : []; - } else if (addProjectCloneFlow?.step === "confirm") { - displayedGroups = relativePathNeedsActiveProject ? [] : cloneDestinationBrowseGroups; - } else if (isBrowsing) { - displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups; - } + : null; + const displayedGroups: CommandPaletteView["groups"] = addProjectPathItem + ? [ + { value: "add-project-path", label: "Add project", items: [addProjectPathItem] }, + ...filteredGroups, + ] + : filteredGroups; // The thread a highlighted result opens starts loading once the highlight // rests on it, as a pointer resting on a sidebar row does, so choosing it @@ -2866,121 +1556,11 @@ export function OpenCommandPaletteDialog() { return ref ? prewarmHighlightedThread(ref) : undefined; }, [highlightedThreadKey]); + const isSubmenu = currentView !== null; const inputPlaceholder = - remoteProjectInputPlaceholder(addProjectCloneFlow) ?? - currentView?.inputPlaceholder ?? - getCommandPaletteInputPlaceholder(paletteMode); - const commandResultsLoading = - (codexSessionFlow !== null && externalSessionsQuery.isPending) || - (isGitHubRepositorySelectionStep && gitHubRepositoriesQuery.isPending); - const isSubmenu = paletteMode === "submenu" || paletteMode === "submenu-browse"; - const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false; - const hasHighlightedRemoteRepositoryItem = - highlightedItemValue?.startsWith("github-repository:") ?? false; - const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject; - const willCreateProjectPath = - canSubmitBrowsePath && - !isBrowsePending && - query.trim().length > 0 && - !hasHighlightedBrowseItem && - (hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null); - const useMetaForMod = isMacPlatform(navigator.platform); - const submitModifierLabel = useMetaForMod ? "\u2318" : "Ctrl"; - const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm"; - const submitActionLabel = isCloneDestinationStep - ? willCreateProjectPath - ? "Create & Clone" - : "Clone" - : willCreateProjectPath - ? "Create & Add" - : "Add"; - const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"; - const remoteProjectButtonLabel = addProjectCloneFlow - ? addProjectCloneFlow.source === "url" - ? "Continue" - : "Lookup" - : null; - const isRemoteProjectPending = isRemoteProjectLookingUp || isRemoteProjectCloning; - const canSubmitRemoteProjectFlow = - addProjectCloneFlow?.step === "repository" && - query.trim().length > 0 && - !isRemoteProjectPending; - const remoteProjectRepositoryEmptyStateMessage = - addProjectCloneFlow?.step === "repository" - ? addProjectCloneFlow.source === "url" - ? "Enter a Git clone URL and press Enter to continue." - : isGitHubRepositorySelectionStep - ? gitHubRepositoriesQuery.isPending - ? "Loading GitHub repositories..." - : gitHubRepositoriesQuery.isError - ? "Could not load GitHub repositories. Enter owner/repo and press Enter to look it up." - : query.trim().length > 0 - ? "No matching GitHub repositories. Press Enter to look up owner/repo." - : "No unadded GitHub repositories found. Enter owner/repo and press Enter to look it up." - : "Enter a repository path and press Enter to look it up." - : null; - // Only the desktop app offers its folder picker, and only for the primary - // computer, so the shared file manager name (that computer's) is this one's. - const canOpenProjectFromFileManager = - isBrowsing && - browseEnvironmentId !== null && - primaryEnvironmentId !== null && - browseEnvironmentId === primaryEnvironmentId && - typeof window !== "undefined" && - window.desktopBridge !== undefined; - const fileManagerInitialPath = useMemo(() => { - if (!canOpenProjectFromFileManager) { - return undefined; - } - - const trimmedQuery = query.trim(); - if (trimmedQuery.length === 0) { - return undefined; - } - - const initialPath = hasTrailingPathSeparator(query) - ? (browseResult?.parentPath ?? trimmedQuery) - : browseDirectoryPath || trimmedQuery; - - const resolvedPath = resolveProjectPathForDispatch(initialPath, currentProjectCwdForBrowse); - return resolvedPath.length > 0 ? resolvedPath : undefined; - }, [ - browseDirectoryPath, - browseResult?.parentPath, - canOpenProjectFromFileManager, - currentProjectCwdForBrowse, - query, - ]); - - function isPrimaryModifierPressed(event: KeyboardEvent): boolean { - return useMetaForMod ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey; - } + currentView?.inputPlaceholder ?? getCommandPaletteInputPlaceholder(isSubmenu); function handleKeyDown(event: KeyboardEvent): void { - if (addProjectCloneFlow?.step === "repository" && event.key === "Enter") { - if (hasHighlightedRemoteRepositoryItem) { - return; - } - event.preventDefault(); - void submitAddProjectCloneFlow(); - return; - } - - const shouldSubmitBrowsePath = - canSubmitBrowsePath && - event.key === "Enter" && - (!hasHighlightedBrowseItem || isPrimaryModifierPressed(event)); - - if (shouldSubmitBrowsePath) { - event.preventDefault(); - if (isCloneDestinationStep) { - void submitAddProjectCloneFlow(resolvedAddProjectPath); - } else { - void handleAddProject(resolvedAddProjectPath); - } - return; - } - if (event.key === "Backspace" && query === "" && isSubmenu) { event.preventDefault(); popView(); @@ -2998,6 +1578,9 @@ export function OpenCommandPaletteDialog() { } if (!item.keepOpen) { + // A dialog taking over decides where focus goes when it closes, so the + // palette leaves the composer alone on its way out. + if (item.opensDialog) handingOverToDialogRef.current = true; setOpen(false); } // Every result naming a thread opens it: start its load now, so closing @@ -3032,44 +1615,13 @@ export function OpenCommandPaletteDialog() { }); } - const handleOpenProjectFromFileManager = useCallback(async () => { - if (!canOpenProjectFromFileManager || isPickingProjectFolder) { - return; - } - const api = readLocalApi(); - if (!api) { - return; - } - - setIsPickingProjectFolder(true); - let pickedPath: string | null = null; - try { - pickedPath = await api.dialogs.pickFolder( - fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : undefined, - ); - } catch { - // Ignore picker failures and leave the palette open. - setIsPickingProjectFolder(false); - return; - } - setIsPickingProjectFolder(false); - if (!pickedPath) { - return; - } - await handleAddProject(pickedPath); - }, [ - canOpenProjectFromFileManager, - fileManagerInitialPath, - handleAddProject, - isPickingProjectFolder, - ]); - return ( { + if (handingOverToDialogRef.current) return false; composerHandleRef?.current?.focusAtEnd(); return false; }} @@ -3078,9 +1630,9 @@ export function OpenCommandPaletteDialog() { }} > { setHighlightedItemValue(typeof value === "string" ? value : null); @@ -3088,150 +1640,35 @@ export function OpenCommandPaletteDialog() { onValueChange={handleQueryChange} value={query} > -
- - - - ), - } - : isBrowsing && !isSubmenu - ? { - startAddon: , - } - : {})} - onKeyDown={handleKeyDown} - /> - {addProjectCloneFlow?.step === "repository" ? ( - - ) : isBrowsing ? ( - + ), } - onMouseDown={(event) => { - event.preventDefault(); - }} - onClick={() => { - if (relativePathNeedsActiveProject) { - return; - } - if (isCloneDestinationStep) { - void submitAddProjectCloneFlow(resolvedAddProjectPath); - } else { - void handleAddProject(resolvedAddProjectPath); - } - }} - > - - {isCloneDestinationStep && isRemoteProjectPending ? "Cloning" : submitActionLabel} - - - {hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"} - - - ) : null} -
+ : {})} + onKeyDown={handleKeyDown} + /> - {remoteProjectContext ? ( -
-
- Repository -
-
- {remoteProjectContext.icon} - - - {remoteProjectContext.title} - - - {remoteProjectContext.description} - - -
-
- ) : null} 0 - ? "No matching external Codex conversations in this project." - : "No other Codex conversations were found. Conversations already in Threadlines are hidden.", - } - : addProjectCloneFlow?.step === "repository" - ? { - emptyStateMessage: - remoteProjectRepositoryEmptyStateMessage ?? - "Enter a repository path and press Enter to look it up.", - } - : addProjectCloneFlow?.step === "confirm" - ? { emptyStateMessage: "Choose a destination path and press Enter to clone." } - : relativePathNeedsActiveProject - ? { emptyStateMessage: "Relative paths require an active project." } - : willCreateProjectPath - ? { - emptyStateMessage: - "Press Enter to create this folder and add it as a project.", - } - : {})} />
@@ -3245,19 +1682,10 @@ export function OpenCommandPaletteDialog() { Navigate - {addProjectCloneFlow?.step === "repository" ? ( - - Enter - - {remoteProjectButtonLabel ?? "Continue"} - - - ) : !canSubmitBrowsePath || hasHighlightedBrowseItem ? ( - - Enter - Select - - ) : null} + + Enter + Select + {isSubmenu ? ( Backspace @@ -3269,19 +1697,6 @@ export function OpenCommandPaletteDialog() { Close - {canOpenProjectFromFileManager ? ( - - ) : null}
diff --git a/apps/web/src/components/NoActiveThreadState.tsx b/apps/web/src/components/NoActiveThreadState.tsx index 0fa69e3cc..55fca2645 100644 --- a/apps/web/src/components/NoActiveThreadState.tsx +++ b/apps/web/src/components/NoActiveThreadState.tsx @@ -10,6 +10,7 @@ import { import { useMemo } from "react"; import { useCommandPaletteStore } from "../commandPaletteStore"; +import { openAddProject } from "./addProject/addProjectStore"; import { usePrimaryEnvironmentId } from "../environments/primary"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { @@ -39,7 +40,6 @@ export function NoActiveThreadState() { const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, orderedProjects } = useHandleNewThread(); const setCommandPaletteOpen = useCommandPaletteStore((store) => store.setOpen); - const openAddProject = useCommandPaletteStore((store) => store.openAddProject); const activeEnvironmentId = useStore((state) => state.activeEnvironmentId); const hasRecentThreads = useStore((state) => selectSidebarThreadsAcrossEnvironments(state).some((thread) => thread.archivedAt === null), @@ -202,7 +202,7 @@ export function NoActiveThreadState() { ) : null} diff --git a/apps/web/src/components/addProject/AddProjectDialog.tsx b/apps/web/src/components/addProject/AddProjectDialog.tsx new file mode 100644 index 000000000..3b102e2d0 --- /dev/null +++ b/apps/web/src/components/addProject/AddProjectDialog.tsx @@ -0,0 +1,45 @@ +"use client"; + +import { lazy, Suspense, useEffect } from "react"; + +import { CommandDialog } from "../ui/command"; +import { useAddProjectStore } from "./addProjectStore"; + +const OpenAddProjectDialog = lazy(() => + import("./OpenAddProjectDialog").then((module) => ({ default: module.OpenAddProjectDialog })), +); + +/** + * The Add project dialog. It loads at startup but its body only on first + * open, and it mounts the body once per session, so nothing from one opening + * (a step, a half-typed path) carries into the next. + */ +export function AddProjectDialog() { + const session = useAddProjectStore((store) => store.session); + const close = useAddProjectStore((store) => store.close); + + // The store outlives this tree: a dialog left open when the shell goes away + // must not greet the next mount already open. + useEffect(() => { + return () => { + if (useAddProjectStore.getState().session !== null) { + close(); + } + }; + }, [close]); + + return ( + { + if (!open) close(); + }} + > + {session ? ( + + + + ) : null} + + ); +} diff --git a/apps/web/src/components/addProject/OpenAddProjectDialog.tsx b/apps/web/src/components/addProject/OpenAddProjectDialog.tsx new file mode 100644 index 000000000..b2bbd205c --- /dev/null +++ b/apps/web/src/components/addProject/OpenAddProjectDialog.tsx @@ -0,0 +1,1635 @@ +"use client"; + +import { scopedProjectKey, scopeProjectRef, scopeThreadRef } from "@threadlines/client-runtime"; +import { + type EnvironmentId, + type ScopedProjectRef, + type SourceControlDiscoveryResult, + type SourceControlProviderKind, + type SourceControlRepositoryInfo, +} from "@threadlines/contracts"; +import { deriveRepositoryDirectoryName, normalizeGitRemoteUrl } from "@threadlines/shared/git"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useNavigate } from "@tanstack/react-router"; +import * as Option from "effect/Option"; +import { + ArrowDownIcon, + ArrowLeftIcon, + ArrowUpIcon, + CornerLeftUpIcon, + FolderIcon, + FolderPlusIcon, + LinkIcon, +} from "lucide-react"; +import { + useCallback, + useDeferredValue, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, + type KeyboardEvent, + type ReactNode, +} from "react"; +import { useShallow } from "zustand/react/shallow"; + +import { readEnvironmentApi } from "../../environmentApi"; +import { usePrimaryEnvironmentId } from "../../environments/primary"; +import { + hasSavedEnvironmentRegistryHydrated, + useSavedEnvironmentRuntimeStore, + waitForSavedEnvironmentRegistryHydration, +} from "../../environments/runtime"; +import { isHostedStaticApp } from "../../hostedPairing"; +import { useHandleNewThread } from "../../hooks/useHandleNewThread"; +import { useSettings } from "../../hooks/useSettings"; +import { resolveDialogReturnFocus } from "../../lib/dialogReturnFocus"; +import { gitCloneRepositoryMutationOptions, runGitMutation } from "../../lib/gitReactQuery"; +import { + appendBrowsePathSegment, + canNavigateUp, + ensureBrowseDirectoryPath, + findProjectByPath, + getBrowseDirectoryPath, + getBrowseLeafPathSegment, + getBrowseParentPath, + hasTrailingPathSeparator, + inferProjectTitleFromPath, + isExplicitRelativeProjectPath, + isFilesystemBrowseQuery, + isUnsupportedWindowsProjectPath, + resolveCloneDestinationPathForDispatch, + resolveProjectPathForDispatch, +} from "../../lib/projectPaths"; +import { + getSourceControlDiscoverySnapshot, + refreshSourceControlDiscovery, +} from "../../lib/sourceControlDiscoveryState"; +import { getLatestThreadForProject } from "../../lib/threadSort"; +import { cn, isMacPlatform, newCommandId, newProjectId } from "../../lib/utils"; +import { waitForProjectInStore } from "../../lib/waitForProject"; +import { readLocalApi } from "../../localApi"; +import { useServerKeybindings } from "../../rpc/serverState"; +import { + selectProjectsAcrossEnvironments, + selectSidebarThreadsAcrossEnvironments, + useStore, +} from "../../store"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import { useWorktreePickupStore } from "../../worktreePickup"; +import { + ADDON_ICON_CLASS, + filterCommandPaletteGroups, + ITEM_ICON_CLASS, + type CommandPaletteActionItem, + type CommandPaletteSubmenuItem, + type CommandPaletteView, +} from "../CommandPalette.logic"; +import { CommandPaletteResults } from "../CommandPaletteResults"; +import { addComputerNotConnectedNotice } from "../computerConnectionNotices"; +import { editorLabel } from "../EditorOpenOptions"; +import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "../Icons"; +import { Button } from "../ui/button"; +import { + Command, + CommandDialogPopup, + CommandFooter, + CommandInput, + CommandPanel, +} from "../ui/command"; +import { Kbd, KbdGroup } from "../ui/kbd"; +import { failureNotice, stackedThreadToast, toastManager } from "../ui/toast"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { + ADD_PROJECT_PATH_PLACEHOLDER, + buildBrowseGroups, + filterBrowseEntries, + resolveAddProjectUnavailableGuidance, +} from "./addProject.logic"; +import { + useAddProjectEnvironmentOptions, + useEnvironmentBrowsePlatform, +} from "./addProjectComputers"; +import { finishAddProject, useAddProjectStore, type AddProjectSession } from "./addProjectStore"; + +const EMPTY_BROWSE_ENTRIES: never[] = []; +const BROWSE_STALE_TIME_MS = 30_000; +const GITHUB_REPOSITORY_LIST_LIMIT = 100; +const GITHUB_REPOSITORY_LIST_STALE_TIME_MS = 60_000; + +/** A step of the dialog, and the computer it is adding on (null: the default one). */ +interface AddProjectView extends CommandPaletteView { + readonly environmentId: EnvironmentId | null; +} + +type AddProjectRemoteProviderKind = Extract< + SourceControlProviderKind, + "github" | "gitlab" | "bitbucket" | "azure-devops" +>; +type AddProjectRemoteSource = AddProjectRemoteProviderKind | "url"; + +type AddProjectCloneFlow = + | { + readonly step: "repository"; + readonly environmentId: EnvironmentId; + readonly source: AddProjectRemoteSource; + } + | { + readonly step: "confirm"; + readonly environmentId: EnvironmentId; + readonly source: AddProjectRemoteSource; + readonly repositoryInput: string; + readonly repository: SourceControlRepositoryInfo | null; + readonly remoteUrl: string; + }; + +const REMOTE_PROJECT_SOURCES: ReadonlyArray = [ + "url", + "github", + "gitlab", + "bitbucket", + "azure-devops", +]; +const REMOTE_PROJECT_PROVIDER_SOURCES: ReadonlyArray = [ + "github", + "gitlab", + "bitbucket", + "azure-devops", +]; + +function remoteProjectSourceLabel(source: AddProjectRemoteSource): string { + switch (source) { + case "github": + return "GitHub"; + case "gitlab": + return "GitLab"; + case "bitbucket": + return "Bitbucket"; + case "azure-devops": + return "Azure DevOps"; + case "url": + return "Git URL"; + } +} + +function remoteProjectSourcePathHint(source: AddProjectRemoteSource): string { + switch (source) { + case "github": + return "owner/repo"; + case "gitlab": + return "group/project"; + case "bitbucket": + return "workspace/repository"; + case "azure-devops": + return "project/repository"; + case "url": + return "URL"; + } +} + +function remoteProjectSourceProvider( + source: AddProjectRemoteSource, +): AddProjectRemoteProviderKind | null { + return source === "url" ? null : source; +} + +function remoteProjectSourceIcon(source: AddProjectRemoteSource, className: string): ReactNode { + switch (source) { + case "github": + return ; + case "gitlab": + return ; + case "bitbucket": + return ; + case "azure-devops": + return ; + case "url": + return ; + } +} + +function remoteProjectInputPlaceholder(flow: AddProjectCloneFlow | null): string | null { + if (!flow) return null; + if (flow.step === "confirm") return null; + if (flow.source === "url") { + return "Enter Git clone URL"; + } + return `Enter ${remoteProjectSourceLabel(flow.source)} repository (${remoteProjectSourcePathHint(flow.source)})`; +} + +function sortAddProjectProviderSources( + readinessBySource: AddProjectRemoteSourceReadiness, +): ReadonlyArray { + return REMOTE_PROJECT_PROVIDER_SOURCES.toSorted((left, right) => { + const leftReady = readinessBySource[left].ready; + const rightReady = readinessBySource[right].ready; + if (leftReady !== rightReady) { + return leftReady ? -1 : 1; + } + return remoteProjectSourceLabel(left).localeCompare(remoteProjectSourceLabel(right)); + }); +} + +type AddProjectRemoteSourceReadiness = Record< + AddProjectRemoteSource, + { readonly ready: boolean; readonly hint: string | null } +>; + +function buildAddProjectRemoteSourceReadiness( + discovery: SourceControlDiscoveryResult | null, +): AddProjectRemoteSourceReadiness { + const unavailable = { + ready: false, + hint: "Provider status unavailable. Open Settings -> Source Control and rescan.", + } as const; + const defaultReadiness: AddProjectRemoteSourceReadiness = { + url: { ready: true, hint: null }, + github: unavailable, + gitlab: unavailable, + bitbucket: unavailable, + "azure-devops": unavailable, + }; + + if (!discovery) { + return defaultReadiness; + } + + const providerByKind = new Map( + discovery.sourceControlProviders.map((provider) => [provider.kind, provider]), + ); + const readiness = { ...defaultReadiness }; + + for (const source of REMOTE_PROJECT_SOURCES) { + const kind = remoteProjectSourceProvider(source); + if (!kind) continue; + const provider = providerByKind.get(kind); + if (!provider) { + readiness[source] = unavailable; + continue; + } + if (provider.status !== "available") { + readiness[source] = { ready: false, hint: provider.installHint }; + continue; + } + if (provider.auth.status === "unauthenticated") { + readiness[source] = { + ready: false, + hint: + Option.getOrNull(provider.auth.detail) ?? + `${provider.label} is not authenticated. Open Settings -> Source Control for setup guidance.`, + }; + continue; + } + readiness[source] = { ready: true, hint: null }; + } + + return readiness; +} + +function errorMessage(error: unknown): string { + if (error instanceof Error && error.message.trim().length > 0) { + return error.message; + } + return "An error occurred."; +} + +function sourceControlRepositoryComparisonKeys( + repository: SourceControlRepositoryInfo, +): ReadonlyArray { + return [repository.sshUrl, repository.url] + .map((remoteUrl) => normalizeGitRemoteUrl(remoteUrl)) + .filter((key) => key.length > 0); +} + +function getAddProjectCloneDirectoryName( + input: Extract, +): string | null { + return ( + deriveRepositoryDirectoryName(input.repository?.nameWithOwner) ?? + deriveRepositoryDirectoryName(input.remoteUrl) ?? + deriveRepositoryDirectoryName(input.repositoryInput) + ); +} + +/** + * Says a project was added after the dialog that started it went away, with + * a button that opens it. + */ +function announceProjectAdded(title: string, openProject: () => Promise): void { + toastManager.add( + stackedThreadToast({ + type: "success", + title: `Added ${title}`, + actionProps: { + children: "Open", + onClick: () => { + void openProject(); + }, + }, + actionVariant: "outline", + }), + ); +} + +/** + * The open Add project dialog: pick a computer and a source, then browse to a + * folder or clone a repository. Loaded on demand by AddProjectDialog, which + * owns the session; mounted once per session. + */ +export function OpenAddProjectDialog({ session }: { session: AddProjectSession }) { + const navigate = useNavigate(); + const queryClient = useQueryClient(); + const settings = useSettings(); + const keybindings = useServerKeybindings(); + const { activeDraftThread, activeThread, handleNewThread } = useHandleNewThread(); + const projects = useStore(useShallow(selectProjectsAcrossEnvironments)); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId); + const addProjectEnvironmentOptions = useAddProjectEnvironmentOptions(); + const [query, setQuery] = useState(""); + const deferredQuery = useDeferredValue(query); + const [highlightedItemValue, setHighlightedItemValue] = useState(null); + const [viewStack, setViewStack] = useState([]); + const currentView = viewStack.at(-1) ?? null; + const [browseGeneration, setBrowseGeneration] = useState(0); + const [isPickingProjectFolder, setIsPickingProjectFolder] = useState(false); + const [addProjectCloneFlow, setAddProjectCloneFlow] = useState(null); + const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false); + const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false); + // The clone step on screen now, for a lookup that answers after the user + // went Back or picked another computer. + const cloneFlowRef = useRef(null); + useEffect(() => { + cloneFlowRef.current = addProjectCloneFlow; + }, [addProjectCloneFlow]); + const closeDialog = useCallback(() => { + useAddProjectStore.getState().closeSession(session.id); + }, [session.id]); + + const defaultAddProjectEnvironmentId = addProjectEnvironmentOptions[0]?.environmentId ?? null; + const browseEnvironmentId = currentView?.environmentId ?? defaultAddProjectEnvironmentId; + const browseEnvironmentPlatform = useEnvironmentBrowsePlatform(browseEnvironmentId); + const isRemoteProjectCloneFlow = addProjectCloneFlow !== null; + const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository"; + const isBrowsing = + !isRemoteProjectRepositoryStep && isFilesystemBrowseQuery(query, browseEnvironmentPlatform); + // The first step has no step before it to go back to. + const isSubmenu = viewStack.length > 1; + const getAddProjectInitialQueryForEnvironment = useCallback( + (environmentId: EnvironmentId | null): string => { + const environmentSettings = + environmentId && primaryEnvironmentId && environmentId === primaryEnvironmentId + ? settings + : environmentId + ? savedEnvironmentRuntimeById[environmentId]?.serverConfig?.settings + : null; + const baseDirectory = environmentSettings?.addProjectBaseDirectory?.trim() ?? ""; + if (baseDirectory.length === 0) { + return "~/"; + } + return ensureBrowseDirectoryPath(baseDirectory); + }, + [primaryEnvironmentId, savedEnvironmentRuntimeById, settings], + ); + + const existingGitHubRepositoryKeys = useMemo(() => { + const keys = new Set(); + for (const project of projects) { + const canonicalKey = project.repositoryIdentity?.canonicalKey?.trim().toLowerCase() ?? ""; + if (canonicalKey.startsWith("github.com/")) { + keys.add(canonicalKey); + } + const remoteUrl = project.repositoryIdentity?.locator.remoteUrl; + if (remoteUrl) { + const remoteKey = normalizeGitRemoteUrl(remoteUrl); + if (remoteKey.startsWith("github.com/")) { + keys.add(remoteKey); + } + } + } + return keys; + }, [projects]); + + // A relative path resolves against the open project's folder, and only on + // that project's computer. + const currentProjectEnvironmentId = + activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null; + const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null; + const openProjectCwd = + currentProjectId && currentProjectEnvironmentId + ? (projects.find( + (project) => + project.id === currentProjectId && + project.environmentId === currentProjectEnvironmentId, + )?.cwd ?? null) + : null; + // Taken when the dialog opens, so a route change behind it (the desktop + // menu's Back) cannot move where a relative path lands. + const [relativeBase] = useState(() => + currentProjectEnvironmentId && openProjectCwd + ? { environmentId: currentProjectEnvironmentId, cwd: openProjectCwd } + : null, + ); + const currentProjectCwdForBrowse = + relativeBase && browseEnvironmentId === relativeBase.environmentId ? relativeBase.cwd : null; + const relativePathNeedsActiveProject = + isExplicitRelativeProjectPath(query.trim()) && currentProjectCwdForBrowse === null; + const browseDirectoryPath = isBrowsing ? getBrowseDirectoryPath(query) : ""; + const browseFilterQuery = + isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : ""; + + const fetchBrowseResult = useCallback( + async (partialPath: string) => { + if (!browseEnvironmentId) return null; + const api = readEnvironmentApi(browseEnvironmentId); + if (!api) return null; + return api.filesystem.browse({ + partialPath, + ...(currentProjectCwdForBrowse ? { cwd: currentProjectCwdForBrowse } : {}), + }); + }, + [browseEnvironmentId, currentProjectCwdForBrowse], + ); + + const { data: browseResult, isPending: isBrowsePending } = useQuery({ + queryKey: [ + "filesystemBrowse", + browseEnvironmentId, + browseDirectoryPath, + currentProjectCwdForBrowse, + ], + queryFn: () => fetchBrowseResult(browseDirectoryPath), + staleTime: BROWSE_STALE_TIME_MS, + enabled: + isBrowsing && + browseDirectoryPath.length > 0 && + browseEnvironmentId !== null && + !relativePathNeedsActiveProject, + }); + const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES; + const { + filteredEntries: filteredBrowseEntries, + highlightedEntry: highlightedBrowseEntry, + exactEntry: exactBrowseEntry, + } = useMemo( + () => filterBrowseEntries({ browseEntries, browseFilterQuery, highlightedItemValue }), + [browseEntries, browseFilterQuery, highlightedItemValue], + ); + const isGitHubRepositorySelectionStep = + addProjectCloneFlow?.step === "repository" && addProjectCloneFlow.source === "github"; + const gitHubRepositorySelectionEnvironmentId = isGitHubRepositorySelectionStep + ? addProjectCloneFlow.environmentId + : null; + const gitHubRepositoriesQuery = useQuery({ + queryKey: [ + "sourceControlRepositories", + gitHubRepositorySelectionEnvironmentId, + "github", + GITHUB_REPOSITORY_LIST_LIMIT, + ], + queryFn: async () => { + if (!gitHubRepositorySelectionEnvironmentId) { + return { repositories: [] }; + } + const api = readEnvironmentApi(gitHubRepositorySelectionEnvironmentId); + if (!api) { + return { repositories: [] }; + } + return api.sourceControl.listRepositories({ + provider: "github", + limit: GITHUB_REPOSITORY_LIST_LIMIT, + }); + }, + staleTime: GITHUB_REPOSITORY_LIST_STALE_TIME_MS, + enabled: gitHubRepositorySelectionEnvironmentId !== null, + }); + + const prefetchBrowsePath = useCallback( + (partialPath: string) => { + void queryClient.prefetchQuery({ + queryKey: [ + "filesystemBrowse", + browseEnvironmentId, + partialPath, + currentProjectCwdForBrowse, + ], + queryFn: () => fetchBrowseResult(partialPath), + staleTime: BROWSE_STALE_TIME_MS, + }); + }, + [browseEnvironmentId, currentProjectCwdForBrowse, fetchBrowseResult, queryClient], + ); + + // Prefetch the parent and the most likely next child so browse navigation + // stays warm without scanning every child directory in large trees. + useEffect(() => { + if (!isBrowsing || filteredBrowseEntries.length === 0) return; + + if (canNavigateUp(query)) { + prefetchBrowsePath(getBrowseParentPath(query)!); + } + + const nextChild = highlightedBrowseEntry ?? exactBrowseEntry; + if (nextChild) { + prefetchBrowsePath(appendBrowsePathSegment(query, nextChild.name)); + } + }, [ + exactBrowseEntry, + filteredBrowseEntries.length, + highlightedBrowseEntry, + isBrowsing, + prefetchBrowsePath, + query, + ]); + + const pushView = useCallback((view: AddProjectView): void => { + setViewStack((previousViews) => [...previousViews, view]); + setHighlightedItemValue(null); + setQuery(view.initialQuery ?? ""); + }, []); + + function popView(): void { + if (viewStack.length <= 1) { + return; + } + setAddProjectCloneFlow(null); + setViewStack((previousViews) => previousViews.slice(0, -1)); + setHighlightedItemValue(null); + setQuery(""); + } + + function handleQueryChange(nextQuery: string): void { + setHighlightedItemValue(null); + setQuery(nextQuery); + if (nextQuery === "" && currentView?.initialQuery && isSubmenu) { + popView(); + } + } + + const startAddProjectBrowse = useCallback( + (environmentId: EnvironmentId): void => { + setAddProjectCloneFlow(null); + const initialQuery = getAddProjectInitialQueryForEnvironment(environmentId); + setViewStack((previousViews) => [ + ...previousViews, + { + addonIcon: , + groups: [], + initialQuery, + environmentId, + }, + ]); + setHighlightedItemValue(null); + setQuery(initialQuery); + }, + [getAddProjectInitialQueryForEnvironment], + ); + + const startAddProjectClone = useCallback( + (environmentId: EnvironmentId, source: AddProjectRemoteSource): void => { + setAddProjectCloneFlow({ step: "repository", environmentId, source }); + setViewStack((previousViews) => [ + ...previousViews, + { + addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS), + groups: [], + initialQuery: "", + environmentId, + }, + ]); + setHighlightedItemValue(null); + setQuery(""); + }, + [], + ); + + const openSourceControlSettings = useCallback(() => { + closeDialog(); + void navigate({ to: "/settings/source-control" }); + }, [closeDialog, navigate]); + + const buildAddProjectSourceGroups = useCallback( + ( + environmentId: EnvironmentId, + readinessBySource: AddProjectRemoteSourceReadiness, + ): CommandPaletteView["groups"] => { + const sourceItems: Array = [ + { + kind: "action", + value: `action:add-project:${environmentId}:local`, + searchTerms: ["local", "folder", "directory", "browse"], + title: "Local folder", + description: "Browse a folder on disk", + icon: , + keepOpen: true, + run: async () => { + startAddProjectBrowse(environmentId); + }, + }, + ]; + + const orderedSources: ReadonlyArray = [ + "url", + ...sortAddProjectProviderSources(readinessBySource), + ]; + + for (const source of orderedSources) { + const label = remoteProjectSourceLabel(source); + const title = source === "url" ? "Git URL" : `${label} repository`; + const description = + source === "url" + ? "Clone from a remote URL" + : `Clone ${label} ${remoteProjectSourcePathHint(source)}`; + const readiness = readinessBySource[source]; + const disabledHint = readiness.hint; + + const titleTrailingContent = readiness.ready ? undefined : ( + + + { + openSourceControlSettings(); + }} + > + Setup Required + + } + /> + + {disabledHint ?? "Open Settings -> Source Control to configure this provider."} + + + + ); + + if (!readiness.ready) { + sourceItems.push({ + kind: "action", + value: `action:add-project:${environmentId}:${source}:not-ready`, + searchTerms: ["clone", "remote", "repository", "repo", "git", label, "setup required"], + title, + description, + disabled: true, + icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS), + ...(titleTrailingContent ? { titleTrailingContent } : {}), + run: async () => {}, + }); + continue; + } + + sourceItems.push({ + kind: "action", + value: `action:add-project:${environmentId}:${source}`, + searchTerms: ["clone", "remote", "repository", "repo", "git", label], + title, + description, + icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS), + ...(titleTrailingContent ? { titleTrailingContent } : {}), + keepOpen: true, + run: async () => { + startAddProjectClone(environmentId, source); + }, + }); + } + + return [{ value: `sources:${environmentId}`, label: "Sources", items: sourceItems }]; + }, + [openSourceControlSettings, startAddProjectBrowse, startAddProjectClone], + ); + + const startAddProjectSourceSelection = useCallback( + (environmentId: EnvironmentId): void => { + setAddProjectCloneFlow(null); + const target = { environmentId }; + const initialDiscovery = getSourceControlDiscoverySnapshot(target).data; + setViewStack((previousViews) => [ + ...previousViews, + { + addonIcon: , + groups: buildAddProjectSourceGroups( + environmentId, + buildAddProjectRemoteSourceReadiness(initialDiscovery), + ), + environmentId, + }, + ]); + setHighlightedItemValue(null); + setQuery(""); + + if (initialDiscovery) { + return; + } + + void refreshSourceControlDiscovery(target).then((discovery) => { + if (!discovery) { + return; + } + setViewStack((previousViews) => { + const currentTopView = previousViews.at(-1); + if (currentTopView?.groups[0]?.value !== `sources:${environmentId}`) { + return previousViews; + } + return [ + ...previousViews.slice(0, -1), + { + ...currentTopView, + groups: buildAddProjectSourceGroups( + environmentId, + buildAddProjectRemoteSourceReadiness(discovery), + ), + }, + ]; + }); + }); + }, + [buildAddProjectSourceGroups], + ); + + // The first step, once the computer list is in: straight to browsing for a + // path from the palette, the sources for a computer the caller chose or the + // only one there is, or the list of computers. Computers arrive a beat after + // the app can open this dialog, so it waits for them instead of dead-ending + // on an empty list. A hosted page knows at once that none is coming and + // shows the pairing guidance instead. + const [savedComputersLoaded, setSavedComputersLoaded] = useState( + hasSavedEnvironmentRegistryHydrated, + ); + useEffect(() => { + if (savedComputersLoaded) return; + let cancelled = false; + const markLoaded = () => { + if (!cancelled) setSavedComputersLoaded(true); + }; + void waitForSavedEnvironmentRegistryHydration().then(markLoaded, markLoaded); + return () => { + cancelled = true; + }; + }, [savedComputersLoaded]); + const startedRef = useRef(false); + useLayoutEffect(() => { + if (startedRef.current || !savedComputersLoaded) { + return; + } + if (addProjectEnvironmentOptions.length === 0 && !isHostedStaticApp()) { + return; + } + startedRef.current = true; + + const lockedEnvironmentId = session.selection?.environmentId ?? null; + if (session.initialPath !== null && defaultAddProjectEnvironmentId) { + pushView({ + addonIcon: , + groups: [], + initialQuery: session.initialPath, + environmentId: lockedEnvironmentId, + }); + return; + } + if (lockedEnvironmentId) { + startAddProjectSourceSelection(lockedEnvironmentId); + return; + } + if (addProjectEnvironmentOptions.length > 1) { + pushView({ + addonIcon: , + groups: [ + { + value: "environments", + label: "Environments", + items: addProjectEnvironmentOptions.map((option) => ({ + kind: "action", + value: `action:add-project:environment:${option.environmentId}`, + searchTerms: [ + option.label, + option.environmentId, + option.isPrimary ? "this device" : "", + ], + title: option.label, + description: option.isPrimary ? "This device" : option.environmentId, + icon: , + keepOpen: true, + run: async () => { + startAddProjectSourceSelection(option.environmentId); + }, + })), + }, + ], + environmentId: null, + }); + return; + } + if (defaultAddProjectEnvironmentId) { + startAddProjectSourceSelection(defaultAddProjectEnvironmentId); + return; + } + + const guidance = resolveAddProjectUnavailableGuidance({ isHostedStatic: isHostedStaticApp() }); + const guidanceAction = guidance.action; + closeDialog(); + toastManager.add( + stackedThreadToast({ + type: guidance.type, + title: guidance.title, + description: guidance.description, + ...(guidanceAction + ? { + actionProps: { + children: guidanceAction.label, + onClick: () => { + void navigate({ to: guidanceAction.to }); + }, + }, + actionVariant: "outline" as const, + } + : {}), + }), + ); + }, [ + addProjectEnvironmentOptions, + closeDialog, + defaultAddProjectEnvironmentId, + navigate, + pushView, + savedComputersLoaded, + session, + startAddProjectSourceSelection, + ]); + + // Opens a project: its latest thread, or a new one. Read when it runs, so + // the button on a late "Added" notice still finds the newest thread. + const openProject = useCallback( + async (projectRef: ScopedProjectRef): Promise => { + const latestThread = getLatestThreadForProject( + selectSidebarThreadsAcrossEnvironments(useStore.getState()).filter( + (thread) => thread.environmentId === projectRef.environmentId, + ), + projectRef.projectId, + ); + if (latestThread) { + await navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams( + scopeThreadRef(latestThread.environmentId, latestThread.id), + ), + }); + return; + } + await handleNewThread(projectRef).catch(() => undefined); + }, + [handleNewThread, navigate], + ); + + const handleAddProject = useCallback( + async (rawCwd: string) => { + if (!browseEnvironmentId) return; + const api = readEnvironmentApi(browseEnvironmentId); + if (!api) return; + + if (isUnsupportedWindowsProjectPath(rawCwd.trim(), browseEnvironmentPlatform)) { + toastManager.add( + failureNotice({ + title: "Couldn't add the project", + reason: "Windows-style paths are only supported on Windows.", + }), + ); + return; + } + + if (isExplicitRelativeProjectPath(rawCwd.trim()) && !currentProjectCwdForBrowse) { + toastManager.add( + failureNotice({ + title: "Couldn't add the project", + reason: "Relative paths require an active project.", + }), + ); + return; + } + + const cwd = resolveProjectPathForDispatch(rawCwd, currentProjectCwdForBrowse); + if (cwd.length === 0) return; + + const existing = findProjectByPath( + projects.filter((project) => project.environmentId === browseEnvironmentId), + cwd, + ); + if (existing) { + const existingRef = scopeProjectRef(existing.environmentId, existing.id); + await finishAddProject({ + session, + projectRef: existingRef, + openProject: () => openProject(existingRef), + announce: (open) => announceProjectAdded(existing.name, open), + }); + return; + } + + try { + const projectId = newProjectId(); + const title = inferProjectTitleFromPath(cwd); + await api.orchestration.dispatchCommand({ + type: "project.create", + commandId: newCommandId(), + projectId, + title, + workspaceRoot: cwd, + createWorkspaceRootIfMissing: true, + // Keep newly added projects on the provider's live default until + // the user explicitly chooses a project/thread model. + defaultModelSelection: null, + createdAt: new Date().toISOString(), + }); + const createdProjectRef = scopeProjectRef(browseEnvironmentId, projectId); + // A repository added with worktrees already in it lays them out for + // picking on the screen that opens next (worktree pickup). + useWorktreePickupStore.getState().offer(scopedProjectKey(createdProjectRef)); + // Let the created project reach the store first so the draft is keyed + // to the project's real identity. If it does not arrive in time the + // draft is adopted (re-keyed) on the next new-thread call instead. + await waitForProjectInStore(createdProjectRef); + await finishAddProject({ + session, + projectRef: createdProjectRef, + openProject: () => openProject(createdProjectRef), + announce: (open) => announceProjectAdded(title, open), + }); + } catch (error) { + toastManager.add( + failureNotice({ + title: "Couldn't add the project", + error, + }), + ); + } + }, + [ + browseEnvironmentId, + browseEnvironmentPlatform, + currentProjectCwdForBrowse, + openProject, + projects, + session, + ], + ); + + const continueAddProjectCloneFlowWithRepository = useCallback( + ( + flow: Extract, + input: { + readonly repositoryInput: string; + readonly repository: SourceControlRepositoryInfo | null; + readonly remoteUrl: string; + }, + ): void => { + const destinationPath = getAddProjectInitialQueryForEnvironment(flow.environmentId); + setAddProjectCloneFlow({ + step: "confirm", + environmentId: flow.environmentId, + source: flow.source, + repositoryInput: input.repositoryInput, + repository: input.repository, + remoteUrl: input.remoteUrl, + }); + setHighlightedItemValue(null); + setQuery(destinationPath); + setBrowseGeneration((generation) => generation + 1); + }, + [getAddProjectInitialQueryForEnvironment], + ); + + async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise { + if (!addProjectCloneFlow) { + return; + } + + const api = readEnvironmentApi(addProjectCloneFlow.environmentId); + if (!api) { + addComputerNotConnectedNotice({ + environmentId: addProjectCloneFlow.environmentId, + failure: "Couldn't clone the project", + }); + return; + } + + if (addProjectCloneFlow.step === "repository") { + const rawRepository = query.trim(); + if (rawRepository.length === 0 || isRemoteProjectLookingUp) { + return; + } + + const provider = remoteProjectSourceProvider(addProjectCloneFlow.source); + if (!provider) { + continueAddProjectCloneFlowWithRepository(addProjectCloneFlow, { + repositoryInput: rawRepository, + repository: null, + remoteUrl: rawRepository, + }); + return; + } + + setIsRemoteProjectLookingUp(true); + try { + const repository = await api.sourceControl.lookupRepository({ + provider, + repository: rawRepository, + }); + if (cloneFlowRef.current !== addProjectCloneFlow) { + return; + } + continueAddProjectCloneFlowWithRepository(addProjectCloneFlow, { + repositoryInput: rawRepository, + repository, + remoteUrl: repository.url, + }); + } catch (error) { + toastManager.add( + failureNotice({ + title: "Couldn't find the repository", + reason: errorMessage(error), + }), + ); + } finally { + setIsRemoteProjectLookingUp(false); + } + return; + } + + const rawDestination = (destinationPathInput ?? query).trim(); + if (rawDestination.length === 0 || isRemoteProjectCloning) { + return; + } + + if (isUnsupportedWindowsProjectPath(rawDestination, browseEnvironmentPlatform)) { + toastManager.add( + failureNotice({ + title: "Couldn't clone the project", + reason: "Windows-style paths are only supported on Windows.", + }), + ); + return; + } + + if (isExplicitRelativeProjectPath(rawDestination) && !currentProjectCwdForBrowse) { + toastManager.add( + failureNotice({ + title: "Couldn't clone the project", + reason: "Relative paths require an active project.", + }), + ); + return; + } + + const cloneDirectoryName = getAddProjectCloneDirectoryName(addProjectCloneFlow); + const destinationPath = resolveCloneDestinationPathForDispatch({ + destinationPath: rawDestination, + repositoryDirectoryName: cloneDirectoryName, + cwd: currentProjectCwdForBrowse, + }); + if (destinationPath.length === 0) { + return; + } + + setIsRemoteProjectCloning(true); + try { + const provider = remoteProjectSourceProvider(addProjectCloneFlow.source); + // As a mutation, so the new folder reads as busy until the clone lands. + const result = await runGitMutation( + queryClient, + gitCloneRepositoryMutationOptions({ environmentId: addProjectCloneFlow.environmentId }), + { + remoteUrl: addProjectCloneFlow.remoteUrl, + destinationPath, + ...(provider ? { provider } : {}), + }, + ); + // This session's handler: the clone's result belongs to the session + // that started it, even if the dialog closed or reopened meanwhile. + await handleAddProject(result.cwd); + } catch (error) { + toastManager.add( + failureNotice({ + title: "Couldn't clone the project", + reason: errorMessage(error), + }), + ); + } finally { + setIsRemoteProjectCloning(false); + } + } + + function browseTo(name: string): void { + const nextQuery = appendBrowsePathSegment(query, name); + setHighlightedItemValue(null); + setQuery(nextQuery); + setBrowseGeneration((generation) => generation + 1); + } + + function browseUp(): void { + const parentPath = getBrowseParentPath(query); + if (parentPath === null) { + return; + } + + setHighlightedItemValue(null); + setQuery(parentPath); + setBrowseGeneration((generation) => generation + 1); + } + + // Resolve the add-project path from browse data when available. When the + // query has a trailing separator (e.g. "~/projects/foo/"), parentPath is the + // directory itself. Otherwise the user typed a partial leaf name, so we need + // the exact browse entry's fullPath or fall back to the raw query. + const resolvedAddProjectPath = hasTrailingPathSeparator(query) + ? (browseResult?.parentPath ?? query.trim()) + : (exactBrowseEntry?.fullPath ?? query.trim()); + + const canBrowseUp = + isBrowsing && !relativePathNeedsActiveProject && canNavigateUp(browseDirectoryPath); + + const browseGroups = buildBrowseGroups({ + browseEntries: filteredBrowseEntries, + browseQuery: query, + canBrowseUp, + upIcon: , + directoryIcon: , + browseUp, + browseTo, + }); + const cloneDestinationBrowseGroups = useMemo( + () => + browseGroups.map((group) => + group.value === "directories" ? { ...group, label: "Select where to clone" } : group, + ), + [browseGroups], + ); + const gitHubRepositorySuggestionGroups = useMemo(() => { + if (!isGitHubRepositorySelectionStep || addProjectCloneFlow?.step !== "repository") { + return []; + } + + const repositories = gitHubRepositoriesQuery.data?.repositories ?? []; + const items: CommandPaletteActionItem[] = repositories + .filter((repository) => + sourceControlRepositoryComparisonKeys(repository).every( + (key) => !existingGitHubRepositoryKeys.has(key), + ), + ) + .map((repository) => ({ + kind: "action", + value: `github-repository:${repository.nameWithOwner}`, + searchTerms: [repository.nameWithOwner, repository.url, repository.sshUrl, "github"], + title: repository.nameWithOwner, + description: repository.url, + icon: , + keepOpen: true, + run: async () => { + if (addProjectCloneFlow?.step !== "repository") { + return; + } + continueAddProjectCloneFlowWithRepository(addProjectCloneFlow, { + repositoryInput: repository.nameWithOwner, + repository, + remoteUrl: repository.url, + }); + }, + })); + + return items.length > 0 + ? [{ value: "github-repositories", label: "GitHub repositories", items }] + : []; + }, [ + addProjectCloneFlow, + continueAddProjectCloneFlowWithRepository, + existingGitHubRepositoryKeys, + gitHubRepositoriesQuery.data?.repositories, + isGitHubRepositorySelectionStep, + ]); + const filteredGitHubRepositorySuggestionGroups = useMemo( + () => + filterCommandPaletteGroups({ + activeGroups: gitHubRepositorySuggestionGroups, + query: deferredQuery, + isInSubmenu: true, + projectSearchItems: [], + threadSearchItems: [], + }), + [deferredQuery, gitHubRepositorySuggestionGroups], + ); + const filteredViewGroups = useMemo( + () => + filterCommandPaletteGroups({ + activeGroups: currentView?.groups ?? [], + query: deferredQuery, + isInSubmenu: true, + projectSearchItems: [], + threadSearchItems: [], + }), + [currentView?.groups, deferredQuery], + ); + + const remoteProjectContext = useMemo(() => { + if (addProjectCloneFlow?.step !== "confirm") { + return null; + } + + return { + title: addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.repositoryInput, + description: addProjectCloneFlow.repository?.url ?? addProjectCloneFlow.remoteUrl, + icon: remoteProjectSourceIcon(addProjectCloneFlow.source, ITEM_ICON_CLASS), + }; + }, [addProjectCloneFlow]); + + let displayedGroups: CommandPaletteView["groups"] = filteredViewGroups; + if (addProjectCloneFlow?.step === "repository") { + displayedGroups = isGitHubRepositorySelectionStep + ? filteredGitHubRepositorySuggestionGroups + : []; + } else if (addProjectCloneFlow?.step === "confirm") { + displayedGroups = relativePathNeedsActiveProject ? [] : cloneDestinationBrowseGroups; + } else if (isBrowsing) { + displayedGroups = relativePathNeedsActiveProject ? [] : browseGroups; + } + + const inputPlaceholder = + remoteProjectInputPlaceholder(addProjectCloneFlow) ?? + currentView?.inputPlaceholder ?? + (isBrowsing || currentView?.initialQuery ? ADD_PROJECT_PATH_PLACEHOLDER : "Search..."); + const commandResultsLoading = + viewStack.length === 0 || + (isGitHubRepositorySelectionStep && gitHubRepositoriesQuery.isPending); + const hasHighlightedBrowseItem = highlightedItemValue?.startsWith("browse:") ?? false; + const hasHighlightedRemoteRepositoryItem = + highlightedItemValue?.startsWith("github-repository:") ?? false; + const canSubmitBrowsePath = isBrowsing && !relativePathNeedsActiveProject; + const willCreateProjectPath = + canSubmitBrowsePath && + !isBrowsePending && + query.trim().length > 0 && + !hasHighlightedBrowseItem && + (hasTrailingPathSeparator(query) ? !browseResult : exactBrowseEntry === null); + const useMetaForMod = isMacPlatform(navigator.platform); + const submitModifierLabel = useMetaForMod ? "⌘" : "Ctrl"; + const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm"; + const submitActionLabel = isCloneDestinationStep + ? willCreateProjectPath + ? "Create & Clone" + : "Clone" + : willCreateProjectPath + ? "Create & Add" + : "Add"; + const addShortcutLabel = hasHighlightedBrowseItem ? `${submitModifierLabel} Enter` : "Enter"; + const remoteProjectButtonLabel = addProjectCloneFlow + ? addProjectCloneFlow.source === "url" + ? "Continue" + : "Lookup" + : null; + const isRemoteProjectPending = isRemoteProjectLookingUp || isRemoteProjectCloning; + const canSubmitRemoteProjectFlow = + addProjectCloneFlow?.step === "repository" && + query.trim().length > 0 && + !isRemoteProjectPending; + const remoteProjectRepositoryEmptyStateMessage = + addProjectCloneFlow?.step === "repository" + ? addProjectCloneFlow.source === "url" + ? "Enter a Git clone URL and press Enter to continue." + : isGitHubRepositorySelectionStep + ? gitHubRepositoriesQuery.isPending + ? "Loading GitHub repositories..." + : gitHubRepositoriesQuery.isError + ? "Could not load GitHub repositories. Enter owner/repo and press Enter to look it up." + : query.trim().length > 0 + ? "No matching GitHub repositories. Press Enter to look up owner/repo." + : "No unadded GitHub repositories found. Enter owner/repo and press Enter to look it up." + : "Enter a repository path and press Enter to look it up." + : null; + // Only the desktop app offers its folder picker, and only for the primary + // computer, so the shared file manager name (that computer's) is this one's. + const canOpenProjectFromFileManager = + isBrowsing && + browseEnvironmentId !== null && + primaryEnvironmentId !== null && + browseEnvironmentId === primaryEnvironmentId && + typeof window !== "undefined" && + window.desktopBridge !== undefined; + const fileManagerInitialPath = useMemo(() => { + if (!canOpenProjectFromFileManager) { + return undefined; + } + + const trimmedQuery = query.trim(); + if (trimmedQuery.length === 0) { + return undefined; + } + + const initialPath = hasTrailingPathSeparator(query) + ? (browseResult?.parentPath ?? trimmedQuery) + : browseDirectoryPath || trimmedQuery; + + const resolvedPath = resolveProjectPathForDispatch(initialPath, currentProjectCwdForBrowse); + return resolvedPath.length > 0 ? resolvedPath : undefined; + }, [ + browseDirectoryPath, + browseResult?.parentPath, + canOpenProjectFromFileManager, + currentProjectCwdForBrowse, + query, + ]); + + function isPrimaryModifierPressed(event: KeyboardEvent): boolean { + return useMetaForMod ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey; + } + + function handleKeyDown(event: KeyboardEvent): void { + if (addProjectCloneFlow?.step === "repository" && event.key === "Enter") { + if (hasHighlightedRemoteRepositoryItem) { + return; + } + event.preventDefault(); + void submitAddProjectCloneFlow(); + return; + } + + const shouldSubmitBrowsePath = + canSubmitBrowsePath && + event.key === "Enter" && + (!hasHighlightedBrowseItem || isPrimaryModifierPressed(event)); + + if (shouldSubmitBrowsePath) { + event.preventDefault(); + if (isCloneDestinationStep) { + void submitAddProjectCloneFlow(resolvedAddProjectPath); + } else { + void handleAddProject(resolvedAddProjectPath); + } + return; + } + + if (event.key === "Backspace" && query === "" && isSubmenu) { + event.preventDefault(); + popView(); + } + } + + function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void { + if (item.disabled) { + return; + } + if (item.kind === "submenu") { + pushView({ + addonIcon: item.addonIcon, + groups: item.groups, + ...(item.initialQuery ? { initialQuery: item.initialQuery } : {}), + environmentId: currentView?.environmentId ?? null, + }); + return; + } + if (!item.keepOpen) { + closeDialog(); + } + void item.run().catch((error: unknown) => { + toastManager.add( + failureNotice({ + title: "Couldn't run the command", + error, + }), + ); + }); + } + + const handleOpenProjectFromFileManager = useCallback(async () => { + if (!canOpenProjectFromFileManager || isPickingProjectFolder) { + return; + } + const api = readLocalApi(); + if (!api) { + return; + } + + setIsPickingProjectFolder(true); + let pickedPath: string | null = null; + try { + pickedPath = await api.dialogs.pickFolder( + fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : undefined, + ); + } catch { + // Ignore picker failures and leave the dialog open. + setIsPickingProjectFolder(false); + return; + } + setIsPickingProjectFolder(false); + if (!pickedPath) { + return; + } + await handleAddProject(pickedPath); + }, [ + canOpenProjectFromFileManager, + fileManagerInitialPath, + handleAddProject, + isPickingProjectFolder, + ]); + + return ( + resolveDialogReturnFocus(session.returnFocus)} + onBackdropPointerDown={closeDialog} + > + { + setHighlightedItemValue(typeof value === "string" ? value : null); + }} + onValueChange={handleQueryChange} + value={query} + > +
+ + + + ) : ( + + ) + } + onKeyDown={handleKeyDown} + /> + {addProjectCloneFlow?.step === "repository" ? ( + + ) : isBrowsing ? ( + + ) : null} +
+ + {remoteProjectContext ? ( +
+
+ Repository +
+
+ {remoteProjectContext.icon} + + + {remoteProjectContext.title} + + + {remoteProjectContext.description} + + +
+
+ ) : null} + +
+ +
+ + + + + + + + Navigate + + {addProjectCloneFlow?.step === "repository" ? ( + + Enter + + {remoteProjectButtonLabel ?? "Continue"} + + + ) : !canSubmitBrowsePath || hasHighlightedBrowseItem ? ( + + Enter + Select + + ) : null} + {isSubmenu ? ( + + Backspace + Back + + ) : null} + + Esc + Close + +
+ {canOpenProjectFromFileManager ? ( + + ) : null} +
+
+
+ ); +} diff --git a/apps/web/src/components/addProject/addProject.logic.test.ts b/apps/web/src/components/addProject/addProject.logic.test.ts new file mode 100644 index 000000000..9eb7148bb --- /dev/null +++ b/apps/web/src/components/addProject/addProject.logic.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveAddProjectUnavailableGuidance } from "./addProject.logic"; + +describe("resolveAddProjectUnavailableGuidance", () => { + it("routes an unpaired hosted visitor to Devices instead of reporting a failure", () => { + const guidance = resolveAddProjectUnavailableGuidance({ isHostedStatic: true }); + + expect(guidance.type).toBe("warning"); + expect(guidance.title).toBe("Pair a computer to add projects"); + expect(guidance.action).toEqual({ label: "Open Connections", to: "/settings/connections" }); + }); + + it("keeps the plain error for a desktop session that really has no environment", () => { + expect(resolveAddProjectUnavailableGuidance({ isHostedStatic: false })).toEqual({ + type: "error", + title: "Can't browse projects", + description: "No computer is available.", + action: null, + }); + }); +}); diff --git a/apps/web/src/components/addProject/addProject.logic.ts b/apps/web/src/components/addProject/addProject.logic.ts new file mode 100644 index 000000000..23196213c --- /dev/null +++ b/apps/web/src/components/addProject/addProject.logic.ts @@ -0,0 +1,118 @@ +import { type FilesystemBrowseEntry } from "@threadlines/contracts"; +import { type ReactNode } from "react"; + +import { type CommandPaletteActionItem, type CommandPaletteGroup } from "../CommandPalette.logic"; +import { + CONNECTIONS_SETTINGS_SECTION_PATH, + type SettingsSectionPath, +} from "../settings/settingsPaths"; + +/** What the Add project field asks for while it browses folders. */ +export const ADD_PROJECT_PATH_PLACEHOLDER = "Enter path (e.g. ~/projects/my-app)"; + +export function filterBrowseEntries(input: { + browseEntries: ReadonlyArray; + browseFilterQuery: string; + highlightedItemValue: string | null; +}): { + filteredEntries: FilesystemBrowseEntry[]; + highlightedEntry: FilesystemBrowseEntry | null; + exactEntry: FilesystemBrowseEntry | null; +} { + const lowerFilter = input.browseFilterQuery.toLowerCase(); + const showHidden = input.browseFilterQuery.startsWith("."); + + const filteredEntries = input.browseEntries.filter( + (entry) => + entry.name.toLowerCase().startsWith(lowerFilter) && + (showHidden || !entry.name.startsWith(".")), + ); + + let highlightedEntry: FilesystemBrowseEntry | null = null; + if (input.highlightedItemValue?.startsWith("browse:")) { + const highlightedPath = input.highlightedItemValue.slice("browse:".length); + highlightedEntry = filteredEntries.find((entry) => entry.fullPath === highlightedPath) ?? null; + } + + const exactEntry = + input.browseFilterQuery.length > 0 + ? (filteredEntries.find((entry) => entry.name === input.browseFilterQuery) ?? null) + : null; + + return { filteredEntries, highlightedEntry, exactEntry }; +} + +export function buildBrowseGroups(input: { + browseEntries: ReadonlyArray; + browseQuery: string; + canBrowseUp: boolean; + upIcon: ReactNode; + directoryIcon: ReactNode; + browseUp: () => void; + browseTo: (name: string) => void; +}): CommandPaletteGroup[] { + const items: CommandPaletteActionItem[] = []; + + if (input.canBrowseUp) { + items.push({ + kind: "action", + value: "browse:up", + searchTerms: [input.browseQuery, ".."], + title: "..", + icon: input.upIcon, + keepOpen: true, + run: async () => { + input.browseUp(); + }, + }); + } + + for (const entry of input.browseEntries) { + items.push({ + kind: "action", + value: `browse:${entry.fullPath}`, + searchTerms: [input.browseQuery, entry.fullPath, entry.name], + title: entry.name, + icon: input.directoryIcon, + keepOpen: true, + run: async () => { + input.browseTo(entry.name); + }, + }); + } + + return [{ value: "directories", label: "Directories", items }]; +} + +/** + * Copy for the add-project action when there is no environment to browse. + * + * In the hosted browser that state is not a failure, it is the setup step the + * visitor has not done yet: projects live on the paired computer, so there is + * nothing to browse until one exists. Say that and point at pairing instead of + * reporting a bare "no environment" error. A desktop session that somehow has + * no environment is a real fault, so it keeps the error wording. + */ +export function resolveAddProjectUnavailableGuidance(input: { readonly isHostedStatic: boolean }): { + readonly type: "error" | "warning"; + readonly title: string; + readonly description: string; + readonly action: { readonly label: string; readonly to: SettingsSectionPath } | null; +} { + if (!input.isHostedStatic) { + return { + type: "error", + title: "Can't browse projects", + description: "No computer is available.", + action: null, + }; + } + + return { + type: "warning", + title: "Pair a computer to add projects", + description: + "Threadlines browses projects on the computer running the desktop app. Pair one from Connections, then add a project.", + action: { label: "Open Connections", to: CONNECTIONS_SETTINGS_SECTION_PATH }, + }; +} diff --git a/apps/web/src/components/addProject/addProjectComputers.ts b/apps/web/src/components/addProject/addProjectComputers.ts new file mode 100644 index 000000000..b9eb6c782 --- /dev/null +++ b/apps/web/src/components/addProject/addProjectComputers.ts @@ -0,0 +1,112 @@ +import type { EnvironmentId } from "@threadlines/contracts"; +import { useMemo } from "react"; + +import { + readPrimaryEnvironmentDescriptor, + usePrimaryEnvironmentId, +} from "../../environments/primary"; +import { + useSavedEnvironmentRegistryStore, + useSavedEnvironmentRuntimeStore, +} from "../../environments/runtime"; +import { resolveEnvironmentOptionLabel } from "../BranchToolbar.logic"; + +export interface AddProjectEnvironmentOption { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly isPrimary: boolean; +} + +/** + * The computers a project can be added on: this one first, then the linked + * ones by name. Empty until the computer list arrives on a cold start. + */ +export function useAddProjectEnvironmentOptions(): ReadonlyArray { + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const primaryEnvironmentLabel = readPrimaryEnvironmentDescriptor()?.label ?? null; + const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((state) => state.byId); + const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId); + + return useMemo(() => { + const options: AddProjectEnvironmentOption[] = []; + const seenEnvironmentIds = new Set(); + + if (primaryEnvironmentId) { + seenEnvironmentIds.add(primaryEnvironmentId); + options.push({ + environmentId: primaryEnvironmentId, + label: resolveEnvironmentOptionLabel({ + isPrimary: true, + environmentId: primaryEnvironmentId, + runtimeLabel: primaryEnvironmentLabel, + }), + isPrimary: true, + }); + } + + for (const record of Object.values(savedEnvironmentRegistry)) { + if (seenEnvironmentIds.has(record.environmentId)) { + continue; + } + + const runtimeState = savedEnvironmentRuntimeById[record.environmentId]; + options.push({ + environmentId: record.environmentId, + label: resolveEnvironmentOptionLabel({ + isPrimary: false, + environmentId: record.environmentId, + runtimeLabel: runtimeState?.descriptor?.label ?? null, + savedLabel: record.label, + }), + isPrimary: false, + }); + } + + options.sort((left, right) => { + if (left.isPrimary !== right.isPrimary) { + return left.isPrimary ? -1 : 1; + } + return left.label.localeCompare(right.label); + }); + + return options; + }, [ + primaryEnvironmentId, + primaryEnvironmentLabel, + savedEnvironmentRegistry, + savedEnvironmentRuntimeById, + ]); +} + +function getEnvironmentBrowsePlatform(os: string | null | undefined): string { + if (os === "windows") { + return "Win32"; + } + if (os === "darwin") { + return "MacIntel"; + } + if (os === "linux") { + return "Linux"; + } + return typeof navigator === "undefined" ? "" : navigator.platform; +} + +/** + * The computer's platform in `navigator.platform` terms, which decides what + * reads as a path there (a Windows drive letter only on Windows). + */ +export function useEnvironmentBrowsePlatform(environmentId: EnvironmentId | null): string { + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId); + return useMemo(() => { + const os = + environmentId && primaryEnvironmentId && environmentId === primaryEnvironmentId + ? (readPrimaryEnvironmentDescriptor()?.platform.os ?? null) + : environmentId + ? (savedEnvironmentRuntimeById[environmentId]?.descriptor?.platform.os ?? + savedEnvironmentRuntimeById[environmentId]?.serverConfig?.environment.platform.os ?? + null) + : null; + return getEnvironmentBrowsePlatform(os); + }, [environmentId, primaryEnvironmentId, savedEnvironmentRuntimeById]); +} diff --git a/apps/web/src/components/addProject/addProjectStore.test.ts b/apps/web/src/components/addProject/addProjectStore.test.ts new file mode 100644 index 000000000..dadaa70d3 --- /dev/null +++ b/apps/web/src/components/addProject/addProjectStore.test.ts @@ -0,0 +1,80 @@ +import { EnvironmentId, ProjectId } from "@threadlines/contracts"; +import { scopeProjectRef } from "@threadlines/client-runtime"; +import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { finishAddProject, useAddProjectStore } from "./addProjectStore"; + +const PROJECT_REF = scopeProjectRef(EnvironmentId.make("environment-local"), ProjectId.make("p1")); + +function openSession(onProjectSelected?: (ref: typeof PROJECT_REF) => void) { + useAddProjectStore + .getState() + .open(onProjectSelected ? { selection: { onProjectSelected } } : undefined); + return useAddProjectStore.getState().session!; +} + +describe("add project store", () => { + beforeEach(() => { + useAddProjectStore.setState({ session: null, lastSessionId: 0 }); + }); + + it("hands a finished add to the session that started it, then closes", async () => { + const onProjectSelected = vi.fn(); + const session = openSession(onProjectSelected); + const openProject = vi.fn(async () => undefined); + const announce = vi.fn(); + + await finishAddProject({ session, projectRef: PROJECT_REF, openProject, announce }); + + expect(onProjectSelected).toHaveBeenCalledWith(PROJECT_REF); + expect(openProject).not.toHaveBeenCalled(); + expect(announce).not.toHaveBeenCalled(); + expect(useAddProjectStore.getState().session).toBeNull(); + }); + + it("opens the project and closes when nobody is picking a folder", async () => { + const session = openSession(); + const openProject = vi.fn(async () => undefined); + + await finishAddProject({ session, projectRef: PROJECT_REF, openProject, announce: vi.fn() }); + + expect(openProject).toHaveBeenCalledOnce(); + expect(useAddProjectStore.getState().session).toBeNull(); + }); + + it("leaves a replacing session alone when an older one finishes", async () => { + const firstCaller = vi.fn(); + const staleSession = openSession(firstCaller); + useAddProjectStore.getState().close(); + const secondCaller = vi.fn(); + const currentSession = openSession(secondCaller); + const openProject = vi.fn(async () => undefined); + const announce = vi.fn(); + + await finishAddProject({ + session: staleSession, + projectRef: PROJECT_REF, + openProject, + announce, + }); + + expect(firstCaller).not.toHaveBeenCalled(); + expect(secondCaller).not.toHaveBeenCalled(); + expect(openProject).not.toHaveBeenCalled(); + expect(useAddProjectStore.getState().session).toBe(currentSession); + // The user still hears what was added, with a way to open it. + expect(announce).toHaveBeenCalledWith(openProject); + }); + + it("announces instead of navigating when its session was closed", async () => { + const session = openSession(); + useAddProjectStore.getState().close(); + const openProject = vi.fn(async () => undefined); + const announce = vi.fn(); + + await finishAddProject({ session, projectRef: PROJECT_REF, openProject, announce }); + + expect(openProject).not.toHaveBeenCalled(); + expect(announce).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/web/src/components/addProject/addProjectStore.ts b/apps/web/src/components/addProject/addProjectStore.ts new file mode 100644 index 000000000..1ccd431fe --- /dev/null +++ b/apps/web/src/components/addProject/addProjectStore.ts @@ -0,0 +1,98 @@ +import type { EnvironmentId, ScopedProjectRef } from "@threadlines/contracts"; +import { create } from "zustand"; + +import { captureReturnFocus, type DialogReturnFocus } from "../../lib/dialogReturnFocus"; + +/** + * Add project opened to pick a folder for someone else (the setup screen): the + * dialog reports the project instead of opening a thread in it, and stays on + * the given computer. + */ +export interface AddProjectSelection { + readonly environmentId?: EnvironmentId; + readonly onProjectSelected: (projectRef: ScopedProjectRef) => void; +} + +export interface AddProjectOpenRequest { + readonly selection?: AddProjectSelection; + /** A path to start browsing at, from the palette's "Add project at" row. */ + readonly initialPath?: string; + /** Where focus goes when the dialog closes; the focused element by default. */ + readonly returnFocus?: DialogReturnFocus; +} + +/** One opening of the dialog. Everything it was opened with is fixed for its life. */ +export interface AddProjectSession { + readonly id: number; + readonly selection: AddProjectSelection | null; + readonly initialPath: string | null; + readonly returnFocus: DialogReturnFocus | null; +} + +interface AddProjectStore { + /** The open session, or null while the dialog is closed. */ + session: AddProjectSession | null; + lastSessionId: number; + /** Opens a new session, replacing any open one, and returns its id. */ + open: (request?: AddProjectOpenRequest) => number; + close: () => void; + /** Closes only if the given session is still the open one. */ + closeSession: (sessionId: number) => void; +} + +export const useAddProjectStore = create((set, get) => ({ + session: null, + lastSessionId: 0, + open: (request = {}) => { + const id = get().lastSessionId + 1; + set({ + lastSessionId: id, + session: { + id, + selection: request.selection ?? null, + initialPath: request.initialPath ?? null, + returnFocus: request.returnFocus ?? captureReturnFocus(), + }, + }); + return id; + }, + close: () => set({ session: null }), + closeSession: (sessionId) => + set((state) => (state.session?.id === sessionId ? { session: null } : state)), +})); + +export function openAddProject(request?: AddProjectOpenRequest): number { + return useAddProjectStore.getState().open(request); +} + +export function isAddProjectSessionOpen(sessionId: number): boolean { + return useAddProjectStore.getState().session?.id === sessionId; +} + +/** + * What happens once a project was added or found. The project exists either + * way. Only the session that started the operation, if it is still the open + * one, gets the selection callback, the navigation and the close; after it was + * closed or replaced, `announce` tells the user what was added instead, so a + * late clone never lands in another caller's flow. + */ +export async function finishAddProject(input: { + readonly session: AddProjectSession; + readonly projectRef: ScopedProjectRef; + /** Opens the project: its latest thread, or a new one. */ + readonly openProject: () => Promise; + readonly announce: (openProject: () => Promise) => void; +}): Promise { + const { session, projectRef, openProject } = input; + if (!isAddProjectSessionOpen(session.id)) { + input.announce(openProject); + return; + } + if (session.selection) { + session.selection.onProjectSelected(projectRef); + useAddProjectStore.getState().closeSession(session.id); + return; + } + await openProject(); + useAddProjectStore.getState().closeSession(session.id); +} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 4142f4193..033a860e3 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -86,7 +86,7 @@ import { import { compressImageForStash, readFileForStash } from "../../lib/stashImageCompression"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings"; import { isTerminalFocused } from "../../lib/terminalFocus"; -import { useCommandPaletteStore } from "../../commandPaletteStore"; +import { isKeyboardOwnedByDialog } from "../../commands/shortcutBlock"; import { type TerminalContextDraft, type TerminalContextSelection, @@ -2489,7 +2489,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // even when the composer is in a state that cannot stash. event.preventDefault(); event.stopPropagation(); - if (useCommandPaletteStore.getState().open || attachmentsDisabled) { + if (isKeyboardOwnedByDialog() || attachmentsDisabled) { return; } void stashCurrentPrompt(); diff --git a/apps/web/src/components/chat/ProjectCrumbMenu.tsx b/apps/web/src/components/chat/ProjectCrumbMenu.tsx index 5bf2242b4..5b37fadec 100644 --- a/apps/web/src/components/chat/ProjectCrumbMenu.tsx +++ b/apps/web/src/components/chat/ProjectCrumbMenu.tsx @@ -27,6 +27,7 @@ import { } from "../EditorOpenOptions"; import { ProjectFavicon } from "../ProjectFavicon"; import { readLocalApi } from "~/localApi"; +import { isKeyboardOwnedByDialog } from "~/commands/shortcutBlock"; /** * The project crumb in the chat header, and everything that acts on the @@ -82,7 +83,7 @@ export const ProjectCrumbMenu = memo(function ProjectCrumbMenu({ useEffect(() => { if (!canOpenInEditor) return; const handler = (event: globalThis.KeyboardEvent) => { - if (!isOpenFavoriteEditorShortcut(event, keybindings)) return; + if (isKeyboardOwnedByDialog() || !isOpenFavoriteEditorShortcut(event, keybindings)) return; if (!preferredEditor || !readLocalApi()) return; event.preventDefault(); openIn(cwd, preferredEditor); diff --git a/apps/web/src/components/codexImport/CodexSessionImportDialog.tsx b/apps/web/src/components/codexImport/CodexSessionImportDialog.tsx new file mode 100644 index 000000000..6ed14cef1 --- /dev/null +++ b/apps/web/src/components/codexImport/CodexSessionImportDialog.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { lazy, Suspense, useEffect } from "react"; + +import { CommandDialog } from "../ui/command"; +import { useCodexImportStore } from "./codexImportStore"; + +const OpenCodexSessionImportDialog = lazy(() => + import("./OpenCodexSessionImportDialog").then((module) => ({ + default: module.OpenCodexSessionImportDialog, + })), +); + +/** + * The "Bring in Codex conversation" dialog. It loads at startup but its body + * only on first open, and it mounts the body once per session. + */ +export function CodexSessionImportDialog() { + const session = useCodexImportStore((store) => store.session); + const close = useCodexImportStore((store) => store.close); + + // The store outlives this tree: a dialog left open when the shell goes away + // must not greet the next mount already open. + useEffect(() => { + return () => { + if (useCodexImportStore.getState().session !== null) { + close(); + } + }; + }, [close]); + + return ( + { + if (!open) close(); + }} + > + {session ? ( + + + + ) : null} + + ); +} diff --git a/apps/web/src/components/codexImport/OpenCodexSessionImportDialog.tsx b/apps/web/src/components/codexImport/OpenCodexSessionImportDialog.tsx new file mode 100644 index 000000000..31f21ba54 --- /dev/null +++ b/apps/web/src/components/codexImport/OpenCodexSessionImportDialog.tsx @@ -0,0 +1,473 @@ +"use client"; + +import { scopeThreadRef } from "@threadlines/client-runtime"; +import { + type ProviderExternalThreadCandidate, + type ProviderInstanceId, +} from "@threadlines/contracts"; +import { useInfiniteQuery } from "@tanstack/react-query"; +import { useDebouncedValue } from "@tanstack/react-pacer"; +import { useNavigate } from "@tanstack/react-router"; +import { + ArrowDownIcon, + ArrowLeftIcon, + ArrowUpIcon, + MessageSquareIcon, + MessagesSquareIcon, +} from "lucide-react"; +import { useCallback, useDeferredValue, useMemo, useState } from "react"; + +import { usePrimaryEnvironmentId } from "../../environments/primary"; +import { + requireEnvironmentConnection, + useSavedEnvironmentRuntimeStore, +} from "../../environments/runtime"; +import { useSettings } from "../../hooks/useSettings"; +import { resolveDialogReturnFocus } from "../../lib/dialogReturnFocus"; +import { cn, newThreadId } from "../../lib/utils"; +import { resolveAppModelSelectionForInstance } from "../../modelSelection"; +import { useServerKeybindings, useServerProviders } from "../../rpc/serverState"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import { + filterCommandPaletteGroups, + ITEM_ICON_CLASS, + type CommandPaletteActionItem, + type CommandPaletteGroup, + type CommandPaletteSubmenuItem, +} from "../CommandPalette.logic"; +import { CommandPaletteResults } from "../CommandPaletteResults"; +import { + Command, + CommandDialogPopup, + CommandFooter, + CommandInput, + CommandPanel, +} from "../ui/command"; +import { Kbd, KbdGroup } from "../ui/kbd"; +import { failureNotice, stackedThreadToast, toastManager } from "../ui/toast"; +import { + finishCodexImport, + useCodexImportStore, + type CodexImportSession, +} from "./codexImportStore"; + +const EXTERNAL_SESSION_SEARCH_DEBOUNCE_MS = 180; + +function externalSessionSourceLabel(source: ProviderExternalThreadCandidate["source"]): string { + switch (source) { + case "cli": + return "Codex CLI"; + case "vscode": + return "Codex app / IDE"; + case "exec": + return "Codex exec"; + case "appServer": + return "Codex app"; + case "unknown": + return "Codex"; + } +} + +function errorMessage(error: unknown): string { + if (error instanceof Error && error.message.trim().length > 0) { + return error.message; + } + return "An error occurred."; +} + +function candidateTitle(candidate: ProviderExternalThreadCandidate): string { + return ( + candidate.name?.trim() || + candidate.preview.trim().split(/\r?\n/, 1)[0] || + "Untitled Codex session" + ); +} + +/** Says a conversation came in after the dialog that started it went away, with a button that opens it. */ +function announceConversationBroughtIn(title: string, openThread: () => Promise): void { + toastManager.add( + stackedThreadToast({ + type: "success", + title: `Brought in ${title}`, + actionProps: { + children: "Open", + onClick: () => { + void openThread(); + }, + }, + actionVariant: "outline", + }), + ); +} + +/** + * The open "Bring in Codex conversation" dialog: pick a Codex account when + * there is more than one, then a conversation from the project's folder to + * continue here. Loaded on demand by CodexSessionImportDialog; mounted once + * per session. + */ +export function OpenCodexSessionImportDialog({ session }: { session: CodexImportSession }) { + const navigate = useNavigate(); + const keybindings = useServerKeybindings(); + const settings = useSettings(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const primaryServerProviders = useServerProviders(); + const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId); + const { project } = session; + const [query, setQuery] = useState(""); + const deferredQuery = useDeferredValue(query); + const [highlightedItemValue, setHighlightedItemValue] = useState(null); + // One account goes straight to its conversations; more show a picker first. + const [providerInstanceId, setProviderInstanceId] = useState( + session.accounts.length === 1 ? session.accounts[0]!.instanceId : null, + ); + const [importingProviderThreadId, setImportingProviderThreadId] = useState(null); + const canGoBack = providerInstanceId !== null && session.accounts.length > 1; + const closeDialog = useCallback(() => { + useCodexImportStore.getState().closeSession(session.id); + }, [session.id]); + + // The project's computer's agents and settings pick the model a brought-in + // conversation continues on. + const environmentProviders = useMemo( + () => + project.environmentId === primaryEnvironmentId + ? primaryServerProviders + : (savedEnvironmentRuntimeById[project.environmentId]?.serverConfig?.providers ?? []), + [ + primaryEnvironmentId, + primaryServerProviders, + project.environmentId, + savedEnvironmentRuntimeById, + ], + ); + const environmentSettings = useMemo(() => { + const environmentServerSettings = + project.environmentId !== primaryEnvironmentId + ? savedEnvironmentRuntimeById[project.environmentId]?.serverConfig?.settings + : null; + return environmentServerSettings ? { ...settings, ...environmentServerSettings } : settings; + }, [primaryEnvironmentId, project.environmentId, savedEnvironmentRuntimeById, settings]); + + const [externalSessionSearchQuery] = useDebouncedValue( + providerInstanceId ? deferredQuery : "", + { wait: EXTERNAL_SESSION_SEARCH_DEBOUNCE_MS }, + (debouncerState) => ({ isPending: debouncerState.isPending }), + ); + const externalSessionsQuery = useInfiniteQuery({ + queryKey: [ + "externalCodexSessions", + project.environmentId, + providerInstanceId, + project.cwd, + externalSessionSearchQuery.trim(), + ], + queryFn: async ({ pageParam }) => { + if (!providerInstanceId) { + return { data: [] }; + } + return requireEnvironmentConnection( + project.environmentId, + ).client.server.listExternalProviderThreads({ + providerInstanceId, + cwd: project.cwd, + limit: 20, + ...(typeof pageParam === "string" ? { cursor: pageParam } : {}), + ...(externalSessionSearchQuery.trim().length > 0 + ? { searchTerm: externalSessionSearchQuery.trim() } + : {}), + }); + }, + initialPageParam: undefined as string | undefined, + getNextPageParam: (lastPage) => lastPage.nextCursor, + enabled: providerInstanceId !== null, + }); + + const importExternalCodexSession = useCallback( + async (candidate: ProviderExternalThreadCandidate): Promise => { + if (!providerInstanceId || importingProviderThreadId !== null) { + return; + } + const model = resolveAppModelSelectionForInstance( + providerInstanceId, + environmentSettings, + environmentProviders, + null, + ); + if (!model) { + throw new Error("No usable model is available for this Codex account."); + } + + setImportingProviderThreadId(candidate.providerThreadId); + try { + const connection = requireEnvironmentConnection(project.environmentId); + const result = await connection.client.server.importExternalProviderThread({ + providerInstanceId, + providerThreadId: candidate.providerThreadId, + projectId: project.projectId, + threadId: newThreadId(), + modelSelection: { + instanceId: providerInstanceId, + model, + }, + runtimeMode: session.runtimeMode, + }); + const threadRef = scopeThreadRef(project.environmentId, result.threadId); + await finishCodexImport({ + sessionId: session.id, + threadRef, + openThread: async () => { + await navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), + }); + }, + announce: (open) => announceConversationBroughtIn(candidateTitle(candidate), open), + }); + } finally { + setImportingProviderThreadId(null); + } + }, + [ + environmentProviders, + environmentSettings, + importingProviderThreadId, + navigate, + project.environmentId, + project.projectId, + providerInstanceId, + session.id, + session.runtimeMode, + ], + ); + + const accountGroups = useMemo>( + () => [ + { + value: "codex-accounts", + label: "Codex accounts", + items: session.accounts.map((account) => ({ + kind: "action" as const, + value: `external-codex-account:${account.instanceId}`, + searchTerms: [account.displayName, account.instanceId, "codex", "account"], + title: account.displayName, + description: "Sessions stored by this Codex account", + icon: , + keepOpen: true, + run: async () => { + setHighlightedItemValue(null); + setQuery(""); + setProviderInstanceId(account.instanceId); + }, + })), + }, + ], + [session.accounts], + ); + + const externalCodexSessionGroups = useMemo>(() => { + if (!providerInstanceId) { + return []; + } + const candidates = externalSessionsQuery.data?.pages.flatMap((page) => page.data) ?? []; + const items: CommandPaletteActionItem[] = candidates.map((candidate) => { + const title = candidateTitle(candidate); + const source = externalSessionSourceLabel(candidate.source); + const isImporting = importingProviderThreadId === candidate.providerThreadId; + return { + kind: "action", + value: `external-codex-session:${candidate.providerThreadId}`, + searchTerms: [title, candidate.preview, source, candidate.cliVersion], + title, + description: candidate.unavailableReason ?? `${source} · ${candidate.preview}`, + icon: , + timestampAt: candidate.updatedAt, + disabled: !candidate.canImport || importingProviderThreadId !== null, + ...(isImporting + ? { + titleTrailingContent: ( + Importing… + ), + } + : {}), + keepOpen: true, + run: async () => { + await importExternalCodexSession(candidate); + }, + }; + }); + + if (externalSessionsQuery.hasNextPage) { + items.push({ + kind: "action", + value: "external-codex-session:load-more", + searchTerms: ["load more", "older", "sessions"], + title: externalSessionsQuery.isFetchingNextPage ? "Loading more…" : "Load more sessions", + description: "Fetch the next 20 conversations", + icon: , + disabled: externalSessionsQuery.isFetchingNextPage || importingProviderThreadId !== null, + keepOpen: true, + run: async () => { + await externalSessionsQuery.fetchNextPage(); + }, + }); + } + + return items.length > 0 + ? [ + { + value: "external-codex-sessions", + label: `Other Codex conversations in ${project.projectName}`, + items, + }, + ] + : []; + }, [ + providerInstanceId, + externalSessionsQuery.data?.pages, + externalSessionsQuery.fetchNextPage, + externalSessionsQuery.hasNextPage, + externalSessionsQuery.isFetchingNextPage, + importExternalCodexSession, + importingProviderThreadId, + project.projectName, + ]); + + const filteredAccountGroups = useMemo( + () => + filterCommandPaletteGroups({ + activeGroups: accountGroups, + query: deferredQuery, + isInSubmenu: true, + projectSearchItems: [], + threadSearchItems: [], + }), + [accountGroups, deferredQuery], + ); + + function goBack(): void { + if (!canGoBack) return; + setHighlightedItemValue(null); + setQuery(""); + setProviderInstanceId(null); + } + + function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void { + if (item.disabled || item.kind !== "action") { + return; + } + void item.run().catch((error: unknown) => { + toastManager.add( + failureNotice({ + title: "Couldn't run the command", + error, + }), + ); + }); + } + + return ( + resolveDialogReturnFocus(session.returnFocus)} + onBackdropPointerDown={closeDialog} + > + { + setHighlightedItemValue(typeof value === "string" ? value : null); + }} + onValueChange={(nextQuery) => { + setHighlightedItemValue(null); + setQuery(nextQuery); + }} + value={query} + > + + + + ) : ( + + ) + } + onKeyDown={(event) => { + if (event.key === "Backspace" && query === "" && canGoBack) { + event.preventDefault(); + goBack(); + } + }} + /> + + 0 + ? "No matching external Codex conversations in this project." + : "No other Codex conversations were found. Conversations already in Threadlines are hidden." + } + /> + + +
+ + + + + + + + Navigate + + + Enter + Select + + {canGoBack ? ( + + Backspace + Back + + ) : null} + + Esc + Close + +
+
+
+
+ ); +} diff --git a/apps/web/src/components/codexImport/codexImportStore.test.ts b/apps/web/src/components/codexImport/codexImportStore.test.ts new file mode 100644 index 000000000..155d791e6 --- /dev/null +++ b/apps/web/src/components/codexImport/codexImportStore.test.ts @@ -0,0 +1,58 @@ +import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@threadlines/contracts"; +import { scopeThreadRef } from "@threadlines/client-runtime"; +import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { finishCodexImport, useCodexImportStore } from "./codexImportStore"; + +const ENVIRONMENT_ID = EnvironmentId.make("environment-local"); +const THREAD_REF = scopeThreadRef(ENVIRONMENT_ID, ThreadId.make("imported")); + +function openSession(): number { + return useCodexImportStore.getState().open({ + project: { + environmentId: ENVIRONMENT_ID, + projectId: ProjectId.make("p1"), + projectName: "Project", + cwd: "/repo/project", + }, + accounts: [{ instanceId: ProviderInstanceId.make("codex"), displayName: "Codex" }], + runtimeMode: "full-access", + }); +} + +describe("codex import store", () => { + beforeEach(() => { + useCodexImportStore.setState({ session: null, lastSessionId: 0 }); + }); + + it("closes and opens the thread when its session is still open", async () => { + const sessionId = openSession(); + const openThread = vi.fn(async () => undefined); + const announce = vi.fn(); + + await finishCodexImport({ sessionId, threadRef: THREAD_REF, openThread, announce }); + + expect(openThread).toHaveBeenCalledOnce(); + expect(announce).not.toHaveBeenCalled(); + expect(useCodexImportStore.getState().session).toBeNull(); + }); + + it("does not navigate or close a newer session when an older import finishes", async () => { + const staleSessionId = openSession(); + useCodexImportStore.getState().close(); + const currentSessionId = openSession(); + const openThread = vi.fn(async () => undefined); + const announce = vi.fn(); + + await finishCodexImport({ + sessionId: staleSessionId, + threadRef: THREAD_REF, + openThread, + announce, + }); + + expect(openThread).not.toHaveBeenCalled(); + expect(useCodexImportStore.getState().session?.id).toBe(currentSessionId); + expect(announce).toHaveBeenCalledWith(openThread); + }); +}); diff --git a/apps/web/src/components/codexImport/codexImportStore.ts b/apps/web/src/components/codexImport/codexImportStore.ts new file mode 100644 index 000000000..a7ef228d5 --- /dev/null +++ b/apps/web/src/components/codexImport/codexImportStore.ts @@ -0,0 +1,97 @@ +import type { + EnvironmentId, + ProjectId, + ProviderInstanceId, + RuntimeMode, + ScopedThreadRef, +} from "@threadlines/contracts"; +import { create } from "zustand"; + +import { captureReturnFocus, type DialogReturnFocus } from "../../lib/dialogReturnFocus"; + +/** The workspace project whose other Codex conversations the dialog lists. */ +export interface CodexImportProject { + readonly environmentId: EnvironmentId; + readonly projectId: ProjectId; + readonly projectName: string; + readonly cwd: string; +} + +export interface CodexImportAccount { + readonly instanceId: ProviderInstanceId; + readonly displayName: string; +} + +export interface CodexImportOpenRequest { + readonly project: CodexImportProject; + /** The usable Codex accounts on the project's computer; more than one shows a picker first. */ + readonly accounts: ReadonlyArray; + /** The open thread's or draft's mode when the dialog opened; a brought-in thread starts in it. */ + readonly runtimeMode: RuntimeMode; + readonly returnFocus?: DialogReturnFocus; +} + +/** One opening of the dialog. Everything it was opened with is fixed for its life. */ +export interface CodexImportSession { + readonly id: number; + readonly project: CodexImportProject; + readonly accounts: ReadonlyArray; + readonly runtimeMode: RuntimeMode; + readonly returnFocus: DialogReturnFocus | null; +} + +interface CodexImportStore { + session: CodexImportSession | null; + lastSessionId: number; + /** Opens a new session, replacing any open one, and returns its id. */ + open: (request: CodexImportOpenRequest) => number; + close: () => void; + /** Closes only if the given session is still the open one. */ + closeSession: (sessionId: number) => void; +} + +export const useCodexImportStore = create((set, get) => ({ + session: null, + lastSessionId: 0, + open: (request) => { + const id = get().lastSessionId + 1; + set({ + lastSessionId: id, + session: { + id, + project: request.project, + accounts: request.accounts, + runtimeMode: request.runtimeMode, + returnFocus: request.returnFocus ?? captureReturnFocus(), + }, + }); + return id; + }, + close: () => set({ session: null }), + closeSession: (sessionId) => + set((state) => (state.session?.id === sessionId ? { session: null } : state)), +})); + +export function openCodexImport(request: CodexImportOpenRequest): number { + return useCodexImportStore.getState().open(request); +} + +/** + * What happens once a conversation was brought in. The thread exists either + * way. If the session that started the import is still open it closes and the + * thread opens; after it was closed or replaced, `announce` tells the user + * instead of moving them off whatever they went to. + */ +export async function finishCodexImport(input: { + readonly sessionId: number; + readonly threadRef: ScopedThreadRef; + readonly openThread: () => Promise; + readonly announce: (openThread: () => Promise) => void; +}): Promise { + if (useCodexImportStore.getState().session?.id !== input.sessionId) { + input.announce(input.openThread); + return; + } + useCodexImportStore.getState().closeSession(input.sessionId); + await input.openThread(); +} diff --git a/apps/web/src/components/setup/AgentSetupScreen.browser.tsx b/apps/web/src/components/setup/AgentSetupScreen.browser.tsx index a5cd331b6..9d7c7a654 100644 --- a/apps/web/src/components/setup/AgentSetupScreen.browser.tsx +++ b/apps/web/src/components/setup/AgentSetupScreen.browser.tsx @@ -21,7 +21,7 @@ import { } from "@tanstack/react-router"; import { useState, type ReactNode } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { render } from "vitest-browser-react"; import { @@ -34,6 +34,8 @@ import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/ser import { useStore } from "../../store"; import { ToastProvider } from "../ui/toast"; import { parseSetupStep } from "./agentSetup.logic"; +import { AddProjectDialog } from "../addProject/AddProjectDialog"; +import { useAddProjectStore } from "../addProject/addProjectStore"; import { AgentSetupScreen } from "./AgentSetupScreen"; import { SETUP_PROGRESS_STORAGE_KEY, useSetupProgressStore } from "./setupProgress"; import { resetTestPage } from "../../lib/testPage.browser-harness"; @@ -120,11 +122,12 @@ function SetupRoute() { return ; } -function renderSetup() { +function renderSetup(initialEntry = "/setup") { const rootRoute = createRootRoute({ component: () => ( + ), }); @@ -140,7 +143,7 @@ function renderSetup() { }); const router = createRouter({ routeTree: rootRoute.addChildren([setupRoute, indexRoute]), - history: createMemoryHistory({ initialEntries: ["/setup"] }), + history: createMemoryHistory({ initialEntries: [initialEntry] }), }); return { router, @@ -287,4 +290,23 @@ describe("AgentSetupScreen", () => { root.style.removeProperty("--workspace-controls-right"); } }); + + it("returns focus to Choose a folder when Add project closes", async () => { + setServerConfigSnapshot(serverConfig([])); + const rendered = renderSetup("/setup?step=folder"); + mounted = await rendered.mounted; + + const chooseFolder = page.getByRole("button", { name: "Choose a folder" }); + await chooseFolder.click(); + const dialog = page.getByTestId("add-project-dialog"); + await expect.element(dialog).toBeInTheDocument(); + // Picking for the setup screen: the dialog stays on this computer. + expect(useAddProjectStore.getState().session?.selection?.environmentId).toBe(ENVIRONMENT_ID); + + await userEvent.keyboard("{Escape}"); + await expect.element(dialog).not.toBeInTheDocument(); + await vi.waitFor(() => { + expect(document.activeElement).toBe(chooseFolder.element()); + }); + }); }); diff --git a/apps/web/src/components/setup/AgentSetupScreen.tsx b/apps/web/src/components/setup/AgentSetupScreen.tsx index f8762df6d..9da015737 100644 --- a/apps/web/src/components/setup/AgentSetupScreen.tsx +++ b/apps/web/src/components/setup/AgentSetupScreen.tsx @@ -21,12 +21,12 @@ import { } from "@threadlines/shared/providerAuthCommands"; import { Link, useNavigate } from "@tanstack/react-router"; import { CheckIcon, ExternalLinkIcon, FolderIcon, GitBranchIcon, LoaderIcon } from "lucide-react"; -import { useEffect, useMemo, useState, type ReactNode } from "react"; +import { useEffect, useMemo, useState, type MouseEvent, type ReactNode } from "react"; import * as Option from "effect/Option"; import { useShallow } from "zustand/react/shallow"; import { APP_BASE_NAME } from "../../branding"; -import { useCommandPaletteStore } from "../../commandPaletteStore"; +import { openAddProject } from "../addProject/addProjectStore"; import { usePrimaryEnvironmentDescriptor } from "../../environments/primary/context"; import { useNavigateBackWithinApp } from "../../hooks/useNavigateBackWithinApp"; import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; @@ -745,13 +745,16 @@ export function AgentSetupScreen({ routeStep }: { readonly routeStep: SetupStep void handleNewThread(projectRef, { replace: true }); }; - const chooseFolder = () => { - useCommandPaletteStore.getState().openAddProject({ - ...(environmentId ? { environmentId } : {}), - onProjectSelected: (selected) => { - if (!environmentId || selected.environmentId !== environmentId) return; - updateProgress(environmentId, { projectId: String(selected.projectId) }); + const chooseFolder = (event: MouseEvent) => { + openAddProject({ + selection: { + ...(environmentId ? { environmentId } : {}), + onProjectSelected: (selected) => { + if (!environmentId || selected.environmentId !== environmentId) return; + updateProgress(environmentId, { projectId: String(selected.projectId) }); + }, }, + returnFocus: event.currentTarget, }); }; diff --git a/apps/web/src/components/sidebar/ProjectScopeMenu.tsx b/apps/web/src/components/sidebar/ProjectScopeMenu.tsx index dfe71ee6c..f9a5bdc9a 100644 --- a/apps/web/src/components/sidebar/ProjectScopeMenu.tsx +++ b/apps/web/src/components/sidebar/ProjectScopeMenu.tsx @@ -191,7 +191,8 @@ export interface ProjectScopeMenuProps { sort: InboxSort; onSortChange: (sort: InboxSort) => void; onResetCustomOrder: () => void; - onAddProject: () => void; + /** `opener` is where focus returns when Add project closes. */ + onAddProject: (opener?: HTMLElement) => void; /** * A new-thread button at the row's end, on a phone. Null on a wide screen, * where the rail's New thread is the one. @@ -863,7 +864,7 @@ export const ProjectScopeMenu = memo(function ProjectScopeMenu(props: ProjectSco {searching ? null : ( <> - + onAddProject()}> Add project… @@ -907,7 +908,7 @@ export const ProjectScopeMenu = memo(function ProjectScopeMenu(props: ProjectSco aria-label="Add project" data-testid="sidebar-add-project-trigger" className="inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-sidebar-accent/60 hover:text-foreground focus-ring" - onClick={onAddProject} + onClick={(event) => onAddProject(event.currentTarget)} /> } > diff --git a/apps/web/src/components/terminals/TerminalsPage.tsx b/apps/web/src/components/terminals/TerminalsPage.tsx index ea22ae444..09b6c653e 100644 --- a/apps/web/src/components/terminals/TerminalsPage.tsx +++ b/apps/web/src/components/terminals/TerminalsPage.tsx @@ -30,7 +30,7 @@ import { useLocalStorage } from "../../hooks/useLocalStorage"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings"; import { isTerminalFocused } from "../../lib/terminalFocus"; import { cn, randomUUID } from "../../lib/utils"; -import { useCommandPaletteStore } from "../../commandPaletteStore"; +import { isKeyboardOwnedByDialog } from "../../commands/shortcutBlock"; import { useServerKeybindings } from "../../rpc/serverState"; import { selectWorkspaceProjectsAcrossEnvironments, useStore } from "../../store"; import { type TerminalCommandKind, useTerminalCommandsStore } from "../../terminalCommands"; @@ -552,7 +552,7 @@ function ComputerTerminals({ }); useEffect(() => { const handler = (event: KeyboardEvent) => { - if (useCommandPaletteStore.getState().open || event.defaultPrevented) return; + if (isKeyboardOwnedByDialog() || event.defaultPrevented) return; const command = resolveShortcutCommand(event, keybindings, { context: { terminalFocus: isTerminalFocused(), terminalOpen }, }); diff --git a/apps/web/src/lib/dialogReturnFocus.ts b/apps/web/src/lib/dialogReturnFocus.ts new file mode 100644 index 000000000..6afee474b --- /dev/null +++ b/apps/web/src/lib/dialogReturnFocus.ts @@ -0,0 +1,29 @@ +/** + * Where focus goes when a dialog opened from somewhere else closes: the + * element that opened it (a sidebar or setup button), or a function for a + * place that has no element to hold, like the composer when the command + * palette handed over to the dialog. + */ +export type DialogReturnFocus = HTMLElement | (() => void); + +/** The element focused right now, to return to later; null when nothing is. */ +export function captureReturnFocus(): HTMLElement | null { + if (typeof document === "undefined") return null; + const active = document.activeElement; + return active instanceof HTMLElement && active !== document.body ? active : null; +} + +/** + * The dialog's `finalFocus` answer. An element that left the page (a sheet + * that closed) falls back to the dialog's own default. + */ +export function resolveDialogReturnFocus( + returnFocus: DialogReturnFocus | null, +): HTMLElement | boolean { + if (returnFocus === null) return true; + if (typeof returnFocus === "function") { + returnFocus(); + return false; + } + return returnFocus.isConnected ? returnFocus : true; +} diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx index 499ff7773..5ef6e352e 100644 --- a/apps/web/src/routes/_chat.tsx +++ b/apps/web/src/routes/_chat.tsx @@ -2,7 +2,7 @@ import { scopeThreadRef } from "@threadlines/client-runtime"; import { Outlet, createFileRoute, redirect, useParams } from "@tanstack/react-router"; import { useEffect } from "react"; -import { useCommandPaletteStore } from "../commandPaletteStore"; +import { isKeyboardOwnedByDialog } from "../commands/shortcutBlock"; import { FirstRunSetupRedirect } from "../components/setup/firstRunGateState"; import { useComposerDraftStore } from "../composerDraftStore"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; @@ -42,7 +42,7 @@ function ChatRouteGlobalShortcuts() { }, }); - if (useCommandPaletteStore.getState().open) { + if (isKeyboardOwnedByDialog()) { return; } diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsx index 70e030938..d4f0c3e93 100644 --- a/apps/web/src/routes/settings.tsx +++ b/apps/web/src/routes/settings.tsx @@ -8,6 +8,7 @@ import { } from "@tanstack/react-router"; import { useEffect, useRef, useState } from "react"; +import { isKeyboardOwnedByDialog } from "../commands/shortcutBlock"; import { useSettingsRestore } from "../components/settings/SettingsPanels"; import { SettingsSearchResults } from "../components/settings/SettingsSearch"; import { @@ -110,8 +111,9 @@ function SettingsContentLayout() { useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { - // An open menu or dialog takes its Escape first. - if (event.defaultPrevented) return; + // An open menu or dialog takes its Escape first, and the palette or + // Add project takes every key while it is open. + if (event.defaultPrevented || isKeyboardOwnedByDialog()) return; if (event.key === "Escape") { const search = useSettingsSearchStore.getState(); if (search.query.trim().length > 0) { diff --git a/docs/design/command-palette-mockup.html b/docs/design/command-palette-mockup.html new file mode 100644 index 000000000..df218eb15 --- /dev/null +++ b/docs/design/command-palette-mockup.html @@ -0,0 +1,1020 @@ + + + +Command palette mockup + + + +
+

+ This one works. Type in it, use the arrow keys, press Tab to change the filter, Escape to step + back. It runs on made-up data. +

+
+ Try: + + + + + + + + + +
+ +
+
+ + + + + +
+
+
+
+ ↑↓Move + ↵Open + TabFilter + + +
+
+ +

What changed from today

+
    +
  • + Opens on your threads. The last five, with the one you just left on top, so Search then + Enter takes you back. Under them, a few commands that fit what's on screen and the ones you + use most. +
  • +
  • + Best match first, whatever it is. The group holding the best match moves to the top. + Each group shows five and a "Show all" row. +
  • +
  • + Settings are in. A setting opens its page with the row lit up, the way Settings search + already does. +
  • +
  • + Filters. All, Threads, Commands, Settings, Projects, with a count on each while you + type. Typing > first jumps to Commands. +
  • +
  • + It says what it's doing. "Searching messages" while chats are still being read, and a + plain line when a computer can't be reached or its search may be incomplete. +
  • +
  • + A path is a suggestion, not a switch. Typing one adds an "Add project at" row on top. + The search results stay. +
  • +
  • + One flat surface. No box inside a box, wider, one-line rows, about 13 rows visible + instead of 8. +
  • +
+
+ diff --git a/docs/design/command-palette.md b/docs/design/command-palette.md new file mode 100644 index 000000000..2573fbc7d --- /dev/null +++ b/docs/design/command-palette.md @@ -0,0 +1,724 @@ +# Command palette and app search + +Status: plan, rev 3 (Nov 18 2026). Building started Nov 23 2026, step 1 first. +Line numbers are as of main at e5293cd83 (Nov 23); find code by name when +they have moved. Rev 2 took Sol's seven findings, +rev 3 takes Astra's fourteen (both listed at the end). Mockup: +`command-palette-mockup.html` beside this file. It works, so type in it. + +## Why + +The palette is two things at once: the app's search (the sidebar's Search +field opens it) and its command list. Today it does neither well. Seen in a +running app on Nov 17: + +- It opens on 30 commands. Recent threads start at row 31 and the box shows 8 + rows. +- It doesn't know settings. "font size" and "dark mode" find only threads + with those words. "diff", "model" and "theme" find nothing, though each has + a shortcut or a screen. +- Typing a path (`/src/auth.ts`) silently turns the search into Add project, + and Enter then creates a project. +- "No matching commands, projects, or threads" shows while the message search + is still running. A computer that failed to answer and an incomplete result + list are never mentioned. +- Groups have a fixed order (commands, projects, threads), so a thread named + exactly what you typed sits under every command that mentions the word. + +The causes are structural: + +- Every command is typed by hand inside one component + (`CommandPaletteDialog.tsx`, 3,289 lines, from line 1688). The app already + keeps a list of every settings row (`appPlaces.ts`) and every shortcut + command (`contracts/keybindings.ts`), and the palette reads neither. That + is how the theme commands were written (`themePaletteItems.tsx`, #827) and + never plugged in, while the docs and the app guide say they exist. +- The same component is the Add project wizard (folder browser, clone from + GitHub/GitLab/URL, pick a computer) and the Codex conversation importer. It + decides which one it is from the text in the field + (`isFilesystemBrowseQuery`, line 750). +- Ranking runs inside each group (`CommandPalette.logic.ts:347`), and the + thread search's `truncated` and `failedEnvironmentIds` are dropped at + line 1142. + +## What stays + +The server's message index and its ranking, snippets and jump-to-message, +quoted phrases, the highlighted thread loading ahead of Enter, the +`commandPalette.toggle` binding, the `>` shorthand, project-scoped thread +search from the sidebar, lazy loading of the palette's body, the +open-generation guard in the store, and how a command runs today (see +"Running a command"). + +## What the user gets + +1. **It opens on where you'd go.** Recent shows the five threads you last had + open on this device, newest first, the one on screen left out, so Search + then Enter goes back to the thread you just left. Suggested shows four + commands, the ones you use most here. Before there is any history they are + New thread, Toggle terminal, Toggle diff and Add project, as far as each + applies. An "All commands" row follows. +2. **One search over four kinds of thing**: threads (titles and messages), + commands, settings, projects. The group holding the best match comes + first. In the All view each group shows five rows and a "Show all N" row. +3. **Filters**: All, Threads, Commands, Settings, Projects, under the field. + While you type each shows how many rows it holds. Tab and Shift+Tab move + between them. Typing `>` first switches to Commands and leaves the field + empty, so the filter has one state. Every "Show all N" row switches to + that group's filter. +4. **Settings results** are link rows with the setting's name and where it + lives ("General › Terminal") on the right. Enter opens the page with the + row lit (the existing place arrival). Providers and skills come along, as + in Settings search. Live controls stay in Settings search. +5. **Every command the app has**, including the ones missing today (table + below), named the same in the palette and on the Keybindings page. +6. **It says what it's doing.** "Searching messages" at the foot of the list + until the message search for the text now in the field settles, and "No + matches" only after. "Couldn't search " when one didn't + answer. "The search on may be incomplete. Add a word to + narrow it." when that computer stopped early. +7. **A path is a suggestion.** Typing one adds an "Add project at " row + on top, and results stay underneath. Add project and "Bring in Codex + conversation" become dialogs of their own, opened by a command. +8. **Typos get a second chance.** When nothing matches, command and setting + names are tried letter by letter in order ("stngs" finds Open Settings), + under "Close matches". +9. **A flatter, bigger box**: one surface, 640px wide, about 13 one-line rows. + +Archived threads stay out of search in this build. Finding them needs the +thread page to open an archived thread, which it can't today. See "Archived +threads, a later build". + +## Design decisions + +### 1. One command catalog, in `packages/shared` + +`packages/shared/src/appCommands.ts`, data only (no React, no icons), in the +manner of `appPlaces.ts`: + +```ts +interface AppCommandSpec { + readonly title: string; // exactly what the palette row says + readonly about?: string; // one sentence, shown on wide rows and to agents + readonly group: "thread" | "panels" | "project" | "goTo" | "app"; + readonly keywords?: ReadonlyArray; + /** "list": Enter opens a list to pick from (projects, themes, scripts, computers). */ + readonly kind?: "action" | "list"; + /** List commands whose items are also found from the main search. */ + readonly itemsSearchable?: true; + /** One entry for a numbered shortcut family; "{n}" in the title is the number. */ + readonly numbered?: true; + readonly appliesWhen?: "desktop" | "notPhone"; +} +export const APP_COMMANDS = { "terminal.toggle": {...}, ... } as const satisfies Record; +export type AppCommandId = keyof typeof APP_COMMANDS; +``` + +- A command that has a shortcut uses the shortcut's id as its own + (`terminal.toggle`, `diff.toggle`, `chat.new`). A type check requires every + static `KeybindingCommand` to be a catalog key. The numbered families + (`thread.jump.N`, `modelPicker.jump.N`) share one `numbered` entry each, + titled "Jump to thread {n}", so the Keybindings page still tells Jump 1 + from Jump 9. A new shortcut command without a name no longer compiles. +- It lives in shared and not in `apps/web` because the Keybindings page and + settings search label commands from it, and `app_guide` can list it for + agents later without another move. +- Components that load at startup (ChatView, ChatComposer, Sidebar, the + thread route) import only its types (`import type { AppCommandId }`). The + catalog's data is read only from lazy chunks (the palette, Settings), so it + adds nothing to startup. +- A static catalog and not only commands declared by components, because the + names must exist when the owning screen isn't mounted (Keybindings page, + the guide, the drift tests), and a list you can read in one file is how + omissions get noticed. + +### 2. Handlers are registered by whoever owns the behavior + +`apps/web/src/commands/commandHandlers.ts`: + +```ts +useCommandHandlers({ + "terminal.toggle": { run: () => runTerminalCommand("toggle") }, + "composer.stash": attachmentsDisabled ? null : { run: stashCurrentPrompt }, + "thread.pullRequest": pr ? { run: openPr, title: `Open pull request #${pr.number}` } : null, + "project.runScript": { items: scriptItems }, // a "list" command +}); +``` + +**Registered means available.** A command with no handler right now is not +offered. This replaces the long `if (...) actionItems.push(...)` chain. Each +rule moves next to the code it protects, with its comment. + +**A handler is the guarded way in, never the bare function.** The shortcut +and button paths check things before they act, and the palette must not skip +them: + +- A command the palette offers today registers what today's palette path ends + in. The terminal commands register ChatView's `runTerminalCommand(kind)` + (line 5114), which opens a closed drawer for Find, and asks before + restarting or killing a busy shell. They do not register the keyboard + branch, which returns when the drawer is closed. +- A command new to the palette registers what its button or shortcut calls, + with that path's guard as the availability rule. Stash is not offered while + `attachmentsDisabled` (ChatComposer.tsx:2492). The table in section 4 names + each guard. +- Thread menu commands keep going through `useThreadMenu`, with its + confirmations. + +**What a handler can say**: + +- `title`, to override the catalog's (the PR number, "Hide sidebar" or "Show + sidebar"). +- `disabledReason`, when a row should show but not run. +- `keepOpen`, for a command that works inside the palette. +- `afterFocusReturns`, for a command that needs focus back in the page first + (find in chat, screenshot, the terminal commands, Add agent). +- `opensDialog`, for a command that hands over to another dialog (Add + project, Codex import, move thread). The palette then skips its usual + return of focus to the composer. +- `run` may resolve to `"cancelled"` (the user said no to Archive or Delete, + or closed a dialog). Use on this device is counted only for a run that was + not cancelled. + +**What the palette observes, and what stays fresh.** ChatView re-renders on +every streamed token, and the palette must still see a command arrive while +it is open (the pull request lookup is asynchronous, a script can be +renamed): + +- Observable: per command its id, title, disabled reason and flags, and for a + list each item's id, title, description and disabled state. The hook + compares this description with the last one in a layout effect and notifies + subscribers only when it differs. It checks an items array by reference + first, so an owner that memoizes its items pays one comparison. A streamed + token changes none of it, so nothing is published. The only subscriber is + the open palette. +- Fresh: the `run` functions live in a ref replaced on every render and are + read at the moment of use. +- An open list page draws from the current items, not a copy taken when it + opened. A script renamed while its list is open shows its new name. +- Enter resolves the row again by id (command id, or list id plus item id) + against the current handlers, takes the function, then closes. If the row + is gone the palette does nothing. `PaletteCommandSources` unmounts with the + palette, so a function looked up after the close would be missing. + +**Running a command** keeps today's order (`executeItem`, line 2990). The +palette closes unless the handler says `keepOpen`, and calls `run` in the +same tick. Only `afterFocusReturns` commands wait one frame, which is the +`requestAnimationFrame` each of them does by hand today. A list command +pushes its page and stays open ("New thread in…" stays a list). + +**Two places register**: + +- Components that own state: ChatView (terminal, find, scripts, files, + browser panel, pull request), the thread route (diff and the right-panel + tabs, through its `selectTab`), ChatComposer (model picker, stash, + screenshot, plan and default mode), Sidebar (previous and next thread). + This removes `terminalCommands.ts` and `composerCommands.ts`, the stores + that exist only so the palette can ask ChatView to do something. +- `PaletteCommandSources`, a component inside the palette's lazy chunk, + mounted while the palette is open. It calls one hook per feature, each in + the feature's own folder (`theme/ui/themeCommands.tsx`, + `fleet/fleetCommands.ts`, `commands/navigationCommands.ts`, + `commands/threadCommands.ts` over `useThreadMenu`). These need only stores + and `navigate`, and nothing uses them while the palette is closed. + +**The palette stops reading the whole open thread.** Today it subscribes to +it (`CommandPaletteDialog.tsx:582`) for its availability rules, so every +token re-renders the open palette. Once the rules live with their owners the +palette needs none of it. A source that still needs a fact about the thread +selects that one field. + +Icons are in `commands/commandIcons.tsx` in the palette chunk, typed +`Record`, so a command without an icon doesn't +compile. + +**Not in this build:** the eight keyboard listeners (`resolveShortcutCommand` +call sites) stay where they are. Folding them into one dispatcher changes +capture order and terminal pass-through and deserves its own change. + +### 3. Names: one per command + +`commandLabel()` (`KeybindingsSettings.logic.ts:270`) invents labels from ids +("Terminal: Toggle"). It reads the catalog title instead ("Toggle terminal"). +Project scripts keep "Run script: ". The Keybindings filter and +settings search's shortcut entries follow, since both go through +`commandLabel`. **Visible change** on the Keybindings page: the list is +grouped by the catalog's `group`, so related commands still sit together. + +Tooltips and the rail keep their own words for now (`AppTitleBar.tsx`, +`NavigationRail.tsx`). Where one differs from the catalog, the builder lists +it in the PR for a later pass. + +### 4. Commands to add + +All have a real action today and no palette row: + +| Command | Registers | Offered when | +| ----------------------------------------------------------------------- | --------------------------------------------------------- | ---------------------------------------------------- | +| Toggle diff | the route's `selectTab("diff")` / hide, as `onToggleRail` | a thread is open | +| Show source control / agents / threads panel | the route's `selectTab(tab)`, which also updates the URL | that tab is available for the thread | +| Switch model | `toggleModelPicker` on the composer handle | a composer is mounted, no approval holds its toolbar | +| Stash message | `stashCurrentPrompt` | not `attachmentsDisabled` | +| Plan mode / Default mode | `handleInteractionModeChange` | a composer is mounted | +| Open in editor | `openIn(cwd, preferredEditor)` | `canOpenInEditor` (the app's own computer) | +| New local thread | `startNewLocalThreadFromContext` | as `chat.newLocal` | +| Previous thread / Next thread | Sidebar's traversal | the sidebar has an adjacent thread | +| Back / Forward | `appHistory` | there is history that way | +| Run script… (list, searchable) | `runProjectScript` | the project has scripts | +| Browse project files | `openActiveFileViewer` | as the header's button | +| Toggle browser panel | `handleToggleBrowser` | desktop app, not a general chat | +| Open computer in Fleet… (list, searchable) | navigate to that computer's page | more than one computer | +| Change theme… (list, searchable), Edit theme colors…, Use default theme | `themePaletteItems.tsx`, rewritten as `themeCommands.tsx` | always | +| Show wrapped threads | `setInboxWrappedOpen` | the inbox is on screen | + +"Open computer in Fleet…" replaces today's one row per computer +(`CommandPaletteDialog.tsx:2005`). A single command id can't be several rows, +so each computer is an item of a searchable list, titled "Open in +Fleet" as today, and typing a computer's name still finds it from the main +search. + +Left out on purpose, as today: mark unread, separate, put back, stop children +(the comment at `CommandPaletteDialog.tsx:492`). "Open archived threads" is +not a command. It is a settings place and the Settings source finds it. + +### 5. Search: sources, then one ordering + +`apps/web/src/commands/paletteSearch.ts`, pure and unit-tested. Input: query, +filter, each source's entries, the message matches. Output: ordered sections. + +| Source | Entries | Decides what matches | +| -------- | ------------------------------------------------------- | ------------------------------------------------------- | +| Threads | title, project name, branch (client), messages (server) | `searchRanking` (unchanged: substrings, quoted phrases) | +| Commands | offered commands, plus items of searchable lists | `placeSearch.matchSearchFields` | +| Settings | `settingsSearchIndex` minus its shortcut entries | `placeSearch` (as Settings does) | +| Projects | name and path | `placeSearch` | + +Commands move from substring matching to the word-start matching Settings +uses. "term" finds Terminal, "phone" no longer finds "microphone", and both +searches read words the same way. + +**Tiers.** Each source's matcher decides whether a row matches. A separate +pure function, `matchTier(queryWords, fields)`, then places every matched row +on one scale. It does not read the matchers' own flags or ranges, which don't +say enough: `analyzeSearchText` reports the first place a phrase occurs, so +"term" in "Longterm terminal" looks like a mid-word match, and +`matchSearchFields` names a keyword even when another word needed the +section. `matchTier` works from the row's fields and the query's words (lower +case, quotes removed): + +- title +- second fields: a command's or setting's keywords, a thread's project name + and branch +- third fields: description, section, where it lives, a project's path + +A row takes the first tier it fits: + +0. the title is the query +1. the title starts with the query +2. every query word begins a word of the title +3. every query word is somewhere in the title +4. every query word begins a word of the title or the second fields +5. anything else its matcher accepted without a message (words spread across + title and third fields, a word inside a branch name) +6. only a message matched + +Every matched row lands in a tier, because 5 and 6 catch the rest. + +Rows inside a section sort by tier, then by the source's own score in its own +direction (lower is better for threads, higher for places), then for commands +by use on this device. Tier comes first because `placeSearch` weighs a title +word and a keyword the same, so by score alone a much-used command found by a +keyword ("Connect an agent" carries "terminal") could sit above Toggle +terminal for "term". + +Sections are ordered by their best row's tier. Ties go Threads, Commands, +Settings, Projects. Expected orders, all of them tests: + +- "terminal", with a thread titled "Terminal": Threads (tier 0), then + Commands (Toggle terminal, tier 2). +- "term", same data: Threads ("Terminal", tier 1), then Commands (tier 2). +- "term", thread "Longterm terminal" only: that thread is tier 2, and ties + with Toggle terminal go to Threads. +- "term", no thread with it in a title: Commands first, and a thread that + only mentions terminals in a message is tier 6. +- "toggle t": Commands (Toggle terminal, tier 1). +- "inal ror", thread "Terminal error": found, tier 3, below any tier 2. +- "payments", thread on branch `fix/payments` with another title: found, + tier 4. +- "dark terminal", a setting with keyword "dark" in section Terminal: tier 5. +- "font size": the thread with those words in its title (tier 2), then + Settings (Text size, by keyword, tier 4). +- `"font size"` in quotes: the same tiers as without them. +- A message match never sits above a title match in its section. + +**Close matches.** Only when the whole result is empty and the query has +three letters or more, an in-order letter match (`scoreSubsequenceMatch`, +already in `searchRanking.ts`) over command and setting titles. + +**The Settings source must behave as Settings search does.** Three things +today exist only inside the settings layout: + +- Which places exist. `settingsSearchIndex` asks `SettingsSurfaceContext` and + `SettingsPlaceSignalsProvider` (`routes/settings.tsx:158`). Outside them + the defaults are the full desktop set with optimistic signals, so a hosted + phone would be offered Keybindings. Both move into one + `SettingsAvailabilityProvider` that the settings layout and the open + palette mount with the same inputs. +- The reach probe. The one-time-link row depends on a check that runs only + while the settings search store is active + (`settingsPlaceAvailability.tsx:164`, `:204`). The provider takes "a search + is active" and its session number from its host: the settings store in + Settings, the palette's open generation in the palette. +- Where a result goes. Providers open `?instance=`, skills open the Skills + section, places use the place arrival. That resolution moves out of + `SettingsSearch.tsx` into a shared function. Settings keeps navigating with + `replace: true`. The palette navigates without it, so Back returns to the + chat you searched from. + +**Status lines.** `threadSearchReactQuery.ts` keeps each computer's outcome +instead of OR-ing them: answered, failed, or stopped early. The server's +`truncated` is true both when it found more than the limit and when its +candidate scan filled up (`ThreadSearch.ts:161`), so it never proves more +matches exist. The line therefore says "may be incomplete", and counts show +the rows actually found, never "50+". "Searching messages" shows while the +text in the field is long enough to search messages and its own request +hasn't answered, the debounce wait included. An answer to an earlier text +doesn't count. + +### 6. What the device remembers + +Two small persisted stores, per device, never sent anywhere: + +- `commandUsageStore`: per command id (and list item id), a count and a + last-used time. Feeds Suggested and the tie-break. +- recent thread visits: the last 20 thread keys in the order opened, written + when the thread in the route changes, not on a re-render (extend + `lastVisitedThreadRoute.ts`, which keeps one). Feeds Recent. Threads that + no longer exist are skipped. With no history the list falls back to latest + activity, as today. + +### 7. Add project and Codex import leave the palette + +Two dialogs, each with a small store that loads at startup and a body that +loads on first open, the way the palette's does: `addProject/addProjectStore.ts` +with `AddProjectDialog.tsx`, and `codexImport/codexImportStore.ts` with +`CodexSessionImportDialog.tsx`. Both draw with the same `ui/command` parts +under a title, so they look like the palette's siblings and keep their keys. +The code moves, about 1,400 lines. Nothing is redesigned. + +**What Add project is opened with**, all taken when it opens: + +- `selection`: the setup screen's "pick a folder for me" callback and its + computer, which stays locked (`AgentSetupScreen.tsx:749`). +- `initialPath`: from the palette's path row. +- `relativeBase`: the open project's computer and folder. A typed relative + path resolves against it and only on that computer. Without one, a relative + path is refused as today. +- The target computer's OS decides what counts as a path (Windows drive + letters), as `browseEnvironmentPlatform` does today. +- A cold start waits for the computer list. A hosted phone with no paired + computer goes straight to the pairing guidance + (`resolveAddProjectUnavailableGuidance`). + +**What Codex import is opened with**: the project (computer, id, name, +folder), the account when there is more than one (its picker moves along), +and the runtime mode of the open thread or draft at that moment. Its +paginated query keeps its key (computer, account, folder, search text), and +Load more, a failed import and retry stay inside the dialog. + +**A finished operation belongs to the session that started it.** Today a +clone awaits the server and then reads the selection from the store +(`CommandPaletteDialog.tsx:2518`, `:2723`), so closing and reopening for +something else mid-clone can hand the result to the wrong caller. A Codex +import navigates even when its palette is gone (`:1594`). In the new stores +every open is a session with an id. An operation captures its session (id, +selection callback, computer, project, where focus returns) when it starts. +When it finishes: + +- What the server did stands. The project exists. +- The worktree-pickup offer and the wait for the project to reach the store + stay as they are. +- The callback, the navigation and the close happen only if that session is + still the open one. Otherwise a toast says what was added, with a button to + open it. + +**Shortcuts and focus while a dialog is open.** The listeners that stand +down for the palette check `useCommandPaletteStore.getState().open` +(`ChatView.tsx:5000`, `routes/_chat.tsx:45`, `AppSidebarLayout.tsx:86`, +`ChatComposer.tsx:2492`). Once these flows are their own dialogs that check +no longer covers them, and a terminal or new-thread shortcut would act behind +a clone in progress. A small module, `commands/shortcutBlock.ts`, answers "is +a dialog that owns the keyboard open" for the palette and both new dialogs. +Every one of those listeners asks it, and the palette's own toggle shortcut +stands down while either dialog is open. On close each dialog returns focus +to where it was opened from: the setup screen's button, the sidebar's button, +or the composer when the palette launched it. The palette does not also send +focus to the composer on the way (`opensDialog`, section 2). + +`commandPaletteStore` loses `openAddProject`, `projectSelection` and the +add-project intent. Callers move to `addProjectStore`: Sidebar (two), +`NoActiveThreadState`, `AgentSetupScreen`, and the Add project command. + +In the palette, a query that `isFilesystemBrowseQuery` accepts adds the row +"Add project at ", which opens the dialog with the path filled in. One +more Enter than today for people who add projects by typing a path. In +exchange the search field never becomes a form. + +Whether Add project should be a different design altogether is a separate +question. + +### 8. Look + +Follows `design-language.md`. The mockup is the reference. + +- One `--popover` surface, 12px radius, `elevate-overlay`. The inner bordered + panel goes (a box in a box). Field, filters, a hairline, the list, a + hairline, the footer. +- 640px wide (576 today), the list up to `min(440px, 60vh)`. +- Rows are one line, 32px: icon, title (13.5px, 500), then on the right what + it belongs to (project, command group while searching All, settings path) + and the age or shortcut in mono 10.5px. A message match adds its snippet as + a second line. Thread rows keep the sidebar's status marks. +- Filters are plain text buttons. The chosen one takes the soft `--accent` + fill. Counts in mono. +- Section labels 11.5px, sentence case. +- All secondary text is opaque `--muted-foreground`. Today's rows fade it + (`/60`, `/70`, `/80`, `opacity-64`), which the design language rules out. +- Footer: Move, Enter with the highlighted row's verb (Open thread, Run, Go + to setting), Tab for filters. No footer on touch. +- Phone: the box is full width under the top edge, the filters scroll + sideways, and what a row belongs to moves to a second line under its + title, so rows are finger-sized. +- Field placeholder: "Search threads, commands and settings". +- **The highlight follows the row, not the position.** When message matches + arrive late, a row the user moved to stays highlighted by its identity even + if rows are inserted above it. If the user hasn't moved, the highlight + stays on the first row. +- **Escape in stages**: it clears the text, then the filter, then closes. + +## Archived threads, a later build + +Rev 2 put archived threads into search. Two reviews showed it is a feature +of its own, so it is out of these four steps. What it needs, for whoever +plans it: + +- The thread page must open an archived thread. Today the route sends you + Home when the thread isn't in the shell list + (`_chat.$environmentId.$threadId.tsx:1065`), and archived threads never are + (`ProjectionSnapshotQuery.ts:1088`). +- Archived titles and rows come from a separate request + (`archivedThreadsState.ts`), which uses `Promise.all`, so one computer + failing loses the others' lists. +- Which computers and projects to ask must come from the known computers and + the sidebar's project members, not from active threads + (`CommandPaletteDialog.tsx:1114`). A project with only archived threads is + otherwise never asked. +- The server needs an `includeArchived` input, and its answer must say + whether it honored it. An older server ignores the unknown key and returns + an ordinary empty list, which would read as "nothing archived matches". + Any new field on a match must be optional, or older computers' results + stop decoding. + +Until then, an empty search ends with a row that opens Settings › Archived +threads. + +## Hit every surface + +- **Entry points**: the sidebar Search field, the inbox search icon, the + Search button on the empty screen, the shortcut, the desktop View menu, + project-scoped search from a sidebar project (opens on Threads with the + project named in the field's left edge, as today). Add project: both + sidebar buttons, the empty screen, the setup screen, the command, the path + row. +- **Clients**: web, desktop, a narrow browser, and the hosted phone app. The + last two are different Settings surfaces and both get a test. + Desktop-only commands use `appliesWhen`. +- **Providers**: nothing provider-shaped. "Bring in Codex conversation" keeps + its rule (a workspace project with a Codex account). +- **Contracts**: nothing crosses the wire in these four steps, so linked + computers on older versions see no change. +- **Reverse states**: Escape in stages. A list page goes back with Backspace + on an empty field and its back arrow. Each new dialog closes back to where + it was opened from. +- **The app guide**: topics that say "in the command palette" are checked + against the catalog (theme colors, lead chat, move threads, worktrees), and + a short "Search and commands" topic says what the palette finds and how + the filters work. + +## Build order + +Each step is its own PR, in this order, since they all pass through +`CommandPaletteDialog.tsx`. Each leaves the app at least as good as it found +it. + +1. **Add project and Codex import move out** (section 7), with the shortcut + block, the session guard and the focus returns. No new behavior except the + path row. The palette file drops to about 1,700 lines. +2. **Catalog and handlers, and a root that opens on threads** (sections 1 to + 4, and `commandUsageStore` from 6). Every existing command moves to its + owner, the missing ones arrive, and Keybindings takes its names from the + catalog. Adding fifteen commands to today's commands-first list would push + recent threads further down, so this step also reorders the opening list, + in today's look: Recent threads (five, by latest activity), then Suggested + (four), then an "All commands" row that switches to the `>` view. The + whole-thread subscription goes. +3. **Search core** (section 5, and thread visits from 6): `paletteSearch.ts`, + the Settings and Projects sources, tiers, the status lines, close matches. + Still today's look. Groups show every match as they do now (no caps), and + `>` is the only filter. Nothing here needs a control that arrives later. +4. **The new look** (section 8): the box, filters, five-row caps with "Show + all", rows, the highlight rule, staged Escape, phone. + +Optional step 0, ten lines, if wanted before the rest: call +`useThemePaletteItems` in today's dialog so the theme commands the docs +promise exist now. + +## Tests + +- shared: catalog type checks (every shortcut command named, unique titles, + numbered families labeled per number). +- web unit: + - `matchTier` and `paletteSearch`: the expected orders in section 5, + section caps, close matches only on an empty result, per-computer status. + The existing `CommandPalette.logic` thread cases carry over unchanged. + - handler registry: registered means offered, a guard withdraws a command + (stash while attachments are disabled), a command registered while the + palette is open appears, a renamed list item shows its new name in an + open list, re-rendering with the same description notifies nobody, Enter + on a row that has gone does nothing, a cancelled run isn't counted. + - both dialog stores: an operation that finishes after its session closed + or was replaced doesn't call the callback, navigate or close. +- browser: + - `ChatView.palette.browser.tsx`: existing cases keep passing (the Add + agent focus case included), with the new placeholder in step 4. The Add + project and Codex import cases move to the new dialogs' specs. + - New dialogs: a shortcut pressed while one is open does nothing behind it, + the palette shortcut doesn't open over it, focus returns to the opener + (setup, sidebar, composer), a relative path resolves on the project's + computer, two Codex accounts show the picker. + - Palette: opens on recent threads, a setting result lands on its row and + Back returns to the chat, "Searching messages" shows before a slow search + answers and "No matches" does not, a failed computer is named, a typed + path keeps results and its row opens Add project, a late message match + doesn't move the highlight off a row the user chose. + - One test lists which commands are offered on a thread and on the home + screen (the drift check for handlers). + - Settings source on three setups: the desktop app with a reachable + computer (the one-time-link row appears), a narrow browser, the hosted + phone app (Keybindings is not offered). + - The open palette commits no React renders while a reply streams, counted + with a `Profiler` around it. `readAfterEachPaint` samples frames and + can't count commits. +- Gates as usual, the browser suite included. `scripts/check-web-bundle-size.ts` + must show no growth in what loads at startup. The builder checks that the + new stores, which do load at startup, pull in neither dialog body nor the + catalog's data. + +## Risks + +- **Step 2 moves about 40 availability rules.** Each has a reason in a + comment today. A rule lost in the move offers a command that lands on + "unsupported". The offered-commands browser test is the guard. The builder + moves rules verbatim and lists any it changed. +- **Step 1 moves live flows.** Clone, lookup and import have pending, retry + and cancel states that only a browser test exercises. The moved specs must + pass unchanged apart from how the dialog is opened. +- **Command matching changes** from substrings to word starts. A habit like + typing "erminal" stops working. "term" and "kill t" keep working. Called + out in release notes. +- **Keybindings labels change** (section 3). +- **Settings results that lead nowhere.** If the palette's availability + inputs ever differ from the settings layout's, it offers a row the page + hides. Section 5 makes them one provider, and the three-setup test checks + it. + +## Follow-ups, not in this plan + +- Archived threads in search (its own section above). +- One keyboard dispatcher over the handler registry, replacing the eight + listeners, and the desktop menu's action strings typed from the catalog. +- Tooltips and the rail taking their words from the catalog. +- Actions on a result without opening it (rename, pin or archive the + highlighted thread), which `useThreadMenu.describe` already supports for + any thread. +- Composer slash commands (`/model`, `/theme`, `/plan`) reading the catalog. +- `app_guide` answering "what commands are there" from the catalog. +- A redesign of Add project. + +## As built: step 1 (Nov 23 2026) + +Add project and Codex import are their own dialogs (`components/addProject/`, +`components/codexImport/`), and `CommandPaletteDialog.tsx` is 1,704 lines. +Where the build differs from section 7: + +- **The folder for relative paths** is read by the dialog when it opens and + kept, instead of each opener passing a `relativeBase`. Every entry point + gets it the same way, and a route change behind the dialog can't move it. +- **No title row.** The dialogs keep the palette's look, with a folder icon + in the field on the first step where the back arrow was. A title waits for + step 4's new box. +- **More listeners stand down** than the plan listed: the sidebar's thread + jumps, open-in-editor, Settings' Find and Escape, the Terminals page, and + the desktop menu's "toggle command palette". +- **A cold start also waits for the saved computers**, or a second computer + that loads late is never offered. +- **A repository lookup continues only if its step is still on screen**, so a + late answer can't bring back a clone the user backed out of (Astra's review + of the diff). +- **Startup grew 3.6 KB gzip** (904.9 KB of the 915 KB budget). The two + stores and the focus helper are about 1 KB. The rest is the bundler + splitting code that already loaded at startup into more files. Neither + dialog body loads at startup. + +## Rev 2 changes (Sol's review of rev 1) + +1. **Older linked computers.** A new field on a search match must be + optional. (Rev 3 moved the archived work out, and the note stays in its + section.) +2. **Archived titles.** Archived threads aren't in the thread list. +3. **The registry sees changes while open.** What is offered is published + when it changes, and what runs stays in a ref. +4. **Settings results match Settings.** One availability provider for the + settings layout and the palette. +5. **Tiers are complete.** Rows sort by tier before score, with the expected + orders written down. +6. **Every group can expand, and steps stand alone.** A Projects filter, and + caps move to step 4 with the filters. +7. **The cut-off line is true.** The limit is per computer. + +## Rev 3 changes (Astra's review of rev 2) + +1. **Archived results could send you Home.** The thread page redirects for a + thread that isn't in the list. Archived search is now a later build. +2. **Shortcuts behind the new dialogs.** One "a dialog owns the keyboard" + check for the palette and both dialogs, and focus returns to the opener. +3. **Results going to the wrong caller.** Each open is a session, and an + operation's callback, navigation and close belong to its session. +4. **"Include archived" could quietly return nothing.** Recorded as a + requirement of the later build. +5. **The incomplete-results line.** The server's flag doesn't prove more + matches exist, so the line says "may be incomplete" and counts are real. + "Searching messages" follows the text now in the field. +6. **Handlers are the guarded way in.** Stash, Find in terminal, Restart and + Kill keep their checks, a cancelled run isn't counted, and commands run in + today's order. +7. **Lists stay current.** Item names are observed, an open list redraws, and + Enter resolves the row again by id. +8. **Tiers from fields, not matcher flags.** `matchTier` covers branch + matches, mixed fields, quoted queries and the "Longterm terminal" case. +9. **Rows a single id can't hold.** Fleet's per-computer rows are list items, + panel commands use the route's tab selector so the URL follows, and + numbered shortcuts keep their numbers. +10. **Settings search outside Settings.** The reach probe gets its "search is + active" signal, results resolve through one shared function, and the + palette doesn't replace history. +11. **What each dialog is opened with** is written down, relative paths and + Codex accounts included. +12. **Performance checks that measure the right thing.** The palette drops + its whole-thread subscription, renders are counted with a Profiler, and + the dialog bodies load on first open. +13. **Step 2 no longer makes opening Search worse.** The threads-first + opening list and the usage store land with the catalog. +14. **The mockup agrees with the plan.** Counts match what is listed, `>` + becomes the Commands filter, Escape works in stages, and the highlight + follows the row. From dbec1d68c03e12faae81e41bcfd10013a2c2a7bd Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:24:10 -0500 Subject: [PATCH 2/4] feat(web): one command list, and the palette opens on recent threads The palette's commands were a hand-built list inside one component, each behind its own if, so commands the app already had (the panel's tabs, switching model, stashing a message, the theme commands) were never offered, and the Keybindings page made up its own labels ("Diff: Toggle"). The palette also opened on about 30 commands, with recent threads below them. One catalog in packages/shared names every command, and a build fails when a shortcut command has no name. Whoever owns a behavior registers its handler, with the same guard its button or shortcut uses, and the palette offers what is registered. The palette now opens on the five most recent threads, then four suggested commands learned on this device, then a row into every command. Keybindings takes its names and groups from the catalog. The open palette no longer redraws while a reply streams, except the part that decides Wrap up or Reopen, which still reads the inbox on every token. --- .../src/commands/PaletteCommandSources.tsx | 59 + apps/web/src/commands/commandHandlers.test.ts | 198 +++ apps/web/src/commands/commandHandlers.ts | 318 ++++ apps/web/src/commands/commandIcons.tsx | 150 ++ apps/web/src/commands/commandUsageStore.ts | 85 + apps/web/src/commands/navigationCommands.ts | 117 ++ apps/web/src/commands/panelTabCommands.ts | 22 + apps/web/src/commands/projectCommands.tsx | 272 +++ apps/web/src/commands/runCommand.ts | 77 + apps/web/src/commands/threadCommands.ts | 146 ++ .../components/ChatView.browser-harness.tsx | 24 + .../ChatView.codex-import.browser.tsx | 6 +- .../ChatView.move-thread.browser.tsx | 30 +- .../components/ChatView.palette.browser.tsx | 253 ++- .../components/ChatView.sidebar.browser.tsx | 6 +- apps/web/src/components/ChatView.tsx | 102 +- .../src/components/CommandPalette.logic.ts | 29 +- apps/web/src/components/CommandPalette.tsx | 30 +- .../src/components/CommandPaletteDialog.tsx | 1473 +++-------------- apps/web/src/components/Sidebar.tsx | 41 +- .../addProject/addProjectStore.test.ts | 26 +- .../components/addProject/addProjectStore.ts | 21 + apps/web/src/components/chat/ChatComposer.tsx | 55 +- .../src/components/chat/ProjectCrumbMenu.tsx | 16 + .../src/components/chats/useGeneralChats.ts | 55 +- .../codexImport/codexImportStore.test.ts | 3 +- .../codexImport/codexImportStore.ts | 21 + .../web/src/components/fleet/fleetCommands.ts | 33 + .../KeybindingsSettings.logic.test.ts | 11 +- .../settings/KeybindingsSettings.logic.ts | 50 +- .../settings/KeybindingsSettings.tsx | 41 +- .../settings/settingsSearchIndex.ts | 2 +- .../components/terminals/TerminalsPage.tsx | 33 +- .../src/components/theme/ui/themeCommands.tsx | 77 + .../components/theme/ui/themePaletteItems.tsx | 110 -- apps/web/src/composerCommands.ts | 24 - apps/web/src/hooks/useThreadMenu.ts | 9 +- .../routes/_chat.$environmentId.$threadId.tsx | 15 + apps/web/src/routes/_chat.draft.$draftId.tsx | 3 + apps/web/src/store.ts | 19 + apps/web/src/terminalCommands.ts | 32 - docs/design/command-palette.md | 53 + packages/shared/package.json | 4 + packages/shared/src/appCommands.test.ts | 50 + packages/shared/src/appCommands.ts | 570 +++++++ 45 files changed, 3266 insertions(+), 1505 deletions(-) create mode 100644 apps/web/src/commands/PaletteCommandSources.tsx create mode 100644 apps/web/src/commands/commandHandlers.test.ts create mode 100644 apps/web/src/commands/commandHandlers.ts create mode 100644 apps/web/src/commands/commandIcons.tsx create mode 100644 apps/web/src/commands/commandUsageStore.ts create mode 100644 apps/web/src/commands/navigationCommands.ts create mode 100644 apps/web/src/commands/panelTabCommands.ts create mode 100644 apps/web/src/commands/projectCommands.tsx create mode 100644 apps/web/src/commands/runCommand.ts create mode 100644 apps/web/src/commands/threadCommands.ts create mode 100644 apps/web/src/components/fleet/fleetCommands.ts create mode 100644 apps/web/src/components/theme/ui/themeCommands.tsx delete mode 100644 apps/web/src/components/theme/ui/themePaletteItems.tsx delete mode 100644 apps/web/src/composerCommands.ts delete mode 100644 apps/web/src/terminalCommands.ts create mode 100644 packages/shared/src/appCommands.test.ts create mode 100644 packages/shared/src/appCommands.ts diff --git a/apps/web/src/commands/PaletteCommandSources.tsx b/apps/web/src/commands/PaletteCommandSources.tsx new file mode 100644 index 000000000..76f46ef5e --- /dev/null +++ b/apps/web/src/commands/PaletteCommandSources.tsx @@ -0,0 +1,59 @@ +/** + * The palette's own command sources: features whose commands need only stores + * and navigation, so nothing registers them while the palette is closed. Each + * hook lives in its feature's folder and sits in its own component here, so + * one feature's state changing re-runs only that feature's rules. + */ +import { useFleetCommands } from "../components/fleet/fleetCommands"; +import { useThemeCommands } from "../components/theme/ui/themeCommands"; +import { useNavigationCommands } from "./navigationCommands"; +import { useProjectCommands } from "./projectCommands"; +import { useThreadCommands, useThreadInboxCommands } from "./threadCommands"; + +function NavigationCommands() { + useNavigationCommands(); + return null; +} + +function ProjectCommands() { + useProjectCommands(); + return null; +} + +function ThreadCommands() { + useThreadCommands(); + return null; +} + +function FleetCommands() { + useFleetCommands(); + return null; +} + +function ThemeCommands() { + useThemeCommands(); + return null; +} + +export function PaletteCommandSources() { + return ( + <> + + + + + + + ); +} + +/** + * Wrap up, Reopen and the lead commands. Their rule reads the inbox, which + * re-derives on every streamed token, so this source is mounted beside the + * palette rather than inside it: the palette's own rows and its other sources + * commit nothing while a reply streams. + */ +export function PaletteInboxCommandSource() { + useThreadInboxCommands(); + return null; +} diff --git a/apps/web/src/commands/commandHandlers.test.ts b/apps/web/src/commands/commandHandlers.test.ts new file mode 100644 index 000000000..4584304c9 --- /dev/null +++ b/apps/web/src/commands/commandHandlers.test.ts @@ -0,0 +1,198 @@ +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + getOfferedCommands, + publishCommandHandlers, + resetCommandHandlersForTests, + subscribeOfferedCommands, + withdrawCommandHandlers, + type CommandHandlerMap, + type CommandListItem, +} from "./commandHandlers"; +import { suggestCommands } from "./commandUsageStore"; +import { runCommand } from "./runCommand"; + +function run(id: Parameters[0]["id"], itemId?: string) { + const close = vi.fn(); + const recordUse = vi.fn(); + const onError = vi.fn(); + const outcome = runCommand({ id, itemId, close, recordUse, onError, nextFrame: (cb) => cb() }); + return { outcome, close, recordUse, onError }; +} + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +describe("command handlers", () => { + afterEach(resetCommandHandlersForTests); + + it("offers a command while a handler is registered, and not after", () => { + publishCommandHandlers("composer", { "composer.stash": { run: () => undefined } }); + expect(getOfferedCommands().has("composer.stash")).toBe(true); + + withdrawCommandHandlers("composer"); + expect(getOfferedCommands().has("composer.stash")).toBe(false); + }); + + it("withdraws a command when its guard says no", () => { + const handlers = (attachmentsDisabled: boolean): CommandHandlerMap => ({ + "composer.stash": attachmentsDisabled ? null : { run: () => undefined }, + }); + publishCommandHandlers("composer", handlers(false)); + publishCommandHandlers("composer", handlers(true)); + + expect(getOfferedCommands().has("composer.stash")).toBe(false); + expect(run("composer.stash").outcome).toBe("unavailable"); + }); + + it("tells an open palette about a command registered after it opened", () => { + const listener = vi.fn(); + const unsubscribe = subscribeOfferedCommands(listener); + publishCommandHandlers("route", {}); + expect(listener).not.toHaveBeenCalled(); + + publishCommandHandlers("route", { + "thread.pullRequest": { run: () => undefined, title: "Open pull request #12" }, + }); + + expect(listener).toHaveBeenCalledOnce(); + expect(getOfferedCommands().get("thread.pullRequest")?.title).toBe("Open pull request #12"); + unsubscribe(); + }); + + it("tells no one when what the palette shows didn't change", () => { + publishCommandHandlers("chat", { "terminal.new": { run: () => undefined } }); + publishCommandHandlers("terminals-page", { "terminal.new": { run: () => undefined } }); + const listener = vi.fn(); + const unsubscribe = subscribeOfferedCommands(listener); + + // A handler shadowed by a newer owner changes, and an owner of nothing leaves. + publishCommandHandlers("chat", { "terminal.new": { run: () => undefined, title: "Older" } }); + publishCommandHandlers("empty", {}); + withdrawCommandHandlers("empty"); + + expect(listener).not.toHaveBeenCalled(); + unsubscribe(); + }); + + it("publishes nothing when an owner re-renders with the same description", () => { + const items: CommandListItem[] = [{ id: "dev", title: "dev", run: () => undefined }]; + publishCommandHandlers("chat", { + "terminal.toggle": { run: () => undefined }, + "project.runScript": { items }, + }); + const before = getOfferedCommands(); + + // A streamed token: new functions, a new (equal) items array, same words. + publishCommandHandlers("chat", { + "terminal.toggle": { run: () => undefined }, + "project.runScript": { items: [{ id: "dev", title: "dev", run: () => undefined }] }, + }); + + expect(getOfferedCommands()).toBe(before); + }); + + it("shows a renamed list item by its new name, and runs the newest function", async () => { + const first = vi.fn(); + const second = vi.fn(); + publishCommandHandlers("chat", { + "project.runScript": { items: [{ id: "dev", title: "dev", run: first }] }, + }); + const listener = vi.fn(); + const unsubscribe = subscribeOfferedCommands(listener); + publishCommandHandlers("chat", { + "project.runScript": { items: [{ id: "dev", title: "Dev server", run: second }] }, + }); + + // An open list page reads this snapshot, so it redraws with the new name. + expect(getOfferedCommands().get("project.runScript")?.items?.[0]?.title).toBe("Dev server"); + expect(listener).toHaveBeenCalledOnce(); + unsubscribe(); + expect(run("project.runScript", "dev").outcome).toBe("ran"); + await flush(); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledOnce(); + }); + + it("does nothing for a row that has gone", () => { + publishCommandHandlers("chat", { + "project.runScript": { items: [{ id: "dev", title: "dev", run: () => undefined }] }, + }); + publishCommandHandlers("chat", { "project.runScript": { items: [] } }); + + const gone = run("project.runScript", "dev"); + expect(gone.outcome).toBe("unavailable"); + expect(gone.close).not.toHaveBeenCalled(); + }); + + it("counts a run as use unless it was cancelled", async () => { + publishCommandHandlers("menu", { + "thread.archive": { run: async () => "cancelled" as const }, + "thread.pin": { run: async () => undefined }, + }); + + const cancelled = run("thread.archive"); + const pinned = run("thread.pin"); + await flush(); + + expect(cancelled.recordUse).not.toHaveBeenCalled(); + expect(pinned.recordUse).toHaveBeenCalledWith("thread.pin"); + }); + + it("counts an item of a list for the list too", async () => { + publishCommandHandlers("chat", { + "project.runScript": { items: [{ id: "dev", title: "dev", run: () => undefined }] }, + }); + + const ran = run("project.runScript", "dev"); + await flush(); + + expect(ran.recordUse.mock.calls).toEqual([["project.runScript"], ["project.runScript:dev"]]); + }); + + it("closes before running, hands focus over for a dialog, and keeps open when asked", () => { + const order: string[] = []; + publishCommandHandlers("palette", { + "project.add": { run: () => void order.push("run"), opensDialog: true }, + "theme.change": { items: [], keepOpen: true }, + }); + + const close = vi.fn(() => void order.push("close")); + runCommand({ + id: "project.add", + close, + recordUse: () => undefined, + onError: () => undefined, + }); + expect(order).toEqual(["close", "run"]); + expect(close).toHaveBeenCalledWith({ handingOver: true }); + expect(run("theme.change").outcome).toBe("list"); + }); + + it("lets the newest owner of a command answer for it", () => { + const thread = vi.fn(); + const terminals = vi.fn(); + publishCommandHandlers("chat", { "terminal.new": { run: thread } }); + publishCommandHandlers("terminals-page", { "terminal.new": { run: terminals } }); + + run("terminal.new"); + expect(terminals).toHaveBeenCalledOnce(); + expect(thread).not.toHaveBeenCalled(); + }); +}); + +describe("suggested commands", () => { + it("puts the most used offered commands first, then fills from the fallback", () => { + const suggested = suggestCommands({ + candidates: ["chat.new", "terminal.toggle", "diff.toggle", "project.add", "chat.find"], + usage: { + "chat.find": { count: 5, lastUsedAt: 1 }, + "diff.toggle": { count: 5, lastUsedAt: 2 }, + "navigate.usage": { count: 9, lastUsedAt: 3 }, + }, + fallback: ["chat.new", "terminal.toggle", "diff.toggle", "project.add"], + limit: 4, + }); + // navigate.usage is not offered here, so it is never suggested. + expect(suggested).toEqual(["diff.toggle", "chat.find", "chat.new", "terminal.toggle"]); + }); +}); diff --git a/apps/web/src/commands/commandHandlers.ts b/apps/web/src/commands/commandHandlers.ts new file mode 100644 index 000000000..3ccb952c8 --- /dev/null +++ b/apps/web/src/commands/commandHandlers.ts @@ -0,0 +1,318 @@ +/** + * Who can do each command right now (docs/design/command-palette.md, + * section 2). Whoever owns a behavior registers a handler for its command + * with `useCommandHandlers`; a command with no handler is not offered. + * + * Two halves, kept apart on purpose: + * + * - What the palette sees (title, description, flags, a list's items) is + * compared with the last version on every commit of the owner, and + * published only when it differs. An owner that re-renders on every + * streamed token publishes nothing, so the open palette does not redraw. + * - What runs (`run`, a list item's `run`) is replaced on every commit and + * read at the moment of use, by id, so it is never stale. + * + * A handler is the guarded way in: the function its button or shortcut ends + * in, never the bare action behind it, and registered only while that path + * would act. This module loads at startup with its owners, so it imports only + * the catalog's types. + */ +import type { AppCommandId } from "@threadlines/shared/appCommands"; +import { useId, useLayoutEffect, useSyncExternalStore, type ReactNode } from "react"; + +/** "cancelled": the user said no (a confirmation, a closed dialog), so it doesn't count as use. */ +export type CommandRunResult = void | "cancelled"; +export type CommandRun = () => CommandRunResult | Promise; + +/** One row of a list command (a project, a theme, a script, a computer). */ +export interface CommandListItem { + readonly id: string; + readonly title: string; + readonly description?: string | undefined; + readonly disabled?: boolean | undefined; + readonly keywords?: ReadonlyArray | undefined; + /** The heading it sits under on the list page. */ + readonly group?: string | undefined; + /** Drawn beside it. Not compared: derive it from the item, not from render state. */ + readonly icon?: ReactNode; + readonly run: CommandRun; +} + +interface CommandHandlerBase { + /** Replaces the catalog's title ("Hide sidebar", "Open pull request #12"). */ + readonly title?: string | undefined; + /** Shown in bold after the title ("New thread in **Project**"). */ + readonly titleEmphasis?: string | undefined; + /** Replaces the catalog's `about`. */ + readonly description?: string | undefined; + /** Words that find it besides the catalog's (a project name, "#12"). */ + readonly keywords?: ReadonlyArray | undefined; + /** Shown, but not run. */ + readonly disabledReason?: string | undefined; + /** Works inside the palette, which stays open. */ + readonly keepOpen?: boolean | undefined; + /** Needs focus back in the page first: runs one frame after the palette closes. */ + readonly afterFocusReturns?: boolean | undefined; + /** Opens another dialog, which owns where focus goes when it closes. */ + readonly opensDialog?: boolean | undefined; +} + +export interface CommandActionHandler extends CommandHandlerBase { + readonly run: CommandRun; + readonly items?: undefined; +} + +export interface CommandListHandler extends CommandHandlerBase { + /** Memoize it: an unchanged array is one comparison. */ + readonly items: ReadonlyArray; + readonly run?: undefined; + /** The list page's field placeholder. */ + readonly placeholder?: string | undefined; +} + +export type CommandHandler = CommandActionHandler | CommandListHandler; + +/** A falsy entry means "not offered right now". */ +export type CommandHandlerMap = { + readonly [Id in AppCommandId]?: CommandHandler | null | false | undefined; +}; + +/** What the palette sees of a list item: everything but its `run`. */ +export interface OfferedListItem { + readonly id: string; + readonly title: string; + readonly description: string | undefined; + readonly disabled: boolean; + readonly keywords: ReadonlyArray | undefined; + readonly group: string | undefined; + readonly icon: ReactNode; +} + +/** What the palette sees of an offered command: everything but its functions. */ +export interface OfferedCommand { + readonly id: AppCommandId; + readonly title: string | undefined; + readonly titleEmphasis: string | undefined; + readonly description: string | undefined; + readonly keywords: ReadonlyArray | undefined; + readonly disabledReason: string | undefined; + readonly keepOpen: boolean; + readonly afterFocusReturns: boolean; + readonly opensDialog: boolean; + readonly placeholder: string | undefined; + /** Null for an action; a list command's current items. */ + readonly items: ReadonlyArray | null; +} + +interface Slot { + /** Later registrations win when two owners register the same command. */ + readonly order: number; + handlers: CommandHandlerMap; + offered: ReadonlyMap; + /** The raw items each list was last described from, to skip comparing an unchanged array. */ + itemsSource: ReadonlyMap>; +} + +const slots = new Map(); +const listeners = new Set<() => void>(); +let nextOrder = 0; +let snapshot: ReadonlyMap = new Map(); + +function sameStrings( + left: ReadonlyArray | undefined, + right: ReadonlyArray | undefined, +): boolean { + if (left === right) return true; + if (!left || !right || left.length !== right.length) return false; + return left.every((value, index) => value === right[index]); +} + +function describeItem( + item: CommandListItem, + previous: OfferedListItem | undefined, +): OfferedListItem { + const disabled = item.disabled === true; + if ( + previous && + previous.id === item.id && + previous.title === item.title && + previous.description === item.description && + previous.disabled === disabled && + previous.group === item.group && + sameStrings(previous.keywords, item.keywords) + ) { + return previous; + } + return { + id: item.id, + title: item.title, + description: item.description, + disabled, + keywords: item.keywords, + group: item.group, + icon: item.icon, + }; +} + +function describeItems( + items: ReadonlyArray, + previous: ReadonlyArray | null | undefined, +): ReadonlyArray { + const described = items.map((item, index) => describeItem(item, previous?.[index])); + return previous && + previous.length === described.length && + described.every((item, index) => item === previous[index]) + ? previous + : described; +} + +function describe( + id: AppCommandId, + handler: CommandHandler, + previous: OfferedCommand | undefined, + previousItemsSource: ReadonlyArray | undefined, +): OfferedCommand { + const items = + handler.items === undefined + ? null + : handler.items === previousItemsSource && previous?.items + ? previous.items + : describeItems(handler.items, previous?.items); + const next: OfferedCommand = { + id, + title: handler.title, + titleEmphasis: handler.titleEmphasis, + description: handler.description, + keywords: handler.keywords, + disabledReason: handler.disabledReason, + keepOpen: handler.keepOpen === true, + afterFocusReturns: handler.afterFocusReturns === true, + opensDialog: handler.opensDialog === true, + placeholder: handler.items === undefined ? undefined : handler.placeholder, + items, + }; + if ( + previous && + previous.title === next.title && + previous.titleEmphasis === next.titleEmphasis && + previous.description === next.description && + sameStrings(previous.keywords, next.keywords) && + previous.disabledReason === next.disabledReason && + previous.keepOpen === next.keepOpen && + previous.afterFocusReturns === next.afterFocusReturns && + previous.opensDialog === next.opensDialog && + previous.placeholder === next.placeholder && + previous.items === next.items + ) { + return previous; + } + return next; +} + +function rebuildSnapshot(): void { + const owners = [...slots.values()].toSorted((left, right) => left.order - right.order); + const next = new Map(); + for (const slot of owners) { + for (const [id, offered] of slot.offered) next.set(id, offered); + } + // A change the palette can't see (an owner of nothing leaving, a handler + // shadowed by a newer owner) keeps the old snapshot and tells no one. + if ( + next.size === snapshot.size && + [...next].every(([id, offered]) => snapshot.get(id) === offered) + ) { + return; + } + snapshot = next; + for (const listener of listeners) listener(); +} + +/** + * Records an owner's handlers. The functions are kept every time; the + * palette hears about it only when what it shows changed. + */ +export function publishCommandHandlers(slotKey: string, handlers: CommandHandlerMap): void { + let slot = slots.get(slotKey); + if (!slot) { + slot = { order: nextOrder++, handlers, offered: new Map(), itemsSource: new Map() }; + slots.set(slotKey, slot); + } + slot.handlers = handlers; + const offered = new Map(); + const itemsSource = new Map>(); + let changed = false; + for (const id of Object.keys(handlers) as AppCommandId[]) { + const handler = handlers[id]; + if (!handler) continue; + const previous = slot.offered.get(id); + const described = describe(id, handler, previous, slot.itemsSource.get(id)); + if (described !== previous) changed = true; + offered.set(id, described); + if (handler.items !== undefined) itemsSource.set(id, handler.items); + } + if (offered.size !== slot.offered.size) changed = true; + slot.itemsSource = itemsSource; + if (!changed) return; + slot.offered = offered; + rebuildSnapshot(); +} + +export function withdrawCommandHandlers(slotKey: string): void { + if (!slots.delete(slotKey)) return; + rebuildSnapshot(); +} + +function ownerOf(id: AppCommandId): Slot | null { + let owner: Slot | null = null; + for (const slot of slots.values()) { + if (slot.offered.has(id) && (owner === null || slot.order > owner.order)) owner = slot; + } + return owner; +} + +/** The handler offered for a command now, read when it is used; null when it is gone. */ +export function resolveCommandHandler(id: AppCommandId): CommandHandler | null { + return ownerOf(id)?.handlers[id] || null; +} + +/** A list command's item now, by id; null when the list or the item is gone. */ +export function resolveCommandListItem(id: AppCommandId, itemId: string): CommandListItem | null { + const handler = resolveCommandHandler(id); + if (!handler?.items) return null; + return handler.items.find((item) => item.id === itemId) ?? null; +} + +/** Hears every change to what is offered; the palette subscribes through `useOfferedCommands`. */ +export function subscribeOfferedCommands(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +export function getOfferedCommands(): ReadonlyMap { + return snapshot; +} + +/** + * Registers this component's commands for as long as it is mounted. Pass a + * new object every render if that is easiest: only what the palette shows is + * compared, and only a difference reaches it. + */ +export function useCommandHandlers(handlers: CommandHandlerMap): void { + const slotKey = useId(); + useLayoutEffect(() => { + publishCommandHandlers(slotKey, handlers); + }); + useLayoutEffect(() => () => withdrawCommandHandlers(slotKey), [slotKey]); +} + +/** The commands offered now; re-renders only when one is added, removed or relabeled. */ +export function useOfferedCommands(): ReadonlyMap { + return useSyncExternalStore(subscribeOfferedCommands, getOfferedCommands, getOfferedCommands); +} + +/** Tests only: forgets every registration. */ +export function resetCommandHandlersForTests(): void { + slots.clear(); + snapshot = new Map(); + for (const listener of listeners) listener(); +} diff --git a/apps/web/src/commands/commandIcons.tsx b/apps/web/src/commands/commandIcons.tsx new file mode 100644 index 000000000..30d37d733 --- /dev/null +++ b/apps/web/src/commands/commandIcons.tsx @@ -0,0 +1,150 @@ +/** + * Each command's glyph in the palette. Typed over the whole catalog, so a new + * command without an icon doesn't compile. Loads with the palette. + */ +import type { AppCommandId } from "@threadlines/shared/appCommands"; +import { + ArchiveIcon, + ArrowLeftIcon, + ArrowRightIcon, + BotIcon, + CalendarClockIcon, + CalendarPlusIcon, + CameraIcon, + ChartColumnIcon, + CheckIcon, + ChevronDownIcon, + ChevronUpIcon, + CircleArrowUpIcon, + CloudIcon, + CodeIcon, + CommandIcon, + CopyIcon, + CpuIcon, + CrownIcon, + DiffIcon, + EraserIcon, + FileTextIcon, + FolderGitIcon, + FolderOpenIcon, + FolderPlusIcon, + FolderSyncIcon, + GitBranchIcon, + GitPullRequestIcon, + GlobeIcon, + HashIcon, + HomeIcon, + InboxIcon, + LaptopIcon, + ListTodoIcon, + MessageCirclePlusIcon, + MessageCircleWarningIcon, + MessagesSquareIcon, + MonitorUpIcon, + PaintbrushIcon, + PaletteIcon, + PanelLeftIcon, + PanelRightIcon, + PencilIcon, + PinIcon, + PinOffIcon, + PlayIcon, + PlugIcon, + PlusIcon, + RotateCcwIcon, + ScrollTextIcon, + SearchIcon, + SettingsIcon, + SmartphoneIcon, + SquarePenIcon, + SquareSplitHorizontalIcon, + TerminalSquareIcon, + Trash2Icon, + UsersRoundIcon, + WaypointsIcon, + WrenchIcon, + type LucideIcon, +} from "lucide-react"; + +export const COMMAND_ICONS: Readonly> = { + "chat.new": SquarePenIcon, + "chat.newLocal": SquarePenIcon, + "codex.import": MessagesSquareIcon, + "worktrees.pickUp": FolderGitIcon, + "project.brief": ScrollTextIcon, + "chat.newIn": SquarePenIcon, + "project.add": FolderPlusIcon, + "navigate.home": HomeIcon, + "chat.newGeneral": MessageCirclePlusIcon, + "navigate.generalChats": MessagesSquareIcon, + "navigate.terminals": TerminalSquareIcon, + "navigate.fleet": WaypointsIcon, + "navigate.scheduled": CalendarClockIcon, + "scheduled.new": CalendarPlusIcon, + "computer.rename": PencilIcon, + "app.whatsNew": CircleArrowUpIcon, + "app.reportProblem": MessageCircleWarningIcon, + "computer.connect": LaptopIcon, + "outsideAgents.connect": PlugIcon, + "assistants.connect": CloudIcon, + "fleet.openComputer": WaypointsIcon, + "sidebar.toggle": PanelLeftIcon, + "navigate.pullRequests": GitPullRequestIcon, + "thread.pullRequest": GitPullRequestIcon, + "panel.device": SmartphoneIcon, + "chat.find": SearchIcon, + "composer.screenshot": CameraIcon, + "terminal.toggle": TerminalSquareIcon, + "terminal.new": PlusIcon, + "terminal.split": SquareSplitHorizontalIcon, + "terminal.find": SearchIcon, + "terminal.restart": RotateCcwIcon, + "terminal.clear": EraserIcon, + "terminal.close": Trash2Icon, + "room.addAgent": UsersRoundIcon, + "thread.move": MonitorUpIcon, + "threads.moveMany": MonitorUpIcon, + "project.setUpElsewhere": FolderSyncIcon, + "thread.makeLead": CrownIcon, + "thread.stopLead": CrownIcon, + "thread.rename": PencilIcon, + "thread.pin": PinIcon, + "thread.unpin": PinOffIcon, + "thread.wrapUp": CheckIcon, + "thread.reopen": RotateCcwIcon, + "thread.copyPath": CopyIcon, + "thread.copyId": CopyIcon, + "thread.archive": ArchiveIcon, + "thread.delete": Trash2Icon, + "leadChat.goTo": CrownIcon, + "leadChat.new": CrownIcon, + "navigate.usage": ChartColumnIcon, + "navigate.settings": SettingsIcon, + "navigate.setup": BotIcon, + "navigate.communityAgents": BotIcon, + "navigate.skills": FileTextIcon, + "diff.toggle": PanelRightIcon, + "panel.diff": DiffIcon, + "panel.sourceControl": GitBranchIcon, + "panel.agents": CpuIcon, + "panel.threads": ListTodoIcon, + "modelPicker.toggle": BotIcon, + "composer.stash": InboxIcon, + "composer.planMode": ListTodoIcon, + "composer.defaultMode": WrenchIcon, + "editor.openFavorite": CodeIcon, + "thread.previous": ChevronUpIcon, + "thread.next": ChevronDownIcon, + "navigate.back": ArrowLeftIcon, + "navigate.forward": ArrowRightIcon, + "project.runScript": PlayIcon, + "files.browse": FolderOpenIcon, + "browser.toggle": GlobeIcon, + "theme.change": PaletteIcon, + "theme.editColors": PaintbrushIcon, + "theme.useDefault": RotateCcwIcon, + "inbox.showWrapped": CheckIcon, + "commandPalette.toggle": CommandIcon, + "thread.jump": HashIcon, + "modelPicker.jump": HashIcon, +}; diff --git a/apps/web/src/commands/commandUsageStore.ts b/apps/web/src/commands/commandUsageStore.ts new file mode 100644 index 000000000..81cf28fb2 --- /dev/null +++ b/apps/web/src/commands/commandUsageStore.ts @@ -0,0 +1,85 @@ +/** + * Which commands this device uses, for the palette's Suggested group + * (docs/design/command-palette.md, section 6). Per command id, and per list + * item as `:`: a count and when it was last used. Kept on this + * device only, never sent anywhere. + */ +import * as Schema from "effect/Schema"; +import { create } from "zustand"; + +import { getLocalStorageItem, setLocalStorageItem } from "../hooks/useLocalStorage"; + +export const COMMAND_USAGE_STORAGE_KEY = "threadlines:command-usage:v1"; +/** Enough for every command and a few list items each; the oldest go first. */ +const MAX_ENTRIES = 200; + +const CommandUsageEntry = Schema.Struct({ count: Schema.Number, lastUsedAt: Schema.Number }); +const CommandUsageRecord = Schema.Record(Schema.String, CommandUsageEntry); +export type CommandUsageEntry = typeof CommandUsageEntry.Type; +type CommandUsageRecord = typeof CommandUsageRecord.Type; + +function readRecord(): CommandUsageRecord { + try { + return getLocalStorageItem(COMMAND_USAGE_STORAGE_KEY, CommandUsageRecord) ?? {}; + } catch { + return {}; + } +} + +interface CommandUsageState { + readonly byKey: CommandUsageRecord; + readonly recordUse: (key: string, now?: number) => void; +} + +export const useCommandUsageStore = create()((set) => ({ + byKey: readRecord(), + recordUse: (key, now = Date.now()) => + set((state) => { + const previous = state.byKey[key]; + const entries = Object.entries({ + ...state.byKey, + [key]: { count: (previous?.count ?? 0) + 1, lastUsedAt: now }, + }) + .toSorted((left, right) => right[1].lastUsedAt - left[1].lastUsedAt) + .slice(0, MAX_ENTRIES); + const byKey = Object.fromEntries(entries); + try { + setLocalStorageItem(COMMAND_USAGE_STORAGE_KEY, byKey, CommandUsageRecord); + } catch { + // A full or blocked storage keeps this session's counts only. + } + return { byKey }; + }), +})); + +/** The usage key of a command, or of one item of a list command. */ +export function commandUsageKey(commandId: string, itemId?: string): string { + return itemId === undefined ? commandId : `${commandId}:${itemId}`; +} + +/** + * Up to `limit` of `candidates`, most used first (ties to the most recent), + * then `fallback` in its own order to fill the rest. Only candidates count: + * a command not offered now is never suggested. + */ +export function suggestCommands(input: { + readonly candidates: ReadonlyArray; + readonly usage: CommandUsageRecord; + readonly fallback: ReadonlyArray; + readonly limit: number; +}): Id[] { + const offered = new Set(input.candidates); + const used = input.candidates + .filter((id) => input.usage[id] !== undefined) + .toSorted((left, right) => { + const a = input.usage[left]!; + const b = input.usage[right]!; + return b.count - a.count || b.lastUsedAt - a.lastUsedAt; + }); + const picked = used.slice(0, input.limit); + for (const id of input.fallback) { + if (picked.length >= input.limit) break; + if (offered.has(id) && !picked.includes(id)) picked.push(id); + } + return picked; +} diff --git a/apps/web/src/commands/navigationCommands.ts b/apps/web/src/commands/navigationCommands.ts new file mode 100644 index 000000000..6281aa0e9 --- /dev/null +++ b/apps/web/src/commands/navigationCommands.ts @@ -0,0 +1,117 @@ +/** + * Going places and app-wide commands for the palette. Registered while the + * palette is open (PaletteCommandSources); each rule says where the command + * would act, the same place its button lives. + */ +import { useLocation, useNavigate } from "@tanstack/react-router"; + +import { useAppHistory } from "../appHistory"; +import { APP_VERSION } from "../branding"; +import { requestGeneralChatsReveal } from "../components/chats/generalChatsPlacement"; +import { useStartGeneralChat } from "../components/chats/useGeneralChats"; +import { openComputerRenameDialog, useComputerNaming } from "../components/DeviceRenameDialog"; +import { openMoveThreadsDialog } from "../components/MoveThreadsDialog"; +import { openReportProblemDialog } from "../components/ReportProblemDialog"; +import { openConnectComputerDialog } from "../components/settings/connections/JoinComputerDialog"; +import { openWhatsNewDialog } from "../components/WhatsNewDialog"; +import { useMoveThreadsOffered } from "../environments/links/threadMoves"; +import { + startAssistantCode, + useOutsideAgentsSnapshot, +} from "../environments/outsideAgents/outsideAgents"; +import { usePrimaryEnvironmentId } from "../environments/primary"; +import { useIsMobile } from "../hooks/useMediaQuery"; +import { useSettings } from "../hooks/useSettings"; +import { usePullRequestEnvironments } from "../lib/pullRequestsReactQuery"; +import { useScheduledTaskEnvironments } from "../lib/scheduledTasksState"; +import { selectSidebarListShown, useUiStateStore } from "../uiStateStore"; +import { useCommandHandlers } from "./commandHandlers"; + +export function useNavigationCommands(): void { + const navigate = useNavigate(); + const isHomeRoute = useLocation({ select: (location) => location.pathname === "/" }); + const onTerminalsPage = useLocation({ + select: (location) => location.pathname === "/terminals", + }); + const generalChatsPlacement = useSettings((settings) => settings.generalChatsPlacement); + const startGeneralChat = useStartGeneralChat(); + const isMobile = useIsMobile(); + const sidebarListOpen = useUiStateStore(selectSidebarListShown); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const scheduledTaskEnvironments = useScheduledTaskEnvironments(); + const pullRequestEnvironments = usePullRequestEnvironments(); + // Heard from only for this computer's owner, where its server takes outside agents. + const managesOutsideAgents = useOutsideAgentsSnapshot() !== null; + const thisComputerNaming = useComputerNaming(primaryEnvironmentId); + // Clearing this computer (Part 3c): several of its threads to a linked one. + const moveThreadsOffered = useMoveThreadsOffered(primaryEnvironmentId, null); + const history = useAppHistory(); + + useCommandHandlers({ + "navigate.home": !isHomeRoute && { run: () => navigate({ to: "/" }) }, + "chat.newGeneral": startGeneralChat !== null && { run: () => startGeneralChat() }, + "navigate.generalChats": { + run: async () => { + // Where the chats are a section of Threads, the shell opens it there + // without a stop at the old page's address. + if (generalChatsPlacement === "threads") requestGeneralChatsReveal(); + else await navigate({ to: "/chats" }); + }, + }, + "navigate.terminals": !onTerminalsPage && { run: () => navigate({ to: "/terminals" }) }, + "navigate.fleet": { run: () => navigate({ to: "/fleet" }) }, + // Only where a connected computer runs scheduled tasks, like the rail's button. + "navigate.scheduled": scheduledTaskEnvironments.length > 0 && { + run: () => navigate({ to: "/scheduled" }), + }, + "scheduled.new": scheduledTaskEnvironments.length > 0 && { + run: () => navigate({ to: "/scheduled", search: { view: "new" } }), + }, + "computer.rename": thisComputerNaming !== null && { + description: `Now called ${thisComputerNaming.label}`, + run: () => openComputerRenameDialog(thisComputerNaming), + }, + "app.whatsNew": { + description: `The notes for v${APP_VERSION}`, + run: () => openWhatsNewDialog(), + }, + "app.reportProblem": { run: () => openReportProblemDialog() }, + "computer.connect": { run: () => openConnectComputerDialog() }, + "outsideAgents.connect": managesOutsideAgents && { + run: () => navigate({ to: "/settings/connections", search: { section: "agents" } }), + }, + "assistants.connect": managesOutsideAgents && { + run: async () => { + // The Assistants group shows the code, or why there isn't one. + void startAssistantCode(); + await navigate({ to: "/settings/connections", search: { section: "assistants" } }); + }, + }, + // The thread list beside the rail; a phone shows it as a sheet instead. + "sidebar.toggle": !isMobile && { + title: sidebarListOpen ? "Hide sidebar" : "Show sidebar", + run: () => useUiStateStore.getState().toggleSidebarListShown(), + }, + // Registered only where the rail's button is: a command that lands on + // "unsupported" is worse than one the palette never offers. + "navigate.pullRequests": pullRequestEnvironments.length > 0 && { + run: () => navigate({ to: "/pull-requests", search: { state: "open" } }), + }, + "threads.moveMany": moveThreadsOffered && + primaryEnvironmentId !== null && { + run: () => openMoveThreadsDialog({ sourceEnvironmentId: primaryEnvironmentId }), + }, + // As the title row's arrows: only when there is a page that way. + "navigate.back": history.canGoBack && { run: history.back }, + "navigate.forward": history.canGoForward && { run: history.forward }, + "navigate.usage": { run: () => navigate({ to: "/usage" }) }, + "navigate.settings": { run: () => navigate({ to: "/settings" }) }, + "navigate.setup": { run: () => navigate({ to: "/setup" }) }, + "navigate.communityAgents": { + run: () => navigate({ to: "/settings/providers", search: { section: "community" } }), + }, + "navigate.skills": { + run: () => navigate({ to: "/settings/plugins", search: { tab: "skills" } }), + }, + }); +} diff --git a/apps/web/src/commands/panelTabCommands.ts b/apps/web/src/commands/panelTabCommands.ts new file mode 100644 index 000000000..edb69e991 --- /dev/null +++ b/apps/web/src/commands/panelTabCommands.ts @@ -0,0 +1,22 @@ +/** + * The side panel's tabs as palette commands, for a route that owns the panel + * (a thread or a draft). Each runs the route's own tab selector, so the URL + * follows, and is offered only where the tab is. + */ +import type { RightPanelTab } from "../rightPanelTabs"; +import { useCommandHandlers } from "./commandHandlers"; + +export function usePanelTabCommands( + availableTabs: ReadonlyArray, + selectTab: (tab: RightPanelTab) => void, +): void { + const tabCommand = (tab: RightPanelTab) => + availableTabs.includes(tab) && { run: () => selectTab(tab) }; + useCommandHandlers({ + "panel.device": tabCommand("device"), + "panel.diff": tabCommand("diff"), + "panel.sourceControl": tabCommand("sourceControl"), + "panel.agents": tabCommand("agents"), + "panel.threads": tabCommand("threads"), + }); +} diff --git a/apps/web/src/commands/projectCommands.tsx b/apps/web/src/commands/projectCommands.tsx new file mode 100644 index 000000000..93504cd2d --- /dev/null +++ b/apps/web/src/commands/projectCommands.tsx @@ -0,0 +1,272 @@ +/** + * Commands about the project in scope (the open thread's or draft's), for + * the palette. Registered while the palette is open (PaletteCommandSources). + */ +import { scopedProjectKey, scopedThreadKey, scopeProjectRef } from "@threadlines/client-runtime"; +import { DEFAULT_NEW_THREAD_RUNTIME_MODE } from "@threadlines/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { useLayoutEffect, useMemo, useRef } from "react"; +import { useShallow } from "zustand/react/shallow"; + +import { + openAddProject, + waitForAddProjectSessionEnd, +} from "../components/addProject/addProjectStore"; +import { + openCodexImport, + waitForCodexImportSessionEnd, +} from "../components/codexImport/codexImportStore"; +import { ITEM_ICON_CLASS } from "../components/CommandPalette.logic"; +import { openProjectSetupDialog } from "../components/ProjectSetupDialog"; +import { ProjectFavicon } from "../components/ProjectFavicon"; +import { useComposerHandleContext } from "../composerHandleContext"; +import { usePrimaryEnvironmentId } from "../environments/primary"; +import { useProjectSetupTargets } from "../environments/projectSetups/projectSetupTargets"; +import { useSavedEnvironmentRuntimeStore } from "../environments/runtime"; +import { useHandleNewThread } from "../hooks/useHandleNewThread"; +import { useWorktreePickup } from "../hooks/useWorktreePickup"; +import { + createLeadChat, + environmentSupportsProjectLead, + leadSettingRefusal, + projectLeadRef, +} from "../leadChat"; +import { + resolveThreadActionProjectRef, + startNewLocalThreadFromContext, + startNewThreadFromContext, + startNewThreadInProjectFromContext, +} from "../lib/chatThreadActions"; +import { projectBriefLocation, useProjectBriefSupport } from "../projectBrief"; +import { deriveProviderInstanceEntries } from "../providerInstances"; +import { useServerProviders } from "../rpc/serverState"; +import { selectProjectsAcrossEnvironments, selectThreadByRef, useStore } from "../store"; +import { buildThreadRouteParams } from "../threadRoutes"; +import { useWorktreePickupStore } from "../worktreePickup"; +import { useCommandHandlers, type CommandListItem } from "./commandHandlers"; + +export function useProjectCommands(): void { + const navigate = useNavigate(); + const composerHandleRef = useComposerHandleContext(); + const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } = + useHandleNewThread(); + const projects = useStore(useShallow(selectProjectsAcrossEnvironments)); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const primaryServerProviders = useServerProviders(); + const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId); + // The one fact about the open thread these commands read, not the thread. + const openThreadRuntimeMode = useStore((state) => + routeThreadRef ? (selectThreadByRef(state, routeThreadRef)?.runtimeMode ?? null) : null, + ); + + const focusComposer = () => composerHandleRef?.current?.focusAtEnd(); + const context = { activeDraftThread, activeThread, defaultProjectRef, handleNewThread }; + // The list's items are memoized on the projects; they read the context + // when they run, so a list left open still starts from the thread on screen. + const contextRef = useRef(context); + useLayoutEffect(() => { + contextRef.current = context; + }); + + const currentProjectEnvironmentId = + activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null; + const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null; + const currentProject = + currentProjectId && currentProjectEnvironmentId + ? (projects.find( + (project) => + project.id === currentProjectId && + project.environmentId === currentProjectEnvironmentId, + ) ?? null) + : null; + const currentProjectCwd = currentProject?.cwd ?? null; + const supportsProjectBrief = useProjectBriefSupport(); + // The project's worktrees made outside Threadlines, asked for while the + // palette is open: the command shows only when there is one to add. + const currentProjectRef = useMemo( + () => + currentProject?.kind === "workspace" + ? scopeProjectRef(currentProject.environmentId, currentProject.id) + : null, + [currentProject?.environmentId, currentProject?.id, currentProject?.kind], + ); + const worktreePickup = useWorktreePickup({ + projectRef: currentProjectRef, + projectCwd: currentProjectRef === null ? null : currentProjectCwd, + }); + const currentEnvironmentProviders = + currentProjectEnvironmentId && currentProjectEnvironmentId === primaryEnvironmentId + ? primaryServerProviders + : currentProjectEnvironmentId + ? (savedEnvironmentRuntimeById[currentProjectEnvironmentId]?.serverConfig?.providers ?? []) + : []; + const availableCodexInstances = deriveProviderInstanceEntries(currentEnvironmentProviders).filter( + (entry) => + entry.driverKind === "codex" && + entry.enabled && + entry.installed && + entry.isAvailable && + entry.models.length > 0, + ); + // The open thread's project, where another computer could take a copy of it. + const openThreadProjectRef = activeThread + ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) + : activeDraftThread + ? scopeProjectRef(activeDraftThread.environmentId, activeDraftThread.projectId) + : null; + const projectSetupTargets = useProjectSetupTargets(openThreadProjectRef); + + const newThreadInItems = useMemo>( + () => + projects.map((project) => ({ + id: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), + title: project.name, + description: project.cwd, + keywords: [project.cwd], + group: "Projects", + icon: ( + + ), + run: async () => { + await startNewThreadInProjectFromContext( + contextRef.current, + scopeProjectRef(project.environmentId, project.id), + ); + }, + })), + [projects], + ); + + // Lead chats (docs/design/lead-chat.md): one "Go to" per project that has + // one, and "New lead chat" for the project in scope when it has none. + const leadChatItems: CommandListItem[] = []; + for (const project of projects) { + const leadRef = projectLeadRef(useStore.getState(), project); + if (leadRef === null) continue; + leadChatItems.push({ + id: scopedThreadKey(leadRef), + title: "Go to lead chat", + description: project.name, + keywords: [project.name], + run: () => + navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(leadRef) }), + }); + } + // The open thread's or draft's project (none until its computer's projects + // load); the first project only when neither is open. + const leadScopeProject = + currentProjectId !== null + ? (currentProject ?? undefined) + : defaultProjectRef + ? projects.find( + (project) => + project.environmentId === defaultProjectRef.environmentId && + project.id === defaultProjectRef.projectId, + ) + : undefined; + const offersNewLeadChat = + leadScopeProject !== undefined && + leadScopeProject.kind === "workspace" && + environmentSupportsProjectLead(leadScopeProject.environmentId) && + leadSettingRefusal(leadScopeProject.environmentId) === null && + projectLeadRef(useStore.getState(), leadScopeProject) === null; + + const hasProjects = projects.length > 0; + const projectTitle = hasProjects ? (currentProject?.name ?? null) : null; + + useCommandHandlers({ + "chat.new": projectTitle !== null && { + title: "New thread in", + titleEmphasis: projectTitle, + run: async () => { + await startNewThreadFromContext(context); + }, + }, + // As its shortcut, where New thread is offered. + // As its shortcut: wherever there is a project to start in, Home included. + "chat.newLocal": resolveThreadActionProjectRef(context) !== null && { + run: async () => { + await startNewLocalThreadFromContext(context); + }, + }, + "codex.import": projectTitle !== null && + currentProject?.kind === "workspace" && + currentProjectCwd !== null && + availableCodexInstances.length > 0 && { + opensDialog: true, + // Takes the project, its accounts and the open thread's mode as they are now. + run: async () => { + const sessionId = openCodexImport({ + project: { + environmentId: currentProject.environmentId, + projectId: currentProject.id, + projectName: currentProject.name, + cwd: currentProject.cwd, + }, + accounts: availableCodexInstances.map((instance) => ({ + instanceId: instance.instanceId, + displayName: instance.displayName, + })), + runtimeMode: + openThreadRuntimeMode ?? + activeDraftThread?.runtimeMode ?? + DEFAULT_NEW_THREAD_RUNTIME_MODE, + returnFocus: focusComposer, + }); + // Closing the dialog without bringing one in isn't a use. + return (await waitForCodexImportSessionEnd(sessionId)) === "imported" + ? undefined + : "cancelled"; + }, + }, + "worktrees.pickUp": projectTitle !== null && + currentProjectRef !== null && + worktreePickup.candidates.length > 0 && { + // Lays the list out on the new-thread screen, where each worktree + // can be ticked; it also brings a hidden count back. + run: async () => { + useWorktreePickupStore.getState().offer(scopedProjectKey(currentProjectRef)); + await handleNewThread(currentProjectRef, { continueActiveCheckout: false }); + }, + }, + "project.brief": hasProjects && + currentProject?.kind === "workspace" && + supportsProjectBrief(currentProject.environmentId) && { + description: currentProject.name, + keywords: [currentProject.name], + run: () => navigate(projectBriefLocation(currentProject)), + }, + "chat.newIn": hasProjects && { items: newThreadInItems, placeholder: "Search..." }, + "project.add": { + opensDialog: true, + run: async () => { + const sessionId = openAddProject({ returnFocus: focusComposer }); + // Closing the dialog without adding one isn't a use. + return (await waitForAddProjectSessionEnd(sessionId)) === "added" ? undefined : "cancelled"; + }, + }, + "project.setUpElsewhere": openThreadProjectRef !== null && + projectSetupTargets.length > 0 && { + run: () => openProjectSetupDialog({ project: openThreadProjectRef }), + }, + "leadChat.goTo": leadChatItems.length > 0 && { items: leadChatItems }, + "leadChat.new": offersNewLeadChat && + leadScopeProject !== undefined && { + description: leadScopeProject.name, + run: async () => { + const leadRef = await createLeadChat(leadScopeProject); + if (leadRef !== null) { + await navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(leadRef), + }); + } + }, + }, + }); +} diff --git a/apps/web/src/commands/runCommand.ts b/apps/web/src/commands/runCommand.ts new file mode 100644 index 000000000..b5eedbbc7 --- /dev/null +++ b/apps/web/src/commands/runCommand.ts @@ -0,0 +1,77 @@ +/** + * Running an offered command from the palette, in today's order: resolve the + * row again by id against the current handlers and take its function, close + * unless it keeps the palette open, then run it in the same tick, or one + * frame later for a command that needs focus back in the page first. A run + * that resolves to "cancelled" is not counted as use. + */ +import type { AppCommandId } from "@threadlines/shared/appCommands"; + +import { + resolveCommandHandler, + resolveCommandListItem, + type CommandRun, + type CommandRunResult, +} from "./commandHandlers"; +import { commandUsageKey } from "./commandUsageStore"; + +export type CommandRunOutcome = + /** The row is gone, or shown disabled: nothing happened. */ + | "unavailable" + /** A list command: the caller opens its page. */ + | "list" + | "ran"; + +export interface RunCommandInput { + readonly id: AppCommandId; + /** An item of a list command. */ + readonly itemId?: string | undefined; + /** Closes the palette. `handingOver`: another dialog owns where focus goes. */ + readonly close: (options: { readonly handingOver: boolean }) => void; + readonly recordUse: (key: string) => void; + readonly onError: (error: unknown) => void; + /** One frame later, for commands that wait for focus to come back. */ + readonly nextFrame?: (callback: () => void) => void; +} + +export function runCommand(input: RunCommandInput): CommandRunOutcome { + const handler = resolveCommandHandler(input.id); + if (!handler || handler.disabledReason !== undefined) return "unavailable"; + + let run: CommandRun; + if (input.itemId === undefined) { + if (handler.items !== undefined) return "list"; + run = handler.run; + } else { + const item = resolveCommandListItem(input.id, input.itemId); + if (!item || item.disabled) return "unavailable"; + run = item.run; + } + + if (!handler.keepOpen) input.close({ handingOver: handler.opensDialog === true }); + const settle = (result: CommandRunResult | Promise) => { + void Promise.resolve(result).then( + (outcome) => { + if (outcome === "cancelled") return; + // An item counts for its list too, so a script run every day brings + // "Run script…" into Suggested. + input.recordUse(input.id); + if (input.itemId !== undefined) input.recordUse(commandUsageKey(input.id, input.itemId)); + }, + (error: unknown) => input.onError(error), + ); + }; + const start = () => { + try { + settle(run()); + } catch (error) { + input.onError(error); + } + }; + if (handler.afterFocusReturns) { + (input.nextFrame ?? ((callback) => window.requestAnimationFrame(callback)))(start); + } else { + start(); + } + return "ran"; +} diff --git a/apps/web/src/commands/threadCommands.ts b/apps/web/src/commands/threadCommands.ts new file mode 100644 index 000000000..3eb3a6497 --- /dev/null +++ b/apps/web/src/commands/threadCommands.ts @@ -0,0 +1,146 @@ +/** + * The open thread's own commands for the palette: its menu's actions, run + * through `useThreadMenu` with the menu's confirmations, and Move. Registered + * while the palette is open (PaletteCommandSources). + */ +import { scopedThreadKey } from "@threadlines/client-runtime"; +import type { ScopedThreadRef } from "@threadlines/contracts"; +import type { AppCommandId } from "@threadlines/shared/appCommands"; + +import type { ThreadMenuAction } from "../components/threadMenu.logic"; +import { openThreadMoveDialog } from "../components/ThreadMoveDialog"; +import { useThreadMoveOffered } from "../environments/links/threadMoves"; +import { useHandleNewThread } from "../hooks/useHandleNewThread"; +import { useInboxThreads } from "../hooks/useInboxThreads"; +import { useThreadMenu } from "../hooks/useThreadMenu"; +import { selectThreadByRef, useStore } from "../store"; +import { threadMoveStatus } from "../threadMove"; +import { + useCommandHandlers, + type CommandActionHandler, + type CommandHandlerMap, +} from "./commandHandlers"; + +/** + * The menu's actions the palette offers, by their command. Mark unread, + * separate, put back, stop children and move up or down stay in the menu; + * Move is its own command below. + */ +const PALETTE_THREAD_ACTIONS: Partial> = { + rename: "thread.rename", + pin: "thread.pin", + unpin: "thread.unpin", + "copy-path": "thread.copyPath", + "copy-thread-id": "thread.copyId", + archive: "thread.archive", + delete: "thread.delete", +}; + +/** + * The menu's actions that need the inbox's word on the thread: Wrap up or + * Reopen, and making it the lead, which reopens a wrapped thread. + */ +const INBOX_THREAD_ACTIONS: Partial> = { + "make-lead": "thread.makeLead", + "stop-lead": "thread.stopLead", + "wrap-up": "thread.wrapUp", + reopen: "thread.reopen", +}; + +/** The menu's words for these, which change with the thread; the rest use the catalog's. */ +const ACTIONS_WITH_MENU_WORDS = new Set(["make-lead", "stop-lead"]); + +type InboxFacts = { readonly isDone: boolean; readonly canMarkDone: boolean } | null; + +function menuCommandHandlers(input: { + readonly threadMenu: ReturnType; + readonly threadRef: ScopedThreadRef; + readonly inbox: InboxFacts; + readonly actions: Partial>; +}): Partial> { + const target = { threadRef: input.threadRef, inbox: input.inbox }; + const handlers: Partial> = {}; + for (const item of input.threadMenu.describe(target) ?? []) { + const commandId = input.actions[item.id]; + if (!commandId || item.disabled) continue; + handlers[commandId] = { + ...(ACTIONS_WITH_MENU_WORDS.has(item.id) ? { title: item.label } : {}), + run: () => input.threadMenu.run(item.id, target), + }; + } + return handlers; +} + +/** The open thread's project, or null while no saved thread is open. */ +function useOpenThreadProjectId(threadRef: ScopedThreadRef | null) { + return useStore((state) => + threadRef ? (selectThreadByRef(state, threadRef)?.projectId ?? null) : null, + ); +} + +/** + * The open thread's menu actions that don't need the inbox, and Move. It + * reads single facts about the thread, so a streamed reply re-renders none + * of it. + */ +export function useThreadCommands(): void { + const { routeThreadRef } = useHandleNewThread(); + // The facts these commands read about the open thread, not the thread: + // its project (null while it isn't saved), whether it is pinned, and where + // it is in a move. + const threadProjectId = useOpenThreadProjectId(routeThreadRef); + useStore((state) => + routeThreadRef ? (selectThreadByRef(state, routeThreadRef)?.pinnedAt ?? null) : null, + ); + const moveStatus = useStore((state) => { + const thread = routeThreadRef ? selectThreadByRef(state, routeThreadRef) : undefined; + return thread ? threadMoveStatus(thread) : undefined; + }); + const threadMenu = useThreadMenu(); + const moveOffered = useThreadMoveOffered( + routeThreadRef && threadProjectId !== null + ? { environmentId: routeThreadRef.environmentId, projectId: threadProjectId, moveStatus } + : null, + ); + + let handlers: Partial> = {}; + if (routeThreadRef && threadProjectId !== null) { + const threadRef = routeThreadRef; + handlers = menuCommandHandlers({ + threadMenu, + threadRef, + inbox: null, + actions: PALETTE_THREAD_ACTIONS, + }); + // Where its computer can move it: one linked computer at least, and the + // thread not already on its way. The dialog says why one can't go. + // Its dialog returns focus to what had it when it opened, which the + // palette's own focus return makes the composer: no hand-over here. + handlers["thread.move"] = moveOffered && { run: () => openThreadMoveDialog(threadRef) }; + } + useCommandHandlers(handlers as CommandHandlerMap); +} + +/** + * Wrap up, Reopen and the lead commands for the open thread. The inbox says + * which apply, and reading it re-derives every thread's place on each change, + * a streamed token included, so this source is kept apart from the rest. + */ +export function useThreadInboxCommands(): void { + const { routeThreadRef } = useHandleNewThread(); + const threadProjectId = useOpenThreadProjectId(routeThreadRef); + const threadMenu = useThreadMenu(); + const { entries } = useInboxThreads(); + let handlers: Partial> = {}; + if (routeThreadRef && threadProjectId !== null) { + const threadKey = scopedThreadKey(routeThreadRef); + const entry = entries.find((candidate) => candidate.threadKey === threadKey); + handlers = menuCommandHandlers({ + threadMenu, + threadRef: routeThreadRef, + inbox: entry ? { isDone: entry.isDone, canMarkDone: entry.canMarkDone } : null, + actions: INBOX_THREAD_ACTIONS, + }); + } + useCommandHandlers(handlers as CommandHandlerMap); +} diff --git a/apps/web/src/components/ChatView.browser-harness.tsx b/apps/web/src/components/ChatView.browser-harness.tsx index 8b2d07121..322224cba 100644 --- a/apps/web/src/components/ChatView.browser-harness.tsx +++ b/apps/web/src/components/ChatView.browser-harness.tsx @@ -3113,6 +3113,30 @@ export async function openCommandPaletteFromTrigger(): Promise { ); } +/** + * Switches the open palette to every command, through its "All commands" row. + * The palette opens on recent threads and a few suggestions, so a test that + * runs a command by name goes here first, as a user would. + */ +export async function showAllPaletteCommands(): Promise { + await page.getByTestId("command-palette").getByText("All commands", { exact: true }).click(); + await vi.waitFor( + () => { + const input = document.querySelector( + '[data-testid="command-palette"] input', + ); + expect(input?.value).toBe(">"); + }, + { timeout: 8_000, interval: 16 }, + ); +} + +/** Opens the palette from the sidebar and shows every command. */ +export async function openCommandPaletteCommands(): Promise { + await openCommandPaletteFromTrigger(); + await showAllPaletteCommands(); +} + export async function waitForNewThreadShortcutLabel(): Promise { const newThreadButton = page.getByTestId("new-thread-button"); await expect.element(newThreadButton).toBeInTheDocument(); diff --git a/apps/web/src/components/ChatView.codex-import.browser.tsx b/apps/web/src/components/ChatView.codex-import.browser.tsx index 00479db5f..b8fee6df5 100644 --- a/apps/web/src/components/ChatView.codex-import.browser.tsx +++ b/apps/web/src/components/ChatView.codex-import.browser.tsx @@ -9,7 +9,7 @@ import { createSnapshotForTargetUser, dispatchInputKey, mountChatView, - openCommandPaletteFromTrigger, + openCommandPaletteCommands, registerChatViewSuiteHooks, waitForCommandPaletteInput, waitForServerConfigToApply, @@ -96,7 +96,7 @@ describe("ChatView (full app): bring in a Codex conversation", () => { try { await waitForServerConfigToApply(); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); const palette = page.getByTestId("command-palette"); await expect .element(palette.getByText("Bring in Codex conversation…", { exact: true })) @@ -211,7 +211,7 @@ describe("ChatView (full app): bring in a Codex conversation", () => { try { await waitForServerConfigToApply(); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Bring in Codex conversation…", { exact: true }) diff --git a/apps/web/src/components/ChatView.move-thread.browser.tsx b/apps/web/src/components/ChatView.move-thread.browser.tsx index 99d3e86f0..74467aad7 100644 --- a/apps/web/src/components/ChatView.move-thread.browser.tsx +++ b/apps/web/src/components/ChatView.move-thread.browser.tsx @@ -66,7 +66,7 @@ import { waitForElement, waitForURL, waitForServerConfigToApply, - openCommandPaletteFromTrigger, + openCommandPaletteCommands, mountChatView, registerChatViewSuiteHooks, PROJECT_SETUP_SOURCE, @@ -347,7 +347,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { await saveMacMini("disconnected"); await expect.element(page.getByRole("button", { name: "Toggle panel" })).toBeVisible(); // Nowhere to move it yet: the palette doesn't offer it. - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); expect( page .getByTestId("command-palette") @@ -381,7 +381,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { .toBeVisible(); await userEvent.keyboard("{Escape}"); // The command palette too, where the dialog opens from here. - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -434,7 +434,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), ).toBe(true); }); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -566,7 +566,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { try { await waitForServerConfigToApply(); await saveMacMini("connected"); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -800,7 +800,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), ).toBe(true); }); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -847,7 +847,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { // A command runs in the user's terminal, which nothing here stops: // stopping isn't offered, says why, and waiting stays picked. waitsFor = [{ code: "command_run", words: "when its command finishes running" }]; - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -916,7 +916,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), ).toBe(true); }); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -1004,7 +1004,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { try { await waitForServerConfigToApply(); await saveMacMini("connected"); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -1109,7 +1109,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { try { await waitForServerConfigToApply(); await saveMacMini("connected"); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -1191,7 +1191,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { }); const openDialog = async () => { - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -1460,7 +1460,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { readThreadMoveOffered({ environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID }), ).toBe(true); }); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move to another computer", { exact: true }) @@ -1577,7 +1577,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { .element(page.getByTestId(`thread-meta-${THREAD_ID}`)) .toMatchTextContent("moving"); // Nothing else to do with it here, and no other way off it. - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); expect( page .getByTestId("command-palette") @@ -2002,7 +2002,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { try { await waitForServerConfigToApply(); await saveMacMini("connected"); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move threads to another computer…", { exact: true }) @@ -2142,7 +2142,7 @@ describe("ChatView (full app): moving a thread to another computer", () => { try { await waitForServerConfigToApply(); await saveMacMini("connected"); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Move threads to another computer…", { exact: true }) diff --git a/apps/web/src/components/ChatView.palette.browser.tsx b/apps/web/src/components/ChatView.palette.browser.tsx index 54bbe125f..99788aa61 100644 --- a/apps/web/src/components/ChatView.palette.browser.tsx +++ b/apps/web/src/components/ChatView.palette.browser.tsx @@ -1,6 +1,8 @@ import { + EventId, ORCHESTRATION_WS_METHODS, MessageId, + type OrchestrationEvent, type OrchestrationReadModel, OutsideAgentConnectionId, OutsideAgentRequestId, @@ -12,10 +14,15 @@ import { page } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; import { useCommandPaletteStore } from "../commandPaletteStore"; +import { getOfferedCommands } from "../commands/commandHandlers"; +import { useCommandUsageStore } from "../commands/commandUsageStore"; +import { setCommandPaletteCommitListenerForTests } from "./CommandPalette"; import { useComposerDraftStore } from "../composerDraftStore"; import { THREAD_ID, + NOW_ISO, + fixture, PROJECT_ID, SECOND_PROJECT_ID, LOCAL_ENVIRONMENT_ID, @@ -38,6 +45,8 @@ import { CHAT_FIND_KEYBINDING, triggerChatNewShortcutUntilPath, openCommandPaletteFromTrigger, + openCommandPaletteCommands, + showAllPaletteCommands, waitForCommandPaletteShortcutLabel, mountChatView, registerChatViewSuiteHooks, @@ -80,7 +89,7 @@ describe("ChatView (full app): command palette and search", () => { try { await waitForServerConfigToApply(); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); const palette = page.getByTestId("command-palette"); await expect.element(palette.getByText("Find in chat", { exact: true })).toBeInTheDocument(); await palette.getByText("Find in chat", { exact: true }).click(); @@ -184,7 +193,7 @@ describe("ChatView (full app): command palette and search", () => { // What the server says from now on, should the stream open again. setPrimaryOutsideAgentsSnapshot({ ...outsideAgents, pending: [] }); - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Connect an agent", { exact: true }) @@ -200,6 +209,7 @@ describe("ChatView (full app): command palette and search", () => { // "Connect an assistant" opens the Assistants group and shows a code. // Settings has no palette button of its own: open it as its shortcut does. useCommandPaletteStore.getState().setOpen(true); + await showAllPaletteCommands(); await page .getByTestId("command-palette") .getByText("Connect an assistant", { exact: true }) @@ -217,6 +227,243 @@ describe("ChatView (full app): command palette and search", () => { } }); + it("offers exactly the commands their owners register, on a thread and on the home screen", async () => { + // The guard for the availability rules: each moved next to the code it + // protects, so a rule lost in a move shows up here as a change. + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-offered-commands" as MessageId, + targetText: "offered commands", + }), + }); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + await vi.waitFor(() => expect(getOfferedCommands().has("thread.rename")).toBe(true)); + expect([...getOfferedCommands().keys()].toSorted()).toEqual([ + "app.reportProblem", + "app.whatsNew", + "chat.find", + "chat.new", + "chat.newGeneral", + "chat.newIn", + "chat.newLocal", + "composer.planMode", + "composer.stash", + "computer.connect", + "diff.toggle", + "files.browse", + "modelPicker.toggle", + "navigate.communityAgents", + "navigate.fleet", + "navigate.generalChats", + "navigate.home", + "navigate.settings", + "navigate.setup", + "navigate.skills", + "navigate.terminals", + "navigate.usage", + "panel.agents", + "panel.diff", + "panel.sourceControl", + "panel.threads", + "project.add", + "room.addAgent", + "sidebar.toggle", + "terminal.clear", + "terminal.close", + "terminal.find", + "terminal.new", + "terminal.restart", + "terminal.split", + "terminal.toggle", + "theme.change", + "theme.editColors", + "theme.useDefault", + "thread.archive", + "thread.copyId", + "thread.copyPath", + "thread.delete", + "thread.pin", + "thread.rename", + "thread.wrapUp", + ]); + + await showAllPaletteCommands(); + await page.getByTestId("command-palette").getByText("Go to Home", { exact: true }).click(); + await waitForURL(mounted.router, (path) => path === "/", "Go to Home should open Home."); + await openCommandPaletteFromTrigger(); + // Nothing of the thread's is offered once it is off screen. + await vi.waitFor(() => expect(getOfferedCommands().has("terminal.toggle")).toBe(false)); + expect([...getOfferedCommands().keys()].toSorted()).toEqual([ + "app.reportProblem", + "app.whatsNew", + "chat.newGeneral", + "chat.newIn", + "chat.newLocal", + "computer.connect", + "navigate.back", + "navigate.communityAgents", + "navigate.fleet", + "navigate.generalChats", + "navigate.settings", + "navigate.setup", + "navigate.skills", + "navigate.terminals", + "navigate.usage", + "project.add", + "sidebar.toggle", + "theme.change", + "theme.editColors", + "theme.useDefault", + "thread.next", + "thread.previous", + ]); + } finally { + await mounted.cleanup(); + } + }); + + it("opens on recent threads, then suggested commands, and learns which ones are used", async () => { + useCommandUsageStore.setState({ byKey: {} }); + const olderThreadId = "thread-opening-older" as ThreadId; + const newerThreadId = "thread-opening-newer" as ThreadId; + const base = addThreadToSnapshot( + addThreadToSnapshot( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-opening-list" as MessageId, + targetText: "opening list", + }), + olderThreadId, + ), + newerThreadId, + ); + const snapshot = { + ...base, + threads: base.threads.map((thread) => + thread.id === olderThreadId + ? { ...thread, title: "Older plan", updatedAt: "2026-03-01T10:00:00.000Z" } + : thread.id === newerThreadId + ? { ...thread, title: "Newer plan", updatedAt: "2026-03-02T10:00:00.000Z" } + : thread, + ), + }; + const openTitle = snapshot.threads.find((thread) => thread.id === THREAD_ID)!.title; + const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, snapshot }); + + const groupsAndRows = () => + Array.from( + document.querySelectorAll( + '[data-testid="command-palette"] [data-slot="command-group-label"], [data-testid="command-palette"] [data-slot="command-item"]', + ), + ).map((element) => + element.dataset.slot === "command-group-label" + ? `# ${element.textContent?.trim()}` + : (element.querySelector("span span")?.textContent?.trim() ?? + element.textContent?.trim() ?? + ""), + ); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + await vi.waitFor(() => { + const shown = groupsAndRows(); + expect(shown.filter((entry) => entry.startsWith("# "))).toEqual([ + "# Recent threads", + "# Suggested", + "# Commands", + ]); + // Latest activity first, and not the thread on screen. + expect(shown.indexOf("Newer plan")).toBeLessThan(shown.indexOf("Older plan")); + expect(shown).not.toContain(openTitle); + }); + const palette = page.getByTestId("command-palette"); + // Before this device has used anything: the first suggestions, as far as each is offered. + for (const title of ["Toggle terminal", "Toggle panel", "Add project"]) { + await expect.element(palette.getByText(title, { exact: true })).toBeInTheDocument(); + } + + await showAllPaletteCommands(); + await palette.getByText("Open usage", { exact: true }).click(); + await waitForURL(mounted.router, (path) => path === "/usage", "Open usage should open it."); + + // Usage has no Search field of its own: open it as its shortcut does. + useCommandPaletteStore.getState().setOpen(true); + await vi.waitFor(() => { + const shown = groupsAndRows(); + const suggested = shown.slice(shown.indexOf("# Suggested") + 1); + expect(suggested[0]).toBe("Open usage"); + }); + } finally { + await mounted.cleanup(); + } + }); + + it("commits nothing in the palette's rows and command sources while a reply streams (Wrap up and Reopen sit outside)", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-streaming" as MessageId, + targetText: "palette while streaming", + }), + }); + let commits = 0; + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + // Let the palette and its command sources settle before counting. + for (let frame = 0; frame < 10; frame += 1) await waitForLayout(); + setCommandPaletteCommitListenerForTests(() => { + commits += 1; + }); + + const messageId = MessageId.make("msg-assistant-streaming-behind-palette"); + let text = ""; + for (let token = 0; token < 20; token += 1) { + text += `word${token} `; + rpcHarness.emitStreamValue(ORCHESTRATION_WS_METHODS.subscribeThread, { + kind: "event", + event: { + sequence: fixture.snapshot.snapshotSequence + 1 + token, + eventId: EventId.make(`evt-streaming-behind-palette-${token}`), + aggregateKind: "thread", + aggregateId: THREAD_ID, + // Each token arrives later than the last, as a real stream's do. + occurredAt: new Date(Date.parse(NOW_ISO) + (token + 1) * 1000).toISOString(), + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.message-sent", + payload: { + threadId: THREAD_ID, + messageId, + role: "assistant", + text, + turnId: null, + streaming: true, + createdAt: NOW_ISO, + updatedAt: NOW_ISO, + }, + } satisfies OrchestrationEvent, + }); + await waitForLayout(); + } + // The reply did reach the chat behind the palette. + await vi.waitFor(() => expect(document.body.textContent).toContain("word19")); + for (let frame = 0; frame < 5; frame += 1) await waitForLayout(); + + expect(commits).toBe(0); + } finally { + setCommandPaletteCommitListenerForTests(null); + await mounted.cleanup(); + } + }); + it("stays open under StrictMode", async () => { // The app mounts under StrictMode, which runs every new effect's cleanup // once right after mount. An unmount reset on the open dialog turned that @@ -253,7 +500,7 @@ describe("ChatView (full app): command palette and search", () => { }); try { - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); const palette = page.getByTestId("command-palette"); await palette.getByText("Add agent", { exact: true }).click(); diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index 8dd8072b6..f1af6ddd6 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -87,7 +87,7 @@ import { toShellSnapshot, clickProjectMenuItem, registerChatViewSuiteHooks, - openCommandPaletteFromTrigger, + openCommandPaletteCommands, } from "./ChatView.browser-harness"; vi.mock("../lib/gitStatusState", () => ({ @@ -966,7 +966,7 @@ describe("ChatView (full app): sidebar", () => { await userEvent.keyboard("{Escape}"); // The palette's Rename asks in a dialog, and saving sends the new name. - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page.getByTestId("command-palette").getByText("Rename thread", { exact: true }).click(); const input = page.getByTestId("thread-rename-input"); await expect.element(input).toHaveValue(THREAD_TITLE); @@ -1234,7 +1234,7 @@ describe("ChatView (full app): sidebar", () => { // The palette opens the section where the user is, adding no step to Back. const historyLength = window.history.length; - await openCommandPaletteFromTrigger(); + await openCommandPaletteCommands(); await page .getByTestId("command-palette") .getByText("Open general chats", { exact: true }) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1af8b29d2..56ceec822 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -300,7 +300,8 @@ import { ManagedTerminalDrawer, type ManagedTerminalDrawerProps, } from "./terminal/ManagedTerminalDrawer"; -import { type TerminalCommandKind, useTerminalCommandsStore } from "../terminalCommands"; +import { useCommandHandlers } from "../commands/commandHandlers"; +import { openActiveFileViewer } from "../fileViewerStore"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; import { McpAppSidePanel } from "./chat/McpAppCard"; import { NO_COMPOSER_PULL_REQUESTS, type ComposerPullRequest } from "./chat/ComposerPullRequestRow"; @@ -498,6 +499,9 @@ import { resolveComposerProviderSelection, } from "../providerInstances"; +/** The terminal actions the command palette runs for the thread on screen. */ +type TerminalCommandKind = "toggle" | "new" | "split" | "find" | "clear" | "restart" | "kill"; + const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more files without additional text. Respond using the conversation context and the attached file(s).]"; const EMPTY_WORKFLOW_RUNS: ReadonlyArray = []; @@ -4210,8 +4214,22 @@ export default function ChatView(props: ChatViewProps) { [], ); + // A Restart or Kill from the palette waits here for the confirmation's + // answer, so a "Cancel" isn't counted as using the command. + const terminalConfirmationRef = useRef<((confirmed: boolean) => void) | null>(null); + const settleTerminalConfirmation = (confirmed: boolean) => { + const settle = terminalConfirmationRef.current; + terminalConfirmationRef.current = null; + settle?.(confirmed); + }; + const awaitTerminalConfirmation = () => + new Promise<"cancelled" | undefined>((resolve) => { + settleTerminalConfirmation(false); + terminalConfirmationRef.current = (confirmed) => resolve(confirmed ? undefined : "cancelled"); + }); const confirmPendingTerminalAction = useCallback(() => { if (!pendingTerminalAction) return; + settleTerminalConfirmation(true); const perform = pendingTerminalAction.kind === "kill" ? performCloseTerminal : performRestartTerminal; perform( @@ -5108,9 +5126,8 @@ export default function ChatView(props: ChatViewProps) { toggleTerminalVisibility, ]); - // Terminal actions asked for in the command palette, for this thread. - const terminalCommandRequest = useTerminalCommandsStore((state) => state.request); - const handledTerminalCommandNonceRef = useRef(terminalCommandRequest?.nonce ?? 0); + // The terminal's actions as the command palette runs them: a closed drawer + // opens for Find, and Restart and Kill ask first like the drawer's buttons. const runTerminalCommand = useEffectEvent((kind: TerminalCommandKind) => { if (!activeThreadRef || !activeThreadId) return; const terminalId = terminalState.activeTerminalId; @@ -5135,25 +5152,69 @@ export default function ChatView(props: ChatViewProps) { ?.terminal.clear({ threadId: activeThreadId, terminalId }) .catch(() => undefined); return; - case "restart": + case "restart": { setTerminalOpen(true); + const asks = terminalStopNeedsConfirm(activeThreadRef, terminalId); requestRestartTerminal(activeThreadRef, activeThreadId, terminalId); - return; - case "kill": + return asks ? awaitTerminalConfirmation() : undefined; + } + case "kill": { + const asks = terminalStopNeedsConfirm(activeThreadRef, terminalId); requestCloseTerminal(activeThreadRef, activeThreadId, terminalId); - return; + return asks ? awaitTerminalConfirmation() : undefined; + } } }); - useEffect(() => { - if ( - !terminalCommandRequest || - terminalCommandRequest.nonce === handledTerminalCommandNonceRef.current - ) { - return; - } - handledTerminalCommandNonceRef.current = terminalCommandRequest.nonce; - runTerminalCommand(terminalCommandRequest.kind); - }, [terminalCommandRequest]); + // This thread's commands in the palette. Each registers what its button or + // shortcut ends in, and only while that path would act. + const projectScripts = activeProject?.scripts; + const scriptCommandItems = useMemo( + () => + (projectScripts ?? []).map((script) => ({ + id: script.id, + title: script.name, + keywords: [script.command], + run: () => { + void runProjectScript(script); + }, + })), + [projectScripts, runProjectScript], + ); + const terminalHandler = (kind: TerminalCommandKind) => ({ + // After the palette has closed and handed focus back. + afterFocusReturns: true, + run: () => runTerminalCommand(kind), + }); + useCommandHandlers({ + "terminal.toggle": terminalHandler("toggle"), + "terminal.new": terminalHandler("new"), + "terminal.split": terminalHandler("split"), + "terminal.find": terminalHandler("find"), + "terminal.restart": terminalHandler("restart"), + "terminal.clear": terminalHandler("clear"), + "terminal.close": terminalHandler("kill"), + // Where find in chat can open: a saved chat on screen, off phones. + "chat.find": canFindInChat && { + // After the palette has closed and handed focus back, so the bar's + // field keeps it. + afterFocusReturns: true, + run: () => useChatFindStore.getState().requestOpen(null), + }, + // The header's panel toggle, for a thread the panel can show. + "diff.toggle": activeThread !== undefined && { run: onToggleRail }, + "project.runScript": scriptCommandItems.length > 0 && { + items: scriptCommandItems, + placeholder: "Run a script...", + }, + // As the header's button: a project thread with a project to browse. + "files.browse": !isGeneralChatThread && + activeProject !== undefined && { + run: () => { + openActiveFileViewer(); + }, + }, + "browser.toggle": browserAvailable && { run: handleToggleBrowser }, + }); const onRevertToTurnCount = useCallback( async (turnCount: number, revertedMessageText?: string) => { @@ -9258,7 +9319,10 @@ export default function ChatView(props: ChatViewProps) { action={pendingTerminalAction} host="thread" onConfirm={confirmPendingTerminalAction} - onCancel={() => setPendingTerminalAction(null)} + onCancel={() => { + settleTerminalConfirmation(false); + setPendingTerminalAction(null); + }} /> {previewedFile && } diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index d6d33e122..0f52b7c6a 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -1,5 +1,6 @@ import { type EnvironmentId, type KeybindingCommand, type MessageId } from "@threadlines/contracts"; import { scopedThreadKey, scopeThreadRef } from "@threadlines/client-runtime"; +import type { AppCommandId } from "@threadlines/shared/appCommands"; import { analyzeSearchText, parseSearchQuery, @@ -9,7 +10,10 @@ import { type ReactNode } from "react"; import { sortThreads } from "../lib/threadSort"; import { type Project, type SidebarThreadSummary, type Thread } from "../types"; -export const RECENT_THREAD_LIMIT = 12; +/** The opening list's recent threads. */ +export const RECENT_THREAD_LIMIT = 5; +/** The opening list's suggested commands. */ +export const SUGGESTED_COMMAND_LIMIT = 4; export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80"; export const ADDON_ICON_CLASS = "size-4"; @@ -30,6 +34,8 @@ export interface CommandPaletteItem { readonly shortcutCommand?: KeybindingCommand; readonly threadRef?: Pick; readonly threadContentMatch?: ThreadContentSearchMatch & { readonly query: string }; + /** A registered command (or one item of a list command), resolved again by id when it runs. */ + readonly command?: { readonly id: AppCommandId; readonly itemId?: string }; } export interface CommandPaletteActionItem extends CommandPaletteItem { @@ -62,6 +68,8 @@ export interface CommandPaletteView { EnvironmentId, ReadonlyArray >; + /** A list command's page: its rows are drawn from the command's current items. */ + readonly listCommandId?: AppCommandId; } export function normalizeSearchText(value: string): string { @@ -332,21 +340,28 @@ export function filterCommandPaletteGroups(input: { }); } -export function buildRootGroups(input: { - actionItems: ReadonlyArray; +/** + * What the palette shows before anything is typed: where you'd go (the + * threads you were in), then the commands you use most, then a way into + * every command. + */ +export function buildOpeningGroups(input: { recentThreadItems: ReadonlyArray; + suggestedItems: ReadonlyArray; + allCommandsItem: CommandPaletteActionItem; }): CommandPaletteGroup[] { const groups: CommandPaletteGroup[] = []; - if (input.actionItems.length > 0) { - groups.push({ value: "actions", label: "Actions", items: input.actionItems }); - } if (input.recentThreadItems.length > 0) { groups.push({ value: "recent-threads", - label: "Recent Threads", + label: "Recent threads", items: input.recentThreadItems, }); } + if (input.suggestedItems.length > 0) { + groups.push({ value: "suggested", label: "Suggested", items: input.suggestedItems }); + } + groups.push({ value: "all-commands", label: "Commands", items: [input.allCommandsItem] }); return groups; } diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 9dd5f65fb..9884371f0 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -1,7 +1,7 @@ "use client"; import { useParams } from "@tanstack/react-router"; -import { lazy, Suspense, useEffect, useRef, type ReactNode } from "react"; +import { lazy, Profiler, Suspense, useEffect, useRef, type ReactNode } from "react"; import { useCommandPaletteStore } from "../commandPaletteStore"; import { isPaletteLaunchedDialogOpen } from "../commands/shortcutBlock"; @@ -21,6 +21,9 @@ const loadCommandPaletteDialog = () => import("./CommandPaletteDialog"); const OpenCommandPaletteDialog = lazy(() => loadCommandPaletteDialog().then((module) => ({ default: module.OpenCommandPaletteDialog })), ); +const PaletteInboxCommandSource = lazy(() => + loadCommandPaletteDialog().then((module) => ({ default: module.PaletteInboxCommandSource })), +); /** * Fetches the palette's body ahead of its first use. The app calls this once @@ -31,6 +34,24 @@ export function preloadCommandPaletteDialog(): void { void loadCommandPaletteDialog().catch(() => undefined); } +type PaletteCommitListener = (phase: "mount" | "update" | "nested-update") => void; +let paletteCommitListener: PaletteCommitListener | null = null; + +/** + * Tests only: hears every React commit inside the open palette, so a test can + * check that a streaming reply behind it commits nothing there. Counted with a + * Profiler, since frame sampling can't see commits. + */ +export function setCommandPaletteCommitListenerForTests( + listener: PaletteCommitListener | null, +): void { + paletteCommitListener = listener; +} + +function reportPaletteCommit(_id: string, phase: "mount" | "update" | "nested-update"): void { + paletteCommitListener?.(phase); +} + export function CommandPalette({ children }: { children: ReactNode }) { const open = useCommandPaletteStore((store) => store.open); const setOpen = useCommandPaletteStore((store) => store.setOpen); @@ -107,7 +128,12 @@ function CommandPaletteDialog() { // Normally preloaded already; until it arrives the palette stays closed. return ( - + + + + {/* Outside the Profiler on purpose: its rule reads the inbox, which + re-derives on every streamed token (see PaletteInboxCommandSource). */} + ); } diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index 5b30d4e51..d61a86b8a 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -1,70 +1,25 @@ "use client"; -import { usePullRequestRecords } from "../environments/pullRequests/pullRequestRecordsStore"; import { parseScopedThreadKey, scopedProjectKey, - scopedThreadKey, scopeProjectRef, scopeThreadRef, } from "@threadlines/client-runtime"; -import { resolveThreadWorkingCwd } from "@threadlines/shared/threadCwd"; -import { - DEFAULT_NEW_THREAD_RUNTIME_MODE, - type EnvironmentId, - type KeybindingCommand, - type ProjectId, -} from "@threadlines/contracts"; - +import { type EnvironmentId, KeybindingCommand, type ProjectId } from "@threadlines/contracts"; +import { APP_COMMANDS, type AppCommandId } from "@threadlines/shared/appCommands"; import { useQuery } from "@tanstack/react-query"; import { useDebouncedValue } from "@tanstack/react-pacer"; -import { useLocation, useNavigate } from "@tanstack/react-router"; +import { useNavigate } from "@tanstack/react-router"; +import * as Schema from "effect/Schema"; import { ArrowDownIcon, ArrowLeftIcon, ArrowUpIcon, - BotIcon, - ChartColumnIcon, - CloudIcon, - CircleArrowUpIcon, - MessageCircleWarningIcon, - EraserIcon, - FileTextIcon, - FolderGitIcon, + CommandIcon, FolderPlusIcon, - GitPullRequestIcon, - HomeIcon, - LaptopIcon, MessageSquareIcon, - MessageCirclePlusIcon, MessagesSquareIcon, - PanelLeftCloseIcon, - PanelLeftIcon, - PlusIcon, - RotateCcwIcon, - SearchIcon, - SettingsIcon, - SquarePenIcon, - SquareSplitHorizontalIcon, - TerminalSquareIcon, - Trash2Icon, - UsersRoundIcon, - MonitorUpIcon, - CrownIcon, - ScrollTextIcon, - FolderSyncIcon, - WaypointsIcon, - CalendarClockIcon, - CalendarPlusIcon, - ArchiveIcon, - CheckIcon, - CopyIcon, - PencilIcon, - PinIcon, - PinOffIcon, - PlugIcon, - CameraIcon, - SmartphoneIcon, } from "lucide-react"; import { useCallback, @@ -75,83 +30,47 @@ import { useRef, useState, type KeyboardEvent, - type ReactNode, } from "react"; import { useShallow } from "zustand/react/shallow"; + import { useCommandPaletteStore } from "../commandPaletteStore"; -import { openAddProject } from "./addProject/addProjectStore"; -import { - useAddProjectEnvironmentOptions, - useEnvironmentBrowsePlatform, -} from "./addProject/addProjectComputers"; -import { openCodexImport } from "./codexImport/codexImportStore"; -import { useRoomRecipientStore } from "../rooms"; -import { useChatFindStore } from "../chatFindStore"; -import { useComposerCommandsStore } from "../composerCommands"; -import { type TerminalCommandKind, useTerminalCommandsStore } from "../terminalCommands"; -import { derivePendingApprovals } from "../session-logic"; +import { useOfferedCommands, type OfferedCommand } from "../commands/commandHandlers"; +import { COMMAND_ICONS } from "../commands/commandIcons"; +import { suggestCommands, useCommandUsageStore } from "../commands/commandUsageStore"; +import { PaletteCommandSources } from "../commands/PaletteCommandSources"; -import { usePrimaryEnvironmentId } from "../environments/primary"; -import { openComputerRenameDialog, useComputerNaming } from "./DeviceRenameDialog"; -import { useSavedEnvironmentRuntimeStore } from "../environments/runtime"; +export { PaletteInboxCommandSource } from "../commands/PaletteCommandSources"; +import { runCommand } from "../commands/runCommand"; +import { useComposerHandleContext } from "../composerHandleContext"; +import { closeRightPanelSearchParams } from "../diffRouteSearch"; import { holdThreadDetailForOpen, prewarmHighlightedThread } from "../environments/runtime/service"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; -import { useGeneralChats } from "./chats/useGeneralChats"; -import { requestGeneralChatsReveal } from "./chats/generalChatsPlacement"; -import { useInboxThreads } from "../hooks/useInboxThreads"; -import { useThreadMenu } from "../hooks/useThreadMenu"; -import { - createLeadChat, - environmentSupportsProjectLead, - leadSettingRefusal, - projectLeadRef, -} from "../leadChat"; -import { useWorktreePickup } from "../hooks/useWorktreePickup"; -import type { ThreadMenuAction } from "./threadMenu.logic"; -import { useIsMobile } from "../hooks/useMediaQuery"; -import { useSettings } from "../hooks/useSettings"; -import { selectSidebarListShown, useUiStateStore } from "../uiStateStore"; -import { useWorktreePickupStore } from "../worktreePickup"; -import { useRoomsEnabled } from "../hooks/useRoomsEnabled"; - -import { closeRightPanelSearchParams } from "../diffRouteSearch"; - -import { - startNewThreadInProjectFromContext, - startNewThreadFromContext, -} from "../lib/chatThreadActions"; import { isFilesystemBrowseQuery } from "../lib/projectPaths"; - -import { getLatestThreadForProject } from "../lib/threadSort"; import { threadSearchQueryOptions, type ThreadSearchTarget } from "../lib/threadSearchReactQuery"; -import { - PULL_REQUEST_COUNT_REFETCH_INTERVAL_MS, - usePullRequestEnvironments, - usePullRequestLists, -} from "../lib/pullRequestsReactQuery"; -import { useGitStatus } from "../lib/gitStatusState"; -import { useScheduledTaskEnvironments } from "../lib/scheduledTasksState"; -import { resolveThreadPullRequest, threadViewBranch } from "./pull-requests/pullRequests.logic"; -import { - focusRightPanelTab, - pullRequestTabSearchParams, - rightPanelTabSearchParams, -} from "../rightPanelTabs"; +import { getLatestThreadForProject } from "../lib/threadSort"; import { cn, newCommandId } from "../lib/utils"; +import { useServerKeybindings } from "../rpc/serverState"; import { selectProjectsAcrossEnvironments, selectSidebarThreadsAcrossEnvironments, + sidebarThreadSummariesListEqual, useStore, } from "../store"; -import { createThreadSelectorByRef } from "../storeSelectors"; +import type { SidebarThreadSummary } from "../types"; import { buildThreadRouteParams } from "../threadRoutes"; +import { openAddProject } from "./addProject/addProjectStore"; +import { + useAddProjectEnvironmentOptions, + useEnvironmentBrowsePlatform, +} from "./addProject/addProjectComputers"; import { ADDON_ICON_CLASS, applyThreadContentSearchMatches, + buildOpeningGroups, buildProjectActionItems, - buildRootGroups, buildThreadActionItems, type CommandPaletteActionItem, + type CommandPaletteGroup, type CommandPaletteSubmenuItem, type CommandPaletteView, filterCommandPaletteGroups, @@ -160,36 +79,11 @@ import { ITEM_ICON_CLASS, normalizeSearchText, RECENT_THREAD_LIMIT, + SUGGESTED_COMMAND_LIMIT, } from "./CommandPalette.logic"; - import { CommandPaletteResults } from "./CommandPaletteResults"; - -import { openConnectComputerDialog } from "./settings/connections/JoinComputerDialog"; -import { openThreadMoveDialog } from "./ThreadMoveDialog"; -import { openProjectSetupDialog } from "./ProjectSetupDialog"; -import { - PROJECT_BRIEF_MENU_LABEL, - projectBriefLocation, - useProjectBriefSupport, -} from "../projectBrief"; -import { openReportProblemDialog } from "./ReportProblemDialog"; -import { openWhatsNewDialog } from "./WhatsNewDialog"; -import { APP_VERSION } from "../branding"; -import { useProjectSetupTargets } from "../environments/projectSetups/projectSetupTargets"; -import { useMoveThreadsOffered, useThreadMoveOffered } from "../environments/links/threadMoves"; -import { openMoveThreadsDialog } from "./MoveThreadsDialog"; -import { environmentSupportsDevices } from "./device/deviceState"; -import { - startAssistantCode, - useOutsideAgentsSnapshot, -} from "../environments/outsideAgents/outsideAgents"; -import { threadMoveStatus } from "../threadMove"; - import { ProjectFavicon } from "./ProjectFavicon"; import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators"; -import { useServerKeybindings, useServerProviders } from "../rpc/serverState"; - -import { deriveProviderInstanceEntries } from "../providerInstances"; import { Command, CommandDialogPopup, @@ -197,95 +91,129 @@ import { CommandInput, CommandPanel, } from "./ui/command"; - import { Kbd, KbdGroup } from "./ui/kbd"; import { failureNotice, toastManager } from "./ui/toast"; -import { useComposerHandleContext } from "../composerHandleContext"; - const THREAD_CONTENT_SEARCH_DEBOUNCE_MS = 180; const EMPTY_THREAD_CONTENT_MATCHES = [] as const; +const COMMAND_IDS = Object.keys(APP_COMMANDS) as AppCommandId[]; +/** Suggested before this device has used any command, as far as each is offered. */ +const FIRST_SUGGESTIONS: ReadonlyArray = [ + "chat.new", + "terminal.toggle", + "diff.toggle", + "project.add", +]; +const isKeybindingCommand = Schema.is(KeybindingCommand); -const THEME_ITEM_CLASSES = { item: ITEM_ICON_CLASS, addon: ADDON_ICON_CLASS } as const; /** - * The open palette: search, actions and the add-project flows. Loaded on - * demand by CommandPalette, which owns the open state and the shortcut. + * Every thread, as the palette lists them. Kept as the same array while a + * reply streams, which moves only a thread's last-activity time on every + * token, so the open palette doesn't redraw for it. */ +function usePaletteThreads(): ReadonlyArray { + const previous = useRef>([]); + return useStore((state) => { + const next = selectSidebarThreadsAcrossEnvironments(state); + const last = previous.current; + if ( + last.length === next.length && + next.every((thread, index) => sidebarThreadSummariesListEqual(last[index]!, thread)) + ) { + return last; + } + previous.current = next; + return next; + }); +} + +function commandIcon(id: AppCommandId, className: string) { + const Icon = COMMAND_ICONS[id]; + return ; +} + +/** A list page's own heading when its items don't name one: the command's title, unpunctuated. */ +function listHeading(id: AppCommandId): string { + return APP_COMMANDS[id].title.replace(/(…|\.\.\.)$/, ""); +} + +/** The palette row for an offered command: its words from the catalog, unless its owner says otherwise. */ +function commandRow(command: OfferedCommand): CommandPaletteActionItem | CommandPaletteSubmenuItem { + const spec = APP_COMMANDS[command.id]; + const titleText = command.title ?? spec.title; + const title = + command.titleEmphasis === undefined ? ( + titleText + ) : ( + <> + {titleText} {command.titleEmphasis} + + ); + const description = + command.disabledReason ?? command.description ?? ("about" in spec ? spec.about : undefined); + const common = { + value: `command:${command.id}`, + searchTerms: [...("keywords" in spec ? spec.keywords : []), ...(command.keywords ?? [])], + title, + ...(description ? { description } : {}), + icon: commandIcon(command.id, ITEM_ICON_CLASS), + ...(command.disabledReason !== undefined ? { disabled: true } : {}), + ...(isKeybindingCommand(command.id) ? { shortcutCommand: command.id } : {}), + command: { id: command.id }, + }; + if (command.items !== null) { + return { + ...common, + kind: "submenu", + addonIcon: commandIcon(command.id, ADDON_ICON_CLASS), + groups: [], + }; + } + return { ...common, kind: "action", run: async () => undefined }; +} + /** - * The thread menu's actions the palette offers for the open thread, by what - * they are called here. Mark unread, the family's and Move (its own entry) - * stay in the menu. + * The rows of a list command's items, in the list's order. An item is found + * by its own words only, so "theme" finds the theme commands, not every theme. */ -const PALETTE_THREAD_ACTIONS: Partial< - Record< - ThreadMenuAction, - { - /** Absent: the menu item's own words, for an action whose words change. */ - readonly title?: string; - readonly searchTerms: string[]; - readonly icon: ReactNode; +function listItemRows(command: OfferedCommand): CommandPaletteActionItem[] { + return (command.items ?? []).map((item) => ({ + kind: "action", + value: `command:${command.id}:${item.id}`, + searchTerms: [...(item.keywords ?? [])], + title: item.title, + ...(item.description ? { description: item.description } : {}), + icon: item.icon ?? commandIcon(command.id, ITEM_ICON_CLASS), + ...(item.disabled ? { disabled: true } : {}), + command: { id: command.id, itemId: item.id }, + run: async () => undefined, + })); +} + +function listPageGroups(command: OfferedCommand | undefined): CommandPaletteGroup[] { + if (!command?.items) return []; + const rows = listItemRows(command); + const groups: CommandPaletteGroup[] = []; + command.items.forEach((item, index) => { + const label = item.group ?? listHeading(command.id); + const last = groups.at(-1); + if (last && last.label === label) { + (last.items as CommandPaletteActionItem[]).push(rows[index]!); + } else { + groups.push({ value: `list:${command.id}:${label}`, label, items: [rows[index]!] }); } - > -> = { - "make-lead": { - searchTerms: ["lead chat", "lead", "coordinate", "project lead"], - icon: , - }, - "stop-lead": { - searchTerms: ["lead chat", "lead", "coordinate", "project lead"], - icon: , - }, - rename: { - title: "Rename thread", - searchTerms: ["rename", "title", "name"], - icon: , - }, - pin: { - title: "Pin thread", - searchTerms: ["pin", "keep", "top"], - icon: , - }, - unpin: { - title: "Unpin thread", - searchTerms: ["unpin"], - icon: , - }, - "wrap-up": { - title: "Wrap up thread", - searchTerms: ["wrap up", "done", "finish", "file away"], - icon: , - }, - reopen: { - title: "Reopen thread", - searchTerms: ["reopen", "active", "unwrap"], - icon: , - }, - "copy-path": { - title: "Copy thread path", - searchTerms: ["copy", "path", "folder", "directory"], - icon: , - }, - "copy-thread-id": { - title: "Copy thread ID", - searchTerms: ["copy", "id"], - icon: , - }, - archive: { - title: "Archive thread", - searchTerms: ["archive", "hide", "put away"], - icon: , - }, - delete: { - title: "Delete thread", - searchTerms: ["delete", "remove", "trash"], - icon: , - }, -}; + }); + return groups; +} +/** + * The open palette: search over commands, projects and threads. Commands are + * whatever their owners register now (commands/commandHandlers.ts); loaded on + * demand by CommandPalette, which owns the open state and the shortcut. + */ export function OpenCommandPaletteDialog() { const navigate = useNavigate(); const setOpen = useCommandPaletteStore((store) => store.setOpen); - const chatFindAvailable = useChatFindStore((store) => store.available); const openIntent = useCommandPaletteStore((store) => store.openIntent); const clearOpenIntent = useCommandPaletteStore((store) => store.clearOpenIntent); const composerHandleRef = useComposerHandleContext(); @@ -299,99 +227,14 @@ export function OpenCommandPaletteDialog() { const deferredQuery = useDeferredValue(query); const isActionsOnly = deferredQuery.startsWith(">"); const [highlightedItemValue, setHighlightedItemValue] = useState(null); - const settings = useSettings(); - const { activeDraftThread, defaultProjectRef, handleNewThread, routeThreadRef } = - useHandleNewThread(); - // The whole open thread: the palette reads its activities, move and mode, - // which the shared helper leaves out. It is mounted only while open. - const activeThread = useStore( - useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]), - ); + const { handleNewThread, routeThreadRef } = useHandleNewThread(); const projects = useStore(useShallow(selectProjectsAcrossEnvironments)); - const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments)); - const { startChat: startGeneralChat } = useGeneralChats(); + const threads = usePaletteThreads(); const keybindings = useServerKeybindings(); - const isHomeRoute = useLocation({ select: (location) => location.pathname === "/" }); - const onTerminalsPage = useLocation({ - select: (location) => location.pathname === "/terminals", - }); - const isMobile = useIsMobile(); - const sidebarListOpen = useUiStateStore(selectSidebarListShown); + const offeredCommands = useOfferedCommands(); + const commandUsage = useCommandUsageStore((store) => store.byKey); const [viewStack, setViewStack] = useState([]); const currentView = viewStack.at(-1) ?? null; - const primaryEnvironmentId = usePrimaryEnvironmentId(); - const primaryServerProviders = useServerProviders(); - const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((state) => state.byId); - const pullRequestEnvironments = usePullRequestEnvironments(); - const scheduledTaskEnvironments = useScheduledTaskEnvironments(); - // Heard from only for this computer's owner, where its server takes outside agents. - const managesOutsideAgents = useOutsideAgentsSnapshot() !== null; - const thisComputerNaming = useComputerNaming(primaryEnvironmentId); - // The active thread's pull request, so the palette can offer its tab. Both - // reads are the sidebar's: the same refcounted git status and the same open - // listing key, and neither runs on a thread with no branch to match. - const activeThreadProject = activeThread - ? (projects.find( - (project) => - project.environmentId === activeThread.environmentId && - project.id === activeThread.projectId, - ) ?? null) - : null; - const activeThreadRoomsEnabled = useRoomsEnabled( - activeThread?.environmentId ?? activeDraftThread?.environmentId, - ); - // The open thread's project, where another computer could take a copy of it. - const openThreadProjectRef = activeThread - ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) - : activeDraftThread - ? scopeProjectRef(activeDraftThread.environmentId, activeDraftThread.projectId) - : null; - const projectSetupTargets = useProjectSetupTargets(openThreadProjectRef); - // Clearing this computer (Part 3c): several of its threads to a linked one. - const moveThreadsOffered = useMoveThreadsOffered(primaryEnvironmentId, null); - const activeThreadMoveOffered = useThreadMoveOffered( - activeThread - ? { - environmentId: activeThread.environmentId, - projectId: activeThread.projectId, - moveStatus: threadMoveStatus(activeThread), - } - : null, - ); - // The open thread's own actions are its menu's (useThreadMenu); the inbox - // says whether it offers Wrap up or Reopen. This mounts only while open. - const threadMenu = useThreadMenu(); - const { entries: inboxEntries } = useInboxThreads(); - const activeThreadHasBranch = (activeThread?.branch ?? null) !== null; - const activeThreadGitStatus = useGitStatus({ - environmentId: activeThreadHasBranch ? (activeThread?.environmentId ?? null) : null, - cwd: - activeThreadHasBranch && activeThread && activeThreadProject - ? resolveThreadWorkingCwd({ - projectCwd: activeThreadProject.cwd, - worktreePath: activeThread.worktreePath, - effectiveCwd: activeThread.effectiveCwd, - }) - : null, - }); - const activeThreadOpenPullRequests = usePullRequestLists({ - state: "open", - refetchIntervalMs: PULL_REQUEST_COUNT_REFETCH_INTERVAL_MS, - enabled: activeThreadHasBranch, - }); - const activeThreadPullRequestRecords = usePullRequestRecords(activeThread?.environmentId); - const activeThreadPullRequest = activeThread - ? resolveThreadPullRequest({ - thread: { - ...activeThread, - branch: threadViewBranch(activeThread, activeThreadGitStatus.data), - }, - gitStatus: activeThreadGitStatus.data, - openEntries: activeThreadOpenPullRequests.entries, - projects, - records: activeThreadPullRequestRecords, - }) - : null; const addProjectEnvironmentOptions = useAddProjectEnvironmentOptions(); // A typed path offers "Add project at " for the computer Add project @@ -414,60 +257,7 @@ export function OpenCommandPaletteDialog() { [projects], ); - const activeThreadId = activeThread?.id; - const currentProjectEnvironmentId = - activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null; - const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null; - const currentProject = - currentProjectId && currentProjectEnvironmentId - ? (projects.find( - (project) => - project.id === currentProjectId && - project.environmentId === currentProjectEnvironmentId, - ) ?? null) - : null; - const currentProjectCwd = currentProject?.cwd ?? null; - const supportsProjectBrief = useProjectBriefSupport(); - // The project's worktrees made outside Threadlines, asked for while the - // palette is open: the action below shows only when there is one to add. - const currentProjectRef = useMemo( - () => - currentProject?.kind === "workspace" - ? scopeProjectRef(currentProject.environmentId, currentProject.id) - : null, - [currentProject?.environmentId, currentProject?.id, currentProject?.kind], - ); - const worktreePickup = useWorktreePickup({ - projectRef: currentProjectRef, - projectCwd: currentProjectRef === null ? null : currentProjectCwd, - }); - const currentEnvironmentProviders = useMemo( - () => - currentProjectEnvironmentId && currentProjectEnvironmentId === primaryEnvironmentId - ? primaryServerProviders - : currentProjectEnvironmentId - ? (savedEnvironmentRuntimeById[currentProjectEnvironmentId]?.serverConfig?.providers ?? - []) - : [], - [ - currentProjectEnvironmentId, - primaryEnvironmentId, - primaryServerProviders, - savedEnvironmentRuntimeById, - ], - ); - const availableCodexInstances = useMemo( - () => - deriveProviderInstanceEntries(currentEnvironmentProviders).filter( - (entry) => - entry.driverKind === "codex" && - entry.enabled && - entry.installed && - entry.isAvailable && - entry.models.length > 0, - ), - [currentEnvironmentProviders], - ); + const activeThreadId = routeThreadRef?.threadId; const openProjectFromSearch = useMemo( () => async (project: (typeof projects)[number]) => { const latestThread = getLatestThreadForProject( @@ -507,34 +297,6 @@ export function OpenCommandPaletteDialog() { [openProjectFromSearch, projects], ); - const projectThreadItems = useMemo( - () => - buildProjectActionItems({ - projects, - valuePrefix: "new-thread-in", - icon: (project) => ( - - ), - runProject: async (project) => { - await startNewThreadInProjectFromContext( - { - activeDraftThread, - activeThread, - defaultProjectRef, - handleNewThread, - }, - scopeProjectRef(project.environmentId, project.id), - ); - }, - }), - [activeDraftThread, activeThread, defaultProjectRef, handleNewThread, projects], - ); - const allThreadItems = useMemo( () => buildThreadActionItems({ @@ -571,7 +333,26 @@ export function OpenCommandPaletteDialog() { }), [activeThreadId, navigate, projectByScopedKey, projectTitleById, threads], ); - const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT); + // Where you'd go: the threads with the latest activity, pinned or not, the + // one on screen left out. + const activeThreadEnvironmentId = routeThreadRef?.environmentId; + const recentThreadItems = useMemo( + () => + allThreadItems + .filter( + (item) => + !( + item.threadRef?.id === activeThreadId && + item.threadRef?.environmentId === activeThreadEnvironmentId + ), + ) + .toSorted( + (left, right) => + Date.parse(right.timestampAt ?? "") - Date.parse(left.timestampAt ?? "") || 0, + ) + .slice(0, RECENT_THREAD_LIMIT), + [activeThreadEnvironmentId, activeThreadId, allThreadItems], + ); const threadContentSearchTargets = useMemo>(() => { const scopedProjectIds = currentView?.threadSearchProjectIdsByEnvironment; if (currentView && !scopedProjectIds) { @@ -614,21 +395,43 @@ export function OpenCommandPaletteDialog() { [allThreadItems, deferredQuery, threadContentMatches], ); + // Every offered command, in the catalog's order. + const commandRows = useMemo( + () => + COMMAND_IDS.flatMap((id) => { + const command = offeredCommands.get(id); + return command ? [commandRow(command)] : []; + }), + [offeredCommands], + ); + // The items of lists that the main search finds too (a computer, a theme, a script). + const searchableListItemRows = useMemo( + () => + COMMAND_IDS.flatMap((id) => { + const command = offeredCommands.get(id); + return command && "itemsSearchable" in APP_COMMANDS[id] ? listItemRows(command) : []; + }), + [offeredCommands], + ); + const suggestedRows = useMemo(() => { + const offeredIds = COMMAND_IDS.filter((id) => { + const command = offeredCommands.get(id); + return command !== undefined && command.disabledReason === undefined; + }); + const rowById = new Map(commandRows.map((row) => [row.command!.id, row])); + return suggestCommands({ + candidates: offeredIds, + usage: commandUsage, + fallback: FIRST_SUGGESTIONS, + limit: SUGGESTED_COMMAND_LIMIT, + }).flatMap((id) => { + const row = rowById.get(id); + return row ? [{ ...row, value: `suggested:${id}` }] : []; + }); + }, [commandRows, commandUsage, offeredCommands]); + function pushPaletteView(view: CommandPaletteView): void { - setViewStack((previousViews) => [ - ...previousViews, - { - addonIcon: view.addonIcon, - groups: view.groups, - ...(view.initialQuery ? { initialQuery: view.initialQuery } : {}), - ...(view.inputPlaceholder ? { inputPlaceholder: view.inputPlaceholder } : {}), - ...(view.threadSearchProjectIdsByEnvironment - ? { - threadSearchProjectIdsByEnvironment: view.threadSearchProjectIdsByEnvironment, - } - : {}), - }, - ]); + setViewStack((previousViews) => [...previousViews, view]); setHighlightedItemValue(null); setQuery(view.initialQuery ?? ""); } @@ -641,28 +444,13 @@ export function OpenCommandPaletteDialog() { }); } - // Hands over to the Codex import dialog, which takes the project, its - // accounts and the open thread's mode as they are now. - function openCodexImportDialog(): void { - if (!currentProject || currentProject.kind !== "workspace") { - return; - } - openCodexImport({ - project: { - environmentId: currentProject.environmentId, - projectId: currentProject.id, - projectName: currentProject.name, - cwd: currentProject.cwd, - }, - accounts: availableCodexInstances.map((instance) => ({ - instanceId: instance.instanceId, - displayName: instance.displayName, - })), - runtimeMode: - activeThread?.runtimeMode ?? - activeDraftThread?.runtimeMode ?? - DEFAULT_NEW_THREAD_RUNTIME_MODE, - returnFocus: focusComposer, + function pushListView(id: AppCommandId): void { + const placeholder = offeredCommands.get(id)?.placeholder; + pushPaletteView({ + addonIcon: commandIcon(id, ADDON_ICON_CLASS), + groups: [], + listCommandId: id, + ...(placeholder ? { inputPlaceholder: placeholder } : {}), }); } @@ -728,792 +516,43 @@ export function OpenCommandPaletteDialog() { }); }, [activeThreadId, clearOpenIntent, navigate, openIntent, projectTitleById, threads]); - const actionItems: Array = []; - - if (projects.length > 0) { - const activeProjectTitle = currentProject?.name ?? null; - - if (activeProjectTitle) { - actionItems.push({ - kind: "action", - value: "action:new-thread", - searchTerms: ["new thread", "chat", "create", "draft"], - title: ( - <> - New thread in {activeProjectTitle} - - ), - icon: , - shortcutCommand: "chat.new", - run: async () => { - await startNewThreadFromContext({ - activeDraftThread, - activeThread, - defaultProjectRef, - handleNewThread, - }); - }, - }); - - if ( - currentProject?.kind === "workspace" && - currentProjectCwd && - availableCodexInstances.length > 0 - ) { - actionItems.push({ - kind: "action", - value: "action:open-codex-session", - searchTerms: ["open", "import", "codex", "session", "chat", "conversation"], - title: "Bring in Codex conversation…", - description: "Continue work from Codex app, CLI, or IDE", - icon: , - opensDialog: true, - run: async () => { - openCodexImportDialog(); - }, - }); - } - - if (currentProjectRef !== null && worktreePickup.candidates.length > 0) { - const projectRef = currentProjectRef; - actionItems.push({ - kind: "action", - value: "action:pick-up-worktrees", - searchTerms: ["worktree", "existing", "pick up", "import", "branch", "add threads"], - title: "Add existing worktrees as threads…", - description: "Worktrees this repository already has, made outside Threadlines", - icon: , - // Lays the list out on the new-thread screen, where each worktree - // can be ticked; it also brings a hidden count back. - run: async () => { - useWorktreePickupStore.getState().offer(scopedProjectKey(projectRef)); - await handleNewThread(projectRef, { continueActiveCheckout: false }); - }, - }); - } - } - - if ( - currentProject?.kind === "workspace" && - supportsProjectBrief(currentProject.environmentId) - ) { - const briefProject = currentProject; - actionItems.push({ - kind: "action", - value: "action:project-brief", - searchTerms: [ - "brief", - "project brief", - "notes", - "instructions", - "rules", - briefProject.name, - ], - title: PROJECT_BRIEF_MENU_LABEL, - description: briefProject.name, - icon: , - run: async () => { - await navigate(projectBriefLocation(briefProject)); - }, - }); - } - - actionItems.push({ - kind: "submenu", - value: "action:new-thread-in", - searchTerms: ["new thread", "project", "pick", "choose", "select"], - title: "New thread in...", - icon: , - addonIcon: , - groups: [{ value: "projects", label: "Projects", items: projectThreadItems }], - }); - } - - actionItems.push({ + const searchText = (isActionsOnly ? deferredQuery.slice(1) : deferredQuery).trim(); + const allCommandsItem: CommandPaletteActionItem = { kind: "action", - value: "action:add-project", - searchTerms: [ - "add project", - "folder", - "directory", - "browse", - "clone", - "remote", - "repository", - "repo", - "git", - "github", - "gitlab", - "bitbucket", - "azure", - "devops", - "url", - "environment", - ], - title: "Add project", - icon: , - opensDialog: true, + value: "action:all-commands", + searchTerms: [], + title: "All commands", + description: "Type > to search only commands", + icon: , + keepOpen: true, run: async () => { - openAddProject({ returnFocus: focusComposer }); + setHighlightedItemValue(null); + setQuery(">"); }, - }); - - if (!isHomeRoute) { - actionItems.push({ - kind: "action", - value: "action:go-home", - searchTerms: ["home", "landing", "start", "threads"], - title: "Go to Home", - icon: , - run: async () => { - await navigate({ to: "/" }); - }, - }); - } - - if (startGeneralChat !== null) { - actionItems.push({ - kind: "action", - value: "action:new-general-chat", - searchTerms: ["new chat", "general chat", "chat", "conversation", "no project"], - title: "New general chat", - icon: , - run: async () => { - startGeneralChat(); - }, - }); - } - - actionItems.push({ - kind: "action", - value: "action:general-chats", - searchTerms: ["general chats", "chats", "conversations", "no project"], - title: "Open general chats", - icon: , - run: async () => { - // Where the chats are a section of Threads, the shell opens it there - // without a stop at the old page's address. - if (settings.generalChatsPlacement === "threads") requestGeneralChatsReveal(); - else await navigate({ to: "/chats" }); - }, - }); - - if (!onTerminalsPage) { - actionItems.push({ - kind: "action", - value: "action:terminals", - searchTerms: ["terminals", "terminal", "shell", "shells", "split terminal", "dev server"], - title: "Open Terminals", - description: "Terminal tabs for any project, outside a chat", - icon: , - shortcutCommand: "navigate.terminals", - run: async () => { - await navigate({ to: "/terminals" }); - }, - }); - } - - actionItems.push({ - kind: "action", - value: "action:fleet", - searchTerms: ["fleet", "computers", "machines", "devices", "phone", "graph", "running"], - title: "Open Fleet", - description: "Your computers and what runs on them", - icon: , - shortcutCommand: "navigate.fleet", - run: async () => { - await navigate({ to: "/fleet" }); - }, - }); - - // Only where a connected computer runs scheduled tasks, like the rail's button. - if (scheduledTaskEnvironments.length > 0) { - actionItems.push({ - kind: "action", - value: "action:scheduled", - searchTerms: ["scheduled", "schedule", "tasks", "automations", "cron", "recurring", "daily"], - title: "Open Scheduled", - description: "Tasks agents start at set times", - icon: , - shortcutCommand: "navigate.scheduled", - run: async () => { - await navigate({ to: "/scheduled" }); - }, - }); - actionItems.push({ - kind: "action", - value: "action:new-scheduled-task", - searchTerms: ["new scheduled task", "schedule", "automation", "cron", "recurring"], - title: "New scheduled task", - icon: , - run: async () => { - await navigate({ to: "/scheduled", search: { view: "new" } }); - }, - }); - } - if (thisComputerNaming) { - actionItems.push({ - kind: "action", - value: "action:rename-computer", - searchTerms: ["rename computer", "computer name", "name this computer", "fleet", "device"], - title: "Rename this computer", - description: `Now called ${thisComputerNaming.label}`, - icon: , - run: async () => { - openComputerRenameDialog(thisComputerNaming); - }, - }); - } - actionItems.push({ - kind: "action", - value: "action:whats-new", - searchTerms: ["what's new", "whats new", "changelog", "release notes", "version", "update"], - title: "What's new in Threadlines", - description: `The notes for v${APP_VERSION}`, - icon: , - run: async () => { - openWhatsNewDialog(); - }, - }); - actionItems.push({ - kind: "action", - value: "action:report-problem", - searchTerms: ["report a problem", "report", "bug", "issue", "feedback", "github", "crash"], - title: "Report a problem", - description: "Write a bug report and post it to GitHub", - icon: , - run: async () => { - openReportProblemDialog(); - }, - }); - actionItems.push({ - kind: "action", - value: "action:connect-computer", - searchTerms: ["connect", "computer", "add computer", "pair", "code", "ssh", "link computers"], - title: "Connect to a computer", - description: "Use projects from another computer that runs Threadlines", - icon: , - run: async () => { - openConnectComputerDialog(); - }, - }); - - if (managesOutsideAgents) { - actionItems.push({ - kind: "action", - value: "action:connect-agent", - searchTerms: [ - "connect an agent", - "outside agent", - "mcp", - "claude code", - "codex", - "gemini", - "cursor", - "terminal", - ], - title: "Connect an agent", - description: "Let an agent you run outside Threadlines use it", - icon: , - run: async () => { - await navigate({ to: "/settings/connections", search: { section: "agents" } }); - }, - }); - actionItems.push({ - kind: "action", - value: "action:connect-assistant", - searchTerms: [ - "connect an assistant", - "assistant", - "always-on", - "grok bot", - "dots", - "muse", - "claude duet", - "connector", - "sign-in code", - "key", - ], - title: "Connect an assistant", - description: "Show a code for an always-on assistant to sign in with", - icon: , - run: async () => { - // The Assistants group shows the code, or why there isn't one. - void startAssistantCode(); - await navigate({ to: "/settings/connections", search: { section: "assistants" } }); - }, - }); - } - - // Each computer's Fleet page, once there is more than one to choose from. - if (addProjectEnvironmentOptions.length > 1) { - for (const option of addProjectEnvironmentOptions) { - actionItems.push({ - kind: "action", - value: `action:fleet-computer:${option.environmentId}`, - searchTerms: ["fleet", "computer", "link", "unlink", option.label], - title: `Open ${option.label} in Fleet`, - icon: , - run: async () => { - await navigate({ - to: "/fleet/$environmentId", - params: { environmentId: option.environmentId }, - }); - }, - }); - } - } - - // The thread list beside the rail; a phone shows it as a sheet instead. - if (!isMobile) { - actionItems.push({ - kind: "action", - value: "action:toggle-sidebar", - searchTerms: ["sidebar", "thread list", "hide", "show", "toggle", "rail"], - title: sidebarListOpen ? "Hide sidebar" : "Show sidebar", - icon: sidebarListOpen ? ( - - ) : ( - - ), - shortcutCommand: "sidebar.toggle", - run: async () => { - useUiStateStore.getState().toggleSidebarListShown(); - }, - }); - } - - // Registered only where the rail's button is: an action that lands on - // "unsupported" is worse than one the palette never offers. - if (pullRequestEnvironments.length > 0) { - actionItems.push({ - kind: "action", - value: "action:pull-requests", - searchTerms: ["pull requests", "prs", "pr", "reviews", "github"], - title: "Open pull requests", - icon: , - run: async () => { - await navigate({ to: "/pull-requests", search: { state: "open" } }); - }, - }); - } - - // Only where there is one to open: an action that lands on "this branch has - // no pull request" is a dead end the palette should not offer. - if (activeThreadPullRequest && activeThread) { - const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); - const pullRequestNumber = activeThreadPullRequest.number; - actionItems.push({ - kind: "action", - value: "action:thread-pull-request", - searchTerms: ["pull request", "pr", "review", "github", `#${activeThreadPullRequest.number}`], - title: `Open pull request #${activeThreadPullRequest.number}`, - icon: , - run: async () => { - focusRightPanelTab(scopedThreadKey(threadRef), "pullRequest"); - await navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), - search: (previous) => pullRequestTabSearchParams(previous, pullRequestNumber), - }); - }, - }); - } - - // A project thread on a computer whose server has devices: the same rule as - // the Device tab itself (availableRightPanelTabs). - if ( - activeThread && - activeThreadProject !== null && - activeThreadProject.kind !== "general-chat" && - environmentSupportsDevices(activeThread.environmentId) - ) { - const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); - actionItems.push({ - kind: "action", - value: "action:thread-device", - searchTerms: ["device", "simulator", "emulator", "ios", "android", "phone"], - title: "Open device", - icon: , - run: async () => { - focusRightPanelTab(scopedThreadKey(threadRef), "device"); - await navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), - search: (previous) => rightPanelTabSearchParams(previous, "device"), - }); - }, - }); - } - - // Where find in chat can open: a saved chat on screen, off phones. - if (chatFindAvailable) { - actionItems.push({ - kind: "action", - value: "action:find-in-chat", - searchTerms: ["find in chat", "find", "search this chat", "search messages", "ctrl f"], - title: "Find in chat", - description: "Search this chat's messages", - icon: , - shortcutCommand: "chat.find", - run: async () => { - // After the palette has closed and handed focus back, so the bar's - // field keeps it. - window.requestAnimationFrame(() => useChatFindStore.getState().requestOpen(null)); - }, - }); - } - - // A screenshot of a window or part of the screen, added to the message being - // written. The desktop app only; it used to sit in the composer's "+" menu. - if ( - (activeThread || activeDraftThread) && - typeof window.desktopBridge?.captureScreenshot === "function" - ) { - actionItems.push({ - kind: "action", - value: "action:capture-screenshot", - searchTerms: ["screenshot", "capture", "screen", "image", "attach", "picture"], - title: "Capture screenshot", - description: "Add a screenshot to the message you're writing", - icon: , - run: async () => { - // After the palette has closed and handed focus back to the composer. - window.requestAnimationFrame(() => - useComposerCommandsStore.getState().requestComposerCommand("captureScreenshot"), - ); - }, - }); - } - - // The terminal's actions, for the thread on screen or the Terminals page - // (its drawer does them, with the same confirmations as its own buttons). - if (activeThread || activeDraftThread || onTerminalsPage) { - const terminalActions: ReadonlyArray<{ - readonly kind: TerminalCommandKind; - readonly title: string; - readonly description: string; - readonly searchTerms: ReadonlyArray; - readonly icon: ReactNode; - readonly shortcutCommand?: KeybindingCommand; - }> = [ - ...(onTerminalsPage - ? [] - : [ - { - kind: "toggle", - title: "Toggle terminal", - description: "Show or hide this thread's terminal", - searchTerms: [ - "terminal", - "toggle terminal", - "show terminal", - "hide terminal", - "shell", - ], - icon: , - shortcutCommand: "terminal.toggle", - } as const, - ]), - { - kind: "new", - title: "New terminal tab", - description: onTerminalsPage - ? "Open a terminal in the project picked for new tabs" - : "Open another terminal for this thread", - searchTerms: ["new terminal", "terminal tab", "open terminal", "shell"], - icon: , - shortcutCommand: "terminal.new", - }, - { - kind: "split", - title: "Split terminal", - description: "Open a terminal beside the current one", - searchTerms: ["split terminal", "side by side", "terminal"], - icon: , - shortcutCommand: "terminal.split", - }, - { - kind: "find", - title: "Find in terminal", - description: "Search the terminal's output", - searchTerms: ["find in terminal", "search terminal", "terminal output", "find"], - icon: , - shortcutCommand: "terminal.find", - }, - { - kind: "restart", - title: "Restart terminal", - description: onTerminalsPage - ? "A new shell in the same folder, below the old output" - : "A new shell in the thread's folder, below the old output", - searchTerms: ["restart terminal", "reset terminal", "new shell", "terminal"], - icon: , - }, - { - kind: "clear", - title: "Clear terminal output", - description: "Empty the terminal and its saved output", - searchTerms: ["clear terminal", "clear output", "terminal"], - icon: , - }, - { - kind: "kill", - title: "Kill terminal", - description: "Stop the terminal's shell and close its tab", - searchTerms: ["kill terminal", "close terminal", "stop terminal", "terminal"], - icon: , - shortcutCommand: "terminal.close", - }, - ]; - for (const action of terminalActions) { - actionItems.push({ - kind: "action", - value: `action:terminal-${action.kind}`, - searchTerms: [...action.searchTerms], - title: action.title, - description: action.description, - icon: action.icon, - ...(action.shortcutCommand ? { shortcutCommand: action.shortcutCommand } : {}), - run: async () => { - // After the palette has closed and handed focus back. - window.requestAnimationFrame(() => - useTerminalCommandsStore.getState().requestTerminalCommand(action.kind), - ); - }, - }); - } - } - - // Where the composer's model picker lists agents: a thread (a new one - // included), with rooms on, and no approval holding the composer's toolbar. - // It opens the picker ready to add one, the same as its "Add agent" row. - const addAgentThreadRef = !activeThreadRoomsEnabled - ? null - : activeThread - ? derivePendingApprovals(activeThread.activities).length === 0 - ? scopeThreadRef(activeThread.environmentId, activeThread.id) - : null - : activeDraftThread - ? scopeThreadRef(activeDraftThread.environmentId, activeDraftThread.threadId) - : null; - if (addAgentThreadRef !== null) { - const threadRef = addAgentThreadRef; - actionItems.push({ - kind: "action", - value: "action:add-room-agent", - searchTerms: ["add agent", "agents", "room", "model", "invite", "second opinion", "review"], - title: "Add agent", - description: "Bring another model into this thread", - icon: , - run: async () => { - useRoomRecipientStore.getState().requestAddAgent(threadRef); - }, - }); - } - - // Where its computer can move it: one linked computer at least, and the - // thread not already on its way. The dialog says why one can't go. - if (activeThread && activeThreadMoveOffered) { - const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); - actionItems.push({ - kind: "action", - value: "action:move-thread", - searchTerms: ["move", "computer", "linked", "transfer", "send", "another machine"], - title: "Move to another computer", - description: "Move this thread and its changes to a linked computer", - icon: , - run: async () => { - openThreadMoveDialog(threadRef); - }, - }); - } - - if (moveThreadsOffered && primaryEnvironmentId !== null) { - const sourceEnvironmentId = primaryEnvironmentId; - actionItems.push({ - kind: "action", - value: "action:move-threads", - searchTerms: [ - "move", - "threads", - "computer", - "linked", - "shut down", - "clear", - "another machine", - ], - title: "Move threads to another computer…", - description: "Move several of this computer's threads to a linked computer", - icon: , - run: async () => { - openMoveThreadsDialog({ sourceEnvironmentId }); - }, - }); - } - - if (openThreadProjectRef !== null && projectSetupTargets.length > 0) { - const projectRef = openThreadProjectRef; - actionItems.push({ - kind: "action", - value: "action:set-up-project-elsewhere", - searchTerms: ["set up", "project", "computer", "clone", "copy", "another machine"], - title: "Set up project on another computer", - description: "Clone this project on another computer, with the ignored files you pick", - icon: , - run: async () => { - openProjectSetupDialog({ project: projectRef }); - }, - }); - } - - if (activeThread) { - const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); - const inboxEntry = inboxEntries.find((entry) => entry.threadKey === scopedThreadKey(threadRef)); - const target = { - threadRef, - inbox: inboxEntry ? { isDone: inboxEntry.isDone, canMarkDone: inboxEntry.canMarkDone } : null, - }; - for (const item of threadMenu.describe(target) ?? []) { - const offered = PALETTE_THREAD_ACTIONS[item.id]; - if (!offered || item.disabled) continue; - actionItems.push({ - kind: "action", - value: `action:thread-${item.id}`, - searchTerms: offered.searchTerms, - title: offered.title ?? item.label, - icon: offered.icon, - run: async () => { - await threadMenu.run(item.id, target); - }, - }); - } - } - - // Lead chats (docs/design/lead-chat.md): one "Go to" per project that has - // one, and "New lead chat" for the project in scope when it has none. - for (const project of projects) { - const leadRef = projectLeadRef(useStore.getState(), project); - if (leadRef === null) continue; - actionItems.push({ - kind: "action", - value: `action:lead-chat:${scopedThreadKey(leadRef)}`, - searchTerms: ["lead chat", "lead", project.name], - title: "Go to lead chat", - description: project.name, - icon: , - run: async () => { - await navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(leadRef), - }); - }, - }); - } - // The open thread's or draft's project (none until its computer's projects - // load); the first project only when neither is open. - const leadScopeProject = - currentProjectId !== null - ? (currentProject ?? undefined) - : defaultProjectRef - ? projects.find( - (project) => - project.environmentId === defaultProjectRef.environmentId && - project.id === defaultProjectRef.projectId, - ) - : undefined; - if ( - leadScopeProject !== undefined && - leadScopeProject.kind === "workspace" && - environmentSupportsProjectLead(leadScopeProject.environmentId) && - leadSettingRefusal(leadScopeProject.environmentId) === null && - projectLeadRef(useStore.getState(), leadScopeProject) === null - ) { - actionItems.push({ - kind: "action", - value: "action:new-lead-chat", - searchTerms: ["new lead chat", "lead chat", "lead", "coordinate"], - title: "New lead chat", - description: leadScopeProject.name, - icon: , - run: async () => { - const leadRef = await createLeadChat(leadScopeProject); - if (leadRef !== null) { - await navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(leadRef), - }); - } - }, - }); - } - - actionItems.push({ - kind: "action", - value: "action:usage", - searchTerms: ["usage", "tokens", "cost", "spend", "spending", "price", "billing"], - title: "Open usage", - icon: , - run: async () => { - await navigate({ to: "/usage" }); - }, - }); - - actionItems.push({ - kind: "action", - value: "action:settings", - searchTerms: ["settings", "preferences", "configuration", "keybindings"], - title: "Open settings", - icon: , - run: async () => { - await navigate({ to: "/settings" }); - }, - }); - - actionItems.push({ - kind: "action", - value: "action:setup", - searchTerms: ["setup", "set up", "agents", "providers", "install", "sign in", "onboarding"], - title: "Set up agents", - icon: , - run: async () => { - await navigate({ to: "/setup" }); - }, - }); - - actionItems.push({ - kind: "action", - value: "action:community-agents", - searchTerms: ["community", "agents", "add agent", "install agent", "acp", "registry"], - title: "Browse community agents", - icon: , - run: async () => { - await navigate({ to: "/settings/providers", search: { section: "community" } }); - }, - }); - - actionItems.push({ - kind: "action", - value: "action:skills", - searchTerms: ["skills", "plugins", "extensions", "agents", "capabilities"], - title: "Open skills", - icon: , - run: async () => { - await navigate({ to: "/settings/plugins", search: { tab: "skills" } }); - }, - }); - - const rootGroups = buildRootGroups({ actionItems, recentThreadItems }); - const activeGroups = currentView - ? currentView.groups.map((group) => ({ - ...group, - items: applyThreadContentSearchMatches({ - items: group.items, - matches: threadContentMatches, - query: deferredQuery, - }), - })) - : rootGroups; + }; + // A list page draws from the command's items now, not a copy from when it + // opened, so a script renamed while its list is open shows its new name. + const activeGroups: ReadonlyArray = currentView + ? currentView.listCommandId !== undefined + ? listPageGroups(offeredCommands.get(currentView.listCommandId)) + : currentView.groups.map((group) => ({ + ...group, + items: applyThreadContentSearchMatches({ + items: group.items, + matches: threadContentMatches, + query: deferredQuery, + }), + })) + : deferredQuery.length === 0 + ? buildOpeningGroups({ recentThreadItems, suggestedItems: suggestedRows, allCommandsItem }) + : [ + { + value: "actions", + label: "Actions", + items: + searchText.length > 0 ? [...commandRows, ...searchableListItemRows] : commandRows, + }, + ]; const filteredGroups = filterCommandPaletteGroups({ activeGroups, @@ -1567,19 +606,44 @@ export function OpenCommandPaletteDialog() { } } + function reportFailure(error: unknown): void { + toastManager.add( + failureNotice({ + title: "Couldn't run the command", + error, + }), + ); + } + function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void { if (item.disabled) { return; } + // A command runs what its owner registered now, looked up again by id. + if (item.command) { + const outcome = runCommand({ + id: item.command.id, + itemId: item.command.itemId, + close: ({ handingOver }) => { + // A dialog taking over decides where focus goes when it closes, so + // the palette leaves the composer alone on its way out. + if (handingOver) handingOverToDialogRef.current = true; + setOpen(false); + }, + recordUse: (key) => useCommandUsageStore.getState().recordUse(key), + onError: reportFailure, + }); + if (outcome === "list") pushListView(item.command.id); + return; + } + if (item.kind === "submenu") { pushView(item); return; } if (!item.keepOpen) { - // A dialog taking over decides where focus goes when it closes, so the - // palette leaves the composer alone on its way out. if (item.opensDialog) handingOverToDialogRef.current = true; setOpen(false); } @@ -1605,14 +669,7 @@ export function OpenCommandPaletteDialog() { }) : item.run(); - void execution.catch((error: unknown) => { - toastManager.add( - failureNotice({ - title: "Couldn't run the command", - error, - }), - ); - }); + void execution.catch(reportFailure); } return ( @@ -1629,6 +686,8 @@ export function OpenCommandPaletteDialog() { setOpen(false); }} > + {/* Commands that need only stores and navigation register while the palette is open. */} + { + const targetKey = resolveAdjacentThreadId({ + threadIds: traversalThreadKeys, + currentThreadId: routeThreadKey, + direction, + }); + const target = targetKey ? sidebarThreadByKey.get(targetKey) : undefined; + return target ? scopeThreadRef(target.environmentId, target.id) : null; + }; + const previousThreadRef = adjacentThreadRef("previous"); + const nextThreadRef = adjacentThreadRef("next"); + useCommandHandlers({ + "thread.previous": previousThreadRef !== null && { + run: () => navigateToThread(previousThreadRef), + }, + "thread.next": nextThreadRef !== null && { run: () => navigateToThread(nextThreadRef) }, + // Only where the inbox and its wrapped shelf are on screen, not under a + // page's own list (Settings, Computers). + "inbox.showWrapped": PageListBody === null && + wrappedRows.length > 0 && { + ...(wrappedOpen ? { title: "Hide wrapped threads" } : {}), + run: toggleWrappedOpen, + }, + }); + // A request opens where it can be read in full: the thread that asked, when // this app has it, else the Fleet page of the computer it would run on. const openLinkRequest = useCallback( @@ -2056,12 +2091,6 @@ export default function Sidebar() { }; }, [clearSelection]); - // What the list shows (see destinationLists). This component stays mounted - // either way, so the thread shortcuts work on every page. - const destinationList = resolveShownDestinationList(selectedDestination, isMobile); - const PageListBody = - destinationList !== null && destinationList.body !== "inbox" ? destinationList.body : null; - return ( <> {/* A phone has no title row and no rail: the sheet carries the name, diff --git a/apps/web/src/components/addProject/addProjectStore.test.ts b/apps/web/src/components/addProject/addProjectStore.test.ts index dadaa70d3..c3865b44c 100644 --- a/apps/web/src/components/addProject/addProjectStore.test.ts +++ b/apps/web/src/components/addProject/addProjectStore.test.ts @@ -2,7 +2,11 @@ import { EnvironmentId, ProjectId } from "@threadlines/contracts"; import { scopeProjectRef } from "@threadlines/client-runtime"; import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { finishAddProject, useAddProjectStore } from "./addProjectStore"; +import { + finishAddProject, + useAddProjectStore, + waitForAddProjectSessionEnd, +} from "./addProjectStore"; const PROJECT_REF = scopeProjectRef(EnvironmentId.make("environment-local"), ProjectId.make("p1")); @@ -14,8 +18,9 @@ function openSession(onProjectSelected?: (ref: typeof PROJECT_REF) => void) { } describe("add project store", () => { + // Session ids only ever grow, as in the app. beforeEach(() => { - useAddProjectStore.setState({ session: null, lastSessionId: 0 }); + useAddProjectStore.setState({ session: null }); }); it("hands a finished add to the session that started it, then closes", async () => { @@ -77,4 +82,21 @@ describe("add project store", () => { expect(openProject).not.toHaveBeenCalled(); expect(announce).toHaveBeenCalledOnce(); }); + + it("says a session ended cancelled when it closed, and added when a project came through it", async () => { + const closed = openSession(); + const closedEnd = waitForAddProjectSessionEnd(closed.id); + useAddProjectStore.getState().close(); + await expect(closedEnd).resolves.toBe("cancelled"); + + const finished = openSession(); + const finishedEnd = waitForAddProjectSessionEnd(finished.id); + await finishAddProject({ + session: finished, + projectRef: PROJECT_REF, + openProject: async () => undefined, + announce: vi.fn(), + }); + await expect(finishedEnd).resolves.toBe("added"); + }); }); diff --git a/apps/web/src/components/addProject/addProjectStore.ts b/apps/web/src/components/addProject/addProjectStore.ts index 1ccd431fe..f507fa303 100644 --- a/apps/web/src/components/addProject/addProjectStore.ts +++ b/apps/web/src/components/addProject/addProjectStore.ts @@ -65,6 +65,26 @@ export function openAddProject(request?: AddProjectOpenRequest): number { return useAddProjectStore.getState().open(request); } +/** The last session that ended with something done through it, as against closed. */ +let lastCompletedSessionId: number | null = null; + +/** + * How a session ended: "added" when a project was added or picked through + * it, "cancelled" when it was closed or replaced first. The palette counts a + * use of Add project only for the first. + */ +export function waitForAddProjectSessionEnd(sessionId: number): Promise<"added" | "cancelled"> { + return new Promise((resolve) => { + const settle = () => { + if (useAddProjectStore.getState().session?.id === sessionId) return; + unsubscribe(); + resolve(lastCompletedSessionId === sessionId ? "added" : "cancelled"); + }; + const unsubscribe = useAddProjectStore.subscribe(settle); + settle(); + }); +} + export function isAddProjectSessionOpen(sessionId: number): boolean { return useAddProjectStore.getState().session?.id === sessionId; } @@ -88,6 +108,7 @@ export async function finishAddProject(input: { input.announce(openProject); return; } + lastCompletedSessionId = session.id; if (session.selection) { session.selection.onProjectSelected(projectRef); useAddProjectStore.getState().closeSession(session.id); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 033a860e3..08423f4bb 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -121,7 +121,7 @@ import { type ComposerCommandItem, ComposerCommandMenu } from "./ComposerCommand import { useComposerMenuRoom } from "./useComposerMenuRoom"; import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; import { ComposerAddMenu } from "./ComposerAddMenu"; -import { type ComposerCommandKind, useComposerCommandsStore } from "../../composerCommands"; +import { useCommandHandlers } from "../../commands/commandHandlers"; import { type ComposerRoomDelivery, type ComposerSendOptions, @@ -3377,10 +3377,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (attachmentsDisabled) return; setIsCapturingScreenshot(true); - void captureScreenshot({ mode: "interactive" }) + // "cancelled" when the user backed out, for the palette's usage count. + return captureScreenshot({ mode: "interactive" }) .then((result) => { if (result.status === "cancelled") { - return; + return "cancelled" as const; } if (result.status === "unsupported" || result.status === "failed") { toastManager.add( @@ -3425,18 +3426,44 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); }; - // "Capture screenshot" asked for from the command palette. - const composerCommandRequest = useComposerCommandsStore((state) => state.request); - const handledComposerCommandNonceRef = useRef(composerCommandRequest?.nonce ?? 0); - const runComposerCommand = useEffectEvent((kind: ComposerCommandKind) => { - if (kind === "captureScreenshot") onCaptureScreenshot(); + // The composer's commands in the palette, each the path its own control or + // shortcut takes, offered only while that control would act. + const runCaptureScreenshot = useEffectEvent(() => onCaptureScreenshot()); + useCommandHandlers({ + // A screenshot of a window or part of the screen, added to the message + // being written. The desktop app only; it used to sit in the "+" menu. + // As the capture itself: not while a question holds the composer. + "composer.screenshot": typeof window.desktopBridge?.captureScreenshot === "function" && + !attachmentsDisabled && { + // After the palette has closed and handed focus back to the composer. + afterFocusReturns: true, + run: () => runCaptureScreenshot(), + }, + // As the stash shortcut, which stands down while a question holds the composer. + "composer.stash": !attachmentsDisabled && { + afterFocusReturns: true, + run: () => { + void stashCurrentPrompt(); + }, + }, + // The model picker sits in the toolbar an approval replaces. + "modelPicker.toggle": activePendingApproval === null && { + afterFocusReturns: true, + run: () => setIsComposerModelPickerOpen((open) => !open), + }, + "composer.planMode": interactionMode !== "plan" && { + run: () => handleInteractionModeChange("plan"), + }, + "composer.defaultMode": interactionMode === "plan" && { + run: () => handleInteractionModeChange("default"), + }, + // Where the model picker lists agents: rooms on, and no approval holding + // the toolbar. It opens the picker ready to add one, as its "Add agent" row. + "room.addAgent": roomsEnabled && + pendingApprovals.length === 0 && { + run: () => useRoomRecipientStore.getState().requestAddAgent(routeThreadRef), + }, }); - useEffect(() => { - if (!composerCommandRequest) return; - if (composerCommandRequest.nonce === handledComposerCommandNonceRef.current) return; - handledComposerCommandNonceRef.current = composerCommandRequest.nonce; - runComposerCommand(composerCommandRequest.kind); - }, [composerCommandRequest]); const removeComposerAttachment = (imageId: string) => { removeComposerAttachmentFromDraft(imageId); diff --git a/apps/web/src/components/chat/ProjectCrumbMenu.tsx b/apps/web/src/components/chat/ProjectCrumbMenu.tsx index 5b37fadec..763b51923 100644 --- a/apps/web/src/components/chat/ProjectCrumbMenu.tsx +++ b/apps/web/src/components/chat/ProjectCrumbMenu.tsx @@ -22,12 +22,14 @@ import { import { copyWithNotice } from "../ui/copyWithNotice"; import { EditorOpenRadioGroup, + editorLabel, editorOpenActionLabel, useEditorOpenOptions, } from "../EditorOpenOptions"; import { ProjectFavicon } from "../ProjectFavicon"; import { readLocalApi } from "~/localApi"; import { isKeyboardOwnedByDialog } from "~/commands/shortcutBlock"; +import { useCommandHandlers } from "~/commands/commandHandlers"; /** * The project crumb in the chat header, and everything that acts on the @@ -80,6 +82,20 @@ export const ProjectCrumbMenu = memo(function ProjectCrumbMenu({ void api.shell.openInEditor(path, editor); }, []); + // Open in editor from the palette: what its shortcut does, where it would act. + const preferredEditorLabel = preferredEditor ? editorLabel(preferredEditor) : null; + useCommandHandlers({ + "editor.openFavorite": canOpenInEditor && + preferredEditor !== null && + preferredEditorLabel !== null && { + title: `Open in ${preferredEditorLabel}`, + keywords: [preferredEditorLabel], + run: () => { + if (readLocalApi()) openIn(cwd, preferredEditor); + }, + }, + }); + useEffect(() => { if (!canOpenInEditor) return; const handler = (event: globalThis.KeyboardEvent) => { diff --git a/apps/web/src/components/chats/useGeneralChats.ts b/apps/web/src/components/chats/useGeneralChats.ts index ad03fe11b..aacc0401f 100644 --- a/apps/web/src/components/chats/useGeneralChats.ts +++ b/apps/web/src/components/chats/useGeneralChats.ts @@ -48,16 +48,15 @@ function resolveChatGroup(activityAt: string, nowMs: number): ChatGroupId { * `environmentId` narrows both to one computer, as the Threads list's * computer filter does: only its chats, and new ones start there. */ -export function useGeneralChats(options?: { readonly environmentId: string | null }): { - readonly chats: readonly SidebarThreadSummary[]; - /** - * Null while no computer has a General Chats project to start one in. - * `initialPrompt` opens the chat with words to finish. - */ - readonly startChat: ((initialPrompt?: string) => void) | null; -} { +/** + * Starts a new general chat (`initialPrompt` opens it with words to finish), + * or null while no computer has a General Chats project to start one in. It + * reads no threads, so a streamed reply doesn't re-render its caller. + */ +export function useStartGeneralChat(options?: { + readonly environmentId: string | null; +}): ((initialPrompt?: string) => void) | null { const { handleNewThread } = useHandleNewThread(); - const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments)); const projects = useStore(useShallow(selectProjectsAcrossEnvironments)); const generalChatsProject = useStore(selectGeneralChatsProjectAcrossEnvironments); const activeEnvironmentId = useStore((state) => state.activeEnvironmentId); @@ -79,6 +78,30 @@ export function useGeneralChats(options?: { readonly environmentId: string | nul }); }, [activeEnvironmentId, generalChatsProject, onlyEnvironmentId, primaryEnvironmentId, projects]); + const startChatInProject = useCallback( + (initialPrompt?: string) => { + if (generalChatsProjectRef) { + void startNewGeneralChatThread(handleNewThread, generalChatsProjectRef, initialPrompt); + } + }, + [generalChatsProjectRef, handleNewThread], + ); + return generalChatsProjectRef === null ? null : startChatInProject; +} + +export function useGeneralChats(options?: { readonly environmentId: string | null }): { + readonly chats: readonly SidebarThreadSummary[]; + /** + * Null while no computer has a General Chats project to start one in. + * `initialPrompt` opens the chat with words to finish. + */ + readonly startChat: ((initialPrompt?: string) => void) | null; +} { + const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments)); + const projects = useStore(useShallow(selectProjectsAcrossEnvironments)); + const startChat = useStartGeneralChat(options); + const onlyEnvironmentId = options?.environmentId ?? null; + const chats = useMemo(() => { const generalChatProjectKeys = new Set( projects @@ -97,19 +120,7 @@ export function useGeneralChats(options?: { readonly environmentId: string | nul ); }, [onlyEnvironmentId, projects, threads]); - const startChatInProject = useCallback( - (initialPrompt?: string) => { - if (generalChatsProjectRef) { - void startNewGeneralChatThread(handleNewThread, generalChatsProjectRef, initialPrompt); - } - }, - [generalChatsProjectRef, handleNewThread], - ); - - return { - chats, - startChat: generalChatsProjectRef === null ? null : startChatInProject, - }; + return { chats, startChat }; } /** diff --git a/apps/web/src/components/codexImport/codexImportStore.test.ts b/apps/web/src/components/codexImport/codexImportStore.test.ts index 155d791e6..a5fa8480d 100644 --- a/apps/web/src/components/codexImport/codexImportStore.test.ts +++ b/apps/web/src/components/codexImport/codexImportStore.test.ts @@ -21,8 +21,9 @@ function openSession(): number { } describe("codex import store", () => { + // Session ids only ever grow, as in the app. beforeEach(() => { - useCodexImportStore.setState({ session: null, lastSessionId: 0 }); + useCodexImportStore.setState({ session: null }); }); it("closes and opens the thread when its session is still open", async () => { diff --git a/apps/web/src/components/codexImport/codexImportStore.ts b/apps/web/src/components/codexImport/codexImportStore.ts index a7ef228d5..38b399491 100644 --- a/apps/web/src/components/codexImport/codexImportStore.ts +++ b/apps/web/src/components/codexImport/codexImportStore.ts @@ -76,6 +76,26 @@ export function openCodexImport(request: CodexImportOpenRequest): number { return useCodexImportStore.getState().open(request); } +/** The last session that ended with something done through it, as against closed. */ +let lastCompletedSessionId: number | null = null; + +/** + * How a session ended: "imported" when a conversation came in through it, + * "cancelled" when it was closed or replaced first. The palette counts a use + * of the command only for the first. + */ +export function waitForCodexImportSessionEnd(sessionId: number): Promise<"imported" | "cancelled"> { + return new Promise((resolve) => { + const settle = () => { + if (useCodexImportStore.getState().session?.id === sessionId) return; + unsubscribe(); + resolve(lastCompletedSessionId === sessionId ? "imported" : "cancelled"); + }; + const unsubscribe = useCodexImportStore.subscribe(settle); + settle(); + }); +} + /** * What happens once a conversation was brought in. The thread exists either * way. If the session that started the import is still open it closes and the @@ -92,6 +112,7 @@ export async function finishCodexImport(input: { input.announce(input.openThread); return; } + lastCompletedSessionId = input.sessionId; useCodexImportStore.getState().closeSession(input.sessionId); await input.openThread(); } diff --git a/apps/web/src/components/fleet/fleetCommands.ts b/apps/web/src/components/fleet/fleetCommands.ts new file mode 100644 index 000000000..4273ac456 --- /dev/null +++ b/apps/web/src/components/fleet/fleetCommands.ts @@ -0,0 +1,33 @@ +/** + * "Open computer in Fleet…" for the palette: each computer's Fleet page, once + * there is more than one to choose from. Its items are found from the main + * search too, as "Open in Fleet". + */ +import { useNavigate } from "@tanstack/react-router"; +import { useMemo } from "react"; + +import { useCommandHandlers, type CommandListItem } from "../../commands/commandHandlers"; +import { useAddProjectEnvironmentOptions } from "../addProject/addProjectComputers"; + +export function useFleetCommands(): void { + const navigate = useNavigate(); + const computers = useAddProjectEnvironmentOptions(); + const items = useMemo>( + () => + computers.map((computer) => ({ + id: computer.environmentId, + title: `Open ${computer.label} in Fleet`, + // As the one row per computer the palette had: found by "fleet" and "unlink" too. + keywords: ["fleet", "computer", "link", "unlink", computer.label], + run: () => + navigate({ + to: "/fleet/$environmentId", + params: { environmentId: computer.environmentId }, + }), + })), + [computers, navigate], + ); + useCommandHandlers({ + "fleet.openComputer": computers.length > 1 && { items, placeholder: "Search computers..." }, + }); +} diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts index 3cde03fd9..3c84bb901 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts @@ -133,9 +133,10 @@ describe("KeybindingsSettings.logic", () => { }); }); - it("formats static and project script command labels", () => { - expect(commandLabel("commandPalette.toggle")).toBe("Command Palette: Toggle"); - expect(commandLabel("script.setup-db.run")).toBe("Run Script: Setup Db"); + it("names shortcut commands as the palette does, and project scripts by name", () => { + expect(commandLabel("terminal.toggle")).toBe("Toggle terminal"); + expect(commandLabel("thread.jump.3")).toBe("Jump to thread 3"); + expect(commandLabel("script.setup-db.run")).toBe("Run script: Setup Db"); }); it("builds known when variable options from defaults without frontend labels", () => { @@ -249,13 +250,13 @@ describe("KeybindingsSettings.logic", () => { "", ); - expect(rows[0]?.conflicts).toEqual(["Chat: New Local"]); + expect(rows[0]?.conflicts).toEqual(["New local thread"]); expect( keybindingConflictLabels(rows, { rowId: rows[0]?.id ?? "", key: "mod+n", when: "", }), - ).toEqual(["Chat: New Local"]); + ).toEqual(["New local thread"]); }); }); diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index b69bd45d0..1ef73a450 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -11,6 +11,13 @@ import { } from "@threadlines/shared/keybindings"; import { isMacPlatform } from "../../lib/utils"; +import { + APP_COMMAND_GROUP_TITLES, + APP_COMMANDS, + appCommandForKeybinding, + appCommandTitle, + type AppCommandGroup, +} from "@threadlines/shared/appCommands"; export type KeybindingSource = "Default" | "Custom" | "Project"; @@ -185,7 +192,7 @@ export function buildKeybindingRows( }); rowsWithConflicts.sort((left, right) => { - const commandCompare = left.command.localeCompare(right.command); + const commandCompare = compareCommands(left.command, right.command); if (commandCompare !== 0) return commandCompare; return left.key.localeCompare(right.key); }); @@ -196,7 +203,7 @@ export function buildKeybindingRows( return rowsWithConflicts.filter((row) => { return ( - // The label is what the table shows ("Terminal: Toggle"); the id is what keybindings.json says. + // The label is what the table shows ("Toggle terminal"); the id is what keybindings.json says. commandLabel(row.command).toLowerCase().includes(normalizedQuery) || row.command.toLowerCase().includes(normalizedQuery) || row.key.toLowerCase().includes(normalizedQuery) || @@ -267,14 +274,51 @@ export function buildKeybindingCommandOptions( ); } +/** + * What a shortcut command is called: the command palette's name for it (the + * catalog's title, with a jump's number), so the two never disagree. A + * project script is "Run script: ". + */ export function commandLabel(command: KeybindingCommand): string { const raw = String(command); if (raw.startsWith("script.") && raw.endsWith(".run")) { - return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`; + return `Run script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`; } + const named = appCommandForKeybinding(command); + if (named) return appCommandTitle(named.id, named.number); return raw.split(".").map(titleCaseCommandSegment).join(": "); } +const GROUP_ORDER: ReadonlyArray = ["thread", "panels", "project", "goTo", "app"]; +const CATALOG_ORDER = new Map(Object.keys(APP_COMMANDS).map((id, index) => [id, index])); + +/** The palette's group a shortcut command belongs to; project scripts are the project's. */ +export function commandGroup(command: KeybindingCommand): AppCommandGroup { + const named = appCommandForKeybinding(command); + return named ? APP_COMMANDS[named.id].group : "project"; +} + +/** The heading a group of shortcuts sits under on the Keybindings page. */ +export function commandGroupTitle(group: AppCommandGroup): string { + return APP_COMMAND_GROUP_TITLES[group]; +} + +/** Grouped as the palette groups commands, then in the palette's order. */ +function compareCommands(left: KeybindingCommand, right: KeybindingCommand): number { + const groupCompare = + GROUP_ORDER.indexOf(commandGroup(left)) - GROUP_ORDER.indexOf(commandGroup(right)); + if (groupCompare !== 0) return groupCompare; + const leftNamed = appCommandForKeybinding(left); + const rightNamed = appCommandForKeybinding(right); + const orderCompare = + (leftNamed ? (CATALOG_ORDER.get(leftNamed.id) ?? 0) : Number.MAX_SAFE_INTEGER) - + (rightNamed ? (CATALOG_ORDER.get(rightNamed.id) ?? 0) : Number.MAX_SAFE_INTEGER); + if (orderCompare !== 0) return orderCompare; + const numberCompare = (leftNamed?.number ?? 0) - (rightNamed?.number ?? 0); + if (numberCompare !== 0) return numberCompare; + return left.localeCompare(right); +} + function titleCaseCommandSegment(segment: string): string { return segment .replace(/([a-z0-9])([A-Z])/g, "$1 $2") diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 5ab4fe6a6..a8498b9f6 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -11,6 +11,7 @@ import { XIcon, } from "lucide-react"; import { + Fragment, type KeyboardEvent, type ReactNode, type RefObject, @@ -52,6 +53,8 @@ import { Toggle } from "../ui/toggle"; import { failureNotice, toastManager } from "../ui/toast"; import { buildKeybindingRows, + commandGroup, + commandGroupTitle, buildKeybindingCommandOptions, buildWhenVariableOptions, commandLabel, @@ -1259,18 +1262,32 @@ export function KeybindingsSettingsPanel() { onCancel={() => setIsAddingBinding(false)} /> ) : null} - {rows.map((row) => ( - - ))} + {rows.map((row, index) => { + // Grouped as the command palette groups commands, each under its heading. + const group = commandGroup(row.command); + const startsGroup = index === 0 || commandGroup(rows[index - 1]!.command) !== group; + return ( + + {startsGroup ? ( +
+ {commandGroupTitle(group)} +
+ ) : null} + +
+ ); + })} {rows.length === 0 && !isAddingBinding ? (
No keybindings match your search. diff --git a/apps/web/src/components/settings/settingsSearchIndex.ts b/apps/web/src/components/settings/settingsSearchIndex.ts index e577fd6d6..120125910 100644 --- a/apps/web/src/components/settings/settingsSearchIndex.ts +++ b/apps/web/src/components/settings/settingsSearchIndex.ts @@ -242,7 +242,7 @@ function skillItems(providers: ReadonlyArray): ReadonlyArray window.removeEventListener("keydown", handler, true); }, [keybindings, terminalOpen]); - // The palette's terminal actions, while this page is open. - const commandRequest = useTerminalCommandsStore((state) => state.request); - const handledNonceRef = useRef(commandRequest?.nonce ?? 0); - useEffect(() => { - if (!commandRequest || commandRequest.nonce === handledNonceRef.current) return; - handledNonceRef.current = commandRequest.nonce; - runCommand(commandRequest.kind); - }, [commandRequest]); + // The palette's terminal actions, while this page is open: the same paths + // as its shortcuts, run once the palette has handed focus back. + const terminalHandler = (kind: TerminalCommandKind, description?: string) => ({ + afterFocusReturns: true, + description, + run: () => runCommand(kind), + }); + // New and Split open the first tab; the rest act on an open terminal only. + useCommandHandlers({ + "terminal.new": terminalHandler("new", "Open a terminal in the project picked for new tabs"), + "terminal.split": terminalHandler("split"), + "terminal.find": terminalOpen && terminalHandler("find"), + "terminal.restart": + terminalOpen && + terminalHandler("restart", "A new shell in the same folder, below the old output"), + "terminal.clear": terminalOpen && terminalHandler("clear"), + "terminal.close": terminalOpen && terminalHandler("kill"), + }); const shortcutOptions = useMemo( () => ({ context: { terminalFocus: true, terminalOpen: true } }), diff --git a/apps/web/src/components/theme/ui/themeCommands.tsx b/apps/web/src/components/theme/ui/themeCommands.tsx new file mode 100644 index 000000000..519e55947 --- /dev/null +++ b/apps/web/src/components/theme/ui/themeCommands.tsx @@ -0,0 +1,77 @@ +/** + * The command palette's theme commands (docs/design/custom-themes.md, + * "Switching"): "Change theme…" lists every theme a device can wear and + * switches the way Settings does; "Use default theme" is the escape hatch, + * always there, whatever the theme looks like. + */ +import { useMemo } from "react"; + +import { useCommandHandlers, type CommandListItem } from "~/commands/commandHandlers"; +import { chooseTheme, useThemeChoice } from "~/theme/themeStore"; +import { + sameThemeChoice, + shownThemeChoice, + switchToTheme, + tileIsChosen, + type ThemeTile, + useThemeTiles, +} from "~/themeLibrary/themeCatalog"; +import { ITEM_ICON_CLASS } from "../../CommandPalette.logic"; +import { failureNotice, toastManager } from "../../ui/toast"; +import { openThemeEditor } from "./themeEditorState"; + +export function useThemeCommands(): void { + const { builtins, starters, library } = useThemeTiles(); + const committed = useThemeChoice(); + const items = useMemo>(() => { + const itemOf = (tile: ThemeTile, group: string): CommandListItem => ({ + id: tile.key, + title: tile.name, + description: tileIsChosen(tile, committed) ? `${tile.detail} · in use` : tile.detail, + keywords: [tile.detail], + group, + icon: ( + + ), + run: async () => { + await switchToTheme(tile).catch((error: unknown) => + toastManager.add( + failureNotice({ + title: `Couldn't switch to ${tile.name}`, + reason: error instanceof Error ? error.message : "Try again.", + }), + ), + ); + }, + }); + return [ + ...builtins.map((tile) => itemOf(tile, "Built in")), + ...starters.map((tile) => itemOf(tile, "Starters")), + ...library.map((tile) => itemOf(tile, "Your themes")), + ]; + }, [builtins, committed, library, starters]); + + useCommandHandlers({ + "theme.change": { items, placeholder: "Search themes..." }, + "theme.editColors": { + run: () => { + const tiles = [...builtins, ...starters, ...library]; + // System, and its pair, show one theme at a time: the one the computer's mode picks. + const shown = shownThemeChoice(committed); + const tile = tiles.find((candidate) => sameThemeChoice(candidate.choice, shown)); + if (tile !== undefined) openThemeEditor(tile); + else + toastManager.add({ + type: "info", + title: "This theme can't be edited here", + description: "Keep it first, then edit it from Appearance.", + }); + }, + }, + "theme.useDefault": { run: () => chooseTheme({ kind: "builtin", id: "system" }) }, + }); +} diff --git a/apps/web/src/components/theme/ui/themePaletteItems.tsx b/apps/web/src/components/theme/ui/themePaletteItems.tsx deleted file mode 100644 index 0eb8209d7..000000000 --- a/apps/web/src/components/theme/ui/themePaletteItems.tsx +++ /dev/null @@ -1,110 +0,0 @@ -/** - * The command palette's theme entries (docs/design/custom-themes.md, - * "Switching"): "Change theme…" lists every theme a device can wear and - * switches the way Settings does; "Use default theme" is the escape hatch, - * always there, whatever the theme looks like. - */ -import { PaintbrushIcon, PaletteIcon, RotateCcwIcon } from "lucide-react"; -import { useMemo } from "react"; - -import { chooseTheme, useThemeChoice } from "~/theme/themeStore"; -import { - sameThemeChoice, - shownThemeChoice, - switchToTheme, - tileIsChosen, - type ThemeTile, - useThemeTiles, -} from "~/themeLibrary/themeCatalog"; -import type { - CommandPaletteActionItem, - CommandPaletteSubmenuItem, -} from "../../CommandPalette.logic"; -import { failureNotice, toastManager } from "../../ui/toast"; -import { openThemeEditor } from "./themeEditorState"; - -export function useThemePaletteItems(classes: { - readonly item: string; - readonly addon: string; -}): ReadonlyArray { - const { builtins, starters, library } = useThemeTiles(); - const committed = useThemeChoice(); - return useMemo(() => { - const itemOf = (tile: ThemeTile): CommandPaletteActionItem => ({ - kind: "action", - value: `theme:${tile.key}`, - searchTerms: [tile.name, tile.detail, "theme"], - title: tile.name, - description: tileIsChosen(tile, committed) ? `${tile.detail} · in use` : tile.detail, - icon: ( - - ), - run: async () => { - await switchToTheme(tile).catch((error: unknown) => - toastManager.add( - failureNotice({ - title: `Couldn't switch to ${tile.name}`, - reason: error instanceof Error ? error.message : "Try again.", - }), - ), - ); - }, - }); - const groups = [ - { value: "theme-builtin", label: "Built in", items: builtins.map(itemOf) }, - { value: "theme-starters", label: "Starters", items: starters.map(itemOf) }, - ...(library.length > 0 - ? [{ value: "theme-library", label: "Your themes", items: library.map(itemOf) }] - : []), - ]; - return [ - { - kind: "submenu", - value: "action:change-theme", - searchTerms: ["theme", "appearance", "dark mode", "light mode", "colors", "wallpaper"], - title: "Change theme…", - icon: , - addonIcon: , - groups, - }, - { - kind: "action", - value: "action:edit-theme-colors", - searchTerms: [ - "edit theme", - "theme colors", - "customize colors", - "accent color", - "tweak theme", - ], - title: "Edit theme colors…", - icon: , - run: async () => { - const tiles = [...builtins, ...starters, ...library]; - // System, and its pair, show one theme at a time: the one the computer's mode picks. - const shown = shownThemeChoice(committed); - const tile = tiles.find((candidate) => sameThemeChoice(candidate.choice, shown)); - if (tile !== undefined) openThemeEditor(tile); - else - toastManager.add({ - type: "info", - title: "This theme can't be edited here", - description: "Keep it first, then edit it from Appearance.", - }); - }, - }, - { - kind: "action", - value: "action:default-theme", - searchTerms: ["default theme", "reset theme", "system theme", "can't read"], - title: "Use default theme", - icon: , - run: async () => chooseTheme({ kind: "builtin", id: "system" }), - }, - ]; - }, [builtins, classes.addon, classes.item, committed, library, starters]); -} diff --git a/apps/web/src/composerCommands.ts b/apps/web/src/composerCommands.ts deleted file mode 100644 index 589869516..000000000 --- a/apps/web/src/composerCommands.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Composer actions asked for from outside the composer (the command palette): - * the composer on screen carries them out, the same way its own controls do. - */ -import { create } from "zustand"; - -export type ComposerCommandKind = "captureScreenshot"; - -export interface ComposerCommandRequest { - readonly kind: ComposerCommandKind; - /** Tells a repeat of the same action from the one already handled. */ - readonly nonce: number; -} - -interface ComposerCommandsState { - readonly request: ComposerCommandRequest | null; - readonly requestComposerCommand: (kind: ComposerCommandKind) => void; -} - -export const useComposerCommandsStore = create()((set) => ({ - request: null, - requestComposerCommand: (kind) => - set((state) => ({ request: { kind, nonce: (state.request?.nonce ?? 0) + 1 } })), -})); diff --git a/apps/web/src/hooks/useThreadMenu.ts b/apps/web/src/hooks/useThreadMenu.ts index 969b8a0ee..7b650269d 100644 --- a/apps/web/src/hooks/useThreadMenu.ts +++ b/apps/web/src/hooks/useThreadMenu.ts @@ -147,8 +147,9 @@ export function useThreadMenu() { }, []); /** Does what the menu item says, for the thread as it is now. */ + /** Does what the item says; "cancelled" when the user said no to a confirmation. */ const run = useCallback( - async (action: ThreadMenuAction, target: ThreadMenuTarget) => { + async (action: ThreadMenuAction, target: ThreadMenuTarget): Promise => { const { threadRef } = target; const threadKey = scopedThreadKey(threadRef); const byKey = summariesByKey(); @@ -270,7 +271,7 @@ export function useThreadMenu() { api && !(await api.dialogs.confirm(`Archive thread "${thread.title}"?`)) ) { - return; + return "cancelled"; } try { await archiveThread(threadRef); @@ -291,7 +292,7 @@ export function useThreadMenu() { title: thread.title, childCount, }); - if (answer === null) return; + if (answer === null) return "cancelled"; await deleteThread(threadRef, { withChildren: answer.withChildren }); return; } @@ -305,7 +306,7 @@ export function useThreadMenu() { ].join("\n"), )) ) { - return; + return "cancelled"; } await deleteThread(threadRef); return; diff --git a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx index 8d659bcd8..a66c20a68 100644 --- a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx +++ b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx @@ -134,6 +134,8 @@ import { SourceControlPanel, type SourceControlProjectTarget, } from "../components/source-control/SourceControlPanel"; +import { useCommandHandlers } from "../commands/commandHandlers"; +import { usePanelTabCommands } from "../commands/panelTabCommands"; // The rail can be opened before the chat column has published its turn state // (or on a thread with nothing running at all), so the agents tab renders from @@ -800,6 +802,19 @@ function ChatThreadRouteView() { ); // What a transcript link to one of these opens. Only the ones the tab can // show are offered, so a link never lands on the tab's fallback. + // The panel's tabs in the palette, through the same selector the tab row + // uses so the URL follows, and the thread's pull request. + const leadPullRequestNumber = leadPullRequestTarget?.reference.number ?? null; + usePanelTabCommands(availableTabs, selectTab); + useCommandHandlers({ + // Only where there is one to open: a command that lands on "this thread + // has no pull request" is a dead end the palette should not offer. + "thread.pullRequest": leadPullRequestNumber !== null && { + title: `Open pull request #${leadPullRequestNumber}`, + keywords: [`#${leadPullRequestNumber}`], + run: () => openPullRequestTab(leadPullRequestNumber), + }, + }); const threadPullRequestLinks = useMemo( () => threadPullRequests.length === 0 diff --git a/apps/web/src/routes/_chat.draft.$draftId.tsx b/apps/web/src/routes/_chat.draft.$draftId.tsx index a1e220516..765c8e7ef 100644 --- a/apps/web/src/routes/_chat.draft.$draftId.tsx +++ b/apps/web/src/routes/_chat.draft.$draftId.tsx @@ -56,6 +56,7 @@ import { buildThreadRouteParams, resolveDraftCanonicalThreadRef, } from "../threadRoutes"; +import { usePanelTabCommands } from "../commands/panelTabCommands"; const FileViewerOverlay = lazy(() => import("../components/file-viewer/FileViewerOverlay")); @@ -240,6 +241,8 @@ function DraftChatThreadRouteView() { }, [navigateToTab, openDiffOnThreadRoute, panelStateKey], ); + // The panel's tabs in the palette, through this route's own selector. + usePanelTabCommands(availableTabs, selectTab); const closeTab = useCallback( (tab: RightPanelTab) => { navigateToTab(closeRightPanelTab(panelStateKey, tab)); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 206d0da75..7c3ce3347 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -1372,6 +1372,25 @@ function withScheduleApproval( : { ...summary, pendingScheduleApproval: pending }; } +/** + * Whether a thread reads the same in a list that dates and orders threads by + * their latest user message (the command palette's). A streamed reply moves + * `updatedAt` on every token, which such a list never shows for a thread the + * user has written in. + */ +export function sidebarThreadSummariesListEqual( + left: SidebarThreadSummary, + right: SidebarThreadSummary, +): boolean { + if (left === right) return true; + const activityOnlyFromReplies = + left.latestUserMessageAt != null && left.latestUserMessageAt === right.latestUserMessageAt; + return sidebarThreadSummariesEqual( + left, + activityOnlyFromReplies ? { ...right, updatedAt: left.updatedAt } : right, + ); +} + function sidebarThreadSummariesEqual( left: SidebarThreadSummary | undefined, right: SidebarThreadSummary, diff --git a/apps/web/src/terminalCommands.ts b/apps/web/src/terminalCommands.ts deleted file mode 100644 index c01bbbb54..000000000 --- a/apps/web/src/terminalCommands.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Terminal actions asked for from outside the thread view (the command - * palette): the thread view that shows the thread carries them out, with the - * same confirmations its own buttons use. - */ -import { create } from "zustand"; - -export type TerminalCommandKind = - | "toggle" - | "new" - | "split" - | "find" - | "clear" - | "restart" - | "kill"; - -export interface TerminalCommandRequest { - readonly kind: TerminalCommandKind; - /** Tells a repeat of the same action from the one already handled. */ - readonly nonce: number; -} - -interface TerminalCommandsState { - readonly request: TerminalCommandRequest | null; - readonly requestTerminalCommand: (kind: TerminalCommandKind) => void; -} - -export const useTerminalCommandsStore = create()((set) => ({ - request: null, - requestTerminalCommand: (kind) => - set((state) => ({ request: { kind, nonce: (state.request?.nonce ?? 0) + 1 } })), -})); diff --git a/docs/design/command-palette.md b/docs/design/command-palette.md index 2573fbc7d..acad17574 100644 --- a/docs/design/command-palette.md +++ b/docs/design/command-palette.md @@ -644,6 +644,9 @@ promise exist now. - Composer slash commands (`/model`, `/theme`, `/plan`) reading the catalog. - `app_guide` answering "what commands are there" from the catalog. - A redesign of Add project. +- One shared inbox derivation that the Sidebar, the desktop badge, the alert + sounds and the palette all read. Today each runs its own copy on every + streamed token. ## As built: step 1 (Nov 23 2026) @@ -670,6 +673,56 @@ Where the build differs from section 7: splitting code that already loaded at startup into more files. Neither dialog body loads at startup. +## As built: step 2 (Nov 23 2026) + +The catalog is `packages/shared/src/appCommands.ts`, the registry +`apps/web/src/commands/commandHandlers.ts`, and the palette reads only what +owners register. Where the build differs from sections 1 to 4: + +- **No `appliesWhen` field.** Every "where" is a registration rule, so the + catalog holds names only. +- **Toggle diff is "Toggle panel".** `diff.toggle` (the shortcut) shows or + hides the side panel on the tab it was left on, which is also what the + header's button does and says. "diff" is one of its keywords. + "Show diff" (`panel.diff`) opens the diff tab itself, beside the other + panel tabs. +- **Plan and build mode** are "Switch to plan mode" and "Switch to build + mode", and only the one you're not in is offered. +- **Lead chats are a list**, "Go to lead chat…", with one item per project + that has a lead; typing "lead" still finds each from the main search. +- **The thread's pull request** comes from the thread route's own answer (the + one the Pull request tab shows), not a second lookup in the palette. +- **The panel's tabs** are offered on drafts too, through the draft route's + own tab selector. +- **Rules changed rather than moved**, each because the command would + otherwise land on nothing: Capture screenshot is hidden while a question + holds the composer; on the Terminals page, Find, Clear, Restart and Kill + need an open terminal; New local thread is offered wherever its shortcut + works, Home included; Show wrapped threads only where the inbox and its + shelf are on screen. +- **`opensDialog` is only Add project and Codex import.** Move, Move + threads and Rename keep the palette's return of focus to the composer, + because their dialogs give focus back to whatever had it when they opened. +- **A cancelled run** is reported by Archive and Delete (the thread menu), + Restart and Kill on a thread's terminal (its confirmation), Add project and + Codex import (closed without adding), and Capture screenshot. Other dialogs + count as used once opened. A list item counts for its list too. +- **Streaming.** The palette's rows and its command sources commit nothing + while a reply streams: the palette ignores a thread's last-activity time + when it has a user message (`sidebarThreadSummariesListEqual`), and "can a + general chat start" no longer lists every chat (`useStartGeneralChat`). + Wrap up, Reopen and the lead commands are the exception. They need the + inbox, which re-derives on every token, so their source is mounted beside + the palette, outside the Profiler, and still recomputes per token while the + palette is open, as the old palette did. +- **Startup** went from 904.9 KB to 904.7 KB gzip. The catalog's data, the + icons and the palette's sources are not in it. +- **Words that differ from the catalog**, left for the later pass: the + header's "Toggle terminal drawer" (Toggle terminal); the rail's + Terminals, Fleet, Scheduled, Usage, Settings, General Chats and Pull + Requests (each "Open …" here); the title row's Back and Forward (Go back, + Go forward). + ## Rev 2 changes (Sol's review of rev 1) 1. **Older linked computers.** A new field on a search match must be diff --git a/packages/shared/package.json b/packages/shared/package.json index c51910aac..f058d722b 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -447,6 +447,10 @@ "types": "./src/threadFiling.ts", "import": "./src/threadFiling.ts" }, + "./appCommands": { + "types": "./src/appCommands.ts", + "import": "./src/appCommands.ts" + }, "./appPlaces": { "types": "./src/appPlaces.ts", "import": "./src/appPlaces.ts" diff --git a/packages/shared/src/appCommands.test.ts b/packages/shared/src/appCommands.test.ts new file mode 100644 index 000000000..c73b93802 --- /dev/null +++ b/packages/shared/src/appCommands.test.ts @@ -0,0 +1,50 @@ +import { + MODEL_PICKER_JUMP_KEYBINDING_COMMANDS, + THREAD_JUMP_KEYBINDING_COMMANDS, +} from "@threadlines/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + APP_COMMANDS, + appCommandForKeybinding, + appCommandTitle, + type AppCommandId, +} from "./appCommands.ts"; + +const ids = Object.keys(APP_COMMANDS) as AppCommandId[]; + +describe("app command catalog", () => { + it("gives every command its own title, so no two rows read the same", () => { + const titles = ids.map((id) => APP_COMMANDS[id].title); + expect(titles.filter((title, index) => titles.indexOf(title) !== index)).toEqual([]); + }); + + it("puts a number placeholder in exactly the numbered families", () => { + for (const id of ids) { + const spec: { readonly title: string; readonly numbered?: true } = APP_COMMANDS[id]; + expect(spec.title.includes("{n}"), id).toBe(spec.numbered === true); + } + }); + + it("labels each numbered shortcut with its own number", () => { + const labels = [ + ...THREAD_JUMP_KEYBINDING_COMMANDS, + ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS, + ].map((command) => { + const named = appCommandForKeybinding(command); + return named ? appCommandTitle(named.id, named.number) : null; + }); + expect(labels).toContain("Jump to thread 1"); + expect(labels).toContain("Jump to thread 9"); + expect(labels).toContain("Choose model 4"); + expect(new Set(labels).size).toBe(labels.length); + }); + + it("names a plain shortcut command by its own id, and a script by none", () => { + expect(appCommandForKeybinding("terminal.toggle")).toEqual({ + id: "terminal.toggle", + number: null, + }); + expect(appCommandForKeybinding("script.dev.run")).toBeNull(); + }); +}); diff --git a/packages/shared/src/appCommands.ts b/packages/shared/src/appCommands.ts new file mode 100644 index 000000000..4ef5fed62 --- /dev/null +++ b/packages/shared/src/appCommands.ts @@ -0,0 +1,570 @@ +/** + * Every command the app has, by name (docs/design/command-palette.md, + * section 1). Data only: the command palette offers a command when whoever + * owns its behavior registers a handler for it, and takes the words from + * here; the Keybindings page and settings search label shortcuts from it. + * + * - A command with a shortcut uses the shortcut's id, and the check at the + * bottom fails to compile when a shortcut command has no entry. + * - The numbered shortcut families (`thread.jump.N`, `modelPicker.jump.N`) + * share one `numbered` entry each, with "{n}" in the title. + * - Order is the palette's order for commands that rank the same. + * + * Components that load at startup import only the `AppCommandId` type, so + * this data loads with the palette and Settings. + */ +import type { + KeybindingCommand, + ModelPickerJumpKeybindingCommand, + ThreadJumpKeybindingCommand, +} from "@threadlines/contracts"; + +export type AppCommandGroup = "thread" | "panels" | "project" | "goTo" | "app"; + +export interface AppCommandSpec { + /** Exactly what the palette row says. */ + readonly title: string; + /** One sentence, shown under the title. */ + readonly about?: string; + readonly group: AppCommandGroup; + /** Other words that find it. */ + readonly keywords?: ReadonlyArray; + /** "list": Enter opens a list to pick from (projects, themes, scripts, computers). */ + readonly kind?: "action" | "list"; + /** A list whose items are also found from the main search. */ + readonly itemsSearchable?: true; + /** One entry for a numbered shortcut family; "{n}" in the title is the number. */ + readonly numbered?: true; +} + +export const APP_COMMAND_GROUP_TITLES: Readonly> = { + thread: "Thread", + panels: "Panels", + project: "Projects", + goTo: "Go to", + app: "App", +}; + +export const APP_COMMANDS = { + "chat.new": { + title: "New thread", + group: "thread", + keywords: ["new thread", "chat", "create", "draft"], + }, + "chat.newLocal": { + title: "New local thread", + about: "A new thread in the project's own folder, not a worktree", + group: "thread", + keywords: ["new thread", "local", "checkout", "no worktree"], + }, + "codex.import": { + title: "Bring in Codex conversation…", + about: "Continue work from Codex app, CLI, or IDE", + group: "thread", + keywords: ["open", "import", "codex", "session", "chat", "conversation"], + }, + "worktrees.pickUp": { + title: "Add existing worktrees as threads…", + about: "Worktrees this repository already has, made outside Threadlines", + group: "project", + keywords: ["worktree", "existing", "pick up", "import", "branch", "add threads"], + }, + "project.brief": { + title: "Project brief and notes", + group: "project", + keywords: ["brief", "project brief", "notes", "instructions", "rules"], + }, + "chat.newIn": { + title: "New thread in...", + group: "thread", + kind: "list", + keywords: ["new thread", "project", "pick", "choose", "select"], + }, + "project.add": { + title: "Add project", + group: "project", + keywords: [ + "add project", + "folder", + "directory", + "browse", + "clone", + "remote", + "repository", + "repo", + "git", + "github", + "gitlab", + "bitbucket", + "azure", + "devops", + "url", + "environment", + ], + }, + "navigate.home": { + title: "Go to Home", + group: "goTo", + keywords: ["home", "landing", "start", "threads"], + }, + "chat.newGeneral": { + title: "New general chat", + group: "thread", + keywords: ["new chat", "general chat", "chat", "conversation", "no project"], + }, + "navigate.generalChats": { + title: "Open general chats", + group: "goTo", + keywords: ["general chats", "chats", "conversations", "no project"], + }, + "navigate.terminals": { + title: "Open Terminals", + about: "Terminal tabs for any project, outside a chat", + group: "goTo", + keywords: ["terminals", "terminal", "shell", "shells", "split terminal", "dev server"], + }, + "navigate.fleet": { + title: "Open Fleet", + about: "Your computers and what runs on them", + group: "goTo", + keywords: ["fleet", "computers", "machines", "devices", "phone", "graph", "running"], + }, + "navigate.scheduled": { + title: "Open Scheduled", + about: "Tasks agents start at set times", + group: "goTo", + keywords: ["scheduled", "schedule", "tasks", "automations", "cron", "recurring", "daily"], + }, + "scheduled.new": { + title: "New scheduled task", + group: "app", + keywords: ["new scheduled task", "schedule", "automation", "cron", "recurring"], + }, + "computer.rename": { + title: "Rename this computer", + group: "app", + keywords: ["rename computer", "computer name", "name this computer", "fleet", "device"], + }, + "app.whatsNew": { + title: "What's new in Threadlines", + group: "app", + keywords: ["what's new", "whats new", "changelog", "release notes", "version", "update"], + }, + "app.reportProblem": { + title: "Report a problem", + about: "Write a bug report and post it to GitHub", + group: "app", + keywords: ["report a problem", "report", "bug", "issue", "feedback", "github", "crash"], + }, + "computer.connect": { + title: "Connect to a computer", + about: "Use projects from another computer that runs Threadlines", + group: "app", + keywords: ["connect", "computer", "add computer", "pair", "code", "ssh", "link computers"], + }, + "outsideAgents.connect": { + title: "Connect an agent", + about: "Let an agent you run outside Threadlines use it", + group: "app", + keywords: [ + "connect an agent", + "outside agent", + "mcp", + "claude code", + "codex", + "gemini", + "cursor", + "terminal", + ], + }, + "assistants.connect": { + title: "Connect an assistant", + about: "Show a code for an always-on assistant to sign in with", + group: "app", + keywords: [ + "connect an assistant", + "assistant", + "always-on", + "grok bot", + "dots", + "muse", + "claude duet", + "connector", + "sign-in code", + "key", + ], + }, + "fleet.openComputer": { + title: "Open computer in Fleet…", + group: "goTo", + kind: "list", + itemsSearchable: true, + keywords: ["fleet", "computer", "link", "unlink"], + }, + "sidebar.toggle": { + title: "Toggle sidebar", + group: "panels", + keywords: ["sidebar", "thread list", "hide", "show", "toggle", "rail"], + }, + "navigate.pullRequests": { + title: "Open pull requests", + group: "goTo", + keywords: ["pull requests", "prs", "pr", "reviews", "github"], + }, + "thread.pullRequest": { + title: "Open pull request", + group: "panels", + keywords: ["pull request", "pr", "review", "github"], + }, + "panel.device": { + title: "Open device", + group: "panels", + keywords: ["device", "simulator", "emulator", "ios", "android", "phone"], + }, + "chat.find": { + title: "Find in chat", + about: "Search this chat's messages", + group: "thread", + keywords: ["find in chat", "find", "search this chat", "search messages", "ctrl f"], + }, + "composer.screenshot": { + title: "Capture screenshot", + about: "Add a screenshot to the message you're writing", + group: "thread", + keywords: ["screenshot", "capture", "screen", "image", "attach", "picture"], + }, + "terminal.toggle": { + title: "Toggle terminal", + about: "Show or hide this thread's terminal", + group: "panels", + keywords: ["terminal", "toggle terminal", "show terminal", "hide terminal", "shell"], + }, + "terminal.new": { + title: "New terminal tab", + about: "Open another terminal for this thread", + group: "panels", + keywords: ["new terminal", "terminal tab", "open terminal", "shell"], + }, + "terminal.split": { + title: "Split terminal", + about: "Open a terminal beside the current one", + group: "panels", + keywords: ["split terminal", "side by side", "terminal"], + }, + "terminal.find": { + title: "Find in terminal", + about: "Search the terminal's output", + group: "panels", + keywords: ["find in terminal", "search terminal", "terminal output", "find"], + }, + "terminal.restart": { + title: "Restart terminal", + about: "A new shell in the thread's folder, below the old output", + group: "panels", + keywords: ["restart terminal", "reset terminal", "new shell", "terminal"], + }, + "terminal.clear": { + title: "Clear terminal output", + about: "Empty the terminal and its saved output", + group: "panels", + keywords: ["clear terminal", "clear output", "terminal"], + }, + "terminal.close": { + title: "Kill terminal", + about: "Stop the terminal's shell and close its tab", + group: "panels", + keywords: ["kill terminal", "close terminal", "stop terminal", "terminal"], + }, + "room.addAgent": { + title: "Add agent", + about: "Bring another model into this thread", + group: "thread", + keywords: ["add agent", "agents", "room", "model", "invite", "second opinion", "review"], + }, + "thread.move": { + title: "Move to another computer", + about: "Move this thread and its changes to a linked computer", + group: "thread", + keywords: ["move", "computer", "linked", "transfer", "send", "another machine"], + }, + "threads.moveMany": { + title: "Move threads to another computer…", + about: "Move several of this computer's threads to a linked computer", + group: "app", + keywords: ["move", "threads", "computer", "linked", "shut down", "clear", "another machine"], + }, + "project.setUpElsewhere": { + title: "Set up project on another computer", + about: "Clone this project on another computer, with the ignored files you pick", + group: "project", + keywords: ["set up", "project", "computer", "clone", "copy", "another machine"], + }, + "thread.makeLead": { + title: "Make this the lead chat", + group: "thread", + keywords: ["lead chat", "lead", "coordinate", "project lead"], + }, + "thread.stopLead": { + title: "Stop using as lead chat", + group: "thread", + keywords: ["lead chat", "lead", "coordinate", "project lead"], + }, + "thread.rename": { + title: "Rename thread", + group: "thread", + keywords: ["rename", "title", "name"], + }, + "thread.pin": { + title: "Pin thread", + group: "thread", + keywords: ["pin", "keep", "top"], + }, + "thread.unpin": { + title: "Unpin thread", + group: "thread", + keywords: ["unpin"], + }, + "thread.wrapUp": { + title: "Wrap up thread", + group: "thread", + keywords: ["wrap up", "done", "finish", "file away"], + }, + "thread.reopen": { + title: "Reopen thread", + group: "thread", + keywords: ["reopen", "active", "unwrap"], + }, + "thread.copyPath": { + title: "Copy thread path", + group: "thread", + keywords: ["copy", "path", "folder", "directory"], + }, + "thread.copyId": { + title: "Copy thread ID", + group: "thread", + keywords: ["copy", "id"], + }, + "thread.archive": { + title: "Archive thread", + group: "thread", + keywords: ["archive", "hide", "put away"], + }, + "thread.delete": { + title: "Delete thread", + group: "thread", + keywords: ["delete", "remove", "trash"], + }, + "leadChat.goTo": { + title: "Go to lead chat…", + group: "goTo", + kind: "list", + itemsSearchable: true, + keywords: ["lead chat", "lead"], + }, + "leadChat.new": { + title: "New lead chat", + group: "project", + keywords: ["new lead chat", "lead chat", "lead", "coordinate"], + }, + "navigate.usage": { + title: "Open usage", + group: "goTo", + keywords: ["usage", "tokens", "cost", "spend", "spending", "price", "billing"], + }, + "navigate.settings": { + title: "Open settings", + group: "goTo", + keywords: ["settings", "preferences", "configuration", "keybindings"], + }, + "navigate.setup": { + title: "Set up agents", + group: "app", + keywords: ["setup", "set up", "agents", "providers", "install", "sign in", "onboarding"], + }, + "navigate.communityAgents": { + title: "Browse community agents", + group: "app", + keywords: ["community", "agents", "add agent", "install agent", "acp", "registry"], + }, + "navigate.skills": { + title: "Open skills", + group: "goTo", + keywords: ["skills", "plugins", "extensions", "agents", "capabilities"], + }, + + // Commands with a real action today that the palette did not offer (section 4). + "diff.toggle": { + title: "Toggle panel", + about: "Show or hide the panel beside the chat: diff, source control, agents", + group: "panels", + keywords: ["diff", "toggle diff", "panel", "changes", "review", "side panel"], + }, + "panel.diff": { + title: "Show diff", + about: "The changes this thread made", + group: "panels", + keywords: ["diff", "changes", "review", "files changed", "panel"], + }, + "panel.sourceControl": { + title: "Show source control", + group: "panels", + keywords: ["source control", "git", "commit", "branch", "changes", "panel"], + }, + "panel.agents": { + title: "Show agents", + about: "The agents working in this thread", + group: "panels", + keywords: ["agents", "subagents", "workers", "panel"], + }, + "panel.threads": { + title: "Show threads panel", + about: "Threads this thread started", + group: "panels", + keywords: ["threads", "child threads", "children", "panel"], + }, + "modelPicker.toggle": { + title: "Switch model", + group: "thread", + keywords: ["model", "switch model", "change model", "agent", "provider"], + }, + "composer.stash": { + title: "Stash message", + about: "Put the message you're writing aside for later", + group: "thread", + keywords: ["stash", "save draft", "put aside", "later"], + }, + "composer.planMode": { + title: "Switch to plan mode", + about: "The agent plans before it changes anything", + group: "thread", + keywords: ["plan", "plan mode", "mode", "think first"], + }, + "composer.defaultMode": { + title: "Switch to build mode", + about: "The agent works on the task directly", + group: "thread", + keywords: ["build", "default mode", "mode", "leave plan mode"], + }, + "editor.openFavorite": { + title: "Open in editor", + group: "project", + keywords: ["editor", "open in editor", "vs code", "cursor", "zed", "ide"], + }, + "thread.previous": { + title: "Previous thread", + group: "goTo", + keywords: ["previous thread", "thread above", "up"], + }, + "thread.next": { + title: "Next thread", + group: "goTo", + keywords: ["next thread", "thread below", "down"], + }, + "navigate.back": { + title: "Go back", + group: "goTo", + keywords: ["back", "previous page", "history"], + }, + "navigate.forward": { + title: "Go forward", + group: "goTo", + keywords: ["forward", "next page", "history"], + }, + "project.runScript": { + title: "Run script…", + group: "project", + kind: "list", + itemsSearchable: true, + keywords: ["run", "script", "action", "dev server", "build", "test"], + }, + "files.browse": { + title: "Browse project files", + group: "project", + keywords: ["files", "file viewer", "browse", "open file", "tree"], + }, + "browser.toggle": { + title: "Toggle browser preview", + group: "panels", + keywords: ["browser", "preview", "web page", "localhost", "panel"], + }, + "theme.change": { + title: "Change theme…", + group: "app", + kind: "list", + itemsSearchable: true, + keywords: ["theme", "appearance", "dark mode", "light mode", "colors", "wallpaper"], + }, + "theme.editColors": { + title: "Edit theme colors…", + group: "app", + keywords: ["edit theme", "theme colors", "customize colors", "accent color", "tweak theme"], + }, + "theme.useDefault": { + title: "Use default theme", + group: "app", + keywords: ["default theme", "reset theme", "system theme", "can't read"], + }, + "inbox.showWrapped": { + title: "Show wrapped threads", + about: "Threads you wrapped up, below the active ones", + group: "thread", + keywords: ["wrapped", "done", "finished", "filed away", "show wrapped"], + }, + + // Shortcut commands the palette has no row for: named for the Keybindings page. + "commandPalette.toggle": { + title: "Toggle command palette", + group: "app", + keywords: ["search", "commands", "palette"], + }, + "thread.jump": { + title: "Jump to thread {n}", + group: "goTo", + numbered: true, + }, + "modelPicker.jump": { + title: "Choose model {n}", + group: "thread", + numbered: true, + }, +} as const satisfies Record; + +export type AppCommandId = keyof typeof APP_COMMANDS; + +type NumberedFamilyCommand = ThreadJumpKeybindingCommand | ModelPickerJumpKeybindingCommand; +type StaticKeybindingCommand = Exclude; +/** The catalog id each static shortcut command is named by. */ +type ShortcutCatalogId = + | Exclude + | "thread.jump" + | "modelPicker.jump"; +type UnnamedShortcutCommand = Exclude; +// A shortcut command without a catalog entry fails here, naming the command. +const everyShortcutIsNamed: [UnnamedShortcutCommand] extends [never] + ? true + : UnnamedShortcutCommand = true; +void everyShortcutIsNamed; + +const NUMBERED_FAMILY = /^(thread\.jump|modelPicker\.jump)\.(\d+)$/; + +/** The catalog entry a shortcut command is named by, with its number for a numbered family. */ +export function appCommandForKeybinding( + command: KeybindingCommand, +): { readonly id: AppCommandId; readonly number: number | null } | null { + const numbered = NUMBERED_FAMILY.exec(command); + if (numbered) { + return { id: numbered[1] as AppCommandId, number: Number(numbered[2]) }; + } + return command in APP_COMMANDS ? { id: command as AppCommandId, number: null } : null; +} + +/** A command's title, with a numbered family's number filled in. */ +export function appCommandTitle(id: AppCommandId, number: number | null = null): string { + const title: string = APP_COMMANDS[id].title; + return number === null ? title : title.replace("{n}", String(number)); +} + +/** Whether a string names a catalog command. */ +export function isAppCommandId(value: string): value is AppCommandId { + return Object.hasOwn(APP_COMMANDS, value); +} From df4ebd111013a58e858ea8183011cb0925b1e851 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:57:05 -0500 Subject: [PATCH 3/4] feat(web): search finds settings and projects, best match first The palette searched threads and commands only, kept its groups in a fixed order, and said "No matching commands, projects, or threads" while the message search was still running. A setting like terminal text size could not be found, and a thread named exactly what you typed sat under every command that mentioned the word. Search now covers threads, commands, settings and projects through one pure module. Each source keeps its own matcher, and every match gets a tier from its own words, so the group holding the best match comes first. Settings results use the same availability rules as Settings search and open their page with the row lit, and Back returns to the chat. The palette says when it is still searching messages, names a computer that failed or stopped early, and offers close matches only when nothing matched. Recent threads follow this device's last visits. --- apps/web/src/commands/paletteSearch.test.ts | 268 ++++++++++++++ apps/web/src/commands/paletteSearch.ts | 295 ++++++++++++++++ .../src/commands/paletteSettingsSurface.ts | 11 + .../ChatView.desktop-window.browser.tsx | 47 ++- .../ChatView.palette-settings.browser.tsx | 101 ++++++ .../components/ChatView.palette.browser.tsx | 216 ++++++++++++ .../src/components/CommandPalette.logic.ts | 25 +- .../src/components/CommandPaletteDialog.tsx | 326 ++++++++++++++++-- .../src/components/CommandPaletteResults.tsx | 44 ++- .../settings/SettingsPanels.browser.tsx | 9 +- .../components/settings/SettingsSearch.tsx | 107 +----- .../settings/SettingsSidebarNav.tsx | 13 +- .../settings/settingsPlaceAvailability.tsx | 87 +++-- .../settings/settingsSearchNavigation.ts | 108 ++++++ apps/web/src/lastVisitedThreadRoute.test.ts | 24 ++ apps/web/src/lastVisitedThreadRoute.ts | 41 +++ apps/web/src/lib/threadSearchReactQuery.ts | 29 +- apps/web/src/routes/_chat.tsx | 11 +- apps/web/src/routes/settings.tsx | 147 ++++---- docs/design/command-palette.md | 32 ++ 20 files changed, 1679 insertions(+), 262 deletions(-) create mode 100644 apps/web/src/commands/paletteSearch.test.ts create mode 100644 apps/web/src/commands/paletteSearch.ts create mode 100644 apps/web/src/commands/paletteSettingsSurface.ts create mode 100644 apps/web/src/components/ChatView.palette-settings.browser.tsx create mode 100644 apps/web/src/components/settings/settingsSearchNavigation.ts diff --git a/apps/web/src/commands/paletteSearch.test.ts b/apps/web/src/commands/paletteSearch.test.ts new file mode 100644 index 000000000..4b6ad57b1 --- /dev/null +++ b/apps/web/src/commands/paletteSearch.test.ts @@ -0,0 +1,268 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + matchTier, + paletteSearch, + paletteSearchStatus, + type PlaceSearchEntry, + type ThreadSearchEntry, + tierQueryWords, +} from "./paletteSearch"; + +const thread = ( + title: string, + options: { branch?: string; messageScore?: number } = {}, +): ThreadSearchEntry => ({ + title, + projectName: "Shop", + branch: options.branch ?? "", + messageScore: options.messageScore ?? null, + value: `thread:${title}`, +}); + +const place = ( + value: string, + title: string, + keywords: ReadonlyArray = [], + extra: { section?: string; usage?: number } = {}, +): PlaceSearchEntry => ({ + fields: { + title, + keywords, + ...(extra.section ? { section: extra.section } : {}), + }, + order: 0, + ...(extra.usage !== undefined ? { usage: extra.usage } : {}), + value, +}); + +const COMMANDS = [ + place("command:toggle-terminal", "Toggle terminal", ["terminal", "shell"]), + place("command:connect-agent", "Connect an agent", ["mcp", "terminal"], { usage: 40 }), +]; + +function search( + query: string, + sources: { + threads?: ReadonlyArray>; + commands?: ReadonlyArray>; + settings?: ReadonlyArray>; + projects?: ReadonlyArray>; + filter?: "all" | "commands"; + }, +) { + return paletteSearch({ + query, + filter: sources.filter ?? "all", + threads: sources.threads ?? [], + commands: sources.commands ?? COMMANDS, + settings: sources.settings ?? [], + projects: sources.projects ?? [], + }); +} + +/** Each section as "source: value(tier), …". */ +function shape(result: ReturnType): string[] { + return result.sections.map( + (section) => + `${section.source}: ${section.rows.map((row) => `${row.value}(${row.tier})`).join(", ")}`, + ); +} + +describe("matchTier", () => { + it("reads quoted and unquoted queries the same", () => { + const fields = { title: "Bigger font size" }; + expect(matchTier(tierQueryWords('"font size"'), fields)).toBe( + matchTier(tierQueryWords("font size"), fields), + ); + }); + + it("puts a word inside a longer title word at the word that starts with it", () => { + // "term" inside "Longterm" first, but "terminal" starts with it: tier 2. + expect(matchTier(tierQueryWords("term"), { title: "Longterm terminal" })).toBe(2); + }); +}); + +describe("paletteSearch", () => { + it('"terminal" with a thread titled Terminal: the thread, then Toggle terminal', () => { + expect(shape(search("terminal", { threads: [thread("Terminal")] }))).toEqual([ + "threads: thread:Terminal(0)", + "commands: command:toggle-terminal(2), command:connect-agent(4)", + ]); + }); + + it('"term", same data: the thread at tier 1, then commands at tier 2', () => { + expect(shape(search("term", { threads: [thread("Terminal")] }))).toEqual([ + "threads: thread:Terminal(1)", + "commands: command:toggle-terminal(2), command:connect-agent(4)", + ]); + }); + + it('"term" with only "Longterm terminal": a tie at tier 2 goes to Threads', () => { + expect(shape(search("term", { threads: [thread("Longterm terminal")] }))[0]).toBe( + "threads: thread:Longterm terminal(2)", + ); + }); + + it('"term" with the word only in a message: Commands first, the thread at tier 6', () => { + expect(shape(search("term", { threads: [thread("Fix login", { messageScore: 10 })] }))).toEqual( + [ + "commands: command:toggle-terminal(2), command:connect-agent(4)", + "threads: thread:Fix login(6)", + ], + ); + }); + + it("keeps a much-used command found by a keyword below one found by its title", () => { + const commands = search("term", {}).sections[0]!.rows.map((row) => row.value); + expect(commands).toEqual(["command:toggle-terminal", "command:connect-agent"]); + }); + + it('"toggle t": Toggle terminal at tier 1', () => { + expect(shape(search("toggle t", {}))).toEqual(["commands: command:toggle-terminal(1)"]); + }); + + it('"inal ror" finds "Terminal error" at tier 3, below any tier 2', () => { + expect( + shape( + search("inal ror", { + threads: [thread("Terminal error")], + commands: [place("command:x", "Inalert rorschach")], + }), + ), + ).toEqual(["commands: command:x(2)", "threads: thread:Terminal error(3)"]); + }); + + it('"payments" finds a thread by its branch at tier 4', () => { + expect( + shape(search("payments", { threads: [thread("Checkout bug", { branch: "fix/payments" })] })), + ).toEqual(["threads: thread:Checkout bug(4)"]); + }); + + it('"dark terminal" finds a setting by keyword and section at tier 5', () => { + expect( + shape( + search("dark terminal", { + commands: [], + settings: [place("setting:terminal-theme", "Theme", ["dark"], { section: "Terminal" })], + }), + ), + ).toEqual(["settings: setting:terminal-theme(5)"]); + }); + + it('"font size": the thread with those words, then Text size by keyword', () => { + const settings = [place("setting:text-size", "Text size", ["font size"])]; + const threads = [thread("Bigger font size in the composer")]; + expect(shape(search("font size", { commands: [], settings, threads }))).toEqual([ + "threads: thread:Bigger font size in the composer(2)", + "settings: setting:text-size(4)", + ]); + // Quoted, the same tiers. + expect(shape(search('"font size"', { commands: [], settings, threads }))).toEqual( + shape(search("font size", { commands: [], settings, threads })), + ); + }); + + it("never puts a message match above a title match in its section", () => { + const rows = search("deploy", { + commands: [], + threads: [thread("Release notes", { messageScore: 0 }), thread("Deploy staging")], + }).sections[0]!.rows; + expect(rows.map((row) => row.value)).toEqual(["thread:Deploy staging", "thread:Release notes"]); + }); + + it("orders commands of one tier by use on this device", () => { + const rows = search("open", { + commands: [ + place("command:open-usage", "Open usage", [], { usage: 1 }), + place("command:open-fleet", "Open fleet", [], { usage: 9 }), + ], + }).sections[0]!.rows; + expect(rows.map((row) => row.value)).toEqual(["command:open-fleet", "command:open-usage"]); + }); + + it("offers close matches only when nothing matched, and only from three letters", () => { + const commands = [place("command:settings", "Open settings")]; + expect(search("stngs", { commands }).closeMatches).toEqual(["command:settings"]); + expect(search("st", { commands }).closeMatches).toEqual([]); + // Digits aren't letters: "k12" has one. + expect( + search("k12", { commands: [place("command:task", "Run task1v2")] }).closeMatches, + ).toEqual([]); + // "open" matches, so there is nothing to offer instead. + expect(search("open", { commands }).closeMatches).toEqual([]); + }); + + it("searches only commands behind the > filter", () => { + expect(shape(search("term", { filter: "commands", threads: [thread("Terminal")] }))).toEqual([ + "commands: command:toggle-terminal(2), command:connect-agent(4)", + ]); + }); + + it("matches commands by word starts: phone doesn't find microphone", () => { + const commands = [place("command:dictate", "Dictate", ["microphone"])]; + expect(search("phone", { commands }).sections).toEqual([]); + expect(search("micro", { commands }).sections).toHaveLength(1); + }); +}); + +describe("paletteSearchStatus", () => { + const answered = { computerName: "Studio Mac", outcome: "answered" as const }; + + it("keeps searching, and never says No matches, until this text's answer is in", () => { + expect( + paletteSearchStatus({ + searchesMessages: true, + answeredCurrentText: false, + outcomes: [], + rowCount: 0, + }), + ).toEqual({ searching: true, noMatches: false, lines: [] }); + expect( + paletteSearchStatus({ + searchesMessages: true, + answeredCurrentText: true, + outcomes: [answered], + rowCount: 0, + }), + ).toEqual({ searching: false, noMatches: true, lines: [] }); + }); + + it("names each computer that failed or stopped early, and only for this text's answer", () => { + const outcomes = [ + answered, + { computerName: "Laptop", outcome: "failed" as const }, + { computerName: "Build box", outcome: "stoppedEarly" as const }, + ]; + expect( + paletteSearchStatus({ + searchesMessages: true, + answeredCurrentText: true, + outcomes, + rowCount: 3, + }).lines, + ).toEqual([ + "Couldn't search Laptop", + "The search on Build box may be incomplete. Add a word to narrow it.", + ]); + expect( + paletteSearchStatus({ + searchesMessages: true, + answeredCurrentText: false, + outcomes, + rowCount: 3, + }).lines, + ).toEqual([]); + }); + + it("doesn't wait for messages on text too short to search them", () => { + expect( + paletteSearchStatus({ + searchesMessages: false, + answeredCurrentText: false, + outcomes: [], + rowCount: 0, + }), + ).toEqual({ searching: false, noMatches: true, lines: [] }); + }); +}); diff --git a/apps/web/src/commands/paletteSearch.ts b/apps/web/src/commands/paletteSearch.ts new file mode 100644 index 000000000..ffb12a2fe --- /dev/null +++ b/apps/web/src/commands/paletteSearch.ts @@ -0,0 +1,295 @@ +/** + * The command palette's search over four kinds of thing + * (docs/design/command-palette.md, section 5): threads, commands, settings + * and projects. Each source's own matcher decides what matches; `matchTier` + * then puts every match on one scale, so the best row leads whichever kind it + * is. Pure: the palette hands in each source's entries. + */ +import { + matchSearchFields, + parseSearchQuery as parsePlaceQuery, + type SearchFields, + searchWords, +} from "@threadlines/shared/placeSearch"; +import { + parseSearchQuery as parseThreadQuery, + scoreSubsequenceMatch, +} from "@threadlines/shared/searchRanking"; + +import { rankSearchTerms } from "../components/CommandPalette.logic"; + +/** + * How well a row matches, best first: + * 0. the title is the query + * 1. the title starts with the query + * 2. every query word begins a word of the title + * 3. every query word is somewhere in the title + * 4. every query word begins a word of the title or the second fields + * 5. anything else its matcher accepted without a message + * 6. only a message matched + */ +export type MatchTier = 0 | 1 | 2 | 3 | 4 | 5 | 6; + +/** What `matchTier` reads of a row: its own words, never its matcher's flags. */ +export interface TierFields { + readonly title: string; + /** A command's or setting's keywords, a thread's project name and branch. */ + readonly second?: ReadonlyArray; + /** Only a message matched this row (a thread found by the server's search). */ + readonly messageOnly?: boolean; +} + +/** The query's words as `matchTier` reads them: lower case, quotes gone. */ +export function tierQueryWords(query: string): ReadonlyArray { + return searchWords(query.replaceAll('"', " ")); +} + +/** Places a row its matcher accepted on the one scale (see MatchTier). */ +export function matchTier(queryWords: ReadonlyArray, fields: TierFields): MatchTier { + if (fields.messageOnly) return 6; + if (queryWords.length === 0) return 5; + const titleWords = searchWords(fields.title); + const titleText = titleWords.join(" "); + const queryText = queryWords.join(" "); + if (titleText === queryText) return 0; + if (titleText.startsWith(queryText)) return 1; + const begins = (words: ReadonlyArray, word: string) => + words.some((candidate) => candidate.startsWith(word)); + if (queryWords.every((word) => begins(titleWords, word))) return 2; + if (queryWords.every((word) => titleText.includes(word))) return 3; + const secondWords = (fields.second ?? []).flatMap((field) => searchWords(field)); + if (queryWords.every((word) => begins(titleWords, word) || begins(secondWords, word))) { + return 4; + } + return 5; +} + +export type PaletteSource = "threads" | "commands" | "settings" | "projects"; + +/** Ties between sections whose best rows share a tier go in this order. */ +const SOURCE_ORDER: ReadonlyArray = ["threads", "commands", "settings", "projects"]; + +/** A thread, matched with `searchRanking` (substrings and quoted phrases), as before. */ +export interface ThreadSearchEntry { + readonly title: string; + readonly projectName: string; + readonly branch: string; + /** The server's score for a message match (lower is better); null without one. */ + readonly messageScore: number | null; + readonly value: T; +} + +/** A command, a setting or a project, matched by word starts as Settings search does. */ +export interface PlaceSearchEntry { + readonly fields: SearchFields; + /** Breaks ties after tier and score: lower first (catalog or page order). */ + readonly order: number; + /** How often this device used it; commands only. Higher first. */ + readonly usage?: number; + readonly value: T; +} + +export interface PaletteSearchRow { + readonly value: T; + readonly tier: MatchTier; +} + +export interface PaletteSearchSection { + readonly source: PaletteSource; + readonly rows: ReadonlyArray>; +} + +export interface PaletteSearchResult { + readonly sections: ReadonlyArray>; + /** Commands and settings whose titles hold the query's letters in order; only when nothing matched. */ + readonly closeMatches: ReadonlyArray; +} + +/** "commands": the `>` filter. */ +export type PaletteSearchFilter = "all" | "commands"; + +interface Scored { + readonly row: PaletteSearchRow; + /** Higher is better within a source. */ + readonly score: number; + readonly usage: number; + readonly order: number; +} + +function sortSection(rows: Scored[]): ReadonlyArray> { + return rows + .toSorted( + (left, right) => + left.row.tier - right.row.tier || + right.score - left.score || + right.usage - left.usage || + left.order - right.order, + ) + .map((scored) => scored.row); +} + +function searchThreads( + entries: ReadonlyArray>, + text: string, + words: ReadonlyArray, +): Scored[] { + const query = parseThreadQuery(text); + if (query.clauses.length === 0) return []; + const scored: Scored[] = []; + entries.forEach((entry, order) => { + const terms = [entry.title, entry.projectName, entry.branch]; + const clientRank = rankSearchTerms(terms, null, query); + const rank = rankSearchTerms(terms, entry.messageScore, query); + if (rank === Number.NEGATIVE_INFINITY) return; + const tier = matchTier(words, { + title: entry.title, + second: [entry.projectName, entry.branch], + messageOnly: clientRank === Number.NEGATIVE_INFINITY, + }); + // `searchRanking` scores lower-is-better inside the rank, which is already + // turned so higher is better here. + scored.push({ row: { value: entry.value, tier }, score: rank, usage: 0, order }); + }); + return scored; +} + +function searchPlaces(entries: ReadonlyArray>, text: string): Scored[] { + const query = parsePlaceQuery(text); + if (query.words.length === 0) return []; + const words = tierQueryWords(text); + const scored: Scored[] = []; + for (const entry of entries) { + const match = matchSearchFields(query, entry.fields); + if (match === null) continue; + const tier = matchTier(words, { + title: entry.fields.title, + second: entry.fields.keywords ?? [], + }); + scored.push({ + row: { value: entry.value, tier }, + score: match.score, + usage: entry.usage ?? 0, + order: entry.order, + }); + } + return scored; +} + +/** Letters (not digits) the query needs before close matches are offered. */ +const CLOSE_MATCH_MIN_LETTERS = 3; + +function closeMatches( + entries: ReadonlyArray>, + text: string, +): ReadonlyArray { + if ((text.match(/\p{L}/gu) ?? []).length < CLOSE_MATCH_MIN_LETTERS) return []; + const letters = text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ""); + const found: { value: T; score: number; order: number }[] = []; + entries.forEach((entry, order) => { + const title = entry.fields.title.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ""); + const score = scoreSubsequenceMatch(title, letters); + if (score !== null) found.push({ value: entry.value, score, order }); + }); + return found + .toSorted((left, right) => left.score - right.score || left.order - right.order) + .map((entry) => entry.value); +} + +/** + * Searches every source for `query` and orders what it finds: rows in a + * section by tier, then the source's own score, then (commands) use on this + * device; sections by their best row's tier, ties going Threads, Commands, + * Settings, Projects. When nothing matches at all, command and setting titles + * with the query's letters in order come back as close matches. + */ +export function paletteSearch(input: { + readonly query: string; + readonly filter: PaletteSearchFilter; + readonly threads: ReadonlyArray>; + readonly commands: ReadonlyArray>; + readonly settings: ReadonlyArray>; + readonly projects: ReadonlyArray>; +}): PaletteSearchResult { + type Value = TThread | TCommand | TSetting | TProject; + const text = input.query.trim(); + const words = tierQueryWords(text); + const commandsOnly = input.filter === "commands"; + const bySource: Array<{ source: PaletteSource; rows: ReadonlyArray> }> = [ + { + source: "threads", + rows: commandsOnly ? [] : sortSection(searchThreads(input.threads, text, words)), + }, + { source: "commands", rows: sortSection(searchPlaces(input.commands, text)) }, + { + source: "settings", + rows: commandsOnly ? [] : sortSection(searchPlaces(input.settings, text)), + }, + { + source: "projects", + rows: commandsOnly ? [] : sortSection(searchPlaces(input.projects, text)), + }, + ]; + const sections = bySource + .filter((section) => section.rows.length > 0) + .toSorted( + (left, right) => + left.rows[0]!.tier - right.rows[0]!.tier || + SOURCE_ORDER.indexOf(left.source) - SOURCE_ORDER.indexOf(right.source), + ); + return { + sections, + closeMatches: + sections.length > 0 + ? [] + : closeMatches( + commandsOnly ? input.commands : [...input.commands, ...input.settings], + text, + ), + }; +} + +/** How one computer's message search went (see threadSearchReactQuery). */ +export interface MessageSearchOutcome { + readonly computerName: string; + readonly outcome: "answered" | "failed" | "stoppedEarly"; +} + +export interface PaletteSearchStatus { + /** "Searching messages" at the foot of the list. */ + readonly searching: boolean; + /** Only once the search for the text in the field has answered and found nothing. */ + readonly noMatches: boolean; + /** One per computer that couldn't be searched or stopped early. */ + readonly lines: ReadonlyArray; +} + +/** + * What the palette says about its search. Messages are searched once the + * text in the field is long enough; until the answer for that text arrives + * (the wait before asking included) the list says it is still searching and + * never "No matches". An answer to an earlier text doesn't count. + */ +export function paletteSearchStatus(input: { + /** The text in the field can search messages (three letters in a word). */ + readonly searchesMessages: boolean; + /** The answer in hand is for the text now in the field. */ + readonly answeredCurrentText: boolean; + /** Each computer's outcome, for that answer. */ + readonly outcomes: ReadonlyArray; + /** Rows the list shows, close matches included. */ + readonly rowCount: number; +}): PaletteSearchStatus { + const searching = input.searchesMessages && !input.answeredCurrentText; + const outcomes = input.searchesMessages && input.answeredCurrentText ? input.outcomes : []; + return { + searching, + noMatches: !searching && input.rowCount === 0, + lines: outcomes.flatMap((entry) => + entry.outcome === "failed" + ? [`Couldn't search ${entry.computerName}`] + : entry.outcome === "stoppedEarly" + ? [`The search on ${entry.computerName} may be incomplete. Add a word to narrow it.`] + : [], + ), + }; +} diff --git a/apps/web/src/commands/paletteSettingsSurface.ts b/apps/web/src/commands/paletteSettingsSurface.ts new file mode 100644 index 000000000..de3be7b76 --- /dev/null +++ b/apps/web/src/commands/paletteSettingsSurface.ts @@ -0,0 +1,11 @@ +/** + * How the palette's Settings source sees Settings: as the hosted phone app + * shows it, or in full. The same answer the settings menu gives + * (SettingsSidebarNav), kept in one place the palette and its tests share. + */ +import type { SettingsSurface } from "../components/settings/settingsPlaceAvailability"; +import { isHostedStaticApp } from "../hostedPairing"; + +export function paletteSettingsSurface(): SettingsSurface { + return isHostedStaticApp() ? "phone" : "full"; +} diff --git a/apps/web/src/components/ChatView.desktop-window.browser.tsx b/apps/web/src/components/ChatView.desktop-window.browser.tsx index 5388c067a..dd85cd840 100644 --- a/apps/web/src/components/ChatView.desktop-window.browser.tsx +++ b/apps/web/src/components/ChatView.desktop-window.browser.tsx @@ -1,6 +1,6 @@ import { MessageId } from "@threadlines/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; -import { cdp } from "vite-plus/test/browser"; +import { cdp, page } from "vite-plus/test/browser"; // Types `cdp()` as Playwright's session. import type {} from "vite-plus/test/browser-playwright"; @@ -9,8 +9,11 @@ import { DEFAULT_VIEWPORT, mountChatView, registerChatViewSuiteHooks, + setPrimarySessionRole, waitForElement, + waitForServerConfigToApply, } from "./ChatView.browser-harness"; +import { useCommandPaletteStore } from "../commandPaletteStore"; // The desktop app: `isElectron` is read when modules load, so this whole file // runs as the app's own window would (the other ChatView suites are a browser). @@ -192,4 +195,46 @@ describe("ChatView (full app): the desktop app's window", () => { await mounted.cleanup(); } }); + + it("offers the one-time link in the palette when other devices can reach this computer", async () => { + // The palette's Settings source asks what exists as Settings does: here + // the desktop app's owner, with the computer open to its network. + setPrimarySessionRole("owner"); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-settings-desktop" as MessageId, + targetText: "palette settings desktop", + }), + }); + window.desktopBridge = { + getServerExposureState: vi.fn().mockResolvedValue({ + mode: "network-accessible", + endpointUrl: "http://192.168.1.44:3773", + advertisedHost: "192.168.1.44", + tailscaleServeEnabled: false, + tailscaleServePort: 443, + }), + getAdvertisedEndpoints: vi.fn().mockResolvedValue([]), + } as unknown as NonNullable; + + try { + await waitForServerConfigToApply(); + useCommandPaletteStore.getState().setOpen(true); + await page + .getByPlaceholder("Search commands, projects, and threads...") + .fill("one-time link"); + await expect + .element( + page + .getByTestId("command-palette") + .getByText("One-time link for this network", { exact: true }), + ) + .toBeInTheDocument(); + } finally { + setPrimarySessionRole(null); + Reflect.deleteProperty(window, "desktopBridge"); + await mounted.cleanup(); + } + }); }); diff --git a/apps/web/src/components/ChatView.palette-settings.browser.tsx b/apps/web/src/components/ChatView.palette-settings.browser.tsx new file mode 100644 index 000000000..050e618d7 --- /dev/null +++ b/apps/web/src/components/ChatView.palette-settings.browser.tsx @@ -0,0 +1,101 @@ +import { MessageId } from "@threadlines/contracts"; +import { page } from "vite-plus/test/browser"; + +import { useCommandPaletteStore } from "../commandPaletteStore"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + createSnapshotForTargetUser, + DEFAULT_VIEWPORT, + mountChatView, + registerChatViewSuiteHooks, + waitForServerConfigToApply, +} from "./ChatView.browser-harness"; + +// The palette's Settings source asks what exists exactly as Settings does. +// A browser here; the hosted phone app's Settings for one case, through the +// palette's own answer to "which Settings is this" (the app itself stays a +// browser, since hosted mode changes how it connects). The desktop app's case +// is in ChatView.desktop-window.browser.tsx, which runs as the desktop app. +const setup = vi.hoisted(() => ({ hosted: false })); +vi.mock("../commands/paletteSettingsSurface", () => ({ + paletteSettingsSurface: () => (setup.hosted ? "phone" : "full"), +})); +vi.mock("../lib/gitStatusState", () => ({ + getGitStatusSnapshot: () => ({ data: null, error: null, cause: null, isPending: false }), + GIT_STATUS_STALE_MESSAGE: "Source control status isn't updating.", + useGitStatus: () => ({ data: null, error: null, cause: null, isPending: false }), + useGitStatuses: () => new Map(), + rebuildGitStatusSubscription: () => undefined, + refreshGitStatus: () => Promise.resolve(null), + refreshLocalGitStatus: () => Promise.resolve(null), + resetGitStatusStateForTests: () => undefined, +})); + +const NARROW_VIEWPORT = { ...DEFAULT_VIEWPORT, width: 390, height: 844 }; + +async function searchPalette(text: string) { + // A narrow screen keeps Search in the sheet: open it as its shortcut does. + useCommandPaletteStore.getState().setOpen(true); + await page.getByPlaceholder("Search commands, projects, and threads...").fill(text); + return page.getByTestId("command-palette"); +} + +describe("ChatView (full app): the palette's Settings source", () => { + registerChatViewSuiteHooks(); + + afterEach(() => { + setup.hosted = false; + }); + + it("offers Keybindings in a narrow browser", async () => { + const mounted = await mountChatView({ + viewport: NARROW_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-settings-narrow" as MessageId, + targetText: "palette settings narrow", + }), + }); + + try { + await waitForServerConfigToApply(); + const palette = await searchPalette("keybindings"); + await expect + .element(palette.getByText("Keybindings", { exact: true }).first()) + .toBeInTheDocument(); + // Not in a browser, which can't take the desktop app's link. + await page + .getByPlaceholder("Search commands, projects, and threads...") + .fill("one-time link"); + await expect + .element(palette.getByText("One-time link for this network", { exact: true })) + .not.toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + + it("doesn't offer Keybindings in the hosted phone app, where Settings has no such page", async () => { + setup.hosted = true; + const mounted = await mountChatView({ + viewport: NARROW_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-settings-phone" as MessageId, + targetText: "palette settings phone", + }), + }); + + try { + await waitForServerConfigToApply(); + const palette = await searchPalette("keybindings"); + await expect + .element(palette.getByText("Keybindings", { exact: true })) + .not.toBeInTheDocument(); + // The phone's own settings page is there instead. + await page.getByPlaceholder("Search commands, projects, and threads...").fill("text size"); + await expect.element(palette.getByText("Text size", { exact: true })).toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); +}); diff --git a/apps/web/src/components/ChatView.palette.browser.tsx b/apps/web/src/components/ChatView.palette.browser.tsx index 99788aa61..f2c6e5276 100644 --- a/apps/web/src/components/ChatView.palette.browser.tsx +++ b/apps/web/src/components/ChatView.palette.browser.tsx @@ -10,6 +10,7 @@ import { type ThreadId, WS_METHODS, } from "@threadlines/contracts"; +import { scopedProjectKey, scopeProjectRef } from "@threadlines/client-runtime"; import { page } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -464,6 +465,221 @@ describe("ChatView (full app): command palette and search", () => { } }); + it("opens a setting from the palette on its row, and Back returns to the chat", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-setting-result" as MessageId, + targetText: "palette setting result", + }), + }); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + const palette = page.getByTestId("command-palette"); + await page.getByPlaceholder("Search commands, projects, and threads...").fill("text size"); + await palette.getByText("Text size", { exact: true }).click(); + + await waitForURL( + mounted.router, + (path) => path === "/settings/general", + "A setting result should open its Settings page.", + ); + await waitForElement( + () => + document.querySelector( + '[data-place="general.terminalTextSize"] > .place-arrival-overlay', + ), + "The setting's row should be lit on arrival.", + ); + + // The palette pushed Settings rather than replacing the chat's entry. + mounted.router.history.back(); + await waitForURL( + mounted.router, + (path) => path === serverThreadPath(THREAD_ID), + "Back should return to the chat the palette was opened over.", + ); + } finally { + await mounted.cleanup(); + } + }); + + it('says "Searching messages" until the search answers, and only then No matches', async () => { + let answerSearch!: (value: { matches: []; truncated: false }) => void; + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-searching" as MessageId, + targetText: "palette searching", + }), + resolveRpc: (body) => { + if (body._tag === ORCHESTRATION_WS_METHODS.searchThreads) { + return new Promise((resolve) => { + answerSearch = resolve; + }); + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + const palette = page.getByTestId("command-palette"); + await page.getByPlaceholder("Search commands, projects, and threads...").fill("zebracorn"); + + await expect.element(palette.getByText("Searching messages…")).toBeInTheDocument(); + await vi.waitFor(() => expect(answerSearch).toBeTypeOf("function"), { + timeout: 8_000, + interval: 16, + }); + // Still waiting on the server: nothing says there are no matches yet. + expect(document.body.textContent).not.toContain("No matches"); + + answerSearch({ matches: [], truncated: false }); + await expect.element(palette.getByText("No matches", { exact: true })).toBeInTheDocument(); + await expect + .element(palette.getByText("Look in archived threads", { exact: true })) + .toBeInTheDocument(); + await expect.element(palette.getByText("Searching messages…")).not.toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + + it("names a computer whose message search failed", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-search-failed" as MessageId, + targetText: "palette search failed", + }), + resolveRpc: (body) => { + if (body._tag === ORCHESTRATION_WS_METHODS.searchThreads) { + return Promise.reject(new Error("The search index is busy.")); + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + await page.getByPlaceholder("Search commands, projects, and threads...").fill("zebracorn"); + await vi.waitFor( + () => { + const status = document.querySelector('[data-testid="command-palette-status"]'); + expect(status?.textContent).toMatch(/Couldn't search \S/); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("says what a project's thread search is waiting on, and names a computer it couldn't search", async () => { + let failSearch!: (error: Error) => void; + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-project-search-status" as MessageId, + targetText: "project search status", + }), + resolveRpc: (body) => { + if (body._tag === ORCHESTRATION_WS_METHODS.searchThreads) { + return new Promise((_, reject) => { + failSearch = reject; + }); + } + return undefined; + }, + }); + + try { + await waitForServerConfigToApply(); + useCommandPaletteStore.getState().openThreadSearch({ + projectName: "Project", + memberProjectKeys: [scopedProjectKey(scopeProjectRef(LOCAL_ENVIRONMENT_ID, PROJECT_ID))], + }); + const palette = page.getByTestId("command-palette"); + await page.getByPlaceholder("Search threads in Project...").fill("zebracorn"); + + await expect.element(palette.getByText("Searching messages…")).toBeInTheDocument(); + await vi.waitFor(() => expect(failSearch).toBeTypeOf("function"), { + timeout: 8_000, + interval: 16, + }); + expect(document.body.textContent).not.toContain("No matches"); + + failSearch(new Error("The search index is busy.")); + await vi.waitFor( + () => { + const status = document.querySelector('[data-testid="command-palette-status"]'); + expect(status?.textContent).toMatch(/Couldn't search \S/); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("opens on the threads last opened here, ahead of ones with newer activity", async () => { + const olderThreadId = "thread-visits-older" as ThreadId; + const newerThreadId = "thread-visits-newer" as ThreadId; + const base = addThreadToSnapshot( + addThreadToSnapshot( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-recent-visits" as MessageId, + targetText: "recent visits", + }), + olderThreadId, + ), + newerThreadId, + ); + const snapshot = { + ...base, + threads: base.threads.map((thread) => + thread.id === olderThreadId + ? { ...thread, title: "Visited plan", updatedAt: "2026-03-01T10:00:00.000Z" } + : thread.id === newerThreadId + ? { ...thread, title: "Busy plan", updatedAt: "2026-03-02T10:00:00.000Z" } + : thread, + ), + }; + const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, snapshot }); + + try { + await waitForServerConfigToApply(); + // Open the older thread, then come back. + await mounted.router.navigate({ to: serverThreadPath(olderThreadId) }); + await waitForURL(mounted.router, (path) => path === serverThreadPath(olderThreadId), ""); + await mounted.router.navigate({ to: serverThreadPath(THREAD_ID) }); + await waitForURL(mounted.router, (path) => path === serverThreadPath(THREAD_ID), ""); + + await openCommandPaletteFromTrigger(); + await vi.waitFor( + () => { + const titles = Array.from( + document.querySelectorAll( + '[data-testid="command-palette"] [data-slot="command-item"]', + ), + ).map((row) => row.textContent ?? ""); + const visited = titles.findIndex((title) => title.includes("Visited plan")); + const busy = titles.findIndex((title) => title.includes("Busy plan")); + expect(visited).toBeGreaterThanOrEqual(0); + expect(visited).toBeLessThan(busy); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("stays open under StrictMode", async () => { // The app mounts under StrictMode, which runs every new effect's cleanup // once right after mount. An unmount reset on the open dialog turned that diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 0f52b7c6a..77e528fd0 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -31,6 +31,8 @@ export interface CommandPaletteItem { readonly titleLeadingContent?: ReactNode; /** Optional content rendered inline after the title text (before the timestamp). */ readonly titleTrailingContent?: ReactNode; + /** Where it lives, on the right of the row ("General › Terminal" for a setting). */ + readonly whereLabel?: string; readonly shortcutCommand?: KeybindingCommand; readonly threadRef?: Pick; readonly threadContentMatch?: ThreadContentSearchMatch & { readonly query: string }; @@ -241,9 +243,24 @@ function rankCommandPaletteItemMatch( // The visible title is always searchable, and outranks the hidden // searchTerms: typing exactly what an item says on screen must find it. // Titles can be arbitrary nodes; only plain-string ones can be ranked. - const terms = [typeof item.title === "string" ? item.title : "", ...item.searchTerms].filter( - (term) => term.length > 0, + return rankSearchTerms( + [typeof item.title === "string" ? item.title : "", ...item.searchTerms], + item.threadContentMatch?.score ?? null, + query, ); +} + +/** + * How well a row's terms (title first) and its message match, if any, fit a + * query with `searchRanking`: higher is better, -Infinity for no match. The + * thread search's matcher, shared by the palette's own search. + */ +export function rankSearchTerms( + rawTerms: ReadonlyArray, + messageScore: number | null, + query: ParsedSearchQuery, +): number { + const terms = rawTerms.filter((term) => term.length > 0); let bestRank = Number.NEGATIVE_INFINITY; for (const [index, field] of terms.entries()) { @@ -261,8 +278,8 @@ function rankCommandPaletteItemMatch( bestRank = Math.max(bestRank, SEARCH_COMBINED_FIELD_RANK_BASE - combinedAnalysis.score); } - if (item.threadContentMatch) { - bestRank = Math.max(bestRank, SEARCH_THREAD_BODY_RANK_BASE - item.threadContentMatch.score); + if (messageScore !== null) { + bestRank = Math.max(bestRank, SEARCH_THREAD_BODY_RANK_BASE - messageScore); } return bestRank; diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index d61a86b8a..d72fccfd4 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -3,6 +3,7 @@ import { parseScopedThreadKey, scopedProjectKey, + scopedThreadKey, scopeProjectRef, scopeThreadRef, } from "@threadlines/client-runtime"; @@ -13,6 +14,7 @@ import { useDebouncedValue } from "@tanstack/react-pacer"; import { useNavigate } from "@tanstack/react-router"; import * as Schema from "effect/Schema"; import { + ArchiveIcon, ArrowDownIcon, ArrowLeftIcon, ArrowUpIcon, @@ -20,6 +22,7 @@ import { FolderPlusIcon, MessageSquareIcon, MessagesSquareIcon, + SettingsIcon, } from "lucide-react"; import { useCallback, @@ -29,6 +32,7 @@ import { useMemo, useRef, useState, + type ComponentType, type KeyboardEvent, } from "react"; import { useShallow } from "zustand/react/shallow"; @@ -38,18 +42,31 @@ import { useOfferedCommands, type OfferedCommand } from "../commands/commandHand import { COMMAND_ICONS } from "../commands/commandIcons"; import { suggestCommands, useCommandUsageStore } from "../commands/commandUsageStore"; import { PaletteCommandSources } from "../commands/PaletteCommandSources"; +import { paletteSettingsSurface } from "../commands/paletteSettingsSurface"; export { PaletteInboxCommandSource } from "../commands/PaletteCommandSources"; +import { + paletteSearch, + paletteSearchStatus, + type PaletteSource, + type PlaceSearchEntry, + type ThreadSearchEntry, +} from "../commands/paletteSearch"; import { runCommand } from "../commands/runCommand"; import { useComposerHandleContext } from "../composerHandleContext"; import { closeRightPanelSearchParams } from "../diffRouteSearch"; import { holdThreadDetailForOpen, prewarmHighlightedThread } from "../environments/runtime/service"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { isFilesystemBrowseQuery } from "../lib/projectPaths"; -import { threadSearchQueryOptions, type ThreadSearchTarget } from "../lib/threadSearchReactQuery"; +import { + canSearchThreadContent, + threadSearchQueryOptions, + type ThreadSearchTarget, +} from "../lib/threadSearchReactQuery"; +import { readRecentThreadVisits } from "../lastVisitedThreadRoute"; import { getLatestThreadForProject } from "../lib/threadSort"; import { cn, newCommandId } from "../lib/utils"; -import { useServerKeybindings } from "../rpc/serverState"; +import { useServerKeybindings, useServerProviders } from "../rpc/serverState"; import { selectProjectsAcrossEnvironments, selectSidebarThreadsAcrossEnvironments, @@ -83,6 +100,14 @@ import { } from "./CommandPalette.logic"; import { CommandPaletteResults } from "./CommandPaletteResults"; import { ProjectFavicon } from "./ProjectFavicon"; +import { SETTINGS_NAV_ITEMS } from "./settings/settingsNavigation"; +import { useSettingsAvailability } from "./settings/settingsPlaceAvailability"; +import { settingsSearchItems } from "./settings/settingsSearchIndex"; +import { + settingsSearchItemTarget, + settingsSearchItemWhere, + useOpenSettingsResult, +} from "./settings/settingsSearchNavigation"; import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators"; import { Command, @@ -105,6 +130,18 @@ const FIRST_SUGGESTIONS: ReadonlyArray = [ "project.add", ]; const isKeybindingCommand = Schema.is(KeybindingCommand); +/** How each source's section is headed. */ +const SECTION_GROUPS: Readonly> = { + threads: { value: "threads-search", label: "Threads" }, + commands: { value: "actions", label: "Commands" }, + settings: { value: "settings-search", label: "Settings" }, + projects: { value: "projects-search", label: "Projects" }, +}; +/** Each Settings page's glyph, which its settings carry in the palette. */ +const SETTINGS_PAGE_ICONS: ReadonlyMap> = new Map< + string, + ComponentType<{ className?: string }> +>(SETTINGS_NAV_ITEMS.map((item) => [item.place, item.icon])); /** * Every thread, as the palette lists them. Kept as the same array while a @@ -333,26 +370,37 @@ export function OpenCommandPaletteDialog() { }), [activeThreadId, navigate, projectByScopedKey, projectTitleById, threads], ); - // Where you'd go: the threads with the latest activity, pinned or not, the - // one on screen left out. + // Where you'd go: the threads last opened on this device, newest first, + // then the latest activity (pinned or not) to fill the rest; the one on + // screen left out, and a thread that no longer exists skipped. const activeThreadEnvironmentId = routeThreadRef?.environmentId; - const recentThreadItems = useMemo( - () => - allThreadItems - .filter( - (item) => - !( - item.threadRef?.id === activeThreadId && - item.threadRef?.environmentId === activeThreadEnvironmentId - ), - ) - .toSorted( - (left, right) => - Date.parse(right.timestampAt ?? "") - Date.parse(left.timestampAt ?? "") || 0, - ) - .slice(0, RECENT_THREAD_LIMIT), - [activeThreadEnvironmentId, activeThreadId, allThreadItems], - ); + const [recentVisitKeys] = useState(readRecentThreadVisits); + const recentThreadItems = useMemo(() => { + const candidates = allThreadItems.filter( + (item) => + !( + item.threadRef?.id === activeThreadId && + item.threadRef?.environmentId === activeThreadEnvironmentId + ), + ); + const byKey = new Map( + candidates.map((item) => [ + scopedThreadKey(scopeThreadRef(item.threadRef!.environmentId, item.threadRef!.id)), + item, + ]), + ); + const visited = recentVisitKeys.flatMap((key) => { + const item = byKey.get(key); + return item ? [item] : []; + }); + const byActivity = candidates + .filter((item) => !visited.includes(item)) + .toSorted( + (left, right) => + Date.parse(right.timestampAt ?? "") - Date.parse(left.timestampAt ?? "") || 0, + ); + return [...visited, ...byActivity].slice(0, RECENT_THREAD_LIMIT); + }, [activeThreadEnvironmentId, activeThreadId, allThreadItems, recentVisitKeys]); const threadContentSearchTargets = useMemo>(() => { const scopedProjectIds = currentView?.threadSearchProjectIdsByEnvironment; if (currentView && !scopedProjectIds) { @@ -430,6 +478,133 @@ export function OpenCommandPaletteDialog() { }); }, [commandRows, commandUsage, offeredCommands]); + const searchText = (isActionsOnly ? deferredQuery.slice(1) : deferredQuery).trim(); + + // The Settings source asks what exists here exactly as Settings does, with + // the palette's opening as the search a fact is read for. + const [paletteSession] = useState(() => useCommandPaletteStore.getState().openGeneration); + const settingsSurface = paletteSettingsSurface(); + const { shown: settingShown } = useSettingsAvailability(settingsSurface, { + searchActive: searchText.length > 0 && !isActionsOnly, + searchSession: paletteSession, + }); + const providers = useServerProviders(); + const openSettingsResult = useOpenSettingsResult({ replace: false }); + const settingEntries = useMemo>>( + () => + settingsSearchItems({ + surface: settingsSurface, + shown: settingShown, + providers, + keybindings, + }) + // Shortcuts are commands here: they are found as themselves. + .filter((item) => item.type !== "shortcut") + .map((item) => { + const PageIcon = SETTINGS_PAGE_ICONS.get(item.page) ?? SettingsIcon; + return { + fields: item.fields, + order: item.kindRank * 100_000 + item.order, + value: { + kind: "action", + value: `setting:${item.key}`, + searchTerms: [], + title: item.fields.title, + icon: , + whereLabel: settingsSearchItemWhere(item), + run: async () => openSettingsResult(settingsSearchItemTarget(item)), + }, + }; + }), + [keybindings, openSettingsResult, providers, settingShown, settingsSurface], + ); + // Commands and the items of lists the main search finds, by their own words. + const commandEntries = useMemo< + ReadonlyArray> + >(() => { + const rowById = new Map(commandRows.map((row) => [row.command!.id, row])); + const itemRowByValue = new Map(searchableListItemRows.map((row) => [row.value, row])); + const entries: PlaceSearchEntry[] = []; + COMMAND_IDS.forEach((id, order) => { + const command = offeredCommands.get(id); + const row = rowById.get(id); + if (!command || !row) return; + const spec = APP_COMMANDS[id]; + const title = [command.title ?? spec.title, command.titleEmphasis] + .filter((part) => part !== undefined) + .join(" "); + entries.push({ + fields: { + title, + keywords: row.searchTerms, + ...(row.description ? { about: row.description } : {}), + }, + order, + usage: commandUsage[id]?.count ?? 0, + value: row, + }); + if (!("itemsSearchable" in spec)) return; + for (const item of command.items ?? []) { + const itemRow = itemRowByValue.get(`command:${id}:${item.id}`); + if (!itemRow) continue; + entries.push({ + fields: { + title: item.title, + keywords: item.keywords ?? [], + ...(item.description ? { about: item.description } : {}), + }, + order, + usage: commandUsage[`${id}:${item.id}`]?.count ?? 0, + value: itemRow, + }); + } + }); + return entries; + }, [commandRows, commandUsage, offeredCommands, searchableListItemRows]); + const threadEntries = useMemo>>( + () => + allThreadSearchItems.map((item) => ({ + title: item.searchTerms[0] ?? "", + projectName: item.searchTerms[1] ?? "", + branch: item.searchTerms[2] ?? "", + messageScore: item.threadContentMatch?.score ?? null, + value: item, + })), + [allThreadSearchItems], + ); + const projectEntries = useMemo>>( + () => + projectSearchItems.map((row, order) => ({ + fields: { title: projects[order]?.name ?? "", about: projects[order]?.cwd ?? "" }, + order, + value: row, + })), + [projectSearchItems, projects], + ); + const searching = currentView === null && searchText.length > 0; + const searchResult = useMemo( + () => + searching + ? paletteSearch({ + query: searchText, + filter: isActionsOnly ? "commands" : "all", + threads: threadEntries, + commands: commandEntries, + settings: settingEntries, + projects: projectEntries, + }) + : null, + [ + commandEntries, + isActionsOnly, + projectEntries, + searchText, + searching, + settingEntries, + threadEntries, + ], + ); + function pushPaletteView(view: CommandPaletteView): void { setViewStack((previousViews) => [...previousViews, view]); setHighlightedItemValue(null); @@ -516,7 +691,6 @@ export function OpenCommandPaletteDialog() { }); }, [activeThreadId, clearOpenIntent, navigate, openIntent, projectTitleById, threads]); - const searchText = (isActionsOnly ? deferredQuery.slice(1) : deferredQuery).trim(); const allCommandsItem: CommandPaletteActionItem = { kind: "action", value: "action:all-commands", @@ -545,22 +719,89 @@ export function OpenCommandPaletteDialog() { })) : deferredQuery.length === 0 ? buildOpeningGroups({ recentThreadItems, suggestedItems: suggestedRows, allCommandsItem }) - : [ - { - value: "actions", - label: "Actions", - items: - searchText.length > 0 ? [...commandRows, ...searchableListItemRows] : commandRows, - }, - ]; - - const filteredGroups = filterCommandPaletteGroups({ - activeGroups, - query: deferredQuery, - isInSubmenu: currentView !== null, - projectSearchItems: projectSearchItems, - threadSearchItems: allThreadSearchItems, - }); + : // ">" alone: every command, in the catalog's order. + [{ value: "actions", label: "Commands", items: commandRows }]; + + const archivedThreadsItem: CommandPaletteActionItem = { + kind: "action", + value: "action:archived-threads", + searchTerms: [], + title: "Look in archived threads", + description: "Archived threads aren't searched here", + icon: , + whereLabel: "Settings › Archived threads", + run: async () => openSettingsResult({ placeId: "settings.archived" }), + }; + // The root's search: four sources in one ordering (commands/paletteSearch). + // List pages and a project's thread search keep filtering their own rows. + const listGroups = searchResult + ? null + : filterCommandPaletteGroups({ + activeGroups, + query: deferredQuery, + isInSubmenu: currentView !== null, + projectSearchItems: projectSearchItems, + threadSearchItems: allThreadSearchItems, + }); + // What the palette says about a search over messages (the root's, or a + // project's thread search): still searching, a computer that couldn't + // answer or stopped early, and No matches only once the answer for the + // text in the field is in. + const searchesThreadsHere = + currentView === null || currentView.threadSearchProjectIdsByEnvironment !== undefined; + const messageSearch = searchesThreadsHere && searchText.length > 0; + const computerNames = new Map( + addProjectEnvironmentOptions.map((option) => [option.environmentId, option.label]), + ); + const searchStatus = messageSearch + ? paletteSearchStatus({ + searchesMessages: + !isActionsOnly && + threadContentSearchTargets.length > 0 && + canSearchThreadContent(searchText), + // The field's own text, not only the deferred one the list was drawn + // for, so a keystroke never inherits the last text's answer. + answeredCurrentText: + query === deferredQuery && + normalizeSearchText(debouncedThreadContentQuery) === normalizeSearchText(deferredQuery) && + threadContentSearchQuery.data !== undefined, + outcomes: (threadContentSearchQuery.data?.outcomes ?? []).map((entry) => ({ + computerName: computerNames.get(entry.environmentId) ?? "a linked computer", + outcome: entry.outcome, + })), + rowCount: searchResult + ? searchResult.sections.reduce((total, section) => total + section.rows.length, 0) + + searchResult.closeMatches.length + : (listGroups ?? []).reduce((total, group) => total + group.items.length, 0), + }) + : null; + const filteredGroups: ReadonlyArray = [ + ...(searchResult + ? [ + ...searchResult.sections.map((section) => ({ + value: SECTION_GROUPS[section.source].value, + label: SECTION_GROUPS[section.source].label, + items: section.rows.map((row) => row.value), + })), + // Only once messages are searched too: a message match would end them. + ...(searchResult.closeMatches.length > 0 && !searchStatus?.searching + ? [ + { + value: "close-matches", + label: "Close matches", + items: searchResult.closeMatches.map((row) => ({ + ...row, + value: `close:${row.value}`, + })), + }, + ] + : []), + ] + : (listGroups ?? [])), + ...(searchStatus?.noMatches + ? [{ value: "no-matches", label: "No matches", items: [archivedThreadsItem] }] + : []), + ]; // A typed path adds one row above the results that opens Add project there. // The search itself carries on underneath, so the field never turns into a @@ -725,6 +966,15 @@ export function OpenCommandPaletteDialog() { groups={displayedGroups} highlightedItemValue={highlightedItemValue} isActionsOnly={isActionsOnly} + {...(searchStatus + ? { + statusLines: [ + ...(searchStatus.searching ? ["Searching messages…"] : []), + ...searchStatus.lines, + ], + emptyStateMessage: "", + } + : {})} keybindings={keybindings} query={deferredQuery} onExecuteItem={executeItem} diff --git a/apps/web/src/components/CommandPaletteResults.tsx b/apps/web/src/components/CommandPaletteResults.tsx index f94f7e95f..180e517da 100644 --- a/apps/web/src/components/CommandPaletteResults.tsx +++ b/apps/web/src/components/CommandPaletteResults.tsx @@ -22,6 +22,8 @@ import { cn } from "~/lib/utils"; interface CommandPaletteResultsProps { emptyStateMessage?: string; + /** Lines under the list about the search itself ("Searching messages", a computer that failed). */ + statusLines?: ReadonlyArray; groups: ReadonlyArray; highlightedItemValue?: string | null; isActionsOnly: boolean; @@ -39,21 +41,46 @@ const COMMAND_PALETTE_LOADING_ROWS = [ ] as const; export function CommandPaletteResults(props: CommandPaletteResultsProps) { + const statusLines = + props.statusLines && props.statusLines.length > 0 ? ( +
+ {props.statusLines.map((line) => ( +

+ {line} +

+ ))} +
+ ) : null; if (props.groups.length === 0) { if (props.isLoading) { return ; } + if (props.emptyStateMessage === "" && statusLines) { + return statusLines; + } return ( -
- {props.emptyStateMessage ?? - (props.isActionsOnly - ? "No matching actions." - : "No matching commands, projects, or threads.")} -
+ <> +
+ {props.emptyStateMessage ?? + (props.isActionsOnly + ? "No matching actions." + : "No matching commands, projects, or threads.")} +
+ {statusLines} + ); } + return ( + <> + + {statusLines} + + ); +} + +function CommandListWithGroups(props: CommandPaletteResultsProps) { return ( {props.groups.map((group) => ( @@ -184,6 +211,11 @@ function CommandPaletteResultRow(props: {
)} {props.item.titleTrailingContent} + {props.item.whereLabel ? ( + + {props.item.whereLabel} + + ) : null} {props.item.timestampAt ? ( diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index d6016700e..16bccfddb 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -126,7 +126,7 @@ import { useSettingsSearchStore } from "./settingsSearchStore"; import { placePage } from "@threadlines/shared/appPlaces"; import { SettingsGroup } from "./settingsLayout"; import { - SettingsPlaceSignalsProvider, + SettingsAvailabilityProvider, type SettingsPlaceSearchId, type SettingsRowPlaceId, useSettingsPlaceShown, @@ -7592,10 +7592,13 @@ describe("Settings search rows", () => { ] as const) { const screen = await renderWithTestRouter( - + - + , ); const onPage = liveRows.filter(({ id }) => placePage(id).id === page); diff --git a/apps/web/src/components/settings/SettingsSearch.tsx b/apps/web/src/components/settings/SettingsSearch.tsx index 240f21881..b88d5e2b9 100644 --- a/apps/web/src/components/settings/SettingsSearch.tsx +++ b/apps/web/src/components/settings/SettingsSearch.tsx @@ -1,14 +1,10 @@ -import { placeById, placeHref, type PlaceId } from "@threadlines/shared/appPlaces"; +import { placeById, type PlaceId } from "@threadlines/shared/appPlaces"; import type { SearchQuery } from "@threadlines/shared/placeSearch"; -import { useNavigate } from "@tanstack/react-router"; import { ChevronRightIcon } from "lucide-react"; import { createContext, type ReactNode, useCallback, useContext, useMemo } from "react"; -import { placeScope, resolvePlaceLink } from "../../appPlaceLinks"; -import { nextPlaceArrivalHash } from "../../placeArrival"; +import { placeScope } from "../../appPlaceLinks"; import { PLACE_COPIES_ATTRIBUTE } from "../../hooks/usePlaceArrival"; -import { usePrimaryEnvironmentId } from "../../environments/primary/context"; -import { isElectron } from "../../env"; import { formatShortcutLabel } from "../../keybindings"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { Button } from "../ui/button"; @@ -38,6 +34,7 @@ import { useSettingsSearch, } from "./settingsSearchIndex"; import { useSettingsSearchStore } from "./settingsSearchStore"; +import { settingsSearchItemTarget, useOpenSettingsResult } from "./settingsSearchNavigation"; /** * Settings search (docs/design/settings-search.md): the field, and the @@ -46,46 +43,6 @@ import { useSettingsSearchStore } from "./settingsSearchStore"; * line opens the page at the setting. */ -/** - * Opens what a result names: its page, at the place, with the place - * highlighted. The search clears first, so the page (not the result's copy - * of the row) is what the arrival finds. - */ -function useOpenFromSearch() { - const navigate = useNavigate(); - const primaryEnvironmentId = usePrimaryEnvironmentId(); - const clear = useSettingsSearchStore((state) => state.clear); - const openPlace = useCallback( - (placeId: PlaceId) => { - const target = resolvePlaceLink({ - href: placeHref(placeId), - threadEnvironmentId: null, - primaryEnvironmentId, - isDesktopApp: isElectron, - }); - if (target?.kind !== "open") return; - clear(); - void navigate({ - href: `${target.href}#${nextPlaceArrivalHash(placeId)}`, - // The hash names a place, not an element id; usePlaceArrival scrolls. - hashScrollIntoView: false, - // Like the menu: moving within Settings replaces, so leaving it goes - // back to where the user was before opening it. - replace: true, - }); - }, - [clear, navigate, primaryEnvironmentId], - ); - const openHref = useCallback( - (href: string) => { - clear(); - void navigate({ href, replace: true }); - }, - [clear, navigate], - ); - return { openPlace, openHref }; -} - /** Each Settings page's glyph, drawn once: a result's line starts with its page's. */ const PAGE_ICONS: Readonly> = Object.fromEntries( SETTINGS_NAV_ITEMS.map((item) => [ @@ -94,15 +51,6 @@ const PAGE_ICONS: Readonly> = Object.fromEntries( ]), ); -/** - * What a result opens: a place (highlighted on arrival), a page with its own - * reveal, or Keybindings filtered to a shortcut. - */ -type ResultTarget = - | { readonly placeId: PlaceId } - | { readonly href: string } - | { readonly shortcut: string }; - /** Opens the result the control sits in (ResultFrame provides it). */ const ResultOpenContext = createContext<() => void>(() => undefined); @@ -123,18 +71,6 @@ function OpenButton({ label }: { readonly label: string }) { ); } -let lastShortcutOpening = 0; - -/** - * Numbers each opening of a shortcut, so the Keybindings page filters again - * for it. Taken from the clock, so a reload never repeats one still in the URL. - */ -function nextShortcutOpening(): number { - lastShortcutOpening = Math.max(Date.now(), lastShortcutOpening + 1); - return lastShortcutOpening; -} - -/** On the phone app, a setting stored on the paired computer says so: the rest are this phone's. */ const pairedComputerNote = (placeId: PlaceId): string | null => placeScope(placeId) === "computer" ? "your paired computer" : null; @@ -149,7 +85,6 @@ function ResultFrame({ place, trail, extraNote = null, - target, children, }: { readonly result: SettingsSearchResult; @@ -158,22 +93,15 @@ function ResultFrame({ readonly place?: SettingsRowPlaceId | undefined; readonly trail: ReadonlyArray | null; readonly extraNote?: string | null; - readonly target: ResultTarget; readonly children: ReactNode; }) { - const { openPlace, openHref } = useOpenFromSearch(); - const targetPlace = "placeId" in target ? target.placeId : null; - const targetHref = "href" in target ? target.href : null; - const targetShortcut = "shortcut" in target ? target.shortcut : null; - const open = useCallback(() => { - if (targetPlace !== null) openPlace(targetPlace); - else if (targetHref !== null) openHref(targetHref); - else if (targetShortcut !== null) { - openHref( - `/settings/keybindings?q=${encodeURIComponent(targetShortcut)}&n=${nextShortcutOpening()}`, - ); - } - }, [openHref, openPlace, targetHref, targetPlace, targetShortcut]); + // Moving within Settings replaces, so leaving it goes back to where the + // user was before opening it; the search clears first, so the page (not + // the result's copy of the row) is what the arrival finds. + const clear = useSettingsSearchStore((state) => state.clear); + const openResult = useOpenSettingsResult({ replace: true, beforeOpen: clear }); + const item = result.item; + const open = useCallback(() => openResult(settingsSearchItemTarget(item)), [item, openResult]); const page = placeById(result.item.page); const where = trail === null ? null : [page.title, ...trail].join(" › "); const note = @@ -227,7 +155,7 @@ function PlaceResult({ const place = placeById(placeId); if (place.kind === "page") { return ( - + } description={place.about} @@ -246,7 +174,6 @@ function PlaceResult({ place={rowPlace} trail={section === null ? [] : [section.title]} extraNote={phone ? pairedComputerNote(placeId) : null} - target={{ placeId }} > {entry?.kind === "live" ? ( @@ -283,14 +210,7 @@ function ResultRow({ snapshot: provider, }); return ( - + @@ -314,7 +234,7 @@ function ResultRow({ case "shortcut": { const label = commandLabel(item.binding.command); return ( - + } description={item.binding.when ? `When ${item.binding.when}` : "Always"} @@ -337,7 +257,6 @@ function ResultRow({ query={query} trail={["Skills"]} extraNote={item.providers.join(", ")} - target={{ placeId: "plugins.skills" }} > } diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index c1d9a55fb..6a37c3309 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -19,8 +19,8 @@ import { } from "./settingsNavigation"; import { type SettingsSectionPath } from "./settingsPaths"; import { - SettingsPlaceSignalsProvider, - SettingsSurfaceContext, + SettingsAvailabilityProvider, + useSettingsStoreSearchHost, type SettingsPagePlaceId, } from "./settingsPlaceAvailability"; import { SettingsSearchField } from "./SettingsSearchField"; @@ -33,12 +33,11 @@ const isHostedStatic = () => /** Settings' list beside the rail: its search, then its sections, for the page on screen. */ export function SettingsDestinationList() { const pathname = useLocation({ select: (location) => location.pathname }); + const searchHost = useSettingsStoreSearchHost(); return ( - - - - - + + + ); } diff --git a/apps/web/src/components/settings/settingsPlaceAvailability.tsx b/apps/web/src/components/settings/settingsPlaceAvailability.tsx index 4e9c49047..a6675c9dc 100644 --- a/apps/web/src/components/settings/settingsPlaceAvailability.tsx +++ b/apps/web/src/components/settings/settingsPlaceAvailability.tsx @@ -63,7 +63,7 @@ export const SettingsSurfaceContext = createContext("full"); export const useSettingsSurface = (): SettingsSurface => useContext(SettingsSurfaceContext); /** What the rules below read: how Settings is shown, and live facts some rows depend on. */ -interface PlaceSignals { +export interface PlaceSignals { readonly phone: boolean; readonly desktopApp: boolean; readonly keepAwakeForTasks: boolean; @@ -160,9 +160,10 @@ const PlaceSignalsContext = createContext(null); * Whether the desktop app's computer is reachable from other devices, read * from the desktop app each time a search starts (Connections can change it * in between). Unknown, so not offered, until this search's read answers. + * `search` numbers the host's searches: Settings counts them, the palette + * uses its opening. */ -function useDesktopReach(enabled: boolean): boolean { - const search = useSettingsSearchStore((state) => state.searchesStarted); +function useDesktopReach(enabled: boolean, search: number): boolean { const [answer, setAnswer] = useState<{ readonly search: number; readonly reachable: boolean; @@ -190,8 +191,14 @@ function useDesktopReach(enabled: boolean): boolean { return enabled && answer?.search === search && answer.reachable; } -function usePlaceSignals(): PlaceSignals { - const phone = useSettingsSurface() === "phone"; +/** What a host of the settings search tells the rules: is a search showing, and which one. */ +export interface SettingsSearchHost { + readonly searchActive: boolean; + /** Changes for each new search, so facts read per search are read again. */ + readonly searchSession: number; +} + +function usePlaceSignals(phone: boolean, host: SettingsSearchHost): PlaceSignals { const background = useDesktopBackgroundOptions(); const dictation = useDictationStatus(usePrimaryEnvironmentId()); const alertsEnabled = usePushAlertsStore((state) => state.enabled); @@ -200,8 +207,10 @@ function usePlaceSignals(): PlaceSignals { (state) => Object.values(state.byId).filter((record) => relayLinkOf(record) !== null).length, ); const { role, authPolicy } = usePrimarySessionAccess(!phone); - const searching = useSettingsSearchStore(selectSettingsSearchActive); - const desktopReach = useDesktopReach(isElectron && !phone && role === "owner" && searching); + const desktopReach = useDesktopReach( + isElectron && !phone && role === "owner" && host.searchActive, + host.searchSession, + ); const primaryCapabilities = usePrimaryEnvironmentDescriptor()?.capabilities; const outsideAgents = primaryCapabilities?.outsideAgents === true; const projectContext = primaryCapabilities?.projectContext === true; @@ -248,13 +257,56 @@ function usePlaceSignals(): PlaceSignals { ); } +/** Whether a place is on screen under these facts. */ +function placeShown(signals: PlaceSignals, id: SettingsPlaceSearchId): boolean { + const place = placeById(id); + if ("appliesWhen" in place && place.appliesWhen === "desktop" && !signals.desktopApp) { + return false; + } + return SHOWN_WHEN[id]?.(signals) ?? true; +} + +/** + * Which settings places exist here, for a host of the settings search: + * Settings (through SettingsAvailabilityProvider) and the command palette, + * which asks with the same inputs so it never offers a row Settings hides. + */ +export function useSettingsAvailability( + surface: SettingsSurface, + host: SettingsSearchHost, +): { readonly signals: PlaceSignals; readonly shown: (id: SettingsPlaceSearchId) => boolean } { + const signals = usePlaceSignals(surface === "phone", host); + const shown = useCallback((id: SettingsPlaceSearchId) => placeShown(signals, id), [signals]); + return { signals, shown }; +} + +/** The settings search as Settings hosts it: its own store says what is being searched. */ +export function useSettingsStoreSearchHost(): SettingsSearchHost { + const searchActive = useSettingsSearchStore(selectSettingsSearchActive); + const searchSession = useSettingsSearchStore((state) => state.searchesStarted); + return useMemo(() => ({ searchActive, searchSession }), [searchActive, searchSession]); +} + /** - * Gathers the live facts once for all of Settings (the layout mounts it), so - * a page full of places doesn't ask the server once per row. + * How Settings is shown and the live facts its places depend on, gathered + * once for everything inside (the settings layout mounts it), so a page full + * of places doesn't ask the server once per row. */ -export function SettingsPlaceSignalsProvider({ children }: { readonly children: ReactNode }) { - const signals = usePlaceSignals(); - return {children}; +export function SettingsAvailabilityProvider({ + surface, + host, + children, +}: { + readonly surface: SettingsSurface; + readonly host: SettingsSearchHost; + readonly children: ReactNode; +}) { + const { signals } = useSettingsAvailability(surface, host); + return ( + + {children} + + ); } /** Answers whether a settings place is on screen here; follows the live facts. */ @@ -266,16 +318,7 @@ export function useSettingsPlaceShown(): (id: SettingsPlaceSearchId) => boolean () => (gathered.phone === phone ? gathered : { ...gathered, phone }), [gathered, phone], ); - return useCallback( - (id) => { - const place = placeById(id); - if ("appliesWhen" in place && place.appliesWhen === "desktop" && !signals.desktopApp) { - return false; - } - return SHOWN_WHEN[id]?.(signals) ?? true; - }, - [signals], - ); + return useCallback((id) => placeShown(signals, id), [signals]); } /** Draws its children only where `place` is on screen (see SHOWN_WHEN). */ diff --git a/apps/web/src/components/settings/settingsSearchNavigation.ts b/apps/web/src/components/settings/settingsSearchNavigation.ts new file mode 100644 index 000000000..5f6059c08 --- /dev/null +++ b/apps/web/src/components/settings/settingsSearchNavigation.ts @@ -0,0 +1,108 @@ +/** + * Where a settings search result goes, for every host of the search: + * Settings' own results and the command palette's Settings rows. A place + * opens its page with the place lit (the place arrival), a provider opens its + * card, a skill the Skills section, a shortcut Keybindings filtered to it. + */ +import { placeById, placeHref, type PlaceId } from "@threadlines/shared/appPlaces"; +import { useNavigate } from "@tanstack/react-router"; +import { useCallback } from "react"; + +import { resolvePlaceLink } from "../../appPlaceLinks"; +import { usePrimaryEnvironmentId } from "../../environments/primary/context"; +import { isElectron } from "../../env"; +import { nextPlaceArrivalHash } from "../../placeArrival"; +import { commandLabel } from "./KeybindingsSettings.logic"; +import type { SettingsSearchItem } from "./settingsSearchIndex"; + +/** + * What a result opens: a place (lit on arrival), a page with its own reveal, + * or Keybindings filtered to a shortcut. + */ +export type SettingsResultTarget = + | { readonly placeId: PlaceId } + | { readonly href: string } + | { readonly shortcut: string }; + +export function settingsSearchItemTarget(item: SettingsSearchItem): SettingsResultTarget { + switch (item.type) { + case "place": + return { placeId: item.place }; + case "provider": + return { href: `/settings/providers?instance=${encodeURIComponent(item.instanceId)}` }; + case "shortcut": + return { shortcut: commandLabel(item.binding.command) }; + case "skill": + return { placeId: "plugins.skills" }; + } +} + +/** Where a result lives, as a line reads it: "General › Terminal". */ +export function settingsSearchItemWhere(item: SettingsSearchItem): string { + const page = placeById(item.page).title; + if (item.type === "place") { + const place = placeById(item.place); + // A page names itself; the right side says it is in Settings. + if (place.kind === "page") return "Settings"; + if (place.kind === "row") { + return `${page} › ${placeById(item.shownIn ?? (place.parent as PlaceId)).title}`; + } + return page; + } + if (item.type === "skill") return `${page} › Skills`; + return page; +} + +let lastShortcutOpening = 0; + +/** + * Numbers each opening of a shortcut, so the Keybindings page filters again + * for it. Taken from the clock, so a reload never repeats one still in the URL. + */ +function nextShortcutOpening(): number { + lastShortcutOpening = Math.max(Date.now(), lastShortcutOpening + 1); + return lastShortcutOpening; +} + +/** + * Opens a result. Settings replaces the entry it is on (moving within + * Settings, so leaving it goes back to before Settings); the palette pushes + * one, so Back returns to the chat it was opened over. `beforeOpen` runs + * first (Settings clears its search, so the page is what the arrival finds). + */ +export function useOpenSettingsResult(options: { + readonly replace: boolean; + readonly beforeOpen?: () => void; +}): (target: SettingsResultTarget) => void { + const navigate = useNavigate(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const { replace, beforeOpen } = options; + return useCallback( + (target) => { + if ("placeId" in target) { + const link = resolvePlaceLink({ + href: placeHref(target.placeId), + threadEnvironmentId: null, + primaryEnvironmentId, + isDesktopApp: isElectron, + }); + if (link?.kind !== "open") return; + beforeOpen?.(); + void navigate({ + href: `${link.href}#${nextPlaceArrivalHash(target.placeId)}`, + // The hash names a place, not an element id; usePlaceArrival scrolls. + hashScrollIntoView: false, + replace, + }); + return; + } + const href = + "href" in target + ? target.href + : `/settings/keybindings?q=${encodeURIComponent(target.shortcut)}&n=${nextShortcutOpening()}`; + beforeOpen?.(); + void navigate({ href, replace }); + }, + [beforeOpen, navigate, primaryEnvironmentId, replace], + ); +} diff --git a/apps/web/src/lastVisitedThreadRoute.test.ts b/apps/web/src/lastVisitedThreadRoute.test.ts index 5e0635848..3e1e623a2 100644 --- a/apps/web/src/lastVisitedThreadRoute.test.ts +++ b/apps/web/src/lastVisitedThreadRoute.test.ts @@ -5,6 +5,10 @@ import { beforeEach, describe, expect, it } from "vite-plus/test"; import type { DraftId } from "./composerDraftStore"; import { removeLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage"; import { + RECENT_THREAD_VISITS_LIMIT, + RECENT_THREAD_VISITS_STORAGE_KEY, + readRecentThreadVisits, + recordRecentThreadVisit, LAST_VISITED_THREAD_ROUTE_STORAGE_KEY, readLastVisitedThreadRoute, recordLastVisitedThreadRoute, @@ -113,3 +117,23 @@ describe("lastVisitedThreadRoute", () => { expect(readLastVisitedThreadRoute(LOCAL)).toBeNull(); }); }); + +describe("recent thread visits", () => { + beforeEach(() => { + removeLocalStorageItem(RECENT_THREAD_VISITS_STORAGE_KEY); + }); + + it("keeps the threads opened newest first, once each, up to the limit", () => { + recordRecentThreadVisit("a"); + recordRecentThreadVisit("b"); + recordRecentThreadVisit("a"); + expect(readRecentThreadVisits()).toEqual(["a", "b"]); + + for (let index = 0; index < RECENT_THREAD_VISITS_LIMIT + 5; index += 1) { + recordRecentThreadVisit(`thread-${index}`); + } + const visits = readRecentThreadVisits(); + expect(visits).toHaveLength(RECENT_THREAD_VISITS_LIMIT); + expect(visits[0]).toBe(`thread-${RECENT_THREAD_VISITS_LIMIT + 4}`); + }); +}); diff --git a/apps/web/src/lastVisitedThreadRoute.ts b/apps/web/src/lastVisitedThreadRoute.ts index 45329d65e..6db7a2d20 100644 --- a/apps/web/src/lastVisitedThreadRoute.ts +++ b/apps/web/src/lastVisitedThreadRoute.ts @@ -141,3 +141,44 @@ export function resolveRestorableThreadRoute(input: { ? { kind: "draft", draftId: input.entry.draftId as DraftId } : null; } + +/** + * The threads opened on this device, newest first, for the command palette's + * Recent group (docs/design/command-palette.md, section 6). Scoped thread + * keys, written when the thread in the route changes; a thread opened again + * moves to the front. Never sent anywhere. + */ +export const RECENT_THREAD_VISITS_STORAGE_KEY = "threadlines:recent-thread-visits:v1"; +export const RECENT_THREAD_VISITS_LIMIT = 20; +const RecentThreadVisitsSchema = Schema.Array(Schema.String); + +export function readRecentThreadVisits(): ReadonlyArray { + try { + return ( + getLocalStorageItemWithLegacyKeys( + RECENT_THREAD_VISITS_STORAGE_KEY, + [], + RecentThreadVisitsSchema, + ) ?? [] + ); + } catch { + return []; + } +} + +export function recordRecentThreadVisit(threadKey: string): void { + const current = readRecentThreadVisits(); + if (current[0] === threadKey) return; + try { + setLocalStorageItem( + RECENT_THREAD_VISITS_STORAGE_KEY, + [threadKey, ...current.filter((key) => key !== threadKey)].slice( + 0, + RECENT_THREAD_VISITS_LIMIT, + ), + RecentThreadVisitsSchema, + ); + } catch { + // Best-effort, like the last visited route: storage failing must not break routing. + } +} diff --git a/apps/web/src/lib/threadSearchReactQuery.ts b/apps/web/src/lib/threadSearchReactQuery.ts index af969d083..2d379c364 100644 --- a/apps/web/src/lib/threadSearchReactQuery.ts +++ b/apps/web/src/lib/threadSearchReactQuery.ts @@ -16,10 +16,23 @@ export interface EnvironmentThreadSearchMatch extends OrchestrationThreadSearchM readonly environmentId: EnvironmentId; } +/** + * How one computer's search went: it answered, it couldn't be asked or + * failed, or it stopped early. The server stops early both when it found more + * than the limit and when its candidate scan filled up, so "stoppedEarly" + * means the list may be incomplete, never that more matches exist. + */ +export type ThreadSearchOutcome = "answered" | "failed" | "stoppedEarly"; + +export interface EnvironmentThreadSearchOutcome { + readonly environmentId: EnvironmentId; + readonly outcome: ThreadSearchOutcome; +} + export interface ThreadSearchAcrossEnvironmentsResult { readonly matches: ReadonlyArray; - readonly truncated: boolean; - readonly failedEnvironmentIds: ReadonlyArray; + /** One per computer searched, in the order asked. */ + readonly outcomes: ReadonlyArray; } const THREAD_SEARCH_RESULT_LIMIT_PER_ENVIRONMENT = 50; @@ -60,8 +73,7 @@ export function threadSearchQueryOptions(input: { ); const matches: EnvironmentThreadSearchMatch[] = []; - const failedEnvironmentIds: EnvironmentId[] = []; - let truncated = false; + const outcomes: EnvironmentThreadSearchOutcome[] = []; searches.forEach((search, index) => { const target = normalizedTargets[index]; @@ -69,11 +81,14 @@ export function threadSearchQueryOptions(input: { return; } if (search.status === "rejected") { - failedEnvironmentIds.push(target.environmentId); + outcomes.push({ environmentId: target.environmentId, outcome: "failed" }); return; } - truncated ||= search.value.result.truncated; + outcomes.push({ + environmentId: target.environmentId, + outcome: search.value.result.truncated ? "stoppedEarly" : "answered", + }); matches.push( ...search.value.result.matches.map((match) => ({ ...match, @@ -82,7 +97,7 @@ export function threadSearchQueryOptions(input: { ); }); - return { matches, truncated, failedEnvironmentIds }; + return { matches, outcomes }; }, enabled: (input.enabled ?? true) && diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx index 5ef6e352e..8a5a0ca59 100644 --- a/apps/web/src/routes/_chat.tsx +++ b/apps/web/src/routes/_chat.tsx @@ -1,4 +1,4 @@ -import { scopeThreadRef } from "@threadlines/client-runtime"; +import { scopedThreadKey, scopeThreadRef } from "@threadlines/client-runtime"; import { Outlet, createFileRoute, redirect, useParams } from "@tanstack/react-router"; import { useEffect } from "react"; @@ -6,7 +6,7 @@ import { isKeyboardOwnedByDialog } from "../commands/shortcutBlock"; import { FirstRunSetupRedirect } from "../components/setup/firstRunGateState"; import { useComposerDraftStore } from "../composerDraftStore"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; -import { recordLastVisitedThreadRoute } from "../lastVisitedThreadRoute"; +import { recordLastVisitedThreadRoute, recordRecentThreadVisit } from "../lastVisitedThreadRoute"; import { markLaunchVisitConsumed } from "../launchVisit"; import { resolveThreadRouteTarget } from "../threadRoutes"; import { useStore } from "../store"; @@ -122,10 +122,9 @@ function LastVisitedThreadRouteRecorder() { // Being on any thread means the launch already landed somewhere; a later // trip to `/` is deliberate and must render the home surface. markLaunchVisitConsumed(); - recordLastVisitedThreadRoute(routeThreadEnvironmentId, { - kind: "server", - threadRef: scopeThreadRef(routeThreadEnvironmentId, routeThreadId), - }); + const threadRef = scopeThreadRef(routeThreadEnvironmentId, routeThreadId); + recordLastVisitedThreadRoute(routeThreadEnvironmentId, { kind: "server", threadRef }); + recordRecentThreadVisit(scopedThreadKey(threadRef)); return; } if (routeDraftId) { diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsx index d4f0c3e93..b1d6d01fc 100644 --- a/apps/web/src/routes/settings.tsx +++ b/apps/web/src/routes/settings.tsx @@ -16,8 +16,8 @@ import { useSettingsSearchActive, } from "../components/settings/SettingsSearchField"; import { - SettingsPlaceSignalsProvider, - SettingsSurfaceContext, + SettingsAvailabilityProvider, + useSettingsStoreSearchHost, } from "../components/settings/settingsPlaceAvailability"; import { useSettingsSearchStore } from "../components/settings/settingsSearchStore"; import { settingsSectionLabelForPath } from "../components/settings/settingsNavigation"; @@ -156,87 +156,86 @@ function SettingsContentLayout() { setListOpen, ]); + const searchHost = useSettingsStoreSearchHost(); return ( - - - - {/* Clear under a theme with art: the page's column is glass (index.css). */} -
- {!isElectron && ( -
-
- {!isSettingsIndex ? ( - - ) : null} - - {mobileHeaderTitle} - Settings + + + {/* Clear under a theme with art: the page's column is glass (index.css). */} +
+ {!isElectron && ( +
+
+ {!isSettingsIndex ? ( + + ) : null} + + {mobileHeaderTitle} + Settings + + {isHostedStatic ? ( + + Phone - {isHostedStatic ? ( - - Phone - + ) : null} +
+ {showRestoreDefaults && !searching ? ( + ) : null} -
- {showRestoreDefaults && !searching ? ( - - ) : null} - -
+
-
- )} +
+
+ )} - - {showRestoreDefaults && !searching ? ( -
- -
- ) : null} -
+ + {showRestoreDefaults && !searching ? ( +
+ +
+ ) : null} +
-
- {searching ? : null} - {/* Kept mounted under the results, so a half-done page (a sign-in, a +
+ {searching ? : null} + {/* Kept mounted under the results, so a half-done page (a sign-in, a typed field) and its scroll are there when the search clears. */} -
- -
+
+
- - - +
+ + ); } diff --git a/docs/design/command-palette.md b/docs/design/command-palette.md index acad17574..bac72d2c8 100644 --- a/docs/design/command-palette.md +++ b/docs/design/command-palette.md @@ -723,6 +723,38 @@ owners register. Where the build differs from sections 1 to 4: Requests (each "Open …" here); the title row's Back and Forward (Go back, Go forward). +## As built: step 3 (Nov 23 2026) + +The search is `apps/web/src/commands/paletteSearch.ts`, pure, with every +expected order from section 5 as a unit test. Where the build differs from +section 5 and the thread-visits part of section 6: + +- **One availability hook, not a mounted provider.** Settings mounts + `SettingsAvailabilityProvider`; the palette calls the same + `useSettingsAvailability(surface, host)` with the same inputs. The palette + needs the answer inside its own body, where a provider would have to wrap + it. The host passes "a search is active" and the palette's open count as + its session. +- **One result opener.** `settingsSearchNavigation.ts` holds where a result + goes and where it lives. Settings opens with `replace: true`; the palette + pushes, so Back returns to the chat. +- **Close matches** come from command and setting titles only, uncapped, and + only once the message search for that text has answered empty. The three + letters don't count digits. +- **The status covers a project's thread search too** (the sidebar's search + of one project): "Searching messages…", the per-computer lines and No + matches work there as at the root. +- **No message search, no wait.** With no computer to ask (no threads yet) or + text too short to search messages, No matches shows at once. +- **The search's group is "Commands"**, as the opening list and `>` call it. +- **Recent threads** are this device's last visits first + (`threadlines:recent-thread-visits:v1`, twenty kept), then latest activity + to fill five, never the thread you're on. +- **The hosted phone app** is told apart through `paletteSettingsSurface()`, + the one seam its test replaces. +- **Startup** went from 904.7 KB to 904.9 KB gzip (118 B). The settings index, + the places catalog and the search code are not in it. + ## Rev 2 changes (Sol's review of rev 1) 1. **Older linked computers.** A new field on a search match must be From 47d45a0fa828fd368c1861f44aa205cdf732e148 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:55:01 -0500 Subject: [PATCH 4/4] feat(web): the palette's grouped look, with filters The palette was a small box inside a box that showed eight two-line rows, faded its secondary text, and had one hidden filter (typing ">"). Add project and the Codex import shared the box with no title to say which was open. Each kind of result now sits in its own quiet filled group, in a wider single surface with one-line rows. Filters for All, Threads, Commands, Settings and Projects sit under the field with a count each, and Tab moves between them. In All a group shows five rows and a "Show all" row. Escape clears the text, then the filter, then closes. The palette draws its own list so the highlight follows the row the user chose when message matches arrive late. Add project and the Codex import take the same look and name their step in a title row. --- apps/server/src/guide/topics.ts | 10 + apps/web/src/commands/paletteFilters.test.ts | 82 +++ apps/web/src/commands/paletteFilters.ts | 91 +++ apps/web/src/commands/paletteSearch.test.ts | 16 +- apps/web/src/commands/paletteSearch.ts | 65 +- .../ChatView.add-project.browser.tsx | 17 +- .../components/ChatView.browser-harness.tsx | 13 +- .../ChatView.desktop-window.browser.tsx | 4 +- .../ChatView.move-thread.browser.tsx | 3 + .../ChatView.palette-settings.browser.tsx | 46 +- .../components/ChatView.palette.browser.tsx | 261 +++++++- .../src/components/CommandPalette.logic.ts | 44 +- .../src/components/CommandPaletteDialog.tsx | 557 +++++++++++++----- .../src/components/CommandPaletteResults.tsx | 432 ++++++++------ .../addProject/OpenAddProjectDialog.tsx | 106 ++-- .../OpenCodexSessionImportDialog.tsx | 66 +-- apps/web/src/components/ui/command.tsx | 82 ++- docs/design/command-palette-mockup.html | 208 +++---- docs/design/command-palette.md | 118 +++- 19 files changed, 1561 insertions(+), 660 deletions(-) create mode 100644 apps/web/src/commands/paletteFilters.test.ts create mode 100644 apps/web/src/commands/paletteFilters.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 606b35fcf..ab4d7cb80 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -400,6 +400,16 @@ The project menu's Project brief and notes, the command palette and the lead cha Show device toolbar, in the browser's options menu (⋮), sets the page's size: Responsive fills the panel, and a Phone, Tablet, Laptop or Desktop size shrinks to fit it. New tabs open at {place:general.browserPageSize}, which the size menu can also set. Words typed in the browser's address bar are searched for, with the search engine set in {place:general.browserSearchEngine}. An address loads as it always did.`, + }, + { + id: "search-and-commands", + title: "Search and commands", + keywords: ["search", "command palette", "cmd k", "commands", "find", "filter", "quick open"], + body: `Search (Cmd+K, Ctrl+K on Windows and Linux, or the Search field at the top of the sidebar) finds threads by title and by what was said in them, every command the app has, settings, and projects, in one list with the best match first. With nothing typed it shows the threads last opened on this device and a few commands you use most. + +The filters under the field (All, Threads, Commands, Settings, Projects) narrow it to one kind; while you type each shows how many it holds. Tab and Shift+Tab move between them, and typing > first switches to Commands. In All each kind shows five rows, then Show all for the rest. Escape clears the text, then the filter, then closes. + +A setting opens its page with the row lit. A typed folder path offers Add project there. Archived threads aren't searched; the empty result links to {place:settings.archived}.`, }, { id: "terminals", diff --git a/apps/web/src/commands/paletteFilters.test.ts b/apps/web/src/commands/paletteFilters.test.ts new file mode 100644 index 000000000..1eadebfa1 --- /dev/null +++ b/apps/web/src/commands/paletteFilters.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + ALL_FILTER_GROUP_CAP, + filterPaletteSearch, + paletteFilterCounts, + stepPaletteFilter, +} from "./paletteFilters"; +import type { PaletteSearchResult } from "./paletteSearch"; + +const rows = (prefix: string, count: number) => + Array.from({ length: count }, (_, index) => ({ value: `${prefix}${index}`, tier: 2 as const })); + +const RESULT: PaletteSearchResult = { + sections: [ + { source: "threads", rows: rows("t", 7) }, + { source: "commands", rows: rows("c", 2) }, + ], + closeMatches: [], +}; + +describe("filterPaletteSearch", () => { + it("shows five rows of each kind in All, and the total for its Show all row", () => { + const { sections } = filterPaletteSearch(RESULT, "all"); + expect(sections.map((section) => [section.source, section.rows.length, section.total])).toEqual( + [ + ["threads", ALL_FILTER_GROUP_CAP, 7], + ["commands", 2, 2], + ], + ); + }); + + it("shows one kind whole under its own filter", () => { + const { sections } = filterPaletteSearch(RESULT, "threads"); + expect(sections).toHaveLength(1); + expect(sections[0]!.rows).toHaveLength(7); + }); + + it("offers close matches only to a view that found nothing itself", () => { + const result: PaletteSearchResult = { + sections: [{ source: "threads", rows: rows("t", 1) }], + closeMatches: [{ source: "commands", value: "open-settings" }], + }; + // All found a thread: nothing to offer instead. + expect(filterPaletteSearch(result, "all").closeMatches).toEqual([]); + // The thread doesn't hide the command's close match from Commands. + expect(filterPaletteSearch(result, "commands").closeMatches).toEqual(["open-settings"]); + expect(paletteFilterCounts(result)).toMatchObject({ all: 1, threads: 1, commands: 1 }); + }); + + it("keeps close matches with their kind's filter", () => { + const closeMatches: PaletteSearchResult["closeMatches"] = [ + { source: "commands", value: "open-settings" }, + { source: "settings", value: "text-size" }, + ]; + const result = { sections: [], closeMatches }; + expect(filterPaletteSearch(result, "all").closeMatches).toEqual(["open-settings", "text-size"]); + expect(filterPaletteSearch(result, "settings").closeMatches).toEqual(["text-size"]); + expect(filterPaletteSearch(result, "threads").closeMatches).toEqual([]); + expect(paletteFilterCounts(result)).toMatchObject({ all: 2, commands: 1, settings: 1 }); + }); +}); + +describe("paletteFilterCounts", () => { + it("counts every row a kind found, not just the five All shows", () => { + expect(paletteFilterCounts(RESULT)).toEqual({ + all: 9, + threads: 7, + commands: 2, + settings: 0, + projects: 0, + }); + }); +}); + +describe("stepPaletteFilter", () => { + it("moves through the filters in order and wraps both ways", () => { + expect(stepPaletteFilter("all", 1)).toBe("threads"); + expect(stepPaletteFilter("projects", 1)).toBe("all"); + expect(stepPaletteFilter("all", -1)).toBe("projects"); + }); +}); diff --git a/apps/web/src/commands/paletteFilters.ts b/apps/web/src/commands/paletteFilters.ts new file mode 100644 index 000000000..f0302b29f --- /dev/null +++ b/apps/web/src/commands/paletteFilters.ts @@ -0,0 +1,91 @@ +/** + * The palette's filters (docs/design/command-palette.md, section 8): All, + * Threads, Commands, Settings, Projects. In All each kind's group shows five + * rows and a row that switches to that kind's filter for the rest; a single + * filter shows its group whole. Pure: the palette hands in its sections. + */ +import type { PaletteSearchResult, PaletteSource } from "./paletteSearch"; + +export type PaletteFilter = "all" | PaletteSource; + +export const PALETTE_FILTERS: ReadonlyArray<{ + readonly id: PaletteFilter; + readonly label: string; +}> = [ + { id: "all", label: "All" }, + { id: "threads", label: "Threads" }, + { id: "commands", label: "Commands" }, + { id: "settings", label: "Settings" }, + { id: "projects", label: "Projects" }, +]; + +/** Rows a kind's group shows in All before its "Show all N" row. */ +export const ALL_FILTER_GROUP_CAP = 5; + +/** The filter Tab (step 1) or Shift+Tab (step -1) moves to, wrapping around. */ +export function stepPaletteFilter(current: PaletteFilter, step: 1 | -1): PaletteFilter { + const index = PALETTE_FILTERS.findIndex((filter) => filter.id === current); + const next = (index + step + PALETTE_FILTERS.length) % PALETTE_FILTERS.length; + return PALETTE_FILTERS[next]!.id; +} + +/** Each filter's row count for a search: what that filter shows, close matches included. */ +export function paletteFilterCounts( + result: PaletteSearchResult, +): Readonly> { + const count = (filter: PaletteFilter) => { + const shown = filterPaletteSearch(result, filter); + return ( + shown.sections.reduce((total, section) => total + section.total, 0) + + shown.closeMatches.length + ); + }; + return { + all: count("all"), + threads: count("threads"), + commands: count("commands"), + settings: count("settings"), + projects: count("projects"), + }; +} + +export interface PaletteFilteredSection { + readonly source: PaletteSource; + /** The rows shown, at most five in All. */ + readonly rows: ReadonlyArray; + /** How many the kind found; more than `rows` means a "Show all" row follows. */ + readonly total: number; +} + +/** + * The search's sections as a filter shows them: in All every kind, five rows + * each; in a single filter only its kind, whole. Close matches show only when + * the filter found nothing itself: under the filter of their kind, or all of + * them in All. So a thread match never hides a command's close match from + * the Commands filter. + */ +export function filterPaletteSearch( + result: PaletteSearchResult, + filter: PaletteFilter, +): { + readonly sections: ReadonlyArray>; + readonly closeMatches: ReadonlyArray; +} { + const sections = result.sections + .filter((section) => filter === "all" || section.source === filter) + .map((section) => { + const rows = section.rows.map((row) => row.value); + return { + source: section.source, + rows: filter === "all" ? rows.slice(0, ALL_FILTER_GROUP_CAP) : rows, + total: rows.length, + }; + }); + const closeMatches = + sections.length > 0 + ? [] + : result.closeMatches + .filter((match) => filter === "all" || match.source === filter) + .map((match) => match.value); + return { sections, closeMatches }; +} diff --git a/apps/web/src/commands/paletteSearch.test.ts b/apps/web/src/commands/paletteSearch.test.ts index 4b6ad57b1..1305b871b 100644 --- a/apps/web/src/commands/paletteSearch.test.ts +++ b/apps/web/src/commands/paletteSearch.test.ts @@ -48,12 +48,10 @@ function search( commands?: ReadonlyArray>; settings?: ReadonlyArray>; projects?: ReadonlyArray>; - filter?: "all" | "commands"; }, ) { return paletteSearch({ query, - filter: sources.filter ?? "all", threads: sources.threads ?? [], commands: sources.commands ?? COMMANDS, settings: sources.settings ?? [], @@ -181,22 +179,16 @@ describe("paletteSearch", () => { expect(rows.map((row) => row.value)).toEqual(["command:open-fleet", "command:open-usage"]); }); - it("offers close matches only when nothing matched, and only from three letters", () => { + it("finds close matches from three letters", () => { const commands = [place("command:settings", "Open settings")]; - expect(search("stngs", { commands }).closeMatches).toEqual(["command:settings"]); + expect(search("stngs", { commands }).closeMatches).toEqual([ + { source: "commands", value: "command:settings" }, + ]); expect(search("st", { commands }).closeMatches).toEqual([]); // Digits aren't letters: "k12" has one. expect( search("k12", { commands: [place("command:task", "Run task1v2")] }).closeMatches, ).toEqual([]); - // "open" matches, so there is nothing to offer instead. - expect(search("open", { commands }).closeMatches).toEqual([]); - }); - - it("searches only commands behind the > filter", () => { - expect(shape(search("term", { filter: "commands", threads: [thread("Terminal")] }))).toEqual([ - "commands: command:toggle-terminal(2), command:connect-agent(4)", - ]); }); it("matches commands by word starts: phone doesn't find microphone", () => { diff --git a/apps/web/src/commands/paletteSearch.ts b/apps/web/src/commands/paletteSearch.ts index ffb12a2fe..1081a2999 100644 --- a/apps/web/src/commands/paletteSearch.ts +++ b/apps/web/src/commands/paletteSearch.ts @@ -99,15 +99,21 @@ export interface PaletteSearchSection { readonly rows: ReadonlyArray>; } +export interface PaletteCloseMatch { + readonly source: "commands" | "settings"; + readonly value: T; +} + export interface PaletteSearchResult { + /** Every source that found something, best first; a filter shows one of them. */ readonly sections: ReadonlyArray>; - /** Commands and settings whose titles hold the query's letters in order; only when nothing matched. */ - readonly closeMatches: ReadonlyArray; + /** + * Commands and settings whose titles hold the query's letters in order. A + * view shows them only when it found nothing itself (paletteFilters.ts). + */ + readonly closeMatches: ReadonlyArray>; } -/** "commands": the `>` filter. */ -export type PaletteSearchFilter = "all" | "commands"; - interface Scored { readonly row: PaletteSearchRow; /** Higher is better within a source. */ @@ -179,32 +185,35 @@ function searchPlaces(entries: ReadonlyArray>, text: stri const CLOSE_MATCH_MIN_LETTERS = 3; function closeMatches( - entries: ReadonlyArray>, + entries: ReadonlyArray & { readonly source: PaletteCloseMatch["source"] }>, text: string, -): ReadonlyArray { +): ReadonlyArray> { if ((text.match(/\p{L}/gu) ?? []).length < CLOSE_MATCH_MIN_LETTERS) return []; const letters = text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ""); - const found: { value: T; score: number; order: number }[] = []; + const found: { match: PaletteCloseMatch; score: number; order: number }[] = []; entries.forEach((entry, order) => { const title = entry.fields.title.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ""); const score = scoreSubsequenceMatch(title, letters); - if (score !== null) found.push({ value: entry.value, score, order }); + if (score !== null) { + found.push({ match: { source: entry.source, value: entry.value }, score, order }); + } }); return found .toSorted((left, right) => left.score - right.score || left.order - right.order) - .map((entry) => entry.value); + .map((entry) => entry.match); } /** * Searches every source for `query` and orders what it finds: rows in a * section by tier, then the source's own score, then (commands) use on this * device; sections by their best row's tier, ties going Threads, Commands, - * Settings, Projects. When nothing matches at all, command and setting titles - * with the query's letters in order come back as close matches. + * Settings, Projects. Command and setting titles with the query's letters in + * order come back as close matches, for a view that finds nothing else. Every + * source is searched whatever the palette's filter, so each filter can show + * its count. */ export function paletteSearch(input: { readonly query: string; - readonly filter: PaletteSearchFilter; readonly threads: ReadonlyArray>; readonly commands: ReadonlyArray>; readonly settings: ReadonlyArray>; @@ -213,21 +222,11 @@ export function paletteSearch(input: { type Value = TThread | TCommand | TSetting | TProject; const text = input.query.trim(); const words = tierQueryWords(text); - const commandsOnly = input.filter === "commands"; const bySource: Array<{ source: PaletteSource; rows: ReadonlyArray> }> = [ - { - source: "threads", - rows: commandsOnly ? [] : sortSection(searchThreads(input.threads, text, words)), - }, + { source: "threads", rows: sortSection(searchThreads(input.threads, text, words)) }, { source: "commands", rows: sortSection(searchPlaces(input.commands, text)) }, - { - source: "settings", - rows: commandsOnly ? [] : sortSection(searchPlaces(input.settings, text)), - }, - { - source: "projects", - rows: commandsOnly ? [] : sortSection(searchPlaces(input.projects, text)), - }, + { source: "settings", rows: sortSection(searchPlaces(input.settings, text)) }, + { source: "projects", rows: sortSection(searchPlaces(input.projects, text)) }, ]; const sections = bySource .filter((section) => section.rows.length > 0) @@ -238,13 +237,13 @@ export function paletteSearch(input: { ); return { sections, - closeMatches: - sections.length > 0 - ? [] - : closeMatches( - commandsOnly ? input.commands : [...input.commands, ...input.settings], - text, - ), + closeMatches: closeMatches( + [ + ...input.commands.map((entry) => ({ ...entry, source: "commands" as const })), + ...input.settings.map((entry) => ({ ...entry, source: "settings" as const })), + ], + text, + ), }; } diff --git a/apps/web/src/components/ChatView.add-project.browser.tsx b/apps/web/src/components/ChatView.add-project.browser.tsx index e3ae9a277..04a8fa21d 100644 --- a/apps/web/src/components/ChatView.add-project.browser.tsx +++ b/apps/web/src/components/ChatView.add-project.browser.tsx @@ -791,7 +791,7 @@ describe("ChatView (full app): add project", () => { await vi.waitFor( () => { const legendEntries = getCommandPaletteLegendEntries(); - expect(legendEntries).toContain("Enter Select"); + expect(legendEntries).toContain("Select"); }, { timeout: 8_000, interval: 16 }, ); @@ -1020,14 +1020,12 @@ describe("ChatView (full app): add project", () => { await waitForServerConfigToApply(); await openCommandPaletteFromTrigger(); const palette = page.getByTestId("command-palette"); - await page - .getByPlaceholder("Search commands, projects, and threads...") - .fill("/repo/project"); + await page.getByPlaceholder("Search threads, commands and settings").fill("/repo/project"); const pathRow = palette.getByText("Add project at /repo/project", { exact: true }); await expect.element(pathRow).toBeInTheDocument(); // The search carries on underneath: the project in that folder is listed. - await expect.element(palette.getByText("Projects", { exact: true })).toBeInTheDocument(); + await expect.element(palette.getByRole("group", { name: "Projects" })).toBeInTheDocument(); expect(wsRequests.some((request) => request._tag === WS_METHODS.filesystemBrowse)).toBe( false, ); @@ -1072,7 +1070,7 @@ describe("ChatView (full app): add project", () => { await waitForServerConfigToApply(); await openCommandPaletteFromTrigger(); const palette = page.getByTestId("command-palette"); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("./fresh"); + await page.getByPlaceholder("Search threads, commands and settings").fill("./fresh"); await palette.getByText("Add project at ./fresh", { exact: true }).click(); const browseInput = await waitForCommandPaletteInput(ADD_PROJECT_SUBMENU_PLACEHOLDER); @@ -1138,8 +1136,11 @@ describe("ChatView (full app): add project", () => { await openCommandPaletteFromTrigger(); await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("docs"); - await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); + await page.getByPlaceholder("Search threads, commands and settings").fill("docs"); + // The project, and its thread (whose row names the project too). + await expect + .element(palette.getByRole("group", { name: "Projects" }).getByText("Docs Portal")) + .toBeInTheDocument(); await expect .element(palette.getByText("Release checklist", { exact: true })) .toBeInTheDocument(); diff --git a/apps/web/src/components/ChatView.browser-harness.tsx b/apps/web/src/components/ChatView.browser-harness.tsx index 322224cba..0f02eb8d0 100644 --- a/apps/web/src/components/ChatView.browser-harness.tsx +++ b/apps/web/src/components/ChatView.browser-harness.tsx @@ -3114,18 +3114,19 @@ export async function openCommandPaletteFromTrigger(): Promise { } /** - * Switches the open palette to every command, through its "All commands" row. - * The palette opens on recent threads and a few suggestions, so a test that - * runs a command by name goes here first, as a user would. + * Switches the open palette to every command, through its "All commands" row + * (the Commands filter). The palette opens on recent threads and a few + * suggestions, so a test that runs a command by name goes here first, as a + * user would. */ export async function showAllPaletteCommands(): Promise { await page.getByTestId("command-palette").getByText("All commands", { exact: true }).click(); await vi.waitFor( () => { - const input = document.querySelector( - '[data-testid="command-palette"] input', + const chosen = document.querySelector( + '[data-testid="command-palette"] [data-slot="command-filter"][aria-pressed="true"]', ); - expect(input?.value).toBe(">"); + expect(chosen?.textContent).toBe("Commands"); }, { timeout: 8_000, interval: 16 }, ); diff --git a/apps/web/src/components/ChatView.desktop-window.browser.tsx b/apps/web/src/components/ChatView.desktop-window.browser.tsx index dd85cd840..7d1b53163 100644 --- a/apps/web/src/components/ChatView.desktop-window.browser.tsx +++ b/apps/web/src/components/ChatView.desktop-window.browser.tsx @@ -221,9 +221,7 @@ describe("ChatView (full app): the desktop app's window", () => { try { await waitForServerConfigToApply(); useCommandPaletteStore.getState().setOpen(true); - await page - .getByPlaceholder("Search commands, projects, and threads...") - .fill("one-time link"); + await page.getByPlaceholder("Search threads, commands and settings").fill("one-time link"); await expect .element( page diff --git a/apps/web/src/components/ChatView.move-thread.browser.tsx b/apps/web/src/components/ChatView.move-thread.browser.tsx index 74467aad7..a07c27d1f 100644 --- a/apps/web/src/components/ChatView.move-thread.browser.tsx +++ b/apps/web/src/components/ChatView.move-thread.browser.tsx @@ -1584,7 +1584,10 @@ describe("ChatView (full app): moving a thread to another computer", () => { .getByText("Move to another computer", { exact: true }) .elements(), ).toHaveLength(0); + // Escape steps back from the Commands filter, then closes. await userEvent.keyboard("{Escape}"); + await userEvent.keyboard("{Escape}"); + await expect.element(page.getByTestId("command-palette")).not.toBeInTheDocument(); await page.getByRole("button", { name: "Cancel the move" }).click(); await vi.waitFor(() => { diff --git a/apps/web/src/components/ChatView.palette-settings.browser.tsx b/apps/web/src/components/ChatView.palette-settings.browser.tsx index 050e618d7..323e4a279 100644 --- a/apps/web/src/components/ChatView.palette-settings.browser.tsx +++ b/apps/web/src/components/ChatView.palette-settings.browser.tsx @@ -37,7 +37,7 @@ const NARROW_VIEWPORT = { ...DEFAULT_VIEWPORT, width: 390, height: 844 }; async function searchPalette(text: string) { // A narrow screen keeps Search in the sheet: open it as its shortcut does. useCommandPaletteStore.getState().setOpen(true); - await page.getByPlaceholder("Search commands, projects, and threads...").fill(text); + await page.getByPlaceholder("Search threads, commands and settings").fill(text); return page.getByTestId("command-palette"); } @@ -64,9 +64,7 @@ describe("ChatView (full app): the palette's Settings source", () => { .element(palette.getByText("Keybindings", { exact: true }).first()) .toBeInTheDocument(); // Not in a browser, which can't take the desktop app's link. - await page - .getByPlaceholder("Search commands, projects, and threads...") - .fill("one-time link"); + await page.getByPlaceholder("Search threads, commands and settings").fill("one-time link"); await expect .element(palette.getByText("One-time link for this network", { exact: true })) .not.toBeInTheDocument(); @@ -75,6 +73,44 @@ describe("ChatView (full app): the palette's Settings source", () => { } }); + it("puts what a row belongs to on a second line on a phone", async () => { + const mounted = await mountChatView({ + viewport: NARROW_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-phone-rows" as MessageId, + targetText: "palette phone rows", + }), + }); + + try { + await waitForServerConfigToApply(); + const palette = await searchPalette("text size"); + await expect.element(palette.getByText("Text size", { exact: true })).toBeInTheDocument(); + await vi.waitFor(() => { + const row = Array.from( + document.querySelectorAll( + '[data-testid="command-palette"] [data-slot="command-item"]', + ), + ).find((candidate) => candidate.dataset.value?.startsWith("setting:") === true); + const title = Array.from(row?.querySelectorAll("span") ?? []).find( + (span) => span.textContent === "Text size", + ); + const where = Array.from(row?.querySelectorAll("span") ?? []).find( + (span) => span.textContent === "General › Terminal", + ); + expect(title).toBeDefined(); + expect(where).toBeDefined(); + const titleBox = title!.getBoundingClientRect(); + const whereBox = where!.getBoundingClientRect(); + // Under the title, from the same left edge. + expect(whereBox.top).toBeGreaterThanOrEqual(titleBox.bottom - 1); + expect(Math.abs(whereBox.left - titleBox.left)).toBeLessThan(2); + }); + } finally { + await mounted.cleanup(); + } + }); + it("doesn't offer Keybindings in the hosted phone app, where Settings has no such page", async () => { setup.hosted = true; const mounted = await mountChatView({ @@ -92,7 +128,7 @@ describe("ChatView (full app): the palette's Settings source", () => { .element(palette.getByText("Keybindings", { exact: true })) .not.toBeInTheDocument(); // The phone's own settings page is there instead. - await page.getByPlaceholder("Search commands, projects, and threads...").fill("text size"); + await page.getByPlaceholder("Search threads, commands and settings").fill("text size"); await expect.element(palette.getByText("Text size", { exact: true })).toBeInTheDocument(); } finally { await mounted.cleanup(); diff --git a/apps/web/src/components/ChatView.palette.browser.tsx b/apps/web/src/components/ChatView.palette.browser.tsx index f2c6e5276..caa4c3034 100644 --- a/apps/web/src/components/ChatView.palette.browser.tsx +++ b/apps/web/src/components/ChatView.palette.browser.tsx @@ -11,7 +11,7 @@ import { WS_METHODS, } from "@threadlines/contracts"; import { scopedProjectKey, scopeProjectRef } from "@threadlines/client-runtime"; -import { page } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; import { useCommandPaletteStore } from "../commandPaletteStore"; @@ -373,9 +373,8 @@ describe("ChatView (full app): command palette and search", () => { await vi.waitFor(() => { const shown = groupsAndRows(); expect(shown.filter((entry) => entry.startsWith("# "))).toEqual([ - "# Recent threads", + "# Recent", "# Suggested", - "# Commands", ]); // Latest activity first, and not the thread on screen. expect(shown.indexOf("Newer plan")).toBeLessThan(shown.indexOf("Older plan")); @@ -478,7 +477,7 @@ describe("ChatView (full app): command palette and search", () => { await waitForServerConfigToApply(); await openCommandPaletteFromTrigger(); const palette = page.getByTestId("command-palette"); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("text size"); + await page.getByPlaceholder("Search threads, commands and settings").fill("text size"); await palette.getByText("Text size", { exact: true }).click(); await waitForURL( @@ -528,7 +527,7 @@ describe("ChatView (full app): command palette and search", () => { await waitForServerConfigToApply(); await openCommandPaletteFromTrigger(); const palette = page.getByTestId("command-palette"); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("zebracorn"); + await page.getByPlaceholder("Search threads, commands and settings").fill("zebracorn"); await expect.element(palette.getByText("Searching messages…")).toBeInTheDocument(); await vi.waitFor(() => expect(answerSearch).toBeTypeOf("function"), { @@ -567,7 +566,7 @@ describe("ChatView (full app): command palette and search", () => { try { await waitForServerConfigToApply(); await openCommandPaletteFromTrigger(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("zebracorn"); + await page.getByPlaceholder("Search threads, commands and settings").fill("zebracorn"); await vi.waitFor( () => { const status = document.querySelector('[data-testid="command-palette-status"]'); @@ -627,6 +626,242 @@ describe("ChatView (full app): command palette and search", () => { } }); + it("filters by kind with counts, moves between filters with Tab, and takes > as the Commands filter", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-filters" as MessageId, + targetText: "palette filters", + }), + }); + const chosenFilter = () => + document.querySelector( + '[data-testid="command-palette"] [data-slot="command-filter"][aria-pressed="true"]', + )?.firstChild?.textContent; + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + const field = page.getByPlaceholder("Search threads, commands and settings"); + await field.fill("settings"); + // Each filter counts what it holds while there is text. + await vi.waitFor(() => { + const counts = Object.fromEntries( + Array.from( + document.querySelectorAll( + '[data-testid="command-palette"] [data-slot="command-filter"]', + ), + ).map((button) => [button.firstChild?.textContent, button.lastChild?.textContent]), + ); + const commands = Number(counts.Commands); + expect(commands).toBeGreaterThan(0); + expect(Number(counts.All)).toBe( + Number(counts.Threads) + commands + Number(counts.Settings) + Number(counts.Projects), + ); + }); + + await userEvent.keyboard("{Tab}"); + expect(chosenFilter()).toBe("Threads"); + await userEvent.keyboard("{Tab}"); + expect(chosenFilter()).toBe("Commands"); + // Only commands now. + await vi.waitFor(() => { + const labels = Array.from( + document.querySelectorAll( + '[data-testid="command-palette"] [data-slot="command-group-label"]', + ), + ).map((label) => label.textContent); + expect(labels).toEqual(["Commands"]); + }); + await userEvent.keyboard("{Shift>}{Tab}{/Shift}"); + expect(chosenFilter()).toBe("Threads"); + + // ">" first switches to Commands and leaves the field empty: one state. + await field.fill(""); + await userEvent.keyboard("{Shift>}{Tab}{/Shift}"); + expect(chosenFilter()).toBe("All"); + await userEvent.keyboard(">"); + expect(chosenFilter()).toBe("Commands"); + await expect.element(field).toHaveValue(""); + } finally { + await mounted.cleanup(); + } + }); + + it("shows five rows of a kind in All, and Show all switches to its filter", async () => { + const planIds = Array.from({ length: 7 }, (_, index) => `thread-plan-${index}` as ThreadId); + const base = planIds.reduce( + (snapshot, threadId) => addThreadToSnapshot(snapshot, threadId), + createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-caps" as MessageId, + targetText: "palette caps", + }), + ); + const snapshot = { + ...base, + threads: base.threads.map((thread) => { + const index = planIds.indexOf(thread.id); + return index < 0 ? thread : { ...thread, title: `Quokka plan ${index + 1}` }; + }), + }; + const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, snapshot }); + const threadRows = () => + Array.from( + document.querySelectorAll( + '[data-testid="command-palette"] [role="group"][aria-labelledby$="threads-search"] [data-slot="command-item"]', + ), + ).map((row) => row.textContent ?? ""); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + await page.getByPlaceholder("Search threads, commands and settings").fill("quokka"); + await vi.waitFor(() => { + const rows = threadRows(); + expect(rows.filter((row) => row.includes("Quokka plan"))).toHaveLength(5); + expect(rows.at(-1)).toBe("Show all 7 threads"); + }); + + await page.getByTestId("command-palette").getByText("Show all 7 threads").click(); + await vi.waitFor(() => { + expect(threadRows().filter((row) => row.includes("Quokka plan"))).toHaveLength(7); + expect(threadRows().some((row) => row.startsWith("Show all"))).toBe(false); + }); + const chosen = document.querySelector( + '[data-testid="command-palette"] [data-slot="command-filter"][aria-pressed="true"]', + ); + expect(chosen?.firstChild?.textContent).toBe("Threads"); + } finally { + await mounted.cleanup(); + } + }); + + it("steps back with Escape: the text, then the filter, then closes", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-escape" as MessageId, + targetText: "palette escape", + }), + }); + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + const field = page.getByPlaceholder("Search threads, commands and settings"); + await userEvent.keyboard(">open"); + await expect.element(field).toHaveValue("open"); + + await userEvent.keyboard("{Escape}"); + await expect.element(field).toHaveValue(""); + const chosen = () => + document.querySelector( + '[data-testid="command-palette"] [data-slot="command-filter"][aria-pressed="true"]', + )?.firstChild?.textContent; + expect(chosen()).toBe("Commands"); + + await userEvent.keyboard("{Escape}"); + expect(chosen()).toBe("All"); + await expect.element(page.getByTestId("command-palette")).toBeInTheDocument(); + + await userEvent.keyboard("{Escape}"); + await expect.element(page.getByTestId("command-palette")).not.toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps the highlight on a row the user chose when a message match arrives above it", async () => { + const messageThreadId = "thread-late-message" as ThreadId; + const base = addThreadToSnapshot( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-palette-late-match" as MessageId, + targetText: "palette late match", + }), + messageThreadId, + ); + const snapshot = { + ...base, + threads: base.threads.map((thread) => + thread.id === THREAD_ID + ? { ...thread, title: "Settings sync between tabs" } + : thread.id === messageThreadId + ? { ...thread, title: "Lunch order" } + : thread, + ), + }; + const answers: Array<() => void> = []; + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot, + resolveRpc: (body) => { + if (body._tag !== ORCHESTRATION_WS_METHODS.searchThreads) return undefined; + return new Promise((resolve) => { + answers.push(() => + resolve({ + matches: [ + { + threadId: messageThreadId, + messageId: "msg-late-settings" as MessageId, + role: "user", + snippet: "…the settings page should remember the last tab…", + score: 0, + }, + ], + truncated: false, + }), + ); + }); + }, + }); + const highlighted = () => + document.querySelector( + '[data-testid="command-palette"] [role="option"][aria-selected="true"]', + )?.dataset.value; + const firstRow = () => + document.querySelector('[data-testid="command-palette"] [role="option"]') + ?.dataset.value; + const snippetShown = () => + document.body.textContent?.includes("should remember the last tab") ?? false; + + try { + await waitForServerConfigToApply(); + await openCommandPaletteFromTrigger(); + await page.getByPlaceholder("Search threads, commands and settings").fill("settings"); + await vi.waitFor(() => expect(answers.length).toBeGreaterThan(0), { + timeout: 8_000, + interval: 16, + }); + // The user moves off the first row (the thread) to the next one, a command. + await vi.waitFor(() => expect(highlighted()).toBe(firstRow())); + await userEvent.keyboard("{ArrowDown}"); + const chosen = highlighted(); + expect(chosen).toBeDefined(); + expect(chosen).not.toBe(firstRow()); + + // The message match lands in Threads, above the chosen row. + answers.at(-1)!(); + await vi.waitFor(() => expect(snippetShown()).toBe(true)); + expect(highlighted()).toBe(chosen); + + // Without a move, the highlight stays on the first row as matches arrive. + const asked = answers.length; + await page.getByPlaceholder("Search threads, commands and settings").fill("setting"); + await vi.waitFor(() => expect(snippetShown()).toBe(false)); + await vi.waitFor(() => expect(answers.length).toBeGreaterThan(asked), { + timeout: 8_000, + interval: 16, + }); + await vi.waitFor(() => expect(highlighted()).toBe(firstRow())); + const first = firstRow(); + answers.at(-1)!(); + await vi.waitFor(() => expect(snippetShown()).toBe(true)); + expect(highlighted()).toBe(first); + } finally { + await mounted.cleanup(); + } + }); + it("opens on the threads last opened here, ahead of ones with newer activity", async () => { const olderThreadId = "thread-visits-older" as ThreadId; const newerThreadId = "thread-visits-newer" as ThreadId; @@ -775,7 +1010,7 @@ describe("ChatView (full app): command palette and search", () => { await openCommandPaletteFromTrigger(); await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("settings"); + await page.getByPlaceholder("Search threads, commands and settings").fill("settings"); await expect.element(palette.getByText("Open settings", { exact: true })).toBeInTheDocument(); await expect .element(palette.getByText("New thread in Project", { exact: true })) @@ -846,7 +1081,7 @@ describe("ChatView (full app): command palette and search", () => { const palette = page.getByTestId("command-palette"); await openCommandPaletteFromTrigger(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill(searchQuery); + await page.getByPlaceholder("Search threads, commands and settings").fill(searchQuery); await vi.waitFor( () => { expect( @@ -1230,7 +1465,7 @@ describe("ChatView (full app): command palette and search", () => { await openCommandPaletteFromTrigger(); await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("clients/docs"); + await page.getByPlaceholder("Search threads, commands and settings").fill("clients/docs"); await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); await expect .element(palette.getByText("/repo/clients/docs-portal", { exact: true })) @@ -1292,7 +1527,7 @@ describe("ChatView (full app): command palette and search", () => { await openCommandPaletteFromTrigger(); await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("clients/docs"); + await page.getByPlaceholder("Search threads, commands and settings").fill("clients/docs"); await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); await expect .element(palette.getByText("/repo/clients/docs-portal", { exact: true })) @@ -1349,7 +1584,7 @@ describe("ChatView (full app): command palette and search", () => { await waitForServerConfigToApply(); const palette = page.getByTestId("command-palette"); await openCommandPaletteFromTrigger(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("clients/docs"); + await page.getByPlaceholder("Search threads, commands and settings").fill("clients/docs"); await palette.getByText("Docs Portal", { exact: true }).click(); const draftPath = await waitForURL( mounted.router, @@ -1362,7 +1597,7 @@ describe("ChatView (full app): command palette and search", () => { await expect.element(palette).not.toBeInTheDocument(); await openCommandPaletteFromTrigger(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("new lead"); + await page.getByPlaceholder("Search threads, commands and settings").fill("new lead"); // Named for the draft's project; the first project's lead hides nothing. await expect.element(palette.getByText("New lead chat", { exact: true })).toBeInTheDocument(); await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); @@ -1406,7 +1641,7 @@ describe("ChatView (full app): command palette and search", () => { await openCommandPaletteFromTrigger(); await expect.element(palette).toBeInTheDocument(); - await page.getByPlaceholder("Search commands, projects, and threads...").fill("docs-archive"); + await page.getByPlaceholder("Search threads, commands and settings").fill("docs-archive"); await expect .element(palette.getByText("Archived Docs Notes", { exact: true })) .not.toBeInTheDocument(); diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 77e528fd0..30bc818e9 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -14,7 +14,7 @@ import { type Project, type SidebarThreadSummary, type Thread } from "../types"; export const RECENT_THREAD_LIMIT = 5; /** The opening list's suggested commands. */ export const SUGGESTED_COMMAND_LIMIT = 4; -export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80"; +export const ITEM_ICON_CLASS = "size-4 text-muted-foreground"; export const ADDON_ICON_CLASS = "size-4"; export interface CommandPaletteItem { @@ -31,8 +31,16 @@ export interface CommandPaletteItem { readonly titleLeadingContent?: ReactNode; /** Optional content rendered inline after the title text (before the timestamp). */ readonly titleTrailingContent?: ReactNode; - /** Where it lives, on the right of the row ("General › Terminal" for a setting). */ + /** + * What it belongs to, on the right of the row: a thread's project, a + * setting's path ("General › Terminal"), a command's group while searching. + * Rows without one show their description there instead. + */ readonly whereLabel?: string; + /** What Enter does, for the footer ("Go to setting"); see `paletteRowVerb`. */ + readonly verb?: string; + /** A row that shows more of a list ("Show all 12 threads"), drawn quieter than a result. */ + readonly more?: boolean; readonly shortcutCommand?: KeybindingCommand; readonly threadRef?: Pick; readonly threadContentMatch?: ThreadContentSearchMatch & { readonly query: string }; @@ -153,6 +161,7 @@ export function buildThreadActionItems; @@ -369,19 +378,26 @@ export function buildOpeningGroups(input: { }): CommandPaletteGroup[] { const groups: CommandPaletteGroup[] = []; if (input.recentThreadItems.length > 0) { - groups.push({ - value: "recent-threads", - label: "Recent threads", - items: input.recentThreadItems, - }); + groups.push({ value: "recent-threads", label: "Recent", items: input.recentThreadItems }); } - if (input.suggestedItems.length > 0) { - groups.push({ value: "suggested", label: "Suggested", items: input.suggestedItems }); - } - groups.push({ value: "all-commands", label: "Commands", items: [input.allCommandsItem] }); + groups.push({ + value: "suggested", + label: "Suggested", + items: [...input.suggestedItems, input.allCommandsItem], + }); return groups; } export function getCommandPaletteInputPlaceholder(isSubmenu: boolean): string { - return isSubmenu ? "Search..." : "Search commands, projects, and threads..."; + return isSubmenu ? "Search..." : "Search threads, commands and settings"; +} + +/** What Enter does with a row, as the footer says it. */ +export function paletteRowVerb(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): string { + if (item.verb) return item.verb; + if (item.more) return "Show"; + if (item.threadRef) return "Open thread"; + if (item.kind === "submenu") return "Show"; + if (item.command) return "Run"; + return "Open"; } diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index d72fccfd4..108fe21ad 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -8,7 +8,12 @@ import { scopeThreadRef, } from "@threadlines/client-runtime"; import { type EnvironmentId, KeybindingCommand, type ProjectId } from "@threadlines/contracts"; -import { APP_COMMANDS, type AppCommandId } from "@threadlines/shared/appCommands"; +import { + APP_COMMAND_GROUP_TITLES, + APP_COMMANDS, + type AppCommandGroup, + type AppCommandId, +} from "@threadlines/shared/appCommands"; import { useQuery } from "@tanstack/react-query"; import { useDebouncedValue } from "@tanstack/react-pacer"; import { useNavigate } from "@tanstack/react-router"; @@ -18,16 +23,19 @@ import { ArrowDownIcon, ArrowLeftIcon, ArrowUpIcon, - CommandIcon, + CornerDownLeftIcon, + DeleteIcon, FolderPlusIcon, MessageSquareIcon, MessagesSquareIcon, + SearchIcon, SettingsIcon, } from "lucide-react"; import { useCallback, useDeferredValue, useEffect, + useId, useLayoutEffect, useMemo, useRef, @@ -45,6 +53,13 @@ import { PaletteCommandSources } from "../commands/PaletteCommandSources"; import { paletteSettingsSurface } from "../commands/paletteSettingsSurface"; export { PaletteInboxCommandSource } from "../commands/PaletteCommandSources"; +import { + filterPaletteSearch, + PALETTE_FILTERS, + type PaletteFilter, + paletteFilterCounts, + stepPaletteFilter, +} from "../commands/paletteFilters"; import { paletteSearch, paletteSearchStatus, @@ -95,10 +110,11 @@ import { highlightedThreadKeyOf, ITEM_ICON_CLASS, normalizeSearchText, + paletteRowVerb, RECENT_THREAD_LIMIT, SUGGESTED_COMMAND_LIMIT, } from "./CommandPalette.logic"; -import { CommandPaletteResults } from "./CommandPaletteResults"; +import { PaletteResultList, paletteRowId } from "./CommandPaletteResults"; import { ProjectFavicon } from "./ProjectFavicon"; import { SETTINGS_NAV_ITEMS } from "./settings/settingsNavigation"; import { useSettingsAvailability } from "./settings/settingsPlaceAvailability"; @@ -109,13 +125,7 @@ import { useOpenSettingsResult, } from "./settings/settingsSearchNavigation"; import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators"; -import { - Command, - CommandDialogPopup, - CommandFooter, - CommandInput, - CommandPanel, -} from "./ui/command"; +import { CommandDialogPopup, CommandFooter, CommandPanel } from "./ui/command"; import { Kbd, KbdGroup } from "./ui/kbd"; import { failureNotice, toastManager } from "./ui/toast"; @@ -130,13 +140,23 @@ const FIRST_SUGGESTIONS: ReadonlyArray = [ "project.add", ]; const isKeybindingCommand = Schema.is(KeybindingCommand); -/** How each source's section is headed. */ -const SECTION_GROUPS: Readonly> = { - threads: { value: "threads-search", label: "Threads" }, - commands: { value: "actions", label: "Commands" }, - settings: { value: "settings-search", label: "Settings" }, - projects: { value: "projects-search", label: "Projects" }, +/** How each source's section is headed, and what its "Show all" row counts. */ +const SECTION_GROUPS: Readonly< + Record +> = { + threads: { value: "threads-search", label: "Threads", noun: "threads" }, + commands: { value: "actions", label: "Commands", noun: "commands" }, + settings: { value: "settings-search", label: "Settings", noun: "settings" }, + projects: { value: "projects-search", label: "Projects", noun: "projects" }, }; +/** The Commands filter with nothing typed lists every command under its catalog group, in this order. */ +const COMMAND_GROUP_ORDER: ReadonlyArray = [ + "thread", + "panels", + "project", + "goTo", + "app", +]; /** Each Settings page's glyph, which its settings carry in the palette. */ const SETTINGS_PAGE_ICONS: ReadonlyMap> = new Map< string, @@ -164,6 +184,28 @@ function usePaletteThreads(): ReadonlyArray { }); } +interface PaletteHighlight { + readonly value: string | null; + /** The user moved to `value` (keys or pointer); until then the first row is highlighted. */ + readonly moved: boolean; +} +const NO_HIGHLIGHT: PaletteHighlight = { value: null, moved: false }; + +/** + * While searching All, a command row says which group it belongs to (a list + * item, which list), unless its owner already says something there. + */ +function withCommandGroup( + item: CommandPaletteActionItem | CommandPaletteSubmenuItem, +): CommandPaletteActionItem | CommandPaletteSubmenuItem { + if (!item.command || item.description || item.whereLabel) return item; + const whereLabel = + item.command.itemId === undefined + ? APP_COMMAND_GROUP_TITLES[APP_COMMANDS[item.command.id].group] + : listHeading(item.command.id); + return { ...item, whereLabel }; +} + function commandIcon(id: AppCommandId, className: string) { const Icon = COMMAND_ICONS[id]; return ; @@ -186,8 +228,9 @@ function commandRow(command: OfferedCommand): CommandPaletteActionItem | Command {titleText} {command.titleEmphasis} ); - const description = - command.disabledReason ?? command.description ?? ("about" in spec ? spec.about : undefined); + // One line: what the owner says now (why it's unavailable, a project's + // name) shows on the right; the catalog's sentence only helps find it. + const description = command.disabledReason ?? command.description; const common = { value: `command:${command.id}`, searchTerms: [...("keywords" in spec ? spec.keywords : []), ...(command.keywords ?? [])], @@ -262,8 +305,11 @@ export function OpenCommandPaletteDialog() { }, [composerHandleRef]); const [query, setQuery] = useState(""); const deferredQuery = useDeferredValue(query); - const isActionsOnly = deferredQuery.startsWith(">"); - const [highlightedItemValue, setHighlightedItemValue] = useState(null); + // The root's filter. Typing ">" first switches to Commands (handleQueryChange). + const [filter, setFilter] = useState("all"); + // The highlight is a row, not a position: once the user moves to a row it + // stays on it while rows arrive above it; until then it is the first row. + const [highlight, setHighlight] = useState(NO_HIGHLIGHT); const { handleNewThread, routeThreadRef } = useHandleNewThread(); const projects = useStore(useShallow(selectProjectsAcrossEnvironments)); const threads = usePaletteThreads(); @@ -330,7 +376,7 @@ export function OpenCommandPaletteDialog() { /> ), runProject: openProjectFromSearch, - }), + }).map((row) => ({ ...row, verb: "Open project" })), [openProjectFromSearch, projects], ); @@ -375,7 +421,8 @@ export function OpenCommandPaletteDialog() { // screen left out, and a thread that no longer exists skipped. const activeThreadEnvironmentId = routeThreadRef?.environmentId; const [recentVisitKeys] = useState(readRecentThreadVisits); - const recentThreadItems = useMemo(() => { + // Every thread in that order: the Threads filter with nothing typed. + const threadsByVisit = useMemo(() => { const candidates = allThreadItems.filter( (item) => !( @@ -399,7 +446,7 @@ export function OpenCommandPaletteDialog() { (left, right) => Date.parse(right.timestampAt ?? "") - Date.parse(left.timestampAt ?? "") || 0, ); - return [...visited, ...byActivity].slice(0, RECENT_THREAD_LIMIT); + return [...visited, ...byActivity]; }, [activeThreadEnvironmentId, activeThreadId, allThreadItems, recentVisitKeys]); const threadContentSearchTargets = useMemo>(() => { const scopedProjectIds = currentView?.threadSearchProjectIdsByEnvironment; @@ -425,8 +472,8 @@ export function OpenCommandPaletteDialog() { const threadContentSearchQuery = useQuery( threadSearchQueryOptions({ query: debouncedThreadContentQuery, + // Every filter counts threads while there is text, so the search runs in each. targets: threadContentSearchTargets, - enabled: !isActionsOnly, }), ); const threadContentMatches = @@ -478,14 +525,17 @@ export function OpenCommandPaletteDialog() { }); }, [commandRows, commandUsage, offeredCommands]); - const searchText = (isActionsOnly ? deferredQuery.slice(1) : deferredQuery).trim(); + const searchText = deferredQuery.trim(); + // A list page or a project's thread search has no filters: it is "all" of its own rows. + const activeFilter: PaletteFilter = currentView === null ? filter : "all"; // The Settings source asks what exists here exactly as Settings does, with // the palette's opening as the search a fact is read for. const [paletteSession] = useState(() => useCommandPaletteStore.getState().openGeneration); const settingsSurface = paletteSettingsSurface(); const { shown: settingShown } = useSettingsAvailability(settingsSurface, { - searchActive: searchText.length > 0 && !isActionsOnly, + // Every filter counts settings while there is text, so it is read in each. + searchActive: currentView === null && (activeFilter === "settings" || searchText.length > 0), searchSession: paletteSession, }); const providers = useServerProviders(); @@ -512,6 +562,7 @@ export function OpenCommandPaletteDialog() { title: item.fields.title, icon: , whereLabel: settingsSearchItemWhere(item), + verb: "Go to setting", run: async () => openSettingsResult(settingsSearchItemTarget(item)), }, }; @@ -533,11 +584,13 @@ export function OpenCommandPaletteDialog() { const title = [command.title ?? spec.title, command.titleEmphasis] .filter((part) => part !== undefined) .join(" "); + const about = + command.disabledReason ?? command.description ?? ("about" in spec ? spec.about : undefined); entries.push({ fields: { title, keywords: row.searchTerms, - ...(row.description ? { about: row.description } : {}), + ...(about ? { about } : {}), }, order, usage: commandUsage[id]?.count ?? 0, @@ -587,27 +640,22 @@ export function OpenCommandPaletteDialog() { searching ? paletteSearch({ query: searchText, - filter: isActionsOnly ? "commands" : "all", threads: threadEntries, commands: commandEntries, settings: settingEntries, projects: projectEntries, }) : null, - [ - commandEntries, - isActionsOnly, - projectEntries, - searchText, - searching, - settingEntries, - threadEntries, - ], + [commandEntries, projectEntries, searchText, searching, settingEntries, threadEntries], + ); + const filterCounts = useMemo( + () => (searchResult ? paletteFilterCounts(searchResult) : null), + [searchResult], ); function pushPaletteView(view: CommandPaletteView): void { setViewStack((previousViews) => [...previousViews, view]); - setHighlightedItemValue(null); + setHighlight(NO_HIGHLIGHT); setQuery(view.initialQuery ?? ""); } @@ -631,18 +679,29 @@ export function OpenCommandPaletteDialog() { function popView(): void { setViewStack((previousViews) => previousViews.slice(0, -1)); - setHighlightedItemValue(null); + setHighlight(NO_HIGHLIGHT); setQuery(""); } function handleQueryChange(nextQuery: string): void { - setHighlightedItemValue(null); + setHighlight(NO_HIGHLIGHT); + // ">" first is the Commands filter, and leaves the field: one state, not two. + if (currentView === null && nextQuery.startsWith(">")) { + setFilter("commands"); + setQuery(nextQuery.slice(1).trimStart()); + return; + } setQuery(nextQuery); if (nextQuery === "" && currentView?.initialQuery) { popView(); } } + function chooseFilter(next: PaletteFilter): void { + setFilter(next); + setHighlight(NO_HIGHLIGHT); + } + // Sidebar "Search all N threads" hands off here: a submenu view scoped to // one logical project's threads, searchable with the usual palette ranking. useLayoutEffect(() => { @@ -696,14 +755,46 @@ export function OpenCommandPaletteDialog() { value: "action:all-commands", searchTerms: [], title: "All commands", - description: "Type > to search only commands", - icon: , + icon: null, + more: true, keepOpen: true, run: async () => { - setHighlightedItemValue(null); - setQuery(">"); + chooseFilter("commands"); + setQuery(""); }, }; + // Each kind's rows with nothing typed, as its filter lists them. + const unfilteredGroups = (kind: PaletteFilter): ReadonlyArray => { + switch (kind) { + case "all": + return buildOpeningGroups({ + recentThreadItems: threadsByVisit.slice(0, RECENT_THREAD_LIMIT), + suggestedItems: suggestedRows, + allCommandsItem, + }); + case "threads": + return [{ value: "recent-threads", label: "Recent", items: threadsByVisit }]; + case "commands": + return COMMAND_GROUP_ORDER.flatMap((group) => { + const items = commandRows.filter( + (row) => row.command && APP_COMMANDS[row.command.id].group === group, + ); + return items.length > 0 + ? [{ value: `commands:${group}`, label: APP_COMMAND_GROUP_TITLES[group], items }] + : []; + }); + case "settings": + return [ + { + value: "settings-search", + label: "Settings", + items: settingEntries.map((entry) => entry.value), + }, + ]; + case "projects": + return [{ value: "projects-search", label: "Projects", items: projectSearchItems }]; + } + }; // A list page draws from the command's items now, not a copy from when it // opened, so a script renamed while its list is open shows its new name. const activeGroups: ReadonlyArray = currentView @@ -717,48 +808,67 @@ export function OpenCommandPaletteDialog() { query: deferredQuery, }), })) - : deferredQuery.length === 0 - ? buildOpeningGroups({ recentThreadItems, suggestedItems: suggestedRows, allCommandsItem }) - : // ">" alone: every command, in the catalog's order. - [{ value: "actions", label: "Commands", items: commandRows }]; + : // A kind with nothing in it says so (emptyStateMessage) instead of a bare heading. + unfilteredGroups(activeFilter).filter((group) => group.items.length > 0); const archivedThreadsItem: CommandPaletteActionItem = { kind: "action", value: "action:archived-threads", searchTerms: [], title: "Look in archived threads", - description: "Archived threads aren't searched here", icon: , whereLabel: "Settings › Archived threads", run: async () => openSettingsResult({ placeId: "settings.archived" }), }; - // The root's search: four sources in one ordering (commands/paletteSearch). - // List pages and a project's thread search keep filtering their own rows. + // A "Show all N" row: the rest of a kind's group, under its own filter. + const showAllItem = (source: PaletteSource, total: number): CommandPaletteActionItem => ({ + kind: "action", + value: `more:${source}`, + searchTerms: [], + title: `Show all ${total} ${SECTION_GROUPS[source].noun}`, + icon: null, + more: true, + keepOpen: true, + run: async () => chooseFilter(source), + }); + // The root's search: four sources in one ordering (commands/paletteSearch), + // shown through the filter. List pages and a project's thread search keep + // filtering their own rows. const listGroups = searchResult ? null - : filterCommandPaletteGroups({ - activeGroups, - query: deferredQuery, - isInSubmenu: currentView !== null, - projectSearchItems: projectSearchItems, - threadSearchItems: allThreadSearchItems, - }); + : searchText.length === 0 && currentView === null + ? activeGroups + : filterCommandPaletteGroups({ + activeGroups, + query: deferredQuery, + isInSubmenu: currentView !== null, + projectSearchItems: projectSearchItems, + threadSearchItems: allThreadSearchItems, + }); + const filteredSearch = useMemo( + () => (searchResult ? filterPaletteSearch(searchResult, activeFilter) : null), + [activeFilter, searchResult], + ); // What the palette says about a search over messages (the root's, or a // project's thread search): still searching, a computer that couldn't // answer or stopped early, and No matches only once the answer for the - // text in the field is in. + // text in the field is in. Only where threads are shown. const searchesThreadsHere = - currentView === null || currentView.threadSearchProjectIdsByEnvironment !== undefined; + currentView === null + ? activeFilter === "all" || activeFilter === "threads" + : currentView.threadSearchProjectIdsByEnvironment !== undefined; const messageSearch = searchesThreadsHere && searchText.length > 0; const computerNames = new Map( addProjectEnvironmentOptions.map((option) => [option.environmentId, option.label]), ); + const shownRowCount = filteredSearch + ? filteredSearch.sections.reduce((total, section) => total + section.total, 0) + + filteredSearch.closeMatches.length + : (listGroups ?? []).reduce((total, group) => total + group.items.length, 0); const searchStatus = messageSearch ? paletteSearchStatus({ searchesMessages: - !isActionsOnly && - threadContentSearchTargets.length > 0 && - canSearchThreadContent(searchText), + threadContentSearchTargets.length > 0 && canSearchThreadContent(searchText), // The field's own text, not only the deferred one the list was drawn // for, so a keystroke never inherits the last text's answer. answeredCurrentText: @@ -769,27 +879,31 @@ export function OpenCommandPaletteDialog() { computerName: computerNames.get(entry.environmentId) ?? "a linked computer", outcome: entry.outcome, })), - rowCount: searchResult - ? searchResult.sections.reduce((total, section) => total + section.rows.length, 0) + - searchResult.closeMatches.length - : (listGroups ?? []).reduce((total, group) => total + group.items.length, 0), + rowCount: shownRowCount, }) : null; const filteredGroups: ReadonlyArray = [ - ...(searchResult + ...(filteredSearch ? [ - ...searchResult.sections.map((section) => ({ + ...filteredSearch.sections.map((section) => ({ value: SECTION_GROUPS[section.source].value, label: SECTION_GROUPS[section.source].label, - items: section.rows.map((row) => row.value), + items: [ + ...(section.source === "commands" && activeFilter === "all" + ? section.rows.map(withCommandGroup) + : section.rows), + ...(section.total > section.rows.length + ? [showAllItem(section.source, section.total)] + : []), + ], })), // Only once messages are searched too: a message match would end them. - ...(searchResult.closeMatches.length > 0 && !searchStatus?.searching + ...(filteredSearch.closeMatches.length > 0 && !searchStatus?.searching ? [ { value: "close-matches", label: "Close matches", - items: searchResult.closeMatches.map((row) => ({ + items: filteredSearch.closeMatches.map((row) => ({ ...row, value: `close:${row.value}`, })), @@ -807,13 +921,16 @@ export function OpenCommandPaletteDialog() { // The search itself carries on underneath, so the field never turns into a // form. const addProjectPathItem: CommandPaletteActionItem | null = - currentView === null && isFilesystemBrowseQuery(deferredQuery, addProjectPathPlatform) + currentView === null && + activeFilter === "all" && + isFilesystemBrowseQuery(deferredQuery, addProjectPathPlatform) ? { kind: "action", value: "action:add-project-at-path", searchTerms: [], title: `Add project at ${deferredQuery.trim()}`, icon: , + verb: "Add project", opensDialog: true, run: async () => { openAddProject({ initialPath: deferredQuery.trim(), returnFocus: focusComposer }); @@ -826,11 +943,66 @@ export function OpenCommandPaletteDialog() { ...filteredGroups, ] : filteredGroups; + const emptyStateMessage = + displayedGroups.length > 0 || searchStatus + ? null + : searchText.length > 0 + ? `No matching ${currentView === null && activeFilter !== "all" ? SECTION_GROUPS[activeFilter].noun : "results"}` + : currentView === null && activeFilter === "projects" + ? "No projects yet" + : currentView === null && activeFilter === "threads" + ? "No other threads yet" + : "Nothing here"; + + // The highlighted row: the one the user moved to while it is still listed, + // else the first. A chosen row that went away hands the highlight back to + // the first row for good. + const selectableRows = displayedGroups.flatMap((group) => + group.items.filter((item) => !item.disabled), + ); + const chosenRowListed = + highlight.moved && selectableRows.some((item) => item.value === highlight.value); + if (highlight.moved && !chosenRowListed) { + setHighlight(NO_HIGHLIGHT); + } + const activeItem = + (chosenRowListed + ? selectableRows.find((item) => item.value === highlight.value) + : selectableRows[0]) ?? null; + const activeValue = activeItem?.value ?? null; + const listId = useId(); + const allRows = displayedGroups.flatMap((group) => group.items); + const activeRowIndex = + activeValue === null ? -1 : allRows.findIndex((item) => item.value === activeValue); + const listRef = useRef(null); + // A different list (another filter, page or text) starts at its top, even + // when its first row has the same place as the last list's. + const shownList = `${activeFilter}\u0000${viewStack.length}\u0000${deferredQuery}`; + const lastShownListRef = useRef(shownList); + useLayoutEffect(() => { + if (lastShownListRef.current === shownList) return; + lastShownListRef.current = shownList; + if (listRef.current) listRef.current.scrollTop = 0; + }, [shownList]); + // Keep the highlighted row in view: a row the user moved to scrolls just + // into view; the first row (nothing chosen yet) brings the list to its top. + useLayoutEffect(() => { + const list = listRef.current; + if (!list) return; + if (!highlight.moved) { + list.scrollTop = 0; + return; + } + if (activeRowIndex < 0) return; + document + .getElementById(paletteRowId(listId, activeRowIndex)) + ?.scrollIntoView({ block: "nearest" }); + }, [activeRowIndex, highlight.moved, listId]); // The thread a highlighted result opens starts loading once the highlight // rests on it, as a pointer resting on a sidebar row does, so choosing it // opens a chat that is ready or already on its way. - const highlightedThreadKey = highlightedThreadKeyOf(displayedGroups, highlightedItemValue); + const highlightedThreadKey = highlightedThreadKeyOf(displayedGroups, activeValue); useEffect(() => { const ref = highlightedThreadKey ? parseScopedThreadKey(highlightedThreadKey) : null; return ref ? prewarmHighlightedThread(ref) : undefined; @@ -840,10 +1012,49 @@ export function OpenCommandPaletteDialog() { const inputPlaceholder = currentView?.inputPlaceholder ?? getCommandPaletteInputPlaceholder(isSubmenu); + function moveHighlight(step: 1 | -1): void { + if (selectableRows.length === 0) return; + const index = selectableRows.findIndex((item) => item.value === activeValue); + const next = selectableRows[Math.min(Math.max(index + step, 0), selectableRows.length - 1)]; + if (next) setHighlight({ value: next.value, moved: true }); + } + function handleKeyDown(event: KeyboardEvent): void { - if (event.key === "Backspace" && query === "" && isSubmenu) { - event.preventDefault(); - popView(); + // An input method's Enter confirms its text (Safari reports it as key 229). + if (event.nativeEvent.isComposing || event.keyCode === 229) return; + switch (event.key) { + case "ArrowDown": + case "ArrowUp": + event.preventDefault(); + moveHighlight(event.key === "ArrowDown" ? 1 : -1); + return; + case "Enter": + event.preventDefault(); + if (activeItem) executeItem(activeItem); + return; + case "Tab": + // Focus stays in the field; at the root Tab moves between the filters. + event.preventDefault(); + if (!isSubmenu) chooseFilter(stepPaletteFilter(filter, event.shiftKey ? -1 : 1)); + return; + case "Escape": + // In stages: the text, then the filter, then (left to the dialog) close. + if (query !== "") { + event.preventDefault(); + event.stopPropagation(); + handleQueryChange(""); + } else if (!isSubmenu && filter !== "all") { + event.preventDefault(); + event.stopPropagation(); + chooseFilter("all"); + } + return; + case "Backspace": + if (query === "" && isSubmenu) { + event.preventDefault(); + popView(); + } + return; } } @@ -916,7 +1127,7 @@ export function OpenCommandPaletteDialog() { return ( { if (handingOverToDialogRef.current) return false; @@ -929,85 +1140,133 @@ export function OpenCommandPaletteDialog() { > {/* Commands that need only stores and navigation register while the palette is open. */} - { - setHighlightedItemValue(typeof value === "string" ? value : null); - }} - onValueChange={handleQueryChange} - value={query} - > - + {isSubmenu ? ( + + ) : ( + ); } diff --git a/apps/web/src/components/CommandPaletteResults.tsx b/apps/web/src/components/CommandPaletteResults.tsx index 180e517da..2aa30c123 100644 --- a/apps/web/src/components/CommandPaletteResults.tsx +++ b/apps/web/src/components/CommandPaletteResults.tsx @@ -1,6 +1,7 @@ import { type ResolvedKeybindingsConfig } from "@threadlines/contracts"; import { analyzeSearchText } from "@threadlines/shared/searchRanking"; import { ChevronRightIcon } from "lucide-react"; +import { type ReactNode } from "react"; import { shortcutLabelForCommand } from "../keybindings"; import { splitSearchTextHighlightSegments } from "../lib/searchTextHighlight"; import { @@ -9,6 +10,10 @@ import { type CommandPaletteSubmenuItem, } from "./CommandPalette.logic"; import { + COMMAND_GROUP_CLASS, + COMMAND_RESULT_LIST_CLASS, + COMMAND_ROW_CLASS, + COMMAND_SECTION_LABEL_CLASS, CommandCollection, CommandGroup, CommandGroupLabel, @@ -20,91 +25,203 @@ import { RelativeTimeLabel } from "./RelativeTimeLabel"; import { Skeleton } from "./ui/skeleton"; import { cn } from "~/lib/utils"; +type ResultItem = CommandPaletteActionItem | CommandPaletteSubmenuItem; + interface CommandPaletteResultsProps { emptyStateMessage?: string; /** Lines under the list about the search itself ("Searching messages", a computer that failed). */ statusLines?: ReadonlyArray; groups: ReadonlyArray; - highlightedItemValue?: string | null; - isActionsOnly: boolean; isLoading?: boolean | undefined; keybindings: ResolvedKeybindingsConfig; query: string; - onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void; + onExecuteItem: (item: ResultItem) => void; } -const COMMAND_PALETTE_LOADING_ROWS = [ - { title: "w-36", detail: "w-56" }, - { title: "w-44", detail: "w-64" }, - { title: "w-32", detail: "w-48" }, - { title: "w-40", detail: "w-52" }, -] as const; +const COMMAND_PALETTE_LOADING_ROWS = ["w-36", "w-44", "w-32", "w-40"] as const; +function StatusLines(props: { lines: ReadonlyArray | undefined }) { + if (!props.lines || props.lines.length === 0) return null; + // Under the last group, outside any group. + return ( +
+ {props.lines.map((line) => ( +

+ {line} +

+ ))} +
+ ); +} + +function EmptyState(props: { message: string }) { + return
{props.message}
; +} + +/** + * The results of Add project and the Codex import: grouped rows that the + * dialog's own list part (`Command`) moves through. The palette draws the same + * rows with `PaletteResultList`. + */ export function CommandPaletteResults(props: CommandPaletteResultsProps) { - const statusLines = - props.statusLines && props.statusLines.length > 0 ? ( -
- {props.statusLines.map((line) => ( -

- {line} -

- ))} -
- ) : null; if (props.groups.length === 0) { if (props.isLoading) { return ; } - if (props.emptyStateMessage === "" && statusLines) { - return statusLines; + if (props.emptyStateMessage === "" && props.statusLines?.length) { + return ; } - return ( <> -
- {props.emptyStateMessage ?? - (props.isActionsOnly - ? "No matching actions." - : "No matching commands, projects, or threads.")} -
- {statusLines} + + ); } return ( <> - - {statusLines} + + {props.groups.map((group) => ( + + + {group.label} + +
+ + {(item: ResultItem) => + item.disabled ? ( +
+ +
+ ) : ( + { + event.preventDefault(); + }} + onClick={() => { + props.onExecuteItem(item); + }} + > + + + ) + } +
+
+
+ ))} +
+ ); } -function CommandListWithGroups(props: CommandPaletteResultsProps) { +/** A palette row's DOM id, for the field's `aria-activedescendant`. */ +export function paletteRowId(listId: string, index: number): string { + return `${listId}-row-${index}`; +} + +/** + * The palette's results. The palette moves the highlight itself (it follows a + * row the user chose when rows arrive above it, which a list part that tracks + * a position can't), so this draws a plain listbox the field points into with + * `aria-activedescendant`. Rows are the same as the dialogs'. + */ +export function PaletteResultList(props: { + listId: string; + groups: ReadonlyArray; + activeValue: string | null; + emptyStateMessage: string | null; + statusLines: ReadonlyArray; + keybindings: ResolvedKeybindingsConfig; + query: string; + onHighlight: (value: string) => void; + onExecuteItem: (item: ResultItem) => void; +}) { + let index = 0; return ( - - {props.groups.map((group) => ( - - {group.label} - - {(item) => - item.disabled ? ( - - ) : ( - - ) - } - - - ))} - + <> + {props.groups.length === 0 && props.emptyStateMessage ? ( + + ) : null} +
+ {props.groups.map((group) => { + const labelId = `${props.listId}-group-${group.value}`; + return ( +
+
+ {group.label} +
+
+ {group.items.map((item) => { + const rowIndex = index++; + const active = !item.disabled && item.value === props.activeValue; + return ( +
{ + if (!item.disabled) props.onExecuteItem(item); + }} + onMouseDown={(event) => { + // The field keeps focus, so typing goes on. + event.preventDefault(); + }} + onMouseMove={() => { + if (!item.disabled && !active) props.onHighlight(item.value); + }} + > + +
+ ); + })} +
+
+ ); + })} +
+ + ); } @@ -114,21 +231,16 @@ function CommandPaletteResultsSkeleton() { role="status" aria-label="Loading command results" data-testid="command-palette-results-skeleton" - className="px-2 py-2" + className={COMMAND_RESULT_LIST_CLASS} > - -
- {COMMAND_PALETTE_LOADING_ROWS.map((row) => ( -
- - - - - - + +
+ {COMMAND_PALETTE_LOADING_ROWS.map((width) => ( +
+ +
))}
@@ -136,103 +248,85 @@ function CommandPaletteResultsSkeleton() { ); } -function DisabledCommandPaletteResultRow(props: { - item: CommandPaletteActionItem | CommandPaletteSubmenuItem; - query: string; -}) { - return ( -
- {props.item.icon} - {props.item.description || props.item.threadContentMatch ? ( - - - {props.item.titleLeadingContent} - - - - - - - ) : ( - - {props.item.titleLeadingContent} - - - - - )} - {props.item.titleTrailingContent} -
- ); -} - -function CommandPaletteResultRow(props: { - item: CommandPaletteActionItem | CommandPaletteSubmenuItem; - isActive: boolean; +/** + * One row, one line: the icon, the title (a thread's status marks around it), + * what it belongs to, then its age or shortcut. A message match adds its + * snippet as a second line. On a phone what it belongs to moves under the + * title, so rows are finger-sized. + */ +function PaletteRowContent(props: { + item: ResultItem; keybindings: ResolvedKeybindingsConfig; query: string; - onExecuteItem: (item: CommandPaletteActionItem | CommandPaletteSubmenuItem) => void; }) { - const shortcutLabel = props.item.shortcutCommand - ? shortcutLabelForCommand(props.keybindings, props.item.shortcutCommand) + const { item } = props; + const shortcutLabel = item.shortcutCommand + ? shortcutLabelForCommand(props.keybindings, item.shortcutCommand) : null; + const meta = item.whereLabel ?? item.description; + const match = item.threadContentMatch; + const tail: ReactNode[] = []; + if (item.titleTrailingContent) tail.push(item.titleTrailingContent); + if (item.timestampAt) { + tail.push( + + + , + ); + } + if (shortcutLabel) tail.push({shortcutLabel}); + if (item.kind === "submenu") { + tail.push(); + } return ( - { - event.preventDefault(); - }} - onClick={() => { - props.onExecuteItem(props.item); - }} - > - {props.item.icon} - {props.item.description || props.item.threadContentMatch ? ( - - - {props.item.titleLeadingContent} - - - - - - - ) : ( - - {props.item.titleLeadingContent} - - - + <> + + {item.more ? null : item.icon} + + + {item.titleLeadingContent} + + - )} - {props.item.titleTrailingContent} - {props.item.whereLabel ? ( - - {props.item.whereLabel} + + {meta ? ( + + {meta} ) : null} - {props.item.timestampAt ? ( - - - + {tail.length > 0 ? ( + {tail} ) : null} - {shortcutLabel ? {shortcutLabel} : null} - {props.item.kind === "submenu" ? ( - + {match ? ( + + {splitSearchTextHighlightSegments(match.snippet, match.query).map((segment) => + segment.highlighted ? ( + + {segment.text} + + ) : ( + {segment.text} + ), + )} + ) : null} - + ); } -function CommandPaletteResultTitle(props: { - item: CommandPaletteActionItem | CommandPaletteSubmenuItem; - query: string; -}) { +function CommandPaletteResultTitle(props: { item: ResultItem; query: string }) { if ( !props.item.threadRef || typeof props.item.title !== "string" || @@ -251,37 +345,3 @@ function CommandPaletteResultTitle(props: { ), ); } - -function CommandPaletteResultDescription(props: { - item: CommandPaletteActionItem | CommandPaletteSubmenuItem; -}) { - const match = props.item.threadContentMatch; - return ( - - {props.item.description ? ( - {props.item.description} - ) : null} - {props.item.description && match ? ( - - ) : null} - {match ? ( - - {splitSearchTextHighlightSegments(match.snippet, match.query).map((segment) => - segment.highlighted ? ( - - {segment.text} - - ) : ( - {segment.text} - ), - )} - - ) : null} - - ); -} diff --git a/apps/web/src/components/addProject/OpenAddProjectDialog.tsx b/apps/web/src/components/addProject/OpenAddProjectDialog.tsx index b2bbd205c..f160e84d8 100644 --- a/apps/web/src/components/addProject/OpenAddProjectDialog.tsx +++ b/apps/web/src/components/addProject/OpenAddProjectDialog.tsx @@ -16,7 +16,9 @@ import { ArrowDownIcon, ArrowLeftIcon, ArrowUpIcon, + CornerDownLeftIcon, CornerLeftUpIcon, + DeleteIcon, FolderIcon, FolderPlusIcon, LinkIcon, @@ -92,11 +94,15 @@ import { editorLabel } from "../EditorOpenOptions"; import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "../Icons"; import { Button } from "../ui/button"; import { + COMMAND_GROUP_CLASS, + COMMAND_ROW_CLASS, + COMMAND_SECTION_LABEL_CLASS, Command, CommandDialogPopup, CommandFooter, CommandInput, CommandPanel, + CommandTitle, } from "../ui/command"; import { Kbd, KbdGroup } from "../ui/kbd"; import { failureNotice, stackedThreadToast, toastManager } from "../ui/toast"; @@ -1433,10 +1439,24 @@ export function OpenAddProjectDialog({ session }: { session: AddProjectSession } isPickingProjectFolder, ]); + // Where the user is in Add project, for the title row. + const stepTitle = + addProjectCloneFlow?.step === "repository" + ? "Choose a repository" + : addProjectCloneFlow?.step === "confirm" + ? "Choose where to clone" + : isBrowsing + ? "Choose a folder" + : currentView?.groups[0]?.value === "environments" + ? "Choose a computer" + : currentView?.groups[0]?.value.startsWith("sources:") + ? "Choose a source" + : undefined; + return ( resolveDialogReturnFocus(session.returnFocus)} onBackdropPointerDown={closeDialog} @@ -1452,6 +1472,7 @@ export function OpenAddProjectDialog({ session }: { session: AddProjectSession } onValueChange={handleQueryChange} value={query} > +
) : null}
- + {remoteProjectContext ? ( -
-
- Repository -
-
- {remoteProjectContext.icon} - - +
+
Repository
+
+
+ + {remoteProjectContext.icon} + + {remoteProjectContext.title} - + {remoteProjectContext.description} - +
) : null} - -
+ {/* Key hints only help with a keyboard; on touch the footer stays only for its button. */} + + + + + + + Move + + {addProjectCloneFlow?.step === "repository" ? ( - + + {remoteProjectButtonLabel ?? "Continue"} + + ) : !canSubmitBrowsePath || hasHighlightedBrowseItem ? ( + - + - Navigate + Select - {addProjectCloneFlow?.step === "repository" ? ( - - Enter - - {remoteProjectButtonLabel ?? "Continue"} - - - ) : !canSubmitBrowsePath || hasHighlightedBrowseItem ? ( - - Enter - Select - - ) : null} - {isSubmenu ? ( - - Backspace - Back - - ) : null} + ) : null} + {isSubmenu ? ( - Esc - Close + + + + Back -
+ ) : null} + {canOpenProjectFromFileManager ? ( - + @@ -402,39 +405,6 @@
- -

What changed from today

-
    -
  • - Opens on your threads. The last five, with the one you just left on top, so Search then - Enter takes you back. Under them, a few commands that fit what's on screen and the ones you - use most. -
  • -
  • - Best match first, whatever it is. The group holding the best match moves to the top. - Each group shows five and a "Show all" row. -
  • -
  • - Settings are in. A setting opens its page with the row lit up, the way Settings search - already does. -
  • -
  • - Filters. All, Threads, Commands, Settings, Projects, with a count on each while you - type. Typing > first jumps to Commands. -
  • -
  • - It says what it's doing. "Searching messages" while chats are still being read, and a - plain line when a computer can't be reached or its search may be incomplete. -
  • -
  • - A path is a suggestion, not a switch. Typing one adds an "Add project at" row on top. - The search results stay. -
  • -
  • - One flat surface. No box inside a box, wider, one-line rows, about 13 rows visible - instead of 8. -
  • -