feat(web): give tasks their own command palette scope (#2979)

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
João Salavisa
2026-08-24 21:31:26 +00:00
committed by GitHub
parent 1e05cf9201
commit b8e0dd7dc5
20 changed files with 1177 additions and 553 deletions
@@ -2,6 +2,8 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { WorkspaceContentSearchResult } from "@/lib/types/backend";
import type { Task } from "@/lib/types/http";
import { taskId, workflowId, workspaceId } from "@/lib/types/ids";
vi.mock("@kandev/ui/command", () => ({
Command: ({ children, shouldFilter }: { children: ReactNode; shouldFilter?: boolean }) => (
@@ -66,7 +68,13 @@ vi.mock("@kandev/ui/command", () => ({
/>
</div>
),
CommandItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,
// Forwards onSelect: without it the mock silently swallows every selection
// handler and any assertion about picking a row would prove nothing.
CommandItem: ({ children, onSelect }: { children: ReactNode; onSelect?: () => void }) => (
<div role="option" aria-selected="false" onClick={onSelect}>
{children}
</div>
),
CommandList: ({ children }: { children: ReactNode }) => <div>{children}</div>,
CommandShortcut: ({ children }: { children: ReactNode }) => <span>{children}</span>,
}));
@@ -109,6 +117,7 @@ import {
CommandPanelView,
MODE_COMMANDS,
MODE_SEARCH_CONTENT,
MODE_SEARCH_TASKS,
type CommandPanelViewProps,
} from "./command-panel-footer";
@@ -185,14 +194,21 @@ describe("CommandPanelView task content search mode", () => {
fireEvent.click(screen.getByTestId("mock-content-search"));
expect(props.handleContentSelect).toHaveBeenCalledWith(result);
});
});
describe("CommandPanelView scope switcher", () => {
it("makes all palette scopes visible and switches without clearing the query", () => {
const onScopeChange = vi.fn();
const props = viewProps({ onScopeChange });
render(<CommandPanelView {...props} />);
const tabs = screen.getAllByRole("tab");
expect(tabs).toHaveLength(3);
expect(tabs.map((tab) => tab.getAttribute("aria-label"))).toEqual([
"Commands",
"Tasks",
"Files",
"Contents",
]);
expect(
screen.getByRole("tab", { name: "Commands" }).getAttribute(ARIA_SELECTED_ATTRIBUTE),
).toBe("false");
@@ -262,7 +278,7 @@ describe("CommandPanelView task content search mode", () => {
expect(document.activeElement).toBe(input);
});
it("hides workspace modes and leaves Tab alone outside a task workbench", () => {
it("hides workspace modes but keeps commands and tasks outside a task workbench", () => {
const onScopeChange = vi.fn();
render(
<CommandPanelView
@@ -275,10 +291,15 @@ describe("CommandPanelView task content search mode", () => {
);
const input = screen.getByRole("combobox");
expect(screen.queryByRole("tablist", { name: "Command palette mode" })).toBeNull();
expect(screen.queryByText("Switch mode")).toBeNull();
expect(fireEvent.keyDown(input, { key: "Tab" })).toBe(true);
expect(onScopeChange).not.toHaveBeenCalled();
expect(screen.getAllByRole("tab").map((tab) => tab.getAttribute("aria-label"))).toEqual([
"Commands",
"Tasks",
]);
// Tab still cycles, but only between the two scopes that need no worktree.
expect(fireEvent.keyDown(input, { key: "Tab" })).toBe(false);
expect(onScopeChange).toHaveBeenLastCalledWith("search-tasks");
expect(fireEvent.keyDown(input, { key: "Tab", shiftKey: true })).toBe(false);
expect(onScopeChange).toHaveBeenLastCalledWith("search-tasks");
});
});
@@ -496,3 +517,103 @@ describe("CommandPanelView confirmations", () => {
expect(setOpen).toHaveBeenCalledWith(false);
});
});
function task(id: string, title: string): Task {
return {
id: taskId(id),
workspace_id: workspaceId("workspace-1"),
workflow_id: workflowId("workflow-1"),
workflow_step_id: "step-1",
position: 0,
title,
description: "",
state: "IN_PROGRESS",
priority: "medium",
created_at: "2026-08-24T09:00:00Z",
updated_at: "2026-08-24T09:00:00Z",
};
}
describe("CommandPanelView commands scope ordering", () => {
const archiveCommand = {
id: "task-archive",
label: "Archive task",
group: "Task",
action: vi.fn(),
};
function groupHeadings() {
return Array.from(document.querySelectorAll(CMDK_GROUP_HEADING_SELECTOR)).map(
(heading) => heading.textContent,
);
}
it("puts matching commands above the task preview once the user types", () => {
render(
<CommandPanelView
{...viewProps({
mode: MODE_COMMANDS,
search: "archive",
commands: [archiveCommand],
grouped: [],
taskResults: [task("task-1", "Close every remaining archive item")],
})}
/>,
);
expect(groupHeadings()).toEqual(["Commands", "Tasks"]);
});
it("keeps the active task list on top while nothing is typed", () => {
render(
<CommandPanelView
{...viewProps({
mode: MODE_COMMANDS,
search: "",
commands: [archiveCommand],
grouped: [["Task", [archiveCommand]]],
taskResults: [task("task-1", "Resume yesterday's work")],
})}
/>,
);
expect(groupHeadings()).toEqual(["Active Tasks", "Task"]);
});
});
describe("CommandPanelView tasks scope", () => {
it("lists task results and opens the one that is picked", () => {
const target = task("task-1", "Palette task");
const props = viewProps({
mode: MODE_SEARCH_TASKS,
search: "palette",
taskResults: [target],
});
render(<CommandPanelView {...props} />);
expect(screen.getByPlaceholderText("Search for tasks...")).toBeTruthy();
expect(screen.getByText("Palette task")).toBeTruthy();
expect(screen.getByRole("tab", { name: "Tasks" }).getAttribute(ARIA_SELECTED_ATTRIBUTE)).toBe(
"true",
);
fireEvent.click(screen.getByText("Palette task"));
expect(props.handleTaskSelect).toHaveBeenCalledWith(target);
});
it("reports an empty task search instead of falling back to commands", () => {
render(
<CommandPanelView
{...viewProps({
mode: MODE_SEARCH_TASKS,
search: "nothing",
taskResults: [],
commands: [{ id: "nav-home", label: "Go Home", group: "Navigation" }],
})}
/>,
);
expect(screen.getByText("No tasks found.")).toBeTruthy();
expect(screen.queryByText("Go Home")).toBeNull();
});
});
+52 -347
View File
@@ -3,33 +3,18 @@
import { useEffect, type Dispatch, type SetStateAction } from "react";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { formatTimeDistance, useDateLocale } from "@/lib/i18n/date-locale";
import { IconArchive, IconArrowRight, IconHammer, IconLoader2 } from "@tabler/icons-react";
import {
Command,
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandShortcut,
} from "@kandev/ui/command";
import { Kbd, KbdGroup } from "@kandev/ui/kbd";
import { Badge } from "@kandev/ui/badge";
import type { CommandPanelMode, CommandItem as CommandItemType } from "@/lib/commands/types";
import {
getCommandSearchTerms,
scoreCommandSearch,
sortCommandsForSearch,
} from "@/lib/commands/search";
import { formatShortcut } from "@/lib/keyboard/utils";
import type { Task } from "@/lib/types/http";
import type { FileSearchResult } from "@/lib/types/backend";
import { FileIcon } from "@/components/ui/file-icon";
import { WorkspaceContentSearch } from "@/components/workspace-content-search";
import { useRepoDisplayName } from "@/hooks/domains/session/use-repo-display-name";
import { groupByRepositoryName, isSingleRepoGroup } from "@/lib/group-by-repo";
import {
CommandPanelScopeSwitcher,
getAdjacentCommandPanelScope,
@@ -43,312 +28,25 @@ import {
dismissCommandConfirmation,
getCommandConfirmationState,
} from "@/components/command-panel-confirmation";
import {
CommandsListContent,
FileSearchContent,
MODE_COMMANDS,
MODE_SEARCH_CONTENT,
MODE_SEARCH_FILES,
MODE_SEARCH_TASKS,
TaskSearchContent,
type StepMap,
} from "@/components/command-panel-results";
const ARCHIVED_STATES = new Set(["COMPLETED", "CANCELLED", "FAILED"]);
export const MODE_COMMANDS: CommandPanelMode = "commands";
export const MODE_SEARCH_FILES: CommandPanelMode = "search-files";
export const MODE_SEARCH_CONTENT: CommandPanelMode = "search-content";
const STEP_COLOR_MAP: Record<string, string> = {
"bg-slate-500": "#64748b",
"bg-red-500": "#ef4444",
"bg-orange-500": "#f97316",
"bg-yellow-500": "#eab308",
"bg-green-500": "#22c55e",
"bg-cyan-500": "#06b6d4",
"bg-blue-500": "#3b82f6",
"bg-indigo-500": "#6366f1",
"bg-purple-500": "#a855f7",
};
function getFileName(filePath: string) {
return filePath.split("/").pop() ?? filePath;
}
export function getTaskResultValue(task: Task) {
return `__task:${task.id} ${task.title}`;
}
export function getFileResultValue(filePath: string) {
return `__file:${filePath}`;
}
function CommandItemRow({
cmd,
onSelect,
}: {
cmd: CommandItemType;
onSelect: (cmd: CommandItemType) => void;
}) {
return (
<CommandItem
key={cmd.id}
value={cmd.id}
keywords={getCommandSearchTerms(cmd)}
onSelect={() => onSelect(cmd)}
>
{cmd.icon && (
<span
className={
cmd.context ? "self-start pt-0.5 text-muted-foreground" : "text-muted-foreground"
}
>
{cmd.icon}
</span>
)}
<span className="min-w-0 flex-1">
<span className="block truncate">{cmd.label}</span>
{cmd.context && (
<span className="block truncate text-[0.625rem] leading-4 text-muted-foreground">
{cmd.context}
</span>
)}
</span>
{cmd.shortcut && <CommandShortcut>{formatShortcut(cmd.shortcut)}</CommandShortcut>}
{cmd.enterMode && (
<span className="ml-auto text-muted-foreground">
<IconArrowRight className="size-3" />
</span>
)}
</CommandItem>
);
}
type TaskResultItemProps = {
task: Task;
stepMap: Map<string, { name: string; color: string }>;
repoMap: Map<string, string>;
onSelect: (task: Task) => void;
};
function TaskResultItem({ task, stepMap, repoMap, onSelect }: TaskResultItemProps) {
const locale = useDateLocale();
const isArchived = ARCHIVED_STATES.has(task.state);
const step = stepMap.get(task.workflow_step_id);
const stepHex = step ? STEP_COLOR_MAP[step.color] : undefined;
const rawPath =
task.primary_working_directory ??
(task.repositories?.[0] ? repoMap.get(task.repositories[0].repository_id) : undefined);
const workDir = rawPath ? getFileName(rawPath) : undefined;
const details: string[] = [];
if (workDir) details.push(workDir);
if (task.primary_agent_name) details.push(task.primary_agent_name);
if (task.updated_at) {
details.push(formatTimeDistance(task.updated_at, locale));
}
return (
<CommandItem
key={task.id}
value={getTaskResultValue(task)}
onSelect={() => onSelect(task)}
className={isArchived ? "opacity-60" : ""}
forceMount
>
<div className="flex items-center gap-2 min-w-0 w-full">
{isArchived ? (
<IconArchive className="size-3 shrink-0 text-muted-foreground" />
) : (
<IconHammer className="size-3 shrink-0 text-muted-foreground" />
)}
<span className="truncate font-medium">{task.title}</span>
{step && (
<Badge
variant="secondary"
className="text-[0.6rem] shrink-0"
style={stepHex ? { backgroundColor: stepHex + "22", color: stepHex } : undefined}
>
{step.name}
</Badge>
)}
{details.length > 0 && (
<span className="ml-auto text-[0.6rem] text-muted-foreground truncate shrink-0">
{details.join(" · ")}
</span>
)}
</div>
</CommandItem>
);
}
type CommandsListContentProps = {
commands: CommandItemType[];
grouped: [string, CommandItemType[]][];
search: string;
onSelect: (cmd: CommandItemType) => void;
taskResults: Task[];
isSearching: boolean;
stepMap: Map<string, { name: string; color: string }>;
repoMap: Map<string, string>;
onTaskSelect: (task: Task) => void;
};
function SearchCommandGroups({
commands,
search,
onSelect,
}: Pick<CommandsListContentProps, "commands" | "search" | "onSelect">) {
const { t } = useTranslation();
const matches = sortCommandsForSearch(commands, search).filter(
(cmd) => scoreCommandSearch(cmd.id, search, getCommandSearchTerms(cmd)) > 0,
);
const regularMatches = matches.filter((cmd) => !cmd.searchOnly);
const searchOnlyGroups = new Map<string, CommandItemType[]>();
for (const cmd of matches) {
if (!cmd.searchOnly) continue;
const groupItems = searchOnlyGroups.get(cmd.group) ?? [];
groupItems.push(cmd);
searchOnlyGroups.set(cmd.group, groupItems);
}
return (
<>
{regularMatches.length > 0 && (
<CommandGroup heading={t("common:commandGroupCommands")}>
{regularMatches.map((cmd) => (
<CommandItemRow key={cmd.id} cmd={cmd} onSelect={onSelect} />
))}
</CommandGroup>
)}
{[...searchOnlyGroups].map(([group, items]) => (
<CommandGroup key={group} heading={group}>
{items.map((cmd) => (
<CommandItemRow key={cmd.id} cmd={cmd} onSelect={onSelect} />
))}
</CommandGroup>
))}
</>
);
}
function CommandsListContent({
commands,
grouped,
search,
onSelect,
taskResults,
isSearching,
stepMap,
repoMap,
onTaskSelect,
}: CommandsListContentProps) {
const { t } = useTranslation();
const hasInlineResults = taskResults.length > 0 || isSearching;
return (
<>
{!hasInlineResults && !isSearching && (
<CommandEmpty>{t("common:noCommandsFound")}</CommandEmpty>
)}
{isSearching && taskResults.length === 0 && (
<CommandGroup heading={t("common:activeTasks")} forceMount>
<div className="flex items-center justify-center py-3">
<IconLoader2 className="size-3.5 animate-spin text-muted-foreground" />
</div>
</CommandGroup>
)}
{taskResults.length > 0 && (
<CommandGroup
heading={search.trim() ? t("common:tasks") : t("common:activeTasks")}
forceMount
>
{taskResults.map((task) => (
<TaskResultItem
key={task.id}
task={task}
stepMap={stepMap}
repoMap={repoMap}
onSelect={onTaskSelect}
/>
))}
</CommandGroup>
)}
{search.trim() ? (
<SearchCommandGroups commands={commands} search={search} onSelect={onSelect} />
) : (
grouped.map(([group, items]) => {
const visibleItems = items.filter((cmd) => !cmd.searchOnly);
if (visibleItems.length === 0) return null;
return (
<CommandGroup key={group} heading={group}>
{visibleItems.map((cmd) => (
<CommandItemRow key={cmd.id} cmd={cmd} onSelect={onSelect} />
))}
</CommandGroup>
);
})
)}
</>
);
}
type FileSearchContentProps = {
files: FileSearchResult[];
isSearching: boolean;
search: string;
sessionId: string | null;
onSelect: (path: string) => void;
};
function FileSearchContent({
files,
isSearching,
search,
sessionId,
onSelect,
}: FileSearchContentProps) {
const { t } = useTranslation();
const getRepoDisplayName = useRepoDisplayName(sessionId);
if (isSearching && files.length === 0) {
return (
<div className="flex items-center justify-center py-6">
<IconLoader2 className="size-4 animate-spin text-muted-foreground" />
</div>
);
}
if (search.trim() && files.length === 0)
return <CommandEmpty>{t("common:noFilesFound")}</CommandEmpty>;
if (!search.trim()) return <CommandEmpty>{t("common:typeToSearchFiles")}</CommandEmpty>;
const groups = groupByRepositoryName(files, (file) => file.repository_name);
const singleRepo = isSingleRepoGroup(groups);
return groups.map((group) => (
<CommandGroup
key={group.repositoryName || "workspace"}
heading={
singleRepo
? t("common:files")
: (getRepoDisplayName(group.repositoryName) ??
group.repositoryName ??
t("common:workspace"))
}
forceMount
data-testid="file-search-repo-group"
data-repository={group.repositoryName}
>
{group.items.map((file) => {
const repositoryPrefix = file.repository_name ? `${file.repository_name}/` : "";
const displayPath = file.path.startsWith(repositoryPrefix)
? file.path.slice(repositoryPrefix.length)
: file.path;
const fileName = getFileName(displayPath);
const lastSlash = displayPath.lastIndexOf("/");
const dir = lastSlash > 0 ? displayPath.slice(0, lastSlash) : "";
return (
<CommandItem
key={file.path}
value={getFileResultValue(file.path)}
onSelect={() => onSelect(file.path)}
forceMount
>
<FileIcon fileName={fileName} className="shrink-0" />
<span className="truncate font-medium">{fileName}</span>
{dir && <span className="ml-1 truncate text-xs text-muted-foreground">{dir}</span>}
</CommandItem>
);
})}
</CommandGroup>
));
}
export {
MODE_COMMANDS,
MODE_SEARCH_CONTENT,
MODE_SEARCH_FILES,
MODE_SEARCH_TASKS,
getFileResultValue,
getTaskResultValue,
} from "@/components/command-panel-results";
// `mode` stays an untranslated discriminant — it is compared with `===`
// throughout. Only the labels it selects are copy.
@@ -358,7 +56,7 @@ function getInputPlaceholder(
inputCommand: CommandItemType | null,
) {
if (mode === "input") return inputCommand?.inputPlaceholder ?? t("common:enterValue");
if (mode === "search-tasks") return t("common:searchForTasks");
if (mode === MODE_SEARCH_TASKS) return t("common:searchForTasks");
if (mode === MODE_SEARCH_FILES) return t("common:searchForFiles");
if (mode === MODE_SEARCH_CONTENT) return t("common:searchTaskContents");
return t("common:typeACommand");
@@ -366,7 +64,7 @@ function getInputPlaceholder(
function getEnterLabel(t: TFunction, mode: CommandPanelMode) {
if (mode === "input") return t("common:confirm");
if (mode === "search-tasks" || mode === MODE_SEARCH_FILES || mode === MODE_SEARCH_CONTENT) {
if (mode === MODE_SEARCH_TASKS || mode === MODE_SEARCH_FILES || mode === MODE_SEARCH_CONTENT) {
return t("common:open");
}
return t("common:select");
@@ -374,22 +72,15 @@ function getEnterLabel(t: TFunction, mode: CommandPanelMode) {
function getModeLabel(t: TFunction, mode: CommandPanelMode, inputCommand: CommandItemType | null) {
if (mode === "input") return inputCommand?.label;
if (mode === "search-tasks") return t("common:tasks");
if (mode === MODE_SEARCH_TASKS) return t("common:tasks");
if (mode === MODE_SEARCH_FILES) return t("common:files");
if (mode === MODE_SEARCH_CONTENT) return t("common:contents");
return null;
}
function CommandPanelFooter({
mode,
workspaceSearchAvailable,
}: {
mode: CommandPanelMode;
workspaceSearchAvailable: boolean;
}) {
function CommandPanelFooter({ mode }: { mode: CommandPanelMode }) {
const { t } = useTranslation();
const isScopeMode = isCommandPanelScopeMode(mode);
const canSwitchScope = workspaceSearchAvailable && isScopeMode;
return (
<div className="border-t border-border px-3 py-1.5 flex items-center gap-3 text-[0.6rem] text-muted-foreground">
{isScopeMode && (
@@ -399,12 +90,10 @@ function CommandPanelFooter({
<Kbd>↓</Kbd>
<span>{t("common:navigate")}</span>
</KbdGroup>
{canSwitchScope && (
<KbdGroup>
<Kbd>Tab</Kbd>
<span>{t("common:switchMode")}</span>
</KbdGroup>
)}
<KbdGroup>
<Kbd>Tab</Kbd>
<span>{t("common:switchMode")}</span>
</KbdGroup>
</>
)}
<KbdGroup>
@@ -452,7 +141,7 @@ export type CommandPanelViewProps = {
handleSelect: (cmd: CommandItemType) => void;
isSearching: boolean;
taskResults: Task[];
stepMap: Map<string, { name: string; color: string }>;
stepMap: StepMap;
repoMap: Map<string, string>;
handleTaskSelect: (task: Task) => void;
};
@@ -469,24 +158,27 @@ function CommandPanelInputHeader({
}: CommandPanelViewProps) {
const { t } = useTranslation();
const isTopLevelMode = isCommandPanelScopeMode(mode);
const canSwitchScope = workspaceSearchAvailable && isTopLevelMode;
const modeLabel = getModeLabel(t, mode, inputCommand);
const onInputKeyDown = (event: React.KeyboardEvent) => {
if (
canSwitchScope &&
isTopLevelMode &&
event.key === "Tab" &&
!event.altKey &&
!event.ctrlKey &&
!event.metaKey
) {
event.preventDefault();
onScopeChange(getAdjacentCommandPanelScope(mode, event.shiftKey));
onScopeChange(getAdjacentCommandPanelScope(mode, event.shiftKey, workspaceSearchAvailable));
return;
}
handleKeyDown(event);
};
return (
<div className="flex min-h-10 items-center border-b border-border [&>[data-slot=command-input-wrapper]]:min-w-0 [&>[data-slot=command-input-wrapper]]:flex-1 [&>[data-slot=command-input-wrapper]]:pb-1">
// Four scope tabs do not fit beside the input on a phone, and the tablist
// does not shrink, so the input would collapse to a few characters. The
// min-width forces the tablist onto its own row instead of squeezing the
// query out of view.
<div className="flex min-h-10 flex-wrap items-center border-b border-border [&>[data-slot=command-input-wrapper]]:min-w-44 [&>[data-slot=command-input-wrapper]]:flex-1 [&>[data-slot=command-input-wrapper]]:pb-1">
{!isTopLevelMode && (
<button
onClick={goBack}
@@ -504,7 +196,13 @@ function CommandPanelInputHeader({
onValueChange={setSearch}
onKeyDown={onInputKeyDown}
/>
{canSwitchScope && <CommandPanelScopeSwitcher mode={mode} onScopeChange={onScopeChange} />}
{isTopLevelMode && (
<CommandPanelScopeSwitcher
mode={mode}
onScopeChange={onScopeChange}
workspaceSearchAvailable={workspaceSearchAvailable}
/>
)}
</div>
);
}
@@ -552,6 +250,16 @@ function CommandPanelResultList(props: CommandPanelViewProps) {
onTaskSelect={handleTaskSelect}
/>
)}
{mode === MODE_SEARCH_TASKS && (
<TaskSearchContent
tasks={taskResults}
isSearching={isSearching}
search={search}
stepMap={stepMap}
repoMap={repoMap}
onSelect={handleTaskSelect}
/>
)}
{mode === MODE_SEARCH_FILES && (
<FileSearchContent
files={fileResults}
@@ -632,10 +340,7 @@ export function CommandPanelView(props: CommandPanelViewProps) {
>
<CommandPanelInputHeader {...renderedProps} />
<CommandPanelResultList {...renderedProps} />
<CommandPanelFooter
mode={renderedProps.mode}
workspaceSearchAvailable={workspaceSearchAvailable}
/>
<CommandPanelFooter mode={renderedProps.mode} />
</Command>
</CommandDialog>
);
@@ -0,0 +1,429 @@
"use client";
import { useTranslation } from "react-i18next";
import { formatTimeDistance, useDateLocale } from "@/lib/i18n/date-locale";
import { IconArchive, IconArrowRight, IconHammer, IconLoader2 } from "@tabler/icons-react";
import { CommandEmpty, CommandGroup, CommandItem, CommandShortcut } from "@kandev/ui/command";
import { Badge } from "@kandev/ui/badge";
import type { CommandPanelMode, CommandItem as CommandItemType } from "@/lib/commands/types";
import {
getCommandSearchTerms,
scoreCommandSearch,
sortCommandsForSearch,
} from "@/lib/commands/search";
import { formatShortcut } from "@/lib/keyboard/utils";
import type { Task } from "@/lib/types/http";
import type { FileSearchResult } from "@/lib/types/backend";
import { FileIcon } from "@/components/ui/file-icon";
import { useRepoDisplayName } from "@/hooks/domains/session/use-repo-display-name";
import { groupByRepositoryName, isSingleRepoGroup } from "@/lib/group-by-repo";
const ARCHIVED_STATES = new Set(["COMPLETED", "CANCELLED", "FAILED"]);
export const MODE_COMMANDS: CommandPanelMode = "commands";
export const MODE_SEARCH_TASKS: CommandPanelMode = "search-tasks";
export const MODE_SEARCH_FILES: CommandPanelMode = "search-files";
export const MODE_SEARCH_CONTENT: CommandPanelMode = "search-content";
const STEP_COLOR_MAP: Record<string, string> = {
"bg-slate-500": "#64748b",
"bg-red-500": "#ef4444",
"bg-orange-500": "#f97316",
"bg-yellow-500": "#eab308",
"bg-green-500": "#22c55e",
"bg-cyan-500": "#06b6d4",
"bg-blue-500": "#3b82f6",
"bg-indigo-500": "#6366f1",
"bg-purple-500": "#a855f7",
};
function getFileName(filePath: string) {
return filePath.split("/").pop() ?? filePath;
}
export function getTaskResultValue(task: Task) {
return `__task:${task.id} ${task.title}`;
}
export function getFileResultValue(filePath: string) {
return `__file:${filePath}`;
}
export type StepMap = Map<string, { name: string; color: string }>;
function CommandItemRow({
cmd,
onSelect,
}: {
cmd: CommandItemType;
onSelect: (cmd: CommandItemType) => void;
}) {
return (
<CommandItem
key={cmd.id}
value={cmd.id}
keywords={getCommandSearchTerms(cmd)}
onSelect={() => onSelect(cmd)}
>
{cmd.icon && (
<span
className={
cmd.context ? "self-start pt-0.5 text-muted-foreground" : "text-muted-foreground"
}
>
{cmd.icon}
</span>
)}
<span className="min-w-0 flex-1">
<span className="block truncate">{cmd.label}</span>
{cmd.context && (
<span className="block truncate text-[0.625rem] leading-4 text-muted-foreground">
{cmd.context}
</span>
)}
</span>
{cmd.shortcut && <CommandShortcut>{formatShortcut(cmd.shortcut)}</CommandShortcut>}
{cmd.enterMode && (
<span className="ml-auto text-muted-foreground">
<IconArrowRight className="size-3" />
</span>
)}
</CommandItem>
);
}
type TaskResultItemProps = {
task: Task;
stepMap: StepMap;
repoMap: Map<string, string>;
onSelect: (task: Task) => void;
};
function TaskResultItem({ task, stepMap, repoMap, onSelect }: TaskResultItemProps) {
const locale = useDateLocale();
const isArchived = ARCHIVED_STATES.has(task.state);
const step = stepMap.get(task.workflow_step_id);
const stepHex = step ? STEP_COLOR_MAP[step.color] : undefined;
const rawPath =
task.primary_working_directory ??
(task.repositories?.[0] ? repoMap.get(task.repositories[0].repository_id) : undefined);
const workDir = rawPath ? getFileName(rawPath) : undefined;
const details: string[] = [];
if (workDir) details.push(workDir);
if (task.primary_agent_name) details.push(task.primary_agent_name);
if (task.updated_at) {
details.push(formatTimeDistance(task.updated_at, locale));
}
return (
<CommandItem
key={task.id}
value={getTaskResultValue(task)}
onSelect={() => onSelect(task)}
className={isArchived ? "opacity-60" : ""}
forceMount
>
<div className="flex items-center gap-2 min-w-0 w-full">
{isArchived ? (
<IconArchive className="size-3 shrink-0 text-muted-foreground" />
) : (
<IconHammer className="size-3 shrink-0 text-muted-foreground" />
)}
{/* The title identifies the row, so it takes the free space and the
non-shrinking badge and metadata cannot squeeze it away. Metadata is
secondary and steps aside entirely on a phone. */}
<span className="min-w-0 flex-1 truncate font-medium">{task.title}</span>
{step && (
<Badge
variant="secondary"
className="text-[0.6rem] shrink-0"
style={stepHex ? { backgroundColor: stepHex + "22", color: stepHex } : undefined}
>
{step.name}
</Badge>
)}
{details.length > 0 && (
<span className="hidden shrink-0 truncate text-[0.6rem] text-muted-foreground sm:inline">
{details.join(" · ")}
</span>
)}
</div>
</CommandItem>
);
}
type TaskResultGroupProps = {
tasks: Task[];
search: string;
stepMap: StepMap;
repoMap: Map<string, string>;
onSelect: (task: Task) => void;
testId?: string;
};
function TaskResultGroup({
tasks,
search,
stepMap,
repoMap,
onSelect,
testId,
}: TaskResultGroupProps) {
const { t } = useTranslation();
if (tasks.length === 0) return null;
return (
<CommandGroup
heading={search.trim() ? t("common:tasks") : t("common:activeTasks")}
forceMount
data-testid={testId}
>
{tasks.map((task) => (
<TaskResultItem
key={task.id}
task={task}
stepMap={stepMap}
repoMap={repoMap}
onSelect={onSelect}
/>
))}
</CommandGroup>
);
}
function TaskResultsLoader() {
const { t } = useTranslation();
return (
<CommandGroup heading={t("common:activeTasks")} forceMount>
<div className="flex items-center justify-center py-3">
<IconLoader2 className="size-3.5 animate-spin text-muted-foreground" />
</div>
</CommandGroup>
);
}
type CommandsListContentProps = {
commands: CommandItemType[];
grouped: [string, CommandItemType[]][];
search: string;
onSelect: (cmd: CommandItemType) => void;
taskResults: Task[];
isSearching: boolean;
stepMap: StepMap;
repoMap: Map<string, string>;
onTaskSelect: (task: Task) => void;
};
function SearchCommandGroups({
commands,
search,
onSelect,
}: Pick<CommandsListContentProps, "commands" | "search" | "onSelect">) {
const { t } = useTranslation();
const matches = sortCommandsForSearch(commands, search).filter(
(cmd) => scoreCommandSearch(cmd.id, search, getCommandSearchTerms(cmd)) > 0,
);
const regularMatches = matches.filter((cmd) => !cmd.searchOnly);
const searchOnlyGroups = new Map<string, CommandItemType[]>();
for (const cmd of matches) {
if (!cmd.searchOnly) continue;
const groupItems = searchOnlyGroups.get(cmd.group) ?? [];
groupItems.push(cmd);
searchOnlyGroups.set(cmd.group, groupItems);
}
return (
<>
{regularMatches.length > 0 && (
<CommandGroup heading={t("common:commandGroupCommands")}>
{regularMatches.map((cmd) => (
<CommandItemRow key={cmd.id} cmd={cmd} onSelect={onSelect} />
))}
</CommandGroup>
)}
{[...searchOnlyGroups].map(([group, items]) => (
<CommandGroup key={group} heading={group}>
{items.map((cmd) => (
<CommandItemRow key={cmd.id} cmd={cmd} onSelect={onSelect} />
))}
</CommandGroup>
))}
</>
);
}
function IdleCommandGroups({
grouped,
onSelect,
}: Pick<CommandsListContentProps, "grouped" | "onSelect">) {
return (
<>
{grouped.map(([group, items]) => {
const visibleItems = items.filter((cmd) => !cmd.searchOnly);
if (visibleItems.length === 0) return null;
return (
<CommandGroup key={group} heading={group}>
{visibleItems.map((cmd) => (
<CommandItemRow key={cmd.id} cmd={cmd} onSelect={onSelect} />
))}
</CommandGroup>
);
})}
</>
);
}
/**
* The commands scope mixes commands with task rows. Idle, the Active Tasks
* group leads: reopening the palette is usually a jump back to work, and there
* is no query to rank commands against. Once the user types, the ordering
* flips — a typed query is a command query first, so matching commands lead and
* the fuzzy task matches trail as a preview. The Tasks scope owns the full
* task search.
*/
export function CommandsListContent({
commands,
grouped,
search,
onSelect,
taskResults,
isSearching,
stepMap,
repoMap,
onTaskSelect,
}: CommandsListContentProps) {
const { t } = useTranslation();
const hasQuery = Boolean(search.trim());
const hasInlineResults = taskResults.length > 0 || isSearching;
const taskRows = (
<>
{isSearching && taskResults.length === 0 && <TaskResultsLoader />}
<TaskResultGroup
tasks={taskResults}
search={search}
stepMap={stepMap}
repoMap={repoMap}
onSelect={onTaskSelect}
testId="command-panel-task-preview"
/>
</>
);
const commandRows = hasQuery ? (
<SearchCommandGroups commands={commands} search={search} onSelect={onSelect} />
) : (
<IdleCommandGroups grouped={grouped} onSelect={onSelect} />
);
return (
<>
{!hasInlineResults && <CommandEmpty>{t("common:noCommandsFound")}</CommandEmpty>}
{hasQuery ? commandRows : taskRows}
{hasQuery ? taskRows : commandRows}
</>
);
}
type TaskSearchContentProps = {
tasks: Task[];
isSearching: boolean;
search: string;
stepMap: StepMap;
repoMap: Map<string, string>;
onSelect: (task: Task) => void;
};
export function TaskSearchContent({
tasks,
isSearching,
search,
stepMap,
repoMap,
onSelect,
}: TaskSearchContentProps) {
const { t } = useTranslation();
if (isSearching && tasks.length === 0) {
return (
<div className="flex items-center justify-center py-6">
<IconLoader2 className="size-4 animate-spin text-muted-foreground" />
</div>
);
}
if (tasks.length === 0) return <CommandEmpty>{t("common:noTasksFound")}</CommandEmpty>;
return (
<TaskResultGroup
tasks={tasks}
search={search}
stepMap={stepMap}
repoMap={repoMap}
onSelect={onSelect}
testId="command-panel-task-results"
/>
);
}
type FileSearchContentProps = {
files: FileSearchResult[];
isSearching: boolean;
search: string;
sessionId: string | null;
onSelect: (path: string) => void;
};
export function FileSearchContent({
files,
isSearching,
search,
sessionId,
onSelect,
}: FileSearchContentProps) {
const { t } = useTranslation();
const getRepoDisplayName = useRepoDisplayName(sessionId);
if (isSearching && files.length === 0) {
return (
<div className="flex items-center justify-center py-6">
<IconLoader2 className="size-4 animate-spin text-muted-foreground" />
</div>
);
}
if (search.trim() && files.length === 0)
return <CommandEmpty>{t("common:noFilesFound")}</CommandEmpty>;
if (!search.trim()) return <CommandEmpty>{t("common:typeToSearchFiles")}</CommandEmpty>;
const groups = groupByRepositoryName(files, (file) => file.repository_name);
const singleRepo = isSingleRepoGroup(groups);
return groups.map((group) => (
<CommandGroup
key={group.repositoryName || "workspace"}
heading={
singleRepo
? t("common:files")
: (getRepoDisplayName(group.repositoryName) ??
group.repositoryName ??
t("common:workspace"))
}
forceMount
data-testid="file-search-repo-group"
data-repository={group.repositoryName}
>
{group.items.map((file) => {
const repositoryPrefix = file.repository_name ? `${file.repository_name}/` : "";
const displayPath = file.path.startsWith(repositoryPrefix)
? file.path.slice(repositoryPrefix.length)
: file.path;
const fileName = getFileName(displayPath);
const lastSlash = displayPath.lastIndexOf("/");
const dir = lastSlash > 0 ? displayPath.slice(0, lastSlash) : "";
return (
<CommandItem
key={file.path}
value={getFileResultValue(file.path)}
onSelect={() => onSelect(file.path)}
forceMount
>
<FileIcon fileName={fileName} className="shrink-0" />
<span className="truncate font-medium">{fileName}</span>
{dir && <span className="ml-1 truncate text-xs text-muted-foreground">{dir}</span>}
</CommandItem>
);
})}
</CommandGroup>
));
}
@@ -8,7 +8,7 @@ import { formatShortcut } from "@/lib/keyboard/utils";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";
export type CommandPanelScopeMode = "commands" | "search-files" | "search-content";
export type CommandPanelScopeMode = "commands" | "search-tasks" | "search-files" | "search-content";
type ScopeOption = {
mode: CommandPanelScopeMode;
@@ -18,16 +18,26 @@ type ScopeOption = {
* threaded through the command-panel state.
*/
labelKey: string;
shortcutId: ConfigurableShortcutId;
/** Omitted for scopes that are reachable by click and Tab but unbound. */
shortcutId?: ConfigurableShortcutId;
/** Scopes that read a checked-out worktree, so they need an open session. */
requiresWorkspace?: boolean;
};
const SCOPE_OPTIONS: ScopeOption[] = [
{ mode: "commands", labelKey: "common:scopeCommands", shortcutId: "SEARCH" },
{ mode: "search-files", labelKey: "common:scopeFiles", shortcutId: "FILE_SEARCH" },
{ mode: "search-tasks", labelKey: "common:scopeTasks" },
{
mode: "search-files",
labelKey: "common:scopeFiles",
shortcutId: "FILE_SEARCH",
requiresWorkspace: true,
},
{
mode: "search-content",
labelKey: "common:scopeContents",
shortcutId: "CONTENT_SEARCH",
requiresWorkspace: true,
},
];
@@ -35,22 +45,37 @@ export function isCommandPanelScopeMode(mode: CommandPanelMode): mode is Command
return SCOPE_OPTIONS.some((scope) => scope.mode === mode);
}
function availableScopes(workspaceSearchAvailable: boolean): ScopeOption[] {
return SCOPE_OPTIONS.filter((scope) => workspaceSearchAvailable || !scope.requiresWorkspace);
}
/** Commands and Tasks are always reachable, so the switcher always has tabs. */
export function getAvailableCommandPanelScopes(
workspaceSearchAvailable: boolean,
): CommandPanelScopeMode[] {
return availableScopes(workspaceSearchAvailable).map((scope) => scope.mode);
}
export function getAdjacentCommandPanelScope(
mode: CommandPanelScopeMode,
reverse = false,
workspaceSearchAvailable = true,
): CommandPanelScopeMode {
const currentIndex = SCOPE_OPTIONS.findIndex((scope) => scope.mode === mode);
const scopes = availableScopes(workspaceSearchAvailable);
const currentIndex = scopes.findIndex((scope) => scope.mode === mode);
const offset = reverse ? -1 : 1;
const nextIndex = (currentIndex + offset + SCOPE_OPTIONS.length) % SCOPE_OPTIONS.length;
return SCOPE_OPTIONS[nextIndex].mode;
const nextIndex = (currentIndex + offset + scopes.length) % scopes.length;
return scopes[nextIndex].mode;
}
export function CommandPanelScopeSwitcher({
mode,
onScopeChange,
workspaceSearchAvailable,
}: {
mode: CommandPanelScopeMode;
onScopeChange: (mode: CommandPanelScopeMode) => void;
workspaceSearchAvailable: boolean;
}) {
const { t } = useTranslation();
const keyboardShortcuts = useAppStore((state) => state.userSettings.keyboardShortcuts);
@@ -59,11 +84,13 @@ export function CommandPanelScopeSwitcher({
<div
role="tablist"
aria-label={t("common:commandPaletteMode")}
className="mr-1 flex h-10 shrink-0 items-stretch gap-0.5"
className="mr-1 flex h-10 max-w-full shrink-0 items-stretch gap-0.5 overflow-x-auto"
>
{SCOPE_OPTIONS.map((scope) => {
{availableScopes(workspaceSearchAvailable).map((scope) => {
const active = mode === scope.mode;
const shortcut = formatShortcut(getShortcut(scope.shortcutId, keyboardShortcuts));
const shortcut = scope.shortcutId
? formatShortcut(getShortcut(scope.shortcutId, keyboardShortcuts))
: null;
const label = t(scope.labelKey);
return (
<button
@@ -73,7 +100,7 @@ export function CommandPanelScopeSwitcher({
aria-label={label}
aria-selected={active}
tabIndex={-1}
title={t("common:scopeTitleWithShortcut", { label, shortcut })}
title={shortcut ? t("common:scopeTitleWithShortcut", { label, shortcut }) : label}
onMouseDown={(event) => event.preventDefault()}
onClick={() => onScopeChange(scope.mode)}
className={cn(
+30 -159
View File
@@ -4,11 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { usePathname } from "@/lib/routing/client-router";
import { useCommands, useCommandPanelOpen } from "@/lib/commands/command-registry";
import type { CommandPanelMode, CommandItem as CommandItemType } from "@/lib/commands/types";
import {
findFirstMatchingCommand,
selectCommandSearchResult,
selectContentSearchResult,
} from "@/lib/commands/search";
import { selectCommandSearchResult, selectContentSearchResult } from "@/lib/commands/search";
import { useCommandPanelShortcuts } from "@/hooks/use-command-panel-shortcuts";
import { useContentSearchResultOpener } from "@/hooks/use-content-search-result-opener";
import { useWorkspaceContentSearch } from "@/hooks/domains/session/use-workspace-content-search";
@@ -18,7 +14,6 @@ import {
type CommandPanelScopeMode,
} from "@/components/command-panel-scope-switcher";
import { listTasksByWorkspace } from "@/lib/api";
import type { Task } from "@/lib/types/http";
import type { FileSearchResult } from "@/lib/types/backend";
import { getWebSocketClient } from "@/lib/ws/connection";
@@ -28,11 +23,13 @@ import { getContentSearchResultValue } from "@/components/workspace-content-sear
import { getFileName } from "@/lib/utils/file-path";
import { isTaskWorkspaceSearchAvailable } from "@/lib/commands/task-workspace-search";
import { useCommandPanelTaskNavigation } from "@/hooks/use-command-panel-task-navigation";
import { useInlineTaskSearchEffect } from "@/hooks/use-command-panel-task-results";
import {
CommandPanelView,
MODE_COMMANDS,
MODE_SEARCH_CONTENT,
MODE_SEARCH_FILES,
MODE_SEARCH_TASKS,
getFileResultValue,
getTaskResultValue,
} from "@/components/command-panel-footer";
@@ -132,138 +129,6 @@ function useFileSearchEffect(opts: FileSearchEffectOptions) {
]);
}
const ARCHIVED_STATES = new Set(["COMPLETED", "CANCELLED", "FAILED"]);
function resolveVisibleStepIds(steps: { id: string; show_in_command_panel?: boolean }[]) {
if (steps.length === 0) return null; // no steps loaded yet — don't filter
return new Set(steps.filter((s) => s.show_in_command_panel !== false).map((s) => s.id));
}
type InlineTaskSearchOptions = {
mode: CommandPanelMode;
search: string;
open: boolean;
workspaceId: string | null;
steps: { id: string; position: number; show_in_command_panel?: boolean }[];
setTaskResults: (tasks: Task[]) => void;
setIsSearching: (searching: boolean) => void;
};
function useStepMaps(steps: InlineTaskSearchOptions["steps"]) {
const visibleStepIds = useMemo(() => resolveVisibleStepIds(steps), [steps]);
const stepPositionMap = useMemo(() => {
const map = new Map<string, number>();
for (const step of steps) map.set(step.id, step.position);
return map;
}, [steps]);
return { visibleStepIds, stepPositionMap };
}
function useInlineTaskSearchEffect(opts: InlineTaskSearchOptions) {
const { mode, search, open, workspaceId, steps, setTaskResults, setIsSearching } = opts;
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const abortRef = useRef<AbortController | null>(null);
const { visibleStepIds, stepPositionMap } = useStepMaps(steps);
useEffect(() => {
if (mode !== MODE_COMMANDS) return;
if (debounceRef.current) clearTimeout(debounceRef.current);
abortRef.current?.abort();
// No search: load active tasks (excluding backlog + done steps)
if (!search.trim()) {
if (!open || !workspaceId) {
setTaskResults([]);
setIsSearching(false);
return;
}
setIsSearching(true);
const controller = new AbortController();
abortRef.current = controller;
listTasksByWorkspace(
workspaceId,
{ page: 1, pageSize: 20 },
{ init: { signal: controller.signal } },
)
.then((res) => {
if (controller.signal.aborted) return;
const tasks = (res.tasks ?? []).filter(
(t) =>
(!visibleStepIds || visibleStepIds.has(t.workflow_step_id)) &&
!ARCHIVED_STATES.has(t.state),
);
tasks.sort(
(a, b) =>
(stepPositionMap.get(a.workflow_step_id) ?? 99) -
(stepPositionMap.get(b.workflow_step_id) ?? 99),
);
setTaskResults(tasks);
})
.catch(() => {
if (!controller.signal.aborted) setTaskResults([]);
})
.finally(() => {
if (!controller.signal.aborted) setIsSearching(false);
});
return () => {
controller.abort();
};
}
// Search with < 2 chars: clear results
if (search.trim().length < 2) {
setTaskResults([]);
setIsSearching(false);
return;
}
// Search: query API including archived
setIsSearching(true);
debounceRef.current = setTimeout(async () => {
if (!workspaceId) {
setIsSearching(false);
return;
}
const controller = new AbortController();
abortRef.current = controller;
try {
const res = await listTasksByWorkspace(
workspaceId,
{ query: search.trim(), page: 1, pageSize: 5, includeArchived: true },
{ init: { signal: controller.signal } },
);
if (!controller.signal.aborted) {
const tasks = res.tasks ?? [];
tasks.sort((a, b) => {
const aArchived = ARCHIVED_STATES.has(a.state) ? 1 : 0;
const bArchived = ARCHIVED_STATES.has(b.state) ? 1 : 0;
return aArchived - bArchived;
});
setTaskResults(tasks);
}
} catch {
if (!controller.signal.aborted) setTaskResults([]);
} finally {
if (!controller.signal.aborted) setIsSearching(false);
}
}, 300);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
abortRef.current?.abort();
};
}, [
mode,
search,
open,
workspaceId,
visibleStepIds,
stepPositionMap,
setTaskResults,
setIsSearching,
]);
}
type CommandPanelEffectsOptions = {
open: boolean;
state: ReturnType<typeof useCommandPanelState>;
@@ -356,32 +221,38 @@ function useFirstResultSelection(
contentResults: ReturnType<typeof useWorkspaceContentSearch>["results"],
) {
const { mode, search, taskResults, fileResults, setSelectedValue } = state;
const previousCommandsRef = useRef(commands);
// `search` intentionally re-applies the first result while debounced results are loading.
// Every branch is a functional update, so a re-registration of the command
// list or a late batch of results never discards a selection the user moved.
useEffect(() => {
const commandsChanged = previousCommandsRef.current !== commands;
previousCommandsRef.current = commands;
if (!open) return;
if (mode === MODE_COMMANDS) {
const firstTask = taskResults[0];
if (commandsChanged) {
const taskValues = taskResults.map(getTaskResultValue);
setSelectedValue((current) =>
selectCommandSearchResult(commands, search, taskValues, current),
);
return;
}
if (firstTask) {
setSelectedValue(getTaskResultValue(firstTask));
return;
}
if (search.trim()) {
setSelectedValue(findFirstMatchingCommand(commands, search)?.id ?? "");
return;
}
setSelectedValue((current) => (current.startsWith("__task:") ? "" : current));
// Matching commands render above the task preview once there is a query,
// so the default highlight has to follow that order: Enter on "archive"
// must run the Archive command, not the first task the query fuzzy-matched.
// Task results arrive 300ms behind the keystroke, so this stays a
// functional update: a row the user arrow-keyed to in the meantime must
// survive the results landing rather than snap back to the default.
const commandsLeadResults = Boolean(search.trim());
const taskResultValues = taskResults.map(getTaskResultValue);
setSelectedValue((current) =>
selectCommandSearchResult({
commands,
search,
taskResultValues,
preferredValue: current,
commandsLeadResults,
}),
);
return;
}
if (mode === MODE_SEARCH_TASKS) {
const taskResultValues = taskResults.map(getTaskResultValue);
setSelectedValue((current) =>
current && taskResultValues.includes(current) ? current : (taskResultValues[0] ?? ""),
);
return;
}
+5 -2
View File
@@ -300,8 +300,11 @@ test.describe("Command Panel", () => {
// Type the task name — task search requires ≥2 characters
await dialog.locator("input").fill("Searchable");
// Should show the task in a "Tasks" group (inline search, debounced)
await expect(dialog.getByText("Tasks")).toBeVisible({ timeout: 10_000 });
// Should show the task in a "Tasks" group (inline search, debounced).
// Scope the heading lookup: "Tasks" is also the label of the Tasks tab.
await expect(dialog.getByTestId("command-panel-task-preview")).toBeVisible({
timeout: 10_000,
});
await expect(dialog.getByText("Searchable E2E Task")).toBeVisible({ timeout: 5_000 });
});
@@ -0,0 +1,64 @@
import { test, expect } from "../../fixtures/test-base";
import { SessionPage } from "../../pages/session-page";
/**
* The palette's scope strip does not shrink. With four scopes it no longer fits
* beside the search field on a phone, so it has to wrap onto its own row rather
* than squeeze the query out of view.
*/
const MODIFIER = process.platform === "darwin" ? "Meta" : "Control";
const QUERY = "a reasonably long typed query";
test("@search the palette scope strip wraps below the field on a phone", async ({
testPage,
apiClient,
seedData,
}) => {
test.setTimeout(120_000);
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
"Mobile palette scopes",
seedData.agentProfileId,
{
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
await testPage.goto(`/t/${task.id}`);
await new SessionPage(testPage).waitForLoad();
await testPage.keyboard.press(`${MODIFIER}+k`);
const dialog = testPage.getByRole("dialog");
await expect(dialog).toBeVisible({ timeout: 10_000 });
const input = dialog.getByRole("combobox");
await input.fill(QUERY);
await expect(input).toHaveValue(QUERY);
const tablist = dialog.getByRole("tablist", { name: "Command palette mode" });
await expect(tablist.getByRole("tab")).toHaveCount(4);
const inputBox = (await input.boundingBox())!;
const tablistBox = (await tablist.boundingBox())!;
const dialogBox = (await dialog.boundingBox())!;
// The strip is on a row of its own, under the field.
expect(tablistBox.y).toBeGreaterThanOrEqual(inputBox.y + inputBox.height);
// The field keeps most of the dialog rather than collapsing to a few characters.
expect(inputBox.width).toBeGreaterThan(dialogBox.width * 0.6);
// Neither row pushes the document wider than the viewport.
const overflows = await testPage.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(overflows).toBe(false);
// A task row keeps its title on a narrow screen; the metadata is what yields.
await input.fill("Mobile palette scopes");
const taskRow = dialog.getByRole("option").filter({ hasText: "Mobile palette scopes" });
await expect(taskRow.first()).toBeVisible({ timeout: 15_000 });
const titleBox = (await taskRow.first().getByText("Mobile palette scopes").boundingBox())!;
expect(titleBox.width).toBeGreaterThan(60);
});
@@ -40,8 +40,13 @@ test("@search keeps workspace modes out of non-task routes", async ({ testPage }
await testPage.keyboard.press(`${MODIFIER}+k`);
await expect(dialog).toBeVisible();
await expect(dialog.getByRole("tablist", { name: "Command palette mode" })).toHaveCount(0);
await expect(dialog).not.toContainText("Switch mode");
// Commands and Tasks read no worktree, so they stay reachable off a task
// route; Files and Contents are the ones that must not appear.
await expect(
dialog.getByRole("tablist", { name: "Command palette mode" }).getByRole("tab"),
).toHaveText(["Commands", "Tasks"]);
await expect(dialog.getByRole("tab", { name: "Files" })).toHaveCount(0);
await expect(dialog.getByRole("tab", { name: "Contents" })).toHaveCount(0);
});
test("@search searches all task repositories and opens the selected match", async ({
@@ -113,6 +118,7 @@ test("@search searches all task repositories and opens the selected match", asyn
).toHaveCount(1);
const commandsTab = dialog.getByRole("tab", { name: "Commands" });
const tasksTab = dialog.getByRole("tab", { name: "Tasks" });
const filesTab = dialog.getByRole("tab", { name: "Files" });
const contentsTab = dialog.getByRole("tab", { name: "Contents" });
await expect(contentsTab).toHaveAttribute("aria-selected", "true");
@@ -122,6 +128,10 @@ test("@search searches all task repositories and opens the selected match", asyn
await expect(input).toHaveValue(SEARCH_TERM);
await expect(commandsTab).toHaveAttribute("aria-selected", "true");
await testPage.keyboard.press("Tab");
await expect(tasksTab).toHaveAttribute("aria-selected", "true");
await expect(input).toHaveValue(SEARCH_TERM);
await testPage.keyboard.press("Tab");
await expect(filesTab).toHaveAttribute("aria-selected", "true");
await expect(input).toHaveValue(SEARCH_TERM);
@@ -51,7 +51,11 @@ test.describe("Command palette archive", () => {
.getByRole("option")
.filter({ has: testPage.getByText("Archive task", { exact: true }) });
await expect(option).toBeVisible();
await option.click();
// Matching commands rank above the task rows a query also fuzzy-matches, so
// the exact command is what Enter runs without any arrow-key navigation.
await expect(option).toHaveAttribute("aria-selected", "true");
await expect(dialog.getByRole("option").first()).toContainText("Archive task");
await testPage.keyboard.press("Enter");
// The shared confirmation dialog names the task being archived.
const confirm = testPage.getByRole("alertdialog");
@@ -0,0 +1,89 @@
import { renderHook, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
const listTasksByWorkspace = vi.fn();
vi.mock("@/lib/api", () => ({
listTasksByWorkspace: (...args: unknown[]) => listTasksByWorkspace(...args),
}));
import { useInlineTaskSearchEffect } from "./use-command-panel-task-results";
import type { Task } from "@/lib/types/http";
import { taskId, workflowId, workspaceId } from "@/lib/types/ids";
function task(id: string, title: string): Task {
return {
id: taskId(id),
workspace_id: workspaceId("workspace-1"),
workflow_id: workflowId("workflow-1"),
workflow_step_id: "step-1",
position: 0,
title,
description: "",
state: "IN_PROGRESS",
priority: "medium",
created_at: "2026-08-24T09:00:00Z",
updated_at: "2026-08-24T09:00:00Z",
};
}
const STEPS = [{ id: "step-1", position: 0, show_in_command_panel: true }];
function harness(setTaskResults: (t: Task[]) => void, setIsSearching: (s: boolean) => void) {
return renderHook(
({ mode }: { mode: "commands" | "search-tasks" }) =>
useInlineTaskSearchEffect({
mode,
search: "",
open: true,
workspaceId: "workspace-1",
steps: STEPS,
setTaskResults,
setIsSearching,
}),
{ initialProps: { mode: "commands" } as { mode: "commands" | "search-tasks" } },
);
}
afterEach(() => {
listTasksByWorkspace.mockReset();
});
describe("useInlineTaskSearchEffect", () => {
it("caps the commands scope at a five-row preview and the tasks scope at twenty", async () => {
const many = Array.from({ length: 20 }, (_, i) => task(`task-${i}`, `Task ${i}`));
listTasksByWorkspace.mockResolvedValue({ tasks: many });
const setTaskResults = vi.fn();
const { rerender } = harness(setTaskResults, vi.fn());
await waitFor(() => expect(setTaskResults).toHaveBeenCalledWith(many.slice(0, 5)));
setTaskResults.mockClear();
rerender({ mode: "search-tasks" });
await waitFor(() => expect(setTaskResults).toHaveBeenCalledWith(many));
});
it("drops the previous scope's results when the scope changes", async () => {
listTasksByWorkspace.mockResolvedValue({ tasks: [task("task-1", "Only task")] });
const setTaskResults = vi.fn();
const { rerender } = harness(setTaskResults, vi.fn());
await waitFor(() => expect(setTaskResults).toHaveBeenCalled());
setTaskResults.mockClear();
rerender({ mode: "search-tasks" });
// The five-row preview must not stand in as the tasks scope's full result
// set (nor suppress its loading state) while the wider request is in flight.
expect(setTaskResults).toHaveBeenNthCalledWith(1, []);
});
it("keeps results when the scope is unchanged", async () => {
listTasksByWorkspace.mockResolvedValue({ tasks: [task("task-1", "Only task")] });
const setTaskResults = vi.fn();
const { rerender } = harness(setTaskResults, vi.fn());
await waitFor(() => expect(setTaskResults).toHaveBeenCalled());
setTaskResults.mockClear();
rerender({ mode: "commands" });
expect(setTaskResults).not.toHaveBeenCalledWith([]);
});
});
@@ -0,0 +1,188 @@
"use client";
import { useEffect, useMemo, useRef } from "react";
import { listTasksByWorkspace } from "@/lib/api";
import type { CommandPanelMode } from "@/lib/commands/types";
import type { Task } from "@/lib/types/http";
import { MODE_COMMANDS, MODE_SEARCH_TASKS } from "@/components/command-panel-results";
const ARCHIVED_STATES = new Set(["COMPLETED", "CANCELLED", "FAILED"]);
/** Task rows previewed alongside the commands in the commands scope. */
const TASK_PREVIEW_SIZE = 5;
/** Task rows listed in the dedicated tasks scope. */
const TASK_SCOPE_PAGE_SIZE = 20;
function resolveVisibleStepIds(steps: { id: string; show_in_command_panel?: boolean }[]) {
if (steps.length === 0) return null; // no steps loaded yet — don't filter
return new Set(steps.filter((s) => s.show_in_command_panel !== false).map((s) => s.id));
}
type InlineTaskSearchOptions = {
mode: CommandPanelMode;
search: string;
open: boolean;
workspaceId: string | null;
steps: { id: string; position: number; show_in_command_panel?: boolean }[];
setTaskResults: (tasks: Task[]) => void;
setIsSearching: (searching: boolean) => void;
};
function useStepMaps(steps: InlineTaskSearchOptions["steps"]) {
const visibleStepIds = useMemo(() => resolveVisibleStepIds(steps), [steps]);
const stepPositionMap = useMemo(() => {
const map = new Map<string, number>();
for (const step of steps) map.set(step.id, step.position);
return map;
}, [steps]);
return { visibleStepIds, stepPositionMap };
}
type ActiveTaskQuery = {
workspaceId: string;
signal: AbortSignal;
visibleStepIds: Set<string> | null;
stepPositionMap: Map<string, number>;
resultLimit: number;
};
/** Active tasks for the idle palette: no backlog or done steps, workflow order. */
async function fetchActiveTasks(query: ActiveTaskQuery): Promise<Task[]> {
const { workspaceId, signal, visibleStepIds, stepPositionMap, resultLimit } = query;
// Deliberately over-fetched: the step and archived filters below run on the
// response, so requesting only `resultLimit` rows would show fewer active
// tasks than exist whenever the first page is mostly backlog or done.
const res = await listTasksByWorkspace(
workspaceId,
{ page: 1, pageSize: TASK_SCOPE_PAGE_SIZE },
{ init: { signal } },
);
const tasks = (res.tasks ?? []).filter(
(t) =>
(!visibleStepIds || visibleStepIds.has(t.workflow_step_id)) && !ARCHIVED_STATES.has(t.state),
);
tasks.sort(
(a, b) =>
(stepPositionMap.get(a.workflow_step_id) ?? 99) -
(stepPositionMap.get(b.workflow_step_id) ?? 99),
);
return tasks.slice(0, resultLimit);
}
/** Task search results, archived matches last. */
async function fetchMatchingTasks(
workspaceId: string,
query: string,
resultLimit: number,
signal: AbortSignal,
): Promise<Task[]> {
const res = await listTasksByWorkspace(
workspaceId,
{ query, page: 1, pageSize: resultLimit, includeArchived: true },
{ init: { signal } },
);
const tasks = res.tasks ?? [];
tasks.sort(
(a, b) => (ARCHIVED_STATES.has(a.state) ? 1 : 0) - (ARCHIVED_STATES.has(b.state) ? 1 : 0),
);
return tasks;
}
export function useInlineTaskSearchEffect(opts: InlineTaskSearchOptions) {
const { mode, search, open, workspaceId, steps, setTaskResults, setIsSearching } = opts;
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const abortRef = useRef<AbortController | null>(null);
const taskScopeRef = useRef(mode);
const { visibleStepIds, stepPositionMap } = useStepMaps(steps);
useEffect(() => {
if (mode !== MODE_COMMANDS && mode !== MODE_SEARCH_TASKS) return;
// The commands scope only previews tasks alongside the commands; the tasks
// scope is the one that lists the full result set.
const resultLimit = mode === MODE_SEARCH_TASKS ? TASK_SCOPE_PAGE_SIZE : TASK_PREVIEW_SIZE;
// The two scopes size their result sets differently, so carrying one over
// would present a five-row preview as the tasks scope's full result set
// (and suppress its loading state) until the wider request lands.
if (taskScopeRef.current !== mode) {
taskScopeRef.current = mode;
setTaskResults([]);
}
if (debounceRef.current) clearTimeout(debounceRef.current);
abortRef.current?.abort();
// No search: load active tasks (excluding backlog + done steps)
if (!search.trim()) {
if (!open || !workspaceId) {
setTaskResults([]);
setIsSearching(false);
return;
}
setIsSearching(true);
const controller = new AbortController();
abortRef.current = controller;
fetchActiveTasks({
workspaceId,
signal: controller.signal,
visibleStepIds,
stepPositionMap,
resultLimit,
})
.then((tasks) => {
if (!controller.signal.aborted) setTaskResults(tasks);
})
.catch(() => {
if (!controller.signal.aborted) setTaskResults([]);
})
.finally(() => {
if (!controller.signal.aborted) setIsSearching(false);
});
return () => {
controller.abort();
};
}
// Search with < 2 chars: clear results
if (search.trim().length < 2) {
setTaskResults([]);
setIsSearching(false);
return;
}
// Search: query API including archived
setIsSearching(true);
debounceRef.current = setTimeout(async () => {
if (!workspaceId) {
setIsSearching(false);
return;
}
const controller = new AbortController();
abortRef.current = controller;
try {
const tasks = await fetchMatchingTasks(
workspaceId,
search.trim(),
resultLimit,
controller.signal,
);
if (!controller.signal.aborted) setTaskResults(tasks);
} catch {
if (!controller.signal.aborted) setTaskResults([]);
} finally {
if (!controller.signal.aborted) setIsSearching(false);
}
}, 300);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
abortRef.current?.abort();
};
}, [
mode,
search,
open,
workspaceId,
visibleStepIds,
stepPositionMap,
setTaskResults,
setIsSearching,
]);
}
+68 -5
View File
@@ -89,18 +89,81 @@ describe("command search", () => {
expect(findFirstMatchingCommand([first, selected], "shared", selected.id)).toBe(selected);
});
it("returns no command when nothing matches", () => {
expect(findFirstMatchingCommand([command("home", "Go Home")], "terminal")).toBeUndefined();
});
});
describe("selectCommandSearchResult", () => {
it("preserves a matching command when task results lead the palette", () => {
const first = command("first", SHARED_TERM, [], 0);
const selected = command("selected", SHARED_TERM, [], 10);
const taskValue = "__task:task-1 Shared task";
expect(selectCommandSearchResult([first, selected], "shared", [taskValue], selected.id)).toBe(
selected.id,
);
expect(
selectCommandSearchResult({
commands: [first, selected],
search: "shared",
taskResultValues: [taskValue],
preferredValue: selected.id,
commandsLeadResults: false,
}),
).toBe(selected.id);
});
it("returns no command when nothing matches", () => {
expect(findFirstMatchingCommand([command("home", "Go Home")], "terminal")).toBeUndefined();
it("highlights the best command match when a query puts commands first", () => {
const archive = command("task-archive", "Archive task", ["archive"], 0);
const taskValue = "__task:task-1 Close every remaining archive item";
expect(
selectCommandSearchResult({
commands: [archive],
search: "archive",
taskResultValues: [taskValue],
commandsLeadResults: true,
}),
).toBe(archive.id);
});
it("falls back to the first task when a query matches no command", () => {
const taskValue = "__task:task-1 Shared task";
expect(
selectCommandSearchResult({
commands: [command("unrelated", "Go Home")],
search: "shared",
taskResultValues: [taskValue],
commandsLeadResults: true,
}),
).toBe(taskValue);
});
it("leads with the active task list while nothing is typed", () => {
const taskValue = "__task:task-1 Shared task";
expect(
selectCommandSearchResult({
commands: [command("first", SHARED_TERM, [], 0)],
search: "",
taskResultValues: [taskValue],
commandsLeadResults: false,
}),
).toBe(taskValue);
});
it("keeps a task the user highlighted below the command matches", () => {
const archive = command("task-archive", "Archive task", ["archive"], 0);
const taskValue = "__task:task-1 Archive audit";
expect(
selectCommandSearchResult({
commands: [archive],
search: "archive",
taskResultValues: [taskValue],
preferredValue: taskValue,
commandsLeadResults: true,
}),
).toBe(taskValue);
});
});
+28 -10
View File
@@ -81,15 +81,31 @@ export function selectContentSearchResult(resultValues: string[], preferredValue
return resultValues[0] ?? "";
}
export function selectCommandSearchResult(
commands: CommandItem[],
search: string,
leadingResultValues: string[],
preferredValue?: string,
): string {
export type CommandSearchSelectionOptions = {
commands: CommandItem[];
search: string;
/** Values of the task rows rendered alongside the commands, in list order. */
taskResultValues: string[];
preferredValue?: string;
/**
* True while matching commands render above the task rows. The palette only
* leads with tasks when nothing has been typed: once there is a query, an
* exact command match outranks a fuzzy task match.
*/
commandsLeadResults: boolean;
};
/**
* Picks the highlighted row for the commands scope, which mixes commands with
* task rows. The default highlight follows the rendered order so Enter always
* runs the row the user is looking at, and a selection the user moved survives
* a command re-registration as long as its row is still rendered.
*/
export function selectCommandSearchResult(options: CommandSearchSelectionOptions): string {
const { commands, search, taskResultValues, preferredValue, commandsLeadResults } = options;
const normalizedSearch = search.trim();
if (preferredValue) {
if (leadingResultValues.includes(preferredValue)) return preferredValue;
if (taskResultValues.includes(preferredValue)) return preferredValue;
const preferredCommand = commands.find((command) => command.id === preferredValue);
const preferredCommandStillVisible =
preferredCommand &&
@@ -99,7 +115,9 @@ export function selectCommandSearchResult(
if (preferredCommandStillVisible) return preferredValue;
}
const firstLeadingResult = leadingResultValues[0];
if (firstLeadingResult) return firstLeadingResult;
return normalizedSearch ? (findFirstMatchingCommand(commands, normalizedSearch)?.id ?? "") : "";
const firstCommand = normalizedSearch
? (findFirstMatchingCommand(commands, normalizedSearch)?.id ?? "")
: "";
const firstTask = taskResultValues[0] ?? "";
return commandsLeadResults ? firstCommand || firstTask : firstTask || firstCommand;
}
+2
View File
@@ -263,6 +263,7 @@
"noFilesFound": "No files found.",
"noFoldersHerePickThisOne": "No folders here; pick this one or go up",
"noResults": "No results.",
"noTasksFound": "No tasks found.",
"notificationClarificationBody": "The agent asked a question.",
"notificationClarificationTitle": "Agent needs your answer",
"notificationInboxItemBody": "A new item needs your attention.",
@@ -360,6 +361,7 @@
"scopeCommands": "Commands",
"scopeContents": "Contents",
"scopeFiles": "Files",
"scopeTasks": "Tasks",
"scopeTitleWithShortcut": "{{label}} ({{shortcut}})",
"scratchWorkspace": "scratch workspace",
"script": "Script",
+2
View File
@@ -263,6 +263,7 @@
"noFilesFound": "Ńō ƒĩĺēś ƒōũńď.",
"noFoldersHerePickThisOne": "Ńō ƒōĺďēŕś ĥēŕē; ƥĩćķ ţĥĩś ōńē ōŕ ĝō ũƥ",
"noResults": "Ńō ŕēśũĺţś.",
"noTasksFound": "Ńō ţàśķś ƒōũńď.",
"notificationClarificationBody": "Ţĥē àĝēńţ àśķēď à qũēśţĩōń.",
"notificationClarificationTitle": "Àĝēńţ ńēēďś ŷōũŕ àńśŵēŕ",
"notificationInboxItemBody": "À ńēŵ ĩţēḿ ńēēďś ŷōũŕ àţţēńţĩōń.",
@@ -360,6 +361,7 @@
"scopeCommands": "Ćōḿḿàńďś",
"scopeContents": "Ćōńţēńţś",
"scopeFiles": "Ƒĩĺēś",
"scopeTasks": "Ţàśķś",
"scopeTitleWithShortcut": "{{label}} ({{shortcut}})",
"scratchWorkspace": "śćŕàţćĥ ŵōŕķśƥàćē",
"script": "Śćŕĩƥţ",
+2
View File
@@ -259,6 +259,7 @@
"noFilesFound": "Nenhum ficheiro encontrado.",
"noFoldersHerePickThisOne": "Não há pastas aqui; escolha esta ou suba um nível",
"noResults": "Sem resultados.",
"noTasksFound": "Nenhuma tarefa encontrada.",
"notificationClarificationBody": "O agente fez uma pergunta.",
"notificationClarificationTitle": "O agente precisa da sua resposta",
"notificationInboxItemBody": "Um novo item precisa da sua atenção.",
@@ -353,6 +354,7 @@
"scopeCommands": "Comandos",
"scopeContents": "Conteúdos",
"scopeFiles": "Ficheiros",
"scopeTasks": "Tarefas",
"scopeTitleWithShortcut": "{{label}} ({{shortcut}})",
"scratchWorkspace": "área de trabalho temporária",
"script": "Script",
+2
View File
@@ -258,6 +258,7 @@
"noFilesFound": "未找到文件。",
"noFoldersHerePickThisOne": "此处没有文件夹;选择此项或返回上级",
"noResults": "无结果。",
"noTasksFound": "未找到任务。",
"notificationClarificationBody": "智能体提出了一个问题。",
"notificationClarificationTitle": "智能体需要您的回答",
"notificationInboxItemBody": "有新条目需要您处理。",
@@ -354,6 +355,7 @@
"scopeCommands": "命令",
"scopeContents": "内容",
"scopeFiles": "文件",
"scopeTasks": "任务",
"scopeTitleWithShortcut": "{{label}}({{shortcut}})",
"scratchWorkspace": "临时工作区",
"script": "脚本",
+2
View File
@@ -258,6 +258,7 @@
"noFilesFound": "未找到檔案。",
"noFoldersHerePickThisOne": "此處沒有資料夾;選擇此項或返回上級",
"noResults": "無結果。",
"noTasksFound": "未找到任務。",
"notificationClarificationBody": "代理程式提出了一個問題。",
"notificationClarificationTitle": "代理程式需要您的回答",
"notificationInboxItemBody": "有新條目需要您處理。",
@@ -354,6 +355,7 @@
"scopeCommands": "命令",
"scopeContents": "內容",
"scopeFiles": "檔案",
"scopeTasks": "任務",
"scopeTitleWithShortcut": "{{label}}({{shortcut}})",
"scratchWorkspace": "臨時工作區",
"script": "腳本",
+2
View File
@@ -258,6 +258,7 @@
"noFilesFound": "未找到檔案。",
"noFoldersHerePickThisOne": "此處沒有資料夾;選擇此項或返回上級",
"noResults": "無結果。",
"noTasksFound": "未找到任務。",
"notificationClarificationBody": "代理程式提出了一個問題。",
"notificationClarificationTitle": "代理程式需要您的回答",
"notificationInboxItemBody": "有新條目需要您處理。",
@@ -354,6 +355,7 @@
"scopeCommands": "命令",
"scopeContents": "內容",
"scopeFiles": "檔案",
"scopeTasks": "任務",
"scopeTitleWithShortcut": "{{label}}({{shortcut}})",
"scratchWorkspace": "臨時工作區",
"script": "指令碼",
@@ -44,17 +44,37 @@ repositories.
- The shortcut works while a workbench editor or text input has focus and takes
precedence over that surface's local find shortcut. It prevents the browser's
default search action.
- The command palette visibly exposes **Commands**, **Files**, and **Contents**
as low-chrome text tabs beside the search field. The active mode uses a subtle
underline, and each mode's direct shortcut remains discoverable from its
tooltip without adding a separate selector row.
- The command palette visibly exposes **Commands**, **Tasks**, **Files**, and
**Contents** as low-chrome text tabs beside the search field. The active mode
uses a subtle underline, and a mode with a direct shortcut keeps that shortcut
discoverable from its tooltip without adding a separate selector row.
**Tasks** has no direct shortcut and is reached by click or **Tab**.
- **Files** and **Contents** are available only on the active task-detail route
when its selected session belongs to that task. Elsewhere the palette is
command-only, does not intercept either workspace-search shortcut, and
normalizes a previously open workspace-search palette back to **Commands**.
- Clicking a mode or pressing **Tab** / **Shift+Tab** switches among those modes
without discarding the current query. The existing **Cmd/Ctrl+Shift+K**
shortcut still opens file-name and path search directly.
when its selected session belongs to that task. Elsewhere they are absent, the
palette does not intercept either workspace-search shortcut, and a previously
open workspace-search palette normalizes back to **Commands**.
- **Commands** and **Tasks** read no worktree, so both remain available on every
route. The tab strip therefore always offers at least those two modes, and off
a task route it offers exactly those two.
- Clicking a mode or pressing **Tab** / **Shift+Tab** switches among the modes
that are currently available, without discarding the current query. The
existing **Cmd/Ctrl+Shift+K** shortcut still opens file-name and path search
directly.
- **Commands** mixes commands with task rows. With no query it leads with the
active-task list, capped at five rows, because reopening the palette is
usually a jump back to work and there is no query to rank commands against.
Once there is a query, matching commands rank above the task rows, which
remain as a preview of at most five. The default highlight follows that
rendered order, so pressing **Enter** on an exact command name runs the
command rather than opening a task whose title the query also matched.
- **Tasks** owns the full task search: up to twenty results, archived tasks
included and ranked last. Switching into it discards the commands scope's
narrower preview rather than presenting it as the complete result set.
- A row the user moved to with the arrow keys survives both a command
re-registration and the arrival of debounced task results.
- The tab strip does not shrink. Where it and the search field cannot both fit
on one row, the strip wraps to its own row beneath the field so the query
stays readable, rather than collapsing the field.
- File-name and path search covers every repository materialized for the active
task. Multi-repository results use task-root-relative, repository-prefixed
paths so same-named files remain distinguishable and open in the correct