diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index e34af8b97..4ecd119a5 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/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/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/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 new file mode 100644 index 000000000..1305b871b --- /dev/null +++ b/apps/web/src/commands/paletteSearch.test.ts @@ -0,0 +1,260 @@ +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>; + }, +) { + return paletteSearch({ + query, + 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("finds close matches from three letters", () => { + const commands = [place("command:settings", "Open 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([]); + }); + + 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..1081a2999 --- /dev/null +++ b/apps/web/src/commands/paletteSearch.ts @@ -0,0 +1,294 @@ +/** + * 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 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. A + * view shows them only when it found nothing itself (paletteFilters.ts). + */ + readonly closeMatches: ReadonlyArray>; +} + +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 & { readonly source: PaletteCloseMatch["source"] }>, + 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: { 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({ 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.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. 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 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 bySource: Array<{ source: PaletteSource; rows: ReadonlyArray> }> = [ + { source: "threads", rows: sortSection(searchThreads(input.threads, text, words)) }, + { source: "commands", rows: sortSection(searchPlaces(input.commands, 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) + .toSorted( + (left, right) => + left.rows[0]!.tier - right.rows[0]!.tier || + SOURCE_ORDER.indexOf(left.source) - SOURCE_ORDER.indexOf(right.source), + ); + return { + sections, + closeMatches: closeMatches( + [ + ...input.commands.map((entry) => ({ ...entry, source: "commands" as const })), + ...input.settings.map((entry) => ({ ...entry, source: "settings" as const })), + ], + 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/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/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/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/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..04a8fa21d 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" }); @@ -762,12 +791,12 @@ 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 }, ); await expect - .element(palette.getByRole("button", { name: addButtonLabel })) + .element(dialog.getByRole("button", { name: addButtonLabel })) .toBeInTheDocument(); await dispatchInputKey(browseInput, { @@ -811,6 +840,267 @@ 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 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.getByRole("group", { name: "Projects" })).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 threads, commands and settings").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, @@ -846,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 9d35b105c..ffccaab49 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, @@ -3116,6 +3118,31 @@ export async function openCommandPaletteFromTrigger(): Promise { ); } +/** + * 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 chosen = document.querySelector( + '[data-testid="command-palette"] [data-slot="command-filter"][aria-pressed="true"]', + ); + expect(chosen?.textContent).toBe("Commands"); + }, + { 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(); @@ -3144,9 +3171,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"]'), @@ -3474,6 +3504,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..b8fee6df5 --- /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, + openCommandPaletteCommands, + 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 openCommandPaletteCommands(); + 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 openCommandPaletteCommands(); + 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.desktop-window.browser.tsx b/apps/web/src/components/ChatView.desktop-window.browser.tsx index 5388c067a..7d1b53163 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,44 @@ 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 threads, commands and settings").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.move-thread.browser.tsx b/apps/web/src/components/ChatView.move-thread.browser.tsx index 99d3e86f0..a07c27d1f 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,14 +1577,17 @@ 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") .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(() => { @@ -2002,7 +2005,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 +2145,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-settings.browser.tsx b/apps/web/src/components/ChatView.palette-settings.browser.tsx new file mode 100644 index 000000000..323e4a279 --- /dev/null +++ b/apps/web/src/components/ChatView.palette-settings.browser.tsx @@ -0,0 +1,137 @@ +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 threads, commands and settings").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 threads, commands and settings").fill("one-time link"); + await expect + .element(palette.getByText("One-time link for this network", { exact: true })) + .not.toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + + 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({ + 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 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 77cceeb2e..caa4c3034 100644 --- a/apps/web/src/components/ChatView.palette.browser.tsx +++ b/apps/web/src/components/ChatView.palette.browser.tsx @@ -1,29 +1,33 @@ import { + EventId, ORCHESTRATION_WS_METHODS, MessageId, + type OrchestrationEvent, type OrchestrationReadModel, 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 { scopedProjectKey, scopeProjectRef } from "@threadlines/client-runtime"; +import { page, userEvent } 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, UUID_ROUTE_RE, - ADD_PROJECT_SUBMENU_PLACEHOLDER, - fixture, wsRequests, DEFAULT_VIEWPORT, createSnapshotForTargetUser, @@ -42,10 +46,9 @@ import { CHAT_FIND_KEYBINDING, triggerChatNewShortcutUntilPath, openCommandPaletteFromTrigger, + openCommandPaletteCommands, + showAllPaletteCommands, waitForCommandPaletteShortcutLabel, - waitForCommandPaletteInput, - selectLocalFolderAction, - dispatchInputKey, mountChatView, registerChatViewSuiteHooks, rpcHarness, @@ -87,7 +90,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(); @@ -191,7 +194,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 }) @@ -207,6 +210,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 }) @@ -224,6 +228,693 @@ 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", + "# Suggested", + ]); + // 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("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 threads, commands and settings").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 threads, commands and settings").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 threads, commands and settings").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("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; + 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 @@ -260,7 +951,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(); @@ -319,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 })) @@ -329,122 +1020,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"`; @@ -506,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( @@ -851,117 +1426,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, @@ -1001,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 })) @@ -1063,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 })) @@ -1120,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, @@ -1133,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(); @@ -1177,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/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index cfdbdc9ae..594d1bd7b 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -88,7 +88,7 @@ import { toShellSnapshot, clickProjectMenuItem, registerChatViewSuiteHooks, - openCommandPaletteFromTrigger, + openCommandPaletteCommands, } from "./ChatView.browser-harness"; vi.mock("../lib/gitStatusState", () => ({ @@ -1030,7 +1030,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); @@ -1298,7 +1298,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 0509950a2..d5ecb29c3 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"; @@ -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"; @@ -500,6 +501,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 = []; @@ -4212,8 +4216,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( @@ -4999,7 +5017,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 = { @@ -5110,9 +5128,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; @@ -5137,25 +5154,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) => { @@ -9267,7 +9328,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.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..30bc818e9 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -1,10 +1,6 @@ -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 type { AppCommandId } from "@threadlines/shared/appCommands"; import { analyzeSearchText, parseSearchQuery, @@ -12,14 +8,13 @@ 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; -export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80"; +/** 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"; export const ADDON_ICON_CLASS = "size-4"; export interface CommandPaletteItem { @@ -36,14 +31,28 @@ export interface CommandPaletteItem { readonly titleLeadingContent?: ReactNode; /** Optional content rendered inline after the title text (before the timestamp). */ readonly titleTrailingContent?: ReactNode; + /** + * 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 }; + /** 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 { 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; } @@ -69,40 +78,8 @@ export interface CommandPaletteView { EnvironmentId, ReadonlyArray >; -} - -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 }; + /** A list command's page: its rows are drawn from the command's current items. */ + readonly listCommandId?: AppCommandId; } export function normalizeSearchText(value: string): string { @@ -184,6 +161,7 @@ export function buildThreadActionItems