Skip to content

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

Go

feat(issues): offer target-agent skills in comment slash menu (#10774)

AstralSolipsism23727a6387ca
diff --git a/packages/views/editor/content-editor-quick-actions.test.tsx b/packages/views/editor/content-editor-quick-actions.test.tsx
index 8f11d30030..2d50d368cd 100644
--- a/packages/views/editor/content-editor-quick-actions.test.tsx
+++ b/packages/views/editor/content-editor-quick-actions.test.tsx
@@ -1,35 +1,87 @@
import type { Editor } from "@tiptap/core";
+import { useState, type PropsWithChildren } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";
+import { act, cleanup, fireEvent, renderHook, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import type { ListQuickActionsResponse, QuickAction } from "@multica/core/types";
+import type { Agent, CommentTriggerPreview, Issue, ListQuickActionsResponse, MemberWithUser, QuickAction } from "@multica/core/types";
import { quickActionKeys } from "@multica/core/quick-actions";
+import { issueKeys } from "@multica/core/issues/queries";
+import { workspaceKeys } from "@multica/core/workspace/queries";
import { renderWithI18n } from "../test/i18n";
import { NavigationProvider } from "../navigation/context";
import { useQuickActionMenu } from "../issues/hooks/use-quick-action-menu";
+import { useCommentTriggerPreview } from "../issues/hooks/use-comment-trigger-preview";
import { ContentEditor } from "./content-editor";
+import { CommentInput } from "../issues/components/comment-input";
+import { ReplyInput } from "../issues/components/reply-input";
const listQuickActions = vi.hoisted(() => vi.fn());
const renderQuickAction = vi.hoisted(() => vi.fn());
+const getIssue = vi.hoisted(() => vi.fn());
+const listAgents = vi.hoisted(() => vi.fn());
+const listSquads = vi.hoisted(() => vi.fn());
+const listMembers = vi.hoisted(() => vi.fn());
+const previewCommentTriggers = vi.hoisted(() => vi.fn());
const toastError = vi.hoisted(() => vi.fn());
vi.mock("sonner", () => ({ toast: { error: toastError } }));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: { getState: () => ({ user: { id: "user-1" } }) },
+}));
vi.mock("@multica/core/api", async (importOriginal) => {
const actual = await importOriginal<typeof import("@multica/core/api")>();
- return { ...actual, api: { ...actual.api, listQuickActions, renderQuickAction } };
+ return { ...actual, api: { ...actual.api, getBaseUrl: () => "https://api.example.test", listQuickActions, renderQuickAction, getIssue, listAgents, listSquads, listMembers, previewCommentTriggers } };
});
vi.mock("@multica/core/paths", async (importOriginal) => ({
...(await importOriginal<typeof import("@multica/core/paths")>()),
useCurrentWorkspace: () => ({ id: "ws", slug: "test" }),
useWorkspaceSlug: () => "test",
- useWorkspacePaths: () => ({ issueDetail: (id: string) => `/test/issues/${id}` }),
+ useWorkspacePaths: () => ({
+ issueDetail: (id: string) => `/test/issues/${id}`,
+ memberDetail: (id: string) => `/test/members/${id}`,
+ }),
+}));
+vi.mock("@multica/core/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/hooks")>()),
+ useWorkspaceId: () => "ws",
}));
+function makeIssue(
+ assigneeType: Issue["assignee_type"] = null,
+ assigneeId: string | null = null,
+): Issue {
+ return {
+ id: "issue-1",
+ workspace_id: "ws",
+ assignee_type: assigneeType,
+ assignee_id: assigneeId,
+ } as Issue;
+}
+
+function makeAgent(id: string, skills: Agent["skills"]): Agent {
+ return {
+ id,
+ skills,
+ runtime_id: "runtime-1",
+ archived_at: null,
+ owner_id: null,
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ } as Agent;
+}
+
beforeEach(() => {
- listQuickActions.mockReset();
+ listQuickActions.mockReset().mockResolvedValue({ quick_actions: [] });
renderQuickAction.mockReset().mockResolvedValue("Rendered feedback");
+ getIssue.mockReset().mockResolvedValue(makeIssue());
+ listAgents.mockReset().mockResolvedValue([]);
+ listSquads.mockReset().mockResolvedValue([]);
+ listMembers.mockReset().mockResolvedValue([
+ { user_id: "user-1", role: "member", name: "User" } as MemberWithUser,
+ ]);
toastError.mockReset();
+ previewCommentTriggers.mockReset().mockReturnValue(new Promise(() => {}));
});
const clients: QueryClient[] = [];
@@ -65,9 +117,12 @@ function pendingCatalog() {
}
function Composer() {
+ const [content, setContent] = useState("");
+ const triggerPreview = useCommentTriggerPreview({ issueId: "issue-1", content });
return (
<ContentEditor
- quickActionMenu={useQuickActionMenu()}
+ onUpdate={setContent}
+ quickActionMenu={useQuickActionMenu("issue-1", { triggerPreview, previewContent: content })}
enableSlashCommands
slashCommandMode="command"
showBubbleMenu={false}
@@ -75,12 +130,26 @@ function Composer() {
);
}
-async function mount(initialActions?: QuickAction[]) {
+async function mount(
+ initialActions?: QuickAction[],
+ composer: "standalone" | "comment" | "reply" = "standalone",
+) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
if (initialActions) {
client.setQueryData(quickActionKeys.list("ws"), { quick_actions: initialActions });
}
clients.push(client);
+ const composerUi = composer === "comment" ? (
+ <CommentInput issueId="issue-1" onSubmit={vi.fn().mockResolvedValue(true)} />
+ ) : composer === "reply" ? (
+ <ReplyInput
+ issueId="issue-1"
+ parentId="comment-1"
+ avatarType="member"
+ avatarId="user-1"
+ onSubmit={vi.fn().mockResolvedValue(true)}
+ />
+ ) : <Composer />;
const result = renderWithI18n(
<NavigationProvider value={{
push: vi.fn(),
@@ -91,9 +160,12 @@ async function mount(initialActions?: QuickAction[]) {
hash: "",
getShareableUrl: (path) => path,
}}>
- <QueryClientProvider client={client}><Composer /></QueryClientProvider>
+ <QueryClientProvider client={client}>{composerUi}</QueryClientProvider>
</NavigationProvider>,
);
+ if (composer !== "standalone") {
+ fireEvent.click(screen.getByTestId(`${composer}-composer-shell`));
+ }
const dom = await waitFor(() => {
const el = result.container.querySelector<HTMLElement & { editor: Editor }>(".ProseMirror");
expect(el?.editor).toBeDefined();
@@ -118,6 +190,54 @@ async function type(editor: Editor, text: string) {
const menuItem = () => screen.queryByRole("button", { name: "/delayed-feedback" });
+describe("quick action menu query lifecycle", () => {
+ function renderMenu(client: QueryClient, enabled: boolean) {
+ return renderHook(() => useQuickActionMenu("issue-1", { enabled }), {
+ wrapper: ({ children }: PropsWithChildren) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ });
+ }
+
+ it("disables every query while the composer is a static shell", () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ clients.push(client);
+ const { unmount } = renderMenu(client, false);
+
+ const queries = client.getQueryCache().getAll();
+ const observers = queries.flatMap((query) => query.observers);
+ expect(observers).toHaveLength(5);
+ expect(observers.every((observer) => observer.options.enabled === false)).toBe(true);
+ expect(listQuickActions).not.toHaveBeenCalled();
+ expect(getIssue).not.toHaveBeenCalled();
+ expect(listAgents).not.toHaveBeenCalled();
+ expect(listSquads).not.toHaveBeenCalled();
+ expect(listMembers).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it("disables mount refetches for active Issue context queries", () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ clients.push(client);
+ const { unmount } = renderMenu(client, true);
+
+ const keys = [
+ issueKeys.detail("ws", "issue-1"),
+ workspaceKeys.agents("ws"),
+ workspaceKeys.squads("ws"),
+ workspaceKeys.members("ws"),
+ ];
+ for (const queryKey of keys) {
+ const query = client.getQueryCache().find({ queryKey, exact: true });
+ const observers = query?.observers ?? [];
+ expect(observers).toHaveLength(1);
+ expect(observers[0]?.options.enabled).toBe(true);
+ expect(observers[0]?.options.refetchOnMount).toBe(false);
+ }
+ unmount();
+ });
+});
+
describe("comment quick-action catalog updates in the real editor", () => {
it.each(["", "agent", "squad"])(
"inserts a cached %s action synchronously on Enter without a render request",
@@ -256,3 +376,204 @@ describe("comment quick-action catalog updates in the real editor", () => {
expect(screen.queryByRole("button", { name: /\/note/ })).not.toBeInTheDocument();
});
});
+
+describe("Issue agent-scoped skills in the real editor", () => {
+ it.each([false, true])("refreshes the open menu from a current preview (empty: %s)", async (empty) => {
+ const assignee = makeAgent("assignee", [{ id: "fallback", name: "fallback-preview", description: "" }]);
+ const target = makeAgent("target", [
+ { id: "preview", name: "preview", description: "" },
+ { id: "disabled", name: "disabled", description: "", enabled: false },
+ ]);
+ getIssue.mockResolvedValue(makeIssue("agent", assignee.id));
+ listAgents.mockResolvedValue([assignee, target]);
+ const { promise, resolve } = Promise.withResolvers<CommentTriggerPreview>();
+ previewCommentTriggers.mockReturnValue(promise);
+ const { editor, dom } = await mount();
+
+ expect(previewCommentTriggers).not.toHaveBeenCalled();
+ await type(editor, "/p");
+ await waitFor(() => expect(screen.getByRole("button", { name: "/fallback-preview" })).toBeVisible());
+ await waitFor(() => expect(previewCommentTriggers).toHaveBeenCalled());
+ const selection = editor.state.selection.toJSON();
+
+ await act(async () => resolve({
+ agents: empty ? [] : [{ id: target.id, name: "Target", source: "assignee", reason: "" }],
+ blocked: [],
+ }));
+
+ await waitFor(() => expect(screen.queryByRole("button", { name: "/fallback-preview" })).not.toBeInTheDocument());
+ if (!empty) expect(screen.getByRole("button", { name: "/preview" })).toBeVisible();
+ expect(screen.queryByRole("button", { name: "/disabled" })).not.toBeInTheDocument();
+ expect(dom.editor).toBe(editor);
+ expect(editor.getText()).toBe("/p");
+ expect(editor.state.selection.toJSON()).toEqual(selection);
+ });
+
+ it("uses live synchronous targets while a changed mention is debouncing or loading", async () => {
+ const previous = makeAgent("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", [{ id: "old", name: "old", description: "" }]);
+ const next = makeAgent("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", [{ id: "next", name: "next", description: "" }]);
+ getIssue.mockResolvedValue(makeIssue("agent", previous.id));
+ listAgents.mockResolvedValue([previous, next]);
+ previewCommentTriggers.mockResolvedValueOnce({ agents: [
+ { id: previous.id, name: "Previous", source: "assignee", reason: "" },
+ ], blocked: [] });
+ const { editor } = await mount();
+ await type(editor, "draft");
+ await waitFor(() => expect(previewCommentTriggers).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ editor.commands.setContent("");
+ editor.commands.insertContent([
+ { type: "mention", attrs: { type: "agent", id: next.id, label: "Next", mentionSuggestionChar: "@" } },
+ { type: "text", text: " " },
+ ]);
+ });
+ await type(editor, "/ne");
+ await waitFor(() => expect(screen.getByRole("button", { name: "/next" })).toBeVisible());
+ expect(screen.queryByRole("button", { name: "/old" })).not.toBeInTheDocument();
+ await waitFor(() => expect(previewCommentTriggers).toHaveBeenCalledTimes(2));
+ expect(screen.getByRole("button", { name: "/next" })).toBeVisible();
+ });
+
+ it("uses a just-inserted mention and inserts the selected skill capsule as Markdown", async () => {
+ const explicit = makeAgent("explicit", [
+ { id: "deploy-skill", name: "deploy", description: "" },
+ ]);
+ const assignee = makeAgent("assignee", [
+ { id: "fallback-skill", name: "fallback", description: "" },
+ ]);
+ getIssue.mockResolvedValue(makeIssue("agent", assignee.id));
+ listAgents.mockResolvedValue([explicit, assignee]);
+ listQuickActions.mockResolvedValue({ quick_actions: [action] });
+ const { editor, dom } = await mount([action]);
+
+ await act(async () => {
+ editor.commands.insertContent([
+ {
+ type: "mention",
+ attrs: {
+ type: "agent",
+ id: explicit.id,
+ label: "Explicit",
+ mentionSuggestionChar: "@",
+ },
+ },
+ { type: "text", text: " " },
+ ]);
+ });
+ await type(editor, "/d");
+
+ await waitFor(() => expect(screen.getByRole("button", { name: "/deploy" })).toBeVisible());
+ expect(screen.getByRole("button", { name: "/delayed-feedback" })).toBeVisible();
+ expect(screen.queryByRole("button", { name: /\/note/ })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "/fallback" })).not.toBeInTheDocument();
+
+ fireEvent.keyDown(dom, { key: "ArrowDown" });
+ fireEvent.keyDown(dom, { key: "Enter" });
+
+ expect(editor.getMarkdown()).toBe(
+ "[@Explicit](mention://agent/explicit) [/deploy](slash://skill/deploy-skill) ",
+ );
+ });
+
+ it("keeps /note selection as a plain-text prefix", async () => {
+ const { editor, dom } = await mount();
+ await type(editor, "/no");
+ await waitFor(() => expect(screen.getByRole("button", { name: /\/note/ })).toBeVisible());
+
+ fireEvent.keyDown(dom, { key: "Enter" });
+
+ expect(editor.getText()).toBe("/note ");
+ });
+
+ it.each(["/usr/local/bin", "2026/11/16"])(
+ "renders no empty menu for ordinary prose %s",
+ async (text) => {
+ const { editor } = await mount();
+
+ await type(editor, text);
+
+ expect(screen.queryByRole("button", { name: /\/note/ })).not.toBeInTheDocument();
+ expect(screen.queryByText("No matching skills")).not.toBeInTheDocument();
+ },
+ );
+
+ it("refreshes an open menu on agent and Issue cache updates without resetting the editor", async () => {
+ const first = makeAgent("first", [{ id: "one", name: "target-one", description: "" }]);
+ const second = makeAgent("second", [{ id: "two", name: "target-two", description: "" }]);
+ getIssue.mockResolvedValue(makeIssue("agent", first.id));
+ listAgents.mockResolvedValue([first, second]);
+ const { client, dom, editor } = await mount();
+ await type(editor, "/target");
+ await waitFor(() => expect(screen.getByRole("button", { name: "/target-one" })).toBeVisible());
+
+ await act(async () => client.setQueryData(workspaceKeys.agents("ws"), [
+ makeAgent("first", [{ id: "updated", name: "target-updated", description: "" }]),
+ second,
+ ]));
+ await waitFor(() => expect(screen.getByRole("button", { name: "/target-updated" })).toBeVisible());
+ expect(screen.queryByRole("button", { name: "/target-one" })).not.toBeInTheDocument();
+
+ await act(async () => client.setQueryData(
+ issueKeys.detail("ws", "issue-1"),
+ makeIssue("agent", second.id),
+ ));
+ await waitFor(() => expect(screen.getByRole("button", { name: "/target-two" })).toBeVisible());
+ expect(screen.queryByRole("button", { name: "/target-updated" })).not.toBeInTheDocument();
+ expect(dom.editor).toBe(editor);
+ expect(editor.getText()).toBe("/target");
+ });
+});
+
+describe("Issue composer slash query lifecycle", () => {
+ const skills = [
+ { id: "code-review", name: "code-review", description: "" },
+ { id: "write-tests", name: "write-tests", description: "" },
+ ...Array.from({ length: 13 }, (_, index) => ({
+ id: `extra-${index}`,
+ name: `extra-${index}`,
+ description: "",
+ })),
+ ];
+ const requestChanges = { ...action, id: "request-changes", name: "Request changes" };
+
+ async function expectOnlyQuickActionsAndNote() {
+ await waitFor(() => {
+ expect(screen.getByRole("button", { name: "/Request changes" })).toBeVisible();
+ expect(screen.getByRole("button", { name: /^\/note/ })).toBeVisible();
+ expect(document.querySelector("[data-kind='slash']")?.querySelectorAll("button")).toHaveLength(2);
+ });
+ }
+
+ it.each(["comment", "reply"] as const)(
+ "hides skills for bare and non-matching queries and restores the bare menu in the %s composer",
+ async (composer) => {
+ const target = makeAgent("target", skills);
+ getIssue.mockResolvedValue(makeIssue("agent", target.id));
+ listAgents.mockResolvedValue([target]);
+ listQuickActions.mockResolvedValue({ quick_actions: [requestChanges] });
+ const { editor } = await mount([requestChanges], composer);
+
+ await type(editor, "/");
+ await expectOnlyQuickActionsAndNote();
+ expect(screen.queryByRole("button", { name: "/code-review" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "/write-tests" })).not.toBeInTheDocument();
+
+ await type(editor, "co");
+ await waitFor(() => expect(screen.getByRole("button", { name: "/code-review" })).toBeVisible());
+ expect(document.querySelector("[data-kind='slash']")?.querySelectorAll("button")).toHaveLength(1);
+ fireEvent.click(screen.getByRole("button", { name: "/code-review" }));
+ expect(editor.getMarkdown()).toBe("[/code-review](slash://skill/code-review) ");
+
+ await type(editor, "/zzzz");
+ await waitFor(() => expect(document.querySelector("[data-kind='slash']")).not.toBeInTheDocument());
+
+ await act(async () => {
+ const { from, to } = editor.state.selection;
+ editor.commands.deleteRange({ from: from - 4, to });
+ });
+ await expectOnlyQuickActionsAndNote();
+ expect(screen.queryByRole("button", { name: "/code-review" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "/write-tests" })).not.toBeInTheDocument();
+ },
+ );
+});
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 6866e44dc0..1a199e0dba 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -203,14 +203,14 @@ interface ContentEditorBaseProps {
enableSlashCommands?: boolean;
/**
* Which `/` menu to show when enableSlashCommands is true: "skill" (default)
- * lists the active agent's skills (chat); "command" shows the fixed built-in
- * command menu (issue comments), e.g. /note.
+ * lists the active agent's skills (chat); "command" merges Issue quick
+ * actions, skills matching a nonempty query, and built-ins such as /note.
*/
slashCommandMode?: "skill" | "command";
/**
- * Quick actions to offer in the "command" `/` menu, plus the resolver that
- * turns a pick into the text it would post (MUL-5465). Read through
- * functions so a newly created action appears without remounting the editor.
+ * Quick actions and Issue target-agent skills for the "command" `/` menu,
+ * plus the resolver that turns a quick-action pick into draft text. Read
+ * through functions so cached updates appear without remounting the editor.
*/
quickActionMenu?: BuiltinCommandSuggestionOptions;
/**
@@ -639,6 +639,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
slashCommandMode,
quickActionMenu: {
getQuickActions: () => quickActionMenuRef.current?.getQuickActions?.() ?? [],
+ getSkills: (editor) => quickActionMenuRef.current?.getSkills?.(editor) ?? [],
subscribeQuickActions: (refresh) => {
quickActionMenuListeners.current.add(refresh);
return () => { quickActionMenuListeners.current.delete(refresh); };
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 0c0dadef9d..0ab0b3372c 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -174,14 +174,13 @@ export interface EditorExtensionsOptions {
/**
* Which `/` menu to attach when enableSlashCommands is true:
* - "skill" (default) — the chat picker listing the active agent's skills.
- * - "command" — the fixed built-in command menu (issue comments), e.g. /note.
+ * - "command" — Issue quick actions, skills matching a nonempty query, and /note.
*/
slashCommandMode?: "skill" | "command";
/**
- * Quick actions offered in the "command" `/` menu, plus the resolver that
- * turns a pick into the text it would post (MUL-5465). Both are functions so
- * the editor is created once while still reading live data; the setup layer
- * owns React Query access. Omit on composers with no issue context.
+ * Quick actions and Issue target-agent skills offered in the "command" `/`
+ * menu, plus the resolver that turns a quick-action pick into draft text.
+ * Functions keep the editor mounted while reading live React Query data.
*/
quickActionMenu?: BuiltinCommandSuggestionOptions;
/**
diff --git a/packages/views/editor/extensions/slash-command-suggestion.test.tsx b/packages/views/editor/extensions/slash-command-suggestion.test.tsx
index 41ae848d39..bed0329d40 100644
--- a/packages/views/editor/extensions/slash-command-suggestion.test.tsx
+++ b/packages/views/editor/extensions/slash-command-suggestion.test.tsx
@@ -116,6 +116,24 @@ describe("slash command suggestion items", () => {
expect(items(qc).map((i) => i.label)).toEqual(["deploy", "review"]);
});
+ it("filters paused skills from the active agent", () => {
+ chatState.selectedAgentId = "agent-1";
+ const qc = fakeQc({
+ members: [{ user_id: "u1", name: "Alice", role: "member" }],
+ agents: [
+ agent({
+ id: "agent-1",
+ skills: [
+ { id: "paused", name: "paused", description: "", enabled: false },
+ { id: "active", name: "active", description: "", enabled: true },
+ ],
+ }),
+ ],
+ });
+
+ expect(items(qc).map((item) => item.id)).toEqual(["active"]);
+ });
+
it("filters skills by name case-insensitively", () => {
chatState.selectedAgentId = "agent-1";
const qc = fakeQc({
@@ -551,8 +569,61 @@ describe("SlashCommandList empty states", () => {
});
describe("buildBuiltinCommandItems", () => {
- it("returns the full built-in command set for an empty query", () => {
- expect(buildBuiltinCommandItems("")).toEqual(BUILTIN_COMMANDS);
+ it("returns only quick actions and /note for an empty query with many skills", () => {
+ const skills = Array.from({ length: 18 }, (_, index) => ({
+ id: `skill-${index}`,
+ name: `skill-${index}`,
+ description: "",
+ }));
+ const actions = [{ id: "qa-1", name: "Request changes", description: "Review this" }];
+
+ expect(buildBuiltinCommandItems("", actions, skills)).toEqual([
+ { id: "quick-action:qa-1", label: "Request changes", description: "Review this" },
+ BUILTIN_COMMANDS[0],
+ ]);
+ });
+
+ it("merges matching quick actions, skills, and /note for a nonempty query", () => {
+ expect(buildBuiltinCommandItems(
+ "no",
+ [
+ { id: "qa-1", name: "notify", description: "Notify the team" },
+ { id: "qa-2", name: "review", description: "Review this" },
+ ],
+ [{ id: "skill-1", name: "note-deploy", description: "Ship changes" }],
+ )).toEqual([
+ { id: "quick-action:qa-1", label: "notify", description: "Notify the team" },
+ { id: "skill:skill-1", label: "note-deploy", description: "Ship changes" },
+ BUILTIN_COMMANDS[0],
+ ]);
+ });
+
+ it("ranks Issue skills by name and description within the shared item cap", () => {
+ const skills = [
+ ...Array.from({ length: 25 }, (_, index) => ({
+ id: `description-${index}`,
+ name: `skill-${index}`,
+ description: "Build a throwaway prototype",
+ })),
+ { id: "named", name: "wayfinder", description: "" },
+ ];
+ const result = buildBuiltinCommandItems("wa", [], skills);
+
+ expect(result).toHaveLength(20);
+ expect(result[0]?.id).toBe("skill:named");
+ expect(result.every((item) => item.id.startsWith("skill:"))).toBe(true);
+ });
+
+ it.each(["n", "no"])("reserves /note for query %j with 25 matching skills", (query) => {
+ const skills = Array.from({ length: 25 }, (_, index) => ({
+ id: `skill-${index}`,
+ name: `skill-${index}`,
+ description: "note",
+ }));
+
+ const result = buildBuiltinCommandItems(query, [], skills);
+ expect(result).toHaveLength(20);
+ expect(result.at(-1)?.id).toBe("note");
});
it("includes /note while the query is a prefix of the label", () => {
@@ -567,8 +638,9 @@ describe("buildBuiltinCommandItems", () => {
expect(buildBuiltinCommandItems("ote")).toEqual([]);
});
- it("returns nothing for a query that matches no command", () => {
- expect(buildBuiltinCommandItems("deploy")).toEqual([]);
+ it("returns nothing for a query that matches no command or skill", () => {
+ const skills = [{ id: "skill-1", name: "code-review", description: "Review code" }];
+ expect(buildBuiltinCommandItems("zzz", [], skills)).toEqual([]);
});
});
@@ -604,7 +676,13 @@ describe("builtin `/` menu — cached quick action content", () => {
insertContentAt: vi.fn(() => chain),
run: vi.fn(() => true),
};
- return { chain, editor: { chain: () => chain } };
+ return {
+ chain,
+ editor: {
+ chain: () => chain,
+ view: { state: { selection: { $to: { nodeAfter: null } } } },
+ },
+ };
}
it("replaces the command range synchronously and parses mention markdown", () => {
@@ -631,4 +709,41 @@ describe("builtin `/` menu — cached quick action content", () => {
expect(chain.insertContentAt).not.toHaveBeenCalled();
});
+
+ it("inserts a skill through the shared slashCommand node shape", () => {
+ const selection = window.getSelection()!;
+ const collapse = vi.spyOn(selection, "collapseToEnd").mockImplementation(() => {});
+ const { editor, chain } = fakeEditor();
+ const suggestion = createBuiltinCommandSuggestion();
+
+ suggestion.command!({
+ editor,
+ range,
+ props: { id: "skill:skill-1", label: "deploy" },
+ } as never);
+
+ expect(chain.insertContentAt).toHaveBeenCalledWith(range, [
+ {
+ type: "slashCommand",
+ attrs: { id: "skill-1", label: "deploy", mentionSuggestionChar: "/" },
+ },
+ { type: "text", text: " " },
+ ]);
+ expect(chain.run).toHaveBeenCalledOnce();
+ collapse.mockRestore();
+ });
+
+ it("keeps /note as plain text", () => {
+ const selection = window.getSelection()!;
+ const collapse = vi.spyOn(selection, "collapseToEnd").mockImplementation(() => {});
+ const { editor, chain } = fakeEditor();
+ const suggestion = createBuiltinCommandSuggestion();
+
+ suggestion.command!({ editor, range, props: { id: "note", label: "note" } } as never);
+
+ expect(chain.insertContentAt).toHaveBeenCalledWith(range, [
+ { type: "text", text: "/note " },
+ ]);
+ collapse.mockRestore();
+ });
});
diff --git a/packages/views/editor/extensions/slash-command-suggestion.tsx b/packages/views/editor/extensions/slash-command-suggestion.tsx
index e169e580d9..9a035360c8 100644
--- a/packages/views/editor/extensions/slash-command-suggestion.tsx
+++ b/packages/views/editor/extensions/slash-command-suggestion.tsx
@@ -9,6 +9,7 @@ import {
useState,
} from "react";
import type { QueryClient } from "@tanstack/react-query";
+import type { Editor } from "@tiptap/core";
import type { SuggestionOptions } from "@tiptap/suggestion";
import { PluginKey } from "@tiptap/pm/state";
import { closeHistory } from "@tiptap/pm/history";
@@ -18,7 +19,7 @@ import { getCurrentWsId } from "@multica/core/platform";
import { canAssignAgentToIssue } from "@multica/core/permissions";
import { isImeComposing } from "@multica/core/utils";
import { workspaceKeys } from "@multica/core/workspace/queries";
-import type { Agent, MemberWithUser } from "@multica/core/types";
+import type { Agent, AgentSkillSummary, MemberWithUser } from "@multica/core/types";
import { useT } from "../../i18n";
import {
createSuggestionPopupRender,
@@ -221,11 +222,45 @@ function buildItems(qc: QueryClient, query: string): SlashCommandItem[] {
null;
const q = query.toLowerCase();
- return rankSkillMatches(activeAgent?.skills ?? [], q)
+ return rankSkillMatches(
+ (activeAgent?.skills ?? []).filter((skill) => skill.enabled !== false),
+ q,
+ )
.slice(0, MAX_ITEMS)
.map((s) => ({ id: s.id, label: s.name, description: s.description ?? "" }));
}
+function insertSlashSkill(
+ editor: Editor,
+ range: { from: number; to: number },
+ id: string,
+ label: string,
+) {
+ const nodeAfter = editor.view.state.selection.$to.nodeAfter;
+ const overrideSpace = nodeAfter?.text?.startsWith(" ");
+ if (overrideSpace) {
+ range.to += 1;
+ }
+
+ editor
+ .chain()
+ .focus()
+ .insertContentAt(range, [
+ {
+ type: "slashCommand",
+ attrs: {
+ id,
+ label,
+ mentionSuggestionChar: "/",
+ },
+ },
+ { type: "text", text: " " },
+ ])
+ .run();
+
+ window.getSelection()?.collapseToEnd();
+}
+
export function createSlashCommandSuggestion(qc: QueryClient): Omit<
SuggestionOptions<SlashCommandItem>,
"editor"
@@ -240,29 +275,7 @@ export function createSlashCommandSuggestion(qc: QueryClient): Omit<
shouldShow: ({ editor, range }) => isTriggerArmedAt(editor, range.from),
items: ({ query }) => buildItems(qc, query),
command: ({ editor, range, props }) => {
- const nodeAfter = editor.view.state.selection.$to.nodeAfter;
- const overrideSpace = nodeAfter?.text?.startsWith(" ");
- if (overrideSpace) {
- range.to += 1;
- }
-
- editor
- .chain()
- .focus()
- .insertContentAt(range, [
- {
- type: "slashCommand",
- attrs: {
- id: props.id,
- label: props.label,
- mentionSuggestionChar: "/",
- },
- },
- { type: "text", text: " " },
- ])
- .run();
-
- window.getSelection()?.collapseToEnd();
+ insertSlashSkill(editor, range, props.id, props.label);
},
render: createSuggestionPopupRender<SlashCommandItem, SlashCommandItem, SlashCommandListRef, SlashCommandListProps>({
pluginKey,
@@ -290,6 +303,8 @@ export const BUILTIN_COMMANDS: SlashCommandItem[] = [
{ id: "note", label: "note", descriptionKey: "note" },
];
+const SKILL_ITEM_PREFIX = "skill:";
+
/** Marks a menu entry as a configured quick action rather than a built-in. */
export const QUICK_ACTION_ITEM_PREFIX = "quick-action:";
@@ -301,24 +316,33 @@ export function quickActionIdFromItem(item: SlashCommandItem): string {
return item.id.slice(QUICK_ACTION_ITEM_PREFIX.length);
}
-// Match on the command label as a prefix only — the description is for display,
-// not search. With a single command this keeps the menu predictable (typing
-// `/no` surfaces `note`; an unrelated `/deploy` shows nothing).
+// Quick actions and built-ins match on label prefix only. Skills use the
+// shared name/description ranking; unrelated path/date queries stay empty.
export function buildBuiltinCommandItems(
query: string,
quickActions: { id: string; name: string; description?: string }[] = [],
+ skills: AgentSkillSummary[] = [],
): SlashCommandItem[] {
const q = query.toLowerCase();
// Quick actions lead: on an issue they are the reason a user reaches for
// `/`, and `/note` is a rarely-used escape hatch.
- const actionItems: SlashCommandItem[] = quickActions.map((a) => ({
- id: `${QUICK_ACTION_ITEM_PREFIX}${a.id}`,
- label: a.name,
- description: a.description || undefined,
- }));
- return [...actionItems, ...BUILTIN_COMMANDS]
- .filter((c) => c.label.toLowerCase().startsWith(q))
- .slice(0, MAX_ITEMS);
+ const actionItems: SlashCommandItem[] = quickActions
+ .filter((action) => action.name.toLowerCase().startsWith(q))
+ .map((action) => ({
+ id: `${QUICK_ACTION_ITEM_PREFIX}${action.id}`,
+ label: action.name,
+ description: action.description || undefined,
+ }));
+ const skillItems: SlashCommandItem[] = q ? rankSkillMatches(skills, q).map((skill) => ({
+ id: `${SKILL_ITEM_PREFIX}${skill.id}`,
+ label: skill.name,
+ description: skill.description ?? "",
+ })) : [];
+ const builtinItems = BUILTIN_COMMANDS.filter((command) =>
+ command.label.toLowerCase().startsWith(q),
+ );
+ const cap = Math.max(0, MAX_ITEMS - builtinItems.length);
+ return [...actionItems, ...skillItems].slice(0, cap).concat(builtinItems);
}
export interface BuiltinCommandSuggestionOptions {
@@ -327,6 +351,8 @@ export interface BuiltinCommandSuggestionOptions {
* every keystroke and catalog notification without remounting the editor.
*/
getQuickActions?: () => { id: string; name: string; description?: string }[];
+ /** Reads enabled skills for the draft's current target agents when the query is nonempty. */
+ getSkills?: (editor: Editor) => AgentSkillSummary[];
subscribeQuickActions?: (refresh: () => void) => () => void;
/**
* Builds draft text synchronously from the cached catalog. Returning ""
@@ -346,7 +372,11 @@ export function createBuiltinCommandSuggestion(
// Only open over a `/` the user actually typed, so a pasted path
// (`/usr/local/bin`) never opens the command menu (MUL-5429).
shouldShow: ({ editor, range }) => isTriggerArmedAt(editor, range.from),
- items: ({ query }) => buildBuiltinCommandItems(query, options.getQuickActions?.() ?? []),
+ items: ({ editor, query }) => buildBuiltinCommandItems(
+ query,
+ options.getQuickActions?.() ?? [],
+ query ? (options.getSkills?.(editor) ?? []) : [],
+ ),
command: ({ editor, range, props }) => {
if (isQuickActionItem(props)) {
const content = options.getQuickActionContent?.(quickActionIdFromItem(props));
@@ -366,6 +396,16 @@ export function createBuiltinCommandSuggestion(
return;
}
+ if (props.id.startsWith(SKILL_ITEM_PREFIX)) {
+ insertSlashSkill(
+ editor,
+ range,
+ props.id.slice(SKILL_ITEM_PREFIX.length),
+ props.label,
+ );
+ return;
+ }
+
// Insert the plain-text prefix (e.g. "/note ") rather than a rich node,
// so a menu selection and a hand-typed command are byte-identical and the
// backend can detect the marker with a simple prefix match. The trailing
@@ -385,7 +425,11 @@ export function createBuiltinCommandSuggestion(
getProps: (props) => ({
// Read the current catalog even when Tiptap finishes an older items
// request after a catalog notification.
- items: buildBuiltinCommandItems(props.query, options.getQuickActions?.() ?? []),
+ items: buildBuiltinCommandItems(
+ props.query,
+ options.getQuickActions?.() ?? [],
+ props.query ? (options.getSkills?.(props.editor) ?? []) : [],
+ ),
query: props.query,
command: props.command,
hideOnEmpty: true,
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index f26efbd584..9983382fc2 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -3,8 +3,11 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
-import type { Attachment } from "@multica/core/types";
+import type { AgentSkillSummary, Attachment } from "@multica/core/types";
+import type { Editor } from "@tiptap/core";
import { useCommentComposerStore, useCommentDraftStore } from "@multica/core/issues/stores";
+import { issueKeys } from "@multica/core/issues/queries";
+import { workspaceKeys } from "@multica/core/workspace/queries";
import { WorkspaceSlugProvider } from "@multica/core/paths";
import { renderWithI18n } from "../../test/i18n";
import { CommentInput } from "./comment-input";
@@ -14,8 +17,13 @@ import { ReplyInput } from "./reply-input";
type QuickActionMenuProp = {
getQuickActions?: () => { id: string; name: string; description?: string }[];
getQuickActionContent?: (quickActionId: string) => string;
+ getSkills?: (editor: Editor) => AgentSkillSummary[];
};
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: { getState: () => ({ user: { id: "user-1" } }) },
+}));
+
// Uploads now flow through the module-level coordinator, which calls
// `api.uploadFile(file, ctx, signal)` (MUL-5181). Tests drive uploads by
// mocking that call directly rather than the old `uploadWithToast` hook.
@@ -23,6 +31,10 @@ const apiUploadFile = vi.hoisted(() => vi.fn());
const apiListWorkspaces = vi.hoisted(() => vi.fn());
const apiListQuickActions = vi.hoisted(() => vi.fn());
const apiRenderQuickAction = vi.hoisted(() => vi.fn());
+const apiGetIssue = vi.hoisted(() => vi.fn());
+const apiListAgents = vi.hoisted(() => vi.fn());
+const apiListSquads = vi.hoisted(() => vi.fn());
+const apiListMembers = vi.hoisted(() => vi.fn());
const apiPreviewCommentTriggers = vi.hoisted(() => vi.fn());
const apiListTasksByIssue = vi.hoisted(() => vi.fn());
const apiCancelTask = vi.hoisted(() => vi.fn());
@@ -62,6 +74,10 @@ vi.mock("@multica/core/api", () => ({
listWorkspaces: apiListWorkspaces,
listQuickActions: apiListQuickActions,
renderQuickAction: apiRenderQuickAction,
+ getIssue: apiGetIssue,
+ listAgents: apiListAgents,
+ listSquads: apiListSquads,
+ listMembers: apiListMembers,
previewCommentTriggers: apiPreviewCommentTriggers,
listTasksByIssue: apiListTasksByIssue,
cancelTask: apiCancelTask,
@@ -300,6 +316,10 @@ beforeEach(() => {
apiListWorkspaces.mockReset();
apiListQuickActions.mockReset();
apiRenderQuickAction.mockReset();
+ apiGetIssue.mockReset().mockResolvedValue({ id: "issue-1", assignee_type: null, assignee_id: null });
+ apiListAgents.mockReset().mockResolvedValue([]);
+ apiListSquads.mockReset().mockResolvedValue([]);
+ apiListMembers.mockReset().mockResolvedValue([{ user_id: "user-1", role: "member", name: "User" }]);
apiPreviewCommentTriggers.mockReset();
apiListTasksByIssue.mockReset();
apiCancelTask.mockReset();
@@ -337,13 +357,14 @@ describe("quick action `/` menu", () => {
],
});
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- return renderWithI18n(
+ const view = renderWithI18n(
<QueryClientProvider client={queryClient}>
{/* useQuickActionMenu resolves the workspace from the slug context; without
it the catalog query stays disabled and every menu reads as empty. */}
<WorkspaceSlugProvider slug="acme">{ui}</WorkspaceSlugProvider>
</QueryClientProvider>,
);
+ return { ...view, queryClient };
}
// Both composers post to the same issue, so `/` must offer the same catalog in
@@ -371,6 +392,63 @@ describe("quick action `/` menu", () => {
},
];
+ async function replySkillIds({
+ timeline,
+ parentId = "comment-1",
+ targetMissing = false,
+ squads = [],
+ }: {
+ timeline: unknown[];
+ parentId?: string;
+ targetMissing?: boolean;
+ squads?: unknown[];
+ }) {
+ const agentIds = [
+ "cccccccc-cccc-cccc-cccc-cccccccccccc",
+ "parent-agent",
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
+ "root-leader",
+ ];
+ apiGetIssue.mockResolvedValue({
+ id: "issue-1",
+ assignee_type: "agent",
+ assignee_id: "cccccccc-cccc-cccc-cccc-cccccccccccc",
+ });
+ apiListAgents.mockResolvedValue(agentIds.map((id) => ({
+ id,
+ runtime_id: "runtime-1",
+ archived_at: null,
+ owner_id: null,
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ skills: [{ id: `${id}-skill`, name: id, description: "" }],
+ })));
+ apiListSquads.mockResolvedValue(squads);
+ const view = renderInWorkspace(
+ <ReplyInput
+ issueId="issue-1"
+ parentId={parentId}
+ avatarType="member"
+ avatarId="user-1"
+ targetMissing={targetMissing}
+ onSubmit={vi.fn().mockResolvedValue(true)}
+ />,
+ );
+ view.queryClient.setQueryData(issueKeys.timeline("issue-1"), timeline);
+ activateComposer("reply-composer-shell");
+ await waitFor(() => {
+ expect(view.queryClient.getQueryData(issueKeys.detail("ws-1", "issue-1"))).toBeDefined();
+ expect(view.queryClient.getQueryData(workspaceKeys.agents("ws-1"))).toHaveLength(agentIds.length);
+ if (squads.length) {
+ expect(view.queryClient.getQueryData(workspaceKeys.squads("ws-1"))).toHaveLength(squads.length);
+ }
+ });
+ const editor = { state: { doc: { descendants: () => {} } } } as unknown as Editor;
+ const ids = editorQuickActionMenu.last?.getSkills?.(editor).map((skill) => skill.id) ?? [];
+ expect(apiListTasksByIssue).not.toHaveBeenCalled();
+ return ids;
+ }
+
for (const composer of composers) {
it(`offers the workspace's active quick actions in the ${composer.name}`, async () => {
renderInWorkspace(composer.element);
@@ -392,7 +470,128 @@ describe("quick action `/` menu", () => {
});
expect(apiRenderQuickAction).not.toHaveBeenCalled();
});
+
+ it(`resolves Issue assignee skills in the ${composer.name}`, async () => {
+ apiPreviewCommentTriggers.mockResolvedValue({ agents: [], blocked: [] });
+ apiGetIssue.mockResolvedValue({
+ id: "issue-1",
+ assignee_type: "agent",
+ assignee_id: "agent-1",
+ });
+ apiListAgents.mockResolvedValue([{
+ id: "agent-1",
+ runtime_id: "runtime-1",
+ archived_at: null,
+ owner_id: null,
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ skills: [{ id: "skill-1", name: "deploy", description: "Ship changes" }],
+ }]);
+ renderInWorkspace(composer.element);
+ activateComposer(composer.shell);
+ const editor = {
+ state: { doc: { descendants: () => {} } },
+ } as unknown as Editor;
+
+ await waitFor(() => {
+ expect(editorQuickActionMenu.last?.getSkills?.(editor).map((skill) => skill.id))
+ .toEqual(["skill-1"]);
+ });
+
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "draft" } });
+ await waitFor(() => expect(apiPreviewCommentTriggers).toHaveBeenCalled());
+ await waitFor(() => expect(editorQuickActionMenu.last?.getSkills?.(editor)).toEqual([]));
+ });
}
+
+ it("uses the parent comment agent's skills in ReplyInput", async () => {
+ const parent = {
+ type: "comment",
+ id: "comment-1",
+ actor_type: "agent",
+ actor_id: "parent-agent",
+ content: "Agent answer",
+ parent_id: null,
+ };
+
+ expect(await replySkillIds({ timeline: [parent] })).toEqual(["parent-agent-skill"]);
+ });
+
+ it("uses the conversation owner when ReplyInput targets a member root", async () => {
+ const root = {
+ type: "comment",
+ id: "root",
+ actor_type: "member",
+ actor_id: "user-2",
+ content: "Please investigate",
+ parent_id: null,
+ };
+ const agentReply = {
+ ...root,
+ id: "agent-reply",
+ actor_type: "agent",
+ actor_id: "parent-agent",
+ content: "Agent answer",
+ parent_id: root.id,
+ };
+
+ expect(await replySkillIds({ timeline: [root, agentReply], parentId: root.id }))
+ .toEqual(["parent-agent-skill"]);
+ });
+
+ it.each([
+ {
+ name: "agent",
+ content: "[@Root](mention://agent/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa) [@Assignee](mention://agent/cccccccc-cccc-cccc-cccc-cccccccccccc)",
+ squads: [],
+ expected: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa-skill",
+ },
+ {
+ name: "squad",
+ content: "[@Team](mention://squad/dddddddd-dddd-dddd-dddd-dddddddddddd) [@Assignee](mention://agent/cccccccc-cccc-cccc-cccc-cccccccccccc)",
+ squads: [{ id: "dddddddd-dddd-dddd-dddd-dddddddddddd", leader_id: "root-leader", archived_at: null }],
+ expected: "root-leader-skill",
+ },
+ ])("uses the first root $name mention in ReplyInput", async ({ content, squads, expected }) => {
+ const root = {
+ type: "comment",
+ id: "root",
+ actor_type: "member",
+ actor_id: "user-2",
+ content,
+ parent_id: null,
+ };
+ const reply = { ...root, id: "comment-1", content: "Reply", parent_id: root.id };
+
+ expect(await replySkillIds({ timeline: [root, reply], squads })).toEqual([expected]);
+ });
+
+ it("keeps member-to-member ReplyInput threads silent", async () => {
+ const root = {
+ type: "comment",
+ id: "root",
+ actor_type: "member",
+ actor_id: "user-2",
+ content: "Question",
+ parent_id: null,
+ };
+ const reply = { ...root, id: "comment-1", content: "Reply", parent_id: root.id };
+
+ expect(await replySkillIds({ timeline: [root, reply] })).toEqual([]);
+ });
+
+ it("returns no ReplyInput skills when the target is missing", async () => {
+ const parent = {
+ type: "comment",
+ id: "comment-1",
+ actor_type: "agent",
+ actor_id: "parent-agent",
+ content: "Agent answer",
+ parent_id: null,
+ };
+
+ expect(await replySkillIds({ timeline: [parent], targetMissing: true })).toEqual([]);
+ });
});
/**
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index 6981d7ed61..62ba7d2fad 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -62,9 +62,6 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat
const uploadGate = useUploadGate(editorRef);
// Subscribe to the persisted draft so text written into it from outside
// this composer shows up even while it is mounted.
- // Quick actions in the `/` menu: picking one inserts the cached
- // body so the user can edit before sending, instead of firing immediately.
- const quickActionMenu = useQuickActionMenu();
const draftKey = `new:${issueId}` as const;
const [initialDraft] = useState(() =>
useCommentDraftStore.getState().getDraft(draftKey),
@@ -76,7 +73,8 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat
const previewAnnotations = useMemo(() => annotationsWithPending(annotations, annotationComposer?.pending), [annotations, annotationComposer?.pending]);
const composedContent = useMemo(() => composeAnnotatedReply(content, previewAnnotations), [content, previewAnnotations]);
const canSend = annotations.length ? hasReplyIntent(content, annotations) : !isEmpty;
- const triggerPreview = useCommentTriggerPreview({ issueId, content: canSend || annotationComposer?.pending.note.trim() ? composedContent : "" });
+ const previewContent = canSend || annotationComposer?.pending.note.trim() ? composedContent : "";
+ const triggerPreview = useCommentTriggerPreview({ issueId, content: previewContent });
// Uploads for this composer session (MUL-5181). Owned by the module-level
// coordinator and persisted in the draft store, so closing/scrolling the
// composer away no longer drops an in-flight upload — its result lands in the
@@ -111,6 +109,8 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat
useCommentDraftStore.getState().getUploads(draftKey).length > 0,
editorRef,
});
+ // Inactive shells must not mount query observers or duplicate cold reads.
+ const quickActionMenu = useQuickActionMenu(issueId, { enabled: lazy.active, triggerPreview, previewContent });
const { isDragOver, dropZoneProps } = useFileDropZone({
onDrop: lazy.uploadOrQueue,
});
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index 02a8249027..310101adcd 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -98,10 +98,6 @@ function ReplyInput({
const composerRef = useRef<HTMLDivElement>(null);
// See CommentInput — replying mid-upload posts without the file.
const uploadGate = useUploadGate(editorRef);
- // Quick actions in the `/` menu — same catalog and same insert-don't-run
- // behavior as the top-level composer. A reply posts to the same issue, so
- // `/` has to offer the same thing here (MUL-5588).
- const quickActionMenu = useQuickActionMenu();
// If a draft key is provided, hydrate from store on mount (defaultValue is
// the only injection point on ContentEditorRef) and flush on every onUpdate.
const [initialDraft] = useState(() =>
@@ -116,7 +112,8 @@ function ReplyInput({
const canSend = !targetMissing && (annotations.length ? hasReplyIntent(content, annotations) : !isEmpty);
// Saving the first pending annotation will fix the target before submission.
const previewParentId = annotations.length === 0 ? annotationComposer?.pending.sourceCommentId ?? parentId : parentId;
- const triggerPreview = useCommentTriggerPreview({ issueId, parentId: previewParentId, content: !targetMissing && (canSend || annotationComposer?.pending.note.trim()) ? composedContent : "" });
+ const previewContent = !targetMissing && (canSend || annotationComposer?.pending.note.trim()) ? composedContent : "";
+ const triggerPreview = useCommentTriggerPreview({ issueId, parentId: previewParentId, content: previewContent });
// Uploads for this reply session (MUL-5181) — owned by the coordinator. With
// a draftKey they persist in the draft store so scroll-out/close no longer
// drops an in-flight upload; without one (no persistence context) they fall
@@ -153,6 +150,13 @@ function ReplyInput({
(draftKey ? useCommentDraftStore.getState().getUploads(draftKey).length > 0 : false),
editorRef,
});
+ const quickActionMenu = useQuickActionMenu(issueId, {
+ enabled: lazy.active,
+ parentId: previewParentId,
+ targetMissing,
+ triggerPreview,
+ previewContent,
+ });
useImperativeHandle(handleRef, () => ({ focus: () => lazy.activate() }), [lazy]);
const { isDragOver, dropZoneProps } = useFileDropZone({
onDrop: lazy.uploadOrQueue,
diff --git a/packages/views/issues/hooks/use-quick-action-menu.test.ts b/packages/views/issues/hooks/use-quick-action-menu.test.ts
new file mode 100644
index 0000000000..231f33631e
--- /dev/null
+++ b/packages/views/issues/hooks/use-quick-action-menu.test.ts
@@ -0,0 +1,430 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { Editor } from "@tiptap/core";
+import type { Node } from "@tiptap/pm/model";
+import type { Agent, AgentSkillSummary, AgentTask, MemberWithUser, Squad, TimelineEntry } from "@multica/core/types";
+import { createEditorExtensions } from "../../editor/extensions";
+import { resolveIssueSlashSkills, type IssueSlashSkillContext } from "./use-quick-action-menu";
+
+const editors: Editor[] = [];
+
+afterEach(() => {
+ editors.splice(0).forEach((editor) => editor.destroy());
+});
+
+function skill(id: string, overrides: Partial<AgentSkillSummary> = {}): AgentSkillSummary {
+ return { id, name: id, description: `${id} description`, ...overrides };
+}
+
+function agent(
+ id: string,
+ skills: AgentSkillSummary[],
+ overrides: Partial<Agent> = {},
+): Agent {
+ return {
+ id,
+ skills,
+ runtime_id: "runtime-1",
+ archived_at: null,
+ owner_id: null,
+ permission_mode: "public_to",
+ invocation_targets: [{ target_type: "workspace", target_id: null }],
+ ...overrides,
+ } as Agent;
+}
+
+function squad(id: string, leaderId: string, archivedAt: string | null = null): Squad {
+ return { id, leader_id: leaderId, archived_at: archivedAt } as Squad;
+}
+
+function context(overrides: Partial<IssueSlashSkillContext> = {}): IssueSlashSkillContext {
+ return {
+ agents: [],
+ squads: [],
+ members: [{ user_id: "user-1", role: "member" } as MemberWithUser],
+ userId: "user-1",
+ ...overrides,
+ };
+}
+
+function makeEditor(): Editor {
+ const editor = new Editor({ extensions: createEditorExtensions({}) });
+ editors.push(editor);
+ return editor;
+}
+
+interface TestMentionContent {
+ type: "mention";
+ attrs: { type: string; id: string; label: string; mentionSuggestionChar: string };
+}
+
+function mention(type: string, id: string): TestMentionContent {
+ return {
+ type: "mention",
+ attrs: { type, id, label: id, mentionSuggestionChar: "@" },
+ };
+}
+
+function docWithMentions(...mentions: TestMentionContent[]): Node {
+ const editor = makeEditor();
+ if (mentions.length) editor.commands.insertContent(mentions);
+ return editor.state.doc;
+}
+
+function timelineComment(
+ id: string,
+ overrides: Partial<TimelineEntry> = {},
+): TimelineEntry {
+ return {
+ type: "comment",
+ id,
+ actor_type: "member",
+ actor_id: "user-2",
+ content: "",
+ parent_id: null,
+ created_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+describe("resolveIssueSlashSkills", () => {
+ it.each([undefined, ""])("excludes an agent with runtime_id %s without falling back", (runtimeId) => {
+ const unavailable = agent("unavailable", [skill("unavailable-skill")], { runtime_id: runtimeId });
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const data = context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [unavailable, assignee],
+ });
+
+ expect(resolveIssueSlashSkills(docWithMentions(mention("agent", unavailable.id)), data)).toEqual([]);
+ expect(resolveIssueSlashSkills(docWithMentions(), {
+ ...data,
+ issue: { assignee_type: "agent", assignee_id: unavailable.id },
+ })).toEqual([]);
+ });
+
+ it("reads a newly inserted explicit agent synchronously and locks out the assignee", () => {
+ const editor = makeEditor();
+ const target = agent("explicit", [skill("explicit-skill")]);
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const data = context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [target, assignee],
+ });
+
+ expect(resolveIssueSlashSkills(editor.state.doc, data).map((item) => item.id))
+ .toEqual(["assignee-skill"]);
+
+ editor.commands.insertContent([
+ mention("agent", target.id),
+ { type: "text", text: " " },
+ ]);
+
+ expect(resolveIssueSlashSkills(editor.state.doc, data).map((item) => item.id))
+ .toEqual(["explicit-skill"]);
+ });
+
+ it("maps an explicit squad to its leader ahead of the Issue assignee", () => {
+ const leader = agent("leader", [skill("leader-skill")]);
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const doc = docWithMentions(mention("squad", "squad-1"));
+
+ expect(resolveIssueSlashSkills(doc, context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [leader, assignee],
+ squads: [squad("squad-1", leader.id)],
+ })).map((item) => item.id)).toEqual(["leader-skill"]);
+ });
+
+ it("unions multiple targets in document order and deduplicates agents and skills", () => {
+ const first = agent("first", [skill("one"), skill("two")]);
+ const second = agent("second", [skill("two"), skill("three")]);
+ const leader = agent("leader", [skill("four"), skill("one")]);
+ const doc = docWithMentions(
+ mention("agent", first.id),
+ mention("agent", second.id),
+ mention("squad", "squad-1"),
+ mention("agent", first.id),
+ );
+
+ expect(resolveIssueSlashSkills(doc, context({
+ agents: [first, second, leader],
+ squads: [squad("squad-1", leader.id)],
+ })).map((item) => item.id)).toEqual(["one", "two", "three", "four"]);
+ });
+
+ it("filters archived and unauthorized targets and disabled skills without falling back", () => {
+ const archived = agent("archived", [skill("archived-skill")], { archived_at: "2026-01-01" });
+ const privateAgent = agent("private", [skill("private-skill")], {
+ owner_id: "other-user",
+ permission_mode: "private",
+ invocation_targets: [],
+ });
+ const allowed = agent("allowed", [
+ skill("enabled"),
+ skill("disabled", { enabled: false }),
+ ]);
+ const archivedSquadLeader = agent("squad-leader", [skill("archived-squad-skill")]);
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const doc = docWithMentions(
+ mention("agent", archived.id),
+ mention("agent", privateAgent.id),
+ mention("squad", "archived-squad"),
+ mention("agent", allowed.id),
+ );
+
+ expect(resolveIssueSlashSkills(doc, context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [archived, privateAgent, allowed, archivedSquadLeader, assignee],
+ squads: [squad("archived-squad", archivedSquadLeader.id, "2026-01-01")],
+ })).map((item) => item.id)).toEqual(["enabled"]);
+ });
+
+ it.each([
+ { assigneeType: "agent" as const, squadId: undefined },
+ { assigneeType: "squad" as const, squadId: "squad-1" },
+ ])("falls back to an Issue $assigneeType assignee", ({ assigneeType, squadId }) => {
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const assigneeId = assigneeType === "squad" ? squadId! : assignee.id;
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ issue: { assignee_type: assigneeType, assignee_id: assigneeId },
+ agents: [assignee],
+ squads: squadId ? [squad(squadId, assignee.id)] : [],
+ })).map((item) => item.id)).toEqual(["assignee-skill"]);
+ });
+
+ it.each([null, "member" as const])(
+ "returns no skills for an Issue assigned to %s without explicit targets",
+ (assigneeType) => {
+ const available = agent("available", [skill("unrelated-skill")]);
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ issue: { assignee_type: assigneeType, assignee_id: assigneeType ? "user-2" : null },
+ agents: [available],
+ }))).toEqual([]);
+ },
+ );
+
+ it.each(["member", "all"])("suppresses the Issue assignee fallback for @%s", (type) => {
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const doc = docWithMentions(mention(type, type === "all" ? "all" : "user-2"));
+
+ expect(resolveIssueSlashSkills(doc, context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [assignee],
+ }))).toEqual([]);
+ });
+
+ it("keeps an explicit agent target when member and all mentions are present", () => {
+ const explicit = agent("explicit", [skill("explicit-skill")]);
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const doc = docWithMentions(
+ mention("member", "user-2"),
+ mention("all", "all"),
+ mention("agent", explicit.id),
+ );
+
+ expect(resolveIssueSlashSkills(doc, context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [explicit, assignee],
+ })).map((item) => item.id)).toEqual(["explicit-skill"]);
+ });
+
+ it("does not let issue or project mentions suppress the assignee fallback", () => {
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const doc = docWithMentions(
+ mention("issue", "issue-2"),
+ mention("project", "project-2"),
+ );
+
+ expect(resolveIssueSlashSkills(doc, context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [assignee],
+ })).map((item) => item.id)).toEqual(["assignee-skill"]);
+ });
+
+ it("returns no skills for an archived Issue squad assignee", () => {
+ const leader = agent("leader", [skill("leader-skill")]);
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ issue: { assignee_type: "squad", assignee_id: "squad-1" },
+ agents: [leader],
+ squads: [squad("squad-1", leader.id, "2026-01-01")],
+ }))).toEqual([]);
+ });
+
+ it("routes a reply to its agent parent author instead of the Issue assignee", () => {
+ const parentAuthor = agent("parent-author", [skill("parent-skill")]);
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const parent = timelineComment("parent", {
+ actor_type: "agent",
+ actor_id: parentAuthor.id,
+ parent_id: "root",
+ });
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [parentAuthor, assignee],
+ parentId: parent.id,
+ timeline: [parent],
+ })).map((item) => item.id)).toEqual(["parent-skill"]);
+ });
+
+ it("uses the first explicit agent in a member root comment", () => {
+ const first = agent("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", [skill("first-skill")]);
+ const second = agent("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", [skill("second-skill")]);
+ const root = timelineComment("root", {
+ content: `[@First](mention://agent/${first.id}) [@Second](mention://agent/${second.id})`,
+ });
+ const reply = timelineComment("reply", { parent_id: root.id });
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ agents: [first, second],
+ parentId: reply.id,
+ timeline: [root, reply],
+ })).map((item) => item.id)).toEqual(["first-skill"]);
+ });
+
+ it("maps an explicit squad in a member root comment to its leader", () => {
+ const leader = agent("leader", [skill("leader-skill")]);
+ const squadId = "cccccccc-cccc-cccc-cccc-cccccccccccc";
+ const root = timelineComment("root", {
+ content: `[@Team](mention://squad/${squadId})`,
+ });
+ const reply = timelineComment("reply", { parent_id: root.id });
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ agents: [leader],
+ squads: [squad(squadId, leader.id)],
+ parentId: reply.id,
+ timeline: [root, reply],
+ })).map((item) => item.id)).toEqual(["leader-skill"]);
+ });
+
+ it("does not skip an unavailable first root mention for a later target or assignee", () => {
+ const archived = agent("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", [skill("archived-skill")], { archived_at: "2026-01-01" });
+ const second = agent("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", [skill("second-skill")]);
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const root = timelineComment("root", {
+ content: `[@Archived](mention://agent/${archived.id}) [@Second](mention://agent/${second.id})`,
+ });
+ const reply = timelineComment("reply", { parent_id: root.id });
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [archived, second, assignee],
+ parentId: reply.id,
+ timeline: [root, reply],
+ }))).toEqual([]);
+ });
+
+ it("uses the conversation owner when replying directly to a member root", () => {
+ const owner = agent("owner", [skill("owner-skill")]);
+ const root = timelineComment("root");
+ const tasks = [{ agent_id: owner.id, trigger_comment_id: root.id } as AgentTask];
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ agents: [owner],
+ parentId: root.id,
+ timeline: [root],
+ tasks,
+ })).map((item) => item.id)).toEqual(["owner-skill"]);
+ });
+
+ it("uses the conversation owner from a coalesced root comment", () => {
+ const owner = agent("owner", [skill("owner-skill")]);
+ const root = timelineComment("root");
+ const tasks = [{
+ agent_id: owner.id,
+ trigger_comment_id: "latest-comment",
+ coalesced_comment_ids: [root.id],
+ } as AgentTask];
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ agents: [owner],
+ parentId: root.id,
+ timeline: [root],
+ tasks,
+ })).map((item) => item.id)).toEqual(["owner-skill"]);
+ });
+
+ it("uses task and same-thread agent owners for a nested member reply", () => {
+ const taskOwner = agent("task-owner", [skill("task-skill")]);
+ const replyOwner = agent("reply-owner", [skill("reply-skill")]);
+ const root = timelineComment("root");
+ const agentReply = timelineComment("agent-reply", {
+ actor_type: "agent",
+ actor_id: replyOwner.id,
+ parent_id: root.id,
+ });
+ const memberReply = timelineComment("member-reply", { parent_id: agentReply.id });
+ const tasks = [{ agent_id: taskOwner.id, trigger_comment_id: root.id } as AgentTask];
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ agents: [taskOwner, replyOwner],
+ parentId: memberReply.id,
+ timeline: [root, agentReply, memberReply],
+ tasks,
+ })).map((item) => item.id)).toEqual(["task-skill", "reply-skill"]);
+ });
+
+ it("keeps plain member-to-member replies silent", () => {
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const root = timelineComment("root");
+ const reply = timelineComment("reply", { parent_id: root.id });
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [assignee],
+ parentId: reply.id,
+ timeline: [root, reply],
+ }))).toEqual([]);
+ });
+
+ it("returns no skills when the reply target is missing", () => {
+ const explicit = agent("explicit", [skill("explicit-skill")]);
+
+ expect(resolveIssueSlashSkills(docWithMentions(mention("agent", explicit.id)), context({
+ agents: [explicit],
+ targetMissing: true,
+ }))).toEqual([]);
+ });
+
+ it("returns no skills when a loaded timeline lacks the parent or contains only its tombstone", () => {
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const base = context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [assignee],
+ parentId: "parent",
+ });
+ const deleted = timelineComment("parent", {
+ actor_type: "agent",
+ actor_id: assignee.id,
+ deleted_at: "2026-01-01",
+ });
+
+ expect(resolveIssueSlashSkills(docWithMentions(), { ...base, timeline: [] })).toEqual([]);
+ expect(resolveIssueSlashSkills(docWithMentions(), { ...base, timeline: [deleted] })).toEqual([]);
+ });
+
+ it("retains the assignee fallback while the timeline is not cached", () => {
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [assignee],
+ parentId: "parent",
+ })).map((item) => item.id)).toEqual(["assignee-skill"]);
+ });
+
+ it("retains the assignee fallback for a non-member parent without thread owners", () => {
+ const assignee = agent("assignee", [skill("assignee-skill")]);
+ const parent = timelineComment("parent", { actor_type: "system", actor_id: "system" });
+
+ expect(resolveIssueSlashSkills(docWithMentions(), context({
+ issue: { assignee_type: "agent", assignee_id: assignee.id },
+ agents: [assignee],
+ parentId: parent.id,
+ timeline: [parent],
+ })).map((item) => item.id)).toEqual(["assignee-skill"]);
+ });
+});
diff --git a/packages/views/issues/hooks/use-quick-action-menu.ts b/packages/views/issues/hooks/use-quick-action-menu.ts
index 0ba06326f4..aaba7f0e39 100644
--- a/packages/views/issues/hooks/use-quick-action-menu.ts
+++ b/packages/views/issues/hooks/use-quick-action-menu.ts
@@ -2,14 +2,166 @@
import { useCallback, useMemo } from "react";
import { toast } from "sonner";
-import { useQuery } from "@tanstack/react-query";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import type { Editor } from "@tiptap/core";
+import type { Node } from "@tiptap/pm/model";
+import { useAuthStore } from "@multica/core/auth";
import { useCurrentWorkspace } from "@multica/core/paths";
+import { canAssignAgentToIssue } from "@multica/core/permissions";
+import { isDeletedComment } from "@multica/core/issues/comment-deletion";
+import { parseMentions } from "@multica/core/issues/comment-trigger-outcomes";
+import { issueDetailOptions, issueKeys } from "@multica/core/issues/queries";
import { buildQuickActionBody, quickActionListOptions } from "@multica/core/quick-actions";
+import type { Agent, AgentSkillSummary, AgentTask, Issue, MemberWithUser, Squad, TimelineEntry } from "@multica/core/types";
+import {
+ agentListOptions,
+ memberListOptions,
+ squadListOptions,
+} from "@multica/core/workspace/queries";
import { useT } from "../../i18n";
+import { commentTriggerPreviewSignature, type UseCommentTriggerPreviewResult } from "./use-comment-trigger-preview";
+
+export interface IssueSlashSkillContext {
+ issue?: Pick<Issue, "assignee_type" | "assignee_id">;
+ agents: Agent[];
+ squads: Squad[];
+ members: MemberWithUser[];
+ userId: string | null;
+ parentId?: string;
+ targetMissing?: boolean;
+ timeline?: TimelineEntry[];
+ tasks?: AgentTask[];
+}
+
+function threadRoot(
+ comment: TimelineEntry,
+ comments: Map<string, TimelineEntry>,
+): TimelineEntry | undefined {
+ const seen = new Set<string>();
+ let root = comment;
+ while (root.parent_id) {
+ if (seen.has(root.id)) return undefined;
+ seen.add(root.id);
+ const parent = comments.get(root.parent_id);
+ if (!parent) return undefined;
+ root = parent;
+ }
+ return root;
+}
+
+/** Undefined permits the Issue assignee fallback; an empty list locks routing to no target. */
+function resolveThreadSlashTargetIds(
+ parentId: string,
+ timeline: TimelineEntry[] | undefined,
+ tasks: AgentTask[] | undefined,
+ squadsById: Map<string, Squad>,
+): string[] | undefined {
+ if (!timeline) return undefined;
+ const comments = new Map(
+ timeline.filter((entry) => entry.type === "comment").map((entry) => [entry.id, entry]),
+ );
+ const parent = comments.get(parentId);
+ if (!parent || isDeletedComment(parent)) return [];
+ if (parent.actor_type === "agent") return parent.actor_id ? [parent.actor_id] : [];
+
+ const root = threadRoot(parent, comments);
+ if (root?.actor_type === "member") {
+ const explicit = parseMentions(root.content ?? "").find(
+ (mention) => mention.type === "agent" || mention.type === "squad",
+ );
+ if (explicit) {
+ if (explicit.type === "agent") return [explicit.id];
+ const squad = squadsById.get(explicit.id);
+ return squad && !squad.archived_at ? [squad.leader_id] : [];
+ }
+ const ownerIds = (tasks ?? [])
+ .filter((task) =>
+ task.trigger_comment_id === root.id || task.coalesced_comment_ids?.includes(root.id))
+ .map((task) => task.agent_id);
+ for (const comment of comments.values()) {
+ if (comment.actor_type === "agent" && threadRoot(comment, comments)?.id === root.id) {
+ ownerIds.push(comment.actor_id);
+ }
+ }
+ if (ownerIds.length > 0) return ownerIds;
+ }
+
+ if (parent.actor_type === "member") return [];
+ return undefined;
+}
+
+/** Reads target mentions from the live document; no Markdown/debounce round-trip. */
+export function resolveIssueSlashSkills(
+ doc: Node,
+ { issue, agents, squads, members, userId, parentId, targetMissing, timeline, tasks }: IssueSlashSkillContext,
+): AgentSkillSummary[] {
+ if (targetMissing) return [];
+ const agentsById = new Map(agents.map((agent) => [agent.id, agent]));
+ const squadsById = new Map(squads.map((squad) => [squad.id, squad]));
+ const targetIds: string[] = [];
+ let hasExplicitTarget = false;
+ let hasMemberOrAllMention = false;
+
+ doc.descendants((node) => {
+ if (node.type.name !== "mention") return;
+ const { type, id } = node.attrs as { type?: string; id?: string };
+ if (!id) return;
+ if (type === "member" || type === "all") hasMemberOrAllMention = true;
+ if (type === "agent") {
+ hasExplicitTarget = true;
+ targetIds.push(id);
+ } else if (type === "squad") {
+ hasExplicitTarget = true;
+ const squad = squadsById.get(id);
+ if (squad && !squad.archived_at) targetIds.push(squad.leader_id);
+ }
+ });
+
+ // Explicit agent/squad mentions win over member/all; without one, those
+ // mentions suppress every implicit route just as comment creation does.
+ if (!hasExplicitTarget) {
+ if (hasMemberOrAllMention) return [];
+ const threadTargets = parentId
+ ? resolveThreadSlashTargetIds(parentId, timeline, tasks, squadsById)
+ : undefined;
+ if (threadTargets) {
+ targetIds.push(...threadTargets);
+ } else if (issue?.assignee_id) {
+ if (issue.assignee_type === "agent") {
+ targetIds.push(issue.assignee_id);
+ } else if (issue.assignee_type === "squad") {
+ const squad = squadsById.get(issue.assignee_id);
+ if (squad && !squad.archived_at) targetIds.push(squad.leader_id);
+ }
+ }
+ }
+
+ const memberRole = members.find((member) => member.user_id === userId)?.role ?? null;
+ const seenAgentIds = new Set<string>();
+ const seenSkillIds = new Set<string>();
+ const skills: AgentSkillSummary[] = [];
+ for (const agentId of targetIds) {
+ if (seenAgentIds.has(agentId)) continue;
+ seenAgentIds.add(agentId);
+ const agent = agentsById.get(agentId);
+ if (
+ !agent ||
+ agent.archived_at ||
+ !agent.runtime_id ||
+ !canAssignAgentToIssue(agent, { userId, role: memberRole }).allowed
+ ) continue;
+ for (const skill of agent.skills) {
+ if (skill.enabled === false || seenSkillIds.has(skill.id)) continue;
+ seenSkillIds.add(skill.id);
+ skills.push(skill);
+ }
+ }
+ return skills;
+}
/**
* Supplies the comment composer's `/` menu with this workspace's quick actions
- * (MUL-5465).
+ * and the enabled skills bound to its current Issue target agents (MUL-5465).
*
* Picking one INSERTS the cached body rather than running it — the composer
* path exists precisely for the "this time is different" case, so the user
@@ -25,13 +177,44 @@ import { useT } from "../../i18n";
* workspace route, and an enhancement like this must degrade to "no quick
* actions in the menu", never take the composer down with it.
*/
-export function useQuickActionMenu() {
+export function useQuickActionMenu(
+ issueId?: string,
+ { enabled = true, parentId, targetMissing = false, triggerPreview, previewContent = "" }: {
+ enabled?: boolean;
+ parentId?: string;
+ targetMissing?: boolean;
+ triggerPreview?: Pick<UseCommentTriggerPreviewResult, "agents" | "isCurrent">;
+ previewContent?: string;
+ } = {},
+) {
const { t } = useT("issues");
+ const queryClient = useQueryClient();
const workspace = useCurrentWorkspace();
const wsId = workspace?.id ?? "";
+ const hasIssueContext = enabled && wsId !== "" && !!issueId;
const { data } = useQuery({
...quickActionListOptions(wsId),
- enabled: wsId !== "",
+ enabled: enabled && wsId !== "",
+ });
+ const { data: issue } = useQuery({
+ ...issueDetailOptions(wsId, issueId ?? ""),
+ enabled: hasIssueContext,
+ refetchOnMount: false,
+ });
+ const { data: agents } = useQuery({
+ ...agentListOptions(wsId),
+ enabled: hasIssueContext,
+ refetchOnMount: false,
+ });
+ const { data: squads } = useQuery({
+ ...squadListOptions(wsId),
+ enabled: hasIssueContext,
+ refetchOnMount: false,
+ });
+ const { data: members } = useQuery({
+ ...memberListOptions(wsId),
+ enabled: hasIssueContext,
+ refetchOnMount: false,
});
const actions = useMemo(
@@ -54,8 +237,45 @@ export function useQuickActionMenu() {
return content;
}, [actions, t]);
+ const previewAgents = triggerPreview?.agents;
+ // Empty composers have a synthetic current preview with no targets. Keep
+ // synchronous resolution there so the first nonempty query need not wait
+ // for a network round-trip before offering skills.
+ const hasCurrentPreview = triggerPreview?.isCurrent && commentTriggerPreviewSignature(previewContent) !== "empty";
+ const getSkills = useCallback((editor: Editor): AgentSkillSummary[] => {
+ if (!hasIssueContext || targetMissing) return [];
+ if (hasCurrentPreview) {
+ const agentsById = new Map((agents ?? []).map((agent) => [agent.id, agent]));
+ const seenSkillIds = new Set<string>();
+ return (previewAgents ?? []).flatMap(({ id }) =>
+ (agentsById.get(id)?.skills ?? []).filter((skill) => {
+ if (skill.enabled === false || seenSkillIds.has(skill.id)) return false;
+ seenSkillIds.add(skill.id);
+ return true;
+ }),
+ );
+ }
+ const timeline = parentId && issueId
+ ? queryClient.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId))
+ : undefined;
+ const tasks = parentId && issueId
+ ? queryClient.getQueryData<AgentTask[]>(issueKeys.tasks(issueId))
+ : undefined;
+ return resolveIssueSlashSkills(editor.state.doc, {
+ issue,
+ agents: agents ?? [],
+ squads: squads ?? [],
+ members: members ?? [],
+ userId: useAuthStore.getState().user?.id ?? null,
+ parentId,
+ targetMissing,
+ timeline,
+ tasks,
+ });
+ }, [hasIssueContext, issue, agents, squads, members, queryClient, issueId, parentId, targetMissing, hasCurrentPreview, previewAgents]);
+
return useMemo(
- () => ({ getQuickActions, getQuickActionContent }),
- [getQuickActions, getQuickActionContent],
+ () => ({ getQuickActions, getQuickActionContent, getSkills }),
+ [getQuickActions, getQuickActionContent, getSkills],
);
}