Skip to content

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

Go

fix(editor): insert comment quick actions from cached catalog (MUL-8593) (#9927)

Multica Eve25f4843164a8
diff --git a/.github/ci-paths.json b/.github/ci-paths.json
index d48652c4b4..88ca3e8a11 100644
--- a/.github/ci-paths.json
+++ b/.github/ci-paths.json
@@ -4,6 +4,7 @@
"apps/web/**",
"apps/desktop/**",
"packages/**",
+ "server/internal/handler/testdata/quick_action_bodies.json",
"package.json",
".npmrc",
"pnpm-lock.yaml",
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 0961eb8a79..d8c2110b6e 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -4578,8 +4578,9 @@ export class ApiClient {
}
/**
- * What a quick action WOULD post, without posting it. Backs the composer
- * hand-off (⌥-click and the `/` menu) so the user can edit before sending.
+ * What a quick action WOULD post, with server-side validation but no send.
+ * Retained for callers that resolve drafts over HTTP; the comment composer
+ * builds its draft synchronously from the quick-action catalog.
* Returns "" when the response cannot be read — callers must treat an empty
* string as "insert nothing" rather than clearing the composer.
*/
diff --git a/packages/core/quick-actions/body.test.ts b/packages/core/quick-actions/body.test.ts
new file mode 100644
index 0000000000..1e2a8df299
--- /dev/null
+++ b/packages/core/quick-actions/body.test.ts
@@ -0,0 +1,34 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import { buildQuickActionBody } from "./body";
+
+const cases = JSON.parse(readFileSync(
+ new URL("../../../server/internal/handler/testdata/quick_action_bodies.json", import.meta.url),
+ "utf8",
+)) as { name: string; action: Omit<Parameters<typeof buildQuickActionBody>[0], "target_missing">; expected: string }[];
+
+describe("buildQuickActionBody", () => {
+ // Also consumed by the server's body builder contract test.
+ it.each(cases)("matches the server body: $name", ({ action, expected }) => {
+ expect(buildQuickActionBody({ ...action, target_missing: false })).toBe(expected);
+ });
+
+ const action = {
+ assignee_type: "agent",
+ assignee_id: "agent-id",
+ target_name: "Reviewer",
+ target_missing: false,
+ prompt: "Review this",
+ };
+
+ it.each([
+ { target_missing: true },
+ { target_name: undefined },
+ { target_name: "" },
+ { assignee_id: "" },
+ { assignee_type: "unknown" },
+ ])("refuses an unresolved target: %o", (overrides) => {
+ expect(buildQuickActionBody({ ...action, ...overrides })).toBeNull();
+ });
+});
diff --git a/packages/core/quick-actions/body.ts b/packages/core/quick-actions/body.ts
new file mode 100644
index 0000000000..598e863de6
--- /dev/null
+++ b/packages/core/quick-actions/body.ts
@@ -0,0 +1,19 @@
+import type { QuickAction } from "../types";
+
+type QuickActionBody = Pick<
+ QuickAction,
+ "prompt" | "assignee_type" | "assignee_id" | "target_name" | "target_missing"
+>;
+
+/** Draft text only; the comment send path checks invocation permission. */
+export function buildQuickActionBody(action: QuickActionBody): string | null {
+ if (action.target_missing) return null;
+ if (action.assignee_type === "") return action.prompt;
+ if (
+ (action.assignee_type !== "agent" && action.assignee_type !== "squad") ||
+ !action.assignee_id ||
+ !action.target_name
+ ) return null;
+
+ return `[@${action.target_name}](mention://${action.assignee_type}/${action.assignee_id})\n\n${action.prompt}`;
+}
diff --git a/packages/core/quick-actions/index.ts b/packages/core/quick-actions/index.ts
index c150641212..95ee80e66e 100644
--- a/packages/core/quick-actions/index.ts
+++ b/packages/core/quick-actions/index.ts
@@ -1,4 +1,5 @@
export { quickActionKeys, quickActionListOptions } from "./queries";
+export { buildQuickActionBody } from "./body";
export {
useCreateQuickAction,
useUpdateQuickAction,
diff --git a/packages/core/turbo.json b/packages/core/turbo.json
new file mode 100644
index 0000000000..92d66fd27e
--- /dev/null
+++ b/packages/core/turbo.json
@@ -0,0 +1,11 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "test": {
+ "inputs": [
+ "$TURBO_DEFAULT$",
+ "$TURBO_ROOT$/server/internal/handler/testdata/quick_action_bodies.json"
+ ]
+ }
+ }
+}
diff --git a/packages/views/editor/content-editor-quick-actions.test.tsx b/packages/views/editor/content-editor-quick-actions.test.tsx
index 678ea497ff..f57bbfe3d3 100644
--- a/packages/views/editor/content-editor-quick-actions.test.tsx
+++ b/packages/views/editor/content-editor-quick-actions.test.tsx
@@ -11,6 +11,9 @@ import { ContentEditor } from "./content-editor";
const listQuickActions = vi.hoisted(() => vi.fn());
const renderQuickAction = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+
+vi.mock("sonner", () => ({ toast: { error: toastError } }));
vi.mock("@multica/core/api", async (importOriginal) => {
const actual = await importOriginal<typeof import("@multica/core/api")>();
@@ -39,6 +42,7 @@ beforeAll(() => {
beforeEach(() => {
listQuickActions.mockReset();
renderQuickAction.mockReset().mockResolvedValue("Rendered feedback");
+ toastError.mockReset();
});
const clients: QueryClient[] = [];
@@ -76,7 +80,7 @@ function pendingCatalog() {
function Composer() {
return (
<ContentEditor
- quickActionMenu={useQuickActionMenu("issue")}
+ quickActionMenu={useQuickActionMenu()}
enableSlashCommands
slashCommandMode="command"
showBubbleMenu={false}
@@ -128,6 +132,73 @@ async function type(editor: Editor, text: string) {
const menuItem = () => screen.queryByRole("button", { name: "/delayed-feedback" });
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",
+ async (targetType) => {
+ const configured = {
+ ...action,
+ assignee_type: targetType,
+ assignee_id: targetType ? "target-id" : "",
+ target_name: targetType ? "Review Team" : undefined,
+ };
+ listQuickActions.mockResolvedValue({ quick_actions: [configured] });
+ renderQuickAction.mockReturnValue(new Promise(() => {}));
+ const { editor, dom } = await mount([configured]);
+ await type(editor, "/delayed");
+ await waitFor(() => expect(menuItem()).toBeVisible());
+
+ fireEvent.keyDown(dom, { key: "Enter" });
+
+ expect(editor.getText()).toBe(targetType ? "@Review Team\n\nRendered feedback" : "Rendered feedback");
+ expect(renderQuickAction).not.toHaveBeenCalled();
+ const mentions: { type: string; id: string }[] = [];
+ editor.state.doc.descendants((node) => {
+ if (node.type.name === "mention") mentions.push({ type: node.attrs.type, id: node.attrs.id });
+ });
+ expect(mentions).toEqual(targetType ? [{ type: targetType, id: "target-id" }] : []);
+ },
+ );
+
+ it("keeps the draft and reports an unavailable target without a render request", async () => {
+ const unavailable = { ...action, assignee_type: "agent", assignee_id: "target-id", target_missing: true };
+ listQuickActions.mockResolvedValue({ quick_actions: [unavailable] });
+ renderQuickAction.mockReturnValue(new Promise(() => {}));
+ const { editor, dom } = await mount([unavailable]);
+ await type(editor, "/delayed");
+ await waitFor(() => expect(menuItem()).toBeVisible());
+
+ fireEvent.keyDown(dom, { key: "Enter" });
+
+ expect(editor.getText()).toBe("/delayed");
+ expect(toastError).toHaveBeenCalledWith("This target is unavailable");
+ expect(renderQuickAction).not.toHaveBeenCalled();
+ });
+
+ it("uses a refreshed body and target while preserving the surrounding draft and undo", async () => {
+ listQuickActions.mockResolvedValue({ quick_actions: [action] });
+ const { editor, dom, client } = await mount([action]);
+ await type(editor, "Keep this /delayed");
+ await waitFor(() => expect(menuItem()).toBeVisible());
+ const updated = {
+ ...action,
+ name: "delayed-updated",
+ prompt: "Updated feedback",
+ assignee_type: "squad",
+ assignee_id: "updated-target",
+ target_name: "Current Team",
+ };
+ await act(async () => client.setQueryData(quickActionKeys.list("ws"), { quick_actions: [updated] }));
+ await waitFor(() => expect(screen.getByRole("button", { name: "/delayed-updated" })).toBeVisible());
+ expect(editor.getText()).toBe("Keep this /delayed");
+
+ fireEvent.keyDown(dom, { key: "Enter" });
+
+ expect(editor.getText()).toBe("Keep this \n\n@Current Team\n\nUpdated feedback");
+ expect(renderQuickAction).not.toHaveBeenCalled();
+ act(() => { editor.commands.undo(); });
+ expect(editor.getText()).toBe("Keep this /delayed");
+ });
+
it.each(["/", "/delayed"])(
"refreshes %s after a delayed catalog arrives without another keystroke or editor reset",
async (query) => {
@@ -146,7 +217,7 @@ describe("comment quick-action catalog updates in the real editor", () => {
fireEvent.click(menuItem()!);
await waitFor(() => expect(editor.getText()).toBe("Rendered feedback"));
- expect(renderQuickAction).toHaveBeenCalledExactlyOnceWith("issue", "action");
+ expect(renderQuickAction).not.toHaveBeenCalled();
},
);
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 5f3ab3815a..0bef5de01d 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -622,10 +622,8 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
quickActionMenuListeners.current.add(refresh);
return () => { quickActionMenuListeners.current.delete(refresh); };
},
- renderQuickAction: (id: string) =>
- quickActionMenuRef.current?.renderQuickAction?.(id) ?? Promise.resolve(""),
- onRenderError: (error: unknown) =>
- quickActionMenuRef.current?.onRenderError?.(error),
+ getQuickActionContent: (id: string) =>
+ quickActionMenuRef.current?.getQuickActionContent?.(id) ?? "",
},
resolveIssueIdentifierRef,
}),
diff --git a/packages/views/editor/extensions/slash-command-suggestion.test.tsx b/packages/views/editor/extensions/slash-command-suggestion.test.tsx
index 09e01e4428..41ae848d39 100644
--- a/packages/views/editor/extensions/slash-command-suggestion.test.tsx
+++ b/packages/views/editor/extensions/slash-command-suggestion.test.tsx
@@ -593,121 +593,42 @@ describe("SlashCommandList built-in command rendering", () => {
});
-// Async quick-action rendering in the `/` menu (MUL-5465, review finding #4).
-//
-// The render request resolves after an arbitrary delay, during which the user
-// keeps typing. Three behaviours have to hold, and each one was a real bug at
-// some point in this PR:
-// - a rejection must not destroy what the user typed
-// - a success must replace the ORIGINAL command, not wherever the caret is
-// - a command edited mid-flight must be left alone, not overwritten
-describe("builtin `/` menu — async quick action rendering", () => {
- // Minimal editor stand-in: enough ProseMirror surface for the command to
- // read the range text and issue its chain.
- function fakeEditor(text: string) {
- const calls: { from: number; to: number; content: string; contentType?: string }[] = [];
- let docText = text;
- const chain = {
- focus: () => chain,
- insertContentAt: (
- range: { from: number; to: number },
- content: string,
- opts?: { contentType?: string },
- ) => {
- calls.push({ from: range.from, to: range.to, content, contentType: opts?.contentType });
- return chain;
- },
- insertContent: (content: string) => {
- calls.push({ from: -1, to: -1, content });
- return chain;
- },
- deleteRange: () => chain,
- run: () => true,
- };
- return {
- calls,
- setText: (next: string) => {
- docText = next;
- },
- editor: {
- chain: () => chain,
- state: {
- doc: {
- get content() {
- return { size: docText.length + 1 };
- },
- textBetween: (from: number, to: number) => docText.slice(from, to),
- },
- },
- view: { state: { selection: { $to: { nodeAfter: null } } } },
- },
- };
- }
-
+describe("builtin `/` menu — cached quick action content", () => {
const range = { from: 0, to: 7 };
const item = { id: `${QUICK_ACTION_ITEM_PREFIX}qa-1`, label: "review" };
- it("leaves the typed command intact and reports the failure when render rejects", async () => {
- const { editor, calls } = fakeEditor("/review");
- const onRenderError = vi.fn();
- const suggestion = createBuiltinCommandSuggestion({
- renderQuickAction: () => Promise.reject(new Error("boom")),
- onRenderError,
- });
-
- suggestion.command!({ editor, range, props: item } as never);
- await act(async () => {
- await Promise.resolve();
- await Promise.resolve();
- });
-
- expect(calls).toHaveLength(0);
- expect(onRenderError).toHaveBeenCalledTimes(1);
- });
+ function fakeEditor() {
+ const chain = {
+ focus: vi.fn(() => chain),
+ command: vi.fn(() => chain),
+ insertContentAt: vi.fn(() => chain),
+ run: vi.fn(() => true),
+ };
+ return { chain, editor: { chain: () => chain } };
+ }
- it("replaces the original range once a delayed render resolves", async () => {
- const { editor, calls } = fakeEditor("/review");
- let resolve!: (v: string) => void;
- const suggestion = createBuiltinCommandSuggestion({
- renderQuickAction: () => new Promise<string>((r) => { resolve = r; }),
- });
+ it("replaces the command range synchronously and parses mention markdown", () => {
+ const selection = window.getSelection()!;
+ const collapse = vi.spyOn(selection, "collapseToEnd").mockImplementation(() => {});
+ const { editor, chain } = fakeEditor();
+ const content = "[@Reviewer](mention://agent/agent-id)\n\nReview this";
+ const getQuickActionContent = vi.fn(() => content);
+ const suggestion = createBuiltinCommandSuggestion({ getQuickActionContent });
suggestion.command!({ editor, range, props: item } as never);
- expect(calls).toHaveLength(0); // nothing destroyed while in flight
- await act(async () => {
- resolve("rendered body");
- await Promise.resolve();
- await Promise.resolve();
- });
-
- // contentType must be "markdown": inserted as a plain string, the
- // server-rendered `[@Name](mention://…)` lands as literal text and
- // serialises back out with escaped brackets, so the mention never becomes
- // a node and renders as raw markup in the thread.
- expect(calls).toEqual([
- { from: 0, to: 7, content: "rendered body", contentType: "markdown" },
- ]);
+ expect(getQuickActionContent).toHaveBeenCalledWith("qa-1");
+ expect(chain.insertContentAt).toHaveBeenCalledWith(range, content, { contentType: "markdown" });
+ expect(chain.run).toHaveBeenCalledOnce();
+ collapse.mockRestore();
});
- it("abandons the insert when the command was edited while the request was open", async () => {
- const { editor, calls, setText } = fakeEditor("/review");
- let resolve!: (v: string) => void;
- const suggestion = createBuiltinCommandSuggestion({
- renderQuickAction: () => new Promise<string>((r) => { resolve = r; }),
- });
+ it("leaves the command untouched when content is unavailable", () => {
+ const { editor, chain } = fakeEditor();
+ const suggestion = createBuiltinCommandSuggestion({ getQuickActionContent: () => "" });
suggestion.command!({ editor, range, props: item } as never);
- // The user rewrites the command; a prefix-only check would still see a
- // leading "/" here and clobber it.
- setText("/fixnow");
-
- await act(async () => {
- resolve("rendered body");
- await Promise.resolve();
- await Promise.resolve();
- });
- expect(calls).toHaveLength(0);
+ expect(chain.insertContentAt).not.toHaveBeenCalled();
});
});
diff --git a/packages/views/editor/extensions/slash-command-suggestion.tsx b/packages/views/editor/extensions/slash-command-suggestion.tsx
index 0b5e0424f6..8b8eeb65ef 100644
--- a/packages/views/editor/extensions/slash-command-suggestion.tsx
+++ b/packages/views/editor/extensions/slash-command-suggestion.tsx
@@ -11,6 +11,7 @@ import {
import type { QueryClient } from "@tanstack/react-query";
import type { SuggestionOptions } from "@tiptap/suggestion";
import { PluginKey } from "@tiptap/pm/state";
+import { closeHistory } from "@tiptap/pm/history";
import { useAuthStore } from "@multica/core/auth";
import { useChatStore } from "@multica/core/chat";
import { getCurrentWsId } from "@multica/core/platform";
@@ -324,18 +325,10 @@ export interface BuiltinCommandSuggestionOptions {
getQuickActions?: () => { id: string; name: string; description?: string }[];
subscribeQuickActions?: (refresh: () => void) => () => void;
/**
- * Resolves a quick action to the text it would post. Server-rendered, so the
- * inserted body is byte-identical to what clicking the sidebar button sends.
- * Returning "" (or throwing) must leave the composer untouched rather than
- * inserting a half-rendered prompt.
+ * Builds draft text synchronously from the cached catalog. Returning ""
+ * leaves the composer untouched when an action or its target is unavailable.
*/
- renderQuickAction?: (quickActionId: string) => Promise<string>;
- /**
- * Called when renderQuickAction rejects. The extension cannot show UI of its
- * own — a ProseMirror command runs outside React's tree — so the host turns
- * this into a toast. Without it a failed pick is completely silent.
- */
- onRenderError?: (error: unknown) => void;
+ getQuickActionContent?: (quickActionId: string) => string;
}
export function createBuiltinCommandSuggestion(
@@ -352,53 +345,20 @@ export function createBuiltinCommandSuggestion(
items: ({ query }) => buildBuiltinCommandItems(query, options.getQuickActions?.() ?? []),
command: ({ editor, range, props }) => {
if (isQuickActionItem(props)) {
- const render = options.renderQuickAction;
- if (!render) return;
- const id = quickActionIdFromItem(props);
-
- // The "/query" text is deliberately left in place while the request
- // is in flight. Deleting first meant a failed or slow render destroyed
- // what the user typed with nothing to show for it, and the insert then
- // landed wherever the caret happened to be by the time it resolved.
- //
- // Snapshot the EXACT text under the range, not just its shape. A
- // prefix check ("does it still start with /") passes when the user
- // rewrote `/review` into `/fix` mid-request, and the stale response
- // would then overwrite the new command.
- const originalText = editor.state.doc.textBetween(range.from, range.to);
-
- void render(id)
- .then((content) => {
- if (!content) return;
- const withinDoc = range.to <= editor.state.doc.content.size;
- const unchanged =
- withinDoc && editor.state.doc.textBetween(range.from, range.to) === originalText;
- if (!unchanged) {
- // The command was edited, moved, or removed while the request
- // was outstanding. Inserting anywhere now would either clobber
- // the user's newer text or drop the body in an unrelated spot,
- // so this pick is simply abandoned.
- return;
- }
- editor
- .chain()
- .focus()
- // contentType: "markdown" is load-bearing. Without it Tiptap
- // inserts the string as literal TEXT, so the server-rendered
- // `[@Name](mention://agent/…)` never becomes a mention node —
- // it serialises back out with the brackets escaped
- // (`\[@Name\](…)`) and renders as raw markup in the thread.
- .insertContentAt({ from: range.from, to: range.to }, content, {
- contentType: "markdown",
- })
- .run();
- window.getSelection()?.collapseToEnd();
+ const content = options.getQuickActionContent?.(quickActionIdFromItem(props));
+ if (!content) return;
+ editor
+ .chain()
+ .focus()
+ .command(({ tr }) => {
+ // Undoing a synchronous pick must preserve the preceding draft.
+ closeHistory(tr);
+ return true;
})
- .catch((error: unknown) => {
- // The command text is still there, so the user can retry or edit
- // it by hand; the host surfaces why nothing was inserted.
- options.onRenderError?.(error);
- });
+ // Parse the mention markup into a node, rather than literal text.
+ .insertContentAt(range, content, { contentType: "markdown" })
+ .run();
+ window.getSelection()?.collapseToEnd();
return;
}
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index 66569a7a87..1695ae769e 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -13,8 +13,7 @@ import { ReplyInput } from "./reply-input";
/** Shape of ContentEditor's `quickActionMenu` prop, as the composers pass it. */
type QuickActionMenuProp = {
getQuickActions?: () => { id: string; name: string; description?: string }[];
- renderQuickAction?: (quickActionId: string) => Promise<string>;
- onRenderError?: (error: unknown) => void;
+ getQuickActionContent?: (quickActionId: string) => string;
};
// Uploads now flow through the module-level coordinator, which calls
@@ -327,7 +326,7 @@ describe("quick action `/` menu", () => {
apiListWorkspaces.mockResolvedValue([workspace]);
apiListQuickActions.mockResolvedValue({
quick_actions: [
- { id: "qa-1", name: "review", description: "Ask for a review", status: "active" },
+ { id: "qa-1", name: "review", description: "Ask for a review", status: "active", assignee_type: "", prompt: "Review this issue" },
{ id: "qa-2", name: "retired", description: "", status: "archived" },
],
});
@@ -378,17 +377,14 @@ describe("quick action `/` menu", () => {
});
});
- it(`binds quick action rendering to this issue in the ${composer.name}`, async () => {
- apiRenderQuickAction.mockResolvedValue("rendered body");
+ it(`builds quick action text from the catalog in the ${composer.name}`, async () => {
renderInWorkspace(composer.element);
activateComposer(composer.shell);
await waitFor(() => {
- expect(editorQuickActionMenu.last?.renderQuickAction).toBeTypeOf("function");
+ expect(editorQuickActionMenu.last?.getQuickActionContent?.("qa-1")).toBe("Review this issue");
});
- await editorQuickActionMenu.last?.renderQuickAction?.("qa-1");
-
- expect(apiRenderQuickAction).toHaveBeenCalledWith("issue-1", "qa-1");
+ expect(apiRenderQuickAction).not.toHaveBeenCalled();
});
}
});
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index 32278a1987..06b9abf7f8 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -49,9 +49,9 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme
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 server-rendered
+ // 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(issueId);
+ const quickActionMenu = useQuickActionMenu();
const draftKey = `new:${issueId}` as const;
const [initialDraft] = useState(() =>
useCommentDraftStore.getState().getDraft(draftKey),
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index 6a3ab756a4..a145334775 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -77,7 +77,7 @@ function ReplyInput({
// 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(issueId);
+ 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(() =>
diff --git a/packages/views/issues/hooks/use-quick-action-menu.ts b/packages/views/issues/hooks/use-quick-action-menu.ts
index 203c611637..0ba06326f4 100644
--- a/packages/views/issues/hooks/use-quick-action-menu.ts
+++ b/packages/views/issues/hooks/use-quick-action-menu.ts
@@ -3,29 +3,30 @@
import { useCallback, useMemo } from "react";
import { toast } from "sonner";
import { useQuery } from "@tanstack/react-query";
-import { api } from "@multica/core/api";
import { useCurrentWorkspace } from "@multica/core/paths";
-import { quickActionListOptions } from "@multica/core/quick-actions";
+import { buildQuickActionBody, quickActionListOptions } from "@multica/core/quick-actions";
+import { useT } from "../../i18n";
/**
* Supplies the comment composer's `/` menu with this workspace's quick actions
* (MUL-5465).
*
- * Picking one INSERTS the rendered body rather than running it — the composer
+ * 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
* gets to edit and then send with the normal shortcut. Running without review
* is what the sidebar button is for.
*
- * The menu offers the same catalog the sidebar shows — no permission
- * pre-filtering. A pick the user cannot run fails at the render endpoint and
- * simply inserts nothing, matching how the sidebar reports a refusal.
+ * The menu offers the same catalog the sidebar shows. Inserting draft text
+ * needs no invocation preflight; the comment send path checks permission just
+ * as it does for a hand-typed mention.
*
* Reads workspace identity through `useCurrentWorkspace` (nullable) rather
* than `useWorkspaceId` (throws): the comment composer also mounts outside a
* 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(issueId: string) {
+export function useQuickActionMenu() {
+ const { t } = useT("issues");
const workspace = useCurrentWorkspace();
const wsId = workspace?.id ?? "";
const { data } = useQuery({
@@ -34,28 +35,27 @@ export function useQuickActionMenu(issueId: string) {
});
const actions = useMemo(
- () =>
- (data ?? [])
- .filter((a) => a.status === "active")
- .map((a) => ({ id: a.id, name: a.name, description: a.description || undefined })),
+ () => (data ?? []).filter((a) => a.status === "active"),
[data],
);
- const getQuickActions = useCallback(() => actions, [actions]);
- const renderQuickAction = useCallback(
- (quickActionId: string) => api.renderQuickAction(issueId, quickActionId),
- [issueId],
+ const getQuickActions = useCallback(
+ () => actions.map((a) => ({ id: a.id, name: a.name, description: a.description || undefined })),
+ [actions],
);
-
- // The extension runs outside React's tree, so it reports failures back here
- // rather than rendering anything itself. Without this a failed pick left the
- // command text sitting in the composer with no explanation.
- const onRenderError = useCallback((error: unknown) => {
- toast.error(error instanceof Error ? error.message : String(error));
- }, []);
+ const getQuickActionContent = useCallback((quickActionId: string) => {
+ const action = actions.find((a) => a.id === quickActionId);
+ if (!action) return "";
+ const content = buildQuickActionBody(action);
+ if (content === null) {
+ toast.error(t(($) => $.comment.trigger_blocked_target_unavailable));
+ return "";
+ }
+ return content;
+ }, [actions, t]);
return useMemo(
- () => ({ getQuickActions, renderQuickAction, onRenderError }),
- [getQuickActions, renderQuickAction, onRenderError],
+ () => ({ getQuickActions, getQuickActionContent }),
+ [getQuickActions, getQuickActionContent],
);
}
diff --git a/scripts/ci-scope.test.mjs b/scripts/ci-scope.test.mjs
index 6e06f2871b..146be0739a 100644
--- a/scripts/ci-scope.test.mjs
+++ b/scripts/ci-scope.test.mjs
@@ -39,6 +39,7 @@ for (const [name, files, selected] of [
["reserved slug output", ["packages/core/paths/reserved-slugs.ts"], ["frontend", "quality", "scripts"]],
["integration key gates", ["server/cmd/server/router.go"], ["backend", "runtime", "scripts"]],
["cross-module runtime contract", ["packages/core/runtimes/cli-version.ts"], ["frontend", "backend", "runtime", "quality"]],
+ ["shared quick action body contract", ["server/internal/handler/testdata/quick_action_bodies.json"], ["frontend", "backend", "runtime"]],
["lockfile", ["pnpm-lock.yaml"], ["frontend", "quality"]],
["workspace package patch", ["patches/example.patch"], ["frontend", "quality"]],
["mobile package patch", ["apps/mobile/patches/example.patch"], ["quality"]],
diff --git a/server/internal/handler/quick_action.go b/server/internal/handler/quick_action.go
index 7e1c3c9322..8ac26fb7da 100644
--- a/server/internal/handler/quick_action.go
+++ b/server/internal/handler/quick_action.go
@@ -195,23 +195,6 @@ func normalizeQuickActionVisibility(raw string) (string, error) {
// Target resolution
-// quickActionTarget is the resolved execution target of an action: the agent
-// that will actually run, plus the display identity the client should show.
-// For a squad binding, Agent is the squad leader and Name is the SQUAD's name,
-// because the squad is what the user bound and what the mention will address.
-type quickActionTarget struct {
- Agent db.Agent
- Name string
- AvatarURL string
- // MentionType is the mention:// scheme the rendered comment must use so
- // the existing trigger path routes it exactly as a hand-typed mention.
- MentionType string
- // MentionID is the id inside the mention link: the agent id, or the SQUAD
- // id for a squad binding (the trigger path resolves the leader itself).
- MentionID string
- Found bool
-}
-
// resolveQuickActionTarget loads the execution target. A missing/archived
// agent, or a missing/archived squad, resolves to Found=false — the caller
// renders that as an unavailable target rather than failing the whole list.
@@ -791,11 +774,9 @@ func (h *Handler) validateQuickActionBinding(w http.ResponseWriter, r *http.Requ
// RenderQuickAction returns what the action WOULD post, without posting it.
//
-// This backs the composer hand-off (the `/` slash command): the user gets the
-// fully rendered text in the comment box to edit before sending. Rendering
-// stays on the server even for this read-only path so there is exactly one
-// interpolation implementation — a client-side copy would drift from the run
-// path and quietly send something different from the preview.
+// Kept for installed clients that resolve draft text over HTTP. Current
+// clients build drafts from the catalog; shared fixtures keep that text aligned
+// with buildQuickActionBody. Invocation permission is checked again on send.
func (h *Handler) RenderQuickAction(w http.ResponseWriter, r *http.Request) {
issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
if !ok {
@@ -833,18 +814,6 @@ func (h *Handler) RenderQuickAction(w http.ResponseWriter, r *http.Request) {
})
}
-// buildQuickActionBody prepends the mention line that actually triggers the
-// run. It is parsed by the same ParseMentions the composer's output goes
-// through, so a quick action is indistinguishable from a hand-typed @mention
-// downstream. The prompt itself is passed through untouched — see the file
-// header for why there is no interpolation step.
-func buildQuickActionBody(qa db.QuickAction, target quickActionTarget) string {
- if qa.AssigneeType == "" {
- return qa.Prompt
- }
- return fmt.Sprintf("[@%s](mention://%s/%s)\n\n%s", target.Name, target.MentionType, target.MentionID, qa.Prompt)
-}
-
// RunQuickAction renders the action and posts it as a quick_action comment,
// then hands off to the standard comment trigger path.
//
diff --git a/server/internal/handler/quick_action_body.go b/server/internal/handler/quick_action_body.go
new file mode 100644
index 0000000000..5703658250
--- /dev/null
+++ b/server/internal/handler/quick_action_body.go
@@ -0,0 +1,35 @@
+package handler
+
+import (
+ "fmt"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// quickActionTarget is the resolved execution target of an action: the agent
+// that will actually run, plus the display identity the client should show.
+// For a squad binding, Agent is the squad leader and Name is the SQUAD's name,
+// because the squad is what the user bound and what the mention will address.
+type quickActionTarget struct {
+ Agent db.Agent
+ Name string
+ AvatarURL string
+ // MentionType is the mention:// scheme the rendered comment must use so
+ // the existing trigger path routes it exactly as a hand-typed mention.
+ MentionType string
+ // MentionID is the id inside the mention link: the agent id, or the SQUAD
+ // id for a squad binding (the trigger path resolves the leader itself).
+ MentionID string
+ Found bool
+}
+
+// buildQuickActionBody prepends the mention line that actually triggers the
+// run. It is parsed by the same ParseMentions the composer's output goes
+// through, so a quick action is indistinguishable from a hand-typed @mention
+// downstream. The prompt itself is passed through untouched.
+func buildQuickActionBody(qa db.QuickAction, target quickActionTarget) string {
+ if qa.AssigneeType == "" {
+ return qa.Prompt
+ }
+ return fmt.Sprintf("[@%s](mention://%s/%s)\n\n%s", target.Name, target.MentionType, target.MentionID, qa.Prompt)
+}
diff --git a/server/internal/handler/quick_action_body_test.go b/server/internal/handler/quick_action_body_test.go
new file mode 100644
index 0000000000..07a3d34d29
--- /dev/null
+++ b/server/internal/handler/quick_action_body_test.go
@@ -0,0 +1,44 @@
+package handler
+
+import (
+ "encoding/json"
+ "os"
+ "testing"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestBuildQuickActionBodySharedContract(t *testing.T) {
+ // The frontend consumes the same cases to keep draft and run text aligned.
+ data, err := os.ReadFile("testdata/quick_action_bodies.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var cases []struct {
+ Name string `json:"name"`
+ Action struct {
+ AssigneeType string `json:"assignee_type"`
+ AssigneeID string `json:"assignee_id"`
+ TargetName string `json:"target_name"`
+ Prompt string `json:"prompt"`
+ } `json:"action"`
+ Expected string `json:"expected"`
+ }
+ if err := json.Unmarshal(data, &cases); err != nil {
+ t.Fatal(err)
+ }
+ if len(cases) == 0 {
+ t.Fatal("shared quick action body cases must not be empty")
+ }
+ for _, tc := range cases {
+ t.Run(tc.Name, func(t *testing.T) {
+ got := buildQuickActionBody(
+ db.QuickAction{AssigneeType: tc.Action.AssigneeType, Prompt: tc.Action.Prompt},
+ quickActionTarget{Name: tc.Action.TargetName, MentionType: tc.Action.AssigneeType, MentionID: tc.Action.AssigneeID},
+ )
+ if got != tc.Expected {
+ t.Fatalf("body = %q, want %q", got, tc.Expected)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/testdata/quick_action_bodies.json b/server/internal/handler/testdata/quick_action_bodies.json
new file mode 100644
index 0000000000..5a98a6c234
--- /dev/null
+++ b/server/internal/handler/testdata/quick_action_bodies.json
@@ -0,0 +1,42 @@
+[
+ {
+ "name": "targetless prompt stays verbatim",
+ "action": {
+ "assignee_type": "",
+ "assignee_id": "",
+ "target_name": "",
+ "prompt": " A **note**.\n\nLeave `code` and \\paths intact. "
+ },
+ "expected": " A **note**.\n\nLeave `code` and \\paths intact. "
+ },
+ {
+ "name": "agent mention",
+ "action": {
+ "assignee_type": "agent",
+ "assignee_id": "11111111-1111-4111-8111-111111111111",
+ "target_name": "Reviewer",
+ "prompt": "Review this PR."
+ },
+ "expected": "[@Reviewer](mention://agent/11111111-1111-4111-8111-111111111111)\n\nReview this PR."
+ },
+ {
+ "name": "squad mention uses squad identity",
+ "action": {
+ "assignee_type": "squad",
+ "assignee_id": "22222222-2222-4222-8222-222222222222",
+ "target_name": "Review Team",
+ "prompt": "Check the implementation.\nFocus on correctness."
+ },
+ "expected": "[@Review Team](mention://squad/22222222-2222-4222-8222-222222222222)\n\nCheck the implementation.\nFocus on correctness."
+ },
+ {
+ "name": "unicode label and markdown prompt",
+ "action": {
+ "assignee_type": "agent",
+ "assignee_id": "33333333-3333-4333-8333-333333333333",
+ "target_name": "代码审查员",
+ "prompt": "请检查:\n\n- **权限**\n- `git diff`"
+ },
+ "expected": "[@代码审查员](mention://agent/33333333-3333-4333-8333-333333333333)\n\n请检查:\n\n- **权限**\n- `git diff`"
+ }
+]