Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions apps/server/src/guide/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
10 changes: 5 additions & 5 deletions apps/web/src/commandPaletteStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down
44 changes: 7 additions & 37 deletions apps/web/src/commandPaletteStore.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { EnvironmentId, ScopedProjectRef } from "@threadlines/contracts";
import { create } from "zustand";

export interface CommandPaletteThreadSearchRequest {
Expand All @@ -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;
Expand All @@ -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;
}
Expand All @@ -49,44 +35,28 @@ export const useCommandPaletteStore = create<CommandPaletteStore>((set) => ({
open: false,
openGeneration: 0,
openIntent: null,
projectSelection: null,
setOpen: (open) =>
set((state) => ({
open,
...(open
? 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,
Expand Down
59 changes: 59 additions & 0 deletions apps/web/src/commands/PaletteCommandSources.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<>
<NavigationCommands />
<ProjectCommands />
<ThreadCommands />
<FleetCommands />
<ThemeCommands />
</>
);
}

/**
* 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;
}
198 changes: 198 additions & 0 deletions apps/web/src/commands/commandHandlers.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof runCommand>[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"]);
});
});
Loading
Loading