Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8340 feat(search): context-aware command bar with agent handoff (#9647)

Jiayuan Zhangfb49f5592494
diff --git a/packages/core/command-bar/command-bar-stores.test.ts b/packages/core/command-bar/command-bar-stores.test.ts
new file mode 100644
index 0000000000..29021d5d5f
--- /dev/null
+++ b/packages/core/command-bar/command-bar-stores.test.ts
@@ -0,0 +1,89 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import type { Issue, Project } from "../types";
+import { selectCommandBarContexts, useCommandBarContextStore } from "./context-store";
+import { selectRecentVisits, useRecentVisitsStore } from "./recent-store";
+
+const issue = { id: "issue-1", identifier: "MUL-1" } as Issue;
+const project = { id: "project-1", title: "Launch" } as Project;
+
+describe("useCommandBarContextStore", () => {
+ beforeEach(() => {
+ useCommandBarContextStore.setState({ entries: [] });
+ });
+
+ it("lists the newest registration first", () => {
+ const { register } = useCommandBarContextStore.getState();
+ register("project-page", { kind: "project", project });
+ register("issue-page", { kind: "issue", issue });
+
+ const kinds = selectCommandBarContexts(useCommandBarContextStore.getState()).map(
+ (entry) => entry.context.kind,
+ );
+ expect(kinds).toEqual(["issue", "project"]);
+ });
+
+ it("updates a registration in place and ignores an identical one", () => {
+ const { register } = useCommandBarContextStore.getState();
+ const first = { kind: "issue", issue } as const;
+ register("issue-page", first);
+ register("project-page", { kind: "project", project });
+ const before = useCommandBarContextStore.getState().entries;
+
+ register("issue-page", first);
+ expect(useCommandBarContextStore.getState().entries).toBe(before);
+
+ const renamed = { kind: "issue", issue: { ...issue, title: "Renamed" } } as const;
+ register("issue-page", renamed);
+ const entries = useCommandBarContextStore.getState().entries;
+ expect(entries.map((entry) => entry.token)).toEqual(["project-page", "issue-page"]);
+ expect(entries[1]!.context).toBe(renamed);
+ });
+
+ it("drops a registration on unregister", () => {
+ const { register, unregister } = useCommandBarContextStore.getState();
+ register("issue-page", { kind: "issue", issue });
+ unregister("issue-page");
+ unregister("never-registered");
+
+ expect(useCommandBarContextStore.getState().entries).toEqual([]);
+ });
+});
+
+describe("useRecentVisitsStore", () => {
+ beforeEach(() => {
+ useRecentVisitsStore.setState({ byWorkspace: {} });
+ });
+
+ it("keeps visits per workspace, newest first, without duplicates", () => {
+ const { recordVisit } = useRecentVisitsStore.getState();
+ recordVisit("ws-a", { type: "project", id: "p1" });
+ recordVisit("ws-a", { type: "agent", id: "a1" });
+ recordVisit("ws-a", { type: "project", id: "p1" });
+ recordVisit("ws-b", { type: "autopilot", id: "ap1" });
+
+ const state = useRecentVisitsStore.getState();
+ expect(selectRecentVisits("ws-a")(state).map((e) => `${e.type}:${e.id}`)).toEqual([
+ "project:p1",
+ "agent:a1",
+ ]);
+ expect(selectRecentVisits("ws-b")(state)).toHaveLength(1);
+ expect(selectRecentVisits(null)(state)).toEqual([]);
+ });
+
+ it("treats the same id under another type as a different visit", () => {
+ const { recordVisit } = useRecentVisitsStore.getState();
+ recordVisit("ws-a", { type: "project", id: "x" });
+ recordVisit("ws-a", { type: "agent", id: "x" });
+
+ expect(useRecentVisitsStore.getState().byWorkspace["ws-a"]).toHaveLength(2);
+ });
+
+ it("prunes workspaces the user no longer belongs to", () => {
+ const { recordVisit, pruneWorkspaces } = useRecentVisitsStore.getState();
+ recordVisit("ws-a", { type: "project", id: "p1" });
+ recordVisit("ws-gone", { type: "project", id: "p2" });
+ pruneWorkspaces(["ws-a"]);
+
+ expect(Object.keys(useRecentVisitsStore.getState().byWorkspace)).toEqual(["ws-a"]);
+ });
+});
diff --git a/packages/core/command-bar/context-store.ts b/packages/core/command-bar/context-store.ts
new file mode 100644
index 0000000000..6ffdc6e2ca
--- /dev/null
+++ b/packages/core/command-bar/context-store.ts
@@ -0,0 +1,85 @@
+"use client";
+
+import { create } from "zustand";
+import type {
+ Agent,
+ Autopilot,
+ ChatSession,
+ InboxItem,
+ Issue,
+ Project,
+} from "../types";
+
+/**
+ * What the page on screen is about, registered by the page itself so the
+ * command bar never has to reverse-engineer it from the URL. Handlers are
+ * included where the action has page-local side effects the bar cannot
+ * reproduce (moving the inbox selection off an archived row, the chat
+ * page's archive/advance rule).
+ */
+export type CommandBarContext =
+ | {
+ kind: "issue";
+ issue: Issue;
+ /** Where to land after deleting it when there is no history to go back to. */
+ onDeletedFallbackPath?: string;
+ }
+ | { kind: "issues"; issues: Issue[]; clearSelection: () => void }
+ | { kind: "project"; project: Project }
+ | { kind: "agent"; agent: Agent }
+ | { kind: "autopilot"; autopilot: Autopilot }
+ | {
+ kind: "inbox";
+ item: InboxItem | null;
+ archive: (id: string) => void;
+ markUnread: (id: string) => void;
+ markAllRead: () => void;
+ archiveAllRead: () => void;
+ }
+ | {
+ kind: "chat";
+ session: ChatSession;
+ archive: (session: ChatSession) => void;
+ changeProject: (projectId: string | null) => void;
+ };
+
+export type CommandBarContextKind = CommandBarContext["kind"];
+
+export interface CommandBarContextEntry {
+ token: string;
+ context: CommandBarContext;
+}
+
+interface CommandBarContextState {
+ /** Newest registration first; an update keeps the entry's position. */
+ entries: CommandBarContextEntry[];
+ register: (token: string, context: CommandBarContext) => void;
+ unregister: (token: string) => void;
+}
+
+const EMPTY: CommandBarContextEntry[] = [];
+
+export const useCommandBarContextStore = create<CommandBarContextState>()((set) => ({
+ entries: EMPTY,
+ register: (token, context) =>
+ set((state) => {
+ const index = state.entries.findIndex((entry) => entry.token === token);
+ if (index === -1) {
+ return { entries: [{ token, context }, ...state.entries] };
+ }
+ if (state.entries[index]!.context === context) return state;
+ const entries = state.entries.slice();
+ entries[index] = { token, context };
+ return { entries };
+ }),
+ unregister: (token) =>
+ set((state) => {
+ if (!state.entries.some((entry) => entry.token === token)) return state;
+ const entries = state.entries.filter((entry) => entry.token !== token);
+ return { entries: entries.length > 0 ? entries : EMPTY };
+ }),
+}));
+
+export function selectCommandBarContexts(state: CommandBarContextState) {
+ return state.entries;
+}
diff --git a/packages/core/command-bar/index.ts b/packages/core/command-bar/index.ts
new file mode 100644
index 0000000000..6f4cd1b476
--- /dev/null
+++ b/packages/core/command-bar/index.ts
@@ -0,0 +1,13 @@
+export {
+ useCommandBarContextStore,
+ selectCommandBarContexts,
+ type CommandBarContext,
+ type CommandBarContextEntry,
+ type CommandBarContextKind,
+} from "./context-store";
+export {
+ useRecentVisitsStore,
+ selectRecentVisits,
+ type RecentVisitEntry,
+ type RecentVisitType,
+} from "./recent-store";
diff --git a/packages/core/command-bar/recent-store.ts b/packages/core/command-bar/recent-store.ts
new file mode 100644
index 0000000000..5e012744d9
--- /dev/null
+++ b/packages/core/command-bar/recent-store.ts
@@ -0,0 +1,84 @@
+"use client";
+
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+import { defaultStorage } from "../platform/storage";
+
+const MAX_RECENT_VISITS = 20;
+const MAX_WORKSPACES = 50;
+const EMPTY: RecentVisitEntry[] = [];
+
+/**
+ * Non-issue objects for the command bar's mixed Recent group. Issues keep
+ * their own store (`useRecentIssuesStore`), which already has many readers;
+ * the bar merges the two by `visitedAt`.
+ */
+export type RecentVisitType = "project" | "agent" | "autopilot";
+
+export interface RecentVisitEntry {
+ type: RecentVisitType;
+ id: string;
+ visitedAt: number;
+}
+
+interface RecentVisitsState {
+ byWorkspace: Record<string, RecentVisitEntry[]>;
+ recordVisit: (wsId: string, entry: Pick<RecentVisitEntry, "type" | "id">) => void;
+ pruneWorkspaces: (activeWsIds: string[]) => void;
+}
+
+const sameEntry = (a: Pick<RecentVisitEntry, "type" | "id">, b: Pick<RecentVisitEntry, "type" | "id">) =>
+ a.type === b.type && a.id === b.id;
+
+// Keyed by workspace id rather than a slug-namespaced storage key for the same
+// reason as recent-issues-store: child mount effects fire before the workspace
+// layout sets the current slug.
+export const useRecentVisitsStore = create<RecentVisitsState>()(
+ persist(
+ (set) => ({
+ byWorkspace: {},
+ recordVisit: (wsId, entry) =>
+ set((state) => {
+ const bucket = state.byWorkspace[wsId] ?? EMPTY;
+ const next: RecentVisitEntry = { type: entry.type, id: entry.id, visitedAt: Date.now() };
+ const nextBucket = [next, ...bucket.filter((item) => !sameEntry(item, entry))].slice(
+ 0,
+ MAX_RECENT_VISITS,
+ );
+ let byWorkspace = { ...state.byWorkspace, [wsId]: nextBucket };
+ const ids = Object.keys(byWorkspace);
+ if (ids.length > MAX_WORKSPACES) {
+ const oldest = ids.reduce((oldestId, candidateId) => {
+ const a = byWorkspace[oldestId]?.[0]?.visitedAt ?? 0;
+ const b = byWorkspace[candidateId]?.[0]?.visitedAt ?? 0;
+ return b < a ? candidateId : oldestId;
+ });
+ const { [oldest]: _, ...rest } = byWorkspace;
+ byWorkspace = rest;
+ }
+ return { byWorkspace };
+ }),
+ pruneWorkspaces: (activeWsIds) =>
+ set((state) => {
+ const allow = new Set(activeWsIds);
+ let changed = false;
+ const next: Record<string, RecentVisitEntry[]> = {};
+ for (const [wsId, items] of Object.entries(state.byWorkspace)) {
+ if (allow.has(wsId)) next[wsId] = items;
+ else changed = true;
+ }
+ return changed ? { byWorkspace: next } : state;
+ }),
+ }),
+ {
+ name: "multica_recent_visits",
+ storage: createJSONStorage(() => defaultStorage),
+ partialize: (state) => ({ byWorkspace: state.byWorkspace }),
+ version: 1,
+ },
+ ),
+);
+
+export function selectRecentVisits(wsId: string | null) {
+ return (state: RecentVisitsState) => (wsId ? (state.byWorkspace[wsId] ?? EMPTY) : EMPTY);
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index b0e5b35483..c25543b887 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -110,6 +110,7 @@
"./autopilots/queries": "./autopilots/queries.ts",
"./autopilots/mutations": "./autopilots/mutations.ts",
"./pins": "./pins/index.ts",
+ "./command-bar": "./command-bar/index.ts",
"./pins/queries": "./pins/queries.ts",
"./pins/mutations": "./pins/mutations.ts",
"./issue-views": "./issue-views/index.ts",
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
index a6891dc365..e50db669b2 100644
--- a/packages/views/agents/components/agent-detail-page.tsx
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -1,6 +1,7 @@
"use client";
-import { useState } from "react";
+import { useMemo, useState } from "react";
+import { useRegisterCommandBarContext } from "../../search/register-context";
import {
AlertCircle,
ArrowLeft,
@@ -115,6 +116,9 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
listAgent ?? (isForbidden || isNotFound ? null : detailQuery.data) ?? null;
const presence: AgentPresenceDetail | null =
agent ? presenceMap.get(agent.id) ?? null : null;
+ useRegisterCommandBarContext(
+ useMemo(() => (agent ? { kind: "agent", agent } : null), [agent]),
+ );
// Permission hook MUST be called unconditionally — its `agent | null`
// signature handles the not-found / loading case internally so the early
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index d250258728..5f93ec2e9e 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import {
Zap, Play, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil,
Ban, ChevronDown, ChevronRight,
@@ -12,13 +12,12 @@ import { projectDetailOptions } from "@multica/core/projects/queries";
import {
useUpdateAutopilot,
useDeleteAutopilot,
- useTriggerAutopilot,
useCreateAutopilotTrigger,
useDeleteAutopilotTrigger,
useRotateAutopilotTriggerWebhookToken,
} from "@multica/core/autopilots/mutations";
import { buildAutopilotWebhookUrl } from "@multica/core/autopilots";
-import { api, clientErrorMessage, dispatchReasonCode } from "@multica/core/api";
+import { api } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
@@ -66,7 +65,8 @@ import { ReadonlyContent } from "../../editor";
import { TranscriptButton } from "../../common/task-transcript";
import { AutopilotDialog } from "./autopilot-dialog";
import { EditScheduleTriggerDialog } from "./edit-schedule-trigger-dialog";
-import { runNowToastKind, runNowBlockedKey } from "./run-now-toast";
+import { useRunAutopilotNow } from "./use-run-autopilot-now";
+import { useRegisterCommandBarContext } from "../../search/register-context";
import { WebhookPayloadPreview } from "./webhook-payload-preview";
import { WebhookDeliveriesSection } from "./webhook-deliveries-section";
import { ProjectIcon } from "../../projects/components/project-icon";
@@ -685,7 +685,14 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
const { data: runs = [], isLoading: runsLoading } = useQuery(autopilotRunsOptions(wsId, autopilotId));
const updateAutopilot = useUpdateAutopilot();
const deleteAutopilot = useDeleteAutopilot();
- const triggerAutopilot = useTriggerAutopilot();
+ const { runNow, isPending: runNowPending } = useRunAutopilotNow();
+ const loadedAutopilot = data?.autopilot ?? null;
+ useRegisterCommandBarContext(
+ useMemo(
+ () => (loadedAutopilot ? { kind: "autopilot", autopilot: loadedAutopilot } : null),
+ [loadedAutopilot],
+ ),
+ );
const projectId = data?.autopilot.project_id ?? null;
const { data: project, isLoading: projectLoading } = useQuery({
...projectDetailOptions(wsId, projectId ?? ""),
@@ -755,38 +762,7 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
// doesn't send the field (older backend).
const canManageAccess = autopilot.can_manage_access ?? canWrite;
- const handleRunNow = async () => {
- try {
- const run = await triggerAutopilot.mutateAsync(autopilotId);
- // Manual "run now" returns 200 even when admission blocks the run, so the
- // toast is driven by the run's domain status, not the HTTP 2xx (MUL-4525).
- // Success is a whitelist (issue_created/running) — a skipped run warns, a
- // failed or unknown/future status errors — never a false "triggered".
- const kind = runNowToastKind(run?.status);
- if (kind === "success") {
- toast.success(t(($) => $.detail.toast_triggered));
- return;
- }
- // reason_code is the stable, typed cause the server decided at admission
- // time; an unknown/absent code degrades to a generic "not triggered".
- const message = t(($) => $.detail[runNowBlockedKey(run?.reason_code)]);
- if (kind === "warning") {
- toast.warning(message);
- } else {
- toast.error(message);
- }
- } catch (e: any) {
- const reason = dispatchReasonCode(e);
- if (reason) {
- toast.error(t(($) => $.detail[runNowBlockedKey(reason)]));
- return;
- }
- // Only a 4xx message is written for the user; a 5xx one is internal
- // server detail (MUL-6472), so an unclassified dispatch failure shows the
- // localized generic sentence instead of the raw body.
- toast.error(clientErrorMessage(e) || t(($) => $.detail.toast_trigger_failed));
- }
- };
+ const handleRunNow = () => runNow(autopilotId);
const handleDelete = async () => {
setDeleting(true);
@@ -849,17 +825,17 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
<Button
size="sm"
onClick={handleRunNow}
- disabled={autopilot.status !== "active" || triggerAutopilot.isPending}
+ disabled={autopilot.status !== "active" || runNowPending}
className="px-2 sm:px-2.5"
- aria-label={triggerAutopilot.isPending ? t(($) => $.detail.running) : t(($) => $.detail.run_now)}
+ aria-label={runNowPending ? t(($) => $.detail.running) : t(($) => $.detail.run_now)}
>
- {triggerAutopilot.isPending ? (
+ {runNowPending ? (
<Loader2 className="h-3.5 w-3.5 sm:mr-1 animate-spin" />
) : (
<Play className="h-3.5 w-3.5 sm:mr-1" />
)}
<span className="hidden sm:inline">
- {triggerAutopilot.isPending
+ {runNowPending
? t(($) => $.detail.running)
: t(($) => $.detail.run_now)}
</span>
diff --git a/packages/views/autopilots/components/use-run-autopilot-now.ts b/packages/views/autopilots/components/use-run-autopilot-now.ts
new file mode 100644
index 0000000000..2733f1240a
--- /dev/null
+++ b/packages/views/autopilots/components/use-run-autopilot-now.ts
@@ -0,0 +1,55 @@
+"use client";
+
+import { useCallback } from "react";
+import { toast } from "sonner";
+import { clientErrorMessage, dispatchReasonCode } from "@multica/core/api";
+import { useTriggerAutopilot } from "@multica/core/autopilots/mutations";
+import { useT } from "../../i18n";
+import { runNowBlockedKey, runNowToastKind } from "./run-now-toast";
+
+/**
+ * Manual "run now" with its outcome toast. Shared by the autopilot detail page
+ * and the command bar so both report the same result for the same run.
+ */
+export function useRunAutopilotNow() {
+ const { t } = useT("autopilots");
+ const triggerAutopilot = useTriggerAutopilot();
+
+ const runNow = useCallback(
+ async (autopilotId: string) => {
+ try {
+ const run = await triggerAutopilot.mutateAsync(autopilotId);
+ // Manual "run now" returns 200 even when admission blocks the run, so the
+ // toast is driven by the run's domain status, not the HTTP 2xx (MUL-4525).
+ // Success is a whitelist (issue_created/running) — a skipped run warns, a
+ // failed or unknown/future status errors — never a false "triggered".
+ const kind = runNowToastKind(run?.status);
+ if (kind === "success") {
+ toast.success(t(($) => $.detail.toast_triggered));
+ return;
+ }
+ // reason_code is the stable, typed cause the server decided at admission
+ // time; an unknown/absent code degrades to a generic "not triggered".
+ const message = t(($) => $.detail[runNowBlockedKey(run?.reason_code)]);
+ if (kind === "warning") {
+ toast.warning(message);
+ } else {
+ toast.error(message);
+ }
+ } catch (e: unknown) {
+ const reason = dispatchReasonCode(e);
+ if (reason) {
+ toast.error(t(($) => $.detail[runNowBlockedKey(reason)]));
+ return;
+ }
+ // Only a 4xx message is written for the user; a 5xx one is internal
+ // server detail (MUL-6472), so an unclassified dispatch failure shows the
+ // localized generic sentence instead of the raw body.
+ toast.error(clientErrorMessage(e) || t(($) => $.detail.toast_trigger_failed));
+ }
+ },
+ [triggerAutopilot, t],
+ );
+
+ return { runNow, isPending: triggerAutopilot.isPending };
+}
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index 1f9878e34c..c5ba0a4d27 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useDefaultLayout } from "react-resizable-panels";
import { ArrowLeft, MessageSquare } from "lucide-react";
import { toast } from "sonner";
@@ -36,6 +36,7 @@ import { NoAgentBanner } from "./components/no-agent-banner";
import { ArchivedAgentBanner } from "./components/archived-agent-banner";
import { AgentAccessRevokedBanner } from "./components/agent-access-revoked-banner";
import { RuntimeRequiredBanner } from "./components/runtime-required-banner";
+import { useRegisterCommandBarContext } from "../search/register-context";
/**
* Chat tab — the first-class two-pane surface (thread list on the left,
@@ -187,6 +188,29 @@ export function ChatPage() {
if (!c.currentSession || projectId !== null) setComposingNew(true);
};
+ // The command bar calls the page's own handlers so archiving or re-scoping
+ // from it moves the pane exactly like the header controls do.
+ const commandBarHandlersRef = useRef({ handleArchive, changeProjectContext });
+ useEffect(() => {
+ commandBarHandlersRef.current = { handleArchive, changeProjectContext };
+ });
+ const commandBarSession = c.currentSession ?? null;
+ useRegisterCommandBarContext(
+ useMemo(
+ () =>
+ commandBarSession
+ ? {
+ kind: "chat",
+ session: commandBarSession,
+ archive: (session: ChatSession) => commandBarHandlersRef.current.handleArchive(session),
+ changeProject: (projectId: string | null) =>
+ commandBarHandlersRef.current.changeProjectContext(projectId),
+ }
+ : null,
+ [commandBarSession],
+ ),
+ );
+
// URL → new chat: `?agent=<id>` is the deep link used by "DM" entry points
// (e.g. the agent detail page) to land on a fresh compose bound to that
// agent. The permission-filtered agent list loads async, so the intent is
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 34af52ee50..4692b22401 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -53,6 +53,7 @@ import {
import { IssueDetail, issueHighlightMementoKey } from "../../issues/components/issue-detail";
import { ActionShortcutKeycaps } from "../../common/shortcut-keycaps";
+import { useRegisterCommandBarContext } from "../../search/register-context";
import { IssuePeekHost } from "../../issues/components/issue-peek";
import { useIssueSurfaceActivity } from "../../issues/surface/activity";
import { useViewStateWriter } from "../../platform";
@@ -571,6 +572,37 @@ export function InboxPage() {
});
};
+ // The command bar calls the page's own handlers, so archiving from it moves
+ // the selection and toasts exactly like the row actions do.
+ const commandBarHandlersRef = useRef({
+ handleArchive,
+ handleMarkUnread,
+ handleMarkAllRead,
+ handleArchiveAllRead,
+ });
+ useEffect(() => {
+ commandBarHandlersRef.current = {
+ handleArchive,
+ handleMarkUnread,
+ handleMarkAllRead,
+ handleArchiveAllRead,
+ };
+ });
+ const commandBarItem = isArchivedView ? null : selected;
+ useRegisterCommandBarContext(
+ useMemo(
+ () => ({
+ kind: "inbox",
+ item: commandBarItem,
+ archive: (id: string) => commandBarHandlersRef.current.handleArchive(id),
+ markUnread: (id: string) => commandBarHandlersRef.current.handleMarkUnread(id),
+ markAllRead: () => commandBarHandlersRef.current.handleMarkAllRead(),
+ archiveAllRead: () => commandBarHandlersRef.current.handleArchiveAllRead(),
+ }),
+ [commandBarItem],
+ ),
+ );
+
const handleArchiveCompleted = () => {
setSelectedKey("");
archiveCompletedMutation.mutate(undefined, {
diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsx
index d104b29a09..b7daca353f 100644
--- a/packages/views/issues/components/batch-action-toolbar.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.tsx
@@ -32,6 +32,7 @@ import {
} from "@multica/ui/lib/motion";
import { useIssueSurfaceActionsOptional } from "../surface/actions-context";
import { useIssueSurfaceSelection } from "../surface/selection-context";
+import { useRegisterCommandBarContext } from "../../search/register-context";
export function BatchActionToolbar({
issues,
@@ -78,6 +79,13 @@ export function BatchActionToolbar({
);
const count = selectedIssues.length;
+ useRegisterCommandBarContext(
+ useMemo(
+ () => (count > 0 ? { kind: "issues", issues: selectedIssues, clearSelection: clear } : null),
+ [count, selectedIssues, clear],
+ ),
+ );
+
// Reflect the real shared value of the selected issues in each picker; fall
// back to an empty (no-checkmark) state when the selection is mixed, instead
// of asserting a hardcoded default.
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index a306e6b800..1f03b62db3 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -136,6 +136,7 @@ import {
useProjectWorkflow,
} from "@multica/core/issue-workflows";
import { useRecentContextStore } from "@multica/core/chat";
+import { useRegisterCommandBarContext } from "../../search/register-context";
import { useModalStore } from "@multica/core/modals";
import { issueListOptions, issueDetailOptions, childIssuesOptions, childIssueProgressOptions, issueAttachmentsOptions } from "@multica/core/issues/queries";
import { projectDetailOptions } from "@multica/core/projects/queries";
@@ -1592,6 +1593,15 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
}
}, [issue?.id, wsId]); // eslint-disable-line react-hooks/exhaustive-deps
+ const deletedFallbackPath = onDelete ? undefined : paths.issues();
+ useRegisterCommandBarContext(
+ useMemo(
+ () =>
+ issue ? { kind: "issue", issue, onDeletedFallbackPath: deletedFallbackPath } : null,
+ [issue, deletedFallbackPath],
+ ),
+ );
+
// Fire `onDelete` once when the issue transitions from loaded to missing.
// Delete goes through a shell-level modal, so the caller (e.g. inbox) can't
// be notified directly — instead, the detail page observes its own cache
diff --git a/packages/views/issues/components/quick-actions-section.tsx b/packages/views/issues/components/quick-actions-section.tsx
index 00fe4a0b57..c0d13222f6 100644
--- a/packages/views/issues/components/quick-actions-section.tsx
+++ b/packages/views/issues/components/quick-actions-section.tsx
@@ -124,7 +124,7 @@ export function QuickActionsSection({ issueId }: { issueId: string }) {
* started. "Added to Lambda's current run" is the truth; "Lambda started
* working" is not.
*/
-function outcomeMessage(
+export function outcomeMessage(
outcome: CommentTriggerOutcome | undefined,
targetName: string,
t: ReturnType<typeof useT<"issues">>["t"],
diff --git a/packages/views/layout/use-dashboard-guard.ts b/packages/views/layout/use-dashboard-guard.ts
index c369844f14..0c14688a2f 100644
--- a/packages/views/layout/use-dashboard-guard.ts
+++ b/packages/views/layout/use-dashboard-guard.ts
@@ -11,6 +11,7 @@ import {
} from "@multica/core/paths";
import { useWorkspaceList } from "@multica/core/workspace";
import { useRecentIssuesStore } from "@multica/core/issues/stores";
+import { useRecentVisitsStore } from "@multica/core/command-bar";
import { useNavigation } from "../navigation";
/**
@@ -69,9 +70,9 @@ export function useDashboardGuard() {
// changes (workspace deleted, user kicked, user left).
useEffect(() => {
if (!workspaceListReady) return;
- useRecentIssuesStore
- .getState()
- .pruneWorkspaces(workspaces.map((w) => w.id));
+ const activeWsIds = workspaces.map((w) => w.id);
+ useRecentIssuesStore.getState().pruneWorkspaces(activeWsIds);
+ useRecentVisitsStore.getState().pruneWorkspaces(activeWsIds);
}, [workspaceListReady, workspaces]);
return { user, isLoading, workspace };
diff --git a/packages/views/locales/en/search.json b/packages/views/locales/en/search.json
index 64a1294dac..b705eee98e 100644
--- a/packages/views/locales/en/search.json
+++ b/packages/views/locales/en/search.json
@@ -1,36 +1,172 @@
{
- "title": "Search",
- "description": "Search pages, issues, projects, and members",
- "placeholder": "Type a command or search...",
+ "title": "Command bar",
+ "description": "Search, run commands, or hand work to an agent",
+ "placeholder": "Search, or type what needs doing...",
+ "page_placeholder": "Filter...",
+ "breadcrumb_aria": "Current menu",
"groups": {
"pages": "Pages",
"commands": "Commands",
"members": "Members",
+ "agents": "Agents",
+ "squads": "Squads",
"projects": "Projects",
"issues": "Issues",
+ "autopilots": "Autopilots",
+ "chats": "Chats",
+ "skills": "Skills",
"cancelled": "Cancelled",
"recent": "Recent",
- "workspaces": "Workspaces"
+ "workspaces": "Workspaces",
+ "new": "New",
+ "best_match": "Best match",
+ "actions": "Actions"
+ },
+ "context": {
+ "current_issue": "Current issue",
+ "selected_issues_one": "{{count}} selected issue",
+ "selected_issues_other": "{{count}} selected issues",
+ "current_project": "Current project",
+ "current_agent": "Current agent",
+ "current_autopilot": "Current autopilot",
+ "inbox": "Inbox",
+ "current_chat": "Current chat"
},
"commands": {
"current_theme_aria": "Current theme",
- "new_issue": "New Issue",
- "new_project": "New Project",
- "copy_issue_link": "Copy Issue Link",
- "copy_identifier": "Copy Identifier ({{identifier}})",
- "fold_all_comments": "Fold All Comments",
- "unfold_all_comments": "Unfold All Comments",
- "switch_to_light": "Switch to Light Theme",
- "switch_to_dark": "Switch to Dark Theme",
- "use_system_theme": "Use System Theme"
+ "new_issue": "New issue",
+ "new_project": "New project",
+ "new_autopilot": "New autopilot",
+ "chat_with_agent": "Chat with an agent",
+ "change_theme": "Change theme...",
+ "send_feedback": "Send feedback",
+ "copy_issue_link": "Copy issue link",
+ "copy_identifier": "Copy identifier ({{identifier}})",
+ "fold_all_comments": "Fold all comments",
+ "unfold_all_comments": "Unfold all comments"
+ },
+ "issue": {
+ "change_status": "Change status...",
+ "assign_to": "Assign to...",
+ "set_priority": "Set priority...",
+ "run_quick_action": "Run quick action...",
+ "quick_actions_available_one": "{{count}} available",
+ "quick_actions_available_other": "{{count}} available",
+ "add_label": "Add label...",
+ "set_due_date": "Set due date...",
+ "move_to_project": "Move to project...",
+ "set_parent": "Set parent issue...",
+ "cancel_run": "Cancel current run",
+ "retry_run": "Retry last run",
+ "create_sub_issue": "New sub-issue",
+ "subscribe": "Subscribe",
+ "unsubscribe": "Unsubscribe",
+ "delete": "Delete issue",
+ "delete_selected_one": "Delete {{count}} issue",
+ "delete_selected_other": "Delete {{count}} issues"
+ },
+ "project": {
+ "change_status": "Change project status...",
+ "new_issue": "New issue in this project",
+ "pin": "Pin to sidebar",
+ "unpin": "Unpin from sidebar",
+ "copy_link": "Copy project link"
+ },
+ "agent": {
+ "chat": "Chat with {{name}}",
+ "assign_issue": "Assign an issue to {{name}}...",
+ "new_issue": "New issue for {{name}}",
+ "pin_in_chat": "Pin in chat",
+ "unpin_in_chat": "Unpin from chat"
+ },
+ "autopilot": {
+ "run_now": "Run once now",
+ "pause": "Pause",
+ "resume": "Resume"
+ },
+ "inbox": {
+ "archive": "Archive",
+ "mark_unread": "Mark as unread",
+ "mark_all_read": "Mark all inbox items as read",
+ "archive_all_read": "Archive all read inbox items"
+ },
+ "chat": {
+ "link_project": "Link to project...",
+ "pin": "Pin chat",
+ "unpin": "Unpin chat",
+ "archive": "Archive chat"
+ },
+ "pages": {
+ "status": "Status",
+ "priority": "Priority",
+ "assignee": "Assignee",
+ "labels": "Labels",
+ "due_date": "Due date",
+ "project": "Project",
+ "parent": "Parent issue",
+ "quick_actions": "Quick actions",
+ "theme": "Theme",
+ "project_status": "Project status",
+ "no_project": "No project",
+ "current": "Current"
+ },
+ "theme": {
+ "light": "Light",
+ "dark": "Dark",
+ "system": "System"
},
"toast": {
"link_copied": "Link copied",
- "copied_identifier": "Copied {{identifier}}"
+ "copied_identifier": "Copied {{identifier}}",
+ "run_retried": "Run restarted",
+ "run_cancelled": "Run cancelled",
+ "subscribed": "Subscribed",
+ "unsubscribed": "Unsubscribed",
+ "label_added": "Added label {{name}}",
+ "label_removed": "Removed label {{name}}",
+ "label_failed": "Couldn't add label {{name}} to every issue",
+ "update_failed": "Update failed",
+ "assigned": "Assigned {{identifier}} to {{name}}"
},
"empty": {
"no_results": "No results found.",
- "type_to_search": "Type to search issues and projects"
+ "no_labels": "No labels",
+ "type_to_find_issue": "Type to find an issue",
+ "type_to_find_people": "Type to find people and agents"
+ },
+ "delegate": {
+ "heading": "Hand to agent",
+ "create_and_assign": "New issue and assign to {{name}}",
+ "squad": "Squad",
+ "context_aria": "Created with",
+ "parent": "Under {{identifier}}",
+ "pick_crumb": "Choose",
+ "pick_another": "Hand to another agent or squad...",
+ "detected": "Instruction"
+ },
+ "best": {
+ "assign": "Assign {{subject}} to {{name}}",
+ "chat": "Chat with {{name}}",
+ "new_issue_in": "New issue in {{name}}"
+ },
+ "types": {
+ "issue": "Issue",
+ "project": "Project",
+ "agent": "Agent",
+ "autopilot": "Autopilot",
+ "squad": "Squad",
+ "member": "Member"
+ },
+ "footer": {
+ "navigate": "Navigate",
+ "select": "Select",
+ "open_in_new_tab": "Open in new tab",
+ "delegate": "Create and hand to {{name}}",
+ "search_instead": "Search as keywords",
+ "back": "Back",
+ "prefix_commands": "Commands",
+ "prefix_issues": "Issues",
+ "prefix_people": "People & agents"
},
"trigger": {
"label": "Search..."
diff --git a/packages/views/locales/fr/search.json b/packages/views/locales/fr/search.json
index ea7ee02b9f..55bcccfae7 100644
--- a/packages/views/locales/fr/search.json
+++ b/packages/views/locales/fr/search.json
@@ -1,36 +1,172 @@
{
- "title": "Recherche",
- "description": "Rechercher des pages, des tâches, des projets et des membres",
- "placeholder": "Saisissez une commande ou une recherche...",
+ "title": "Barre de commandes",
+ "description": "Rechercher, lancer une commande ou confier du travail à un agent",
+ "placeholder": "Rechercher, ou décrire ce qu'il faut faire...",
+ "page_placeholder": "Filtrer...",
+ "breadcrumb_aria": "Menu actuel",
"groups": {
"pages": "Pages",
"commands": "Commandes",
"members": "Membres",
+ "agents": "Agents",
+ "squads": "Squads",
"projects": "Projets",
"issues": "Tâches",
+ "autopilots": "Automatisations",
+ "chats": "Discussions",
+ "skills": "Skills",
"cancelled": "Annulés",
"recent": "Récents",
- "workspaces": "Espaces de travail"
+ "workspaces": "Espaces de travail",
+ "new": "Créer",
+ "best_match": "Meilleur résultat",
+ "actions": "Actions"
+ },
+ "context": {
+ "current_issue": "Tâche actuelle",
+ "selected_issues_one": "{{count}} tâche sélectionnée",
+ "selected_issues_other": "{{count}} tâches sélectionnées",
+ "current_project": "Projet actuel",
+ "current_agent": "Agent actuel",
+ "current_autopilot": "Automatisation actuelle",
+ "inbox": "Boîte de réception",
+ "current_chat": "Discussion actuelle"
},
"commands": {
"current_theme_aria": "Thème actuel",
"new_issue": "Nouvelle tâche",
"new_project": "Nouveau projet",
+ "new_autopilot": "Nouvelle automatisation",
+ "chat_with_agent": "Discuter avec un agent",
+ "change_theme": "Changer de thème...",
+ "send_feedback": "Envoyer un retour",
"copy_issue_link": "Copier le lien de la tâche",
"copy_identifier": "Copier l'identifiant ({{identifier}})",
"fold_all_comments": "Replier tous les commentaires",
- "unfold_all_comments": "Déplier tous les commentaires",
- "switch_to_light": "Passer au thème clair",
- "switch_to_dark": "Passer au thème sombre",
- "use_system_theme": "Utiliser le thème du système"
+ "unfold_all_comments": "Déplier tous les commentaires"
+ },
+ "issue": {
+ "change_status": "Changer le statut...",
+ "assign_to": "Assigner à...",
+ "set_priority": "Définir la priorité...",
+ "run_quick_action": "Lancer une action rapide...",
+ "quick_actions_available_one": "{{count}} disponible",
+ "quick_actions_available_other": "{{count}} disponibles",
+ "add_label": "Ajouter un libellé...",
+ "set_due_date": "Définir l'échéance...",
+ "move_to_project": "Déplacer vers un projet...",
+ "set_parent": "Définir la tâche parente...",
+ "cancel_run": "Annuler l'exécution en cours",
+ "retry_run": "Relancer la dernière exécution",
+ "create_sub_issue": "Nouvelle sous-tâche",
+ "subscribe": "S'abonner",
+ "unsubscribe": "Se désabonner",
+ "delete": "Supprimer la tâche",
+ "delete_selected_one": "Supprimer {{count}} tâche",
+ "delete_selected_other": "Supprimer {{count}} tâches"
+ },
+ "project": {
+ "change_status": "Changer le statut du projet...",
+ "new_issue": "Nouvelle tâche dans ce projet",
+ "pin": "Épingler dans la barre latérale",
+ "unpin": "Désépingler de la barre latérale",
+ "copy_link": "Copier le lien du projet"
+ },
+ "agent": {
+ "chat": "Discuter avec {{name}}",
+ "assign_issue": "Assigner une tâche à {{name}}...",
+ "new_issue": "Nouvelle tâche pour {{name}}",
+ "pin_in_chat": "Épingler dans la discussion",
+ "unpin_in_chat": "Désépingler de la discussion"
+ },
+ "autopilot": {
+ "run_now": "Exécuter une fois maintenant",
+ "pause": "Mettre en pause",
+ "resume": "Reprendre"
+ },
+ "inbox": {
+ "archive": "Archiver",
+ "mark_unread": "Marquer comme non lu",
+ "mark_all_read": "Tout marquer comme lu dans la boîte de réception",
+ "archive_all_read": "Archiver tous les éléments lus"
+ },
+ "chat": {
+ "link_project": "Associer à un projet...",
+ "pin": "Épingler la discussion",
+ "unpin": "Désépingler la discussion",
+ "archive": "Archiver la discussion"
+ },
+ "pages": {
+ "status": "Statut",
+ "priority": "Priorité",
+ "assignee": "Responsable",
+ "labels": "Libellés",
+ "due_date": "Échéance",
+ "project": "Projet",
+ "parent": "Tâche parente",
+ "quick_actions": "Actions rapides",
+ "theme": "Thème",
+ "project_status": "Statut du projet",
+ "no_project": "Aucun projet",
+ "current": "Actuel"
+ },
+ "theme": {
+ "light": "Clair",
+ "dark": "Sombre",
+ "system": "Système"
},
"toast": {
"link_copied": "Lien copié",
- "copied_identifier": "{{identifier}} copié"
+ "copied_identifier": "{{identifier}} copié",
+ "run_retried": "Exécution relancée",
+ "run_cancelled": "Exécution annulée",
+ "subscribed": "Abonné",
+ "unsubscribed": "Désabonné",
+ "label_added": "Libellé {{name}} ajouté",
+ "label_removed": "Libellé {{name}} retiré",
+ "label_failed": "Impossible d'ajouter le libellé {{name}} à toutes les tâches",
+ "update_failed": "Échec de la mise à jour",
+ "assigned": "{{identifier}} assignée à {{name}}"
},
"empty": {
"no_results": "Aucun résultat.",
- "type_to_search": "Saisissez du texte pour rechercher des tâches et des projets"
+ "no_labels": "Aucun libellé",
+ "type_to_find_issue": "Tapez pour trouver une tâche",
+ "type_to_find_people": "Tapez pour trouver des membres et des agents"
+ },
+ "delegate": {
+ "heading": "Confier à un agent",
+ "create_and_assign": "Créer une tâche et l'assigner à {{name}}",
+ "squad": "Squad",
+ "context_aria": "Contexte joint",
+ "parent": "Sous {{identifier}}",
+ "pick_crumb": "Choisir",
+ "pick_another": "Confier à un autre agent ou squad...",
+ "detected": "Instruction"
+ },
+ "best": {
+ "assign": "Assigner {{subject}} à {{name}}",
+ "chat": "Discuter avec {{name}}",
+ "new_issue_in": "Nouvelle tâche dans {{name}}"
+ },
+ "types": {
+ "issue": "Tâche",
+ "project": "Projet",
+ "agent": "Agent",
+ "autopilot": "Automatisation",
+ "squad": "Squad",
+ "member": "Membre"
+ },
+ "footer": {
+ "navigate": "Naviguer",
+ "select": "Valider",
+ "open_in_new_tab": "Ouvrir dans un nouvel onglet",
+ "delegate": "Créer et confier à {{name}}",
+ "search_instead": "Rechercher comme mots-clés",
+ "back": "Retour",
+ "prefix_commands": "Commandes",
+ "prefix_issues": "Tâches",
+ "prefix_people": "Membres et agents"
},
"trigger": {
"label": "Rechercher..."
diff --git a/packages/views/locales/ja/search.json b/packages/views/locales/ja/search.json
index 3e51019bf7..bb61bf2ff2 100644
--- a/packages/views/locales/ja/search.json
+++ b/packages/views/locales/ja/search.json
@@ -1,36 +1,169 @@
{
- "title": "検索",
- "description": "ページ、タスク、プロジェクト、メンバーを検索します",
- "placeholder": "コマンドを入力するか検索...",
+ "title": "コマンドバー",
+ "description": "検索、コマンドの実行、またはエージェントへの依頼",
+ "placeholder": "検索するか、やりたいことを入力...",
+ "page_placeholder": "絞り込み...",
+ "breadcrumb_aria": "現在のメニュー",
"groups": {
"pages": "ページ",
"commands": "コマンド",
"members": "メンバー",
+ "agents": "エージェント",
+ "squads": "スクワッド",
"projects": "プロジェクト",
"issues": "タスク",
+ "autopilots": "オートパイロット",
+ "chats": "チャット",
+ "skills": "スキル",
"cancelled": "キャンセル済み",
"recent": "最近の項目",
- "workspaces": "ワークスペース"
+ "workspaces": "ワークスペース",
+ "new": "新規作成",
+ "best_match": "最も一致",
+ "actions": "操作"
+ },
+ "context": {
+ "current_issue": "現在のタスク",
+ "selected_issues_other": "選択中のタスク {{count}} 件",
+ "current_project": "現在のプロジェクト",
+ "current_agent": "現在のエージェント",
+ "current_autopilot": "現在のオートパイロット",
+ "inbox": "インボックス",
+ "current_chat": "現在のチャット"
},
"commands": {
"current_theme_aria": "現在のテーマ",
"new_issue": "新規タスク",
"new_project": "新規プロジェクト",
+ "new_autopilot": "新規オートパイロット",
+ "chat_with_agent": "エージェントとチャット",
+ "change_theme": "テーマを切り替え...",
+ "send_feedback": "フィードバックを送信",
"copy_issue_link": "タスクのリンクをコピー",
"copy_identifier": "識別子をコピー ({{identifier}})",
"fold_all_comments": "すべてのコメントを折りたたむ",
- "unfold_all_comments": "すべてのコメントを展開",
- "switch_to_light": "ライトテーマに切り替え",
- "switch_to_dark": "ダークテーマに切り替え",
- "use_system_theme": "システムテーマを使用"
+ "unfold_all_comments": "すべてのコメントを展開"
+ },
+ "issue": {
+ "change_status": "ステータスを変更...",
+ "assign_to": "担当者を設定...",
+ "set_priority": "優先度を設定...",
+ "run_quick_action": "クイックアクションを実行...",
+ "quick_actions_available_other": "{{count}} 件利用可能",
+ "add_label": "ラベルを追加...",
+ "set_due_date": "期限を設定...",
+ "move_to_project": "プロジェクトに移動...",
+ "set_parent": "親タスクを設定...",
+ "cancel_run": "現在の実行をキャンセル",
+ "retry_run": "前回の実行を再試行",
+ "create_sub_issue": "新規サブタスク",
+ "subscribe": "購読",
+ "unsubscribe": "購読を解除",
+ "delete": "タスクを削除",
+ "delete_selected_other": "タスク {{count}} 件を削除"
+ },
+ "project": {
+ "change_status": "プロジェクトのステータスを変更...",
+ "new_issue": "このプロジェクトにタスクを作成",
+ "pin": "サイドバーにピン留め",
+ "unpin": "サイドバーのピン留めを解除",
+ "copy_link": "プロジェクトのリンクをコピー"
+ },
+ "agent": {
+ "chat": "{{name}} とチャット",
+ "assign_issue": "タスクを {{name}} に割り当て...",
+ "new_issue": "{{name}} 用の新規タスク",
+ "pin_in_chat": "チャットにピン留め",
+ "unpin_in_chat": "チャットのピン留めを解除"
+ },
+ "autopilot": {
+ "run_now": "今すぐ 1 回実行",
+ "pause": "一時停止",
+ "resume": "再開"
+ },
+ "inbox": {
+ "archive": "アーカイブ",
+ "mark_unread": "未読にする",
+ "mark_all_read": "インボックスをすべて既読にする",
+ "archive_all_read": "既読のインボックス項目をすべてアーカイブ"
+ },
+ "chat": {
+ "link_project": "プロジェクトに関連付け...",
+ "pin": "チャットをピン留め",
+ "unpin": "チャットのピン留めを解除",
+ "archive": "チャットをアーカイブ"
+ },
+ "pages": {
+ "status": "ステータス",
+ "priority": "優先度",
+ "assignee": "担当者",
+ "labels": "ラベル",
+ "due_date": "期限",
+ "project": "プロジェクト",
+ "parent": "親タスク",
+ "quick_actions": "クイックアクション",
+ "theme": "テーマ",
+ "project_status": "プロジェクトのステータス",
+ "no_project": "プロジェクトなし",
+ "current": "現在"
+ },
+ "theme": {
+ "light": "ライト",
+ "dark": "ダーク",
+ "system": "システム"
},
"toast": {
"link_copied": "リンクをコピーしました",
- "copied_identifier": "{{identifier}}をコピーしました"
+ "copied_identifier": "{{identifier}} をコピーしました",
+ "run_retried": "実行を再開しました",
+ "run_cancelled": "実行をキャンセルしました",
+ "subscribed": "購読しました",
+ "unsubscribed": "購読を解除しました",
+ "label_added": "ラベル {{name}} を追加しました",
+ "label_removed": "ラベル {{name}} を削除しました",
+ "label_failed": "一部のタスクにラベル {{name}} を追加できませんでした",
+ "update_failed": "更新に失敗しました",
+ "assigned": "{{identifier}} を {{name}} に割り当てました"
},
"empty": {
- "no_results": "結果が見つかりませんでした。",
- "type_to_search": "タスクやプロジェクトを検索するには入力してください"
+ "no_results": "結果が見つかりません。",
+ "no_labels": "ラベルがありません",
+ "type_to_find_issue": "入力してタスクを検索",
+ "type_to_find_people": "入力してメンバーとエージェントを検索"
+ },
+ "delegate": {
+ "heading": "エージェントに依頼",
+ "create_and_assign": "タスクを作成して {{name}} に割り当て",
+ "squad": "スクワッド",
+ "context_aria": "添付するコンテキスト",
+ "parent": "{{identifier}} の配下",
+ "pick_crumb": "選択",
+ "pick_another": "別のエージェントやスクワッドに依頼...",
+ "detected": "指示として認識"
+ },
+ "best": {
+ "assign": "{{subject}} を {{name}} に割り当て",
+ "chat": "{{name}} とチャット",
+ "new_issue_in": "{{name}} にタスクを作成"
+ },
+ "types": {
+ "issue": "タスク",
+ "project": "プロジェクト",
+ "agent": "エージェント",
+ "autopilot": "オートパイロット",
+ "squad": "スクワッド",
+ "member": "メンバー"
+ },
+ "footer": {
+ "navigate": "選択",
+ "select": "実行",
+ "open_in_new_tab": "新しいタブで開く",
+ "delegate": "作成して {{name}} に依頼",
+ "search_instead": "キーワードとして検索",
+ "back": "戻る",
+ "prefix_commands": "コマンド",
+ "prefix_issues": "タスク",
+ "prefix_people": "メンバーとエージェント"
},
"trigger": {
"label": "検索..."
diff --git a/packages/views/locales/ko/search.json b/packages/views/locales/ko/search.json
index c4159ea288..2e57a9adec 100644
--- a/packages/views/locales/ko/search.json
+++ b/packages/views/locales/ko/search.json
@@ -1,36 +1,169 @@
{
- "title": "검색",
- "description": "페이지, 태스크, 프로젝트, 멤버를 검색합니다",
- "placeholder": "명령어를 입력하거나 검색하세요...",
+ "title": "명령 바",
+ "description": "검색하고, 명령을 실행하거나, 에이전트에게 작업을 맡기세요",
+ "placeholder": "검색하거나 할 일을 입력하세요...",
+ "page_placeholder": "필터...",
+ "breadcrumb_aria": "현재 메뉴",
"groups": {
"pages": "페이지",
"commands": "명령어",
"members": "멤버",
+ "agents": "에이전트",
+ "squads": "스쿼드",
"projects": "프로젝트",
"issues": "태스크",
+ "autopilots": "오토파일럿",
+ "chats": "채팅",
+ "skills": "스킬",
"cancelled": "취소됨",
"recent": "최근 항목",
- "workspaces": "워크스페이스"
+ "workspaces": "워크스페이스",
+ "new": "새로 만들기",
+ "best_match": "가장 일치",
+ "actions": "작업"
+ },
+ "context": {
+ "current_issue": "현재 태스크",
+ "selected_issues_other": "선택한 태스크 {{count}}개",
+ "current_project": "현재 프로젝트",
+ "current_agent": "현재 에이전트",
+ "current_autopilot": "현재 오토파일럿",
+ "inbox": "인박스",
+ "current_chat": "현재 채팅"
},
"commands": {
"current_theme_aria": "현재 테마",
"new_issue": "새 태스크",
"new_project": "새 프로젝트",
+ "new_autopilot": "새 오토파일럿",
+ "chat_with_agent": "에이전트와 채팅",
+ "change_theme": "테마 변경...",
+ "send_feedback": "피드백 보내기",
"copy_issue_link": "태스크 링크 복사",
"copy_identifier": "식별자 복사 ({{identifier}})",
"fold_all_comments": "모든 댓글 접기",
- "unfold_all_comments": "모든 댓글 펼치기",
- "switch_to_light": "라이트 테마로 전환",
- "switch_to_dark": "다크 테마로 전환",
- "use_system_theme": "시스템 테마 사용"
+ "unfold_all_comments": "모든 댓글 펼치기"
+ },
+ "issue": {
+ "change_status": "상태 변경...",
+ "assign_to": "담당자 지정...",
+ "set_priority": "우선순위 설정...",
+ "run_quick_action": "빠른 작업 실행...",
+ "quick_actions_available_other": "{{count}}개 사용 가능",
+ "add_label": "라벨 추가...",
+ "set_due_date": "마감일 설정...",
+ "move_to_project": "프로젝트로 이동...",
+ "set_parent": "상위 태스크 설정...",
+ "cancel_run": "현재 실행 취소",
+ "retry_run": "마지막 실행 재시도",
+ "create_sub_issue": "새 하위 태스크",
+ "subscribe": "구독",
+ "unsubscribe": "구독 취소",
+ "delete": "태스크 삭제",
+ "delete_selected_other": "태스크 {{count}}개 삭제"
+ },
+ "project": {
+ "change_status": "프로젝트 상태 변경...",
+ "new_issue": "이 프로젝트에 새 태스크",
+ "pin": "사이드바에 고정",
+ "unpin": "사이드바 고정 해제",
+ "copy_link": "프로젝트 링크 복사"
+ },
+ "agent": {
+ "chat": "{{name}}와 채팅",
+ "assign_issue": "{{name}}에게 태스크 지정...",
+ "new_issue": "{{name}}에게 새 태스크",
+ "pin_in_chat": "채팅에 고정",
+ "unpin_in_chat": "채팅 고정 해제"
+ },
+ "autopilot": {
+ "run_now": "지금 한 번 실행",
+ "pause": "일시 중지",
+ "resume": "다시 시작"
+ },
+ "inbox": {
+ "archive": "보관",
+ "mark_unread": "읽지 않음으로 표시",
+ "mark_all_read": "인박스 모두 읽음으로 표시",
+ "archive_all_read": "읽은 인박스 항목 모두 보관"
+ },
+ "chat": {
+ "link_project": "프로젝트에 연결...",
+ "pin": "채팅 고정",
+ "unpin": "채팅 고정 해제",
+ "archive": "채팅 보관"
+ },
+ "pages": {
+ "status": "상태",
+ "priority": "우선순위",
+ "assignee": "담당자",
+ "labels": "라벨",
+ "due_date": "마감일",
+ "project": "프로젝트",
+ "parent": "상위 태스크",
+ "quick_actions": "빠른 작업",
+ "theme": "테마",
+ "project_status": "프로젝트 상태",
+ "no_project": "프로젝트 없음",
+ "current": "현재"
+ },
+ "theme": {
+ "light": "라이트",
+ "dark": "다크",
+ "system": "시스템"
},
"toast": {
"link_copied": "링크를 복사했습니다",
- "copied_identifier": "{{identifier}}를 복사했습니다"
+ "copied_identifier": "{{identifier}}를 복사했습니다",
+ "run_retried": "실행을 다시 시작했습니다",
+ "run_cancelled": "실행을 취소했습니다",
+ "subscribed": "구독했습니다",
+ "unsubscribed": "구독을 취소했습니다",
+ "label_added": "라벨 {{name}}을 추가했습니다",
+ "label_removed": "라벨 {{name}}을 제거했습니다",
+ "label_failed": "일부 태스크에 라벨 {{name}}을 추가하지 못했습니다",
+ "update_failed": "업데이트에 실패했습니다",
+ "assigned": "{{identifier}}를 {{name}}에게 지정했습니다"
},
"empty": {
- "no_results": "검색 결과가 없습니다.",
- "type_to_search": "태스크와 프로젝트를 검색해 보세요"
+ "no_results": "결과가 없습니다.",
+ "no_labels": "라벨이 없습니다",
+ "type_to_find_issue": "입력해서 태스크 찾기",
+ "type_to_find_people": "입력해서 멤버와 에이전트 찾기"
+ },
+ "delegate": {
+ "heading": "에이전트에게 맡기기",
+ "create_and_assign": "새 태스크를 만들어 {{name}}에게 지정",
+ "squad": "스쿼드",
+ "context_aria": "함께 보낼 컨텍스트",
+ "parent": "{{identifier}} 하위",
+ "pick_crumb": "선택",
+ "pick_another": "다른 에이전트나 스쿼드에게 맡기기...",
+ "detected": "지시로 인식"
+ },
+ "best": {
+ "assign": "{{subject}}를 {{name}}에게 지정",
+ "chat": "{{name}}와 채팅",
+ "new_issue_in": "{{name}}에 새 태스크"
+ },
+ "types": {
+ "issue": "태스크",
+ "project": "프로젝트",
+ "agent": "에이전트",
+ "autopilot": "오토파일럿",
+ "squad": "스쿼드",
+ "member": "멤버"
+ },
+ "footer": {
+ "navigate": "선택",
+ "select": "실행",
+ "open_in_new_tab": "새 탭에서 열기",
+ "delegate": "만들어서 {{name}}에게 맡기기",
+ "search_instead": "키워드로 검색",
+ "back": "뒤로",
+ "prefix_commands": "명령어",
+ "prefix_issues": "태스크",
+ "prefix_people": "멤버와 에이전트"
},
"trigger": {
"label": "검색..."
diff --git a/packages/views/locales/zh-Hans/search.json b/packages/views/locales/zh-Hans/search.json
index e5539b16f5..8d68f658d0 100644
--- a/packages/views/locales/zh-Hans/search.json
+++ b/packages/views/locales/zh-Hans/search.json
@@ -1,36 +1,169 @@
{
- "title": "搜索",
- "description": "搜索页面、任务、项目和成员",
- "placeholder": "输入命令或关键词搜索...",
+ "title": "命令栏",
+ "description": "搜索、执行命令,或把工作交给智能体",
+ "placeholder": "搜索,或输入要做的事...",
+ "page_placeholder": "筛选...",
+ "breadcrumb_aria": "当前菜单",
"groups": {
"pages": "页面",
"commands": "命令",
"members": "成员",
+ "agents": "智能体",
+ "squads": "小队",
"projects": "项目",
"issues": "任务",
+ "autopilots": "自动化",
+ "chats": "对话",
+ "skills": "Skills",
"cancelled": "已取消",
"recent": "最近",
- "workspaces": "工作区"
+ "workspaces": "工作区",
+ "new": "新建",
+ "best_match": "最佳匹配",
+ "actions": "操作"
+ },
+ "context": {
+ "current_issue": "当前任务",
+ "selected_issues_other": "已选 {{count}} 个任务",
+ "current_project": "当前项目",
+ "current_agent": "当前智能体",
+ "current_autopilot": "当前自动化",
+ "inbox": "收件箱",
+ "current_chat": "当前对话"
},
"commands": {
"current_theme_aria": "当前主题",
"new_issue": "新建任务",
"new_project": "新建项目",
+ "new_autopilot": "新建自动化",
+ "chat_with_agent": "和智能体对话",
+ "change_theme": "切换主题...",
+ "send_feedback": "发送反馈",
"copy_issue_link": "复制任务链接",
"copy_identifier": "复制标识符 ({{identifier}})",
"fold_all_comments": "收起全部评论",
- "unfold_all_comments": "展开全部评论",
- "switch_to_light": "切换到浅色主题",
- "switch_to_dark": "切换到深色主题",
- "use_system_theme": "跟随系统主题"
+ "unfold_all_comments": "展开全部评论"
+ },
+ "issue": {
+ "change_status": "更改状态...",
+ "assign_to": "指派给...",
+ "set_priority": "设置优先级...",
+ "run_quick_action": "运行快捷操作...",
+ "quick_actions_available_other": "{{count}} 条可用",
+ "add_label": "添加标签...",
+ "set_due_date": "设置截止日期...",
+ "move_to_project": "移动到项目...",
+ "set_parent": "设置父任务...",
+ "cancel_run": "取消当前运行",
+ "retry_run": "重试上次运行",
+ "create_sub_issue": "新建子任务",
+ "subscribe": "订阅",
+ "unsubscribe": "取消订阅",
+ "delete": "删除任务",
+ "delete_selected_other": "删除 {{count}} 个任务"
+ },
+ "project": {
+ "change_status": "更改项目状态...",
+ "new_issue": "在此项目下新建任务",
+ "pin": "固定到侧边栏",
+ "unpin": "从侧边栏取消固定",
+ "copy_link": "复制项目链接"
+ },
+ "agent": {
+ "chat": "和 {{name}} 对话",
+ "assign_issue": "把任务指派给 {{name}}...",
+ "new_issue": "新建任务给 {{name}}",
+ "pin_in_chat": "在聊天里固定",
+ "unpin_in_chat": "从聊天里取消固定"
+ },
+ "autopilot": {
+ "run_now": "立即运行一次",
+ "pause": "暂停",
+ "resume": "启用"
+ },
+ "inbox": {
+ "archive": "归档",
+ "mark_unread": "标为未读",
+ "mark_all_read": "收件箱全部标为已读",
+ "archive_all_read": "归档收件箱全部已读"
+ },
+ "chat": {
+ "link_project": "关联到项目...",
+ "pin": "固定对话",
+ "unpin": "取消固定对话",
+ "archive": "归档对话"
+ },
+ "pages": {
+ "status": "状态",
+ "priority": "优先级",
+ "assignee": "负责人",
+ "labels": "标签",
+ "due_date": "截止日期",
+ "project": "项目",
+ "parent": "父任务",
+ "quick_actions": "快捷操作",
+ "theme": "主题",
+ "project_status": "项目状态",
+ "no_project": "无项目",
+ "current": "当前"
+ },
+ "theme": {
+ "light": "浅色",
+ "dark": "深色",
+ "system": "跟随系统"
},
"toast": {
"link_copied": "已复制链接",
- "copied_identifier": "已复制 {{identifier}}"
+ "copied_identifier": "已复制 {{identifier}}",
+ "run_retried": "已重新运行",
+ "run_cancelled": "已取消运行",
+ "subscribed": "已订阅",
+ "unsubscribed": "已取消订阅",
+ "label_added": "已添加标签 {{name}}",
+ "label_removed": "已移除标签 {{name}}",
+ "label_failed": "未能给所有任务添加标签 {{name}}",
+ "update_failed": "更新失败",
+ "assigned": "已把 {{identifier}} 指派给 {{name}}"
},
"empty": {
"no_results": "未找到结果。",
- "type_to_search": "输入关键词搜索任务和项目"
+ "no_labels": "没有标签",
+ "type_to_find_issue": "输入关键词查找任务",
+ "type_to_find_people": "输入关键词查找成员和智能体"
+ },
+ "delegate": {
+ "heading": "交给智能体",
+ "create_and_assign": "新建任务并指派给 {{name}}",
+ "squad": "小队",
+ "context_aria": "附带上下文",
+ "parent": "挂在 {{identifier}} 下",
+ "pick_crumb": "选择",
+ "pick_another": "换一个智能体或小队...",
+ "detected": "识别为指令"
+ },
+ "best": {
+ "assign": "把 {{subject}} 指派给 {{name}}",
+ "chat": "和 {{name}} 对话",
+ "new_issue_in": "在 {{name}} 下新建任务"
+ },
+ "types": {
+ "issue": "任务",
+ "project": "项目",
+ "agent": "智能体",
+ "autopilot": "自动化",
+ "squad": "小队",
+ "member": "成员"
+ },
+ "footer": {
+ "navigate": "选择",
+ "select": "执行",
+ "open_in_new_tab": "在新标签页打开",
+ "delegate": "新建并交给 {{name}}",
+ "search_instead": "仅作为关键词搜索",
+ "back": "返回",
+ "prefix_commands": "命令",
+ "prefix_issues": "任务",
+ "prefix_people": "人和智能体"
},
"trigger": {
"label": "搜索..."
diff --git a/packages/views/locales/zh-Hant/search.json b/packages/views/locales/zh-Hant/search.json
index 1db3ae3229..3a593db09c 100644
--- a/packages/views/locales/zh-Hant/search.json
+++ b/packages/views/locales/zh-Hant/search.json
@@ -1,36 +1,169 @@
{
- "title": "搜尋",
- "description": "搜尋頁面、任務、專案和成員",
- "placeholder": "輸入命令或關鍵詞搜尋...",
+ "title": "命令列",
+ "description": "搜尋、執行命令,或把工作交給智慧體",
+ "placeholder": "搜尋,或輸入要做的事...",
+ "page_placeholder": "篩選...",
+ "breadcrumb_aria": "目前選單",
"groups": {
"pages": "頁面",
"commands": "命令",
"members": "成員",
+ "agents": "智慧體",
+ "squads": "小隊",
"projects": "專案",
"issues": "任務",
+ "autopilots": "自動化",
+ "chats": "對話",
+ "skills": "Skills",
"cancelled": "已取消",
"recent": "最近",
- "workspaces": "工作區"
+ "workspaces": "工作區",
+ "new": "新建",
+ "best_match": "最佳符合",
+ "actions": "操作"
+ },
+ "context": {
+ "current_issue": "目前任務",
+ "selected_issues_other": "已選 {{count}} 個任務",
+ "current_project": "目前專案",
+ "current_agent": "目前智慧體",
+ "current_autopilot": "目前自動化",
+ "inbox": "收件箱",
+ "current_chat": "目前對話"
},
"commands": {
"current_theme_aria": "當前主題",
"new_issue": "新建任務",
"new_project": "新建專案",
+ "new_autopilot": "新建自動化",
+ "chat_with_agent": "和智慧體對話",
+ "change_theme": "切換主題...",
+ "send_feedback": "傳送意見回饋",
"copy_issue_link": "複製任務連結",
"copy_identifier": "複製識別符號 ({{identifier}})",
"fold_all_comments": "收起全部評論",
- "unfold_all_comments": "展開全部評論",
- "switch_to_light": "切換到淺色主題",
- "switch_to_dark": "切換到深色主題",
- "use_system_theme": "跟隨系統主題"
+ "unfold_all_comments": "展開全部評論"
+ },
+ "issue": {
+ "change_status": "變更狀態...",
+ "assign_to": "指派給...",
+ "set_priority": "設定優先級...",
+ "run_quick_action": "執行快捷操作...",
+ "quick_actions_available_other": "{{count}} 條可用",
+ "add_label": "新增標籤...",
+ "set_due_date": "設定截止日期...",
+ "move_to_project": "移動到專案...",
+ "set_parent": "設定父任務...",
+ "cancel_run": "取消目前執行",
+ "retry_run": "重試上次執行",
+ "create_sub_issue": "新建子任務",
+ "subscribe": "訂閱",
+ "unsubscribe": "取消訂閱",
+ "delete": "刪除任務",
+ "delete_selected_other": "刪除 {{count}} 個任務"
+ },
+ "project": {
+ "change_status": "變更專案狀態...",
+ "new_issue": "在此專案下新建任務",
+ "pin": "固定到側邊欄",
+ "unpin": "從側邊欄取消固定",
+ "copy_link": "複製專案連結"
+ },
+ "agent": {
+ "chat": "和 {{name}} 對話",
+ "assign_issue": "把任務指派給 {{name}}...",
+ "new_issue": "新建任務給 {{name}}",
+ "pin_in_chat": "在聊天裡固定",
+ "unpin_in_chat": "從聊天裡取消固定"
+ },
+ "autopilot": {
+ "run_now": "立即執行一次",
+ "pause": "暫停",
+ "resume": "啟用"
+ },
+ "inbox": {
+ "archive": "封存",
+ "mark_unread": "標為未讀",
+ "mark_all_read": "收件箱全部標為已讀",
+ "archive_all_read": "封存收件箱全部已讀"
+ },
+ "chat": {
+ "link_project": "關聯到專案...",
+ "pin": "固定對話",
+ "unpin": "取消固定對話",
+ "archive": "封存對話"
+ },
+ "pages": {
+ "status": "狀態",
+ "priority": "優先級",
+ "assignee": "負責人",
+ "labels": "標籤",
+ "due_date": "截止日期",
+ "project": "專案",
+ "parent": "父任務",
+ "quick_actions": "快捷操作",
+ "theme": "主題",
+ "project_status": "專案狀態",
+ "no_project": "無專案",
+ "current": "目前"
+ },
+ "theme": {
+ "light": "淺色",
+ "dark": "深色",
+ "system": "跟隨系統"
},
"toast": {
"link_copied": "已複製連結",
- "copied_identifier": "已複製 {{identifier}}"
+ "copied_identifier": "已複製 {{identifier}}",
+ "run_retried": "已重新執行",
+ "run_cancelled": "已取消執行",
+ "subscribed": "已訂閱",
+ "unsubscribed": "已取消訂閱",
+ "label_added": "已新增標籤 {{name}}",
+ "label_removed": "已移除標籤 {{name}}",
+ "label_failed": "未能給所有任務新增標籤 {{name}}",
+ "update_failed": "更新失敗",
+ "assigned": "已把 {{identifier}} 指派給 {{name}}"
},
"empty": {
"no_results": "未找到結果。",
- "type_to_search": "輸入關鍵詞搜尋任務和專案"
+ "no_labels": "沒有標籤",
+ "type_to_find_issue": "輸入關鍵詞查找任務",
+ "type_to_find_people": "輸入關鍵詞查找成員和智慧體"
+ },
+ "delegate": {
+ "heading": "交給智慧體",
+ "create_and_assign": "新建任務並指派給 {{name}}",
+ "squad": "小隊",
+ "context_aria": "附帶上下文",
+ "parent": "掛在 {{identifier}} 下",
+ "pick_crumb": "選擇",
+ "pick_another": "換一個智慧體或小隊...",
+ "detected": "識別為指令"
+ },
+ "best": {
+ "assign": "把 {{subject}} 指派給 {{name}}",
+ "chat": "和 {{name}} 對話",
+ "new_issue_in": "在 {{name}} 下新建任務"
+ },
+ "types": {
+ "issue": "任務",
+ "project": "專案",
+ "agent": "智慧體",
+ "autopilot": "自動化",
+ "squad": "小隊",
+ "member": "成員"
+ },
+ "footer": {
+ "navigate": "選擇",
+ "select": "執行",
+ "open_in_new_tab": "在新分頁開啟",
+ "delegate": "新建並交給 {{name}}",
+ "search_instead": "僅作為關鍵詞搜尋",
+ "back": "返回",
+ "prefix_commands": "命令",
+ "prefix_issues": "任務",
+ "prefix_people": "人和智慧體"
},
"trigger": {
"label": "搜尋..."
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index be113f6618..61b147a5cd 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -1,6 +1,7 @@
"use client";
import { useMemo, useState, useCallback, useRef, useEffect } from "react";
+import { useRegisterCommandBarContext } from "../../search/register-context";
import { useDefaultLayout, usePanelRef } from "react-resizable-panels";
import { Check, ChevronRight, Link2, MoreHorizontal, PanelRight, Pin, PinOff, Trash2, UserMinus } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
@@ -119,6 +120,9 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
const router = useNavigation();
const userId = useAuthStore((s) => s.user?.id);
const { data: project, isLoading } = useQuery(projectDetailOptions(wsId, projectId));
+ useRegisterCommandBarContext(
+ useMemo(() => (project ? { kind: "project", project } : null), [project]),
+ );
const recordRecentContext = useRecentContextStore((s) => s.recordVisit);
useEffect(() => {
if (project) {
diff --git a/packages/views/search/commands/context-commands.tsx b/packages/views/search/commands/context-commands.tsx
new file mode 100644
index 0000000000..b3543a982b
--- /dev/null
+++ b/packages/views/search/commands/context-commands.tsx
@@ -0,0 +1,308 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import {
+ Archive,
+ CircleDashed,
+ FolderInput,
+ Link2,
+ MailOpen,
+ MessageSquare,
+ Pause,
+ Pin,
+ PinOff,
+ Play,
+ SquarePen,
+ UserPlus,
+} from "lucide-react";
+import { isAgentRuntimeBound } from "@multica/core/agents";
+import { useAuthStore } from "@multica/core/auth";
+import type { CommandBarContext } from "@multica/core/command-bar";
+import { useUpdateAutopilot } from "@multica/core/autopilots/mutations";
+import { usePinChatAgent, useSetChatSessionPinned, useUnpinChatAgent } from "@multica/core/chat/mutations";
+import { chatPinnedAgentsOptions } from "@multica/core/chat/queries";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { openCreateIssueWithPreference } from "@multica/core/issues/stores";
+import { useModalStore } from "@multica/core/modals";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { canAssignAgentToIssue, useCurrentMember } from "@multica/core/permissions";
+import { pinListOptions, useCreatePin, useDeletePin } from "@multica/core/pins";
+import { getShortcut } from "@multica/core/shortcuts";
+import { copyText } from "@multica/ui/lib/clipboard";
+import { useRunAutopilotNow } from "../../autopilots/components/use-run-autopilot-now";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import type { PaletteCommand, PaletteCommandGroup } from "../types";
+import { ContextHeading } from "./context-heading";
+
+type ContextOf<K extends CommandBarContext["kind"]> = Extract<CommandBarContext, { kind: K }>;
+
+export function useProjectCommandGroup(
+ context: ContextOf<"project"> | null,
+): PaletteCommandGroup | null {
+ const { t } = useT("search");
+ const wsId = useWorkspaceId();
+ const p = useWorkspacePaths();
+ const { getShareableUrl } = useNavigation();
+ const userId = useAuthStore((s) => s.user?.id ?? "");
+ const { data: pins = [] } = useQuery({
+ ...pinListOptions(wsId, userId),
+ enabled: !!context && !!userId,
+ });
+ const createPin = useCreatePin();
+ const deletePin = useDeletePin();
+
+ return useMemo(() => {
+ if (!context) return null;
+ const { project } = context;
+ const pinned = pins.some((pin) => pin.item_type === "project" && pin.item_id === project.id);
+ const commands: PaletteCommand[] = [
+ {
+ id: "project-status",
+ label: t(($) => $.project.change_status),
+ icon: CircleDashed,
+ keywords: ["status", "state", "状态"],
+ page: { type: "project-status", project },
+ crumb: project.title,
+ primary: true,
+ },
+ {
+ id: "project-new-issue",
+ label: t(($) => $.project.new_issue),
+ icon: SquarePen,
+ keywords: ["new", "issue", "create", "新建", "任务"],
+ run: () => openCreateIssueWithPreference({ project_id: project.id }),
+ primary: true,
+ },
+ {
+ id: "project-pin",
+ label: pinned ? t(($) => $.project.unpin) : t(($) => $.project.pin),
+ icon: pinned ? PinOff : Pin,
+ keywords: ["pin", "sidebar", "固定"],
+ run: () => {
+ if (pinned) deletePin.mutate({ itemType: "project", itemId: project.id });
+ else createPin.mutate({ item_type: "project", item_id: project.id });
+ },
+ },
+ {
+ id: "project-copy-link",
+ label: t(($) => $.project.copy_link),
+ icon: Link2,
+ keywords: ["copy", "link", "share", "url", "复制", "链接"],
+ run: () => {
+ void copyText(getShareableUrl(p.projectDetail(project.id))).then((ok) => {
+ if (ok) toast.success(t(($) => $.toast.link_copied));
+ });
+ },
+ primary: true,
+ },
+ ];
+ return {
+ id: "context-project",
+ heading: <ContextHeading label={t(($) => $.context.current_project)} subject={project.title} />,
+ commands,
+ };
+ }, [context, createPin, deletePin, getShareableUrl, p, pins, t]);
+}
+
+export function useAgentCommandGroup(context: ContextOf<"agent"> | null): PaletteCommandGroup | null {
+ const { t } = useT("search");
+ const { t: tAgents } = useT("agents");
+ const wsId = useWorkspaceId();
+ const p = useWorkspacePaths();
+ const navigation = useNavigation();
+ const { userId, role } = useCurrentMember(wsId);
+ const { data: pinnedAgents = [] } = useQuery({
+ ...chatPinnedAgentsOptions(wsId),
+ enabled: !!context,
+ });
+ const pinAgent = usePinChatAgent();
+ const unpinAgent = useUnpinChatAgent();
+
+ return useMemo(() => {
+ if (!context) return null;
+ const { agent } = context;
+ if (agent.archived_at) return null;
+ const allowed = canAssignAgentToIssue(agent, { userId, role }).allowed;
+ const runtimeBound = isAgentRuntimeBound(agent);
+ // Same gate as the agent page's own buttons: say why instead of opening
+ // a chat or a form that cannot start a run.
+ const guard = (proceed: () => void) => () => {
+ if (!allowed) {
+ toast.error(tAgents(($) => $.detail.dm_no_permission_toast));
+ return;
+ }
+ if (!runtimeBound) {
+ toast.error(tAgents(($) => $.detail.runtime_required_toast));
+ return;
+ }
+ proceed();
+ };
+ const pinned = pinnedAgents.some((pin) => pin.agent_id === agent.id);
+ const commands: PaletteCommand[] = [
+ {
+ id: "agent-chat",
+ label: t(($) => $.agent.chat, { name: agent.name }),
+ icon: MessageSquare,
+ keywords: ["chat", "dm", "message", "talk", "对话", "聊天"],
+ run: guard(() => navigation.push(p.chatWithAgent(agent.id))),
+ primary: true,
+ },
+ {
+ id: "agent-assign-issue",
+ label: t(($) => $.agent.assign_issue, { name: agent.name }),
+ icon: UserPlus,
+ keywords: ["assign", "issue", "指派", "任务"],
+ page: allowed && runtimeBound ? { type: "agent-assign-issue", agent } : undefined,
+ crumb: agent.name,
+ run: guard(() => {}),
+ primary: true,
+ },
+ {
+ id: "agent-new-issue",
+ label: t(($) => $.agent.new_issue, { name: agent.name }),
+ icon: SquarePen,
+ keywords: ["new", "issue", "create", "新建", "任务"],
+ run: guard(() =>
+ useModalStore.getState().open("quick-create-issue", { agent_id: agent.id }),
+ ),
+ },
+ {
+ id: "agent-pin-chat",
+ label: pinned ? t(($) => $.agent.unpin_in_chat) : t(($) => $.agent.pin_in_chat),
+ icon: pinned ? PinOff : Pin,
+ keywords: ["pin", "chat", "固定", "聊天"],
+ run: () => {
+ if (pinned) unpinAgent.mutate(agent.id);
+ else pinAgent.mutate(agent.id);
+ },
+ },
+ ];
+ return {
+ id: "context-agent",
+ heading: <ContextHeading label={t(($) => $.context.current_agent)} subject={agent.name} />,
+ commands,
+ };
+ }, [context, navigation, p, pinAgent, pinnedAgents, role, t, tAgents, unpinAgent, userId]);
+}
+
+export function useAutopilotCommandGroup(
+ context: ContextOf<"autopilot"> | null,
+): PaletteCommandGroup | null {
+ const { t } = useT("search");
+ const { runNow } = useRunAutopilotNow();
+ const updateAutopilot = useUpdateAutopilot();
+
+ return useMemo(() => {
+ if (!context) return null;
+ const { autopilot } = context;
+ if (autopilot.status === "archived" || autopilot.can_write === false) return null;
+ const active = autopilot.status === "active";
+ const commands: PaletteCommand[] = [];
+ if (active) {
+ commands.push({
+ id: "autopilot-run-now",
+ label: t(($) => $.autopilot.run_now),
+ icon: Play,
+ keywords: ["run", "trigger", "now", "运行", "触发"],
+ run: () => void runNow(autopilot.id),
+ primary: true,
+ });
+ }
+ commands.push({
+ id: "autopilot-toggle",
+ label: active ? t(($) => $.autopilot.pause) : t(($) => $.autopilot.resume),
+ icon: active ? Pause : Play,
+ keywords: ["pause", "resume", "enable", "disable", "暂停", "启用"],
+ run: () =>
+ updateAutopilot.mutate({ id: autopilot.id, status: active ? "paused" : "active" }),
+ primary: true,
+ });
+ return {
+ id: "context-autopilot",
+ heading: (
+ <ContextHeading label={t(($) => $.context.current_autopilot)} subject={autopilot.title} />
+ ),
+ commands,
+ };
+ }, [context, runNow, t, updateAutopilot]);
+}
+
+export function useInboxCommandGroup(context: ContextOf<"inbox"> | null): PaletteCommandGroup | null {
+ const { t } = useT("search");
+ return useMemo(() => {
+ if (!context?.item) return null;
+ const { item } = context;
+ const commands: PaletteCommand[] = [
+ {
+ id: "inbox-archive",
+ label: t(($) => $.inbox.archive),
+ icon: Archive,
+ keywords: ["archive", "done", "归档"],
+ shortcut: getShortcut("archiveInboxItem"),
+ run: () => context.archive(item.id),
+ primary: true,
+ },
+ ];
+ if (item.read) {
+ commands.push({
+ id: "inbox-mark-unread",
+ label: t(($) => $.inbox.mark_unread),
+ icon: MailOpen,
+ keywords: ["unread", "未读"],
+ run: () => context.markUnread(item.id),
+ primary: true,
+ });
+ }
+ return {
+ id: "context-inbox",
+ heading: <ContextHeading label={t(($) => $.context.inbox)} detail={item.title} />,
+ commands,
+ };
+ }, [context, t]);
+}
+
+export function useChatCommandGroup(context: ContextOf<"chat"> | null): PaletteCommandGroup | null {
+ const { t } = useT("search");
+ const setPinned = useSetChatSessionPinned();
+ return useMemo(() => {
+ if (!context) return null;
+ const { session } = context;
+ if (session.status === "archived") return null;
+ const pinned = !!session.pinned;
+ const commands: PaletteCommand[] = [
+ {
+ id: "chat-link-project",
+ label: t(($) => $.chat.link_project),
+ icon: FolderInput,
+ keywords: ["project", "context", "项目", "关联"],
+ page: { type: "chat-project", session, changeProject: context.changeProject },
+ crumb: session.title,
+ primary: true,
+ },
+ {
+ id: "chat-pin",
+ label: pinned ? t(($) => $.chat.unpin) : t(($) => $.chat.pin),
+ icon: pinned ? PinOff : Pin,
+ keywords: ["pin", "固定"],
+ run: () => setPinned.mutate({ sessionId: session.id, pinned: !pinned }),
+ primary: true,
+ },
+ {
+ id: "chat-archive",
+ label: t(($) => $.chat.archive),
+ icon: Archive,
+ keywords: ["archive", "归档"],
+ run: () => context.archive(session),
+ primary: true,
+ },
+ ];
+ return {
+ id: "context-chat",
+ heading: <ContextHeading label={t(($) => $.context.current_chat)} detail={session.title} />,
+ commands,
+ };
+ }, [context, setPinned, t]);
+}
diff --git a/packages/views/search/commands/context-heading.tsx b/packages/views/search/commands/context-heading.tsx
new file mode 100644
index 0000000000..5247ef5221
--- /dev/null
+++ b/packages/views/search/commands/context-heading.tsx
@@ -0,0 +1,27 @@
+import type { ReactNode } from "react";
+
+/**
+ * "Current issue · MUL-12 Fix login". The object a group acts on is named in
+ * its heading, not in the input: the input always searches everything.
+ */
+export function ContextHeading({
+ label,
+ subject,
+ detail,
+ icon,
+}: {
+ label: string;
+ subject?: string;
+ detail?: string;
+ icon?: ReactNode;
+}) {
+ return (
+ <>
+ <span className="shrink-0">{label}</span>
+ {(subject || detail) && <span aria-hidden="true">·</span>}
+ {icon}
+ {subject && <span className="shrink-0 font-semibold text-foreground">{subject}</span>}
+ {detail && <span className="min-w-0 truncate font-normal">{detail}</span>}
+ </>
+ );
+}
diff --git a/packages/views/search/commands/global-commands.tsx b/packages/views/search/commands/global-commands.tsx
new file mode 100644
index 0000000000..0054f4a357
--- /dev/null
+++ b/packages/views/search/commands/global-commands.tsx
@@ -0,0 +1,160 @@
+"use client";
+
+import { useMemo } from "react";
+import { toast } from "sonner";
+import {
+ Archive,
+ CheckCheck,
+ FolderPlus,
+ MessageCircleQuestion,
+ MessageSquare,
+ Palette,
+ SquarePen,
+ Zap,
+} from "lucide-react";
+import { useChatStore } from "@multica/core/chat";
+import type { CommandBarContext } from "@multica/core/command-bar";
+import { useArchiveAllReadInbox, useMarkAllInboxRead } from "@multica/core/inbox/mutations";
+import { openCreateIssueWithPreference } from "@multica/core/issues/stores";
+import { useModalStore } from "@multica/core/modals";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { useShortcut } from "@multica/core/shortcuts";
+import { isFloatingChatRouteSuppressed } from "../../chat/floating-chat-visibility";
+import { useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { usePalette } from "../palette-context";
+import type { PaletteCommand } from "../types";
+
+/**
+ * Commands that exist everywhere. `primary` ones form the empty state's New
+ * group; the rest surface once the user types.
+ */
+export function useGlobalCommands(contexts: readonly CommandBarContext[]): PaletteCommand[] {
+ const { t } = useT("search");
+ const { t: tInbox } = useT("inbox");
+ const palette = usePalette();
+ const p = useWorkspacePaths();
+ const navigation = useNavigation();
+ const createIssueShortcut = useShortcut("createIssue");
+ const toggleChatShortcut = useShortcut("toggleChat");
+ const markAllRead = useMarkAllInboxRead();
+ const archiveAllRead = useArchiveAllReadInbox();
+
+ const projectContext = contexts.find((c) => c.kind === "project");
+ const projectId = projectContext?.kind === "project" ? projectContext.project.id : null;
+ const inboxContext = contexts.find((c) => c.kind === "inbox");
+ const inbox = inboxContext?.kind === "inbox" ? inboxContext : null;
+ const { pathname } = navigation;
+
+ return useMemo<PaletteCommand[]>(() => {
+ const chatPath = p.chat();
+ return [
+ {
+ id: "new-issue",
+ label: t(($) => $.commands.new_issue),
+ icon: SquarePen,
+ keywords: ["new", "issue", "create", "add", "新建", "任务"],
+ shortcut: createIssueShortcut,
+ run: () => openCreateIssueWithPreference(projectId ? { project_id: projectId } : undefined),
+ primary: true,
+ },
+ {
+ id: "chat-with-agent",
+ label: t(($) => $.commands.chat_with_agent),
+ icon: MessageSquare,
+ keywords: ["chat", "agent", "talk", "ask", "对话", "聊天", "智能体"],
+ shortcut: toggleChatShortcut,
+ run: () => {
+ // ⌘J opens the floating chat where it is available; elsewhere (the
+ // Chat page itself, or with the overlay turned off) go to Chat.
+ const chat = useChatStore.getState();
+ if (chat.floatingChatEnabled && !isFloatingChatRouteSuppressed(pathname, chatPath)) {
+ chat.setOpen(true);
+ } else {
+ navigation.push(chatPath);
+ }
+ },
+ primary: true,
+ },
+ {
+ id: "new-project",
+ label: t(($) => $.commands.new_project),
+ icon: FolderPlus,
+ keywords: ["new", "project", "create", "add", "新建", "项目"],
+ run: () => useModalStore.getState().open("create-project"),
+ },
+ {
+ id: "new-autopilot",
+ label: t(($) => $.commands.new_autopilot),
+ icon: Zap,
+ keywords: ["new", "autopilot", "automation", "schedule", "create", "新建", "自动化"],
+ run: () => palette.openHostDialog({ type: "new-autopilot" }),
+ },
+ {
+ id: "inbox-mark-all-read",
+ label: t(($) => $.inbox.mark_all_read),
+ icon: CheckCheck,
+ keywords: ["inbox", "read", "all", "收件箱", "已读"],
+ run: () => {
+ if (inbox) {
+ inbox.markAllRead();
+ return;
+ }
+ markAllRead.mutateAsync(undefined).catch((err: unknown) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : tInbox(($) => $.errors.mark_all_read_failed),
+ ),
+ );
+ },
+ },
+ {
+ id: "inbox-archive-all-read",
+ label: t(($) => $.inbox.archive_all_read),
+ icon: Archive,
+ keywords: ["inbox", "archive", "read", "收件箱", "归档"],
+ run: () => {
+ if (inbox) {
+ inbox.archiveAllRead();
+ return;
+ }
+ archiveAllRead.mutateAsync(undefined).catch((err: unknown) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : tInbox(($) => $.errors.archive_all_read_failed),
+ ),
+ );
+ },
+ },
+ {
+ id: "theme",
+ label: t(($) => $.commands.change_theme),
+ icon: Palette,
+ keywords: ["theme", "appearance", "dark", "light", "system", "mode", "主题", "深色", "浅色"],
+ page: { type: "theme" },
+ },
+ {
+ id: "feedback",
+ label: t(($) => $.commands.send_feedback),
+ icon: MessageCircleQuestion,
+ keywords: ["feedback", "bug", "report", "support", "反馈"],
+ run: () => useModalStore.getState().open("feedback"),
+ },
+ ];
+ }, [
+ archiveAllRead,
+ createIssueShortcut,
+ inbox,
+ markAllRead,
+ navigation,
+ p,
+ palette,
+ pathname,
+ projectId,
+ t,
+ tInbox,
+ toggleChatShortcut,
+ ]);
+}
diff --git a/packages/views/search/commands/issue-commands.tsx b/packages/views/search/commands/issue-commands.tsx
new file mode 100644
index 0000000000..b42c55f284
--- /dev/null
+++ b/packages/views/search/commands/issue-commands.tsx
@@ -0,0 +1,377 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import {
+ BellOff,
+ BellRing,
+ CalendarClock,
+ CircleDashed,
+ Copy,
+ FolderInput,
+ Link2,
+ ListChevronsDownUp,
+ ListChevronsUpDown,
+ Network,
+ Pin,
+ PinOff,
+ RotateCcw,
+ SignalHigh,
+ Square,
+ SquarePlus,
+ Tag,
+ Trash2,
+ UserPlus,
+ Zap,
+} from "lucide-react";
+import { dispatchReasonCode } from "@multica/core/api";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ issueSubscribersOptions,
+ issueTasksOptions,
+ issueTimelineOptions,
+} from "@multica/core/issues/queries";
+import { useRetryIssueRun, useToggleIssueSubscriber } from "@multica/core/issues/mutations";
+import { useCommentCollapseStore, useResolvedExpandStore } from "@multica/core/issues/stores";
+import { quickActionListOptions } from "@multica/core/quick-actions";
+import type { AgentTask, Issue } from "@multica/core/types";
+import { copyText } from "@multica/ui/lib/clipboard";
+import { useIssueActions } from "../../issues/actions/use-issue-actions";
+import { resolvedThreadRootIds, rootCommentIds } from "../../issues/components/thread-utils";
+import { canRetryRun } from "../../issues/components/retry-run-button";
+import { useT } from "../../i18n";
+import { usePalette } from "../palette-context";
+import type { IssueTarget, PaletteCommand, PaletteCommandGroup } from "../types";
+import { ContextHeading } from "./context-heading";
+
+const ACTIVE_TASK_STATUSES = new Set<AgentTask["status"]>([
+ "queued",
+ "dispatched",
+ "waiting_local_directory",
+ "deferred",
+ "running",
+]);
+
+/** Commands for the issue on screen (`issue`) or a list selection (`issues`). */
+export function useIssueCommandGroup(
+ target: IssueTarget | null,
+ onDeletedFallbackPath?: string,
+): PaletteCommandGroup | null {
+ const { t } = useT("search");
+ const { t: tIssues } = useT("issues");
+ const wsId = useWorkspaceId();
+ const palette = usePalette();
+ const queryClient = useQueryClient();
+ const userId = useAuthStore((s) => s.user?.id ?? null);
+
+ const single: Issue | null = target?.kind === "single" ? target.issue : null;
+ const singleId = single?.id ?? "";
+ const actions = useIssueActions(single);
+
+ const { data: quickActions = [] } = useQuery({
+ ...quickActionListOptions(wsId),
+ enabled: !!single,
+ });
+ const activeQuickActions = useMemo(
+ () => quickActions.filter((action) => action.status === "active"),
+ [quickActions],
+ );
+ const { data: tasks = [] } = useQuery({ ...issueTasksOptions(singleId), enabled: !!single });
+ const { data: subscribers = [] } = useQuery({
+ ...issueSubscribersOptions(singleId),
+ enabled: !!single,
+ });
+ const toggleSubscriber = useToggleIssueSubscriber(singleId);
+ const retryRun = useRetryIssueRun(singleId);
+
+ return useMemo(() => {
+ if (!target) return null;
+ const isSingle = target.kind === "single";
+ const crumb = isSingle
+ ? target.issue.identifier
+ : t(($) => $.context.selected_issues, { count: target.issues.length });
+
+ const commands: PaletteCommand[] = [
+ {
+ id: "issue-status",
+ label: t(($) => $.issue.change_status),
+ icon: CircleDashed,
+ keywords: ["status", "state", "状态"],
+ page: { type: "issue-status", target },
+ crumb,
+ primary: true,
+ },
+ {
+ id: "issue-assignee",
+ label: t(($) => $.issue.assign_to),
+ icon: UserPlus,
+ keywords: ["assign", "assignee", "owner", "agent", "指派", "负责人"],
+ page: { type: "issue-assignee", target },
+ crumb,
+ primary: true,
+ },
+ {
+ id: "issue-priority",
+ label: t(($) => $.issue.set_priority),
+ icon: SignalHigh,
+ keywords: ["priority", "urgent", "优先级"],
+ page: { type: "issue-priority", target },
+ crumb,
+ primary: true,
+ },
+ ];
+
+ if (single) {
+ if (activeQuickActions.length > 0) {
+ commands.push({
+ id: "issue-quick-action",
+ label: t(($) => $.issue.run_quick_action),
+ icon: Zap,
+ keywords: ["quick", "action", "run", "快捷"],
+ hint: t(($) => $.issue.quick_actions_available, { count: activeQuickActions.length }),
+ page: { type: "issue-quick-action", issue: single },
+ crumb,
+ primary: true,
+ });
+ }
+ commands.push({
+ id: "issue-copy-link",
+ label: t(($) => $.commands.copy_issue_link),
+ icon: Link2,
+ keywords: ["copy", "link", "share", "url", single.identifier.toLowerCase()],
+ run: () => void actions.copyLink(),
+ primary: true,
+ });
+ }
+
+ commands.push(
+ {
+ id: "issue-labels",
+ label: t(($) => $.issue.add_label),
+ icon: Tag,
+ keywords: ["label", "tag", "标签"],
+ page: { type: "issue-labels", target },
+ crumb,
+ },
+ {
+ id: "issue-due-date",
+ label: t(($) => $.issue.set_due_date),
+ icon: CalendarClock,
+ keywords: ["due", "date", "deadline", "截止"],
+ page: { type: "issue-due-date", target },
+ crumb,
+ },
+ {
+ id: "issue-project",
+ label: t(($) => $.issue.move_to_project),
+ icon: FolderInput,
+ keywords: ["project", "move", "项目"],
+ page: { type: "issue-project", target },
+ crumb,
+ },
+ );
+
+ if (single) {
+ commands.push({
+ id: "issue-parent",
+ label: t(($) => $.issue.set_parent),
+ icon: Network,
+ keywords: ["parent", "sub", "父任务"],
+ run: actions.openSetParent,
+ });
+
+ const sorted = [...tasks].sort((a, b) => b.created_at.localeCompare(a.created_at));
+ const activeTask = sorted.find((task) => ACTIVE_TASK_STATUSES.has(task.status));
+ const lastTask = sorted[0];
+ if (activeTask) {
+ commands.push({
+ id: "issue-cancel-run",
+ label: t(($) => $.issue.cancel_run),
+ icon: Square,
+ keywords: ["cancel", "stop", "terminate", "run", "取消", "停止", "运行"],
+ run: () =>
+ palette.openHostDialog({
+ type: "cancel-run",
+ issueId: single.id,
+ taskId: activeTask.id,
+ running:
+ activeTask.status === "running" ||
+ activeTask.status === "dispatched" ||
+ activeTask.status === "waiting_local_directory",
+ }),
+ });
+ } else if (lastTask && canRetryRun(lastTask)) {
+ commands.push({
+ id: "issue-retry-run",
+ label: t(($) => $.issue.retry_run),
+ icon: RotateCcw,
+ keywords: ["retry", "rerun", "again", "run", "重试", "运行"],
+ run: () => {
+ retryRun.mutateAsync(lastTask.id).then(
+ () => toast.success(t(($) => $.toast.run_retried)),
+ (e: unknown) =>
+ toast.error(
+ dispatchReasonCode(e) === "invocation_not_allowed"
+ ? tIssues(($) => $.execution_log.retry_blocked)
+ : e instanceof Error
+ ? e.message
+ : tIssues(($) => $.execution_log.retry_failed),
+ ),
+ );
+ },
+ });
+ }
+
+ const subscribed = !!userId && subscribers.some(
+ (s) => s.user_type === "member" && s.user_id === userId,
+ );
+ commands.push(
+ {
+ id: "issue-create-sub-issue",
+ label: t(($) => $.issue.create_sub_issue),
+ icon: SquarePlus,
+ keywords: ["sub", "child", "new", "子任务"],
+ run: actions.openCreateSubIssue,
+ },
+ {
+ id: "issue-subscribe",
+ label: subscribed ? t(($) => $.issue.unsubscribe) : t(($) => $.issue.subscribe),
+ icon: subscribed ? BellOff : BellRing,
+ keywords: ["subscribe", "watch", "notify", "订阅"],
+ run: () => {
+ if (!userId) return;
+ toggleSubscriber.mutateAsync({ userId, userType: "member", subscribed }).then(
+ () =>
+ toast.success(
+ subscribed ? t(($) => $.toast.unsubscribed) : t(($) => $.toast.subscribed),
+ ),
+ (err: unknown) =>
+ toast.error(err instanceof Error && err.message ? err.message : t(($) => $.toast.update_failed)),
+ );
+ },
+ },
+ {
+ id: "issue-pin",
+ label: actions.isPinned
+ ? tIssues(($) => $.actions.unpin_from_sidebar)
+ : tIssues(($) => $.actions.pin_to_sidebar),
+ icon: actions.isPinned ? PinOff : Pin,
+ keywords: ["pin", "sidebar", "固定"],
+ run: actions.togglePin,
+ },
+ {
+ id: "issue-copy-identifier",
+ label: t(($) => $.commands.copy_identifier, { identifier: single.identifier }),
+ icon: Copy,
+ keywords: ["copy", "id", "identifier", single.identifier.toLowerCase()],
+ run: () => {
+ void copyText(single.identifier).then((ok) => {
+ if (ok) {
+ toast.success(t(($) => $.toast.copied_identifier, { identifier: single.identifier }));
+ }
+ });
+ },
+ },
+ {
+ id: "issue-fold-comments",
+ label: t(($) => $.commands.fold_all_comments),
+ icon: ListChevronsDownUp,
+ keywords: ["fold", "collapse", "comments", "收起", "折叠", "评论"],
+ run: () => {
+ // The timeline is already cached whenever the issue page has
+ // rendered; ensureQueryData only fetches on a cold cache. If it
+ // still can't load, no comments are on screen — dropping the
+ // action matches the visible state.
+ void queryClient
+ .ensureQueryData(issueTimelineOptions(single.id))
+ .then((entries) => {
+ useCommentCollapseStore.getState().collapseAll(single.id, rootCommentIds(entries));
+ useResolvedExpandStore.getState().collapseAll(single.id);
+ })
+ .catch(() => {});
+ },
+ },
+ {
+ id: "issue-unfold-comments",
+ label: t(($) => $.commands.unfold_all_comments),
+ icon: ListChevronsUpDown,
+ keywords: ["unfold", "expand", "comments", "展开", "评论"],
+ run: () => {
+ void queryClient
+ .ensureQueryData(issueTimelineOptions(single.id))
+ .then((entries) => {
+ useCommentCollapseStore.getState().expandAll(single.id);
+ useResolvedExpandStore
+ .getState()
+ .expandAll(single.id, resolvedThreadRootIds(entries));
+ })
+ .catch(() => {});
+ },
+ },
+ {
+ id: "issue-delete",
+ label: t(($) => $.issue.delete),
+ icon: Trash2,
+ keywords: ["delete", "remove", "删除"],
+ destructive: true,
+ run: () => actions.openDeleteConfirm({ onDeletedFallbackPath }),
+ },
+ );
+ } else if (target.kind === "batch") {
+ commands.push(
+ {
+ id: "issue-parent",
+ label: t(($) => $.issue.set_parent),
+ icon: Network,
+ keywords: ["parent", "sub", "父任务"],
+ page: { type: "issue-parent", target },
+ crumb,
+ },
+ {
+ id: "issue-delete",
+ label: t(($) => $.issue.delete_selected, { count: target.issues.length }),
+ icon: Trash2,
+ keywords: ["delete", "remove", "删除"],
+ destructive: true,
+ run: () =>
+ palette.openHostDialog({
+ type: "batch-delete",
+ issues: target.issues,
+ clearSelection: target.clearSelection,
+ }),
+ },
+ );
+ }
+
+ return {
+ id: isSingle ? "context-issue" : "context-issues",
+ heading: isSingle ? (
+ <ContextHeading
+ label={t(($) => $.context.current_issue)}
+ subject={target.issue.identifier}
+ detail={target.issue.title}
+ />
+ ) : (
+ <ContextHeading label={crumb} />
+ ),
+ commands,
+ };
+ }, [
+ actions,
+ activeQuickActions.length,
+ onDeletedFallbackPath,
+ palette,
+ queryClient,
+ retryRun,
+ single,
+ subscribers,
+ t,
+ tIssues,
+ target,
+ tasks,
+ toggleSubscriber,
+ userId,
+ ]);
+}
diff --git a/packages/views/search/delegate/delegate-group.tsx b/packages/views/search/delegate/delegate-group.tsx
new file mode 100644
index 0000000000..37aacff5ed
--- /dev/null
+++ b/packages/views/search/delegate/delegate-group.tsx
@@ -0,0 +1,123 @@
+"use client";
+
+import { FolderOpen, Network, Sparkles, Users } from "lucide-react";
+import { Command as CommandPrimitive } from "cmdk";
+import { createShortcutChord } from "@multica/core/shortcuts";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { ShortcutKeycaps } from "../../common/shortcut-keycaps";
+import { useT } from "../../i18n";
+import { usePalette } from "../palette-context";
+import { AgentPresenceText } from "../result-rows";
+import { PaletteGroup, ROW_CLASS, ROW_ICON_CLASS } from "../rows";
+import type { DelegateActor } from "../types";
+import type { AgentEntry } from "../use-actor-directory";
+import type { DelegateAttachments } from "./use-delegate";
+
+const ENTER = createShortcutChord("Enter");
+
+function AttachmentChip({ icon: Icon, children }: { icon: typeof FolderOpen; children: string }) {
+ return (
+ <span className="inline-flex min-w-0 items-center gap-1 text-caption text-muted-foreground">
+ <Icon className="size-3 shrink-0" />
+ <span className="truncate">{children}</span>
+ </span>
+ );
+}
+
+/**
+ * "Hand to agent": shown above the results when the input reads as an
+ * instruction. The first row creates the issue from the input as typed and
+ * assigns it; it previews who and what context, never guessed fields.
+ */
+export function DelegateGroup({
+ prompt,
+ actor,
+ agentEntry,
+ attachments,
+ onSubmit,
+}: {
+ prompt: string;
+ actor: DelegateActor;
+ agentEntry: AgentEntry | null;
+ attachments: DelegateAttachments;
+ onSubmit: (actor: DelegateActor) => void;
+}) {
+ const { t } = useT("search");
+ const palette = usePalette();
+ const hasAttachments = !!attachments.project || !!attachments.parent;
+
+ return (
+ <PaletteGroup
+ heading={
+ <>
+ <Sparkles className="size-3 text-brand" />
+ <span className="text-brand">{t(($) => $.delegate.heading)}</span>
+ </>
+ }
+ >
+ <CommandPrimitive.Item
+ value="delegate:submit"
+ onSelect={() => {
+ palette.close();
+ onSubmit(actor);
+ }}
+ className={cn(ROW_CLASS, "items-start py-1.5")}
+ >
+ <ActorAvatar
+ actorType={actor.type}
+ actorId={actor.id}
+ size="sm"
+ profileLink={false}
+ showStatusDot={actor.type === "agent"}
+ className="mt-0.5 shrink-0"
+ />
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate">
+ {t(($) => $.delegate.create_and_assign, { name: actor.name })}
+ </span>
+ <span className="flex min-w-0 items-center gap-3">
+ {actor.type === "agent" && agentEntry && (
+ <AgentPresenceText
+ availability={agentEntry.availability}
+ runtimeLabel={agentEntry.runtimeLabel}
+ className="shrink-0"
+ />
+ )}
+ {actor.type === "squad" && (
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {t(($) => $.delegate.squad)}
+ </span>
+ )}
+ {hasAttachments && (
+ <span className="flex min-w-0 items-center gap-2" aria-label={t(($) => $.delegate.context_aria)}>
+ {attachments.project && (
+ <AttachmentChip icon={FolderOpen}>{attachments.project.title}</AttachmentChip>
+ )}
+ {attachments.parent && (
+ <AttachmentChip icon={Network}>
+ {t(($) => $.delegate.parent, { identifier: attachments.parent.identifier })}
+ </AttachmentChip>
+ )}
+ </span>
+ )}
+ </span>
+ </div>
+ <ShortcutKeycaps shortcut={ENTER} decorative className="mt-0.5 shrink-0" />
+ </CommandPrimitive.Item>
+ <CommandPrimitive.Item
+ value="delegate:choose"
+ onSelect={() =>
+ palette.push({
+ page: { type: "delegate-target", prompt },
+ crumbs: [t(($) => $.delegate.heading), t(($) => $.delegate.pick_crumb)],
+ })
+ }
+ className={ROW_CLASS}
+ >
+ <Users className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate">{t(($) => $.delegate.pick_another)}</span>
+ </CommandPrimitive.Item>
+ </PaletteGroup>
+ );
+}
diff --git a/packages/views/search/delegate/detect-instruction.test.ts b/packages/views/search/delegate/detect-instruction.test.ts
new file mode 100644
index 0000000000..143a1fd81f
--- /dev/null
+++ b/packages/views/search/delegate/detect-instruction.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+import { detectInstruction, type NamedActor } from "./detect-instruction";
+
+const lambda: NamedActor = { type: "agent", id: "agent-lambda", name: "Lambda" };
+const lambdaPro: NamedActor = { type: "agent", id: "agent-lambda-pro", name: "Lambda Pro" };
+const backend: NamedActor = { type: "squad", id: "squad-backend", name: "Backend" };
+const actors = [lambda, lambdaPro, backend];
+
+const settled = { hasResults: true, resultsSettled: true };
+const empty = { hasResults: false, resultsSettled: true };
+
+describe("detectInstruction", () => {
+ it("reads a sentence naming an agent as an instruction to it", () => {
+ expect(detectInstruction("让 Lambda 修一下 Safari 登录回调的 500", actors, settled)).toEqual({
+ reason: "names_actor",
+ actor: lambda,
+ });
+ expect(detectInstruction("ask the backend squad to rotate keys", actors, settled)?.actor).toEqual(backend);
+ });
+
+ it("prefers the longest matching name", () => {
+ expect(detectInstruction("Lambda Pro please draft the changelog", actors, settled)?.actor).toEqual(lambdaPro);
+ });
+
+ it("treats a bare name, or a name plus one word, as a search", () => {
+ expect(detectInstruction("lambda", actors, settled)).toBeNull();
+ expect(detectInstruction("lambda runs", actors, settled)).toBeNull();
+ });
+
+ it("only matches Latin names as whole words", () => {
+ expect(detectInstruction("lambdas and closures", actors, settled)).toBeNull();
+ });
+
+ it("reads an imperative opener as an instruction without an actor", () => {
+ expect(detectInstruction("fix the safari login callback", actors, settled)).toEqual({
+ reason: "starts_with_verb",
+ actor: null,
+ });
+ expect(detectInstruction("修复登录回调", actors, settled)?.reason).toBe("starts_with_verb");
+ expect(detectInstruction("fix", actors, settled)).toBeNull();
+ });
+
+ it("falls back on multi-word input only once the search came back empty", () => {
+ expect(detectInstruction("safari callback returns 500", actors, empty)?.reason).toBe("no_results");
+ expect(detectInstruction("safari callback returns 500", actors, settled)).toBeNull();
+ expect(
+ detectInstruction("safari callback returns 500", actors, { hasResults: false, resultsSettled: false }),
+ ).toBeNull();
+ expect(detectInstruction("safari", actors, empty)).toBeNull();
+ });
+
+ it("ignores very short input", () => {
+ expect(detectInstruction("修复 a", actors, empty)).toBeNull();
+ });
+});
diff --git a/packages/views/search/delegate/detect-instruction.ts b/packages/views/search/delegate/detect-instruction.ts
new file mode 100644
index 0000000000..458fc0cab6
--- /dev/null
+++ b/packages/views/search/delegate/detect-instruction.ts
@@ -0,0 +1,183 @@
+/**
+ * Decides, without a model, whether palette input reads as work to hand to an
+ * agent rather than a search. A false positive costs one extra group above the
+ * results (and ⇧↵ dismisses it); a false negative leaves the user searching.
+ * The rules lean conservative accordingly.
+ */
+
+export interface NamedActor {
+ type: "agent" | "squad";
+ id: string;
+ name: string;
+}
+
+export type InstructionReason = "names_actor" | "starts_with_verb" | "no_results";
+
+export interface DetectedInstruction {
+ reason: InstructionReason;
+ /** The agent or squad the input names, if any. */
+ actor: NamedActor | null;
+}
+
+// Imperative openers. Single CJK characters that begin ordinary nouns
+// ("加密", "写作") are left out; "让 / 请 / 帮" almost only open a request.
+const LATIN_VERBS = new Set([
+ "fix",
+ "add",
+ "create",
+ "make",
+ "write",
+ "build",
+ "implement",
+ "refactor",
+ "investigate",
+ "debug",
+ "review",
+ "help",
+ "please",
+ "design",
+ "draft",
+ "improve",
+ "optimize",
+ "migrate",
+ "research",
+ "analyze",
+ "analyse",
+ "summarize",
+ "document",
+ "let",
+ "ask",
+ "tell",
+ // fr
+ "corrige",
+ "ajoute",
+ "crée",
+ "cree",
+ "écris",
+ "ecris",
+ "implémente",
+ "analyse",
+ "optimise",
+ "aide",
+]);
+
+const CJK_VERBS = [
+ "让",
+ "請",
+ "请",
+ "帮",
+ "幫",
+ "麻烦",
+ "麻煩",
+ "修复",
+ "修復",
+ "修一下",
+ "改一下",
+ "实现",
+ "實現",
+ "添加",
+ "新增",
+ "加一个",
+ "加一個",
+ "写一个",
+ "寫一個",
+ "优化",
+ "優化",
+ "调查",
+ "調查",
+ "排查",
+ "重构",
+ "重構",
+ "设计",
+ "設計",
+ "检查",
+ "檢查",
+ "处理",
+ "處理",
+ "整理",
+ "分析",
+ "总结",
+ "總結",
+ "研究",
+ "迁移",
+ "遷移",
+];
+
+const CJK = /[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]/;
+const PUNCTUATION = /[\s,.!?;:,。!?;:、"'“”‘’()()]+/g;
+
+function isLatinWordChar(ch: string | undefined) {
+ return !!ch && /[\p{L}\p{N}_-]/u.test(ch) && !CJK.test(ch);
+}
+
+/** Where `name` occurs in `input` as a whole word (for Latin names), or -1. */
+function findName(input: string, name: string): number {
+ const haystack = input.toLowerCase();
+ const needle = name.toLowerCase();
+ let from = 0;
+ while (from <= haystack.length) {
+ const at = haystack.indexOf(needle, from);
+ if (at === -1) return -1;
+ const before = haystack[at - 1];
+ const after = haystack[at + needle.length];
+ if (!isLatinWordChar(before) && !isLatinWordChar(after)) return at;
+ from = at + 1;
+ }
+ return -1;
+}
+
+function meaningfulLength(text: string) {
+ return text.replace(PUNCTUATION, "").length;
+}
+
+function startsWithVerb(input: string): boolean {
+ const lower = input.toLowerCase();
+ const tokens = lower.split(/\s+/).filter(Boolean);
+ const first = tokens[0]?.replace(/[,.!?:;]+$/, "");
+ if (first && LATIN_VERBS.has(first)) return tokens.length >= 2;
+ for (const verb of CJK_VERBS) {
+ if (lower.startsWith(verb)) return meaningfulLength(lower.slice(verb.length)) >= 2;
+ }
+ return false;
+}
+
+function isInstructionRemainder(rest: string): boolean {
+ if (CJK.test(rest)) return meaningfulLength(rest) >= 2;
+ return rest.split(PUNCTUATION).filter(Boolean).length >= 2;
+}
+
+function isMultiWord(input: string): boolean {
+ const tokens = input.split(/\s+/).filter(Boolean);
+ if (tokens.length >= 2) return true;
+ // CJK text has no spaces; four characters is already a phrase.
+ return CJK.test(input) && meaningfulLength(input) >= 4;
+}
+
+export function detectInstruction(
+ rawInput: string,
+ actors: readonly NamedActor[],
+ options: { hasResults: boolean; resultsSettled: boolean },
+): DetectedInstruction | null {
+ const input = rawInput.trim();
+ if (meaningfulLength(input) < 4) return null;
+
+ // Longest name first, so "Lambda Pro" wins over "Lambda".
+ const byLength = [...actors]
+ .filter((actor) => actor.name.trim().length >= 2)
+ .sort((a, b) => b.name.length - a.name.length);
+ for (const actor of byLength) {
+ const at = findName(input, actor.name);
+ if (at === -1) continue;
+ const rest = input.slice(0, at) + " " + input.slice(at + actor.name.length);
+ // The name alone, or with one more word ("lambda runs"), is a search for
+ // the agent, not an instruction to it.
+ if (isInstructionRemainder(rest)) return { reason: "names_actor", actor };
+ }
+
+ if (startsWithVerb(input)) return { reason: "starts_with_verb", actor: null };
+
+ if (options.resultsSettled && !options.hasResults && isMultiWord(input)) {
+ return { reason: "no_results", actor: null };
+ }
+ return null;
+}
diff --git a/packages/views/search/delegate/use-delegate.ts b/packages/views/search/delegate/use-delegate.ts
new file mode 100644
index 0000000000..b00e06ff0e
--- /dev/null
+++ b/packages/views/search/delegate/use-delegate.ts
@@ -0,0 +1,127 @@
+"use client";
+
+import { useCallback, useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { api, ApiError } from "@multica/core/api";
+import type { CommandBarContext } from "@multica/core/command-bar";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useQuickCreateStore } from "@multica/core/issues/stores/quick-create-store";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { useIssueLimitUpgradePrompt } from "../../modals/use-issue-limit-upgrade-prompt";
+import { useT } from "../../i18n";
+import type { DelegateActor } from "../types";
+import { useActorDirectory } from "../use-actor-directory";
+
+export interface DelegateAttachments {
+ project: { id: string; title: string } | null;
+ parent: { id: string; identifier: string } | null;
+}
+
+/**
+ * What a delegated issue is created with, read from the page: the open issue
+ * becomes its parent and lends its project; a project page lends itself.
+ */
+export function useDelegateAttachments(contexts: readonly CommandBarContext[]): DelegateAttachments {
+ const wsId = useWorkspaceId();
+ const issueContext = contexts.find((c) => c.kind === "issue");
+ const projectContext = contexts.find((c) => c.kind === "project");
+ const issue = issueContext?.kind === "issue" ? issueContext.issue : null;
+ const pageProject = projectContext?.kind === "project" ? projectContext.project : null;
+ const { data: projects } = useQuery({
+ ...projectListOptions(wsId),
+ enabled: !!issue?.project_id && !pageProject,
+ });
+
+ return useMemo(() => {
+ let project: DelegateAttachments["project"] = null;
+ if (pageProject) project = { id: pageProject.id, title: pageProject.title };
+ else if (issue?.project_id) {
+ const found = projects?.find((p) => p.id === issue.project_id);
+ if (found) project = { id: found.id, title: found.title };
+ }
+ return {
+ project,
+ parent: issue ? { id: issue.id, identifier: issue.identifier } : null,
+ };
+ }, [issue, pageProject, projects]);
+}
+
+/**
+ * Who "hand to agent" goes to when the input names nobody: the agent or squad
+ * the user last delegated to through quick create, else the first assignable
+ * agent that is online.
+ */
+export function useDelegateCandidates(enabled: boolean) {
+ const { agents, squads } = useActorDirectory(enabled);
+ const lastActorType = useQuickCreateStore((s) => s.lastActorType);
+ const lastActorId = useQuickCreateStore((s) => s.lastActorId);
+
+ return useMemo(() => {
+ const assignableAgents = agents.filter((entry) => entry.assignable);
+ const runnableSquads = squads.filter((entry) => entry.runnable);
+ const actors: DelegateActor[] = [
+ ...assignableAgents.map(
+ (entry): DelegateActor => ({ type: "agent", id: entry.agent.id, name: entry.agent.name, agent: entry.agent }),
+ ),
+ ...runnableSquads.map(
+ (entry): DelegateActor => ({ type: "squad", id: entry.squad.id, name: entry.squad.name, squad: entry.squad }),
+ ),
+ ];
+ const last = actors.find((actor) => actor.type === lastActorType && actor.id === lastActorId);
+ const firstOnline = assignableAgents.find((entry) => entry.availability === "online");
+ const fallback =
+ last ??
+ (firstOnline ? actors.find((actor) => actor.id === firstOnline.agent.id) : undefined) ??
+ actors[0] ??
+ null;
+ return { actors, fallback, agentEntries: agents };
+ }, [agents, lastActorId, lastActorType, squads]);
+}
+
+/** Create an issue from `prompt` and hand it to `actor` via quick create. */
+export function useDelegateSubmit() {
+ const { t } = useT("modals");
+ const showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt();
+ const setLastActor = useQuickCreateStore((s) => s.setLastActor);
+
+ return useCallback(
+ async (actor: DelegateActor, prompt: string, attachments: DelegateAttachments) => {
+ try {
+ await api.quickCreateIssue({
+ ...(actor.type === "agent" ? { agent_id: actor.id } : { squad_id: actor.id }),
+ prompt,
+ project_id: attachments.project?.id,
+ parent_issue_id: attachments.parent?.id,
+ });
+ setLastActor(actor.type, actor.id);
+ toast.success(t(($) => $.create_issue.agent.toast_sent), { duration: 4000 });
+ } catch (e) {
+ if (e instanceof ApiError && e.body && typeof e.body === "object") {
+ const body = e.body as { code?: string; reason?: string; current_version?: string; min_version?: string };
+ if (body.code === "issue_limit_reached") {
+ showIssueLimitUpgradePrompt();
+ return;
+ }
+ if (body.code === "agent_unavailable") {
+ toast.error(body.reason || t(($) => $.create_issue.agent.error_agent_unavailable_fallback));
+ return;
+ }
+ if (body.code === "daemon_version_unsupported") {
+ toast.error(
+ t(($) => $.create_issue.agent.error_daemon_version, {
+ current: body.current_version || "unknown",
+ min: body.min_version || "",
+ }),
+ );
+ return;
+ }
+ }
+ toast.error(
+ e instanceof Error && e.message ? e.message : t(($) => $.create_issue.agent.error_unknown),
+ );
+ }
+ },
+ [setLastActor, showIssueLimitUpgradePrompt, t],
+ );
+}
diff --git a/packages/views/search/footer.tsx b/packages/views/search/footer.tsx
new file mode 100644
index 0000000000..a60c69e693
--- /dev/null
+++ b/packages/views/search/footer.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { createShortcutChord } from "@multica/core/shortcuts";
+import { Kbd } from "@multica/ui/components/ui/kbd";
+import { ShortcutKeycaps } from "../common/shortcut-keycaps";
+import { useT } from "../i18n";
+
+const UP = createShortcutChord("Up");
+const DOWN = createShortcutChord("Down");
+const ENTER = createShortcutChord("Enter");
+const OPEN_IN_TAB = createShortcutChord("Enter", { primary: true });
+const SHIFT_ENTER = createShortcutChord("Enter", { shift: true });
+const BACKSPACE = createShortcutChord("Backspace");
+
+function Hint({ keys, children }: { keys: ReactNode; children: ReactNode }) {
+ return (
+ <span className="inline-flex shrink-0 items-center gap-1.5">
+ {keys}
+ <span>{children}</span>
+ </span>
+ );
+}
+
+function PrefixHint({ prefix, children }: { prefix: string; children: ReactNode }) {
+ return (
+ <Hint
+ keys={
+ <Kbd aria-hidden="true" className="h-5 min-w-5 border border-border/70 bg-muted/80 px-1 text-micro">
+ {prefix}
+ </Kbd>
+ }
+ >
+ {children}
+ </Hint>
+ );
+}
+
+/**
+ * Always-visible key hints. The left side says what the keys do right now;
+ * the right side teaches the scope prefixes (or how to go back).
+ */
+export function PaletteFooter({
+ mode,
+ delegateName,
+}: {
+ mode: "root" | "page" | "delegate";
+ delegateName?: string;
+}) {
+ const { t } = useT("search");
+ return (
+ <div className="flex items-center gap-4 border-t px-3 py-2 text-caption text-muted-foreground">
+ <div className="flex min-w-0 items-center gap-4 overflow-hidden">
+ {mode === "delegate" ? (
+ <>
+ <Hint keys={<ShortcutKeycaps shortcut={ENTER} decorative />}>
+ {t(($) => $.footer.delegate, { name: delegateName ?? "" })}
+ </Hint>
+ <Hint keys={<ShortcutKeycaps shortcut={SHIFT_ENTER} decorative />}>
+ {t(($) => $.footer.search_instead)}
+ </Hint>
+ </>
+ ) : (
+ <>
+ <Hint
+ keys={
+ <span className="inline-flex gap-0.5">
+ <ShortcutKeycaps shortcut={UP} decorative />
+ <ShortcutKeycaps shortcut={DOWN} decorative />
+ </span>
+ }
+ >
+ {t(($) => $.footer.navigate)}
+ </Hint>
+ <Hint keys={<ShortcutKeycaps shortcut={ENTER} decorative />}>{t(($) => $.footer.select)}</Hint>
+ {mode === "root" && (
+ <Hint keys={<ShortcutKeycaps shortcut={OPEN_IN_TAB} decorative />}>
+ {t(($) => $.footer.open_in_new_tab)}
+ </Hint>
+ )}
+ </>
+ )}
+ </div>
+ <div className="ml-auto flex shrink-0 items-center gap-4">
+ {mode === "page" ? (
+ <Hint keys={<ShortcutKeycaps shortcut={BACKSPACE} decorative />}>{t(($) => $.footer.back)}</Hint>
+ ) : (
+ <>
+ <PrefixHint prefix=">">{t(($) => $.footer.prefix_commands)}</PrefixHint>
+ <PrefixHint prefix="#">{t(($) => $.footer.prefix_issues)}</PrefixHint>
+ <PrefixHint prefix="@">{t(($) => $.footer.prefix_people)}</PrefixHint>
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/search/highlight-text.tsx b/packages/views/search/highlight-text.tsx
index 936a12e71d..b18cb28b7d 100644
--- a/packages/views/search/highlight-text.tsx
+++ b/packages/views/search/highlight-text.tsx
@@ -35,7 +35,10 @@ export function HighlightText({ text, query }: { text: string; query: string })
<>
{parts.map((part, i) =>
part.highlight ? (
- <mark key={i} className="bg-yellow-200 dark:bg-yellow-900/60 text-inherit rounded-sm">
+ <mark
+ key={i}
+ className="rounded-sm bg-[var(--find-match)] text-[var(--find-match-foreground)]"
+ >
{part.text}
</mark>
) : (
diff --git a/packages/views/search/host-dialogs.tsx b/packages/views/search/host-dialogs.tsx
new file mode 100644
index 0000000000..05bccbc827
--- /dev/null
+++ b/packages/views/search/host-dialogs.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import { toast } from "sonner";
+import { useBatchDeleteIssues, useCancelIssueRun } from "@multica/core/issues/mutations";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { AutopilotDialog } from "../autopilots/components/autopilot-dialog";
+import { TerminateTaskConfirmDialog } from "../issues/components/terminate-task-confirm-dialog";
+import { useT } from "../i18n";
+import type { PaletteHostDialog } from "./types";
+
+/**
+ * Confirms and forms a palette command opens after the palette closes. They
+ * live here rather than on the page because the page that would host them
+ * may not be the one on screen (a list selection, any route for "New
+ * autopilot").
+ */
+export function PaletteHostDialogs({
+ dialog,
+ onClose,
+}: {
+ dialog: PaletteHostDialog | null;
+ onClose: () => void;
+}) {
+ if (!dialog) return null;
+ switch (dialog.type) {
+ case "cancel-run":
+ return <CancelRunDialog dialog={dialog} onClose={onClose} />;
+ case "batch-delete":
+ return <BatchDeleteDialog dialog={dialog} onClose={onClose} />;
+ case "new-autopilot":
+ return <AutopilotDialog mode="create" open onOpenChange={(open) => !open && onClose()} />;
+ }
+}
+
+function CancelRunDialog({
+ dialog,
+ onClose,
+}: {
+ dialog: Extract<PaletteHostDialog, { type: "cancel-run" }>;
+ onClose: () => void;
+}) {
+ const { t } = useT("issues");
+ const { t: tSearch } = useT("search");
+ const cancelRun = useCancelIssueRun(dialog.issueId);
+ return (
+ <TerminateTaskConfirmDialog
+ open
+ onOpenChange={(open) => !open && onClose()}
+ showRunningNote={dialog.running}
+ onConfirm={() => {
+ onClose();
+ cancelRun.mutateAsync(dialog.taskId).then(
+ () => toast.success(tSearch(($) => $.toast.run_cancelled)),
+ (e: unknown) =>
+ toast.error(e instanceof Error ? e.message : t(($) => $.execution_log.cancel_failed)),
+ );
+ }}
+ />
+ );
+}
+
+function BatchDeleteDialog({
+ dialog,
+ onClose,
+}: {
+ dialog: Extract<PaletteHostDialog, { type: "batch-delete" }>;
+ onClose: () => void;
+}) {
+ const { t } = useT("issues");
+ const batchDelete = useBatchDeleteIssues();
+ const count = dialog.issues.length;
+ const handleDelete = async () => {
+ try {
+ await batchDelete.mutateAsync(dialog.issues.map((issue) => issue.id));
+ dialog.clearSelection();
+ toast.success(t(($) => $.batch.delete_success, { count }));
+ } catch (err) {
+ toast.error(err instanceof Error && err.message ? err.message : t(($) => $.batch.delete_failed));
+ } finally {
+ onClose();
+ }
+ };
+ return (
+ <AlertDialog open onOpenChange={(open) => !open && onClose()}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.batch.delete_dialog_title, { count })}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.batch.delete_dialog_desc, { count })}
+ <span className="mt-2 block text-caption text-muted-foreground">
+ {t(($) => $.batch.delete_dialog_warning)}
+ </span>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.batch.cancel)}</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={handleDelete}
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ >
+ {t(($) => $.batch.delete)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/packages/views/search/issue-target.test.tsx b/packages/views/search/issue-target.test.tsx
new file mode 100644
index 0000000000..721ae9a1b4
--- /dev/null
+++ b/packages/views/search/issue-target.test.tsx
@@ -0,0 +1,96 @@
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { Issue } from "@multica/core/types";
+import { RESOURCES } from "../locales";
+import { useIssueTargetWriter } from "./issue-target";
+import type { IssueTarget } from "./types";
+
+const { mockUpdateIssue, mockToast, mockOpenModal } = vi.hoisted(() => ({
+ mockUpdateIssue: vi.fn(),
+ mockToast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn() }),
+ mockOpenModal: vi.fn(),
+}));
+
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/api")>()),
+ api: { updateIssue: mockUpdateIssue },
+}));
+vi.mock("@multica/core/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/hooks")>()),
+ useWorkspaceId: () => "ws-test",
+}));
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () => buildIssueStatusCatalog([]),
+}));
+vi.mock("@multica/core/modals", async (importOriginal) => {
+ const state = { open: mockOpenModal };
+ return {
+ ...(await importOriginal<typeof import("@multica/core/modals")>()),
+ useModalStore: Object.assign((selector?: (s: typeof state) => unknown) => (selector ? selector(state) : state), {
+ getState: () => state,
+ }),
+ };
+});
+vi.mock("sonner", () => ({ toast: mockToast }));
+
+const issue = {
+ id: "issue-1",
+ workspace_id: "ws-test",
+ identifier: "MUL-1",
+ title: "Demo",
+ status: "todo",
+ priority: "none",
+ assignee_type: null,
+ assignee_id: null,
+} as unknown as Issue;
+
+function renderWriter(target: IssueTarget) {
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>
+ <I18nProvider locale="en" resources={{ en: RESOURCES.en }}>
+ {children}
+ </I18nProvider>
+ </QueryClientProvider>
+ );
+ return renderHook(() => useIssueTargetWriter(target), { wrapper });
+}
+
+describe("useIssueTargetWriter", () => {
+ beforeEach(() => {
+ mockUpdateIssue.mockReset();
+ mockToast.error.mockReset();
+ mockOpenModal.mockReset();
+ });
+
+ // The palette closes — unmounting the writer — as soon as a value is picked,
+ // so a failed write must still reach the user after the unmount.
+ it("reports a failed single-issue write after the palette has unmounted", async () => {
+ let reject!: (err: Error) => void;
+ mockUpdateIssue.mockReturnValue(new Promise((_, r) => (reject = r)));
+ const { result, unmount } = renderWriter({ kind: "single", issue });
+
+ result.current.apply({ priority: "high" });
+ unmount();
+ reject(new Error("Network down"));
+
+ await waitFor(() => expect(mockToast.error).toHaveBeenCalledWith("Network down"));
+ expect(mockUpdateIssue).toHaveBeenCalledWith("issue-1", { priority: "high" });
+ });
+
+ it("still asks before handing a live issue to an agent", () => {
+ const { result } = renderWriter({ kind: "single", issue });
+
+ result.current.assign("agent", "agent-1");
+
+ expect(mockOpenModal).toHaveBeenCalledWith(
+ "issue-run-confirm",
+ expect.objectContaining({ issueIds: ["issue-1"], assigneeType: "agent", assigneeId: "agent-1" }),
+ );
+ expect(mockUpdateIssue).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/search/issue-target.ts b/packages/views/search/issue-target.ts
new file mode 100644
index 0000000000..1fcfac3aac
--- /dev/null
+++ b/packages/views/search/issue-target.ts
@@ -0,0 +1,119 @@
+"use client";
+
+import { useCallback, useMemo } from "react";
+import { toast } from "sonner";
+import type { Issue, UpdateIssueRequest } from "@multica/core/types";
+import { errorCode } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useBatchUpdateIssues, useUpdateIssue } from "@multica/core/issues/mutations";
+import { useModalStore } from "@multica/core/modals";
+import { runConfirmIntent } from "../issues/actions/run-confirm-gate";
+import { useT } from "../i18n";
+import type { IssueTarget } from "./types";
+
+export function targetIssues(target: IssueTarget): Issue[] {
+ return target.kind === "single" ? [target.issue] : target.issues;
+}
+
+/**
+ * Field writes for an issue command, routed the way the matching on-page
+ * control routes them: a single issue passes the run-confirm gate that asks
+ * before handing work to an agent; a selection follows the batch toolbar's
+ * rules.
+ *
+ * The palette closes, and unmounts this hook, before a write settles, so
+ * outcomes are handled on the returned promise: per-call `mutate` callbacks
+ * would be dropped with the component and a rejected write would roll back
+ * silently.
+ */
+export function useIssueTargetWriter(target: IssueTarget) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const { entryOf } = useIssueStatuses(wsId);
+ const single = target.kind === "single" ? target.issue : null;
+ const updateIssue = useUpdateIssue();
+ const batchUpdate = useBatchUpdateIssues();
+ const openModal = useModalStore((s) => s.open);
+ const issues = useMemo(() => targetIssues(target), [target]);
+
+ const applyBatch = useCallback(
+ async (updates: Partial<UpdateIssueRequest>) => {
+ if (target.kind !== "batch") return;
+ const ids = issues.map((issue) => issue.id);
+ const count = ids.length;
+ try {
+ const { updated } = await batchUpdate.mutateAsync({ ids, updates });
+ if (updated < count) {
+ toast.warning(t(($) => $.batch.update_partial, { updated, count }));
+ } else {
+ toast.success(t(($) => $.batch.update_success, { count }));
+ }
+ } catch (err) {
+ toast.error(
+ err instanceof Error && err.message ? err.message : t(($) => $.batch.update_failed),
+ );
+ }
+ },
+ [batchUpdate, issues, t, target.kind],
+ );
+
+ const applySingle = useCallback(
+ (issue: Issue, updates: Partial<UpdateIssueRequest>) => {
+ const intent = runConfirmIntent(issue, updates, { entryOf });
+ if (intent) {
+ openModal("issue-run-confirm", intent);
+ return;
+ }
+ updateIssue.mutateAsync({ id: issue.id, ...updates }).catch((err: unknown) => {
+ toast.error(
+ errorCode(err) === "revision_conflict"
+ ? t(($) => $.revision.conflict)
+ : err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.detail.update_failed),
+ );
+ });
+ },
+ [entryOf, openModal, t, updateIssue],
+ );
+
+ const apply = useCallback(
+ (updates: Partial<UpdateIssueRequest>) => {
+ if (single) {
+ applySingle(single, updates);
+ return;
+ }
+ void applyBatch(updates);
+ },
+ [applyBatch, applySingle, single],
+ );
+
+ const assign = useCallback(
+ (assigneeType: "member" | "agent" | "squad" | null, assigneeId: string | null) => {
+ const updates: Partial<UpdateIssueRequest> = {
+ assignee_type: assigneeType,
+ assignee_id: assigneeId,
+ };
+ if (target.kind === "batch" && (assigneeType === "agent" || assigneeType === "squad") && assigneeId) {
+ // Same rule as the batch toolbar: assigning agent work across a
+ // selection previews the run fan-out, unless everything is parked in
+ // Backlog and nothing would start.
+ const allBacklog = issues.every((issue) => issue.status === "backlog");
+ if (!allBacklog) {
+ openModal("issue-run-confirm", {
+ issueIds: issues.map((issue) => issue.id),
+ mode: "assign",
+ assigneeType,
+ assigneeId,
+ });
+ return;
+ }
+ }
+ apply(updates);
+ },
+ [apply, issues, openModal, target.kind],
+ );
+
+ return { issues, apply, assign };
+}
diff --git a/packages/views/search/matching.ts b/packages/views/search/matching.ts
new file mode 100644
index 0000000000..41bd0ab5e0
--- /dev/null
+++ b/packages/views/search/matching.ts
@@ -0,0 +1,64 @@
+import { matchesPinyin } from "../editor/extensions/pinyin-match";
+
+// Row matcher shared by pages, commands and submenu options.
+//
+// Keywords match by prefix, not substring. They are invisible synonyms, so a
+// substring hit reads as a bug from the outside: "s" used to surface Inbox
+// (via "notifications") and "i" surfaced nearly every page. The visible label
+// still matches anywhere, because there the user can see what they hit.
+//
+// Pinyin is included for the same reason member search has it: under a Chinese
+// UI the localized label is the only thing the user can aim at, so typing
+// "renwu" has to reach "任务".
+export function matchesRow(label: string, keywords: readonly string[], query: string) {
+ return scoreRow(label, keywords, query) > 0;
+}
+
+const WORD_SPLIT = /[\s\-_/·.:()]+/;
+
+/**
+ * How well `text` answers `query` (already lower-cased and trimmed), from 0
+ * (no match) to 100 (exact). The tiers are what ranking across object types
+ * relies on: an exact agent name must beat an issue whose title merely
+ * contains it.
+ */
+export function scoreText(text: string, query: string): number {
+ if (!query || !text) return 0;
+ const t = text.toLowerCase();
+ if (t === query) return 100;
+ if (t.startsWith(query)) return 80;
+ if (t.split(WORD_SPLIT).some((word) => word.startsWith(query))) return 60;
+ if (t.includes(query)) return 40;
+ if (matchesPinyin(text, query)) return 30;
+ return 0;
+}
+
+export function scoreRow(label: string, keywords: readonly string[], query: string): number {
+ const labelScore = scoreText(label, query);
+ if (labelScore > 0) return labelScore;
+ return keywords.some((kw) => kw.startsWith(query)) ? 25 : 0;
+}
+
+/** "Assign to..." → "Assign to", for breadcrumbs. */
+export function stripEllipsis(label: string) {
+ return label.replace(/\s*(\.\.\.|…)$/, "");
+}
+
+export type SearchScope = "all" | "commands" | "issues" | "people";
+
+const SCOPE_PREFIXES: Record<string, SearchScope> = {
+ ">": "commands",
+ "#": "issues",
+ "@": "people",
+};
+
+/**
+ * `>` limits the palette to commands, `#` to issues, `@` to people and
+ * agents. The prefix only counts as the first character; the rest is the
+ * query.
+ */
+export function parseScope(raw: string): { scope: SearchScope; text: string } {
+ const scope = SCOPE_PREFIXES[raw.charAt(0)];
+ if (!scope) return { scope: "all", text: raw.trim() };
+ return { scope, text: raw.slice(1).trim() };
+}
diff --git a/packages/views/search/pages/issue-pages.tsx b/packages/views/search/pages/issue-pages.tsx
new file mode 100644
index 0000000000..f4bc7c5d78
--- /dev/null
+++ b/packages/views/search/pages/issue-pages.tsx
@@ -0,0 +1,567 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { CalendarClock, CalendarX, FolderMinus, Lock, Network, UserMinus, Zap } from "lucide-react";
+import { Command as CommandPrimitive } from "cmdk";
+import { dispatchReasonCode } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { PRIORITY_DISPLAY_ORDER } from "@multica/core/issues/config";
+import { addDaysDateOnly, todayDateOnly } from "@multica/core/issues/date";
+import {
+ sharedWorkflowStatusKeys,
+ stepHandsOff,
+ useIssueWorkflows,
+ workflowStep,
+} from "@multica/core/issue-workflows";
+import { issueLabelsOptions, labelListOptions } from "@multica/core/labels/queries";
+import { useAttachLabelToIssue, useDetachLabel } from "@multica/core/labels/mutations";
+import { useModalStore } from "@multica/core/modals";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { quickActionListOptions, useRunQuickAction } from "@multica/core/quick-actions";
+import type { Issue, IssuePriority, Label } from "@multica/core/types";
+import { StatusIcon } from "../../issues/components/status-icon";
+import { PriorityIcon } from "../../issues/components/priority-icon";
+import { outcomeMessage } from "../../issues/components/quick-actions-section";
+import { useIssueStatusOptions } from "../../issues/utils/status-options";
+import { ProjectIcon } from "../../projects/components/project-icon";
+import { useT } from "../../i18n";
+import { HighlightText } from "../highlight-text";
+import { useIssueTargetWriter, targetIssues } from "../issue-target";
+import { scoreRow, scoreText } from "../matching";
+import { usePalette } from "../palette-context";
+import { PaletteGroup, ROW_CLASS, ROW_ICON_CLASS, RowCheck, RowHint } from "../rows";
+import { AgentPresenceText, ActorRow, IssueResultRow } from "../result-rows";
+import { useActorDirectory } from "../use-actor-directory";
+import { useServerSearch } from "../use-server-search";
+import type { IssueTarget } from "../types";
+
+/** The value every target issue shares, or undefined when they differ. */
+function common<T>(issues: Issue[], pick: (issue: Issue) => T): T | undefined {
+ const first = issues[0];
+ if (!first) return undefined;
+ const value = pick(first);
+ return issues.every((issue) => pick(issue) === value) ? value : undefined;
+}
+
+function sharedProjectIdOf(issues: Issue[]): string | null | undefined {
+ const first = issues[0]?.project_id ?? null;
+ return first && issues.every((i) => i.project_id === first) ? first : undefined;
+}
+
+function filterByLabel<T>(items: T[], query: string, label: (item: T) => string, keywords?: (item: T) => string[]) {
+ const q = query.trim().toLowerCase();
+ if (!q) return items;
+ return items
+ .map((item) => ({ item, score: scoreRow(label(item), keywords?.(item) ?? [], q) }))
+ .filter((entry) => entry.score > 0)
+ .sort((a, b) => b.score - a.score)
+ .map((entry) => entry.item);
+}
+
+export function IssueStatusPage({ target, query }: { target: IssueTarget; query: string }) {
+ const { t } = useT("search");
+ const wsId = useWorkspaceId();
+ const palette = usePalette();
+ const openModal = useModalStore((s) => s.open);
+ const writer = useIssueTargetWriter(target);
+ const issues = writer.issues;
+ const single = target.kind === "single" ? target.issue : null;
+ const sharedProjectId = single ? single.project_id : sharedProjectIdOf(issues);
+ const { workflows } = useIssueWorkflows(wsId);
+ const { data: projects } = useQuery({
+ ...projectListOptions(wsId),
+ enabled: !single && sharedProjectId === undefined,
+ });
+ // A selection inside one project offers that project's workflow statuses;
+ // one spanning projects offers the statuses every selected issue's
+ // workflow allows — the batch toolbar's rule. (MUL-7420)
+ const { options, workflow } = useIssueStatusOptions(
+ wsId,
+ single ? single.project_id : (sharedProjectId ?? undefined),
+ single?.status,
+ );
+ const allowed = useMemo(
+ () => (single || sharedProjectId ? null : sharedWorkflowStatusKeys(workflows, projects, issues)),
+ [issues, projects, sharedProjectId, single, workflows],
+ );
+ const current = common(issues, (issue) => issue.status);
+ const visible = filterByLabel(
+ allowed ? options.filter((o) => allowed.has(o.key)) : options,
+ query,
+ (o) => o.label,
+ (o) => [o.key.replace(/_/g, " ")],
+ );
+
+ const select = (status: string) => {
+ palette.close();
+ if (
+ single &&
+ workflow &&
+ status !== single.status &&
+ stepHandsOff(workflowStep(workflow, status))
+ ) {
+ openModal("issue-workflow-handoff", {
+ issueId: single.id,
+ identifier: single.identifier,
+ status,
+ });
+ return;
+ }
+ writer.apply({ status });
+ };
+
+ return (
+ <PaletteGroup heading={t(($) => $.pages.status)}>
+ {visible.map((option) => (
+ <CommandPrimitive.Item
+ key={option.key}
+ value={`status:${option.key}`}
+ onSelect={() => select(option.key)}
+ className={ROW_CLASS}
+ >
+ <StatusIcon
+ status={option.key}
+ category={option.category}
+ color={option.color}
+ icon={option.icon}
+ className="size-4 shrink-0"
+ />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={option.label} query={query} />
+ </span>
+ {current === option.key && <RowCheck label={t(($) => $.pages.current)} />}
+ </CommandPrimitive.Item>
+ ))}
+ </PaletteGroup>
+ );
+}
+
+export function IssuePriorityPage({ target, query }: { target: IssueTarget; query: string }) {
+ const { t } = useT("search");
+ const { t: tIssues } = useT("issues");
+ const palette = usePalette();
+ const writer = useIssueTargetWriter(target);
+ const current = common(writer.issues, (issue) => issue.priority);
+ const options = filterByLabel(
+ PRIORITY_DISPLAY_ORDER.map((priority) => ({ priority, label: tIssues(($) => $.priority[priority]) })),
+ query,
+ (o) => o.label,
+ (o) => [o.priority],
+ );
+ return (
+ <PaletteGroup heading={t(($) => $.pages.priority)}>
+ {options.map(({ priority, label }) => (
+ <CommandPrimitive.Item
+ key={priority}
+ value={`priority:${priority}`}
+ onSelect={() => {
+ palette.close();
+ writer.apply({ priority: priority as IssuePriority });
+ }}
+ className={ROW_CLASS}
+ >
+ <PriorityIcon priority={priority} className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={label} query={query} />
+ </span>
+ {current === priority && <RowCheck label={t(($) => $.pages.current)} />}
+ </CommandPrimitive.Item>
+ ))}
+ </PaletteGroup>
+ );
+}
+
+export function IssueAssigneePage({ target, query }: { target: IssueTarget; query: string }) {
+ const { t } = useT("search");
+ const { t: tIssues } = useT("issues");
+ const palette = usePalette();
+ const writer = useIssueTargetWriter(target);
+ const { agents, squads, members } = useActorDirectory(true);
+ const currentType = common(writer.issues, (issue) => issue.assignee_type);
+ const currentId = common(writer.issues, (issue) => issue.assignee_id);
+ const isCurrent = (type: string, id: string) => currentType === type && currentId === id;
+ const q = query.trim().toLowerCase();
+
+ // Agents ordered: assignable before not, online before offline. Search
+ // keeps that order inside each match tier.
+ const availabilityRank: Record<string, number> = { online: 0, unstable: 1, offline: 2 };
+ const sortedAgents = [...agents].sort((a, b) => {
+ if (a.assignable !== b.assignable) return a.assignable ? -1 : 1;
+ const ra = a.availability ? (availabilityRank[a.availability] ?? 3) : 3;
+ const rb = b.availability ? (availabilityRank[b.availability] ?? 3) : 3;
+ return ra - rb;
+ });
+ const visibleAgents = filterByLabel(sortedAgents, q, (e) => e.agent.name);
+ const visibleSquads = filterByLabel(squads, q, (e) => e.squad.name);
+ const visibleMembers = filterByLabel(members, q, (m) => m.name, (m) => [m.email.toLowerCase()]);
+ const unassignedLabel = tIssues(($) => $.pickers.assignee.trigger_unassigned);
+ const showUnassigned = !q || scoreText(unassignedLabel, q) > 0;
+
+ const select = (type: "member" | "agent" | "squad" | null, id: string | null) => {
+ palette.close();
+ writer.assign(type, id);
+ };
+
+ return (
+ <>
+ {showUnassigned && (
+ <PaletteGroup heading={t(($) => $.pages.assignee)}>
+ <CommandPrimitive.Item
+ value="assignee:none"
+ onSelect={() => select(null, null)}
+ className={ROW_CLASS}
+ >
+ <UserMinus className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate text-muted-foreground">{unassignedLabel}</span>
+ {currentType === null && currentId === null && <RowCheck label={t(($) => $.pages.current)} />}
+ </CommandPrimitive.Item>
+ </PaletteGroup>
+ )}
+ {visibleAgents.length > 0 && (
+ <PaletteGroup heading={tIssues(($) => $.pickers.assignee.agents_group)}>
+ {visibleAgents.map((entry) => (
+ <ActorRow
+ key={entry.agent.id}
+ value={`assignee:agent:${entry.agent.id}`}
+ actorType="agent"
+ actorId={entry.agent.id}
+ name={entry.agent.name}
+ query={query}
+ showStatusDot
+ disabled={!entry.assignable}
+ onSelect={() => select("agent", entry.agent.id)}
+ detail={
+ entry.assignable ? (
+ <AgentPresenceText availability={entry.availability} runtimeLabel={entry.runtimeLabel} />
+ ) : (
+ <span className="text-caption text-muted-foreground">
+ {entry.deniedReason ?? tIssues(($) => $.pickers.assignee.agent_runtime_required)}
+ </span>
+ )
+ }
+ trailing={
+ isCurrent("agent", entry.agent.id) ? (
+ <RowCheck label={t(($) => $.pages.current)} />
+ ) : entry.agent.visibility === "private" ? (
+ <Lock className="ml-auto size-3 shrink-0 text-muted-foreground" />
+ ) : null
+ }
+ />
+ ))}
+ </PaletteGroup>
+ )}
+ {visibleSquads.length > 0 && (
+ <PaletteGroup heading={tIssues(($) => $.pickers.assignee.squads_group)}>
+ {visibleSquads.map((entry) => (
+ <ActorRow
+ key={entry.squad.id}
+ value={`assignee:squad:${entry.squad.id}`}
+ actorType="squad"
+ actorId={entry.squad.id}
+ name={entry.squad.name}
+ query={query}
+ disabled={!entry.runnable}
+ onSelect={() => select("squad", entry.squad.id)}
+ detail={
+ entry.runnable ? undefined : (
+ <span className="text-caption text-muted-foreground">
+ {tIssues(($) => $.pickers.assignee.squad_runtime_required)}
+ </span>
+ )
+ }
+ trailing={isCurrent("squad", entry.squad.id) ? <RowCheck label={t(($) => $.pages.current)} /> : null}
+ />
+ ))}
+ </PaletteGroup>
+ )}
+ {visibleMembers.length > 0 && (
+ <PaletteGroup heading={tIssues(($) => $.pickers.assignee.members_group)}>
+ {visibleMembers.map((member) => (
+ <ActorRow
+ key={member.user_id}
+ value={`assignee:member:${member.user_id}`}
+ actorType="member"
+ actorId={member.user_id}
+ name={member.name}
+ query={query}
+ onSelect={() => select("member", member.user_id)}
+ trailing={
+ isCurrent("member", member.user_id) ? <RowCheck label={t(($) => $.pages.current)} /> : null
+ }
+ />
+ ))}
+ </PaletteGroup>
+ )}
+ </>
+ );
+}
+
+const EMPTY_LABELS: Label[] = [];
+
+export function IssueLabelsPage({ target, query }: { target: IssueTarget; query: string }) {
+ const { t } = useT("search");
+ const wsId = useWorkspaceId();
+ const palette = usePalette();
+ const issues = targetIssues(target);
+ const single = target.kind === "single" ? target.issue : null;
+ const { data: labels = EMPTY_LABELS } = useQuery(labelListOptions(wsId));
+ const { data: singleLabels } = useQuery({
+ ...issueLabelsOptions(wsId, single?.id ?? ""),
+ enabled: !!single,
+ });
+ const attach = useAttachLabelToIssue();
+ const detach = useDetachLabel(single?.id ?? "");
+ const labelIdsOf = (issue: Issue) =>
+ new Set((single && issue.id === single.id && singleLabels ? singleLabels : issue.labels ?? []).map((l) => l.id));
+ const visible = filterByLabel(labels, query, (label) => label.name);
+
+ const toggle = (label: Label) => {
+ palette.close();
+ const lacking = issues.filter((issue) => !labelIdsOf(issue).has(label.id));
+ if (lacking.length === 0 && single) {
+ // Every target already has it: on a single issue the row reads as a
+ // checked toggle, so selecting it removes the label.
+ detach.mutateAsync(label.id).then(
+ () => toast.success(t(($) => $.toast.label_removed, { name: label.name })),
+ (err: unknown) => toast.error(err instanceof Error ? err.message : String(err)),
+ );
+ return;
+ }
+ void Promise.allSettled(
+ lacking.map((issue) => attach.mutateAsync({ issueId: issue.id, labelId: label.id })),
+ ).then((results) => {
+ const failed = results.filter((r) => r.status === "rejected").length;
+ if (failed > 0) toast.error(t(($) => $.toast.label_failed, { name: label.name }));
+ else toast.success(t(($) => $.toast.label_added, { name: label.name }));
+ });
+ };
+
+ return (
+ <PaletteGroup heading={t(($) => $.pages.labels)}>
+ {visible.map((label) => {
+ const onAll = issues.every((issue) => labelIdsOf(issue).has(label.id));
+ return (
+ <CommandPrimitive.Item
+ key={label.id}
+ value={`label:${label.id}`}
+ onSelect={() => toggle(label)}
+ className={ROW_CLASS}
+ >
+ <span
+ className="mx-1 size-2.5 shrink-0 rounded-full"
+ style={{ backgroundColor: label.color }}
+ />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={label.name} query={query} />
+ </span>
+ {onAll && <RowCheck label={t(($) => $.pages.current)} />}
+ </CommandPrimitive.Item>
+ );
+ })}
+ {visible.length === 0 && (
+ <div className="px-2 py-3 text-caption text-muted-foreground">{t(($) => $.empty.no_labels)}</div>
+ )}
+ </PaletteGroup>
+ );
+}
+
+export function IssueDueDatePage({ target, query }: { target: IssueTarget; query: string }) {
+ const { t } = useT("search");
+ const { t: tIssues } = useT("issues");
+ const palette = usePalette();
+ const writer = useIssueTargetWriter(target);
+ const hasDueDate = writer.issues.some((issue) => !!issue.due_date);
+ const today = todayDateOnly();
+ const options = filterByLabel(
+ [
+ { id: "today", label: tIssues(($) => $.actions.due_today), value: today as string | null },
+ { id: "tomorrow", label: tIssues(($) => $.actions.due_tomorrow), value: addDaysDateOnly(1) },
+ { id: "next-week", label: tIssues(($) => $.actions.due_next_week), value: addDaysDateOnly(7) },
+ ...(hasDueDate ? [{ id: "clear", label: tIssues(($) => $.actions.due_clear), value: null }] : []),
+ ],
+ query,
+ (o) => o.label,
+ );
+ return (
+ <PaletteGroup heading={t(($) => $.pages.due_date)}>
+ {options.map((option) => (
+ <CommandPrimitive.Item
+ key={option.id}
+ value={`due:${option.id}`}
+ onSelect={() => {
+ palette.close();
+ writer.apply({ due_date: option.value });
+ }}
+ className={ROW_CLASS}
+ >
+ {option.value ? (
+ <CalendarClock className={ROW_ICON_CLASS} />
+ ) : (
+ <CalendarX className={ROW_ICON_CLASS} />
+ )}
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={option.label} query={query} />
+ </span>
+ {option.value && <RowHint>{option.value}</RowHint>}
+ </CommandPrimitive.Item>
+ ))}
+ </PaletteGroup>
+ );
+}
+
+export function IssueProjectPage({ target, query }: { target: IssueTarget; query: string }) {
+ const { t } = useT("search");
+ const wsId = useWorkspaceId();
+ const palette = usePalette();
+ const writer = useIssueTargetWriter(target);
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ const current = common(writer.issues, (issue) => issue.project_id);
+ const live = projects.filter((project) => project.status !== "cancelled" || project.id === current);
+ const visible = filterByLabel(live, query, (project) => project.title);
+ const noProjectLabel = t(($) => $.pages.no_project);
+ const q = query.trim().toLowerCase();
+ return (
+ <PaletteGroup heading={t(($) => $.pages.project)}>
+ {(!q || scoreText(noProjectLabel, q) > 0) && (
+ <CommandPrimitive.Item
+ value="project:none"
+ onSelect={() => {
+ palette.close();
+ writer.apply({ project_id: null });
+ }}
+ className={ROW_CLASS}
+ >
+ <FolderMinus className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate text-muted-foreground">{noProjectLabel}</span>
+ {current === null && <RowCheck label={t(($) => $.pages.current)} />}
+ </CommandPrimitive.Item>
+ )}
+ {visible.map((project) => (
+ <CommandPrimitive.Item
+ key={project.id}
+ value={`project:${project.id}`}
+ onSelect={() => {
+ palette.close();
+ writer.apply({ project_id: project.id });
+ }}
+ className={ROW_CLASS}
+ >
+ <ProjectIcon project={project} size="md" />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={project.title} query={query} />
+ </span>
+ {current === project.id && <RowCheck label={t(($) => $.pages.current)} />}
+ </CommandPrimitive.Item>
+ ))}
+ </PaletteGroup>
+ );
+}
+
+/** Batch "Set parent issue": pick the parent by searching issues. */
+export function IssueParentPage({ target, query }: { target: IssueTarget; query: string }) {
+ const { t } = useT("search");
+ const { t: tIssues } = useT("issues");
+ const palette = usePalette();
+ const writer = useIssueTargetWriter(target);
+ const selectedIds = useMemo(() => new Set(writer.issues.map((issue) => issue.id)), [writer.issues]);
+ const { results, isLoading, stale } = useServerSearch(query, { projects: false });
+ const candidates = results.issues.filter((issue) => !selectedIds.has(issue.id));
+ const hasParent = writer.issues.some((issue) => !!issue.parent_issue_id);
+
+ return (
+ <>
+ {hasParent && !query.trim() && (
+ <PaletteGroup heading={t(($) => $.pages.parent)}>
+ <CommandPrimitive.Item
+ value="parent:none"
+ onSelect={() => {
+ palette.close();
+ writer.apply({ parent_issue_id: null });
+ }}
+ className={ROW_CLASS}
+ >
+ <Network className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate">{tIssues(($) => $.actions.remove_parent_issue)}</span>
+ </CommandPrimitive.Item>
+ </PaletteGroup>
+ )}
+ {!query.trim() && (
+ <div className="px-4 py-3 text-caption text-muted-foreground">{t(($) => $.empty.type_to_find_issue)}</div>
+ )}
+ {candidates.length > 0 && (
+ <PaletteGroup heading={t(($) => $.groups.issues)}>
+ {candidates.map((issue) => (
+ <IssueResultRow
+ key={issue.id}
+ issue={issue}
+ query={results.query}
+ disabled={stale}
+ onSelect={() => {
+ palette.close();
+ writer.apply({ parent_issue_id: issue.id });
+ }}
+ />
+ ))}
+ </PaletteGroup>
+ )}
+ {!isLoading && !stale && query.trim() && candidates.length === 0 && (
+ <div className="py-8 text-center text-body text-muted-foreground">{t(($) => $.empty.no_results)}</div>
+ )}
+ </>
+ );
+}
+
+export function IssueQuickActionPage({ issue, query }: { issue: Issue; query: string }) {
+ const { t } = useT("search");
+ const { t: tIssues } = useT("issues");
+ const wsId = useWorkspaceId();
+ const palette = usePalette();
+ const { data = [] } = useQuery(quickActionListOptions(wsId));
+ const run = useRunQuickAction(issue.id);
+ const actions = filterByLabel(
+ data.filter((action) => action.status === "active"),
+ query,
+ (action) => action.name,
+ );
+
+ return (
+ <PaletteGroup heading={t(($) => $.pages.quick_actions)}>
+ {actions.map((action) => {
+ const targetName = action.target_name || tIssues(($) => $.detail.quick_action_target_fallback);
+ return (
+ <CommandPrimitive.Item
+ key={action.id}
+ value={`quick-action:${action.id}`}
+ onSelect={() => {
+ palette.close();
+ run.mutateAsync({ quickActionId: action.id }).then(
+ (comment) => {
+ const { message, kind } = outcomeMessage(comment.trigger_outcomes?.[0], targetName, tIssues);
+ if (kind === "success") toast.success(message);
+ else if (kind === "error") toast.error(message);
+ else toast.info(message);
+ },
+ (error: unknown) => {
+ if (dispatchReasonCode(error) === "invocation_not_allowed") {
+ toast.error(tIssues(($) => $.detail.quick_action_blocked_body, { name: action.name }));
+ return;
+ }
+ toast.error(error instanceof Error ? error.message : String(error));
+ },
+ );
+ }}
+ className={ROW_CLASS}
+ >
+ <Zap className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={action.name} query={query} />
+ </span>
+ <RowHint>{tIssues(($) => $.detail.quick_action_runs_as, { name: targetName })}</RowHint>
+ </CommandPrimitive.Item>
+ );
+ })}
+ </PaletteGroup>
+ );
+}
diff --git a/packages/views/search/pages/other-pages.tsx b/packages/views/search/pages/other-pages.tsx
new file mode 100644
index 0000000000..37a7b324af
--- /dev/null
+++ b/packages/views/search/pages/other-pages.tsx
@@ -0,0 +1,290 @@
+"use client";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { FolderMinus, Monitor, Moon, SquarePen, Sun } from "lucide-react";
+import { Command as CommandPrimitive } from "cmdk";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { issueDetailOptions } from "@multica/core/issues/queries";
+import { useUpdateIssue } from "@multica/core/issues/mutations";
+import { useModalStore } from "@multica/core/modals";
+import { PROJECT_STATUS_CONFIG, PROJECT_STATUS_ORDER } from "@multica/core/projects/config";
+import { useUpdateProject } from "@multica/core/projects/mutations";
+import { projectListOptions } from "@multica/core/projects/queries";
+import type { Agent, ChatSession, Project } from "@multica/core/types";
+import { useTheme } from "@multica/ui/components/common/theme-provider";
+import { cn } from "@multica/ui/lib/utils";
+import { runConfirmIntent } from "../../issues/actions/run-confirm-gate";
+import { ProjectIcon } from "../../projects/components/project-icon";
+import { useProjectStatusLabels } from "../../projects/components/labels";
+import { useT } from "../../i18n";
+import { HighlightText } from "../highlight-text";
+import { scoreRow, scoreText } from "../matching";
+import { usePalette } from "../palette-context";
+import { PaletteGroup, ROW_CLASS, ROW_ICON_CLASS, RowCheck } from "../rows";
+import { ActorRow, AgentPresenceText, IssueResultRow } from "../result-rows";
+import { useServerSearch } from "../use-server-search";
+import type { DelegateActor } from "../types";
+import { useDelegateCandidates } from "../delegate/use-delegate";
+
+type ThemeValue = "light" | "dark" | "system";
+
+export function ThemePage({ query }: { query: string }) {
+ const { t } = useT("search");
+ const palette = usePalette();
+ const { theme, setTheme } = useTheme();
+ const q = query.trim().toLowerCase();
+ const options: { value: ThemeValue; label: string; icon: typeof Sun; keywords: string[] }[] = [
+ { value: "light", label: t(($) => $.theme.light), icon: Sun, keywords: ["light", "bright", "浅色"] },
+ { value: "dark", label: t(($) => $.theme.dark), icon: Moon, keywords: ["dark", "night", "深色"] },
+ { value: "system", label: t(($) => $.theme.system), icon: Monitor, keywords: ["system", "auto", "系统"] },
+ ];
+ const visible = q ? options.filter((o) => scoreRow(o.label, o.keywords, q) > 0) : options;
+ return (
+ <PaletteGroup heading={t(($) => $.pages.theme)}>
+ {visible.map((option) => (
+ <CommandPrimitive.Item
+ key={option.value}
+ value={`theme:${option.value}`}
+ onSelect={() => {
+ palette.close();
+ setTheme(option.value);
+ }}
+ className={ROW_CLASS}
+ >
+ <option.icon className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={option.label} query={query} />
+ </span>
+ {theme === option.value && <RowCheck label={t(($) => $.commands.current_theme_aria)} />}
+ </CommandPrimitive.Item>
+ ))}
+ </PaletteGroup>
+ );
+}
+
+export function ProjectStatusPage({ project, query }: { project: Project; query: string }) {
+ const { t } = useT("search");
+ const palette = usePalette();
+ const labels = useProjectStatusLabels();
+ const updateProject = useUpdateProject();
+ const q = query.trim().toLowerCase();
+ const visible = PROJECT_STATUS_ORDER.filter(
+ (status) => !q || scoreRow(labels[status] ?? status, [status.replace(/_/g, " ")], q) > 0,
+ );
+ return (
+ <PaletteGroup heading={t(($) => $.pages.project_status)}>
+ {visible.map((status) => (
+ <CommandPrimitive.Item
+ key={status}
+ value={`project-status:${status}`}
+ onSelect={() => {
+ palette.close();
+ updateProject.mutateAsync({ id: project.id, status }).catch((err: unknown) =>
+ toast.error(err instanceof Error && err.message ? err.message : t(($) => $.toast.update_failed)),
+ );
+ }}
+ className={ROW_CLASS}
+ >
+ <span className="flex size-4 shrink-0 items-center justify-center">
+ <span className={cn("size-2 rounded-full", PROJECT_STATUS_CONFIG[status].dotColor)} />
+ </span>
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={labels[status] ?? status} query={query} />
+ </span>
+ {project.status === status && <RowCheck label={t(($) => $.pages.current)} />}
+ </CommandPrimitive.Item>
+ ))}
+ </PaletteGroup>
+ );
+}
+
+/** From an agent page: pick an existing issue and assign it to the agent. */
+export function AgentAssignIssuePage({ agent, query }: { agent: Agent; query: string }) {
+ const { t } = useT("search");
+ const { t: tIssues } = useT("issues");
+ const wsId = useWorkspaceId();
+ const palette = usePalette();
+ const queryClient = useQueryClient();
+ const updateIssue = useUpdateIssue();
+ const { entryOf } = useIssueStatuses(wsId);
+ const openModal = useModalStore((s) => s.open);
+ const { results, isLoading, stale } = useServerSearch(query, { projects: false });
+ const newIssueLabel = t(($) => $.agent.new_issue, { name: agent.name });
+ const q = query.trim().toLowerCase();
+
+ const assign = async (issueId: string) => {
+ palette.close();
+ const updates = { assignee_type: "agent" as const, assignee_id: agent.id };
+ try {
+ const issue = await queryClient.fetchQuery(issueDetailOptions(wsId, issueId));
+ // Same gate as every single-issue assignment: confirm before a run starts.
+ const intent = runConfirmIntent(issue, updates, { entryOf });
+ if (intent) {
+ openModal("issue-run-confirm", intent);
+ return;
+ }
+ await updateIssue.mutateAsync({ id: issueId, ...updates });
+ toast.success(t(($) => $.toast.assigned, { identifier: issue.identifier, name: agent.name }));
+ } catch (err) {
+ toast.error(err instanceof Error && err.message ? err.message : tIssues(($) => $.detail.update_failed));
+ }
+ };
+
+ return (
+ <>
+ {(!q || scoreText(newIssueLabel, q) > 0) && (
+ <PaletteGroup heading={t(($) => $.groups.new)}>
+ <CommandPrimitive.Item
+ value="agent-new-issue"
+ onSelect={() => {
+ palette.close();
+ useModalStore.getState().open("quick-create-issue", { agent_id: agent.id });
+ }}
+ className={ROW_CLASS}
+ >
+ <SquarePen className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate">{newIssueLabel}</span>
+ </CommandPrimitive.Item>
+ </PaletteGroup>
+ )}
+ {!q && (
+ <div className="px-4 py-3 text-caption text-muted-foreground">{t(($) => $.empty.type_to_find_issue)}</div>
+ )}
+ {results.issues.length > 0 && (
+ <PaletteGroup heading={t(($) => $.groups.issues)}>
+ {results.issues.map((issue) => (
+ <IssueResultRow
+ key={issue.id}
+ issue={issue}
+ query={results.query}
+ disabled={stale}
+ onSelect={() => void assign(issue.id)}
+ />
+ ))}
+ </PaletteGroup>
+ )}
+ {!isLoading && !stale && q && results.issues.length === 0 && (
+ <div className="py-8 text-center text-body text-muted-foreground">{t(($) => $.empty.no_results)}</div>
+ )}
+ </>
+ );
+}
+
+export function ChatProjectPage({
+ session,
+ changeProject,
+ query,
+}: {
+ session: ChatSession;
+ changeProject: (projectId: string | null) => void;
+ query: string;
+}) {
+ const { t } = useT("search");
+ const wsId = useWorkspaceId();
+ const palette = usePalette();
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ const current = session.project_id ?? null;
+ const q = query.trim().toLowerCase();
+ const visible = projects
+ .filter((project) => project.status !== "cancelled" || project.id === current)
+ .filter((project) => !q || scoreText(project.title, q) > 0);
+ const noProjectLabel = t(($) => $.pages.no_project);
+ const select = (projectId: string | null) => {
+ palette.close();
+ changeProject(projectId);
+ };
+ return (
+ <PaletteGroup heading={t(($) => $.pages.project)}>
+ {current && (!q || scoreText(noProjectLabel, q) > 0) && (
+ <CommandPrimitive.Item value="chat-project:none" onSelect={() => select(null)} className={ROW_CLASS}>
+ <FolderMinus className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate text-muted-foreground">{noProjectLabel}</span>
+ </CommandPrimitive.Item>
+ )}
+ {visible.map((project) => (
+ <CommandPrimitive.Item
+ key={project.id}
+ value={`chat-project:${project.id}`}
+ onSelect={() => select(project.id)}
+ className={ROW_CLASS}
+ >
+ <ProjectIcon project={project} size="md" />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={project.title} query={query} />
+ </span>
+ {current === project.id && <RowCheck label={t(($) => $.pages.current)} />}
+ </CommandPrimitive.Item>
+ ))}
+ </PaletteGroup>
+ );
+}
+
+export function DelegateTargetPage({
+ query,
+ onSubmit,
+}: {
+ query: string;
+ onSubmit: (actor: DelegateActor) => void;
+}) {
+ const { t } = useT("search");
+ const { t: tIssues } = useT("issues");
+ const palette = usePalette();
+ const { actors, agentEntries } = useDelegateCandidates(true);
+ const q = query.trim().toLowerCase();
+ const visible = q ? actors.filter((actor) => scoreText(actor.name, q) > 0) : actors;
+ const agents = visible.filter((actor) => actor.type === "agent");
+ const squads = visible.filter((actor) => actor.type === "squad");
+ const entryOf = (id: string) => agentEntries.find((entry) => entry.agent.id === id) ?? null;
+ const select = (actor: DelegateActor) => {
+ palette.close();
+ onSubmit(actor);
+ };
+ return (
+ <>
+ {agents.length > 0 && (
+ <PaletteGroup heading={tIssues(($) => $.pickers.assignee.agents_group)}>
+ {agents.map((actor) => {
+ const entry = entryOf(actor.id);
+ return (
+ <ActorRow
+ key={actor.id}
+ value={`delegate-target:agent:${actor.id}`}
+ actorType="agent"
+ actorId={actor.id}
+ name={actor.name}
+ query={query}
+ showStatusDot
+ onSelect={() => select(actor)}
+ detail={
+ entry ? (
+ <AgentPresenceText availability={entry.availability} runtimeLabel={entry.runtimeLabel} />
+ ) : undefined
+ }
+ />
+ );
+ })}
+ </PaletteGroup>
+ )}
+ {squads.length > 0 && (
+ <PaletteGroup heading={tIssues(($) => $.pickers.assignee.squads_group)}>
+ {squads.map((actor) => (
+ <ActorRow
+ key={actor.id}
+ value={`delegate-target:squad:${actor.id}`}
+ actorType="squad"
+ actorId={actor.id}
+ name={actor.name}
+ query={query}
+ onSelect={() => select(actor)}
+ />
+ ))}
+ </PaletteGroup>
+ )}
+ {visible.length === 0 && (
+ <div className="py-8 text-center text-body text-muted-foreground">{t(($) => $.empty.no_results)}</div>
+ )}
+ </>
+ );
+}
diff --git a/packages/views/search/pages/page-view.tsx b/packages/views/search/pages/page-view.tsx
new file mode 100644
index 0000000000..9431bbd189
--- /dev/null
+++ b/packages/views/search/pages/page-view.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import type { DelegateActor, PalettePage } from "../types";
+import {
+ IssueAssigneePage,
+ IssueDueDatePage,
+ IssueLabelsPage,
+ IssueParentPage,
+ IssuePriorityPage,
+ IssueProjectPage,
+ IssueQuickActionPage,
+ IssueStatusPage,
+} from "./issue-pages";
+import {
+ AgentAssignIssuePage,
+ ChatProjectPage,
+ DelegateTargetPage,
+ ProjectStatusPage,
+ ThemePage,
+} from "./other-pages";
+
+export function PageView({
+ page,
+ query,
+ onDelegate,
+}: {
+ page: PalettePage;
+ query: string;
+ onDelegate: (actor: DelegateActor, prompt: string) => void;
+}) {
+ switch (page.type) {
+ case "issue-status":
+ return <IssueStatusPage target={page.target} query={query} />;
+ case "issue-assignee":
+ return <IssueAssigneePage target={page.target} query={query} />;
+ case "issue-priority":
+ return <IssuePriorityPage target={page.target} query={query} />;
+ case "issue-labels":
+ return <IssueLabelsPage target={page.target} query={query} />;
+ case "issue-due-date":
+ return <IssueDueDatePage target={page.target} query={query} />;
+ case "issue-project":
+ return <IssueProjectPage target={page.target} query={query} />;
+ case "issue-parent":
+ return <IssueParentPage target={page.target} query={query} />;
+ case "issue-quick-action":
+ return <IssueQuickActionPage issue={page.issue} query={query} />;
+ case "theme":
+ return <ThemePage query={query} />;
+ case "project-status":
+ return <ProjectStatusPage project={page.project} query={query} />;
+ case "agent-assign-issue":
+ return <AgentAssignIssuePage agent={page.agent} query={query} />;
+ case "chat-project":
+ return <ChatProjectPage session={page.session} changeProject={page.changeProject} query={query} />;
+ case "delegate-target":
+ return <DelegateTargetPage query={query} onSubmit={(actor) => onDelegate(actor, page.prompt)} />;
+ }
+}
diff --git a/packages/views/search/palette-context.tsx b/packages/views/search/palette-context.tsx
new file mode 100644
index 0000000000..e4a86be9c2
--- /dev/null
+++ b/packages/views/search/palette-context.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { createContext, useContext } from "react";
+import type { PaletteHostDialog, PaletteStackEntry } from "./types";
+
+export interface PaletteApi {
+ close: () => void;
+ push: (entry: PaletteStackEntry) => void;
+ /** Navigate honoring the gesture's modifiers (⌘↵ / ⌘-click open a new tab), then close. */
+ navigate: (href: string) => void;
+ /** Close the palette and open a confirm or form dialog it hosts. */
+ openHostDialog: (dialog: PaletteHostDialog) => void;
+}
+
+export const PaletteContext = createContext<PaletteApi | null>(null);
+
+export function usePalette(): PaletteApi {
+ const api = useContext(PaletteContext);
+ if (!api) throw new Error("usePalette must be used inside SearchCommand");
+ return api;
+}
diff --git a/packages/views/search/register-context.ts b/packages/views/search/register-context.ts
new file mode 100644
index 0000000000..405275d15b
--- /dev/null
+++ b/packages/views/search/register-context.ts
@@ -0,0 +1,54 @@
+"use client";
+
+import { useEffect, useId } from "react";
+import {
+ useCommandBarContextStore,
+ useRecentVisitsStore,
+ type CommandBarContext,
+ type RecentVisitType,
+} from "@multica/core/command-bar";
+
+function recentVisitOf(
+ context: CommandBarContext | null,
+): { wsId: string; type: RecentVisitType; id: string } | null {
+ switch (context?.kind) {
+ case "project":
+ return { wsId: context.project.workspace_id, type: "project", id: context.project.id };
+ case "agent":
+ return { wsId: context.agent.workspace_id, type: "agent", id: context.agent.id };
+ case "autopilot":
+ return { wsId: context.autopilot.workspace_id, type: "autopilot", id: context.autopilot.id };
+ default:
+ return null;
+ }
+}
+
+/**
+ * Tell the command bar what this page is about. Pass `null` while the object
+ * is still loading. The context must be memoized: a new object re-registers.
+ *
+ * Project, agent and autopilot pages also land in the bar's Recent group.
+ */
+export function useRegisterCommandBarContext(context: CommandBarContext | null) {
+ const token = useId();
+
+ useEffect(() => {
+ const store = useCommandBarContextStore.getState();
+ if (context) store.register(token, context);
+ else store.unregister(token);
+ }, [token, context]);
+
+ useEffect(
+ () => () => useCommandBarContextStore.getState().unregister(token),
+ [token],
+ );
+
+ const visit = recentVisitOf(context);
+ const wsId = visit?.wsId ?? null;
+ const visitType = visit?.type ?? null;
+ const visitId = visit?.id ?? null;
+ useEffect(() => {
+ if (!wsId || !visitType || !visitId) return;
+ useRecentVisitsStore.getState().recordVisit(wsId, { type: visitType, id: visitId });
+ }, [wsId, visitType, visitId]);
+}
diff --git a/packages/views/search/result-rows.tsx b/packages/views/search/result-rows.tsx
new file mode 100644
index 0000000000..58c34d58b5
--- /dev/null
+++ b/packages/views/search/result-rows.tsx
@@ -0,0 +1,259 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { FileText, MessageSquare } from "lucide-react";
+import { Command as CommandPrimitive } from "cmdk";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { issueStatusCategory } from "@multica/core/issues";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";
+import type {
+ AgentAvailability,
+} from "@multica/core/agents";
+import type {
+ Issue,
+ ProjectStatus,
+ SearchIssueResult,
+ SearchProjectResult,
+} from "@multica/core/types";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../common/actor-avatar";
+import { availabilityConfig } from "../agents/presence";
+import { StatusIcon } from "../issues/components";
+import { ProjectIcon } from "../projects/components/project-icon";
+import { useProjectStatusLabels } from "../projects/components/labels";
+import { useT } from "../i18n";
+import { HighlightText } from "./highlight-text";
+import { ROW_CLASS, RowHint } from "./rows";
+
+function IssueAssigneeAvatar({
+ assigneeType,
+ assigneeId,
+}: {
+ assigneeType?: string | null;
+ assigneeId?: string | null;
+}) {
+ if (!assigneeType || !assigneeId) return null;
+ return (
+ <ActorAvatar
+ actorType={assigneeType}
+ actorId={assigneeId}
+ size="sm"
+ profileLink={false}
+ className="shrink-0"
+ />
+ );
+}
+
+const SNIPPET_CLASS = "flex items-start gap-2 pl-[26px]";
+
+export function ProjectResultRow({
+ project,
+ query,
+ disabled,
+ onSelect,
+ trailing,
+}: {
+ project: SearchProjectResult;
+ query: string;
+ disabled?: boolean;
+ onSelect: () => void;
+ trailing?: ReactNode;
+}) {
+ const projectStatusLabels = useProjectStatusLabels();
+ const status = project.status as ProjectStatus;
+
+ return (
+ <CommandPrimitive.Item
+ value={`project:${project.id}`}
+ disabled={disabled}
+ onSelect={onSelect}
+ className={cn(ROW_CLASS, "flex-col items-stretch gap-0.5")}
+ >
+ <div className="flex min-h-7 items-center gap-2.5">
+ <ProjectIcon project={project} size="md" />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={project.title} query={query} />
+ </span>
+ <span
+ className={`shrink-0 text-caption ${PROJECT_STATUS_CONFIG[status]?.color ?? "text-muted-foreground"}`}
+ >
+ {projectStatusLabels[status] ?? project.status}
+ </span>
+ {trailing}
+ </div>
+ {project.match_source === "description" && project.matched_snippet && (
+ <div className={SNIPPET_CLASS}>
+ <span className="truncate text-caption text-muted-foreground">
+ <HighlightText text={project.matched_snippet} query={query} />
+ </span>
+ </div>
+ )}
+ </CommandPrimitive.Item>
+ );
+}
+
+export function IssueResultRow({
+ issue,
+ query,
+ disabled,
+ onSelect,
+ value,
+ trailing,
+}: {
+ issue: SearchIssueResult | Issue;
+ query: string;
+ disabled?: boolean;
+ onSelect: () => void;
+ /** cmdk value; defaults to the issue id. */
+ value?: string;
+ trailing?: ReactNode;
+}) {
+ const { colorOf, iconOf } = useIssueStatuses(useWorkspaceId());
+ const descriptionSnippet =
+ "matched_description_snippet" in issue ? issue.matched_description_snippet : undefined;
+ const commentSnippet =
+ "matched_comment_snippet" in issue ? issue.matched_comment_snippet : undefined;
+ return (
+ <CommandPrimitive.Item
+ value={value ?? issue.id}
+ disabled={disabled}
+ onSelect={onSelect}
+ className={cn(ROW_CLASS, "flex-col items-stretch gap-0.5")}
+ >
+ <div className="flex min-h-7 items-center gap-2.5">
+ <StatusIcon
+ status={issue.status}
+ color={colorOf(issue.status)}
+ icon={iconOf(issue.status)}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="size-4 shrink-0"
+ />
+ <span className="shrink-0 text-caption text-muted-foreground">{issue.identifier}</span>
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={issue.title} query={query} />
+ </span>
+ <IssueAssigneeAvatar assigneeType={issue.assignee_type} assigneeId={issue.assignee_id} />
+ {trailing}
+ </div>
+ {descriptionSnippet && (
+ <div className={SNIPPET_CLASS}>
+ <FileText className="mt-0.5 size-3 shrink-0 text-muted-foreground" />
+ <span className="truncate text-caption text-muted-foreground">
+ <HighlightText text={descriptionSnippet} query={query} />
+ </span>
+ </div>
+ )}
+ {commentSnippet && (
+ <div className={SNIPPET_CLASS}>
+ <MessageSquare className="mt-0.5 size-3 shrink-0 text-muted-foreground" />
+ <span className="truncate text-caption text-muted-foreground">
+ <HighlightText text={commentSnippet} query={query} />
+ </span>
+ </div>
+ )}
+ </CommandPrimitive.Item>
+ );
+}
+
+/** "● Online · Claude Code (host)" under or beside an agent's name. */
+export function AgentPresenceText({
+ availability,
+ runtimeLabel,
+ className,
+}: {
+ availability: AgentAvailability | null;
+ runtimeLabel?: string | null;
+ className?: string;
+}) {
+ const { t } = useT("agents");
+ if (!availability && !runtimeLabel) return null;
+ return (
+ <span className={cn("flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground", className)}>
+ {availability && (
+ <>
+ <span className={cn("size-1.5 shrink-0 rounded-full", availabilityConfig[availability].dotClass)} />
+ <span className="shrink-0">{t(($) => $.availability[availability])}</span>
+ </>
+ )}
+ {availability && runtimeLabel && <span aria-hidden="true">·</span>}
+ {runtimeLabel && <span className="truncate">{runtimeLabel}</span>}
+ </span>
+ );
+}
+
+export function ActorRow({
+ value,
+ actorType,
+ actorId,
+ name,
+ query,
+ onSelect,
+ disabled,
+ detail,
+ trailing,
+ showStatusDot,
+}: {
+ value: string;
+ actorType: "member" | "agent" | "squad";
+ actorId: string;
+ name: string;
+ query: string;
+ onSelect: () => void;
+ disabled?: boolean;
+ detail?: ReactNode;
+ trailing?: ReactNode;
+ showStatusDot?: boolean;
+}) {
+ return (
+ <CommandPrimitive.Item value={value} disabled={disabled} onSelect={onSelect} className={ROW_CLASS}>
+ <ActorAvatar
+ actorType={actorType}
+ actorId={actorId}
+ size="sm"
+ profileLink={false}
+ showStatusDot={showStatusDot}
+ className="shrink-0"
+ />
+ <span className="shrink-0 truncate">
+ <HighlightText text={name} query={query} />
+ </span>
+ {detail && <span className="min-w-0 flex-1 truncate">{detail}</span>}
+ {!detail && <span className="flex-1" />}
+ {trailing}
+ </CommandPrimitive.Item>
+ );
+}
+
+/** A generic object row: icon, title, optional detail, type label. */
+export function ObjectRow({
+ value,
+ icon,
+ title,
+ query,
+ detail,
+ typeLabel,
+ onSelect,
+ disabled,
+}: {
+ value: string;
+ icon: ReactNode;
+ title: string;
+ query: string;
+ detail?: ReactNode;
+ typeLabel?: string;
+ onSelect: () => void;
+ disabled?: boolean;
+}) {
+ return (
+ <CommandPrimitive.Item value={value} disabled={disabled} onSelect={onSelect} className={ROW_CLASS}>
+ {icon}
+ <span className="min-w-0 shrink truncate">
+ <HighlightText text={title} query={query} />
+ </span>
+ {detail && <span className="min-w-0 flex-1 truncate text-caption text-muted-foreground">{detail}</span>}
+ {!detail && <span className="flex-1" />}
+ {typeLabel && <RowHint>{typeLabel}</RowHint>}
+ </CommandPrimitive.Item>
+ );
+}
diff --git a/packages/views/search/root-view.tsx b/packages/views/search/root-view.tsx
new file mode 100644
index 0000000000..061f554056
--- /dev/null
+++ b/packages/views/search/root-view.tsx
@@ -0,0 +1,706 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { Clock, Loader2, MessageSquare, Sparkles, SquarePen, UserPlus, Zap, type LucideIcon } from "lucide-react";
+import { Command as CommandPrimitive } from "cmdk";
+import { useQuery } from "@tanstack/react-query";
+import { inboxUnreadSummaryOptions, unreadWorkspaceIds } from "@multica/core/inbox/queries";
+import { paths, useWorkspacePaths } from "@multica/core/paths";
+import type { InboxWorkspaceUnread } from "@multica/core/types";
+import { openCreateIssueWithPreference } from "@multica/core/issues/stores";
+import { ActorAvatar } from "../common/actor-avatar";
+import { routeIconForPath } from "../layout/route-icon-components";
+import { ProjectIcon } from "../projects/components/project-icon";
+import { WorkspaceAvatar } from "../workspace/workspace-avatar";
+import { useT } from "../i18n";
+import { HighlightText } from "./highlight-text";
+import { useIssueTargetWriter } from "./issue-target";
+import { usePalette } from "./palette-context";
+import { CommandGroupView, CommandRow, PaletteGroup, ROW_CLASS, ROW_ICON_CLASS, RowHint } from "./rows";
+import { ActorRow, AgentPresenceText, IssueResultRow, ObjectRow, ProjectResultRow } from "./result-rows";
+import { DelegateGroup } from "./delegate/delegate-group";
+import type { DelegateActor, IssueTarget } from "./types";
+import type { BestMatch, RootModel } from "./use-root-model";
+
+const EMPTY_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];
+
+// Group render order when scores tie. Lower first.
+const TYPE_ORDER = [
+ "context",
+ "pages",
+ "commands",
+ "agents",
+ "squads",
+ "members",
+ "projects",
+ "issues",
+ "autopilots",
+ "chats",
+ "skills",
+ "workspaces",
+] as const;
+
+interface RankedGroup {
+ key: string;
+ type: (typeof TYPE_ORDER)[number];
+ score: number;
+ node: ReactNode;
+}
+
+export function RootView({
+ model,
+ rawQuery,
+ onDelegate,
+}: {
+ model: RootModel;
+ rawQuery: string;
+ onDelegate: (actor: DelegateActor, prompt: string) => void;
+}) {
+ const { t } = useT("search");
+ const palette = usePalette();
+ const p = useWorkspacePaths();
+ const { data: unreadSummary = EMPTY_UNREAD_SUMMARY } = useQuery(inboxUnreadSummaryOptions());
+ const unreadWsIds = unreadWorkspaceIds(unreadSummary);
+ const { server, partitioned, objects, text } = model;
+ const query = text;
+
+ if (!rawQuery.trim()) {
+ return <EmptyState model={model} />;
+ }
+
+ const best = model.bestMatch;
+ const isBest = (type: BestMatch["type"], id: string) => {
+ if (!best || best.type !== type) return false;
+ if (best.type === "agent") return best.entry.agent.id === id;
+ if (best.type === "squad") return best.entry.squad.id === id;
+ if (best.type === "member") return best.member.user_id === id;
+ return best.project.id === id;
+ };
+
+ const groups: RankedGroup[] = [];
+ for (const group of model.contextGroups) {
+ groups.push({
+ key: group.id,
+ type: "context",
+ // Commands on what is on screen beat an equally good global hit.
+ score: group.score + 5,
+ node: <CommandGroupView key={group.id} group={group} query={query} />,
+ });
+ }
+ if (model.pages.length > 0) {
+ groups.push({
+ key: "pages",
+ type: "pages",
+ score: model.pages[0]!.score,
+ node: (
+ <PaletteGroup key="pages" heading={t(($) => $.groups.pages)}>
+ {model.pages.map(({ item: page }) => {
+ const PageIcon = routeIconForPath(p[page.key]());
+ return (
+ <CommandPrimitive.Item
+ key={page.key}
+ value={`page:${page.key}`}
+ onSelect={() => palette.navigate(p[page.key]())}
+ className={ROW_CLASS}
+ >
+ <PageIcon className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={page.label} query={query} />
+ </span>
+ </CommandPrimitive.Item>
+ );
+ })}
+ </PaletteGroup>
+ ),
+ });
+ }
+ if (model.commands.length > 0) {
+ groups.push({
+ key: "commands",
+ type: "commands",
+ score: model.commands[0]!.score,
+ node: (
+ <PaletteGroup key="commands" heading={t(($) => $.groups.commands)}>
+ {model.commands.map(({ item }) => (
+ <CommandRow key={item.id} command={item} query={query} />
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+
+ const agents = objects.agents.filter((hit) => !isBest("agent", hit.item.agent.id));
+ if (agents.length > 0) {
+ groups.push({
+ key: "agents",
+ type: "agents",
+ score: agents[0]!.score,
+ node: (
+ <PaletteGroup key="agents" heading={t(($) => $.groups.agents)}>
+ {agents.map(({ item: entry }) => (
+ <ActorRow
+ key={entry.agent.id}
+ value={`agent:${entry.agent.id}`}
+ actorType="agent"
+ actorId={entry.agent.id}
+ name={entry.agent.name}
+ query={query}
+ showStatusDot
+ onSelect={() => palette.navigate(p.agentDetail(entry.agent.id))}
+ detail={<AgentPresenceText availability={entry.availability} runtimeLabel={entry.runtimeLabel} />}
+ />
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+ const squads = objects.squads.filter((hit) => !isBest("squad", hit.item.squad.id));
+ if (squads.length > 0) {
+ groups.push({
+ key: "squads",
+ type: "squads",
+ score: squads[0]!.score,
+ node: (
+ <PaletteGroup key="squads" heading={t(($) => $.groups.squads)}>
+ {squads.map(({ item: entry }) => (
+ <ActorRow
+ key={entry.squad.id}
+ value={`squad:${entry.squad.id}`}
+ actorType="squad"
+ actorId={entry.squad.id}
+ name={entry.squad.name}
+ query={query}
+ onSelect={() => palette.navigate(p.squadDetail(entry.squad.id))}
+ />
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+ const members = objects.members.filter((hit) => !isBest("member", hit.item.user_id));
+ if (members.length > 0) {
+ groups.push({
+ key: "members",
+ type: "members",
+ score: members[0]!.score,
+ node: (
+ <PaletteGroup key="members" heading={t(($) => $.groups.members)}>
+ {members.map(({ item: member }) => (
+ <ActorRow
+ key={member.user_id}
+ value={`member:${member.user_id}`}
+ actorType="member"
+ actorId={member.user_id}
+ name={member.name}
+ query={query}
+ onSelect={() => palette.navigate(p.memberDetail(member.user_id))}
+ detail={
+ <span className="text-caption text-muted-foreground">
+ <HighlightText text={member.email} query={query} />
+ </span>
+ }
+ />
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+
+ /*
+ Render order keeps the cross-type cancelled partition (MUL-5824): live
+ projects and live issues rank with everything else, and one trailing
+ Cancelled section holds cancelled projects then cancelled issues. Projects
+ and issues arrive as two independently ranked responses, so per-type
+ ordering is not enough — keeping cancelled rows in a single trailing
+ section is the only arrangement where no cancelled row of either type can
+ precede a live row of the other. Direct hits stay in their live section
+ (see partitionAggregatedSearchResults).
+ */
+ const liveProjects = partitioned.liveProjects.filter((project) => !isBest("project", project.id));
+ if (liveProjects.length > 0) {
+ groups.push({
+ key: "projects",
+ type: "projects",
+ score: model.liveProjectScore,
+ node: (
+ <PaletteGroup key="projects" heading={t(($) => $.groups.projects)}>
+ {liveProjects.map((project) => (
+ <ProjectResultRow
+ key={project.id}
+ project={project}
+ query={server.results.query}
+ disabled={server.stale}
+ onSelect={() => palette.navigate(p.projectDetail(project.id))}
+ />
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+ if (partitioned.liveIssues.length > 0) {
+ groups.push({
+ key: "issues",
+ type: "issues",
+ score: model.liveIssueScore,
+ node: (
+ <PaletteGroup key="issues" heading={t(($) => $.groups.issues)}>
+ {partitioned.liveIssues.map((issue) => (
+ <IssueResultRow
+ key={issue.id}
+ issue={issue}
+ query={server.results.query}
+ disabled={server.stale}
+ onSelect={() => palette.navigate(p.issueDetail(issue.id))}
+ />
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+ if (objects.autopilots.length > 0) {
+ groups.push({
+ key: "autopilots",
+ type: "autopilots",
+ score: objects.autopilots[0]!.score,
+ node: (
+ <PaletteGroup key="autopilots" heading={t(($) => $.groups.autopilots)}>
+ {objects.autopilots.map(({ item: autopilot }) => (
+ <ObjectRow
+ key={autopilot.id}
+ value={`autopilot:${autopilot.id}`}
+ icon={<Zap className={ROW_ICON_CLASS} />}
+ title={autopilot.title}
+ query={query}
+ onSelect={() => palette.navigate(p.autopilotDetail(autopilot.id))}
+ />
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+ if (objects.chats.length > 0) {
+ groups.push({
+ key: "chats",
+ type: "chats",
+ score: objects.chats[0]!.score,
+ node: (
+ <PaletteGroup key="chats" heading={t(($) => $.groups.chats)}>
+ {objects.chats.map(({ item: session }) => (
+ <ObjectRow
+ key={session.id}
+ value={`chat:${session.id}`}
+ icon={<MessageSquare className={ROW_ICON_CLASS} />}
+ title={session.title}
+ query={query}
+ onSelect={() => palette.navigate(p.chatSession(session.id))}
+ />
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+ if (objects.skills.length > 0) {
+ groups.push({
+ key: "skills",
+ type: "skills",
+ score: objects.skills[0]!.score,
+ node: (
+ <PaletteGroup key="skills" heading={t(($) => $.groups.skills)}>
+ {objects.skills.map(({ item: skill }) => (
+ <ObjectRow
+ key={skill.id}
+ value={`skill:${skill.id}`}
+ icon={<Sparkles className={ROW_ICON_CLASS} />}
+ title={skill.name}
+ query={query}
+ detail={skill.description}
+ onSelect={() => palette.navigate(p.skillDetail(skill.id))}
+ />
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+ if (objects.workspaces.length > 0) {
+ groups.push({
+ key: "workspaces",
+ type: "workspaces",
+ score: objects.workspaces[0]!.score,
+ node: (
+ <PaletteGroup key="workspaces" heading={t(($) => $.groups.workspaces)}>
+ {objects.workspaces.map(({ item: ws }) => (
+ <CommandPrimitive.Item
+ key={ws.id}
+ value={`workspace:${ws.id}`}
+ // Web lands on the target's Issues; the desktop adapter reads
+ // this same push as "resume the workspace's last active tab".
+ onSelect={() => palette.navigate(paths.workspace(ws.slug).issues())}
+ className={ROW_CLASS}
+ >
+ <WorkspaceAvatar name={ws.name} avatarUrl={ws.avatar_url} size="sm" />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={ws.name} query={query} />
+ </span>
+ {/* Same dot the sidebar switcher puts on a workspace with
+ unread inbox items. */}
+ {unreadWsIds.has(ws.id) && (
+ <span data-testid="workspace-unread-dot" className="size-2 shrink-0 rounded-full bg-brand" />
+ )}
+ </CommandPrimitive.Item>
+ ))}
+ </PaletteGroup>
+ ),
+ });
+ }
+
+ groups.sort(
+ (a, b) => b.score - a.score || TYPE_ORDER.indexOf(a.type) - TYPE_ORDER.indexOf(b.type),
+ );
+
+ const nothing = !model.hasResults && !model.delegate && !best;
+
+ return (
+ <>
+ {model.delegate && (
+ <DelegateGroup
+ prompt={model.delegate.prompt}
+ actor={model.delegate.actor}
+ agentEntry={model.delegate.agentEntry}
+ attachments={model.delegate.attachments}
+ onSubmit={(actor) => onDelegate(actor, model.delegate!.prompt)}
+ />
+ )}
+ {best && <BestMatchGroups best={best} query={query} target={model.primaryIssueTarget} />}
+ {groups.map((group) => group.node)}
+ {partitioned.hasCancelled && (
+ <PaletteGroup heading={t(($) => $.groups.cancelled)}>
+ {partitioned.cancelledProjects.map((project) => (
+ <ProjectResultRow
+ key={project.id}
+ project={project}
+ query={server.results.query}
+ disabled={server.stale}
+ onSelect={() => palette.navigate(p.projectDetail(project.id))}
+ />
+ ))}
+ {partitioned.cancelledIssues.map((issue) => (
+ <IssueResultRow
+ key={issue.id}
+ issue={issue}
+ query={server.results.query}
+ disabled={server.stale}
+ onSelect={() => palette.navigate(p.issueDetail(issue.id))}
+ />
+ ))}
+ </PaletteGroup>
+ )}
+ {/*
+ Spinner only while there is nothing to look at. isLoading flips on the
+ keystroke, before the debounce even fires, so swapping the whole list
+ for a spinner on every character made it strobe while typing. Keeping
+ the previous query's rows until the next response lands is the
+ standard trade: they are one keystroke stale for a moment, instead of
+ gone.
+ */}
+ {server.isLoading && nothing && <LoadingRow />}
+ {!server.isLoading && nothing && (
+ <CommandPrimitive.Empty className="py-10 text-center text-body text-muted-foreground">
+ {t(($) => $.empty.no_results)}
+ </CommandPrimitive.Empty>
+ )}
+ </>
+ );
+}
+
+function LoadingRow() {
+ return (
+ <div className="flex items-center justify-center py-10">
+ <Loader2 className="size-5 animate-spin text-muted-foreground" />
+ </div>
+ );
+}
+
+function BestMatchGroups({
+ best,
+ query,
+ target,
+}: {
+ best: BestMatch;
+ query: string;
+ target: IssueTarget | null;
+}) {
+ const { t } = useT("search");
+ const palette = usePalette();
+ const p = useWorkspacePaths();
+
+ let row: ReactNode;
+ const actions: { id: string; label: string; icon: LucideIcon; run?: () => void }[] = [];
+ const subject = target
+ ? target.kind === "single"
+ ? target.issue.identifier
+ : t(($) => $.context.selected_issues, { count: target.issues.length })
+ : null;
+
+ if (best.type === "agent") {
+ const { agent } = best.entry;
+ row = (
+ <ActorRow
+ value={`best:agent:${agent.id}`}
+ actorType="agent"
+ actorId={agent.id}
+ name={agent.name}
+ query={query}
+ showStatusDot
+ onSelect={() => palette.navigate(p.agentDetail(agent.id))}
+ detail={<AgentPresenceText availability={best.entry.availability} runtimeLabel={best.entry.runtimeLabel} />}
+ trailing={<RowHint>{t(($) => $.types.agent)}</RowHint>}
+ />
+ );
+ if (best.entry.assignable) {
+ if (target && subject) {
+ actions.push({
+ id: "assign",
+ label: t(($) => $.best.assign, { subject, name: agent.name }),
+ icon: UserPlus,
+ });
+ }
+ actions.push({
+ id: "chat",
+ label: t(($) => $.best.chat, { name: agent.name }),
+ icon: MessageSquare,
+ run: () => palette.navigate(p.chatWithAgent(agent.id)),
+ });
+ }
+ } else if (best.type === "squad") {
+ const { squad } = best.entry;
+ row = (
+ <ActorRow
+ value={`best:squad:${squad.id}`}
+ actorType="squad"
+ actorId={squad.id}
+ name={squad.name}
+ query={query}
+ onSelect={() => palette.navigate(p.squadDetail(squad.id))}
+ trailing={<RowHint>{t(($) => $.types.squad)}</RowHint>}
+ />
+ );
+ if (best.entry.runnable && target && subject) {
+ actions.push({
+ id: "assign",
+ label: t(($) => $.best.assign, { subject, name: squad.name }),
+ icon: UserPlus,
+ });
+ }
+ } else if (best.type === "member") {
+ const { member } = best;
+ row = (
+ <ActorRow
+ value={`best:member:${member.user_id}`}
+ actorType="member"
+ actorId={member.user_id}
+ name={member.name}
+ query={query}
+ onSelect={() => palette.navigate(p.memberDetail(member.user_id))}
+ detail={<span className="text-caption text-muted-foreground">{member.email}</span>}
+ trailing={<RowHint>{t(($) => $.types.member)}</RowHint>}
+ />
+ );
+ if (target && subject) {
+ actions.push({
+ id: "assign",
+ label: t(($) => $.best.assign, { subject, name: member.name }),
+ icon: UserPlus,
+ });
+ }
+ } else {
+ const { project } = best;
+ row = (
+ <ProjectResultRow
+ project={project}
+ query={query}
+ onSelect={() => palette.navigate(p.projectDetail(project.id))}
+ trailing={<RowHint>{t(($) => $.types.project)}</RowHint>}
+ />
+ );
+ actions.push({
+ id: "new-issue",
+ label: t(($) => $.best.new_issue_in, { name: project.title }),
+ icon: SquarePen,
+ run: () => {
+ palette.close();
+ openCreateIssueWithPreference({ project_id: project.id });
+ },
+ });
+ }
+
+ return (
+ <>
+ <PaletteGroup heading={t(($) => $.groups.best_match)}>{row}</PaletteGroup>
+ {actions.length > 0 && (
+ <PaletteGroup heading={t(($) => $.groups.actions)}>
+ {actions.map((action) =>
+ action.id === "assign" && target ? (
+ <AssignActionRow key={action.id} label={action.label} target={target} best={best} query={query} />
+ ) : (
+ <CommandPrimitive.Item
+ key={action.id}
+ value={`best-action:${action.id}`}
+ onSelect={action.run}
+ className={ROW_CLASS}
+ >
+ <action.icon className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={action.label} query={query} />
+ </span>
+ </CommandPrimitive.Item>
+ ),
+ )}
+ </PaletteGroup>
+ )}
+ </>
+ );
+}
+
+function AssignActionRow({
+ label,
+ target,
+ best,
+ query,
+}: {
+ label: string;
+ target: IssueTarget;
+ best: BestMatch;
+ query: string;
+}) {
+ const palette = usePalette();
+ const writer = useIssueTargetWriter(target);
+ return (
+ <CommandPrimitive.Item
+ value="best-action:assign"
+ onSelect={() => {
+ palette.close();
+ if (best.type === "agent") writer.assign("agent", best.entry.agent.id);
+ else if (best.type === "squad") writer.assign("squad", best.entry.squad.id);
+ else if (best.type === "member") writer.assign("member", best.member.user_id);
+ }}
+ className={ROW_CLASS}
+ >
+ <UserPlus className={ROW_ICON_CLASS} />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={label} query={query} />
+ </span>
+ </CommandPrimitive.Item>
+ );
+}
+
+function EmptyState({ model }: { model: RootModel }) {
+ const { t } = useT("search");
+ const palette = usePalette();
+ const p = useWorkspacePaths();
+
+ if (model.scope !== "all") {
+ return (
+ <>
+ {model.contextGroups.map((group) => (
+ <CommandGroupView key={group.id} group={group} query="" />
+ ))}
+ {model.commands.length > 0 && (
+ <PaletteGroup heading={t(($) => $.groups.commands)}>
+ {model.commands.map(({ item }) => (
+ <CommandRow key={item.id} command={item} query="" />
+ ))}
+ </PaletteGroup>
+ )}
+ {model.scope !== "commands" && (
+ <div className="px-5 py-4 text-center text-caption text-muted-foreground">
+ {model.scope === "issues" ? t(($) => $.empty.type_to_find_issue) : t(($) => $.empty.type_to_find_people)}
+ </div>
+ )}
+ </>
+ );
+ }
+
+ return (
+ <>
+ {model.contextGroups.map((group) => (
+ <CommandGroupView key={group.id} group={group} query="" />
+ ))}
+ <PaletteGroup heading={t(($) => $.groups.new)}>
+ {model.newCommands.map((command) => (
+ <CommandRow key={command.id} command={command} query="" />
+ ))}
+ </PaletteGroup>
+ {model.recent.length > 0 && (
+ <PaletteGroup
+ heading={
+ <>
+ <Clock className="size-3" />
+ <span>{t(($) => $.groups.recent)}</span>
+ </>
+ }
+ >
+ {model.recent.map((item) => {
+ switch (item.type) {
+ case "issue":
+ return (
+ <IssueResultRow
+ key={`issue:${item.id}`}
+ issue={item.issue}
+ query=""
+ onSelect={() => palette.navigate(p.issueDetail(item.id))}
+ trailing={<RowHint>{t(($) => $.types.issue)}</RowHint>}
+ />
+ );
+ case "project":
+ return (
+ <ObjectRow
+ key={`project:${item.id}`}
+ value={`recent-project:${item.id}`}
+ icon={<ProjectIcon project={item.project} size="md" />}
+ title={item.project.title}
+ query=""
+ typeLabel={t(($) => $.types.project)}
+ onSelect={() => palette.navigate(p.projectDetail(item.id))}
+ />
+ );
+ case "agent":
+ return (
+ <ObjectRow
+ key={`agent:${item.id}`}
+ value={`recent-agent:${item.id}`}
+ icon={
+ <ActorAvatar
+ actorType="agent"
+ actorId={item.id}
+ size="sm"
+ profileLink={false}
+ showStatusDot
+ className="shrink-0"
+ />
+ }
+ title={item.agent.name}
+ query=""
+ typeLabel={t(($) => $.types.agent)}
+ onSelect={() => palette.navigate(p.agentDetail(item.id))}
+ />
+ );
+ case "autopilot":
+ return (
+ <ObjectRow
+ key={`autopilot:${item.id}`}
+ value={`recent-autopilot:${item.id}`}
+ icon={<Zap className={ROW_ICON_CLASS} />}
+ title={item.autopilot.title}
+ query=""
+ typeLabel={t(($) => $.types.autopilot)}
+ onSelect={() => palette.navigate(p.autopilotDetail(item.id))}
+ />
+ );
+ }
+ })}
+ </PaletteGroup>
+ )}
+ </>
+ );
+}
+
diff --git a/packages/views/search/rows.tsx b/packages/views/search/rows.tsx
new file mode 100644
index 0000000000..65aeaecd88
--- /dev/null
+++ b/packages/views/search/rows.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { Check } from "lucide-react";
+import { Command as CommandPrimitive } from "cmdk";
+import { cn } from "@multica/ui/lib/utils";
+import { ShortcutKeycaps } from "../common/shortcut-keycaps";
+import { HighlightText } from "./highlight-text";
+import { stripEllipsis } from "./matching";
+import { usePalette } from "./palette-context";
+import type { PaletteCommand, PaletteCommandGroup } from "./types";
+
+// One heading treatment for every group. Headings go through cmdk's `heading`
+// prop rather than a hand-rolled div: cmdk renders it into a
+// [cmdk-group-heading] node and points the group's aria-labelledby at it, so a
+// screen reader announces which group a row belongs to.
+export const GROUP_CLASS =
+ "px-2 py-1 [&_[cmdk-group-heading]]:flex [&_[cmdk-group-heading]]:min-w-0 [&_[cmdk-group-heading]]:items-center [&_[cmdk-group-heading]]:gap-1.5 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:pt-1.5 [&_[cmdk-group-heading]]:pb-1 [&_[cmdk-group-heading]]:text-caption [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground";
+
+export const ROW_CLASS =
+ "group/row flex min-h-[var(--issue-row-height)] cursor-default select-none items-center gap-2.5 rounded-md px-2 py-1 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent";
+
+export const ROW_ICON_CLASS = "size-4 shrink-0 text-muted-foreground";
+
+export function PaletteGroup({
+ heading,
+ children,
+ className,
+}: {
+ heading: ReactNode;
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <CommandPrimitive.Group heading={heading} className={cn(GROUP_CLASS, className)}>
+ {children}
+ </CommandPrimitive.Group>
+ );
+}
+
+/** Trailing muted text, e.g. a type label or "3 available". */
+export function RowHint({ children }: { children: ReactNode }) {
+ return <span className="ml-auto shrink-0 text-caption text-muted-foreground">{children}</span>;
+}
+
+export function RowCheck({ label }: { label?: string }) {
+ return (
+ <Check
+ aria-label={label}
+ aria-hidden={label ? undefined : true}
+ className="ml-auto size-4 shrink-0 text-muted-foreground"
+ />
+ );
+}
+
+export function CommandRow({
+ command,
+ query,
+ scope,
+}: {
+ command: PaletteCommand;
+ query: string;
+ /**
+ * The group the row belongs to. cmdk tracks selection by value, so two groups
+ * offering the same command (the previewed issue and the list selection
+ * around it) need distinct values or Enter runs the first group's row.
+ */
+ scope?: string;
+}) {
+ const palette = usePalette();
+ const Icon = command.icon;
+ return (
+ <CommandPrimitive.Item
+ value={scope ? `command:${scope}:${command.id}` : `command:${command.id}`}
+ onSelect={() => {
+ if (command.page) {
+ palette.push({
+ page: command.page,
+ crumbs: [command.crumb, stripEllipsis(command.label)].filter(
+ (crumb): crumb is string => !!crumb,
+ ),
+ });
+ return;
+ }
+ palette.close();
+ command.run?.();
+ }}
+ className={cn(ROW_CLASS, command.destructive && "text-destructive")}
+ >
+ <Icon className={cn(ROW_ICON_CLASS, command.destructive && "text-destructive")} />
+ <span className="min-w-0 flex-1 truncate">
+ <HighlightText text={command.label} query={query} />
+ </span>
+ {command.trailing}
+ {command.hint && <RowHint>{command.hint}</RowHint>}
+ {command.shortcut && (
+ <ShortcutKeycaps shortcut={command.shortcut} decorative className="shrink-0" />
+ )}
+ </CommandPrimitive.Item>
+ );
+}
+
+export function CommandGroupView({ group, query }: { group: PaletteCommandGroup; query: string }) {
+ if (group.commands.length === 0) return null;
+ return (
+ <PaletteGroup heading={group.heading}>
+ {group.commands.map((command) => (
+ <CommandRow key={command.id} command={command} query={query} scope={group.id} />
+ ))}
+ </PaletteGroup>
+ );
+}
diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsx
index f94b8c966c..0d3869d356 100644
--- a/packages/views/search/search-command.test.tsx
+++ b/packages/views/search/search-command.test.tsx
@@ -1,196 +1,199 @@
import { act, type ReactNode } from "react";
-import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";
-
-vi.mock("@multica/core/issue-statuses/hooks", () => ({
- useIssueStatuses: () => buildIssueStatusCatalog([]),
-}));
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";
+import { useCommandBarContextStore, type CommandBarContext } from "@multica/core/command-bar";
+import { inboxUnreadSummaryOptions } from "@multica/core/inbox/queries";
import { I18nProvider } from "@multica/core/i18n/react";
+import { issueDetailOptions, issueTimelineOptions } from "@multica/core/issues/queries";
import { WORKSPACE_PAGES } from "@multica/core/paths";
-import { SearchCommand } from "./search-command";
-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
-import { useSearchStore } from "./search-store";
-import enCommon from "../locales/en/common.json";
-import enAuth from "../locales/en/auth.json";
-import enSettings from "../locales/en/settings.json";
-import enSearch from "../locales/en/search.json";
-// The palette labels its Pages group from the sidebar's own nav strings, so
-// the layout namespace is part of its contract, not incidental setup.
+import type { Issue } from "@multica/core/types";
+import {
+ agentListOptions,
+ memberListOptions,
+ squadListOptions,
+ workspaceListOptions,
+} from "@multica/core/workspace/queries";
+import { RESOURCES } from "../locales";
import enLayout from "../locales/en/layout.json";
-import enProjects from "../locales/en/projects.json";
import zhHansProjects from "../locales/zh-Hans/projects.json";
+import { SearchCommand } from "./search-command";
+import { useSearchStore } from "./search-store";
-const TEST_RESOURCES = {
- en: {
- common: enCommon,
- auth: enAuth,
- settings: enSettings,
- search: enSearch,
- layout: enLayout,
- projects: enProjects,
- },
-};
-
-// Deliberately NOT a full zh-Hans bundle: only `projects` is translated, and
-// every other namespace stays on its English bundle under the zh-Hans key.
-// The one thing under test is whether a project row names its status through
-// the projects namespace, and keeping the chrome in English lets these tests
-// go on addressing the palette by its English placeholder and group headings.
-const ZH_TEST_RESOURCES = {
- "zh-Hans": {
- common: enCommon,
- auth: enAuth,
- settings: enSettings,
- search: enSearch,
- layout: enLayout,
- projects: zhHansProjects,
- },
-};
-
-function I18nWrapper({ children }: { children: ReactNode }) {
- return (
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- {children}
- </I18nProvider>
- );
-}
-
-const renderSearch = () => render(<SearchCommand />, { wrapper: I18nWrapper });
-
-function ChineseI18nWrapper({ children }: { children: ReactNode }) {
- return (
- <I18nProvider locale="zh-Hans" resources={ZH_TEST_RESOURCES}>
- {children}
- </I18nProvider>
- );
-}
-
-const renderSearchInChinese = () =>
- render(<SearchCommand />, { wrapper: ChineseI18nWrapper });
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () => buildIssueStatusCatalog([]),
+}));
const {
+ queryData,
+ apiFns,
+ mockApi,
mockPush,
- mockSearchIssues,
- mockSearchProjects,
- mockRecentItems,
- mockAllIssues,
- mockSetTheme,
- mockTheme,
mockPathname,
mockGetShareableUrl,
- mockMembers,
- mockAgents,
- mockSquads,
- mockWorkspaces,
- mockUnreadSummary,
+ mockRecentItems,
mockOpenModal,
- mockToastSuccess,
- mockClipboardWrite,
- mockTimeline,
+ mockToast,
+ mockSetTheme,
+ mockTheme,
mockCommentCollapseAll,
mockCommentExpandAll,
mockResolvedCollapseAll,
mockResolvedExpandAll,
-} = vi.hoisted(() => ({
- mockPush: vi.fn(),
- mockSearchIssues: vi.fn(),
- mockSearchProjects: vi.fn(),
- mockRecentItems: { current: [] as Array<{ id: string; visitedAt: number }> },
- mockAllIssues: { current: [] as Array<Record<string, unknown>> },
- mockSetTheme: vi.fn(),
- mockTheme: { current: "system" as "light" | "dark" | "system" },
- mockPathname: { current: "/ws-test/issues" as string },
- mockGetShareableUrl: vi.fn((p: string) => `https://app.multica/${p}`),
- mockMembers: {
- current: [] as Array<{
- id: string;
- workspace_id: string;
- user_id: string;
- role: "owner" | "admin" | "member";
- created_at: string;
- name: string;
- email: string;
- avatar_url: string | null;
- }>,
- },
- mockAgents: {
- current: [] as Array<{
- id: string;
- name: string;
- avatar_url: string | null;
- }>,
- },
- mockSquads: {
- current: [] as Array<{
- id: string;
- name: string;
- avatar_url: string | null;
- }>,
- },
- mockWorkspaces: {
- current: [] as Array<{
- id: string;
- name: string;
- slug: string;
- avatar_url: string | null;
- created_at: string;
- }>,
- },
- mockUnreadSummary: {
- current: [] as Array<{ workspace_id: string; count: number }>,
- },
- mockOpenModal: vi.fn(),
- mockToastSuccess: vi.fn(),
- mockClipboardWrite: vi.fn(() => Promise.resolve()),
- mockTimeline: { current: [] as Array<Record<string, unknown>> },
- mockCommentCollapseAll: vi.fn(),
- mockCommentExpandAll: vi.fn(),
- mockResolvedCollapseAll: vi.fn(),
- mockResolvedExpandAll: vi.fn(),
+} = vi.hoisted(() => {
+ const apiFns = new Map<string, ReturnType<typeof vi.fn>>();
+ const toast = Object.assign(vi.fn(), {
+ success: vi.fn(),
+ error: vi.fn(),
+ warning: vi.fn(),
+ info: vi.fn(),
+ message: vi.fn(),
+ });
+ return {
+ queryData: new Map<string, unknown>(),
+ apiFns,
+ // Any API method resolves to an empty object unless a test sets it.
+ mockApi: new Proxy(
+ {},
+ {
+ get(_, prop) {
+ if (typeof prop !== "string" || prop === "then") return undefined;
+ if (!apiFns.has(prop)) apiFns.set(prop, vi.fn(() => Promise.resolve({})));
+ return apiFns.get(prop);
+ },
+ },
+ ),
+ mockPush: vi.fn(),
+ mockPathname: { current: "/ws-test/issues" },
+ mockGetShareableUrl: vi.fn((p: string) => `https://app.multica/${p}`),
+ mockRecentItems: { current: [] as Array<{ id: string; visitedAt: number }> },
+ mockOpenModal: vi.fn(),
+ mockToast: toast,
+ mockSetTheme: vi.fn(),
+ mockTheme: { current: "system" as "light" | "dark" | "system" },
+ mockCommentCollapseAll: vi.fn(),
+ mockCommentExpandAll: vi.fn(),
+ mockResolvedCollapseAll: vi.fn(),
+ mockResolvedExpandAll: vi.fn(),
+ };
+});
+
+vi.mock("@tanstack/react-query", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@tanstack/react-query")>();
+ type Opts = {
+ queryKey: readonly unknown[];
+ enabled?: boolean;
+ select?: (data: unknown) => unknown;
+ };
+ const read = (opts: Opts) => {
+ if (opts.enabled === false) return undefined;
+ const data = queryData.get(JSON.stringify(opts.queryKey));
+ return data !== undefined && opts.select ? opts.select(data) : data;
+ };
+ const fetchLike = (opts: Opts) => {
+ const data = queryData.get(JSON.stringify(opts.queryKey));
+ return data !== undefined
+ ? Promise.resolve(data)
+ : Promise.reject(new Error(`unexpected key ${JSON.stringify(opts.queryKey)}`));
+ };
+ const client = {
+ ensureQueryData: fetchLike,
+ fetchQuery: fetchLike,
+ getQueryData: (key: readonly unknown[]) => queryData.get(JSON.stringify(key)),
+ getQueriesData: () => [],
+ setQueryData: vi.fn(),
+ setQueriesData: vi.fn(),
+ invalidateQueries: vi.fn(() => Promise.resolve()),
+ cancelQueries: vi.fn(() => Promise.resolve()),
+ removeQueries: vi.fn(),
+ };
+ return {
+ ...actual,
+ useQuery: (opts: Opts) => {
+ const data = read(opts);
+ return {
+ data,
+ isLoading: false,
+ isPending: data === undefined,
+ isError: false,
+ isSuccess: data !== undefined,
+ };
+ },
+ useQueries: (opts: { queries: Opts[]; combine?: (r: unknown[]) => unknown }) => {
+ const results = opts.queries.map((q) => ({ data: read(q) }));
+ return opts.combine ? opts.combine(results) : results;
+ },
+ useQueryClient: () => client,
+ // Mutations run their mutationFn (which calls the mocked api) and the
+ // per-call callbacks; cache side effects are out of scope here.
+ useMutation: (opts: { mutationFn?: (vars: unknown) => Promise<unknown> }) => {
+ const run = (vars: unknown) => Promise.resolve().then(() => opts.mutationFn?.(vars));
+ return {
+ mutateAsync: run,
+ mutate: (
+ vars: unknown,
+ cbs?: { onSuccess?: (d: unknown) => void; onError?: (e: unknown) => void },
+ ) => {
+ run(vars).then(
+ (d) => cbs?.onSuccess?.(d),
+ (e) => cbs?.onError?.(e),
+ );
+ },
+ isPending: false,
+ reset: () => {},
+ };
+ },
+ };
+});
+
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/api")>()),
+ api: mockApi,
+}));
+
+vi.mock("@multica/core/auth", async (importOriginal) => {
+ const state = { user: { id: "user-me", name: "Me Myself", email: "[email protected]" } };
+ return {
+ ...(await importOriginal<typeof import("@multica/core/auth")>()),
+ useAuthStore: Object.assign((selector?: (s: typeof state) => unknown) => (selector ? selector(state) : state), {
+ getState: () => state,
+ }),
+ };
+});
+
+vi.mock("@multica/core/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/hooks")>()),
+ useWorkspaceId: () => "ws-test",
}));
-vi.mock("@multica/core/api", () => ({
- api: {
- getBaseUrl: () => "http://127.0.0.1:8080",
- searchIssues: mockSearchIssues,
- searchProjects: mockSearchProjects,
- },
+vi.mock("@multica/core", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core")>()),
+ useWorkspaceId: () => "ws-test",
}));
+vi.mock("@multica/core/paths", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/paths")>();
+ return {
+ ...actual,
+ useWorkspacePaths: () => actual.paths.workspace("ws-test"),
+ useCurrentWorkspace: () => ({ id: "ws-test", slug: "ws-test", name: "Test Workspace" }),
+ };
+});
+
vi.mock("../common/actor-avatar", () => ({
- ActorAvatar: ({
- actorType,
- actorId,
- }: {
- actorType: string;
- actorId: string;
- }) => {
- const name =
- actorType === "member"
- ? mockMembers.current.find((m) => m.user_id === actorId)?.name
- : actorType === "agent"
- ? mockAgents.current.find((a) => a.id === actorId)?.name
- : actorType === "squad"
- ? mockSquads.current.find((s) => s.id === actorId)?.name
- : undefined;
- return (
- <span
- data-testid="issue-assignee-avatar"
- title={name ?? `${actorType}:${actorId}`}
- />
- );
- },
+ ActorAvatar: ({ actorType, actorId }: { actorType: string; actorId: string }) => (
+ <span data-testid="actor-avatar" title={`${actorType}:${actorId}`} />
+ ),
}));
-vi.mock("@multica/core/issues/stores", () => {
+vi.mock("@multica/core/issues/stores", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/issues/stores")>();
const EMPTY: Array<{ id: string; visitedAt: number }> = [];
return {
+ ...actual,
useRecentIssuesStore: (
- selector?: (state: {
- byWorkspace: Record<string, typeof mockRecentItems.current>;
- }) => unknown,
+ selector?: (state: { byWorkspace: Record<string, typeof mockRecentItems.current> }) => unknown,
) => {
const state = { byWorkspace: { "ws-test": mockRecentItems.current } };
return selector ? selector(state) : state;
@@ -202,115 +205,23 @@ vi.mock("@multica/core/issues/stores", () => {
openCreateIssueWithPreference: (data?: Record<string, unknown> | null) =>
mockOpenModal("quick-create-issue", data ?? null),
useCommentCollapseStore: Object.assign(vi.fn(), {
- getState: () => ({
- collapseAll: mockCommentCollapseAll,
- expandAll: mockCommentExpandAll,
- }),
+ getState: () => ({ collapseAll: mockCommentCollapseAll, expandAll: mockCommentExpandAll }),
}),
useResolvedExpandStore: Object.assign(vi.fn(), {
- getState: () => ({
- collapseAll: mockResolvedCollapseAll,
- expandAll: mockResolvedExpandAll,
- }),
+ getState: () => ({ collapseAll: mockResolvedCollapseAll, expandAll: mockResolvedExpandAll }),
}),
};
});
-vi.mock("@multica/core", () => ({
- useWorkspaceId: () => "ws-test",
-}));
-
-vi.mock("@multica/core/paths", async (importOriginal) => ({
- // Spread the real module so pure helpers (resolveRouteIconName, used to
- // derive each nav page's icon from its href) stay intact.
- ...(await importOriginal<typeof import("@multica/core/paths")>()),
- useWorkspacePaths: () => ({
- inbox: () => "/ws-test/inbox",
- chat: () => "/ws-test/chat",
- myIssues: () => "/ws-test/my-issues",
- issues: () => "/ws-test/issues",
- projects: () => "/ws-test/projects",
- autopilots: () => "/ws-test/autopilots",
- agents: () => "/ws-test/agents",
- squads: () => "/ws-test/squads",
- usage: () => "/ws-test/usage",
- runtimes: () => "/ws-test/runtimes",
- skills: () => "/ws-test/skills",
- settings: () => "/ws-test/settings",
- issueDetail: (id: string) => `/ws-test/issues/${id}`,
- memberDetail: (id: string) => `/ws-test/members/${id}`,
- agentDetail: (id: string) => `/ws-test/agents/${id}`,
- squadDetail: (id: string) => `/ws-test/squads/${id}`,
- projectDetail: (id: string) => `/ws-test/projects/${id}`,
- }),
-}));
-
-vi.mock("@multica/core/issues/queries", () => ({
- issueDetailOptions: (_wsId: string, id: string) => ({
- queryKey: ["issues", "ws-test", "detail", id],
- }),
- issueTimelineOptions: (id: string) => ({
- queryKey: ["issues", "timeline", id],
- }),
-}));
-
-vi.mock("@multica/core/workspace/queries", () => ({
- memberListOptions: () => ({ queryKey: ["workspaces", "ws-test", "members"] }),
- agentListOptions: () => ({ queryKey: ["workspaces", "ws-test", "agents"] }),
- squadListOptions: () => ({ queryKey: ["workspaces", "ws-test", "squads"] }),
- workspaceListOptions: () => ({ queryKey: ["workspaces", "list"] }),
-}));
-
-vi.mock("@multica/core/inbox/queries", async (importOriginal) => ({
- ...(await importOriginal<typeof import("@multica/core/inbox/queries")>()),
- inboxUnreadSummaryOptions: () => ({ queryKey: ["inbox", "unread-summary"] }),
-}));
-
-vi.mock("@multica/core/modals", () => ({
- useModalStore: Object.assign(vi.fn(), {
- getState: () => ({ open: mockOpenModal }),
- }),
-}));
-
-function resolveIssue(key: readonly unknown[]) {
- // issueDetailOptions key shape: ["issues", wsId, "detail", id]
- if (key[0] === "issues" && key[2] === "detail") {
- const id = key[3];
- return mockAllIssues.current.find((i) => i.id === id || i.identifier === id);
- }
- return undefined;
-}
-
-vi.mock("@tanstack/react-query", () => ({
- useQuery: (opts: { queryKey: readonly unknown[]; enabled?: boolean }) => {
- const key = opts.queryKey;
- if (key[0] === "workspaces" && key[1] === "list") {
- return { data: mockWorkspaces.current };
- }
- if (key[0] === "inbox" && key[1] === "unread-summary") {
- return { data: mockUnreadSummary.current };
- }
- if (key[0] === "workspaces" && key[2] === "members") {
- return { data: mockMembers.current };
- }
- if (key[0] === "workspaces" && key[2] === "agents") {
- return { data: mockAgents.current };
- }
- if (key[0] === "workspaces" && key[2] === "squads") {
- return { data: mockSquads.current };
- }
- if (opts.enabled === false) return { data: undefined };
- return { data: resolveIssue(key) };
- },
- useQueries: (opts: { queries: Array<{ queryKey: readonly unknown[] }> }) =>
- opts.queries.map((q) => ({ data: resolveIssue(q.queryKey) })),
- useQueryClient: () => ({
- ensureQueryData: (opts: { queryKey: readonly unknown[] }) =>
- opts.queryKey[1] === "timeline"
- ? Promise.resolve(mockTimeline.current)
- : Promise.reject(new Error(`unexpected key ${String(opts.queryKey)}`)),
- }),
-}));
+vi.mock("@multica/core/modals", async (importOriginal) => {
+ const state = { open: mockOpenModal };
+ return {
+ ...(await importOriginal<typeof import("@multica/core/modals")>()),
+ useModalStore: Object.assign((selector?: (s: typeof state) => unknown) => (selector ? selector(state) : state), {
+ getState: () => state,
+ }),
+ };
+});
// Mock the context module, not the barrel: resolveClickIntent and
// useIntentNavigate stay the REAL implementations and read this adapter
@@ -321,860 +232,818 @@ vi.mock("../navigation/context", () => {
pathname: mockPathname.current,
getShareableUrl: mockGetShareableUrl,
});
- return {
- useNavigation: adapter,
- useOptionalNavigation: adapter,
- };
+ return { useNavigation: adapter, useOptionalNavigation: adapter };
});
vi.mock("@multica/ui/components/common/theme-provider", () => ({
useTheme: () => ({ theme: mockTheme.current, setTheme: mockSetTheme }),
}));
-vi.mock("sonner", () => ({
- toast: { success: mockToastSuccess, error: vi.fn() },
-}));
+vi.mock("sonner", () => ({ toast: mockToast }));
+
+const PLACEHOLDER = "Search, or type what needs doing...";
+const ME = "user-me";
+
+function I18nWrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider locale="en" resources={{ en: RESOURCES.en }}>
+ {children}
+ </I18nProvider>
+ );
+}
+
+// Deliberately NOT a full zh-Hans bundle: only `projects` is translated, so
+// the chrome stays addressable by its English strings while a project row's
+// status has to come through the projects namespace.
+function ChineseI18nWrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider
+ locale="zh-Hans"
+ resources={{ "zh-Hans": { ...RESOURCES.en, projects: zhHansProjects } }}
+ >
+ {children}
+ </I18nProvider>
+ );
+}
+
+const renderSearch = () => render(<SearchCommand />, { wrapper: I18nWrapper });
+const renderSearchInChinese = () => render(<SearchCommand />, { wrapper: ChineseI18nWrapper });
+const input = () => screen.getByPlaceholderText(PLACEHOLDER) as HTMLInputElement;
+
+function seed(options: { queryKey: readonly unknown[] }, data: unknown) {
+ queryData.set(JSON.stringify(options.queryKey), data);
+}
+
+function api(name: string): Mock {
+ return (mockApi as Record<string, Mock>)[name]!;
+}
+
+function makeIssue(over: Partial<Issue> & { id: string }): Issue {
+ return {
+ workspace_id: "ws-test",
+ number: 1,
+ identifier: "MUL-1",
+ title: "Untitled",
+ description: null,
+ status: "todo",
+ priority: "none",
+ assignee_type: null,
+ assignee_id: null,
+ creator_type: "member",
+ creator_id: ME,
+ parent_issue_id: null,
+ project_id: null,
+ position: 0,
+ start_date: null,
+ due_date: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ ...over,
+ } as Issue;
+}
+
+function makeAgent(id: string, name: string, over: Record<string, unknown> = {}) {
+ return {
+ id,
+ workspace_id: "ws-test",
+ name,
+ description: "",
+ avatar_url: null,
+ owner_id: ME,
+ permission_mode: "private",
+ runtime_id: "rt-1",
+ runtime_bound: true,
+ archived_at: null,
+ ...over,
+ };
+}
+
+function makeMember(userId: string, name: string, email: string) {
+ return {
+ id: `member-${userId}`,
+ workspace_id: "ws-test",
+ user_id: userId,
+ role: "member" as const,
+ created_at: "2026-01-01T00:00:00Z",
+ name,
+ email,
+ avatar_url: null,
+ };
+}
+
+const registered: string[] = [];
+function registerContext(context: CommandBarContext) {
+ const token = `test-${registered.length}`;
+ registered.push(token);
+ act(() => useCommandBarContextStore.getState().register(token, context));
+}
+
+/** Rendered cmdk rows, top to bottom, by their value. */
+const renderedValues = () =>
+ Array.from(document.querySelectorAll<HTMLElement>('[cmdk-item=""]')).map(
+ (el) => el.getAttribute("data-value") ?? "",
+ );
+
+/** Group headings, top to bottom. */
+const renderedHeadings = () =>
+ Array.from(document.querySelectorAll<HTMLElement>("[cmdk-group-heading]")).map(
+ (el) => el.textContent ?? "",
+ );
+
+const selectedValue = () =>
+ document.querySelector('[cmdk-item=""][aria-selected="true"]')?.getAttribute("data-value") ?? null;
+
+const rowText = (text: string) =>
+ screen.findByText((_, el) => el?.textContent === text && el?.tagName === "SPAN");
describe("SearchCommand", () => {
beforeEach(() => {
+ queryData.clear();
+ apiFns.clear();
+ apiFns.set("getBaseUrl", vi.fn(() => "http://127.0.0.1:8080"));
+ apiFns.set("searchIssues", vi.fn(() => Promise.resolve({ issues: [], total: 0 })));
+ apiFns.set("searchProjects", vi.fn(() => Promise.resolve({ projects: [], total: 0 })));
mockPush.mockReset();
- mockSearchIssues.mockReset().mockResolvedValue({ issues: [] });
- mockSearchProjects.mockReset().mockResolvedValue({ projects: [] });
- mockRecentItems.current = [];
- mockAllIssues.current = [];
- mockAgents.current = [];
- mockSquads.current = [];
- mockWorkspaces.current = [];
- mockUnreadSummary.current = [];
- mockSetTheme.mockReset();
- mockTheme.current = "system";
mockPathname.current = "/ws-test/issues";
mockGetShareableUrl.mockReset().mockImplementation((p: string) => `https://app.multica/${p}`);
- mockMembers.current = [];
+ mockRecentItems.current = [];
mockOpenModal.mockReset();
- mockToastSuccess.mockReset();
- mockClipboardWrite.mockReset().mockResolvedValue(undefined);
- mockTimeline.current = [];
+ mockToast.mockReset();
+ mockToast.success.mockReset();
+ mockToast.error.mockReset();
+ mockToast.warning.mockReset();
+ mockSetTheme.mockReset();
+ mockTheme.current = "system";
mockCommentCollapseAll.mockReset();
mockCommentExpandAll.mockReset();
mockResolvedCollapseAll.mockReset();
mockResolvedExpandAll.mockReset();
- // cmdk calls scrollIntoView on the first selected item, which jsdom doesn't implement
- Element.prototype.scrollIntoView = vi.fn();
+ seed(memberListOptions("ws-test"), [makeMember(ME, "Me Myself", "[email protected]")]);
+ seed(agentListOptions("ws-test"), []);
+ seed(squadListOptions("ws-test"), []);
act(() => {
+ for (const token of registered.splice(0)) useCommandBarContextStore.getState().unregister(token);
useSearchStore.setState({ open: true });
});
+
+ // cmdk calls scrollIntoView on the first selected item, which jsdom doesn't implement
+ Element.prototype.scrollIntoView = vi.fn();
});
it("closes on a single Escape press from the search input", async () => {
const user = userEvent.setup();
-
renderSearch();
-
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.click(input);
-
- expect(useSearchStore.getState().open).toBe(true);
-
+ await user.click(input());
await user.keyboard("{Escape}");
- await waitFor(() => {
- expect(useSearchStore.getState().open).toBe(false);
- });
- expect(screen.queryByPlaceholderText("Type a command or search...")).not.toBeInTheDocument();
+ await waitFor(() => expect(useSearchStore.getState().open).toBe(false));
+ expect(screen.queryByPlaceholderText(PLACEHOLDER)).not.toBeInTheDocument();
});
- it("shows only New Issue by default and hides Pages / low-frequency commands until query", () => {
+ it("shows only creation shortcuts on an empty query off any object page", () => {
renderSearch();
expect(screen.queryByText("Pages")).not.toBeInTheDocument();
- // Only the primary creation action surfaces on empty query; everything
- // else (theme, copy, New Project) must be revealed by typing.
- expect(screen.getByText("Commands")).toBeInTheDocument();
- expect(
- screen.getByText((_, el) => el?.textContent === "New Issue" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
- expect(screen.queryByText("New Project")).not.toBeInTheDocument();
- expect(screen.queryByText("Switch to Light Theme")).not.toBeInTheDocument();
- expect(screen.queryByText("Switch to Dark Theme")).not.toBeInTheDocument();
- expect(screen.queryByText("Use System Theme")).not.toBeInTheDocument();
+ expect(renderedHeadings()).toEqual(["New"]);
+ expect(renderedValues()).toEqual(["command:new-issue", "command:chat-with-agent"]);
});
- it("filters navigation pages by query", async () => {
- const user = userEvent.setup();
- renderSearch();
+ describe("pages and global commands", () => {
+ it("filters navigation pages by query", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "set");
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "set");
+ expect(await rowText("Settings")).toBeInTheDocument();
+ expect(screen.queryByText("Inbox")).not.toBeInTheDocument();
+ });
- await waitFor(() => {
- // HighlightText splits text, so use a function matcher
- expect(screen.getByText((_, el) => el?.textContent === "Settings" && el?.tagName === "SPAN")).toBeInTheDocument();
+ it("offers every workspace nav page, not a hand-maintained subset", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ // The Pages group is generated from WORKSPACE_PAGES — the registry the
+ // sidebar and the desktop tab bar read (MUL-6272).
+ for (const [key, page] of Object.entries(WORKSPACE_PAGES)) {
+ await user.clear(input());
+ await user.type(input(), enLayout.nav[page.navKey]);
+ await waitFor(() => expect(renderedValues()).toContain(`page:${key}`));
+ }
});
- expect(screen.queryByText("Inbox")).not.toBeInTheDocument();
- });
- it("offers every workspace nav page, not a hand-maintained subset", async () => {
- const user = userEvent.setup();
- renderSearch();
- const input = screen.getByPlaceholderText("Type a command or search...");
-
- // The Pages group is generated from WORKSPACE_PAGES — the same registry
- // the sidebar and the desktop tab bar read — so searching a page by the
- // exact name the sidebar shows must always reach it. The hand-written
- // list this replaced had gone stale by four pages (MUL-6272).
- for (const page of Object.values(WORKSPACE_PAGES)) {
- const label = enLayout.nav[page.navKey];
- await user.clear(input);
- await user.type(input, label);
- expect(
- await screen.findByText(
- (_, el) => el?.textContent === label && el?.tagName === "SPAN",
- ),
- ).toBeInTheDocument();
- }
- });
+ it("does not surface a page on an incidental substring of a hidden keyword", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "s");
- it("does not surface a page on an incidental substring of a hidden keyword", async () => {
- const user = userEvent.setup();
- renderSearch();
+ expect(await rowText("Settings")).toBeInTheDocument();
+ expect(screen.queryByText("Inbox")).not.toBeInTheDocument();
+ });
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "s");
+ it("navigates to a page whose label differs from its route segment", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "analytics");
+ await user.click(await screen.findByText("Analytics"));
- // Inbox carries the hidden keyword "notifications". Matching keywords by
- // substring made a bare "s" pull Inbox into the list with nothing on the
- // row to explain why; keywords match by prefix instead.
- await waitFor(() => {
- expect(
- screen.getByText((_, el) => el?.textContent === "Settings" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/usage");
+ expect(useSearchStore.getState().open).toBe(false);
});
- expect(screen.queryByText("Inbox")).not.toBeInTheDocument();
- });
- it("navigates to a page whose label differs from its route segment", async () => {
- const user = userEvent.setup();
- renderSearch();
+ it("cmd-click on a result opens it in a new tab instead of navigating in place", async () => {
+ const user = userEvent.setup();
+ const open = vi.spyOn(window, "open").mockReturnValue(null);
+ renderSearch();
+ await user.type(input(), "settings");
+ fireEvent.click(await screen.findByText("Settings"), { metaKey: true });
- // Analytics lives at /usage: proof the row resolves its destination from
- // the page key rather than from the words on screen.
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "analytics");
+ expect(open).toHaveBeenCalledWith(
+ "https://app.multica//ws-test/settings",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ expect(mockPush).not.toHaveBeenCalled();
+ expect(useSearchStore.getState().open).toBe(false);
+ open.mockRestore();
+ });
- await user.click(await screen.findByText("Analytics"));
+ it("cmd+Enter opens the highlighted result in a new tab", async () => {
+ const user = userEvent.setup();
+ const open = vi.spyOn(window, "open").mockReturnValue(null);
+ renderSearch();
+ await user.type(input(), "settings");
+ await screen.findByText("Settings");
+ fireEvent.keyDown(input(), { key: "Enter", metaKey: true });
+
+ expect(open).toHaveBeenCalledWith(
+ "https://app.multica//ws-test/settings",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ expect(mockPush).not.toHaveBeenCalled();
+ open.mockRestore();
+ });
- expect(mockPush).toHaveBeenCalledWith("/ws-test/usage");
- expect(useSearchStore.getState().open).toBe(false);
- });
+ it("a plain selection after an abandoned cmd-click does not inherit the stale intent", async () => {
+ const user = userEvent.setup();
+ const open = vi.spyOn(window, "open").mockReturnValue(null);
+ renderSearch();
+ fireEvent.click(input(), { metaKey: true });
+ await user.type(input(), "settings");
+ await user.click(await screen.findByText("Settings"));
- it("navigates to page on selection", async () => {
- const user = userEvent.setup();
- renderSearch();
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/settings");
+ expect(open).not.toHaveBeenCalled();
+ open.mockRestore();
+ });
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "settings");
+ it("opens New issue and New project through the modal store", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "new");
- const settingsItem = await screen.findByText("Settings");
- await user.click(settingsItem);
+ expect(await rowText("New project")).toBeInTheDocument();
+ await user.click(await rowText("New issue"));
- expect(mockPush).toHaveBeenCalledWith("/ws-test/settings");
- expect(useSearchStore.getState().open).toBe(false);
- });
+ expect(mockOpenModal).toHaveBeenCalledWith("quick-create-issue", null);
+ expect(useSearchStore.getState().open).toBe(false);
+ });
- it("cmd-click on a result opens it in a new tab instead of navigating in place", async () => {
- const user = userEvent.setup();
- const open = vi.spyOn(window, "open").mockReturnValue(null);
- renderSearch();
+ it("changes theme through a submenu that marks the current theme", async () => {
+ const user = userEvent.setup();
+ mockTheme.current = "dark";
+ renderSearch();
+ await user.type(input(), "theme");
+ await user.click(await rowText("Change theme..."));
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "settings");
+ expect(within(screen.getByRole("navigation", { name: "Current menu" })).getByText("Change theme")).toBeInTheDocument();
+ expect(renderedValues()).toEqual(["theme:light", "theme:dark", "theme:system"]);
+ expect(screen.getByLabelText("Current theme")).toBeInTheDocument();
- const settingsItem = await screen.findByText("Settings");
- fireEvent.click(settingsItem, { metaKey: true });
+ await user.click(screen.getByText("Light"));
+ expect(mockSetTheme).toHaveBeenCalledWith("light");
+ expect(useSearchStore.getState().open).toBe(false);
+ });
- expect(open).toHaveBeenCalledWith(
- "https://app.multica//ws-test/settings",
- "_blank",
- "noopener,noreferrer",
- );
- expect(mockPush).not.toHaveBeenCalled();
- expect(useSearchStore.getState().open).toBe(false);
- open.mockRestore();
+ it("Backspace on an empty submenu input returns to the root", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "theme");
+ await user.click(await rowText("Change theme..."));
+
+ const pageInput = screen.getByPlaceholderText("Filter...");
+ await user.type(pageInput, "da");
+ expect(renderedValues()).toEqual(["theme:dark"]);
+ await user.keyboard("{Backspace}{Backspace}");
+ // Clearing the filter keeps the submenu; one more Backspace leaves it.
+ expect(screen.getByPlaceholderText("Filter...")).toBeInTheDocument();
+ await user.keyboard("{Backspace}");
+
+ expect(await screen.findByPlaceholderText(PLACEHOLDER)).toBeInTheDocument();
+ expect(screen.queryByRole("navigation", { name: "Current menu" })).not.toBeInTheDocument();
+ });
+
+ it("lets Home/End edit the query caret instead of hijacking result navigation", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "new");
+ await rowText("New project");
+
+ const first = selectedValue();
+ expect(first).not.toBeNull();
+ await user.keyboard("{ArrowDown}");
+ expect(selectedValue()).not.toBe(first);
+ await user.keyboard("{ArrowUp}");
+ expect(selectedValue()).toBe(first);
+
+ await user.keyboard("{Home}");
+ expect(input().selectionStart).toBe(0);
+ expect(selectedValue()).toBe(first);
+ await user.keyboard("{End}");
+ expect(input().selectionStart).toBe(input().value.length);
+ expect(selectedValue()).toBe(first);
+ });
});
- it("cmd+Enter opens the highlighted result in a new tab", async () => {
- const user = userEvent.setup();
- const open = vi.spyOn(window, "open").mockReturnValue(null);
- renderSearch();
+ describe("scope prefixes", () => {
+ it("'>' limits the list to commands", async () => {
+ const user = userEvent.setup();
+ seed(agentListOptions("ws-test"), [makeAgent("agent-newton", "Newton")]);
+ renderSearch();
+ await user.type(input(), ">new");
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "settings");
- await screen.findByText("Settings");
- fireEvent.keyDown(input, { key: "Enter", metaKey: true });
-
- expect(open).toHaveBeenCalledWith(
- "https://app.multica//ws-test/settings",
- "_blank",
- "noopener,noreferrer",
- );
- expect(mockPush).not.toHaveBeenCalled();
- open.mockRestore();
- });
+ await rowText("New project");
+ expect(renderedValues().every((v) => v.startsWith("command:"))).toBe(true);
+ expect(api("searchIssues")).not.toHaveBeenCalled();
+ });
- it("a plain selection after an abandoned cmd-click does not inherit the stale intent", async () => {
- const user = userEvent.setup();
- const open = vi.spyOn(window, "open").mockReturnValue(null);
- renderSearch();
+ it("'@' limits the list to people and agents", async () => {
+ const user = userEvent.setup();
+ seed(agentListOptions("ws-test"), [makeAgent("agent-lambda", "Lambda")]);
+ renderSearch();
+ await user.type(input(), "@lam");
- const input = screen.getByPlaceholderText("Type a command or search...");
- // cmd-click somewhere that selects nothing…
- fireEvent.click(input, { metaKey: true });
- await user.type(input, "settings");
+ await waitFor(() => expect(renderedValues()).toEqual(["agent:agent-lambda"]));
+ expect(api("searchIssues")).not.toHaveBeenCalled();
+ });
- const settingsItem = await screen.findByText("Settings");
- // …then a plain click must navigate in place, not open a tab.
- await user.click(settingsItem);
+ it("'#' searches issues only", async () => {
+ const user = userEvent.setup();
+ api("searchIssues").mockResolvedValue({
+ issues: [makeIssue({ id: "issue-settings", identifier: "MUL-5", title: "settings crash" })],
+ total: 1,
+ });
+ renderSearch();
+ await user.type(input(), "#settings");
- expect(mockPush).toHaveBeenCalledWith("/ws-test/settings");
- expect(open).not.toHaveBeenCalled();
- open.mockRestore();
+ await waitFor(() => expect(renderedValues()).toEqual(["issue-settings"]), { timeout: 2000 });
+ expect(api("searchProjects")).not.toHaveBeenCalled();
+ });
});
- it("lists workspace members and navigates to the member page on selection", async () => {
- const user = userEvent.setup();
- mockMembers.current = [
- {
- id: "member-1",
- workspace_id: "ws-test",
- user_id: "user-1",
- role: "member",
- created_at: "2026-01-01T00:00:00Z",
- name: "Alice Zhang",
- email: "[email protected]",
- avatar_url: null,
- },
- {
- id: "member-2",
- workspace_id: "ws-test",
- user_id: "user-2",
- role: "admin",
- created_at: "2026-01-01T00:00:00Z",
- name: "Bob Liu",
- email: "[email protected]",
- avatar_url: null,
- },
- ];
- renderSearch();
+ describe("search results", () => {
+ it("ranks an agent typed by name as the best match with its actions", async () => {
+ const user = userEvent.setup();
+ seed(agentListOptions("ws-test"), [
+ makeAgent("agent-alpha", "Alpha Lambda Helper"),
+ makeAgent("agent-lambda", "Lambda"),
+ ]);
+ renderSearch();
+ await user.type(input(), "lambda");
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "alice");
+ await waitFor(() => expect(renderedValues()[0]).toBe("best:agent:agent-lambda"));
+ expect(renderedHeadings().slice(0, 2)).toEqual(["Best match", "Actions"]);
+ expect(renderedValues()).toContain("best-action:chat");
+ });
+
+ it("lists workspace members and navigates to the member page", async () => {
+ const user = userEvent.setup();
+ seed(memberListOptions("ws-test"), [
+ makeMember(ME, "Me Myself", "[email protected]"),
+ makeMember("user-1", "Alice Zhang", "[email protected]"),
+ makeMember("user-2", "Bob Liu", "[email protected]"),
+ ]);
+ renderSearch();
+ await user.type(input(), "alice");
- await waitFor(() => {
- expect(screen.getByText("Members")).toBeInTheDocument();
+ await waitFor(() => expect(renderedValues()[0]).toBe("best:member:user-1"));
+ expect(screen.queryByText("Bob Liu")).not.toBeInTheDocument();
+ fireEvent.keyDown(input(), { key: "Enter" });
+
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/members/user-1");
+ });
+
+ it("renders recent issues joined from the query cache with type labels", () => {
+ mockRecentItems.current = [
+ { id: "issue-1", visitedAt: 1000 },
+ { id: "deleted-issue", visitedAt: 950 },
+ { id: "issue-2", visitedAt: 900 },
+ ];
+ seed(issueDetailOptions("ws-test", "issue-1"), makeIssue({ id: "issue-1", identifier: "MUL-1", title: "First issue" }));
+ seed(
+ issueDetailOptions("ws-test", "issue-2"),
+ makeIssue({ id: "issue-2", identifier: "MUL-2", title: "Second issue", status: "done" }),
+ );
+ renderSearch();
+
+ expect(screen.getByText("Recent")).toBeInTheDocument();
+ expect(screen.getByText("First issue")).toBeInTheDocument();
+ expect(screen.getByText("Second issue")).toBeInTheDocument();
+ expect(screen.getAllByText("Issue")).toHaveLength(2);
+ expect(screen.queryByText("deleted-issue")).not.toBeInTheDocument();
+ });
+
+ it("renders description and comment snippets regardless of match_source", async () => {
+ const user = userEvent.setup();
+ api("searchIssues").mockResolvedValue({
+ issues: [
+ {
+ ...makeIssue({ id: "issue-snippet", identifier: "MUL-99", title: "HTML rendering pipeline" }),
+ match_source: "title",
+ matched_description_snippet: "...uses HTML templates for rendering...",
+ matched_comment_snippet: "...we should migrate away from HTML...",
+ },
+ ],
+ total: 1,
+ });
+ renderSearch();
+ await user.type(input(), "html");
+
+ await waitFor(() => expect(renderedValues()).toContain("issue-snippet"), { timeout: 2000 });
expect(
- screen.getByText((_, el) => el?.textContent === "Alice Zhang" && el?.tagName === "DIV"),
+ screen.getByText((_, el) => !!el?.textContent?.includes("uses HTML templates") && el?.tagName === "SPAN"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText((_, el) => !!el?.textContent?.includes("migrate away from HTML") && el?.tagName === "SPAN"),
).toBeInTheDocument();
});
- expect(
- screen.getByText((_, el) => el?.textContent === "[email protected]" && el?.tagName === "DIV"),
- ).toBeInTheDocument();
- expect(screen.queryByText("Bob Liu")).not.toBeInTheDocument();
-
- const aliceItem = await screen.findByText(
- (_, el) => el?.textContent === "Alice Zhang" && el?.tagName === "DIV",
- );
- await user.click(aliceItem);
-
- expect(mockPush).toHaveBeenCalledWith("/ws-test/members/user-1");
- expect(useSearchStore.getState().open).toBe(false);
});
- describe("workspace switching", () => {
- // Server order is created_at ascending, which is also the sidebar
- // switcher's order. "Zeta Labs" is the oldest, so an alphabetical re-sort
- // would put it last. The current workspace ("ws-test") has "workspace" in
- // its name, so the bare keyword would match it if it weren't excluded.
- beforeEach(() => {
- mockWorkspaces.current = [
- {
- id: "ws-zeta",
- name: "Zeta Labs",
- slug: "zeta",
- avatar_url: null,
- created_at: "2025-01-01T00:00:00Z",
- },
- {
- id: "ws-test",
- name: "Test Workspace",
- slug: "ws-test",
- avatar_url: null,
- created_at: "2025-06-01T00:00:00Z",
- },
- {
- id: "ws-acme",
- name: "Acme Corp",
- slug: "acme-hq",
- avatar_url: null,
- created_at: "2026-01-01T00:00:00Z",
- },
- ];
- mockUnreadSummary.current = [
+ describe("workspace switching", () => {
+ beforeEach(() => {
+ seed(workspaceListOptions(), [
+ { id: "ws-zeta", name: "Zeta Labs", slug: "zeta", avatar_url: null, created_at: "2025-01-01T00:00:00Z" },
+ { id: "ws-test", name: "Test Workspace", slug: "ws-test", avatar_url: null, created_at: "2025-06-01T00:00:00Z" },
+ { id: "ws-acme", name: "Acme Corp", slug: "acme-hq", avatar_url: null, created_at: "2026-01-01T00:00:00Z" },
+ ]);
+ seed(inboxUnreadSummaryOptions(), [
{ workspace_id: "ws-acme", count: 2 },
{ workspace_id: "ws-test", count: 5 },
- ];
+ ]);
});
const workspaceRows = () =>
- within(screen.getByRole("group", { name: "Workspaces" })).getAllByRole(
- "option",
- );
+ within(screen.getByRole("group", { name: "Workspaces" })).getAllByRole("option");
it("hides the Workspaces group on an empty query", () => {
renderSearch();
-
expect(screen.queryByText("Workspaces")).not.toBeInTheDocument();
});
- it("matches a workspace by name and switches to it by slug on Enter", async () => {
- const user = userEvent.setup();
- renderSearch();
- const input = screen.getByPlaceholderText("Type a command or search...");
-
- await user.type(input, "me co");
- await waitFor(() => {
- expect(workspaceRows().map((row) => row.textContent)).toEqual([
- expect.stringContaining("Acme Corp"),
- ]);
- });
-
- await user.clear(input);
- await user.type(input, "acme-hq");
- await waitFor(() => expect(workspaceRows()).toHaveLength(1));
- fireEvent.keyDown(input, { key: "Enter" });
-
- expect(mockPush).toHaveBeenCalledWith("/acme-hq/issues");
- expect(useSearchStore.getState().open).toBe(false);
- });
-
it('lists every other workspace for "workspace", oldest first, with unread dots', async () => {
const user = userEvent.setup();
renderSearch();
+ await user.type(input(), "workspace");
- await user.type(
- screen.getByPlaceholderText("Type a command or search..."),
- "workspace",
- );
-
- await waitFor(() => {
+ await waitFor(() =>
expect(workspaceRows().map((row) => row.textContent)).toEqual([
expect.stringContaining("Zeta Labs"),
expect.stringContaining("Acme Corp"),
- ]);
- });
+ ]),
+ );
const [zeta, acme] = workspaceRows();
expect(within(zeta!).queryByTestId("workspace-unread-dot")).toBeNull();
expect(within(acme!).getByTestId("workspace-unread-dot")).toBeInTheDocument();
});
- });
-
- it("renders recent issues from query cache joined with store visit records", () => {
- mockRecentItems.current = [
- { id: "issue-1", visitedAt: 1000 },
- { id: "issue-2", visitedAt: 900 },
- ];
- mockAllIssues.current = [
- { id: "issue-1", identifier: "MUL-1", title: "First issue", status: "todo" },
- { id: "issue-2", identifier: "MUL-2", title: "Second issue", status: "done" },
- ];
-
- renderSearch();
-
- expect(screen.getByText("Recent")).toBeInTheDocument();
- expect(screen.getByText("First issue")).toBeInTheDocument();
- expect(screen.getByText("MUL-1")).toBeInTheDocument();
- expect(screen.getByText("Second issue")).toBeInTheDocument();
- expect(screen.getByText("MUL-2")).toBeInTheDocument();
- });
-
- it("shows New Issue / New Project under Commands and triggers the modal store", async () => {
- const user = userEvent.setup();
- renderSearch();
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "new");
+ it("switches to a workspace by slug", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "acme");
+ fireEvent.click(await rowText("Acme Corp"));
- await waitFor(() => {
- expect(screen.getByText("Commands")).toBeInTheDocument();
- expect(
- screen.getByText((_, el) => el?.textContent === "New Issue" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
- expect(
- screen.getByText((_, el) => el?.textContent === "New Project" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
+ expect(mockPush).toHaveBeenCalledWith("/acme-hq/issues");
});
-
- const newIssue = await screen.findByText(
- (_, el) => el?.textContent === "New Issue" && el?.tagName === "SPAN",
- );
- await user.click(newIssue);
-
- expect(mockOpenModal).toHaveBeenCalledWith("quick-create-issue", null);
- expect(useSearchStore.getState().open).toBe(false);
});
- it("hides copy-link commands when not on an issue detail route", async () => {
- const user = userEvent.setup();
- mockPathname.current = "/ws-test/projects";
- renderSearch();
-
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "copy");
+ describe("current issue", () => {
+ const issue = makeIssue({ id: "issue-1", identifier: "MUL-42", title: "Safari login loop" });
- // Commands section may still be empty / absent.
- expect(screen.queryByText("Copy Issue Link")).not.toBeInTheDocument();
- });
-
- it("copies issue link and identifier when on an issue detail route", async () => {
- const user = userEvent.setup();
- // userEvent.setup() installs its own navigator.clipboard; spy on it so we
- // intercept the writeText call without clobbering userEvent's internals.
- const writeSpy = vi
- .spyOn(navigator.clipboard, "writeText")
- .mockImplementation(mockClipboardWrite);
- mockPathname.current = "/ws-test/issues/issue-1";
- mockAllIssues.current = [
- { id: "issue-1", identifier: "MUL-42", title: "Demo", status: "todo" },
- ];
- renderSearch();
+ beforeEach(() => {
+ seed(issueDetailOptions("ws-test", "issue-1"), issue);
+ registerContext({ kind: "issue", issue });
+ });
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "copy");
+ it("leads the empty state with the issue's commands under its own heading", () => {
+ renderSearch();
- const linkItem = await screen.findByText(
- (_, el) => el?.textContent === "Copy Issue Link" && el?.tagName === "SPAN",
- );
- await user.click(linkItem);
+ expect(renderedHeadings()[0]).toContain("Current issue");
+ expect(renderedHeadings()[0]).toContain("MUL-42");
+ expect(renderedValues().slice(0, 4)).toEqual([
+ "command:context-issue:issue-status",
+ "command:context-issue:issue-assignee",
+ "command:context-issue:issue-priority",
+ "command:context-issue:issue-copy-link",
+ ]);
+ // The input stays a global search: no context chip inside it.
+ expect(input().value).toBe("");
+ });
- expect(mockGetShareableUrl).toHaveBeenCalledWith("/ws-test/issues/issue-1");
- expect(mockClipboardWrite).toHaveBeenCalledWith("https://app.multica//ws-test/issues/issue-1");
- expect(mockToastSuccess).toHaveBeenCalledWith("Link copied");
+ it("opens a submenu from its row, with the issue in the breadcrumb", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.click(await rowText("Change status..."));
- // Reopen palette and test identifier copy
- act(() => {
- useSearchStore.setState({ open: true });
+ expect(screen.getByRole("navigation", { name: "Current menu" })).toHaveTextContent("MUL-42Change status");
+ expect(renderedValues().length).toBeGreaterThan(0);
+ expect(renderedValues().every((v) => v.startsWith("status:"))).toBe(true);
});
- const input2 = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input2, "copy");
- const idItem = await screen.findByText(
- (_, el) =>
- el?.textContent === "Copy Identifier (MUL-42)" && el?.tagName === "SPAN",
- );
- await user.click(idItem);
- expect(mockClipboardWrite).toHaveBeenCalledWith("MUL-42");
- expect(mockToastSuccess).toHaveBeenCalledWith("Copied MUL-42");
-
- writeSpy.mockRestore();
- });
- it("hides fold/unfold-all-comments commands off issue detail routes", async () => {
- const user = userEvent.setup();
- mockPathname.current = "/ws-test/projects";
- renderSearch();
+ it("ranks the issue's command first when its name is typed", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "status");
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "fold");
+ await waitFor(() => expect(renderedValues()[0]).toBe("command:context-issue:issue-status"));
+ fireEvent.keyDown(input(), { key: "Enter" });
+ expect(screen.getByRole("navigation", { name: "Current menu" })).toHaveTextContent("MUL-42Change status");
+ });
- expect(screen.queryByText("Fold All Comments")).not.toBeInTheDocument();
- expect(screen.queryByText("Unfold All Comments")).not.toBeInTheDocument();
- });
+ it.each(["s", "a", "p"])("types '%s' into the search instead of opening a submenu", async (key) => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), key);
- it("folds all comments on the current issue, including expanded resolved threads", async () => {
- const user = userEvent.setup();
- mockPathname.current = "/ws-test/issues/issue-1";
- mockAllIssues.current = [
- { id: "issue-1", identifier: "MUL-42", title: "Demo", status: "todo" },
- ];
- mockTimeline.current = [
- { type: "activity", id: "act-1", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T00:00:00Z", action: "status_changed" },
- { type: "comment", id: "root-1", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T01:00:00Z", parent_id: null },
- { type: "comment", id: "reply-1", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T02:00:00Z", parent_id: "root-1" },
- { type: "comment", id: "root-2", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T03:00:00Z", parent_id: null, resolved_at: "2026-01-02T00:00:00Z" },
- ];
- renderSearch();
+ expect(input().value).toBe(key);
+ expect(screen.queryByRole("navigation", { name: "Current menu" })).not.toBeInTheDocument();
+ });
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "fold");
+ it("searches a person whose name starts with A instead of assigning", async () => {
+ const user = userEvent.setup();
+ seed(memberListOptions("ws-test"), [
+ makeMember(ME, "Me Myself", "[email protected]"),
+ makeMember("user-1", "Alice Zhang", "[email protected]"),
+ ]);
+ renderSearch();
+ await user.type(input(), "alice");
- const foldItem = await screen.findByText(
- (_, el) => el?.textContent === "Fold All Comments" && el?.tagName === "SPAN",
- );
- await user.click(foldItem);
+ await waitFor(() => expect(renderedValues()[0]).toBe("best:member:user-1"));
+ fireEvent.keyDown(input(), { key: "Enter" });
- await waitFor(() => {
- // Root comments only — replies fold with their thread, activities are not comments.
- expect(mockCommentCollapseAll).toHaveBeenCalledWith("issue-1", ["root-1", "root-2"]);
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/members/user-1");
+ expect(api("updateIssue")).not.toHaveBeenCalled();
+ expect(mockOpenModal).not.toHaveBeenCalled();
});
- expect(mockResolvedCollapseAll).toHaveBeenCalledWith("issue-1");
- expect(mockCommentExpandAll).not.toHaveBeenCalled();
- expect(useSearchStore.getState().open).toBe(false);
- });
-
- it("folds comments under the issue UUID when the URL carries the identifier", async () => {
- const user = userEvent.setup();
- mockPathname.current = "/ws-test/issues/MUL-42";
- mockAllIssues.current = [
- { id: "issue-1", identifier: "MUL-42", title: "Demo", status: "todo" },
- ];
- mockTimeline.current = [
- { type: "comment", id: "root-1", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T01:00:00Z", parent_id: null },
- ];
- renderSearch();
-
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "fold");
- const foldItem = await screen.findByText(
- (_, el) => el?.textContent === "Fold All Comments" && el?.tagName === "SPAN",
- );
- await user.click(foldItem);
+ it("writes a priority picked in the submenu to the issue", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.click(await rowText("Set priority..."));
+ await user.click(screen.getByText("High"));
- await waitFor(() => {
- expect(mockCommentCollapseAll).toHaveBeenCalledWith("issue-1", ["root-1"]);
+ await waitFor(() => expect(api("updateIssue")).toHaveBeenCalledWith("issue-1", { priority: "high" }));
+ expect(useSearchStore.getState().open).toBe(false);
});
- expect(mockResolvedCollapseAll).toHaveBeenCalledWith("issue-1");
- });
-
- it("unfolds all comments and expands resolved threads", async () => {
- const user = userEvent.setup();
- mockPathname.current = "/ws-test/issues/issue-1";
- mockAllIssues.current = [
- { id: "issue-1", identifier: "MUL-42", title: "Demo", status: "todo" },
- ];
- mockTimeline.current = [
- { type: "comment", id: "root-1", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T01:00:00Z", parent_id: null },
- { type: "comment", id: "root-2", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T03:00:00Z", parent_id: null, resolved_at: "2026-01-02T00:00:00Z" },
- // root-3 is reply-resolved: the resolution lives on the reply.
- { type: "comment", id: "root-3", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T04:00:00Z", parent_id: null },
- { type: "comment", id: "reply-3", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T05:00:00Z", parent_id: "root-3", resolved_at: "2026-01-02T01:00:00Z" },
- ];
- renderSearch();
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "unfold");
+ it("copies the issue link and identifier", async () => {
+ const user = userEvent.setup();
+ const writeSpy = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
+ renderSearch();
+ await user.type(input(), "copy");
+ await user.click(await rowText("Copy issue link"));
- const unfoldItem = await screen.findByText(
- (_, el) => el?.textContent === "Unfold All Comments" && el?.tagName === "SPAN",
- );
- await user.click(unfoldItem);
+ await waitFor(() => expect(writeSpy).toHaveBeenCalledWith("https://app.multica//ws-test/issues/MUL-42"));
- await waitFor(() => {
- expect(mockCommentExpandAll).toHaveBeenCalledWith("issue-1");
+ act(() => useSearchStore.setState({ open: true }));
+ await user.type(input(), "copy");
+ await user.click(await rowText("Copy identifier (MUL-42)"));
+ await waitFor(() => expect(writeSpy).toHaveBeenCalledWith("MUL-42"));
+ expect(mockToast.success).toHaveBeenCalledWith("Copied MUL-42");
+ writeSpy.mockRestore();
});
- // Only threads carrying a resolution get seeded into the expand set.
- expect(mockResolvedExpandAll).toHaveBeenCalledWith("issue-1", ["root-2", "root-3"]);
- expect(mockCommentCollapseAll).not.toHaveBeenCalled();
- expect(useSearchStore.getState().open).toBe(false);
- });
- it("filters theme commands by query keywords", async () => {
- const user = userEvent.setup();
- renderSearch();
-
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "dark");
+ it("folds all comments, including expanded resolved threads", async () => {
+ const user = userEvent.setup();
+ seed(issueTimelineOptions("issue-1"), [
+ { type: "activity", id: "act-1", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T00:00:00Z", action: "status_changed" },
+ { type: "comment", id: "root-1", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T01:00:00Z", parent_id: null },
+ { type: "comment", id: "reply-1", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T02:00:00Z", parent_id: "root-1" },
+ { type: "comment", id: "root-2", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T03:00:00Z", parent_id: null, resolved_at: "2026-01-02T00:00:00Z" },
+ ]);
+ renderSearch();
+ await user.type(input(), "fold");
+ await user.click(await rowText("Fold all comments"));
- await waitFor(() => {
- expect(screen.getByText("Commands")).toBeInTheDocument();
- expect(
- screen.getByText((_, el) => el?.textContent === "Switch to Dark Theme" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
+ await waitFor(() => expect(mockCommentCollapseAll).toHaveBeenCalledWith("issue-1", ["root-1", "root-2"]));
+ expect(mockResolvedCollapseAll).toHaveBeenCalledWith("issue-1");
+ expect(mockCommentExpandAll).not.toHaveBeenCalled();
});
- expect(screen.queryByText("Switch to Light Theme")).not.toBeInTheDocument();
- expect(screen.queryByText("Use System Theme")).not.toBeInTheDocument();
- });
- it("applies the selected theme and closes the palette", async () => {
- const user = userEvent.setup();
- mockTheme.current = "light";
- renderSearch();
-
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "dark");
+ it("unfolds all comments and expands resolved threads", async () => {
+ const user = userEvent.setup();
+ seed(issueTimelineOptions("issue-1"), [
+ { type: "comment", id: "root-1", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T01:00:00Z", parent_id: null },
+ { type: "comment", id: "root-2", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T03:00:00Z", parent_id: null, resolved_at: "2026-01-02T00:00:00Z" },
+ { type: "comment", id: "root-3", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T04:00:00Z", parent_id: null },
+ { type: "comment", id: "reply-3", actor_type: "member", actor_id: "u1", created_at: "2026-01-01T05:00:00Z", parent_id: "root-3", resolved_at: "2026-01-02T01:00:00Z" },
+ ]);
+ renderSearch();
+ await user.type(input(), "unfold");
+ await user.click(await rowText("Unfold all comments"));
- const darkItem = await screen.findByText(
- (_, el) => el?.textContent === "Switch to Dark Theme" && el?.tagName === "SPAN",
- );
- await user.click(darkItem);
+ await waitFor(() => expect(mockCommentExpandAll).toHaveBeenCalledWith("issue-1"));
+ expect(mockResolvedExpandAll).toHaveBeenCalledWith("issue-1", ["root-2", "root-3"]);
+ expect(mockCommentCollapseAll).not.toHaveBeenCalled();
+ });
- expect(mockSetTheme).toHaveBeenCalledWith("dark");
- expect(useSearchStore.getState().open).toBe(false);
- });
+ it("offers assigning the open issue to a best-matched agent", async () => {
+ const user = userEvent.setup();
+ seed(agentListOptions("ws-test"), [makeAgent("agent-lambda", "Lambda")]);
+ renderSearch();
+ await user.type(input(), "lambda");
- it("matches theme action via generic 'theme' keyword and marks current theme", async () => {
- const user = userEvent.setup();
- mockTheme.current = "dark";
- renderSearch();
+ await user.click(await rowText("Assign MUL-42 to Lambda"));
+ // Handing a live issue to an agent goes through the run-confirm gate.
+ expect(mockOpenModal).toHaveBeenCalledWith(
+ "issue-run-confirm",
+ expect.objectContaining({ issueIds: ["issue-1"], assigneeType: "agent", assigneeId: "agent-lambda" }),
+ );
+ });
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "theme");
+ it("hides issue commands once the page unregisters", () => {
+ act(() => {
+ for (const token of registered.splice(0)) useCommandBarContextStore.getState().unregister(token);
+ });
+ renderSearch();
- await waitFor(() => {
- expect(
- screen.getByText((_, el) => el?.textContent === "Switch to Light Theme" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
- expect(
- screen.getByText((_, el) => el?.textContent === "Switch to Dark Theme" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
- expect(
- screen.getByText((_, el) => el?.textContent === "Use System Theme" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
+ expect(renderedValues()).not.toContain("command:context-issue:issue-status");
});
- expect(screen.getByLabelText("Current theme")).toBeInTheDocument();
});
- it("filters out recent items not present in query cache", () => {
- mockRecentItems.current = [
- { id: "issue-1", visitedAt: 1000 },
- { id: "deleted-issue", visitedAt: 900 },
- ];
- mockAllIssues.current = [
- { id: "issue-1", identifier: "MUL-1", title: "Existing issue", status: "in_progress" },
+ describe("selected issues", () => {
+ const issues = [
+ makeIssue({ id: "issue-a", identifier: "MUL-1", status: "todo" }),
+ makeIssue({ id: "issue-b", identifier: "MUL-2", status: "in_progress" }),
+ makeIssue({ id: "issue-c", identifier: "MUL-3", status: "todo" }),
];
- renderSearch();
-
- expect(screen.getByText("Recent")).toBeInTheDocument();
- expect(screen.getByText("Existing issue")).toBeInTheDocument();
- expect(screen.queryByText("deleted-issue")).not.toBeInTheDocument();
- });
-
- it("shows the assignee avatar instead of status text for issue search results", async () => {
- const user = userEvent.setup();
- mockMembers.current = [
- {
- id: "member-1",
- workspace_id: "ws-test",
- user_id: "user-1",
- role: "member",
- created_at: "2026-01-01T00:00:00Z",
- name: "Alice Zhang",
- email: "[email protected]",
- avatar_url: null,
- },
- ];
- mockSearchIssues.mockResolvedValue({
- issues: [
- {
- id: "issue-assigned",
- workspace_id: "ws-test",
- number: 101,
- identifier: "MUL-101",
- title: "Assigned search result",
- description: null,
- status: "in_review",
- priority: "none",
- assignee_type: "member",
- assignee_id: "user-1",
- creator_type: "member",
- creator_id: "user-1",
- parent_issue_id: null,
- project_id: null,
- position: 0,
- start_date: null,
- due_date: null,
- created_at: "2026-01-01T00:00:00Z",
- updated_at: "2026-01-01T00:00:00Z",
- match_source: "title",
- },
- ],
- total: 1,
+ beforeEach(() => {
+ registerContext({ kind: "issues", issues, clearSelection: vi.fn() });
});
- renderSearch();
+ it("applies a priority to every selected issue in one batch write", async () => {
+ const user = userEvent.setup();
+ api("batchUpdateIssues").mockResolvedValue({ updated: 3 });
+ renderSearch();
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "assigned");
-
- await waitFor(
- () => {
- expect(
- screen.getByText((_, el) =>
- el?.textContent === "Assigned search result" &&
- el?.tagName === "SPAN",
- ),
- ).toBeInTheDocument();
- },
- { timeout: 2000 },
- );
+ expect(renderedHeadings()[0]).toBe("3 selected issues");
+ await user.click(await rowText("Set priority..."));
+ expect(screen.getByRole("navigation", { name: "Current menu" })).toHaveTextContent(
+ "3 selected issuesSet priority",
+ );
+ await user.click(screen.getByText("Urgent"));
+
+ await waitFor(() =>
+ expect(api("batchUpdateIssues")).toHaveBeenCalledWith(["issue-a", "issue-b", "issue-c"], { priority: "urgent" }),
+ );
+ expect(api("updateIssue")).not.toHaveBeenCalled();
+ });
- expect(screen.getByTitle("Alice Zhang")).toBeInTheDocument();
- expect(screen.queryByText("In Review")).not.toBeInTheDocument();
+ it("previews the run fan-out before assigning the selection to an agent", async () => {
+ const user = userEvent.setup();
+ seed(agentListOptions("ws-test"), [makeAgent("agent-lambda", "Lambda")]);
+ renderSearch();
+ await user.click(await rowText("Assign to..."));
+ await user.click(await screen.findByText((_, el) => el?.textContent === "Lambda" && el?.tagName === "SPAN"));
+
+ expect(mockOpenModal).toHaveBeenCalledWith("issue-run-confirm", {
+ issueIds: ["issue-a", "issue-b", "issue-c"],
+ mode: "assign",
+ assigneeType: "agent",
+ assigneeId: "agent-lambda",
+ });
+ expect(api("batchUpdateIssues")).not.toHaveBeenCalled();
+ });
});
- it("shows the assignee avatar instead of status text for recent issues", () => {
- mockRecentItems.current = [{ id: "issue-1", visitedAt: 1000 }];
- mockAgents.current = [{ id: "agent-1", name: "Niko", avatar_url: null }];
- mockAllIssues.current = [
- {
- id: "issue-1",
- identifier: "MUL-1",
- title: "Recent assigned issue",
- status: "done",
- assignee_type: "agent",
- assignee_id: "agent-1",
- },
+ describe("previewed issue inside a selection", () => {
+ const issues = [
+ makeIssue({ id: "issue-a", identifier: "MUL-1" }),
+ makeIssue({ id: "issue-b", identifier: "MUL-2" }),
+ makeIssue({ id: "issue-c", identifier: "MUL-3" }),
];
- renderSearch();
+ beforeEach(() => {
+ registerContext({ kind: "issues", issues, clearSelection: vi.fn() });
+ // The preview opens after the selection, so its group renders first.
+ registerContext({ kind: "issue", issue: issues[0]! });
+ });
- expect(screen.getByText("Recent assigned issue")).toBeInTheDocument();
- expect(screen.getByTitle("Niko")).toBeInTheDocument();
- expect(screen.queryByText("Done")).not.toBeInTheDocument();
- });
+ it("runs the selection's command when its row is highlighted, not the issue's", async () => {
+ api("batchUpdateIssues").mockResolvedValue({ updated: 3 });
+ renderSearch();
- it("renders description and comment snippets regardless of match_source", async () => {
- const user = userEvent.setup();
- mockSearchIssues.mockResolvedValue({
- issues: [
- {
- id: "issue-snippet",
- workspace_id: "ws-test",
- number: 99,
- identifier: "MUL-99",
- title: "HTML rendering pipeline",
- description: null,
- status: "todo",
- priority: "none",
- assignee_type: null,
- assignee_id: null,
- creator_type: "member",
- creator_id: "user-1",
- parent_issue_id: null,
- project_id: null,
- position: 0,
- start_date: null,
- due_date: null,
- created_at: "2026-01-01T00:00:00Z",
- updated_at: "2026-01-01T00:00:00Z",
- match_source: "title",
- matched_description_snippet: "...uses HTML templates for rendering...",
- matched_comment_snippet: "...we should migrate away from HTML...",
- },
- ],
- total: 1,
+ const values = renderedValues();
+ expect(new Set(values).size).toBe(values.length);
+ expect(renderedHeadings().slice(0, 2)).toEqual([
+ expect.stringContaining("Current issue"),
+ "3 selected issues",
+ ]);
+
+ const selectionRow = document.querySelector<HTMLElement>(
+ '[cmdk-item=""][data-value="command:context-issues:issue-priority"]',
+ )!;
+ fireEvent.pointerMove(selectionRow);
+ expect(selectedValue()).toBe("command:context-issues:issue-priority");
+ fireEvent.keyDown(input(), { key: "Enter" });
+
+ expect(screen.getByRole("navigation", { name: "Current menu" })).toHaveTextContent(
+ "3 selected issuesSet priority",
+ );
+ fireEvent.click(screen.getByText("Urgent"));
+ await waitFor(() =>
+ expect(api("batchUpdateIssues")).toHaveBeenCalledWith(["issue-a", "issue-b", "issue-c"], { priority: "urgent" }),
+ );
+ expect(api("updateIssue")).not.toHaveBeenCalled();
});
- renderSearch();
+ });
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "html");
+ describe("hand to agent", () => {
+ beforeEach(() => {
+ seed(agentListOptions("ws-test"), [
+ makeAgent("agent-lambda", "Lambda"),
+ makeAgent("agent-sigma", "Sigma"),
+ ]);
+ api("quickCreateIssue").mockResolvedValue({ task_id: "task-1" });
+ });
- await waitFor(
- () => {
- expect(screen.getByText((_, el) => el?.textContent === "HTML rendering pipeline" && el?.tagName === "SPAN")).toBeInTheDocument();
- },
- { timeout: 2000 },
- );
-
- // Description snippet should render even though match_source is "title"
- expect(
- screen.getByText((_, el) =>
- (el?.textContent?.includes("uses HTML templates for rendering") ?? false) &&
- el?.tagName === "SPAN",
- ),
- ).toBeInTheDocument();
-
- // Comment snippet should render even though match_source is "title"
- expect(
- screen.getByText((_, el) =>
- (el?.textContent?.includes("we should migrate away from HTML") ?? false) &&
- el?.tagName === "SPAN",
- ),
- ).toBeInTheDocument();
- });
+ it("turns an instruction naming an agent into a quick-create for it", async () => {
+ const user = userEvent.setup();
+ const prompt = "让 Lambda 修一下 Safari 登录回调的 500";
+ renderSearch();
+ await user.type(input(), prompt);
+
+ await waitFor(() => expect(renderedValues()[0]).toBe("delegate:submit"));
+ expect(await rowText("New issue and assign to Lambda")).toBeInTheDocument();
+ fireEvent.keyDown(input(), { key: "Enter" });
+
+ await waitFor(() =>
+ expect(api("quickCreateIssue")).toHaveBeenCalledWith({
+ agent_id: "agent-lambda",
+ prompt,
+ project_id: undefined,
+ parent_issue_id: undefined,
+ }),
+ );
+ expect(mockToast.success).toHaveBeenCalled();
+ expect(useSearchStore.getState().open).toBe(false);
+ });
- it("lets Home/End edit the query caret instead of hijacking result navigation", async () => {
- const user = userEvent.setup();
- renderSearch();
+ it("attaches the open issue as parent", async () => {
+ const user = userEvent.setup();
+ const parent = makeIssue({ id: "issue-9", identifier: "MUL-9" });
+ registerContext({ kind: "issue", issue: parent });
+ renderSearch();
+ await user.type(input(), "ask Sigma to write the release notes");
- const input = screen.getByPlaceholderText(
- "Type a command or search...",
- ) as HTMLInputElement;
- await user.type(input, "new");
+ await waitFor(() => expect(renderedValues()[0]).toBe("delegate:submit"));
+ expect(screen.getByText("Under MUL-9")).toBeInTheDocument();
+ fireEvent.keyDown(input(), { key: "Enter" });
- // "new" surfaces New Issue + New Project, so cmdk has a multi-item list.
- await waitFor(() => {
- expect(
- screen.getByText((_, el) => el?.textContent === "New Issue" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
- expect(
- screen.getByText((_, el) => el?.textContent === "New Project" && el?.tagName === "SPAN"),
- ).toBeInTheDocument();
+ await waitFor(() =>
+ expect(api("quickCreateIssue")).toHaveBeenCalledWith(
+ expect.objectContaining({ agent_id: "agent-sigma", parent_issue_id: "issue-9" }),
+ ),
+ );
});
- const selectedValue = () =>
- document
- .querySelector('[cmdk-item=""][aria-selected="true"]')
- ?.getAttribute("data-value") ?? null;
-
- // cmdk auto-selects the first item; Arrow keys must still move that selection.
- const first = selectedValue();
- expect(first).not.toBeNull();
+ it("Shift+Enter falls back to a keyword search", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "fix the Safari login callback 500");
+ await waitFor(() => expect(renderedValues()[0]).toBe("delegate:submit"));
- await user.keyboard("{ArrowDown}");
- expect(selectedValue()).not.toBe(first);
+ fireEvent.keyDown(input(), { key: "Enter", shiftKey: true });
- await user.keyboard("{ArrowUp}");
- expect(selectedValue()).toBe(first);
+ await waitFor(() => expect(renderedValues()).not.toContain("delegate:submit"));
+ expect(api("quickCreateIssue")).not.toHaveBeenCalled();
+ });
- // Home moves the text caret to the start — it must NOT jump the result list.
- await user.keyboard("{Home}");
- expect(input.selectionStart).toBe(0);
- expect(input.selectionEnd).toBe(0);
- expect(selectedValue()).toBe(first);
+ it("does not read a plain keyword as an instruction", async () => {
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "login");
- // End moves the caret to the end — again leaving the result selection alone.
- await user.keyboard("{End}");
- expect(input.selectionStart).toBe(input.value.length);
- expect(input.selectionEnd).toBe(input.value.length);
- expect(selectedValue()).toBe(first);
+ await waitFor(() => expect(api("searchIssues")).toHaveBeenCalled(), { timeout: 2000 });
+ expect(renderedValues()).not.toContain("delegate:submit");
+ });
});
- // MUL-5824: the two searches are ranked independently server-side and the
- // palette renders the whole Projects group before the whole Issues group, so
- // per-type ranking let one cancelled project be the very first row. The
- // partition has to be cross-type and applied here, where results aggregate.
+ // MUL-5824: the two searches are ranked independently server-side, so the
+ // cancelled partition has to be cross-type and applied where results meet.
describe("mixed issue/project cancelled demotion", () => {
- const fixtureIssue = (
- over: Partial<Record<string, unknown>> & { id: string },
- ) => ({
- workspace_id: "ws-test",
- number: 1,
- identifier: "MUL-1",
- title: "Untitled",
- description: null,
- status: "todo",
- priority: "none",
- assignee_type: null,
- assignee_id: null,
- creator_type: "member",
- creator_id: "user-1",
- parent_issue_id: null,
- project_id: null,
- position: 0,
- start_date: null,
- due_date: null,
- created_at: "2026-01-01T00:00:00Z",
- updated_at: "2026-01-01T00:00:00Z",
- match_source: "title",
- ...over,
- });
-
- const fixtureProject = (
- over: Partial<Record<string, unknown>> & { id: string },
- ) => ({
+ const fixtureProject = (over: Partial<Record<string, unknown>> & { id: string }) => ({
workspace_id: "ws-test",
title: "Untitled",
description: null,
@@ -1191,251 +1060,103 @@ describe("SearchCommand", () => {
match_source: "title",
...over,
});
-
- /** Rendered result rows, top to bottom, by their cmdk value. */
- const renderedValues = () =>
- Array.from(
- document.querySelectorAll<HTMLElement>('[cmdk-item=""]'),
- )
- .map((el) => el.getAttribute("data-value") ?? "")
- .filter((v) => v.startsWith("project:") || v.startsWith("issue-"));
-
- /**
- * Group headings, top to bottom. Queried structurally rather than by text:
- * a cancelled project also renders "Cancelled" as its status label.
- */
- const renderedHeadings = () =>
- Array.from(
- document.querySelectorAll<HTMLElement>("[cmdk-group-heading]"),
- ).map((el) => el.textContent ?? "");
+ const fixtureIssue = (over: Partial<Issue> & { id: string }) => ({
+ ...makeIssue(over),
+ match_source: "title",
+ });
+ const resultValues = () =>
+ renderedValues().filter((v) => v.startsWith("project:") || v.startsWith("issue-"));
it("renders project status in the selected UI language", async () => {
const user = userEvent.setup();
- mockSearchProjects.mockResolvedValue({
- projects: [
- fixtureProject({
- id: "proj-localized",
- title: "localized project",
- status: "in_progress",
- }),
- ],
+ api("searchProjects").mockResolvedValue({
+ projects: [fixtureProject({ id: "proj-localized", title: "localized project" })],
total: 1,
});
-
renderSearchInChinese();
- await user.type(
- screen.getByPlaceholderText("Type a command or search..."),
- "localized",
- );
+ await user.type(input(), "localized");
- await waitFor(() => expect(screen.getByText("进行中")).toBeInTheDocument(), {
- timeout: 2000,
- });
+ await waitFor(() => expect(screen.getByText("进行中")).toBeInTheDocument(), { timeout: 2000 });
expect(screen.queryByText("In Progress")).toBeNull();
});
- it("keeps a cancelled project below a live issue instead of first", async () => {
- const user = userEvent.setup();
- mockSearchIssues.mockResolvedValue({
- issues: [
- fixtureIssue({
- id: "issue-live",
- number: 10,
- identifier: "MUL-10",
- title: "search live issue",
- status: "in_progress",
- }),
- ],
- total: 1,
- });
- mockSearchProjects.mockResolvedValue({
- projects: [
- fixtureProject({
- id: "proj-dead",
- title: "search dead project",
- status: "cancelled",
- }),
- ],
- total: 1,
- });
-
- renderSearch();
- await user.type(
- screen.getByPlaceholderText("Type a command or search..."),
- "search",
- );
-
- await waitFor(
- () => {
- expect(renderedValues()).toEqual(["issue-live", "project:proj-dead"]);
- },
- { timeout: 2000 },
- );
- // Still discoverable, just under its own heading at the bottom.
- expect(renderedHeadings()).toEqual(["Issues", "Cancelled"]);
- });
-
it("keeps live rows of both types above every cancelled row", async () => {
const user = userEvent.setup();
- mockSearchIssues.mockResolvedValue({
+ api("searchIssues").mockResolvedValue({
issues: [
- fixtureIssue({
- id: "issue-dead",
- number: 11,
- identifier: "MUL-11",
- title: "search a",
- status: "cancelled",
- }),
- fixtureIssue({
- id: "issue-live",
- number: 12,
- identifier: "MUL-12",
- title: "search b",
- status: "todo",
- }),
- fixtureIssue({
- id: "issue-done",
- number: 13,
- identifier: "MUL-13",
- title: "search c",
- status: "done",
- }),
+ fixtureIssue({ id: "issue-dead", number: 11, identifier: "MUL-11", title: "search a", status: "cancelled" }),
+ fixtureIssue({ id: "issue-live", number: 12, identifier: "MUL-12", title: "search b", status: "todo" }),
+ fixtureIssue({ id: "issue-done", number: 13, identifier: "MUL-13", title: "search c", status: "done" }),
],
total: 3,
});
- mockSearchProjects.mockResolvedValue({
+ api("searchProjects").mockResolvedValue({
projects: [
fixtureProject({ id: "proj-dead", title: "search p1", status: "cancelled" }),
fixtureProject({ id: "proj-live", title: "search p2", status: "planned" }),
],
total: 2,
});
-
renderSearch();
- await user.type(
- screen.getByPlaceholderText("Type a command or search..."),
- "search",
- );
+ await user.type(input(), "search");
await waitFor(
- () => {
- expect(renderedValues()).toEqual([
+ () =>
+ expect(resultValues()).toEqual([
"project:proj-live",
- // 'done' is live — only cancelled work is demoted.
"issue-live",
"issue-done",
"project:proj-dead",
"issue-dead",
- ]);
- },
+ ]),
{ timeout: 2000 },
);
+ expect(renderedHeadings().at(-1)).toBe("Cancelled");
});
it("exempts a cancelled issue the query targets by identifier", async () => {
const user = userEvent.setup();
- mockSearchIssues.mockResolvedValue({
- issues: [
- fixtureIssue({
- id: "issue-hit",
- number: 7,
- identifier: "MUL-7",
- title: "Direct hit",
- status: "cancelled",
- }),
- ],
+ api("searchIssues").mockResolvedValue({
+ issues: [fixtureIssue({ id: "issue-hit", number: 7, identifier: "MUL-7", title: "Direct hit", status: "cancelled" })],
total: 1,
});
- mockSearchProjects.mockResolvedValue({ projects: [], total: 0 });
-
renderSearch();
- await user.type(
- screen.getByPlaceholderText("Type a command or search..."),
- "MUL-7",
- );
+ await user.type(input(), "MUL-7");
- await waitFor(
- () => {
- expect(renderedValues()).toEqual(["issue-hit"]);
- },
- { timeout: 2000 },
- );
+ await waitFor(() => expect(resultValues()).toEqual(["issue-hit"]), { timeout: 2000 });
expect(renderedHeadings()).not.toContain("Cancelled");
});
});
- // Rows from the previous query stay on screen while the next request is in
- // flight (that is what keeps the list from strobing on every keystroke), so
- // they have to stop being *reachable*. cmdk re-selects the first valid item
- // on every input change, so a live stale row means Enter opens a result the
- // user is no longer searching for.
+ // Rows from the previous query stay painted while the next request is in
+ // flight, so they have to stop being reachable: cmdk re-selects the first
+ // valid item on every input change.
describe("stale results while the next query is in flight", () => {
- const alphaIssue = {
- id: "issue-alpha",
- workspace_id: "ws-test",
- number: 100,
- identifier: "MUL-100",
- title: "Alpha result",
- description: null,
- status: "todo",
- priority: "none",
- assignee_type: null,
- assignee_id: null,
- creator_type: "member",
- creator_id: "user-1",
- parent_issue_id: null,
- project_id: null,
- position: 0,
- start_date: null,
- due_date: null,
- created_at: "2026-01-01T00:00:00Z",
- updated_at: "2026-01-01T00:00:00Z",
- match_source: "title",
- };
-
- /** HighlightText splits the title into <mark> + text, so match the span. */
const alphaRowTitle = () =>
- screen.getByText(
- (_, el) => el?.textContent === "Alpha result" && el?.tagName === "SPAN",
- );
+ screen.getByText((_, el) => el?.textContent === "Alpha result" && el?.tagName === "SPAN");
- /** Resolve the first query; hang on everything after it. */
- const answerOnlyAlpha = () => {
- mockSearchIssues.mockImplementation(({ q }: { q: string }) =>
+ const typeAlphaThenChange = async (user: ReturnType<typeof userEvent.setup>) => {
+ api("searchIssues").mockImplementation(({ q }: { q: string }) =>
q === "alpha"
- ? Promise.resolve({ issues: [alphaIssue], total: 1 })
+ ? Promise.resolve({
+ issues: [{ ...makeIssue({ id: "issue-alpha", identifier: "MUL-100", title: "Alpha result" }), match_source: "title" }],
+ total: 1,
+ })
: new Promise(() => {}),
);
- mockSearchProjects.mockImplementation(({ q }: { q: string }) =>
- q === "alpha"
- ? Promise.resolve({ projects: [], total: 0 })
- : new Promise(() => {}),
+ api("searchProjects").mockImplementation(({ q }: { q: string }) =>
+ q === "alpha" ? Promise.resolve({ projects: [], total: 0 }) : new Promise(() => {}),
);
- };
-
- const typeAlphaThenChange = async (
- user: ReturnType<typeof userEvent.setup>,
- ) => {
- answerOnlyAlpha();
renderSearch();
- const input = screen.getByPlaceholderText("Type a command or search...");
- await user.type(input, "alpha");
- await waitFor(
- () => {
- expect(alphaRowTitle()).toBeInTheDocument();
- },
- { timeout: 2000 },
- );
- // Query changes; the response for it never arrives.
- await user.type(input, "zzz");
- return input;
+ await user.type(input(), "alpha");
+ await waitFor(() => expect(alphaRowTitle()).toBeInTheDocument(), { timeout: 2000 });
+ await user.type(input(), "zzz");
};
it("does not open the previous query's result on Enter", async () => {
const user = userEvent.setup();
- const input = await typeAlphaThenChange(user);
-
- fireEvent.keyDown(input, { key: "Enter" });
+ await typeAlphaThenChange(user);
+ fireEvent.keyDown(input(), { key: "Enter" });
expect(mockPush).not.toHaveBeenCalled();
expect(useSearchStore.getState().open).toBe(true);
@@ -1444,8 +1165,6 @@ describe("SearchCommand", () => {
it("does not open the previous query's result on click", async () => {
const user = userEvent.setup();
await typeAlphaThenChange(user);
-
- // Still painted (that is the point), but inert.
fireEvent.click(alphaRowTitle());
expect(mockPush).not.toHaveBeenCalled();
diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsx
index 1edadcb495..947986af3a 100644
--- a/packages/views/search/search-command.tsx
+++ b/packages/views/search/search-command.tsx
@@ -1,353 +1,81 @@
"use client";
-import { issueStatusCategory } from "@multica/core/issues";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import {
- Check,
- Clock,
- Copy,
- FileText,
- Link2,
- Loader2,
- MessageSquare,
- Plus,
- SearchIcon,
- ListChevronsDownUp,
- ListChevronsUpDown,
- Monitor,
- Moon,
- Sun,
- type LucideIcon,
-} from "lucide-react";
+import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { ChevronRight, SearchIcon, Sparkles } from "lucide-react";
import { Command as CommandPrimitive } from "cmdk";
-import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
-import { toast } from "sonner";
-import type {
- InboxWorkspaceUnread,
- MemberWithUser,
- SearchIssueResult,
- SearchProjectResult,
- Workspace,
-} from "@multica/core/types";
-import { isLocalSearchReady, searchIssues, searchProjects } from "@multica/core/search-index";
-import { partitionAggregatedSearchResults } from "@multica/core/search/cancelled-rank";
-import {
- openCreateIssueWithPreference,
- selectRecentIssues,
- useCommentCollapseStore,
- useRecentIssuesStore,
- useResolvedExpandStore,
-} from "@multica/core/issues/stores";
-import { issueDetailOptions, issueTimelineOptions } from "@multica/core/issues/queries";
-import { useWorkspaceId } from "@multica/core";
-import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
-import { paths, useWorkspacePaths, WORKSPACE_PAGES } from "@multica/core/paths";
-import type { WorkspacePageKey, WorkspacePaths } from "@multica/core/paths";
-import { useModalStore } from "@multica/core/modals";
+import { selectCommandBarContexts, useCommandBarContextStore } from "@multica/core/command-bar";
import { createShortcutChord } from "@multica/core/shortcuts";
-import { memberListOptions, workspaceListOptions } from "@multica/core/workspace/queries";
-import { inboxUnreadSummaryOptions, unreadWorkspaceIds } from "@multica/core/inbox/queries";
-import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
-import { StatusIcon } from "../issues/components";
-import { resolvedThreadRootIds, rootCommentIds } from "../issues/components/thread-utils";
-import { ProjectIcon } from "../projects/components/project-icon";
-import { WorkspaceAvatar } from "../workspace/workspace-avatar";
-import { useProjectStatusLabels } from "../projects/components/labels";
-import { routeIconForPath } from "../layout/route-icon-components";
-import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";
-import type { ProjectStatus } from "@multica/core/types";
-import { ActorAvatar } from "../common/actor-avatar";
-import { ShortcutKeycaps } from "../common/shortcut-keycaps";
-import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";
import {
Dialog,
DialogContent,
+ DialogDescription,
DialogHeader,
DialogTitle,
- DialogDescription,
} from "@multica/ui/components/ui/dialog";
-import { useTheme } from "@multica/ui/components/common/theme-provider";
-import { copyText } from "@multica/ui/lib/clipboard";
-import {
- resolveClickIntent,
- useIntentNavigate,
- useNavigation,
- type LinkClickIntent,
-} from "../navigation";
+import { ShortcutKeycaps } from "../common/shortcut-keycaps";
+import { resolveClickIntent, useIntentNavigate, type LinkClickIntent } from "../navigation";
import { useT } from "../i18n";
-import { matchesPinyin } from "../editor/extensions/pinyin-match";
-import { HighlightText } from "./highlight-text";
+import { PaletteContext, type PaletteApi } from "./palette-context";
+import { PaletteFooter } from "./footer";
+import { PaletteHostDialogs } from "./host-dialogs";
+import { PageView } from "./pages/page-view";
+import { RootView } from "./root-view";
+import { useDelegateSubmit } from "./delegate/use-delegate";
+import { useRootModel } from "./use-root-model";
import { useSearchStore } from "./search-store";
+import type { DelegateActor, PaletteHostDialog, PaletteStackEntry } from "./types";
-// The palette's Pages group is generated from WORKSPACE_PAGES, the same
-// registry the sidebar nav and the desktop tab bar read. It used to be a
-// hand-written list, which silently went stale every time a page was added:
-// Chat, Autopilot, Squads and Analytics shipped in the sidebar but were
-// unreachable from the palette (MUL-6272). Deriving the list means a new
-// workspace page is in the palette the moment it is in the registry.
-//
-// Page keys double as WorkspacePaths method names, so `p[key]()` resolves the
-// destination against the current workspace slug at render time. Every
-// WorkspacePageKey must therefore stay a parameterless path builder.
-
-// Extra query aliases per page, on top of the localized label. Declared as a
-// total Record so adding a workspace page is a compile error until its
-// keywords are filled in.
-const PAGE_KEYWORDS: Record<WorkspacePageKey, string[]> = {
- inbox: ["inbox", "notifications", "收件箱", "通知"],
- chat: ["chat", "messages", "conversation", "聊天", "消息", "对话"],
- myIssues: ["my", "issues", "assigned", "mine", "我的", "任务"],
- issues: ["issues", "tasks", "bugs", "任务"],
- projects: ["projects", "kanban", "项目"],
- autopilots: ["autopilot", "autopilots", "automation", "schedule", "cron", "webhook", "自动化", "定时"],
- agents: ["agents", "bots", "ai", "智能体"],
- squads: ["squads", "teams", "小队", "团队"],
- usage: ["usage", "analytics", "stats", "metrics", "统计", "分析", "用量"],
- runtimes: ["runtimes", "environments", "machines", "运行时"],
- skills: ["skills", "library", "技能"],
- settings: ["settings", "config", "preferences", "设置", "配置"],
-};
-
-const NAV_PAGE_KEYS = Object.keys(WORKSPACE_PAGES) as WorkspacePageKey[];
-
-// No `icon` field: like the sidebar nav, a page's icon is derived from its
-// destination path via routeIconForPath, so all navigation surfaces show the
-// same icon for the same route.
-interface NavPage {
- key: WorkspacePageKey;
- label: string;
- keywords: string[];
-}
-
-type ThemeValue = "light" | "dark" | "system";
-
-function memberInitials(name: string) {
- return name
- .split(" ")
- .map((word) => word[0])
- .join("")
- .toUpperCase()
- .slice(0, 2);
-}
-
-// Row matcher shared by the Pages and Commands groups.
-//
-// Keywords match by prefix, not substring. They are invisible synonyms, so a
-// substring hit reads as a bug from the outside: "s" used to surface Inbox
-// (via "notifications") and "i" surfaced nearly every page. The visible label
-// still matches anywhere, because there the user can see what they hit.
-//
-// Pinyin is included for the same reason member search has it: under a Chinese
-// UI the localized label is the only thing the user can aim at, so typing
-// "renwu" has to reach "任务".
-function matchesRow(label: string, keywords: string[], query: string) {
- return (
- label.toLowerCase().includes(query) ||
- keywords.some((kw) => kw.startsWith(query)) ||
- matchesPinyin(label, query)
- );
-}
-
-// Hidden aliases for the Workspaces group, prefix-matched like page keywords:
-// typing "workspace" lists every workspace the user can switch to.
-const WORKSPACE_KEYWORDS = ["switch", "workspace"];
+const ESCAPE = createShortcutChord("Escape");
-function matchesWorkspace(workspace: Workspace, query: string) {
- return (
- matchesRow(workspace.name, WORKSPACE_KEYWORDS, query) ||
- workspace.slug.toLowerCase().includes(query)
- );
-}
-
-const EMPTY_WORKSPACES: Workspace[] = [];
-const EMPTY_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];
-
-function matchesMember(member: MemberWithUser, query: string) {
- return (
- member.name.toLowerCase().includes(query) ||
- member.email.toLowerCase().includes(query) ||
- (query.length >= 3 && member.role.startsWith(query)) ||
- matchesPinyin(member.name, query)
- );
-}
-
-function IssueAssigneeAvatar({
- assigneeType,
- assigneeId,
-}: {
- assigneeType?: string | null;
- assigneeId?: string | null;
-}) {
- if (!assigneeType || !assigneeId) return null;
- return (
- <ActorAvatar
- actorType={assigneeType}
- actorId={assigneeId}
- size="sm"
- profileLink={false}
- className="shrink-0"
- />
+/**
+ * ⌘K. The shell owns the dialog, the input, the page stack and the footer;
+ * what the palette offers comes from the pages on screen (registered contexts)
+ * and the search over workspace objects.
+ */
+export function SearchCommand() {
+ const { t } = useT("search");
+ const open = useSearchStore((s) => s.open);
+ const setOpen = useSearchStore((s) => s.setOpen);
+ const [hostDialog, setHostDialog] = useState<PaletteHostDialog | null>(null);
+ const close = useCallback(() => setOpen(false), [setOpen]);
+ const openHostDialog = useCallback(
+ (dialog: PaletteHostDialog) => {
+ setOpen(false);
+ setHostDialog(dialog);
+ },
+ [setOpen],
);
-}
-
-// Project / issue rows are rendered from three groups (Projects, Issues,
-// Cancelled — see the partition note on the results list), so the row markup
-// lives in one component each instead of being duplicated per group.
-function ProjectResultRow({
- project,
- query,
- disabled,
- onSelect,
-}: {
- project: SearchProjectResult;
- query: string;
- disabled?: boolean;
- onSelect: (value: string) => void;
-}) {
- const projectStatusLabels = useProjectStatusLabels();
- const status = project.status as ProjectStatus;
return (
- <CommandPrimitive.Item
- key={`project:${project.id}`}
- value={`project:${project.id}`}
- disabled={disabled}
- onSelect={onSelect}
- className="flex cursor-default select-none flex-col gap-1 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
- >
- <div className="flex items-center gap-2.5">
- <ProjectIcon project={project} size="md" />
- <span className="truncate">
- <HighlightText text={project.title} query={query} />
- </span>
- <span
- className={`ml-auto text-caption shrink-0 ${PROJECT_STATUS_CONFIG[status]?.color ?? "text-muted-foreground"}`}
+ <>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent
+ finalFocus={false}
+ className="top-[20%] translate-y-0 overflow-hidden rounded-xl! p-0 sm:max-w-[640px]!"
+ showCloseButton={false}
>
- {projectStatusLabels[status] ?? project.status}
- </span>
- </div>
- {project.match_source === "description" && project.matched_snippet && (
- <div className="flex items-start gap-2 pl-[26px]">
- <span className="text-caption text-muted-foreground truncate">
- <HighlightText text={project.matched_snippet} query={query} />
- </span>
- </div>
- )}
- </CommandPrimitive.Item>
+ <DialogHeader className="sr-only">
+ <DialogTitle>{t(($) => $.title)}</DialogTitle>
+ <DialogDescription>{t(($) => $.description)}</DialogDescription>
+ </DialogHeader>
+ {open && <PaletteBody close={close} openHostDialog={openHostDialog} />}
+ </DialogContent>
+ </Dialog>
+ <PaletteHostDialogs dialog={hostDialog} onClose={() => setHostDialog(null)} />
+ </>
);
}
-function IssueResultRow({
- issue,
- query,
- disabled,
- onSelect,
+function PaletteBody({
+ close,
+ openHostDialog,
}: {
- issue: SearchIssueResult;
- query: string;
- disabled?: boolean;
- onSelect: (value: string) => void;
+ close: () => void;
+ openHostDialog: (dialog: PaletteHostDialog) => void;
}) {
- const { colorOf, iconOf } = useIssueStatuses(useWorkspaceId());
- return (
- <CommandPrimitive.Item
- key={issue.id}
- value={issue.id}
- disabled={disabled}
- onSelect={onSelect}
- className="flex cursor-default select-none flex-col gap-1 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
- >
- <div className="flex items-center gap-2.5">
- <StatusIcon
- status={issue.status}
- color={colorOf(issue.status)}
- icon={iconOf(issue.status)}
- category={issueStatusCategory(issue) ?? undefined}
- className="size-4 shrink-0"
- />
- <span className="text-caption text-muted-foreground shrink-0">
- {issue.identifier}
- </span>
- <span className="min-w-0 flex-1 truncate">
- <HighlightText text={issue.title} query={query} />
- </span>
- <IssueAssigneeAvatar
- assigneeType={issue.assignee_type}
- assigneeId={issue.assignee_id}
- />
- </div>
- {issue.matched_description_snippet && (
- <div className="flex items-start gap-2 pl-[26px]">
- <FileText className="size-3 shrink-0 text-muted-foreground mt-0.5" />
- <span className="text-caption text-muted-foreground truncate">
- <HighlightText
- text={issue.matched_description_snippet}
- query={query}
- />
- </span>
- </div>
- )}
- {issue.matched_comment_snippet && (
- <div className="flex items-start gap-2 pl-[26px]">
- <MessageSquare className="size-3 shrink-0 text-muted-foreground mt-0.5" />
- <span className="text-caption text-muted-foreground truncate">
- <HighlightText text={issue.matched_comment_snippet} query={query} />
- </span>
- </div>
- )}
- </CommandPrimitive.Item>
- );
-}
-
-interface CommandItem {
- key: string;
- label: string;
- icon: LucideIcon;
- keywords: string[];
- trailing?: React.ReactNode;
- onSelect: () => void;
-}
-
-interface SearchResults {
- /**
- * The trimmed query these rows answer. Rows outlive the query that fetched
- * them — they stay painted while the next request is in flight — so every
- * result set carries the question it is the answer to, and anything that can
- * act on a row checks that it still matches what the user typed.
- */
- query: string;
- issues: SearchIssueResult[];
- projects: SearchProjectResult[];
-}
-
-const NO_RESULTS: SearchResults = { query: "", issues: [], projects: [] };
-
-// One heading treatment for every group. Headings go through cmdk's `heading`
-// prop rather than a hand-rolled div: cmdk renders it into a
-// [cmdk-group-heading] node and points the group's aria-labelledby at it, so a
-// screen reader announces which group a row belongs to.
-const GROUP_CLASS =
- "p-2 [&_[cmdk-group-heading]]:px-3 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-caption [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground";
-
-export function SearchCommand() {
- const { t } = useT("search");
- // Page names come from the sidebar's own namespace rather than a private
- // copy under `search.pages`: one translated string per page, so the palette
- // can never disagree with the sidebar about what a page is called.
- const { t: tNav } = useT("layout");
- const navPages = useMemo<NavPage[]>(
- () =>
- NAV_PAGE_KEYS.map((key) => ({
- key,
- label: tNav(($) => $.nav[WORKSPACE_PAGES[key].navKey]),
- keywords: PAGE_KEYWORDS[key],
- })),
- [tNav],
- );
- const { pathname, getShareableUrl } = useNavigation();
const intentNavigate = useIntentNavigate();
- const open = useSearchStore((s) => s.open);
- const setOpen = useSearchStore((s) => s.setOpen);
+ const [pageQuery, setPageQuery] = useState("");
+ const [stack, setStack] = useState<PaletteStackEntry[]>([]);
// cmdk's onSelect carries no event, so the activating gesture's modifiers
// are recorded on the capture phase (click on a result, Enter in the input)
@@ -365,695 +93,170 @@ export function SearchCommand() {
pendingIntentRef.current = "push";
return intent;
}, []);
- const wsId = useWorkspaceId();
- const { colorOf, iconOf } = useIssueStatuses(wsId);
- const recentItems = useRecentIssuesStore(selectRecentIssues(wsId));
- const p: WorkspacePaths = useWorkspacePaths();
- const { theme, setTheme } = useTheme();
- const { data: members = [] } = useQuery(memberListOptions(wsId));
- // Both are account-level cache entries the sidebar's workspace switcher
- // already holds, so the Workspaces group adds no requests of its own.
- const { data: workspaces = EMPTY_WORKSPACES } = useQuery(workspaceListOptions());
- const { data: unreadSummary = EMPTY_UNREAD_SUMMARY } = useQuery(
- inboxUnreadSummaryOptions(),
- );
- const unreadWsIds = useMemo(() => unreadWorkspaceIds(unreadSummary), [unreadSummary]);
-
- // Resolve each recent issue via its cached detail entry. Recent items are
- // typically already in the detail cache because the user has opened them;
- // if not, this triggers a lookup per id so Recent never depends on whether
- // the issue falls inside the paginated list cache.
- //
- // Gated on `open`: the palette is mounted for the whole session, and the
- // store keeps up to 20 recent ids, so an ungated list fired up to 20 issue
- // detail requests on every cold app load for a surface the user may never
- // open.
- const recentDetailQueries = useQueries({
- queries: open ? recentItems.map((item) => issueDetailOptions(wsId, item.id)) : [],
- });
- const recentIssues = useMemo(
- () =>
- recentDetailQueries.flatMap((q) => (q.data ? [q.data] : [])),
- [recentDetailQueries],
- );
-
- const [query, setQuery] = useState("");
- const [results, setResults] = useState<SearchResults>(NO_RESULTS);
- const [isLoading, setIsLoading] = useState(false);
- const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const abortRef = useRef<AbortController | null>(null);
-
- const filteredPages = useMemo(() => {
- const q = query.trim().toLowerCase();
- if (!q) return [];
- return navPages.filter((page) => matchesRow(page.label, page.keywords, q));
- }, [navPages, query]);
-
- // Detect if current route is an issue detail page — /{slug}/issues/{id}.
- // Falls back to null on any other route; used to gate issue-specific commands.
- const currentIssueId = useMemo(() => {
- const match = pathname.match(/\/issues\/([^/]+)$/);
- const raw = match?.[1];
- return raw ? decodeURIComponent(raw) : null;
- }, [pathname]);
- const { data: currentIssue = null } = useQuery({
- ...issueDetailOptions(wsId, currentIssueId ?? ""),
- enabled: !!currentIssueId,
- });
- const queryClient = useQueryClient();
- const commands = useMemo<CommandItem[]>(() => {
- const activeThemeCheck = (value: ThemeValue) =>
- theme === value ? (
- <Check
- aria-label={t(($) => $.commands.current_theme_aria)}
- className="ml-auto size-4 shrink-0 text-muted-foreground"
- />
- ) : undefined;
-
- const items: CommandItem[] = [
- {
- key: "new-issue",
- label: t(($) => $.commands.new_issue),
- icon: Plus,
- keywords: ["new", "issue", "create", "add"],
- onSelect: () => {
- openCreateIssueWithPreference();
- setOpen(false);
- },
- },
- {
- key: "new-project",
- label: t(($) => $.commands.new_project),
- icon: Plus,
- keywords: ["new", "project", "create", "add"],
- onSelect: () => {
- useModalStore.getState().open("create-project");
- setOpen(false);
- },
- },
- ];
-
- if (currentIssueId && currentIssue) {
- const { id: issueId, identifier } = currentIssue;
- items.push(
- {
- key: "copy-issue-link",
- label: t(($) => $.commands.copy_issue_link),
- icon: Link2,
- keywords: ["copy", "link", "share", "url", identifier.toLowerCase()],
- onSelect: () => {
- void copyText(getShareableUrl(pathname)).then((ok) => {
- if (ok) toast.success(t(($) => $.toast.link_copied));
- });
- setOpen(false);
- },
- },
- {
- key: "copy-issue-identifier",
- label: t(($) => $.commands.copy_identifier, { identifier }),
- icon: Copy,
- keywords: ["copy", "id", "identifier", identifier.toLowerCase()],
- onSelect: () => {
- void copyText(identifier).then((ok) => {
- if (ok) toast.success(t(($) => $.toast.copied_identifier, { identifier }));
- });
- setOpen(false);
- },
- },
- {
- key: "fold-all-comments",
- label: t(($) => $.commands.fold_all_comments),
- icon: ListChevronsDownUp,
- keywords: ["fold", "collapse", "comments", "收起", "折叠", "评论"],
- onSelect: () => {
- // The timeline is already cached whenever the issue page has
- // rendered; ensureQueryData only fetches on a cold cache. If it
- // still can't load, no comments are on screen — dropping the
- // action matches the visible state.
- void queryClient
- .ensureQueryData(issueTimelineOptions(issueId))
- .then((entries) => {
- useCommentCollapseStore
- .getState()
- .collapseAll(issueId, rootCommentIds(entries));
- useResolvedExpandStore.getState().collapseAll(issueId);
- })
- .catch(() => {});
- setOpen(false);
- },
- },
- {
- key: "unfold-all-comments",
- label: t(($) => $.commands.unfold_all_comments),
- icon: ListChevronsUpDown,
- keywords: ["unfold", "expand", "comments", "展开", "评论"],
- onSelect: () => {
- void queryClient
- .ensureQueryData(issueTimelineOptions(issueId))
- .then((entries) => {
- useCommentCollapseStore.getState().expandAll(issueId);
- useResolvedExpandStore
- .getState()
- .expandAll(issueId, resolvedThreadRootIds(entries));
- })
- .catch(() => {});
- setOpen(false);
- },
- },
- );
- }
+ const push = useCallback((entry: PaletteStackEntry) => {
+ setStack((prev) => [...prev, entry]);
+ setPageQuery("");
+ }, []);
- items.push(
- {
- key: "theme-light",
- label: t(($) => $.commands.switch_to_light),
- icon: Sun,
- keywords: ["light", "theme", "appearance", "mode", "bright"],
- trailing: activeThemeCheck("light"),
- onSelect: () => {
- setTheme("light");
- setOpen(false);
- },
- },
- {
- key: "theme-dark",
- label: t(($) => $.commands.switch_to_dark),
- icon: Moon,
- keywords: ["dark", "theme", "appearance", "mode", "night"],
- trailing: activeThemeCheck("dark"),
- onSelect: () => {
- setTheme("dark");
- setOpen(false);
- },
- },
- {
- key: "theme-system",
- label: t(($) => $.commands.use_system_theme),
- icon: Monitor,
- keywords: ["system", "theme", "appearance", "mode", "auto"],
- trailing: activeThemeCheck("system"),
- onSelect: () => {
- setTheme("system");
- setOpen(false);
- },
+ const api = useMemo<PaletteApi>(
+ () => ({
+ close,
+ push,
+ navigate: (href) => {
+ close();
+ intentNavigate(href, consumeIntent());
},
- );
-
- return items;
- }, [currentIssue, currentIssueId, getShareableUrl, pathname, queryClient, setOpen, setTheme, theme, t]);
-
- const filteredCommands = useMemo(() => {
- const q = query.trim().toLowerCase();
- // No query: only surface the primary creation action. Other commands
- // (theme switches, copy actions, New Project) are revealed as the user
- // types, leaving the empty-state space to Recent.
- if (!q) return commands.filter((c) => c.key === "new-issue");
- return commands.filter((c) => matchesRow(c.label, c.keywords, q));
- }, [commands, query]);
-
- const filteredMembers = useMemo(() => {
- const q = query.trim().toLowerCase();
- if (!q) return [];
- const wantsAllMembers =
- q.length >= 3 &&
- ("members".startsWith(q) ||
- "people".startsWith(q) ||
- "users".startsWith(q) ||
- "team".startsWith(q));
- return members
- .filter((member) => wantsAllMembers || matchesMember(member, q))
- .slice(0, 10);
- }, [members, query]);
-
- // The current workspace is never a switch target, so a single-workspace user
- // never sees the group. The list keeps the server's created_at order, the
- // same order as the sidebar switcher.
- const filteredWorkspaces = useMemo(() => {
- const q = query.trim().toLowerCase();
- if (!q) return [];
- return workspaces.filter((ws) => ws.id !== wsId && matchesWorkspace(ws, q));
- }, [workspaces, wsId, query]);
-
- const hasResults =
- results.issues.length > 0 ||
- results.projects.length > 0 ||
- filteredMembers.length > 0 ||
- filteredWorkspaces.length > 0;
-
- // Rows answering an earlier query are still painted while the next request
- // is in flight — that is what keeps the list from strobing on every
- // keystroke — but they must not be actionable: cmdk re-selects the first
- // valid item whenever the input changes, so a live stale row turns the next
- // Enter into a jump to a result the user has already typed past.
- const resultsAreStale = results.query !== query.trim();
-
- // Cross-type cancelled demotion (MUL-5824). The two searches are ranked
- // independently server-side, so the partition has to happen here, where they
- // are aggregated for display. See the render note on the results list.
- const partitionedResults = useMemo(
- () =>
- partitionAggregatedSearchResults({
- issues: results.issues,
- projects: results.projects,
- // The partition describes these rows, so it keys off the query they
- // answer — not what the user has typed since.
- query: results.query,
- }),
- [results],
+ openHostDialog,
+ }),
+ [close, consumeIntent, intentNavigate, openHostDialog, push],
);
// Close on single ESC — capture phase fires before base-ui Dialog's handlers
useEffect(() => {
- if (!open) return;
const handleEsc = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
- setOpen(false);
+ close();
}
};
document.addEventListener("keydown", handleEsc, true);
return () => document.removeEventListener("keydown", handleEsc, true);
- }, [open, setOpen]);
-
- // Cleanup debounce/abort on unmount
- useEffect(() => {
- return () => {
- if (debounceRef.current) clearTimeout(debounceRef.current);
- if (abortRef.current) abortRef.current.abort();
- };
- }, []);
-
- // Reset state when dialog closes
- useEffect(() => {
- if (!open) {
- setQuery("");
- setResults(NO_RESULTS);
- setIsLoading(false);
- }
- }, [open]);
-
- const search = useCallback((q: string) => {
- if (debounceRef.current) clearTimeout(debounceRef.current);
- if (abortRef.current) abortRef.current.abort();
-
- if (!q.trim()) {
- setResults(NO_RESULTS);
- setIsLoading(false);
- return;
- }
-
- setIsLoading(true);
- // The debounce spares the server a request per keystroke; the local index
- // answers in milliseconds, so it searches on every keystroke.
- const delay = isLocalSearchReady() ? 0 : 300;
- debounceRef.current = setTimeout(async () => {
- const controller = new AbortController();
- abortRef.current = controller;
- try {
- const [issueRes, projectRes] = await Promise.all([
- searchIssues({
- q: q.trim(),
- limit: 20,
- include_closed: true,
- signal: controller.signal,
- }),
- searchProjects({
- q: q.trim(),
- limit: 10,
- include_closed: true,
- signal: controller.signal,
- }),
- ]);
- if (!controller.signal.aborted) {
- setResults({
- query: q.trim(),
- issues: issueRes.issues,
- projects: projectRes.projects,
- });
- setIsLoading(false);
- }
- } catch {
- if (!controller.signal.aborted) {
- // Drop the previous query's rows rather than leaving them on screen
- // permanently greyed out: the request that would have replaced them
- // is never coming. The list falls through to the empty state.
- setResults({ query: q.trim(), issues: [], projects: [] });
- setIsLoading(false);
- }
- }
- }, delay);
- }, []);
-
- const handleValueChange = useCallback(
- (value: string) => {
- setQuery(value);
- search(value);
- },
- [search],
- );
+ }, [close]);
- const handleSelect = useCallback(
- (value: string) => {
- setOpen(false);
- const href = value.startsWith("project:")
- ? // value is "project:<id>" — slice off the 8-char prefix to extract the id.
- p.projectDetail(value.slice(8))
- : p.issueDetail(value);
- intentNavigate(href, consumeIntent());
- },
- [intentNavigate, consumeIntent, setOpen, p],
+ return (
+ <PaletteContext.Provider value={api}>
+ <PaletteFrame
+ stack={stack}
+ setStack={setStack}
+ pageQuery={pageQuery}
+ setPageQuery={setPageQuery}
+ recordIntent={recordIntent}
+ />
+ </PaletteContext.Provider>
);
+}
- const handlePageSelect = useCallback(
- (key: WorkspacePageKey) => {
- setOpen(false);
- intentNavigate(p[key](), consumeIntent());
- },
- [intentNavigate, consumeIntent, setOpen, p],
+/** Everything that reads the palette API lives under its provider. */
+function PaletteFrame({
+ stack,
+ setStack,
+ pageQuery,
+ setPageQuery,
+ recordIntent,
+}: {
+ stack: PaletteStackEntry[];
+ setStack: React.Dispatch<React.SetStateAction<PaletteStackEntry[]>>;
+ pageQuery: string;
+ setPageQuery: (value: string) => void;
+ recordIntent: (e: Pick<MouseEvent, "button" | "metaKey" | "ctrlKey" | "shiftKey">) => void;
+}) {
+ const { t } = useT("search");
+ const entries = useCommandBarContextStore(selectCommandBarContexts);
+ const contexts = useMemo(() => entries.map((entry) => entry.context), [entries]);
+ const [rawQuery, setRawQuery] = useState("");
+ const [dismissedDelegateFor, setDismissedDelegateFor] = useState<string | null>(null);
+ const current = stack[stack.length - 1] ?? null;
+ const inputValue = current ? pageQuery : rawQuery;
+
+ const model = useRootModel(rawQuery, contexts, { active: true, dismissedDelegateFor });
+ const submitDelegate = useDelegateSubmit();
+ const onDelegate = useCallback(
+ (actor: DelegateActor, prompt: string) => void submitDelegate(actor, prompt, model.attachments),
+ [model.attachments, submitDelegate],
);
- const handleMemberSelect = useCallback(
- (userId: string) => {
- intentNavigate(p.memberDetail(userId), consumeIntent());
- setOpen(false);
- },
- [intentNavigate, consumeIntent, setOpen, p],
- );
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ // cmdk's root handler intercepts Home/End for list navigation; stop
+ // propagation so the browser moves the text caret instead.
+ if (e.key === "Home" || e.key === "End") {
+ e.stopPropagation();
+ return;
+ }
+ if (e.key === "Backspace" && current && pageQuery === "") {
+ e.preventDefault();
+ setStack((prev) => prev.slice(0, -1));
+ return;
+ }
+ // ⇧↵ treats an input that read as an instruction as a plain search.
+ if (!current && e.key === "Enter" && e.shiftKey && model.delegate) {
+ e.preventDefault();
+ setDismissedDelegateFor(rawQuery);
+ }
+ };
- // Web lands on the target's Issues; the desktop adapter reads this same
- // push as "resume the workspace's last active tab".
- const handleWorkspaceSelect = useCallback(
- (slug: string) => {
- intentNavigate(paths.workspace(slug).issues(), consumeIntent());
- setOpen(false);
- },
- [intentNavigate, consumeIntent, setOpen],
- );
+ const delegate = !current ? model.delegate : null;
return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogContent
- finalFocus={false}
- className="top-[20%] translate-y-0 overflow-hidden rounded-xl! p-0 sm:max-w-xl!"
- showCloseButton={false}
+ <>
+ <CommandPrimitive
+ key={stack.length}
+ label={t(($) => $.title)}
+ shouldFilter={false}
+ onPointerDownCapture={recordIntent}
+ onClickCapture={recordIntent}
+ onKeyDownCapture={(e) => {
+ if (e.key === "Enter") {
+ recordIntent({ button: 0, metaKey: e.metaKey, ctrlKey: e.ctrlKey, shiftKey: e.shiftKey });
+ }
+ }}
+ className="flex size-full flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground"
>
- <DialogHeader className="sr-only">
- <DialogTitle>{t(($) => $.title)}</DialogTitle>
- <DialogDescription>
- {t(($) => $.description)}
- </DialogDescription>
- </DialogHeader>
- <CommandPrimitive
- shouldFilter={false}
- onPointerDownCapture={recordIntent}
- onClickCapture={recordIntent}
- onKeyDownCapture={(e) => {
- if (e.key === "Enter") {
- recordIntent({
- button: 0,
- metaKey: e.metaKey,
- ctrlKey: e.ctrlKey,
- shiftKey: e.shiftKey,
- });
- }
- }}
- className="flex size-full flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground"
- >
- {/* Search input */}
- <div className="flex items-center gap-3 border-b px-4 py-3">
- <SearchIcon className="size-5 shrink-0 text-muted-foreground" />
- <CommandPrimitive.Input
- placeholder={t(($) => $.placeholder)}
- value={query}
- onValueChange={handleValueChange}
- onKeyDown={(e) => {
- // cmdk's root handler intercepts Home/End for list navigation;
- // stop propagation so the browser moves the text caret instead.
- if (e.key === "Home" || e.key === "End") {
- e.stopPropagation();
- }
- }}
- className="flex-1 bg-transparent text-body outline-none placeholder:text-muted-foreground"
- />
- <ShortcutKeycaps
- shortcut={createShortcutChord("Escape")}
- className="hidden shrink-0 sm:inline-flex"
- />
- </div>
-
- {/* Results list */}
- <CommandPrimitive.List className="max-h-[min(400px,50vh)] overflow-y-auto overflow-x-hidden">
- {/* Pages section — only shown when query matches */}
- {filteredPages.length > 0 && (
- <CommandPrimitive.Group
- heading={t(($) => $.groups.pages)}
- className={GROUP_CLASS}
- >
- {filteredPages.map((page) => {
- const PageIcon = routeIconForPath(p[page.key]());
- return (
- <CommandPrimitive.Item
- key={page.key}
- value={`page:${page.key}`}
- onSelect={() => handlePageSelect(page.key)}
- className="flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
- >
- <PageIcon className="size-4 shrink-0 text-muted-foreground" />
- <span className="truncate">
- <HighlightText text={page.label} query={query} />
- </span>
- </CommandPrimitive.Item>
- );
- })}
- </CommandPrimitive.Group>
- )}
-
- {/* Commands section — New Issue / New Project / Copy link / Theme, only shown when query matches */}
- {filteredCommands.length > 0 && (
- <CommandPrimitive.Group
- heading={t(($) => $.groups.commands)}
- className={GROUP_CLASS}
- >
- {filteredCommands.map((cmd) => (
- <CommandPrimitive.Item
- key={cmd.key}
- value={`command:${cmd.key}`}
- onSelect={cmd.onSelect}
- className="flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
- >
- <cmd.icon className="size-4 shrink-0 text-muted-foreground" />
- <span className="truncate">
- <HighlightText text={cmd.label} query={query} />
- </span>
- {cmd.trailing}
- </CommandPrimitive.Item>
- ))}
- </CommandPrimitive.Group>
- )}
-
- {filteredMembers.length > 0 && (
- <CommandPrimitive.Group
- heading={t(($) => $.groups.members)}
- className={GROUP_CLASS}
- >
- {filteredMembers.map((member) => (
- <CommandPrimitive.Item
- key={member.user_id}
- value={`member:${member.user_id}`}
- onSelect={() => handleMemberSelect(member.user_id)}
- className="flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
- >
- <ActorAvatarBase
- name={member.name}
- initials={memberInitials(member.name)}
- avatarUrl={resolvePublicFileUrl(member.avatar_url)}
- size="md"
- />
- <div className="min-w-0 flex-1">
- <div className="truncate">
- <HighlightText text={member.name} query={query} />
- </div>
- <div className="truncate text-caption text-muted-foreground">
- <HighlightText text={member.email} query={query} />
- </div>
- </div>
- </CommandPrimitive.Item>
- ))}
- </CommandPrimitive.Group>
- )}
-
- {filteredWorkspaces.length > 0 && (
- <CommandPrimitive.Group
- heading={t(($) => $.groups.workspaces)}
- className={GROUP_CLASS}
- >
- {filteredWorkspaces.map((ws) => (
- <CommandPrimitive.Item
- key={ws.id}
- value={`workspace:${ws.id}`}
- onSelect={() => handleWorkspaceSelect(ws.slug)}
- className="flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
- >
- <WorkspaceAvatar name={ws.name} avatarUrl={ws.avatar_url} size="sm" />
- <span className="min-w-0 flex-1 truncate">
- <HighlightText text={ws.name} query={query} />
- </span>
- {/* Same dot the sidebar switcher puts on a workspace with
- unread inbox items. */}
- {unreadWsIds.has(ws.id) && (
- <span
- data-testid="workspace-unread-dot"
- className="size-2 shrink-0 rounded-full bg-brand"
- />
- )}
- </CommandPrimitive.Item>
- ))}
- </CommandPrimitive.Group>
- )}
-
- {/*
- Spinner only while there is nothing to look at. isLoading flips
- on the keystroke, before the 300ms debounce even fires, so
- swapping the whole result list for a spinner on every character
- made the list strobe while typing. Keeping the previous query's
- rows until the next response lands is the standard trade: they
- are one keystroke stale for a moment, instead of gone.
- */}
- {isLoading && !hasResults && (
- <div className="flex items-center justify-center py-10">
- <Loader2 className="size-5 animate-spin text-muted-foreground" />
- </div>
- )}
-
- {!isLoading &&
- query.trim() &&
- !hasResults &&
- filteredPages.length === 0 &&
- filteredCommands.length === 0 && (
- <CommandPrimitive.Empty className="py-10 text-center text-body text-muted-foreground">
- {t(($) => $.empty.no_results)}
- </CommandPrimitive.Empty>
- )}
-
- {/*
- Render order is the cross-type cancelled partition (MUL-5824):
- live projects → live issues → one trailing Cancelled section
- holding cancelled projects then cancelled issues. Projects and
- issues arrive as two independently ranked responses, so per-type
- ordering is not enough — the whole Projects group used to render
- above the whole Issues group, letting one cancelled project be the
- first row of the list. Keeping cancelled rows in a single trailing
- section is the only arrangement where no cancelled row of either
- type can precede a live row of the other. Direct hits stay in
- their live section (see partitionAggregatedSearchResults).
- */}
- {partitionedResults.liveProjects.length > 0 && (
- <CommandPrimitive.Group
- heading={t(($) => $.groups.projects)}
- className={GROUP_CLASS}
- >
- {partitionedResults.liveProjects.map((project) => (
- <ProjectResultRow
- key={`project:${project.id}`}
- project={project}
- query={results.query}
- disabled={resultsAreStale}
- onSelect={handleSelect}
- />
- ))}
- </CommandPrimitive.Group>
- )}
-
- {partitionedResults.liveIssues.length > 0 && (
- <CommandPrimitive.Group
- heading={t(($) => $.groups.issues)}
- className={GROUP_CLASS}
- >
- {partitionedResults.liveIssues.map((issue) => (
- <IssueResultRow
- key={issue.id}
- issue={issue}
- query={results.query}
- disabled={resultsAreStale}
- onSelect={handleSelect}
- />
- ))}
- </CommandPrimitive.Group>
- )}
-
- {partitionedResults.hasCancelled && (
- <CommandPrimitive.Group
- heading={t(($) => $.groups.cancelled)}
- className={GROUP_CLASS}
- >
- {partitionedResults.cancelledProjects.map((project) => (
- <ProjectResultRow
- key={`project:${project.id}`}
- project={project}
- query={results.query}
- disabled={resultsAreStale}
- onSelect={handleSelect}
- />
- ))}
- {partitionedResults.cancelledIssues.map((issue) => (
- <IssueResultRow
- key={issue.id}
- issue={issue}
- query={results.query}
- disabled={resultsAreStale}
- onSelect={handleSelect}
- />
- ))}
- </CommandPrimitive.Group>
- )}
-
- {!query.trim() && recentIssues.length > 0 && (
- <CommandPrimitive.Group
- heading={
- <>
- <Clock className="size-3" />
- <span>{t(($) => $.groups.recent)}</span>
- </>
- }
- className={`${GROUP_CLASS} [&_[cmdk-group-heading]]:flex [&_[cmdk-group-heading]]:items-center [&_[cmdk-group-heading]]:gap-2`}
- >
- {recentIssues.map((item) => (
- <CommandPrimitive.Item
- key={item.id}
- value={item.id}
- onSelect={handleSelect}
- className="flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
- >
- <StatusIcon
- status={item.status}
- color={colorOf(item.status)}
- icon={iconOf(item.status)}
- category={issueStatusCategory(item) ?? undefined}
- className="size-4 shrink-0"
- />
- <span className="text-caption text-muted-foreground shrink-0">
- {item.identifier}
- </span>
- <span className="min-w-0 flex-1 truncate">{item.title}</span>
- <IssueAssigneeAvatar
- assigneeType={item.assignee_type}
- assigneeId={item.assignee_id}
- />
- </CommandPrimitive.Item>
- ))}
- </CommandPrimitive.Group>
- )}
+ <div className="flex items-center gap-2 border-b px-4 py-3">
+ {delegate ? (
+ <Sparkles className="size-4 shrink-0 text-brand" aria-hidden="true" />
+ ) : (
+ <SearchIcon className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ )}
+ {current && (
+ <nav aria-label={t(($) => $.breadcrumb_aria)} className="flex min-w-0 shrink items-center gap-1">
+ {current.crumbs.map((crumb, index) => (
+ <Fragment key={`${index}:${crumb}`}>
+ {index > 0 && <ChevronRight className="size-3 shrink-0 text-muted-foreground" />}
+ <span className="max-w-40 truncate rounded-md bg-muted px-1.5 py-0.5 text-caption font-medium">
+ {crumb}
+ </span>
+ </Fragment>
+ ))}
+ </nav>
+ )}
+ <CommandPrimitive.Input
+ autoFocus
+ placeholder={current ? t(($) => $.page_placeholder) : t(($) => $.placeholder)}
+ value={inputValue}
+ onValueChange={(value) => (current ? setPageQuery(value) : setRawQuery(value))}
+ onKeyDown={handleKeyDown}
+ // The input remounts when a page opens or closes; keep the caret
+ // after text carried across.
+ onFocus={(e) => {
+ const end = e.currentTarget.value.length;
+ e.currentTarget.setSelectionRange(end, end);
+ }}
+ className="min-w-0 flex-1 bg-transparent text-body outline-none placeholder:text-muted-foreground"
+ />
+ {delegate && (
+ <span className="hidden shrink-0 items-center gap-1 rounded-md border px-1.5 py-0.5 text-caption text-muted-foreground sm:inline-flex">
+ <Sparkles className="size-3" aria-hidden="true" />
+ {t(($) => $.delegate.detected)}
+ </span>
+ )}
+ <ShortcutKeycaps shortcut={ESCAPE} className="hidden shrink-0 sm:inline-flex" />
+ </div>
- {!isLoading && !query.trim() && recentIssues.length === 0 && (
- <div className="px-5 py-4 text-center text-caption text-muted-foreground">
- {t(($) => $.empty.type_to_search)}
- </div>
- )}
- </CommandPrimitive.List>
- </CommandPrimitive>
- </DialogContent>
- </Dialog>
+ <CommandPrimitive.List className="max-h-[min(440px,55vh)] overflow-y-auto overflow-x-hidden py-1">
+ {current ? (
+ <PageView page={current.page} query={pageQuery} onDelegate={onDelegate} />
+ ) : (
+ <RootView model={model} rawQuery={rawQuery} onDelegate={onDelegate} />
+ )}
+ </CommandPrimitive.List>
+
+ <PaletteFooter
+ mode={current ? "page" : delegate ? "delegate" : "root"}
+ delegateName={delegate?.actor.name}
+ />
+ </CommandPrimitive>
+ </>
);
}
diff --git a/packages/views/search/types.ts b/packages/views/search/types.ts
new file mode 100644
index 0000000000..54032305ef
--- /dev/null
+++ b/packages/views/search/types.ts
@@ -0,0 +1,68 @@
+import type { ComponentType, ReactNode } from "react";
+import type { ShortcutChord } from "@multica/core/shortcuts";
+import type { Agent, ChatSession, Issue, Project, Squad } from "@multica/core/types";
+
+/** The issues an issue command acts on: the open issue, or a list selection. */
+export type IssueTarget =
+ | { kind: "single"; issue: Issue }
+ | { kind: "batch"; issues: Issue[]; clearSelection: () => void };
+
+export type DelegateActor =
+ | { type: "agent"; id: string; name: string; agent: Agent }
+ | { type: "squad"; id: string; name: string; squad: Squad };
+
+/** A submenu the palette can push onto its page stack. */
+export type PalettePage =
+ | { type: "issue-status"; target: IssueTarget }
+ | { type: "issue-assignee"; target: IssueTarget }
+ | { type: "issue-priority"; target: IssueTarget }
+ | { type: "issue-labels"; target: IssueTarget }
+ | { type: "issue-due-date"; target: IssueTarget }
+ | { type: "issue-project"; target: IssueTarget }
+ | { type: "issue-parent"; target: IssueTarget }
+ | { type: "issue-quick-action"; issue: Issue }
+ | { type: "theme" }
+ | { type: "project-status"; project: Project }
+ | { type: "agent-assign-issue"; agent: Agent }
+ | { type: "chat-project"; session: ChatSession; changeProject: (projectId: string | null) => void }
+ | { type: "delegate-target"; prompt: string };
+
+export interface PaletteStackEntry {
+ page: PalettePage;
+ /** Breadcrumb segments shown above the input, e.g. ["MUL-12", "Assign to"]. */
+ crumbs: string[];
+}
+
+export type PaletteIcon = ComponentType<{ className?: string }>;
+
+export interface PaletteCommand {
+ id: string;
+ label: string;
+ icon: PaletteIcon;
+ /** Hidden aliases, prefix-matched. */
+ keywords?: string[];
+ shortcut?: ShortcutChord | null;
+ /** Muted text on the right, e.g. "3 available". */
+ hint?: string;
+ trailing?: ReactNode;
+ /** Opens a submenu instead of running. */
+ page?: PalettePage;
+ /** Breadcrumb subject for `page`, e.g. the issue identifier. */
+ crumb?: string;
+ run?: () => void;
+ /** Shown in the empty state; the rest appear once the user types. */
+ primary?: boolean;
+ destructive?: boolean;
+}
+
+export interface PaletteCommandGroup {
+ id: string;
+ heading: ReactNode;
+ commands: PaletteCommand[];
+}
+
+/** Dialogs the palette opens after it closes itself. */
+export type PaletteHostDialog =
+ | { type: "cancel-run"; issueId: string; taskId: string; running: boolean }
+ | { type: "batch-delete"; issues: Issue[]; clearSelection: () => void }
+ | { type: "new-autopilot" };
diff --git a/packages/views/search/use-actor-directory.ts b/packages/views/search/use-actor-directory.ts
new file mode 100644
index 0000000000..26f1172e7d
--- /dev/null
+++ b/packages/views/search/use-actor-directory.ts
@@ -0,0 +1,78 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { isAgentRuntimeBound, useWorkspacePresenceMap, type AgentAvailability } from "@multica/core/agents";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { canAssignAgentToIssue, useCurrentMember } from "@multica/core/permissions";
+import { runtimeDisplayLabel, runtimeListOptions } from "@multica/core/runtimes";
+import {
+ agentListOptions,
+ memberListOptions,
+ squadListOptions,
+} from "@multica/core/workspace/queries";
+import type { Agent, MemberWithUser, Squad } from "@multica/core/types";
+
+export interface AgentEntry {
+ agent: Agent;
+ /** Whether the viewer may hand this agent work right now. */
+ assignable: boolean;
+ /** Why not, when the permission rule says no; runtime problems are `runtimeBound`. */
+ deniedReason: string | null;
+ runtimeBound: boolean;
+ availability: AgentAvailability | null;
+ runtimeLabel: string | null;
+}
+
+export interface SquadEntry {
+ squad: Squad;
+ /** A squad runs through its leader, so it is runnable when the leader is. */
+ runnable: boolean;
+}
+
+const EMPTY_AGENTS: Agent[] = [];
+const EMPTY_SQUADS: Squad[] = [];
+const EMPTY_MEMBERS: MemberWithUser[] = [];
+
+/**
+ * Agents, squads and members as the palette shows them: archived ones out,
+ * each agent annotated with whether the viewer can assign it and where it
+ * runs. One pass shared by search, the assignee submenu and delegation.
+ */
+export function useActorDirectory(enabled: boolean) {
+ const wsId = useWorkspaceId();
+ const { userId, role } = useCurrentMember(wsId);
+ const { data: agentsData = EMPTY_AGENTS } = useQuery({ ...agentListOptions(wsId), enabled });
+ const { data: squadsData = EMPTY_SQUADS } = useQuery({ ...squadListOptions(wsId), enabled });
+ const { data: members = EMPTY_MEMBERS } = useQuery({ ...memberListOptions(wsId), enabled });
+ const { data: runtimes } = useQuery({ ...runtimeListOptions(wsId), enabled });
+ const { byAgent } = useWorkspacePresenceMap(enabled ? wsId : undefined);
+
+ const agents = useMemo<AgentEntry[]>(() => {
+ const runtimeById = new Map((runtimes ?? []).map((runtime) => [runtime.id, runtime]));
+ return agentsData
+ .filter((agent) => !agent.archived_at)
+ .map((agent) => {
+ const decision = canAssignAgentToIssue(agent, { userId, role });
+ const runtimeBound = isAgentRuntimeBound(agent);
+ const runtime = agent.runtime_id ? runtimeById.get(agent.runtime_id) : undefined;
+ return {
+ agent,
+ assignable: decision.allowed && runtimeBound,
+ deniedReason: decision.allowed ? null : decision.message ?? null,
+ runtimeBound,
+ availability: byAgent.get(agent.id)?.availability ?? null,
+ runtimeLabel: runtime ? runtimeDisplayLabel(runtime) : null,
+ };
+ });
+ }, [agentsData, byAgent, role, runtimes, userId]);
+
+ const squads = useMemo<SquadEntry[]>(() => {
+ const runnable = new Set(agents.filter((entry) => entry.runtimeBound).map((entry) => entry.agent.id));
+ return squadsData
+ .filter((squad) => !squad.archived_at)
+ .map((squad) => ({ squad, runnable: runnable.has(squad.leader_id) }));
+ }, [agents, squadsData]);
+
+ return useMemo(() => ({ agents, squads, members }), [agents, squads, members]);
+}
diff --git a/packages/views/search/use-object-search.ts b/packages/views/search/use-object-search.ts
new file mode 100644
index 0000000000..6a0f974606
--- /dev/null
+++ b/packages/views/search/use-object-search.ts
@@ -0,0 +1,108 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { autopilotListOptions } from "@multica/core/autopilots/queries";
+import { chatSessionsOptions } from "@multica/core/chat/queries";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { skillListOptions, workspaceListOptions } from "@multica/core/workspace/queries";
+import type {
+ Autopilot,
+ ChatSession,
+ MemberWithUser,
+ SkillSummary,
+ Workspace,
+} from "@multica/core/types";
+import { scoreRow, scoreText } from "./matching";
+import { useActorDirectory, type AgentEntry, type SquadEntry } from "./use-actor-directory";
+
+export interface Scored<T> {
+ item: T;
+ score: number;
+}
+
+export interface ObjectHits {
+ agents: Scored<AgentEntry>[];
+ squads: Scored<SquadEntry>[];
+ members: Scored<MemberWithUser>[];
+ autopilots: Scored<Autopilot>[];
+ chats: Scored<ChatSession>[];
+ skills: Scored<SkillSummary>[];
+ workspaces: Scored<Workspace>[];
+}
+
+const EMPTY_AUTOPILOTS: Autopilot[] = [];
+const EMPTY_CHATS: ChatSession[] = [];
+const EMPTY_SKILLS: SkillSummary[] = [];
+const EMPTY_WORKSPACES: Workspace[] = [];
+
+// Hidden aliases for the Workspaces group, prefix-matched like page keywords:
+// typing "workspace" lists every workspace the user can switch to.
+const WORKSPACE_KEYWORDS = ["switch", "workspace"];
+const ALL_MEMBERS_WORDS = ["members", "people", "users", "team"];
+
+function rank<T>(items: readonly T[], score: (item: T) => number, limit: number): Scored<T>[] {
+ return items
+ .map((item) => ({ item, score: score(item) }))
+ .filter((entry) => entry.score > 0)
+ .sort((a, b) => b.score - a.score)
+ .slice(0, limit);
+}
+
+function memberScore(member: MemberWithUser, query: string): number {
+ const byName = scoreText(member.name, query);
+ if (byName > 0) return byName;
+ if (member.email.toLowerCase().includes(query)) return 40;
+ if (query.length >= 3 && member.role.startsWith(query)) return 25;
+ if (query.length >= 3 && ALL_MEMBERS_WORDS.some((word) => word.startsWith(query))) return 20;
+ return 0;
+}
+
+/**
+ * Client-side search over the workspace lists the app already caches. Lists
+ * the palette does not otherwise need (autopilots, chats, skills) load only
+ * once the user types.
+ */
+export function useObjectSearch(query: string, open: boolean): ObjectHits & { directory: ReturnType<typeof useActorDirectory> } {
+ const wsId = useWorkspaceId();
+ const directory = useActorDirectory(open);
+ const typing = open && query.length > 0;
+ const { data: autopilots = EMPTY_AUTOPILOTS } = useQuery({ ...autopilotListOptions(wsId), enabled: typing });
+ const { data: chats = EMPTY_CHATS } = useQuery({ ...chatSessionsOptions(wsId), enabled: typing });
+ const { data: skills = EMPTY_SKILLS } = useQuery({ ...skillListOptions(wsId), enabled: typing });
+ // Account-level cache entry the sidebar's workspace switcher already
+ // holds, so the Workspaces group adds no request of its own.
+ const { data: workspaces = EMPTY_WORKSPACES } = useQuery(workspaceListOptions());
+
+ const hits = useMemo<ObjectHits>(() => {
+ if (!query) {
+ return { agents: [], squads: [], members: [], autopilots: [], chats: [], skills: [], workspaces: [] };
+ }
+ return {
+ agents: rank(directory.agents, (e) => scoreText(e.agent.name, query), 8),
+ squads: rank(directory.squads, (e) => scoreText(e.squad.name, query), 5),
+ members: rank(directory.members, (m) => memberScore(m, query), 10),
+ autopilots: rank(
+ autopilots.filter((a) => a.status !== "archived"),
+ (a) => scoreText(a.title, query),
+ 5,
+ ),
+ chats: rank(
+ chats.filter((c) => c.status !== "archived"),
+ (c) => scoreText(c.title, query),
+ 5,
+ ),
+ skills: rank(skills, (s) => scoreText(s.name, query), 5),
+ // The current workspace is never a switch target, so a single-workspace
+ // user never sees the group. Ties keep the server's created_at order,
+ // the same order as the sidebar switcher.
+ workspaces: rank(
+ workspaces.filter((ws) => ws.id !== wsId),
+ (ws) => Math.max(scoreRow(ws.name, WORKSPACE_KEYWORDS, query), ws.slug.toLowerCase().includes(query) ? 40 : 0),
+ 50,
+ ),
+ };
+ }, [autopilots, chats, directory, query, skills, workspaces, wsId]);
+
+ return { ...hits, directory };
+}
diff --git a/packages/views/search/use-recent-items.ts b/packages/views/search/use-recent-items.ts
new file mode 100644
index 0000000000..7851381120
--- /dev/null
+++ b/packages/views/search/use-recent-items.ts
@@ -0,0 +1,70 @@
+"use client";
+
+import { useMemo } from "react";
+import { useQueries, useQuery } from "@tanstack/react-query";
+import { autopilotListOptions } from "@multica/core/autopilots/queries";
+import { selectRecentVisits, useRecentVisitsStore } from "@multica/core/command-bar";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { issueDetailOptions } from "@multica/core/issues/queries";
+import { selectRecentIssues, useRecentIssuesStore } from "@multica/core/issues/stores";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import type { Agent, Autopilot, Issue, Project } from "@multica/core/types";
+
+export type RecentItem =
+ | { type: "issue"; id: string; visitedAt: number; issue: Issue }
+ | { type: "project"; id: string; visitedAt: number; project: Project }
+ | { type: "agent"; id: string; visitedAt: number; agent: Agent }
+ | { type: "autopilot"; id: string; visitedAt: number; autopilot: Autopilot };
+
+const MAX_RECENT = 8;
+
+/**
+ * Recently opened issues, projects, agents and autopilots, newest first.
+ * Everything is gated on `open`: the palette is mounted for the whole
+ * session, and an ungated lookup fired up to 20 issue detail requests on every
+ * cold app load for a surface the user may never open.
+ */
+export function useRecentItems(open: boolean): RecentItem[] {
+ const wsId = useWorkspaceId();
+ const recentIssues = useRecentIssuesStore(selectRecentIssues(wsId));
+ const recentVisits = useRecentVisitsStore(selectRecentVisits(wsId));
+
+ // Resolve each recent issue via its cached detail entry. Recent items are
+ // typically already in the detail cache because the user has opened them;
+ // if not, this triggers a lookup per id so Recent never depends on whether
+ // the issue falls inside the paginated list cache.
+ const issueQueries = useQueries({
+ queries: open ? recentIssues.map((item) => issueDetailOptions(wsId, item.id)) : [],
+ });
+ const wants = (type: string) => open && recentVisits.some((v) => v.type === type);
+ const { data: projects } = useQuery({ ...projectListOptions(wsId), enabled: wants("project") });
+ const { data: agents } = useQuery({ ...agentListOptions(wsId), enabled: wants("agent") });
+ const { data: autopilots } = useQuery({ ...autopilotListOptions(wsId), enabled: wants("autopilot") });
+
+ return useMemo(() => {
+ if (!open) return [];
+ const items: RecentItem[] = [];
+ recentIssues.forEach((entry, index) => {
+ const issue = issueQueries[index]?.data;
+ if (issue) items.push({ type: "issue", id: issue.id, visitedAt: entry.visitedAt, issue });
+ });
+ for (const visit of recentVisits) {
+ if (visit.type === "project") {
+ const project = projects?.find((p) => p.id === visit.id);
+ if (project) items.push({ type: "project", id: project.id, visitedAt: visit.visitedAt, project });
+ } else if (visit.type === "agent") {
+ const agent = agents?.find((a) => a.id === visit.id);
+ if (agent && !agent.archived_at) {
+ items.push({ type: "agent", id: agent.id, visitedAt: visit.visitedAt, agent });
+ }
+ } else {
+ const autopilot = autopilots?.find((a) => a.id === visit.id);
+ if (autopilot && autopilot.status !== "archived") {
+ items.push({ type: "autopilot", id: autopilot.id, visitedAt: visit.visitedAt, autopilot });
+ }
+ }
+ }
+ return items.sort((a, b) => b.visitedAt - a.visitedAt).slice(0, MAX_RECENT);
+ }, [agents, autopilots, issueQueries, open, projects, recentIssues, recentVisits]);
+}
diff --git a/packages/views/search/use-root-model.ts b/packages/views/search/use-root-model.ts
new file mode 100644
index 0000000000..dd7434bfd7
--- /dev/null
+++ b/packages/views/search/use-root-model.ts
@@ -0,0 +1,350 @@
+"use client";
+
+import { useMemo } from "react";
+import type { CommandBarContext } from "@multica/core/command-bar";
+import { WORKSPACE_PAGES, type WorkspacePageKey } from "@multica/core/paths";
+import { partitionAggregatedSearchResults } from "@multica/core/search/cancelled-rank";
+import type { SearchIssueResult, SearchProjectResult } from "@multica/core/types";
+import { useT } from "../i18n";
+import { useAgentCommandGroup, useAutopilotCommandGroup, useChatCommandGroup, useInboxCommandGroup, useProjectCommandGroup } from "./commands/context-commands";
+import { useGlobalCommands } from "./commands/global-commands";
+import { useIssueCommandGroup } from "./commands/issue-commands";
+import { detectInstruction, type NamedActor } from "./delegate/detect-instruction";
+import { useDelegateAttachments, useDelegateCandidates, type DelegateAttachments } from "./delegate/use-delegate";
+import { parseScope, scoreRow, scoreText, type SearchScope } from "./matching";
+import type { DelegateActor, IssueTarget, PaletteCommand, PaletteCommandGroup } from "./types";
+import type { AgentEntry } from "./use-actor-directory";
+import { useObjectSearch, type ObjectHits, type Scored } from "./use-object-search";
+import { useRecentItems, type RecentItem } from "./use-recent-items";
+import { useServerSearch, type SearchResults } from "./use-server-search";
+
+// The palette's Pages group is generated from WORKSPACE_PAGES, the same
+// registry the sidebar nav and the desktop tab bar read. It used to be a
+// hand-written list, which silently went stale every time a page was added:
+// Chat, Autopilot, Squads and Analytics shipped in the sidebar but were
+// unreachable from the palette (MUL-6272). Deriving the list means a new
+// workspace page is in the palette the moment it is in the registry.
+//
+// Page keys double as WorkspacePaths method names, so `p[key]()` resolves the
+// destination against the current workspace slug at render time. Every
+// WorkspacePageKey must therefore stay a parameterless path builder.
+
+// Extra query aliases per page, on top of the localized label. Declared as a
+// total Record so adding a workspace page is a compile error until its
+// keywords are filled in.
+const PAGE_KEYWORDS: Record<WorkspacePageKey, string[]> = {
+ inbox: ["inbox", "notifications", "收件箱", "通知"],
+ chat: ["chat", "messages", "conversation", "聊天", "消息", "对话"],
+ myIssues: ["my", "issues", "assigned", "mine", "我的", "任务"],
+ issues: ["issues", "tasks", "bugs", "任务"],
+ projects: ["projects", "kanban", "项目"],
+ autopilots: ["autopilot", "autopilots", "automation", "schedule", "cron", "webhook", "自动化", "定时"],
+ agents: ["agents", "bots", "ai", "智能体"],
+ squads: ["squads", "teams", "小队", "团队"],
+ usage: ["usage", "analytics", "stats", "metrics", "统计", "分析", "用量"],
+ runtimes: ["runtimes", "environments", "machines", "运行时"],
+ skills: ["skills", "library", "技能"],
+ settings: ["settings", "config", "preferences", "设置", "配置"],
+};
+
+const NAV_PAGE_KEYS = Object.keys(WORKSPACE_PAGES) as WorkspacePageKey[];
+
+export interface NavPage {
+ key: WorkspacePageKey;
+ label: string;
+ keywords: string[];
+}
+
+export type BestMatch =
+ | { type: "agent"; entry: AgentEntry; score: number }
+ | { type: "squad"; entry: ObjectHits["squads"][number]["item"]; score: number }
+ | { type: "member"; member: ObjectHits["members"][number]["item"]; score: number }
+ | { type: "project"; project: SearchProjectResult; score: number };
+
+export interface DelegateModel {
+ prompt: string;
+ actor: DelegateActor;
+ agentEntry: AgentEntry | null;
+ attachments: DelegateAttachments;
+}
+
+export interface RootModel {
+ scope: SearchScope;
+ text: string;
+ /** Lower-cased `text`. */
+ q: string;
+ contextGroups: (PaletteCommandGroup & { score: number })[];
+ commands: Scored<PaletteCommand>[];
+ pages: Scored<NavPage>[];
+ objects: ObjectHits;
+ server: { results: SearchResults; isLoading: boolean; stale: boolean };
+ partitioned: ReturnType<typeof partitionAggregatedSearchResults>;
+ liveIssueScore: number;
+ liveProjectScore: number;
+ bestMatch: BestMatch | null;
+ recent: RecentItem[];
+ newCommands: PaletteCommand[];
+ delegate: DelegateModel | null;
+ /** The issue or selection that best-match actions such as "Assign … to" act on. */
+ primaryIssueTarget: IssueTarget | null;
+ /** Context a delegated issue is created with. */
+ attachments: DelegateAttachments;
+ hasResults: boolean;
+}
+
+// Server rows answer a query the client cannot re-score exactly (they may
+// have matched on a description or comment). A title hit scores like any
+// other row; a snippet-only hit ranks below every client-side match.
+const SERVER_ONLY_SCORE = 10;
+
+export function issueScore(issue: SearchIssueResult, q: string): number {
+ if (issue.identifier.toLowerCase() === q) return 100;
+ return Math.max(scoreText(issue.title, q), SERVER_ONLY_SCORE);
+}
+
+export function projectScore(project: SearchProjectResult, q: string): number {
+ return Math.max(scoreText(project.title, q), SERVER_ONLY_SCORE);
+}
+
+function maxScore(entries: readonly { score: number }[]) {
+ return entries.reduce((max, entry) => Math.max(max, entry.score), 0);
+}
+
+export function useRootModel(
+ rawQuery: string,
+ contexts: readonly CommandBarContext[],
+ options: { active: boolean; dismissedDelegateFor: string | null },
+): RootModel {
+ const { t: tNav } = useT("layout");
+ const { scope, text } = parseScope(rawQuery);
+ const q = text.toLowerCase();
+ const active = options.active;
+
+ // Context lookups by kind; the store keeps newest registration first.
+ const find = <K extends CommandBarContext["kind"]>(kind: K) =>
+ contexts.find((c): c is Extract<CommandBarContext, { kind: K }> => c.kind === kind) ?? null;
+ const issueContext = find("issue");
+ const issuesContext = find("issues");
+ const singleTarget = useMemo<IssueTarget | null>(
+ () => (issueContext ? { kind: "single", issue: issueContext.issue } : null),
+ [issueContext],
+ );
+ const batchTarget = useMemo<IssueTarget | null>(
+ () =>
+ issuesContext
+ ? { kind: "batch", issues: issuesContext.issues, clearSelection: issuesContext.clearSelection }
+ : null,
+ [issuesContext],
+ );
+
+ const singleGroup = useIssueCommandGroup(singleTarget, issueContext?.onDeletedFallbackPath);
+ const batchGroup = useIssueCommandGroup(batchTarget);
+ const projectGroup = useProjectCommandGroup(find("project"));
+ const agentGroup = useAgentCommandGroup(find("agent"));
+ const autopilotGroup = useAutopilotCommandGroup(find("autopilot"));
+ const inboxGroup = useInboxCommandGroup(find("inbox"));
+ const chatGroup = useChatCommandGroup(find("chat"));
+ const globalCommands = useGlobalCommands(contexts);
+
+ const searching = active && scope !== "commands" && scope !== "people" ? text : "";
+ const server = useServerSearch(searching, { projects: scope === "all" });
+ const objects = useObjectSearch(scope === "issues" || scope === "commands" ? "" : q, active);
+ const recent = useRecentItems(active && !rawQuery.trim());
+ const delegateCandidates = useDelegateCandidates(active);
+ const attachments = useDelegateAttachments(contexts);
+
+ const navPages = useMemo<NavPage[]>(
+ () =>
+ NAV_PAGE_KEYS.map((key) => ({
+ key,
+ label: tNav(($) => $.nav[WORKSPACE_PAGES[key].navKey]),
+ keywords: PAGE_KEYWORDS[key],
+ })),
+ [tNav],
+ );
+
+ return useMemo<RootModel>(() => {
+ const groupByKind: Record<string, PaletteCommandGroup | null> = {
+ issue: singleGroup,
+ issues: batchGroup,
+ project: projectGroup,
+ agent: agentGroup,
+ autopilot: autopilotGroup,
+ inbox: inboxGroup,
+ chat: chatGroup,
+ };
+ const orderedGroups = contexts
+ .map((c) => groupByKind[c.kind])
+ .filter((group, index, all): group is PaletteCommandGroup => !!group && all.indexOf(group) === index);
+
+ const commandsAllowed = scope === "all" || scope === "commands";
+ let contextGroups: RootModel["contextGroups"] = [];
+ let commands: Scored<PaletteCommand>[] = [];
+ let pages: Scored<NavPage>[] = [];
+ if (!q) {
+ if (scope === "all") {
+ contextGroups = orderedGroups
+ .map((group) => ({ ...group, commands: group.commands.filter((c) => c.primary), score: 0 }))
+ .filter((group) => group.commands.length > 0);
+ } else if (scope === "commands") {
+ contextGroups = orderedGroups.map((group) => ({ ...group, score: 0 }));
+ commands = globalCommands.map((command) => ({ item: command, score: 0 }));
+ }
+ } else if (commandsAllowed) {
+ const rank = (list: PaletteCommand[]) =>
+ list
+ .map((command) => ({ item: command, score: scoreRow(command.label, command.keywords ?? [], q) }))
+ .filter((entry) => entry.score > 0)
+ .sort((a, b) => b.score - a.score);
+ contextGroups = orderedGroups
+ .map((group) => {
+ const ranked = rank(group.commands);
+ return { ...group, commands: ranked.map((r) => r.item), score: maxScore(ranked) };
+ })
+ .filter((group) => group.commands.length > 0);
+ commands = rank(globalCommands);
+ pages = navPages
+ .map((page) => ({ item: page, score: scoreRow(page.label, page.keywords, q) }))
+ .filter((entry) => entry.score > 0)
+ .sort((a, b) => b.score - a.score);
+ }
+
+ const { results, isLoading, stale } = server;
+ // The partition describes these rows, so it keys off the query they
+ // answer — not what the user has typed since.
+ const partitioned = partitionAggregatedSearchResults({
+ issues: results.issues,
+ projects: scope === "all" ? results.projects : [],
+ query: results.query,
+ });
+ const resultsQ = results.query.toLowerCase();
+ const liveIssueScore = partitioned.liveIssues.reduce((max, issue) => Math.max(max, issueScore(issue, resultsQ)), 0);
+ const liveProjectScore = partitioned.liveProjects.reduce(
+ (max, project) => Math.max(max, projectScore(project, resultsQ)),
+ 0,
+ );
+
+ const people = scope === "all" || scope === "people";
+ const visibleObjects: ObjectHits = {
+ agents: people ? objects.agents : [],
+ squads: people ? objects.squads : [],
+ members: people ? objects.members : [],
+ autopilots: scope === "all" ? objects.autopilots : [],
+ chats: scope === "all" ? objects.chats : [],
+ skills: scope === "all" ? objects.skills : [],
+ workspaces: scope === "all" ? objects.workspaces : [],
+ };
+
+ // Best match: a top hit worth acting on directly ("Assign MUL-1 to
+ // Lambda", "Chat with Lambda") is lifted above everything, actions under
+ // it. Only prefix-or-better hits qualify; a substring hit is a guess.
+ let bestMatch: BestMatch | null = null;
+ if (q && scope === "all") {
+ const candidates: BestMatch[] = [];
+ const agent = visibleObjects.agents[0];
+ if (agent) candidates.push({ type: "agent", entry: agent.item, score: agent.score });
+ const squad = visibleObjects.squads[0];
+ if (squad) candidates.push({ type: "squad", entry: squad.item, score: squad.score });
+ const member = visibleObjects.members[0];
+ if (member) candidates.push({ type: "member", member: member.item, score: member.score });
+ if (!stale) {
+ const project = partitioned.liveProjects.find((p) => scoreText(p.title, resultsQ) >= 80);
+ if (project) candidates.push({ type: "project", project, score: scoreText(project.title, resultsQ) });
+ }
+ const top = candidates.sort((a, b) => b.score - a.score)[0];
+ if (top && top.score >= 80 && top.score >= liveIssueScore) bestMatch = top;
+ }
+
+ const objectCount =
+ visibleObjects.agents.length +
+ visibleObjects.squads.length +
+ visibleObjects.members.length +
+ visibleObjects.autopilots.length +
+ visibleObjects.chats.length +
+ visibleObjects.skills.length +
+ visibleObjects.workspaces.length;
+ const hasResults =
+ objectCount > 0 ||
+ results.issues.length > 0 ||
+ results.projects.length > 0 ||
+ pages.length > 0 ||
+ commands.length > 0 ||
+ contextGroups.length > 0;
+
+ let delegate: DelegateModel | null = null;
+ if (q && scope === "all" && options.dismissedDelegateFor !== rawQuery) {
+ const named: NamedActor[] = delegateCandidates.actors.map((actor) => ({
+ type: actor.type,
+ id: actor.id,
+ name: actor.name,
+ }));
+ const detected = detectInstruction(text, named, {
+ hasResults: objectCount > 0 || results.issues.length > 0 || results.projects.length > 0,
+ resultsSettled: !isLoading && !stale,
+ });
+ const actor = detected?.actor
+ ? (delegateCandidates.actors.find((a) => a.type === detected.actor!.type && a.id === detected.actor!.id) ?? null)
+ : delegateCandidates.fallback;
+ if (detected && actor) {
+ delegate = {
+ prompt: text,
+ actor,
+ agentEntry:
+ actor.type === "agent"
+ ? (delegateCandidates.agentEntries.find((entry) => entry.agent.id === actor.id) ?? null)
+ : null,
+ attachments,
+ };
+ }
+ }
+
+ const primaryIssueTarget =
+ contexts
+ .map((c) => (c.kind === "issue" ? singleTarget : c.kind === "issues" ? batchTarget : null))
+ .find((target): target is IssueTarget => !!target) ?? null;
+
+ return {
+ scope,
+ text,
+ q,
+ contextGroups,
+ commands,
+ pages,
+ objects: visibleObjects,
+ server,
+ partitioned,
+ liveIssueScore,
+ liveProjectScore,
+ bestMatch,
+ recent,
+ newCommands: globalCommands.filter((command) => command.primary),
+ delegate,
+ primaryIssueTarget,
+ attachments,
+ hasResults,
+ };
+ }, [
+ agentGroup,
+ attachments,
+ autopilotGroup,
+ batchGroup,
+ batchTarget,
+ chatGroup,
+ contexts,
+ delegateCandidates,
+ globalCommands,
+ inboxGroup,
+ navPages,
+ objects,
+ options.dismissedDelegateFor,
+ projectGroup,
+ q,
+ rawQuery,
+ recent,
+ scope,
+ server,
+ singleGroup,
+ singleTarget,
+ text,
+ ]);
+}
diff --git a/packages/views/search/use-server-search.ts b/packages/views/search/use-server-search.ts
new file mode 100644
index 0000000000..7e5acdec65
--- /dev/null
+++ b/packages/views/search/use-server-search.ts
@@ -0,0 +1,88 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import type { SearchIssueResult, SearchProjectResult } from "@multica/core/types";
+import { isLocalSearchReady, searchIssues, searchProjects } from "@multica/core/search-index";
+
+export interface SearchResults {
+ /**
+ * The trimmed query these rows answer. Rows outlive the query that fetched
+ * them — they stay painted while the next request is in flight — so every
+ * result set carries the question it is the answer to, and anything that can
+ * act on a row checks that it still matches what the user typed.
+ */
+ query: string;
+ issues: SearchIssueResult[];
+ projects: SearchProjectResult[];
+}
+
+export const NO_RESULTS: SearchResults = { query: "", issues: [], projects: [] };
+
+/**
+ * Issue (and optionally project) search for the palette. An empty query
+ * clears the results without a request.
+ */
+export function useServerSearch(query: string, options: { projects: boolean }) {
+ const [results, setResults] = useState<SearchResults>(NO_RESULTS);
+ const [isLoading, setIsLoading] = useState(false);
+ const withProjects = options.projects;
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const abortRef = useRef<AbortController | null>(null);
+ const q = query.trim();
+
+ useEffect(() => {
+ if (debounceRef.current) clearTimeout(debounceRef.current);
+ if (abortRef.current) abortRef.current.abort();
+
+ if (!q) {
+ setResults(NO_RESULTS);
+ setIsLoading(false);
+ return;
+ }
+
+ setIsLoading(true);
+ // The debounce spares the server a request per keystroke; the local index
+ // answers in milliseconds, so it searches on every keystroke.
+ const delay = isLocalSearchReady() ? 0 : 300;
+ debounceRef.current = setTimeout(async () => {
+ const controller = new AbortController();
+ abortRef.current = controller;
+ try {
+ const [issueRes, projectRes] = await Promise.all([
+ searchIssues({ q, limit: 20, include_closed: true, signal: controller.signal }),
+ withProjects
+ ? searchProjects({ q, limit: 10, include_closed: true, signal: controller.signal })
+ : Promise.resolve({ projects: [] as SearchProjectResult[] }),
+ ]);
+ if (!controller.signal.aborted) {
+ setResults({ query: q, issues: issueRes.issues, projects: projectRes.projects });
+ setIsLoading(false);
+ }
+ } catch {
+ if (!controller.signal.aborted) {
+ // Drop the previous query's rows rather than leaving them on screen
+ // permanently greyed out: the request that would have replaced them
+ // is never coming. The list falls through to the empty state.
+ setResults({ query: q, issues: [], projects: [] });
+ setIsLoading(false);
+ }
+ }
+ }, delay);
+ }, [q, withProjects]);
+
+ useEffect(
+ () => () => {
+ if (debounceRef.current) clearTimeout(debounceRef.current);
+ if (abortRef.current) abortRef.current.abort();
+ },
+ [],
+ );
+
+ // Rows answering an earlier query are still painted while the next request
+ // is in flight — that is what keeps the list from strobing on every
+ // keystroke — but they must not be actionable: cmdk re-selects the first
+ // valid item whenever the input changes, so a live stale row turns the next
+ // Enter into a jump to a result the user has already typed past.
+ const stale = results.query !== q;
+ return { results, isLoading, stale };
+}