Skip to content

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

Go

MUL-8933: ⌘K hands to an agent through a fixed row instead of guessing (#10286)

Jiayuan Zhang8356a999f1e2
diff --git a/apps/docs/content/docs/shortcuts.fr.mdx b/apps/docs/content/docs/shortcuts.fr.mdx
index 3a558fc526..9cc02ac412 100644
--- a/apps/docs/content/docs/shortcuts.fr.mdx
+++ b/apps/docs/content/docs/shortcuts.fr.mdx
@@ -20,6 +20,7 @@ Appuyez sur `⌘K`, ou cliquez sur **Rechercher...** en haut de la barre latéra
| **Espaces de travail** | Vos autres espaces de travail ; en choisir un vous y fait passer. |
| **Projets**, **Tâches** | Correspondances dans les titres, mais aussi dans les descriptions de projets et de tâches et dans les commentaires. L'extrait trouvé s'affiche sous le résultat, et les tâches terminées sont incluses. |
| **Annulés** | Les projets et tâches annulés sont regroupés à la fin au lieu de se mêler au reste. |
+| **Confier à un agent** | Toujours la dernière ligne pendant la saisie. Elle ouvre **Créer avec un agent** avec ce que vous avez tapé, le projet courant et la tâche ouverte comme parente ; rien n'est créé avant votre confirmation. |
Choisir un résultat l'ouvre. Maintenez `⌘` (`Ctrl` sous Windows et Linux) en cliquant ou en appuyant sur Entrée pour l'ouvrir dans un nouvel onglet. `Échap` ferme la recherche.
diff --git a/apps/docs/content/docs/shortcuts.ja.mdx b/apps/docs/content/docs/shortcuts.ja.mdx
index 517aa24cad..8c7d8a719c 100644
--- a/apps/docs/content/docs/shortcuts.ja.mdx
+++ b/apps/docs/content/docs/shortcuts.ja.mdx
@@ -20,6 +20,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";
| **ワークスペース** | 参加しているほかのワークスペース。選ぶとそこへ切り替わります。 |
| **プロジェクト**、**タスク** | タイトルのほか、プロジェクトの説明、タスクの説明、コメントにも一致します。一致した箇所が結果の下に表示され、完了したタスクも含まれます。 |
| **キャンセル済み** | キャンセルされたプロジェクトとタスクは、ほかの結果に混ざらず最後にまとめて表示されます。 |
+| **エージェントに依頼** | 入力中は常に最後の行に表示されます。選ぶと**エージェントで作成**が開き、入力した内容と現在のプロジェクトが入り、開いているタスクが親タスクになります。そこで確定するまで何も作成されません。 |
結果を選ぶとそのページへ移動します。`⌘`(Windows / Linux では `Ctrl`)を押しながらクリックするか Enter を押すと、新しいタブで開きます。`Esc` で検索ボックスを閉じます。
diff --git a/apps/docs/content/docs/shortcuts.ko.mdx b/apps/docs/content/docs/shortcuts.ko.mdx
index a089daf69b..101be9670e 100644
--- a/apps/docs/content/docs/shortcuts.ko.mdx
+++ b/apps/docs/content/docs/shortcuts.ko.mdx
@@ -20,6 +20,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";
| **워크스페이스** | 내가 속한 다른 워크스페이스. 선택하면 그쪽으로 전환됩니다. |
| **프로젝트**, **태스크** | 제목뿐 아니라 프로젝트 설명, 태스크 설명, 댓글도 검색합니다. 일치한 부분이 결과 아래에 표시되고, 완료된 태스크도 포함됩니다. |
| **취소됨** | 취소된 프로젝트와 태스크는 다른 결과와 섞이지 않고 맨 끝에 모아서 표시됩니다. |
+| **에이전트에게 맡기기** | 입력하는 동안 항상 마지막 행에 표시됩니다. 선택하면 **에이전트로 만들기**가 열리고, 입력한 내용과 현재 프로젝트가 채워지며 열려 있는 태스크가 상위 태스크가 됩니다. 거기서 확인하기 전에는 아무것도 만들어지지 않습니다. |
결과를 선택하면 바로 이동합니다. `⌘`(Windows / Linux에서는 `Ctrl`)를 누른 채 클릭하거나 Enter를 누르면 새 탭에서 엽니다. `Esc`로 검색 창을 닫습니다.
diff --git a/apps/docs/content/docs/shortcuts.mdx b/apps/docs/content/docs/shortcuts.mdx
index d4734e0483..cb89db34b9 100644
--- a/apps/docs/content/docs/shortcuts.mdx
+++ b/apps/docs/content/docs/shortcuts.mdx
@@ -20,6 +20,7 @@ Press `⌘K`, or click **Search...** at the top of the sidebar. With nothing typ
| **Workspaces** | Other workspaces you belong to; selecting one switches to it. |
| **Projects**, **Issues** | Matches titles as well as project descriptions, issue descriptions, and comments. The matching snippet shows under the result, and done issues are included. |
| **Cancelled** | Cancelled projects and issues are grouped at the end instead of mixing in with the rest. |
+| **Hand to agent** | Always the last row while you type. It opens **Create with agent** with what you typed, the current project, and the open issue as parent; nothing is created until you confirm there. |
Selecting a result opens it. Hold `⌘` (`Ctrl` on Windows and Linux) while clicking or pressing Enter to open it in a new tab. `Esc` closes the search box.
diff --git a/apps/docs/content/docs/shortcuts.zh-Hant.mdx b/apps/docs/content/docs/shortcuts.zh-Hant.mdx
index 90b8647cab..5c0b04aace 100644
--- a/apps/docs/content/docs/shortcuts.zh-Hant.mdx
+++ b/apps/docs/content/docs/shortcuts.zh-Hant.mdx
@@ -20,6 +20,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";
| **工作區** | 你加入的其他工作區,選中後切換過去。 |
| **專案**、**任務** | 匹配標題,也匹配專案說明、任務描述和評論。命中的片段顯示在結果下方;已完成的任務也會出現。 |
| **已取消** | 已取消的專案和任務統一排在最後,不會擠到前面。 |
+| **交給 AI 代理** | 有輸入時固定顯示在最後一行。選中後開啟**透過 AI 代理建立**,預填你輸入的內容、目前專案,並把目前開啟的任務設為父任務;在彈窗裡確認後才會建立。 |
選中結果後直接跳轉。按住 `⌘`(Windows / Linux:`Ctrl`)再點選或按Enter,會在新標籤頁裡開啟。按 `Esc` 關閉搜尋框。
diff --git a/apps/docs/content/docs/shortcuts.zh.mdx b/apps/docs/content/docs/shortcuts.zh.mdx
index 409a5e7bde..803c8e76b7 100644
--- a/apps/docs/content/docs/shortcuts.zh.mdx
+++ b/apps/docs/content/docs/shortcuts.zh.mdx
@@ -20,6 +20,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";
| **工作区** | 你加入的其他工作区,选中后切换过去。 |
| **项目**、**任务** | 匹配标题,也匹配项目说明、任务描述和评论。命中的片段显示在结果下方;已完成的任务也会出现。 |
| **已取消** | 已取消的项目和任务统一排在最后,不会挤到前面。 |
+| **交给智能体** | 有输入时固定显示在最后一行。选中后打开**通过智能体创建**,预填你输入的内容、当前项目,并把当前打开的任务设为父任务;在弹窗里确认后才会创建。 |
选中结果后直接跳转。按住 `⌘`(Windows / Linux:`Ctrl`)再点击或按回车,会在新标签页里打开。按 `Esc` 关闭搜索框。
diff --git a/packages/views/locales/en/search.json b/packages/views/locales/en/search.json
index d51554b239..ac78ef92d9 100644
--- a/packages/views/locales/en/search.json
+++ b/packages/views/locales/en/search.json
@@ -136,14 +136,8 @@
"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"
+ "row": "Hand to agent: “{{prompt}}”",
+ "hint": "Quick create"
},
"best": {
"assign": "Assign {{subject}} to {{name}}",
@@ -162,8 +156,6 @@
"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",
diff --git a/packages/views/locales/es/search.json b/packages/views/locales/es/search.json
index a8a9ecd2b6..fe1cb4784f 100644
--- a/packages/views/locales/es/search.json
+++ b/packages/views/locales/es/search.json
@@ -139,14 +139,8 @@
"system": "Sistema"
},
"delegate": {
- "heading": "Encargar a un agente",
- "create_and_assign": "Nueva tarea y asignar a {{name}}",
- "squad": "Squad",
- "context_aria": "Creada con",
- "parent": "Bajo {{identifier}}",
- "pick_crumb": "Elegir",
- "pick_another": "Encargar a otro agente o squad...",
- "detected": "Instrucción"
+ "row": "Encargar a un agente: «{{prompt}}»",
+ "hint": "Creación rápida"
},
"best": {
"assign": "Asignar {{subject}} a {{name}}",
@@ -165,8 +159,6 @@
"navigate": "Navegar",
"select": "Selección",
"open_in_new_tab": "Abrir en una pestaña nueva",
- "delegate": "Crear y encargar a {{name}}",
- "search_instead": "Buscar como palabras clave",
"back": "Atrás",
"prefix_commands": "Comandos",
"prefix_issues": "Tareas",
diff --git a/packages/views/locales/fr/search.json b/packages/views/locales/fr/search.json
index bcd1681cbf..c8d2347894 100644
--- a/packages/views/locales/fr/search.json
+++ b/packages/views/locales/fr/search.json
@@ -136,14 +136,8 @@
"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"
+ "row": "Confier à un agent : « {{prompt}} »",
+ "hint": "Création rapide"
},
"best": {
"assign": "Assigner {{subject}} à {{name}}",
@@ -162,8 +156,6 @@
"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",
diff --git a/packages/views/locales/ja/search.json b/packages/views/locales/ja/search.json
index 6f3dd3e54b..a82273a951 100644
--- a/packages/views/locales/ja/search.json
+++ b/packages/views/locales/ja/search.json
@@ -133,14 +133,8 @@
"type_to_find_people": "入力してメンバーとエージェントを検索"
},
"delegate": {
- "heading": "エージェントに依頼",
- "create_and_assign": "タスクを作成して {{name}} に割り当て",
- "squad": "スクワッド",
- "context_aria": "添付するコンテキスト",
- "parent": "{{identifier}} の配下",
- "pick_crumb": "選択",
- "pick_another": "別のエージェントやスクワッドに依頼...",
- "detected": "指示として認識"
+ "row": "エージェントに依頼:「{{prompt}}」",
+ "hint": "クイック作成"
},
"best": {
"assign": "{{subject}} を {{name}} に割り当て",
@@ -159,8 +153,6 @@
"navigate": "選択",
"select": "実行",
"open_in_new_tab": "新しいタブで開く",
- "delegate": "作成して {{name}} に依頼",
- "search_instead": "キーワードとして検索",
"back": "戻る",
"prefix_commands": "コマンド",
"prefix_issues": "タスク",
diff --git a/packages/views/locales/ko/search.json b/packages/views/locales/ko/search.json
index 6a9096ff3e..ec3fbddbdd 100644
--- a/packages/views/locales/ko/search.json
+++ b/packages/views/locales/ko/search.json
@@ -133,14 +133,8 @@
"type_to_find_people": "입력해서 멤버와 에이전트 찾기"
},
"delegate": {
- "heading": "에이전트에게 맡기기",
- "create_and_assign": "새 태스크를 만들어 {{name}}에게 지정",
- "squad": "스쿼드",
- "context_aria": "함께 보낼 컨텍스트",
- "parent": "{{identifier}} 하위",
- "pick_crumb": "선택",
- "pick_another": "다른 에이전트나 스쿼드에게 맡기기...",
- "detected": "지시로 인식"
+ "row": "에이전트에게 맡기기: “{{prompt}}”",
+ "hint": "빠른 만들기"
},
"best": {
"assign": "{{subject}}를 {{name}}에게 지정",
@@ -159,8 +153,6 @@
"navigate": "선택",
"select": "실행",
"open_in_new_tab": "새 탭에서 열기",
- "delegate": "만들어서 {{name}}에게 맡기기",
- "search_instead": "키워드로 검색",
"back": "뒤로",
"prefix_commands": "명령어",
"prefix_issues": "태스크",
diff --git a/packages/views/locales/ru/search.json b/packages/views/locales/ru/search.json
index bacdb4f81d..5137f20b44 100644
--- a/packages/views/locales/ru/search.json
+++ b/packages/views/locales/ru/search.json
@@ -142,14 +142,8 @@
"type_to_find_people": "Введите текст для поиска участников и агентов"
},
"delegate": {
- "heading": "Передать агенту",
- "create_and_assign": "Создать задачу и назначить агенту {{name}}",
- "squad": "Отряд",
- "context_aria": "Создано с",
- "parent": "Подзадача {{identifier}}",
- "pick_crumb": "Выбрать",
- "pick_another": "Передать другому агенту или отряду...",
- "detected": "Инструкция"
+ "row": "Передать агенту: «{{prompt}}»",
+ "hint": "Быстрое создание"
},
"best": {
"assign": "Назначить «{{subject}}»: {{name}}",
@@ -168,8 +162,6 @@
"navigate": "Навигация",
"select": "Выбрать",
"open_in_new_tab": "Открыть в новой вкладке",
- "delegate": "Создать и передать: {{name}}",
- "search_instead": "Искать по ключевым словам",
"back": "Назад",
"prefix_commands": "Команды",
"prefix_issues": "Задачи",
diff --git a/packages/views/locales/zh-Hans/search.json b/packages/views/locales/zh-Hans/search.json
index 2a4d7409ff..47fdf20bd1 100644
--- a/packages/views/locales/zh-Hans/search.json
+++ b/packages/views/locales/zh-Hans/search.json
@@ -133,14 +133,8 @@
"type_to_find_people": "输入关键词查找成员和智能体"
},
"delegate": {
- "heading": "交给智能体",
- "create_and_assign": "新建任务并指派给 {{name}}",
- "squad": "小队",
- "context_aria": "附带上下文",
- "parent": "挂在 {{identifier}} 下",
- "pick_crumb": "选择",
- "pick_another": "换一个智能体或小队...",
- "detected": "识别为指令"
+ "row": "交给智能体:「{{prompt}}」",
+ "hint": "快速创建"
},
"best": {
"assign": "把 {{subject}} 指派给 {{name}}",
@@ -159,8 +153,6 @@
"navigate": "选择",
"select": "执行",
"open_in_new_tab": "在新标签页打开",
- "delegate": "新建并交给 {{name}}",
- "search_instead": "仅作为关键词搜索",
"back": "返回",
"prefix_commands": "命令",
"prefix_issues": "任务",
diff --git a/packages/views/locales/zh-Hant/search.json b/packages/views/locales/zh-Hant/search.json
index 0ce56baa04..013cc1cdad 100644
--- a/packages/views/locales/zh-Hant/search.json
+++ b/packages/views/locales/zh-Hant/search.json
@@ -133,14 +133,8 @@
"type_to_find_people": "輸入關鍵詞查找成員和 AI 代理"
},
"delegate": {
- "heading": "交給 AI 代理",
- "create_and_assign": "新建任務並指派給 {{name}}",
- "squad": "小隊",
- "context_aria": "附帶上下文",
- "parent": "掛在 {{identifier}} 下",
- "pick_crumb": "選擇",
- "pick_another": "換一個 AI 代理或小隊...",
- "detected": "識別為指令"
+ "row": "交給 AI 代理:「{{prompt}}」",
+ "hint": "快速建立"
},
"best": {
"assign": "把 {{subject}} 指派給 {{name}}",
@@ -159,8 +153,6 @@
"navigate": "選擇",
"select": "執行",
"open_in_new_tab": "在新分頁開啟",
- "delegate": "新建並交給 {{name}}",
- "search_instead": "僅作為關鍵詞搜尋",
"back": "返回",
"prefix_commands": "命令",
"prefix_issues": "任務",
diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsx
index d2a60bd139..b0933f1c1c 100644
--- a/packages/views/modals/quick-create-issue.test.tsx
+++ b/packages/views/modals/quick-create-issue.test.tsx
@@ -597,6 +597,22 @@ describe("AgentCreatePanel", () => {
).toHaveValue("Persisted draft prompt");
});
+ it("prefers a prompt handed in by the opener over the draft and saves it to the draft", () => {
+ renderPanel({
+ onClose: vi.fn(),
+ isExpanded: false,
+ setIsExpanded: vi.fn(),
+ data: { prompt: "fix the Safari login callback 500" },
+ });
+
+ expect(
+ screen.getByPlaceholderText(
+ 'Tell the agent what to do, e.g. "let Bohan fix the inbox loading slowness in the Web project"',
+ ),
+ ).toHaveValue("fix the Safari login callback 500");
+ expect(mockIssueDraftStore.draft.agent.prompt).toBe("fix the Safari login callback 500");
+ });
+
it("restores unfinished actor, project, priority, and due-date selections after remount", async () => {
mockSquadsData.list = [
{ id: "squad-1", name: "Frontend Squad", leader_id: "agent-1", archived_at: null },
diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index 181d9bd542..044bedc6ff 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -373,7 +373,13 @@ export function AgentCreatePanel({
(baseVersionCheck.state !== "ok" ||
(usesExplicitFields && fieldVersionCheck.state !== "ok"));
- const initialPrompt = draft.agent.prompt || (data?.prompt as string) || "";
+ // An opener's prompt (⌘K "Hand to agent") is newer than any unfinished
+ // draft, so it wins, and is written through so a mode switch keeps it.
+ const seedPrompt = typeof data?.prompt === "string" && data.prompt.trim() ? data.prompt : null;
+ const initialPrompt = seedPrompt ?? (draft.agent.prompt || "");
+ useEffect(() => {
+ if (seedPrompt) setAgent({ prompt: seedPrompt });
+ }, [seedPrompt, setAgent]);
// The editor is uncontrolled — we read the latest markdown via the ref at
// submit/switch time. `hasContent` mirrors emptiness so the Create button
// can disable correctly without a controlled-input rerender on every keystroke.
diff --git a/packages/views/search/delegate/delegate-group.tsx b/packages/views/search/delegate/delegate-group.tsx
deleted file mode 100644
index b68d8e4b8b..0000000000
--- a/packages/views/search/delegate/delegate-group.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-"use client";
-
-import { FolderOpen, Network, Sparkles, Users } from "@multica/ui/icons";
-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
deleted file mode 100644
index e6d1e762d1..0000000000
--- a/packages/views/search/delegate/detect-instruction.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-// @vitest-environment node
-
-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
deleted file mode 100644
index 458fc0cab6..0000000000
--- a/packages/views/search/delegate/detect-instruction.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-/**
- * 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
deleted file mode 100644
index b00e06ff0e..0000000000
--- a/packages/views/search/delegate/use-delegate.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-"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
index a60c69e693..054f2690fb 100644
--- a/packages/views/search/footer.tsx
+++ b/packages/views/search/footer.tsx
@@ -10,7 +10,6 @@ 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 }) {
@@ -40,45 +39,26 @@ function PrefixHint({ prefix, children }: { prefix: string; children: ReactNode
* 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;
-}) {
+export function PaletteFooter({ mode }: { mode: "root" | "page" }) {
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>
- )}
- </>
+ <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">
diff --git a/packages/views/search/pages/other-pages.tsx b/packages/views/search/pages/other-pages.tsx
index 50be5dc24d..c77db78281 100644
--- a/packages/views/search/pages/other-pages.tsx
+++ b/packages/views/search/pages/other-pages.tsx
@@ -23,10 +23,8 @@ 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 { 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";
@@ -220,71 +218,3 @@ export function ChatProjectPage({
</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
index 9431bbd189..809730823b 100644
--- a/packages/views/search/pages/page-view.tsx
+++ b/packages/views/search/pages/page-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import type { DelegateActor, PalettePage } from "../types";
+import type { PalettePage } from "../types";
import {
IssueAssigneePage,
IssueDueDatePage,
@@ -14,20 +14,11 @@ import {
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;
-}) {
+export function PageView({ page, query }: { page: PalettePage; query: string }) {
switch (page.type) {
case "issue-status":
return <IssueStatusPage target={page.target} query={query} />;
@@ -53,7 +44,5 @@ export function PageView({
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/root-view.tsx b/packages/views/search/root-view.tsx
index 1e4a604799..c6987cadc1 100644
--- a/packages/views/search/root-view.tsx
+++ b/packages/views/search/root-view.tsx
@@ -8,6 +8,8 @@ import { inboxUnreadSummaryOptions, unreadWorkspaceIds } from "@multica/core/inb
import { paths, useWorkspacePaths } from "@multica/core/paths";
import type { InboxWorkspaceUnread } from "@multica/core/types";
import { openCreateIssueWithPreference } from "@multica/core/issues/stores";
+import { useModalStore } from "@multica/core/modals";
+import { cn } from "@multica/ui/lib/utils";
import { ActorAvatar } from "../common/actor-avatar";
import { routeIconForPath } from "../layout/route-icon-components";
import { ProjectIcon } from "../projects/components/project-icon";
@@ -18,9 +20,8 @@ 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";
+import type { IssueTarget } from "./types";
+import type { BestMatch, HandToAgentSeed, RootModel } from "./use-root-model";
const EMPTY_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];
@@ -47,15 +48,7 @@ interface RankedGroup {
node: ReactNode;
}
-export function RootView({
- model,
- rawQuery,
- onDelegate,
-}: {
- model: RootModel;
- rawQuery: string;
- onDelegate: (actor: DelegateActor, prompt: string) => void;
-}) {
+export function RootView({ model, rawQuery }: { model: RootModel; rawQuery: string }) {
const { t } = useT("search");
const palette = usePalette();
const p = useWorkspacePaths();
@@ -357,19 +350,10 @@ export function RootView({
(a, b) => b.score - a.score || TYPE_ORDER.indexOf(a.type) - TYPE_ORDER.indexOf(b.type),
);
- const nothing = !model.hasResults && !model.delegate && !best;
+ const nothing = !model.hasResults && !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 && (
@@ -403,15 +387,47 @@ export function RootView({
gone.
*/}
{server.isLoading && nothing && <LoadingRow />}
+ {/* A plain div, not cmdk's Empty: the hand-to-agent row below is an
+ item, so cmdk never considers this list empty. */}
{!server.isLoading && nothing && (
- <CommandPrimitive.Empty className="py-10 text-center text-body text-muted-foreground">
- {t(($) => $.empty.no_results)}
- </CommandPrimitive.Empty>
+ <div className="py-10 text-center text-body text-muted-foreground">{t(($) => $.empty.no_results)}</div>
)}
+ {model.handToAgent && <HandToAgentRow seed={model.handToAgent} disabled={server.stale} />}
</>
);
}
+/**
+ * Always the last row while there is input, so ↵ on a result never turns into
+ * a write. It only opens quick create, prefilled; the user confirms there.
+ * Disabled with the stale results so a fast ↵ does not land on it before the
+ * results for what was typed arrive.
+ */
+function HandToAgentRow({ seed, disabled }: { seed: HandToAgentSeed; disabled: boolean }) {
+ const { t } = useT("search");
+ const palette = usePalette();
+ return (
+ <div className="px-2 py-1">
+ <CommandPrimitive.Item
+ // cmdk picks a default selection only when an item mounts, so the row
+ // remounts on enable to become the selection when nothing else matched.
+ key={disabled ? "disabled" : "enabled"}
+ value="hand-to-agent"
+ disabled={disabled}
+ onSelect={() => {
+ palette.close();
+ useModalStore.getState().open("quick-create-issue", { ...seed });
+ }}
+ className={ROW_CLASS}
+ >
+ <Sparkles className={cn(ROW_ICON_CLASS, "text-brand")} />
+ <span className="min-w-0 flex-1 truncate">{t(($) => $.delegate.row, { prompt: seed.prompt })}</span>
+ <RowHint>{t(($) => $.delegate.hint)}</RowHint>
+ </CommandPrimitive.Item>
+ </div>
+ );
+}
+
function LoadingRow() {
return (
<div className="flex items-center justify-center py-10">
diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsx
index 6eac6a9b54..5a82238cf0 100644
--- a/packages/views/search/search-command.test.tsx
+++ b/packages/views/search/search-command.test.tsx
@@ -990,109 +990,69 @@ describe("SearchCommand", () => {
});
describe("hand to agent", () => {
- beforeEach(() => {
- seed(agentListOptions("ws-test"), [
- makeAgent("agent-lambda", "Lambda"),
- makeAgent("agent-sigma", "Sigma"),
- ]);
- api("quickCreateIssue").mockResolvedValue({ task_id: "task-1" });
- });
+ const prompt = "fix the Safari login callback 500";
+ const handRow = () =>
+ document.querySelector<HTMLElement>('[cmdk-item=""][data-value="hand-to-agent"]');
- it("turns an instruction naming an agent into a quick-create for it", async () => {
+ it("ends the results with a fixed row and leaves Enter on the top result", async () => {
const user = userEvent.setup();
- const prompt = "让 Lambda 修一下 Safari 登录回调的 500";
+ api("searchIssues").mockResolvedValue({
+ issues: [{ ...makeIssue({ id: "issue-812", identifier: "MUL-812", title: prompt }), match_source: "title" }],
+ total: 1,
+ });
renderSearch();
await user.type(input(), prompt);
- await waitFor(() => expect(renderedValues()[0]).toBe("delegate:submit"));
- expect(await rowText("New issue and assign to Lambda")).toBeInTheDocument();
+ await waitFor(() => expect(selectedValue()).toBe("issue-812"), { timeout: 2000 });
+ expect(renderedValues().at(-1)).toBe("hand-to-agent");
+ expect(handRow()).toHaveTextContent(`Hand to agent: “${prompt}”`);
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);
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/issues/issue-812");
+ expect(mockOpenModal).not.toHaveBeenCalled();
+ expect(api("quickCreateIssue")).not.toHaveBeenCalled();
});
- it("attaches the open issue as parent", async () => {
+ it("opens quick create prefilled with the input, project and open issue", async () => {
const user = userEvent.setup();
- const parent = makeIssue({ id: "issue-9", identifier: "MUL-9" });
+ const parent = makeIssue({ id: "issue-9", identifier: "MUL-9", project_id: "proj-1" });
registerContext({ kind: "issue", issue: parent });
renderSearch();
- await user.type(input(), "ask Sigma to write the release notes");
-
- await waitFor(() => expect(renderedValues()[0]).toBe("delegate:submit"));
- expect(screen.getByText("Under MUL-9")).toBeInTheDocument();
- fireEvent.keyDown(input(), { key: "Enter" });
-
- await waitFor(() =>
- expect(api("quickCreateIssue")).toHaveBeenCalledWith(
- expect.objectContaining({ agent_id: "agent-sigma", parent_issue_id: "issue-9" }),
- ),
- );
- });
-
- 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.type(input(), "让 Lambda 写一下发布说明");
- fireEvent.keyDown(input(), { key: "Enter", shiftKey: true });
+ await waitFor(() => expect(handRow()).not.toHaveAttribute("data-disabled", "true"), { timeout: 2000 });
+ fireEvent.click(handRow()!);
- await waitFor(() => expect(renderedValues()).not.toContain("delegate:submit"));
+ expect(mockOpenModal).toHaveBeenCalledWith("quick-create-issue", {
+ prompt: "让 Lambda 写一下发布说明",
+ project_id: "proj-1",
+ parent_issue_id: "issue-9",
+ parent_issue_identifier: "MUL-9",
+ });
+ expect(useSearchStore.getState().open).toBe(false);
expect(api("quickCreateIssue")).not.toHaveBeenCalled();
});
- it.each([
- { isComposing: true, keyCode: 13 },
- { isComposing: false, keyCode: 229 },
- ])("preserves delegation during IME Shift+Enter ($isComposing, $keyCode)", async (ime) => {
+ it("is what Enter opens when nothing matches", async () => {
const user = userEvent.setup();
- const prompt = "fix the Safari login callback 500";
renderSearch();
await user.type(input(), prompt);
- await waitFor(() => expect(selectedValue()).toBe("delegate:submit"));
-
- fireEvent.compositionStart(input());
- const event = new KeyboardEvent("keydown", {
- key: "Enter",
- shiftKey: true,
- ...ime,
- bubbles: true,
- cancelable: true,
- });
- fireEvent(input(), event);
- expect.soft(event.defaultPrevented).toBe(false);
- expect.soft(renderedValues()).toContain("delegate:submit");
- expect(input()).toHaveValue(prompt);
- expect(useSearchStore.getState().open).toBe(true);
- expect(api("quickCreateIssue")).not.toHaveBeenCalled();
- expect(mockOpenModal).not.toHaveBeenCalled();
- expect(mockPush).not.toHaveBeenCalled();
+ await waitFor(() => expect(selectedValue()).toBe("hand-to-agent"), { timeout: 2000 });
+ expect(screen.getByText("No results found.")).toBeInTheDocument();
+ fireEvent.keyDown(input(), { key: "Enter" });
- fireEvent.compositionEnd(input());
- fireEvent.keyDown(input(), { key: "Enter", shiftKey: true });
- await waitFor(() => expect(renderedValues()).not.toContain("delegate:submit"));
- expect(input()).toHaveValue(prompt);
- expect(useSearchStore.getState().open).toBe(true);
+ expect(mockOpenModal).toHaveBeenCalledWith("quick-create-issue", { prompt });
expect(api("quickCreateIssue")).not.toHaveBeenCalled();
});
- it("does not read a plain keyword as an instruction", async () => {
+ it("is not offered in a scoped search", async () => {
const user = userEvent.setup();
renderSearch();
- await user.type(input(), "login");
+ await user.type(input(), ">theme");
- await waitFor(() => expect(api("searchIssues")).toHaveBeenCalled(), { timeout: 2000 });
- expect(renderedValues()).not.toContain("delegate:submit");
+ await waitFor(() => expect(renderedValues()).toContain("command:theme"));
+ expect(handRow()).toBeNull();
});
});
@@ -1215,6 +1175,7 @@ describe("SearchCommand", () => {
fireEvent.keyDown(input(), { key: "Enter" });
expect(mockPush).not.toHaveBeenCalled();
+ expect(mockOpenModal).not.toHaveBeenCalled();
expect(useSearchStore.getState().open).toBe(true);
});
diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsx
index 255f83ae92..305f72fed1 100644
--- a/packages/views/search/search-command.tsx
+++ b/packages/views/search/search-command.tsx
@@ -1,7 +1,7 @@
"use client";
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { ChevronRight, SearchIcon, Sparkles } from "@multica/ui/icons";
+import { ChevronRight, SearchIcon } from "@multica/ui/icons";
import { Command as CommandPrimitive } from "cmdk";
import {
selectCommandBarContexts,
@@ -9,7 +9,6 @@ import {
useSearchStore,
} from "@multica/core/command-bar";
import { createShortcutChord } from "@multica/core/shortcuts";
-import { isImeComposing } from "@multica/core/utils";
import {
Dialog,
DialogContent,
@@ -25,9 +24,8 @@ 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 type { DelegateActor, PaletteHostDialog, PaletteStackEntry } from "./types";
+import type { PaletteHostDialog, PaletteStackEntry } from "./types";
const ESCAPE = createShortcutChord("Escape");
@@ -160,16 +158,10 @@ function PaletteFrame({
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 model = useRootModel(rawQuery, contexts, { active: true });
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
// cmdk's root handler intercepts Home/End for list navigation; stop
@@ -181,17 +173,9 @@ function PaletteFrame({
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 && !isImeComposing(e)) {
- e.preventDefault();
- setDismissedDelegateFor(rawQuery);
}
};
- const delegate = !current ? model.delegate : null;
-
return (
<>
<CommandPrimitive
@@ -208,11 +192,7 @@ function PaletteFrame({
className="flex size-full flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground"
>
<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" />
- )}
+ <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) => (
@@ -239,27 +219,18 @@ function PaletteFrame({
}}
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>
<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} />
+ <PageView page={current.page} query={pageQuery} />
) : (
- <RootView model={model} rawQuery={rawQuery} onDelegate={onDelegate} />
+ <RootView model={model} rawQuery={rawQuery} />
)}
</CommandPrimitive.List>
- <PaletteFooter
- mode={current ? "page" : delegate ? "delegate" : "root"}
- delegateName={delegate?.actor.name}
- />
+ <PaletteFooter mode={current ? "page" : "root"} />
</CommandPrimitive>
</>
);
diff --git a/packages/views/search/types.ts b/packages/views/search/types.ts
index 54032305ef..c495feddd4 100644
--- a/packages/views/search/types.ts
+++ b/packages/views/search/types.ts
@@ -1,16 +1,12 @@
import type { ComponentType, ReactNode } from "react";
import type { ShortcutChord } from "@multica/core/shortcuts";
-import type { Agent, ChatSession, Issue, Project, Squad } from "@multica/core/types";
+import type { Agent, ChatSession, Issue, Project } 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 }
@@ -24,8 +20,7 @@ export type PalettePage =
| { 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 };
+ | { type: "chat-project"; session: ChatSession; changeProject: (projectId: string | null) => void };
export interface PaletteStackEntry {
page: PalettePage;
diff --git a/packages/views/search/use-root-model.ts b/packages/views/search/use-root-model.ts
index e1c74b03b5..31ad4fbab1 100644
--- a/packages/views/search/use-root-model.ts
+++ b/packages/views/search/use-root-model.ts
@@ -9,10 +9,8 @@ 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 { 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";
@@ -62,11 +60,15 @@ export type BestMatch =
| { type: "member"; member: ObjectHits["members"][number]["item"]; score: number }
| { type: "project"; project: SearchProjectResult; score: number };
-export interface DelegateModel {
+/**
+ * What the trailing "Hand to agent" row opens quick create with: the input as
+ * typed, plus the page's project and open issue (as parent).
+ */
+export interface HandToAgentSeed {
prompt: string;
- actor: DelegateActor;
- agentEntry: AgentEntry | null;
- attachments: DelegateAttachments;
+ project_id?: string;
+ parent_issue_id?: string;
+ parent_issue_identifier?: string;
}
export interface RootModel {
@@ -85,11 +87,9 @@ export interface RootModel {
bestMatch: BestMatch | null;
recent: RecentItem[];
newCommands: PaletteCommand[];
- delegate: DelegateModel | null;
+ handToAgent: HandToAgentSeed | 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;
}
@@ -114,7 +114,7 @@ function maxScore(entries: readonly { score: number }[]) {
export function useRootModel(
rawQuery: string,
contexts: readonly CommandBarContext[],
- options: { active: boolean; dismissedDelegateFor: string | null },
+ options: { active: boolean },
): RootModel {
const { t: tNav } = useT("layout");
const { scope, text } = parseScope(rawQuery);
@@ -126,6 +126,7 @@ export function useRootModel(
contexts.find((c): c is Extract<CommandBarContext, { kind: K }> => c.kind === kind) ?? null;
const issueContext = find("issue");
const issuesContext = find("issues");
+ const projectContext = find("project");
const singleTarget = useMemo<IssueTarget | null>(
() => (issueContext ? { kind: "single", issue: issueContext.issue } : null),
[issueContext],
@@ -140,7 +141,7 @@ export function useRootModel(
const singleGroup = useIssueCommandGroup(singleTarget, issueContext?.onDeletedFallbackPath);
const batchGroup = useIssueCommandGroup(batchTarget);
- const projectGroup = useProjectCommandGroup(find("project"));
+ const projectGroup = useProjectCommandGroup(projectContext);
const agentGroup = useAgentCommandGroup(find("agent"));
const autopilotGroup = useAutopilotCommandGroup(find("autopilot"));
const inboxGroup = useInboxCommandGroup(find("inbox"));
@@ -151,8 +152,6 @@ export function useRootModel(
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[]>(
() =>
@@ -210,7 +209,7 @@ export function useRootModel(
.sort((a, b) => b.score - a.score);
}
- const { results, isLoading, stale } = server;
+ const { results, 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({
@@ -272,31 +271,15 @@ export function useRootModel(
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,
- };
- }
+ let handToAgent: HandToAgentSeed | null = null;
+ if (q && scope === "all") {
+ const issue = issueContext?.issue ?? null;
+ const projectId = projectContext?.project.id ?? issue?.project_id ?? null;
+ handToAgent = {
+ prompt: text,
+ ...(projectId ? { project_id: projectId } : {}),
+ ...(issue ? { parent_issue_id: issue.id, parent_issue_identifier: issue.identifier } : {}),
+ };
}
const primaryIssueTarget =
@@ -319,28 +302,25 @@ export function useRootModel(
bestMatch,
recent,
newCommands: globalCommands.filter((command) => command.primary),
- delegate,
+ handToAgent,
primaryIssueTarget,
- attachments,
hasResults,
};
}, [
agentGroup,
- attachments,
autopilotGroup,
batchGroup,
batchTarget,
chatGroup,
contexts,
- delegateCandidates,
globalCommands,
inboxGroup,
+ issueContext,
navPages,
objects,
- options.dismissedDelegateFor,
+ projectContext,
projectGroup,
q,
- rawQuery,
recent,
scope,
server,