Skip to content

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

Go

feat(issues): Issue Quick Actions — preset agent + prompt, one-click from the sidebar (MUL-5465) (#6132)

Jiayuan Zhang5e3b7a8c3710
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index c0d285a5bd..5dbb8fbbbc 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -104,6 +104,10 @@ import type {
IssueProperty,
IssuePropertyValue,
CreatePropertyRequest,
+ QuickAction,
+ CreateQuickActionRequest,
+ UpdateQuickActionRequest,
+ ListQuickActionsResponse,
UpdatePropertyRequest,
ListPropertiesResponse,
IssuePropertiesResponse,
@@ -280,6 +284,13 @@ import {
IssuePropertySchema,
ListPropertiesResponseSchema,
IssuePropertiesResponseSchema,
+ QuickActionSchema,
+ ListQuickActionsResponseSchema,
+ QuickActionRenderSchema,
+ EMPTY_QUICK_ACTION,
+ EMPTY_LIST_QUICK_ACTIONS_RESPONSE,
+ CommentSchema,
+ EMPTY_COMMENT,
EMPTY_ISSUE_PROPERTY,
EMPTY_LIST_PROPERTIES_RESPONSE,
EMPTY_ISSUE_PROPERTIES_RESPONSE,
@@ -2541,6 +2552,89 @@ export class ApiClient {
});
}
+ /**
+ * Quick actions catalog — one projection for every caller.
+ *
+ * The server hides nothing beyond `private` ownership; whether the caller
+ * may RUN an action is answered by runQuickAction, not here. There is
+ * deliberately no "runnable only" mode: filtering the sidebar by permission
+ * made two people looking at one issue see different sidebars with no
+ * explanation.
+ *
+ * A backend predating quick actions 404s here; treat that as an empty
+ * catalog so the sidebar section and settings tab simply do not render.
+ */
+ async listQuickActions(opts?: { includeArchived?: boolean }): Promise<ListQuickActionsResponse> {
+ const suffix = opts?.includeArchived === true ? "?include_archived=true" : "";
+ let raw: unknown;
+ try {
+ raw = await this.fetch<unknown>(`/api/quick-actions${suffix}`);
+ } catch (error) {
+ if (error instanceof Error && "status" in error && (error as { status?: number }).status === 404) {
+ return EMPTY_LIST_QUICK_ACTIONS_RESPONSE;
+ }
+ throw error;
+ }
+ return parseWithFallback(raw, ListQuickActionsResponseSchema, EMPTY_LIST_QUICK_ACTIONS_RESPONSE, {
+ endpoint: "GET /api/quick-actions",
+ });
+ }
+
+ async createQuickAction(data: CreateQuickActionRequest): Promise<QuickAction> {
+ const raw = await this.fetch<unknown>(`/api/quick-actions`, {
+ method: "POST",
+ body: JSON.stringify(data),
+ });
+ return parseWithFallback(raw, QuickActionSchema, EMPTY_QUICK_ACTION, {
+ endpoint: "POST /api/quick-actions",
+ });
+ }
+
+ async updateQuickAction(id: string, data: UpdateQuickActionRequest): Promise<QuickAction> {
+ const raw = await this.fetch<unknown>(`/api/quick-actions/${id}`, {
+ method: "PATCH",
+ body: JSON.stringify(data),
+ });
+ return parseWithFallback(raw, QuickActionSchema, EMPTY_QUICK_ACTION, {
+ endpoint: "PATCH /api/quick-actions/{id}",
+ });
+ }
+
+ async deleteQuickAction(id: string): Promise<void> {
+ await this.fetch<void>(`/api/quick-actions/${id}`, { method: "DELETE" });
+ }
+
+ /**
+ * Run a quick action against one issue. The response is a Comment carrying
+ * `trigger_outcomes` — the same shape POST /comments returns — so callers
+ * reuse one result handler and inherit `queued` / `coalesced` / `deferred` /
+ * `blocked` instead of a parallel vocabulary that would drift.
+ */
+ async runQuickAction(issueId: string, quickActionId: string): Promise<Comment> {
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/quick-actions/${quickActionId}/run`, {
+ method: "POST",
+ });
+ return parseWithFallback(raw, CommentSchema, EMPTY_COMMENT, {
+ endpoint: "POST /api/issues/{id}/quick-actions/{quickActionId}/run",
+ });
+ }
+
+ /**
+ * 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.
+ * Returns "" when the response cannot be read — callers must treat an empty
+ * string as "insert nothing" rather than clearing the composer.
+ */
+ async renderQuickAction(issueId: string, quickActionId: string): Promise<string> {
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/quick-actions/${quickActionId}/render`, {
+ method: "POST",
+ });
+ const parsed = parseWithFallback(raw, QuickActionRenderSchema, { content: "" }, {
+ endpoint: "POST /api/issues/{id}/quick-actions/{quickActionId}/render",
+ });
+ return parsed.content;
+ }
+
async createProperty(data: CreatePropertyRequest): Promise<IssueProperty> {
const raw = await this.fetch<unknown>(`/api/properties`, {
method: "POST",
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index f7b617e63d..9aeb1b41a8 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -15,6 +15,7 @@ import type {
BillingTransactionsPage,
CancelTaskResponse,
ChatDraftRestoresResponse,
+ Comment,
CreateAgentFromTemplateResponse,
CreateBillingCheckoutSessionResponse,
CreateBillingPortalSessionResponse,
@@ -27,6 +28,8 @@ import type {
Label,
IssueProperty,
ListPropertiesResponse,
+ QuickAction,
+ ListQuickActionsResponse,
IssuePropertiesResponse,
IssueTableGroupDescriptor,
IssueTableFacetsResponse,
@@ -235,6 +238,63 @@ export const EMPTY_ISSUE_PROPERTY: IssueProperty = {
updated_at: "",
};
+// Quick actions (MUL-5465). `visibility` and `status` stay z.string() rather
+// than z.enum: they are server-driven, and a newer server adding a value must
+// degrade to the UI's default branch, not blank the whole list.
+export const QuickActionSchema = z.object({
+ id: z.string(),
+ workspace_id: z.string(),
+ name: z.string(),
+ description: z.string().optional().default(""),
+ assignee_type: z.string(),
+ assignee_id: z.string(),
+ prompt: z.string().optional().default(""),
+ visibility: z.string().optional().default("public"),
+ status: z.string().optional().default("active"),
+ last_used_at: z.string().nullable().optional().default(null),
+ use_count: z.number().optional().default(0),
+ created_by_id: z.string().optional().default(""),
+ created_at: z.string(),
+ updated_at: z.string(),
+ target_name: z.string().optional(),
+ // Both default to the pessimistic reading on an older server: "not known to
+ // be public" and "not known to be missing" keep the settings row honest
+ // rather than asserting a state the server never sent.
+ target_public: z.boolean().optional().default(false),
+ target_missing: z.boolean().optional().default(false),
+}).loose();
+
+export const EMPTY_QUICK_ACTION: QuickAction = {
+ id: "",
+ workspace_id: "",
+ name: "",
+ description: "",
+ assignee_type: "agent",
+ assignee_id: "",
+ prompt: "",
+ visibility: "public",
+ status: "active",
+ last_used_at: null,
+ use_count: 0,
+ created_by_id: "",
+ created_at: "",
+ updated_at: "",
+ target_public: false,
+ target_missing: true,
+};
+
+export const ListQuickActionsResponseSchema = z.object({
+ quick_actions: z.array(QuickActionSchema).default([]),
+}).loose();
+
+export const EMPTY_LIST_QUICK_ACTIONS_RESPONSE: ListQuickActionsResponse = {
+ quick_actions: [],
+};
+
+export const QuickActionRenderSchema = z.object({
+ content: z.string().default(""),
+}).loose();
+
export const ListPropertiesResponseSchema = z.object({
properties: z.array(IssuePropertySchema).default([]),
total: z.number().default(0),
@@ -496,10 +556,32 @@ export const CommentSchema = z.object({
created_at: z.string(),
updated_at: z.string(),
source_task_id: z.string().nullable().optional(),
+ // Set only on comments a quick action produced (MUL-5465). Server-only.
+ quick_action_id: z.string().nullable().optional(),
}).loose();
export const CommentsListSchema = z.array(CommentSchema);
+// Degraded placeholder for a comment response that failed schema validation.
+// The empty id is the caller's signal that nothing usable came back — the run
+// UI treats it as "could not read the result" rather than a successful run.
+export const EMPTY_COMMENT: Comment = {
+ id: "",
+ issue_id: "",
+ author_type: "member",
+ author_id: "",
+ content: "",
+ type: "comment",
+ parent_id: null,
+ reactions: [],
+ attachments: [],
+ created_at: "",
+ updated_at: "",
+ resolved_at: null,
+ resolved_by_type: null,
+ resolved_by_id: null,
+};
+
const CommentTriggerPreviewAgentSchema = z.object({
id: z.string(),
name: z.string().default(""),
diff --git a/packages/core/package.json b/packages/core/package.json
index 5aa6fe111e..b055626df2 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -79,6 +79,9 @@
"./properties": "./properties/index.ts",
"./properties/queries": "./properties/queries.ts",
"./properties/mutations": "./properties/mutations.ts",
+ "./quick-actions": "./quick-actions/index.ts",
+ "./quick-actions/queries": "./quick-actions/queries.ts",
+ "./quick-actions/mutations": "./quick-actions/mutations.ts",
"./autopilots": "./autopilots/index.ts",
"./autopilots/queries": "./autopilots/queries.ts",
"./autopilots/mutations": "./autopilots/mutations.ts",
diff --git a/packages/core/quick-actions/index.ts b/packages/core/quick-actions/index.ts
new file mode 100644
index 0000000000..c150641212
--- /dev/null
+++ b/packages/core/quick-actions/index.ts
@@ -0,0 +1,7 @@
+export { quickActionKeys, quickActionListOptions } from "./queries";
+export {
+ useCreateQuickAction,
+ useUpdateQuickAction,
+ useDeleteQuickAction,
+ useRunQuickAction,
+} from "./mutations";
diff --git a/packages/core/quick-actions/mutations.ts b/packages/core/quick-actions/mutations.ts
new file mode 100644
index 0000000000..7c806d3a1c
--- /dev/null
+++ b/packages/core/quick-actions/mutations.ts
@@ -0,0 +1,77 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import { quickActionKeys } from "./queries";
+import { useWorkspaceId } from "../hooks";
+import { issueKeys } from "../issues/queries";
+import type {
+ Comment,
+ CreateQuickActionRequest,
+ UpdateQuickActionRequest,
+} from "../types";
+
+/**
+ * Catalog mutations. None are optimistic: they happen in the settings form
+ * where a round-trip is acceptable, and the server canonicalizes values
+ * (position assignment, prompt trimming, derived visibility) anyway — an
+ * optimistic row would show the wrong visibility badge until it settled.
+ */
+export function useCreateQuickAction() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (data: CreateQuickActionRequest) => api.createQuickAction(data),
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: quickActionKeys.all(wsId) });
+ },
+ });
+}
+
+export function useUpdateQuickAction() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: ({ id, ...data }: { id: string } & UpdateQuickActionRequest) =>
+ api.updateQuickAction(id, data),
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: quickActionKeys.all(wsId) });
+ },
+ });
+}
+
+export function useDeleteQuickAction() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (id: string) => api.deleteQuickAction(id),
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: quickActionKeys.all(wsId) });
+ },
+ });
+}
+
+/**
+ * Run one quick action against one issue.
+ *
+ * Returns the created comment plus its `trigger_outcomes`, so the caller can
+ * tell `queued` (a run started) from `coalesced` (merged into the target's
+ * existing pending task) from `blocked`. That distinction is the whole point:
+ * the DB allows only one pending task per (issue, agent), so a second click
+ * genuinely does NOT start a second run and the UI must say so rather than
+ * pretending it did.
+ *
+ * Invalidates the issue's comments and task runs so the new card and the
+ * execution-log entry appear without waiting for a websocket round-trip.
+ */
+export function useRunQuickAction(issueId: string) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation<Comment, Error, { quickActionId: string }>({
+ mutationFn: ({ quickActionId }) => api.runQuickAction(issueId, quickActionId),
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });
+ qc.invalidateQueries({ queryKey: issueKeys.tasks(issueId) });
+ // Usage counters and last_used_at moved server-side on a successful run.
+ qc.invalidateQueries({ queryKey: quickActionKeys.all(wsId) });
+ },
+ });
+}
diff --git a/packages/core/quick-actions/queries.ts b/packages/core/quick-actions/queries.ts
new file mode 100644
index 0000000000..3e24be2a61
--- /dev/null
+++ b/packages/core/quick-actions/queries.ts
@@ -0,0 +1,24 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+/**
+ * Quick action catalog queries (MUL-5465).
+ *
+ * ONE projection, shared by settings and the issue sidebar. There used to be a
+ * second "runnable only" projection that filtered by invoke permission; it was
+ * removed because it made two people looking at the same issue see different
+ * sidebars with no explanation. Permission is now answered once, at run time.
+ */
+export const quickActionKeys = {
+ all: (wsId: string) => ["quick-actions", wsId] as const,
+ list: (wsId: string, includeArchived = false) =>
+ [...quickActionKeys.all(wsId), "list", includeArchived] as const,
+};
+
+export function quickActionListOptions(wsId: string, includeArchived = false) {
+ return queryOptions({
+ queryKey: quickActionKeys.list(wsId, includeArchived),
+ queryFn: () => api.listQuickActions({ includeArchived }),
+ select: (data) => data.quick_actions,
+ });
+}
diff --git a/packages/core/types/activity.ts b/packages/core/types/activity.ts
index 16a947a855..11b666d68c 100644
--- a/packages/core/types/activity.ts
+++ b/packages/core/types/activity.ts
@@ -21,6 +21,8 @@ export interface TimelineEntry {
parent_id?: string | null;
updated_at?: string;
comment_type?: string;
+ /** Set only on comments a quick action produced (MUL-5465). Unforgeable. */
+ quick_action_id?: string | null;
reactions?: Reaction[];
attachments?: Attachment[];
resolved_at?: string | null;
diff --git a/packages/core/types/comment.ts b/packages/core/types/comment.ts
index f4a837de8c..ddc0b7cbe8 100644
--- a/packages/core/types/comment.ts
+++ b/packages/core/types/comment.ts
@@ -30,6 +30,11 @@ export interface Comment {
resolved_by_type: CommentAuthorType | null;
resolved_by_id: string | null;
source_task_id?: string | null;
+ // The quick action that produced this comment (MUL-5465). A quick action
+ // posts an ORDINARY comment and marks it with this id; the collapsed card
+ // keys off the id rather than a dedicated `type`, because `type` is
+ // client-supplied on the generic comment endpoint and would be forgeable.
+ quick_action_id?: string | null;
// Per-target result of every explicit @agent / @squad mention in this comment
// (MUL-4525 §2). Present only on create/edit responses; older servers omit it.
trigger_outcomes?: CommentTriggerOutcome[];
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index c31ec48662..4ea45dd461 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -84,6 +84,20 @@ export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, Co
export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";
export type { IssueProperty, IssuePropertyType, IssuePropertyOption, IssuePropertyConfig, IssuePropertyValue, IssuePropertyValues, CreatePropertyRequest, UpdatePropertyRequest, ListPropertiesResponse, IssuePropertiesResponse } from "./property";
export { ISSUE_PROPERTY_TYPES, isKnownPropertyType } from "./property";
+export type {
+ QuickAction,
+ QuickActionVisibility,
+ QuickActionAssigneeType,
+ QuickActionStatus,
+ CreateQuickActionRequest,
+ UpdateQuickActionRequest,
+ ListQuickActionsResponse,
+} from "./quick-action";
+export {
+ QUICK_ACTION_SIDEBAR_LIMIT,
+ QUICK_ACTION_TEMPLATE_TOKEN_RE,
+ findQuickActionTemplateToken,
+} from "./quick-action";
export type {
TimelineEntry,
AssigneeFrequencyEntry,
diff --git a/packages/core/types/quick-action.ts b/packages/core/types/quick-action.ts
new file mode 100644
index 0000000000..49ca284629
--- /dev/null
+++ b/packages/core/types/quick-action.ts
@@ -0,0 +1,99 @@
+/**
+ * Issue Quick Actions (MUL-5465) — workspace-level presets for "who to call
+ * and what to say" on an existing issue.
+ *
+ * Running one is not a separate dispatch path: the server renders the prompt,
+ * posts a `quick_action` comment carrying the target's mention markup, and the
+ * normal comment -> mention -> task trigger takes over. That is why the run
+ * response is a `Comment` with `trigger_outcomes` rather than a bespoke shape.
+ */
+
+/**
+ * The author's stated intent, chosen at creation.
+ *
+ * - `public` — meant for the team. The server requires a target every member
+ * can invoke, so it is runnable by everyone by construction.
+ * - `private` — meant for its creator only; any target is allowed, and the
+ * list endpoint returns it to nobody else.
+ *
+ * This is intent, NOT an authorization decision — the run endpoint always
+ * re-checks invoke permission. Server-driven enum: switch with a `default`.
+ */
+export type QuickActionVisibility = "private" | "public";
+
+export type QuickActionAssigneeType = "agent" | "squad";
+
+export type QuickActionStatus = "active" | "archived";
+
+export interface QuickAction {
+ id: string;
+ workspace_id: string;
+ name: string;
+ description: string;
+ assignee_type: QuickActionAssigneeType | string;
+ assignee_id: string;
+ /** Sent verbatim — there is no interpolation step. */
+ prompt: string;
+ visibility: QuickActionVisibility | string;
+ status: QuickActionStatus | string;
+ last_used_at: string | null;
+ use_count: number;
+ created_by_id: string;
+ created_at: string;
+ updated_at: string;
+ /** Display name of the bound agent or squad. Absent when it no longer resolves. */
+ target_name?: string;
+ /**
+ * Whether the bound target is currently invocable by every workspace member.
+ * Plain metadata, not a verdict — settings shows it beside the binding so a
+ * `public` action pointing at a now-private agent reads as visibly wrong.
+ */
+ target_public: boolean;
+ /** The bound agent or squad was archived or deleted. */
+ target_missing: boolean;
+}
+
+export interface CreateQuickActionRequest {
+ name: string;
+ description?: string;
+ assignee_type: QuickActionAssigneeType;
+ assignee_id: string;
+ prompt: string;
+ visibility?: QuickActionVisibility;
+}
+
+export interface UpdateQuickActionRequest {
+ name?: string;
+ description?: string;
+ assignee_type?: QuickActionAssigneeType;
+ assignee_id?: string;
+ prompt?: string;
+ visibility?: QuickActionVisibility;
+ status?: QuickActionStatus;
+}
+
+export interface ListQuickActionsResponse {
+ quick_actions: QuickAction[];
+}
+
+/**
+ * How many actions the issue sidebar shows before the rest collapse behind
+ * "More". Scarcity here is structural: a list that renders all 30 stops being
+ * a shortlist and becomes a menu nobody reads.
+ */
+export const QUICK_ACTION_SIDEBAR_LIMIT = 5;
+
+/**
+ * Matches any `{{...}}`, mirroring the server's write-time rejection.
+ *
+ * Templating is not supported: every variable considered named something the
+ * agent already had from the issue context. The check survives the feature so
+ * a habitual token cannot land literally in an agent's instructions — the form
+ * shows it inline instead of waiting for a 400.
+ */
+export const QUICK_ACTION_TEMPLATE_TOKEN_RE = /\{\{[^}]*\}\}/;
+
+/** The first template token in a prompt, or null when there is none. */
+export function findQuickActionTemplateToken(prompt: string): string | null {
+ return prompt.match(QUICK_ACTION_TEMPLATE_TOKEN_RE)?.[0] ?? null;
+}
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 3da0d7f3a0..1ab3155c24 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -56,6 +56,7 @@ import {
} from "./utils/parse-markdown-chunked";
import type { MentionItem } from "./extensions/mention-suggestion";
import type { IssueIdentifierResolver } from "./extensions/issue-identifier-autolink";
+import type { BuiltinCommandSuggestionOptions } from "./extensions/slash-command-suggestion";
import { createEditorExtensions } from "./extensions";
import {
uploadAndInsertFile,
@@ -189,6 +190,12 @@ interface ContentEditorBaseProps {
* command menu (issue comments), e.g. /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.
+ */
+ quickActionMenu?: BuiltinCommandSuggestionOptions;
/**
* Attachments referenced by this content. The download buttons on file
* cards and images inside the editor look up an attachment by `url` and
@@ -362,6 +369,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
mentionContextItems,
enableSlashCommands = false,
slashCommandMode = "skill",
+ quickActionMenu,
attachments,
flushPendingOnUnmount = false,
onReady,
@@ -387,6 +395,10 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
// live without remounting the editor.
const pasteAsFileThresholdRef = useRef<number | undefined>(pasteAsFileThreshold);
const mentionContextItemsRef = useRef<MentionItem[]>(mentionContextItems ?? []);
+ // Kept in a ref for the same reason as mentionContextItems: the extension
+ // set is built once at mount, so a directly-captured options object would
+ // freeze whatever closures existed then and stop seeing new quick actions.
+ const quickActionMenuRef = useRef<BuiltinCommandSuggestionOptions | undefined>(quickActionMenu);
const lastEmittedRef = useRef<string | null>(null);
// `content` already consumes the initial synchronized value when Tiptap
// mounts. Track later changes separately so the sync effect does not parse
@@ -482,6 +494,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
onUploadFileRef.current = wrappedOnUploadFile;
pasteAsFileThresholdRef.current = pasteAsFileThreshold;
mentionContextItemsRef.current = mentionContextItems ?? [];
+ quickActionMenuRef.current = quickActionMenu;
flushPendingOnUnmountRef.current = flushPendingOnUnmount;
const queryClient = useQueryClient();
@@ -584,6 +597,13 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
getMentionContextItems: () => mentionContextItemsRef.current,
enableSlashCommands,
slashCommandMode,
+ quickActionMenu: {
+ getQuickActions: () => quickActionMenuRef.current?.getQuickActions?.() ?? [],
+ renderQuickAction: (id: string) =>
+ quickActionMenuRef.current?.renderQuickAction?.(id) ?? Promise.resolve(""),
+ onRenderError: (error: unknown) =>
+ quickActionMenuRef.current?.onRenderError?.(error),
+ },
resolveIssueIdentifierRef,
}),
onUpdate: ({ editor: ed }) => {
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 7f7699209c..01e472faf1 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -45,6 +45,7 @@ import {
} from "./issue-identifier-autolink";
import { SlashCommandExtension } from "./slash-command-extension";
import { createSlashCommandSuggestion, createBuiltinCommandSuggestion } from "./slash-command-suggestion";
+import type { BuiltinCommandSuggestionOptions } from "./slash-command-suggestion";
import { SuggestionTriggerArmingExtension } from "./suggestion-trigger-arming";
import { CodeBlockView } from "./code-block-view";
import { PatchedListItem, PatchedTaskItem } from "./list-item";
@@ -173,6 +174,13 @@ export interface EditorExtensionsOptions {
* - "command" — the fixed built-in command menu (issue comments), e.g. /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.
+ */
+ quickActionMenu?: BuiltinCommandSuggestionOptions;
/**
* Resolver for Linear-style bare issue-identifier autolinking. When present
* (and mentions are enabled), typing a boundary after `MUL-123` or pasting
@@ -268,7 +276,7 @@ export function createEditorExtensions(
suggestion: !options.enableSlashCommands
? { char: "/", allow: () => false }
: options.slashCommandMode === "command"
- ? createBuiltinCommandSuggestion()
+ ? createBuiltinCommandSuggestion(options.quickActionMenu)
: options.queryClient
? createSlashCommandSuggestion(options.queryClient)
: { char: "/", allow: () => false },
diff --git a/packages/views/editor/extensions/slash-command-suggestion.test.tsx b/packages/views/editor/extensions/slash-command-suggestion.test.tsx
index 8eeaf98fb6..a5897ce2ba 100644
--- a/packages/views/editor/extensions/slash-command-suggestion.test.tsx
+++ b/packages/views/editor/extensions/slash-command-suggestion.test.tsx
@@ -44,6 +44,8 @@ import {
type SlashCommandItem,
buildBuiltinCommandItems,
BUILTIN_COMMANDS,
+ createBuiltinCommandSuggestion,
+ QUICK_ACTION_ITEM_PREFIX,
} from "./slash-command-suggestion";
function agent(overrides: Partial<Agent>): Agent {
@@ -492,3 +494,123 @@ describe("SlashCommandList built-in command rendering", () => {
).toBeInTheDocument();
});
});
+
+
+// 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 } } } },
+ },
+ };
+ }
+
+ 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);
+ });
+
+ 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; }),
+ });
+
+ 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" },
+ ]);
+ });
+
+ 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; }),
+ });
+
+ 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);
+ });
+});
diff --git a/packages/views/editor/extensions/slash-command-suggestion.tsx b/packages/views/editor/extensions/slash-command-suggestion.tsx
index 4281ad0f7c..45e46bbadb 100644
--- a/packages/views/editor/extensions/slash-command-suggestion.tsx
+++ b/packages/views/editor/extensions/slash-command-suggestion.tsx
@@ -263,18 +263,62 @@ export const BUILTIN_COMMANDS: SlashCommandItem[] = [
{ id: "note", label: "note", descriptionKey: "note" },
];
+/** Marks a menu entry as a configured quick action rather than a built-in. */
+export const QUICK_ACTION_ITEM_PREFIX = "quick-action:";
+
+export function isQuickActionItem(item: SlashCommandItem): boolean {
+ return item.id.startsWith(QUICK_ACTION_ITEM_PREFIX);
+}
+
+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).
-export function buildBuiltinCommandItems(query: string): SlashCommandItem[] {
+export function buildBuiltinCommandItems(
+ query: string,
+ quickActions: { id: string; name: string; description?: string }[] = [],
+): SlashCommandItem[] {
const q = query.toLowerCase();
- return BUILTIN_COMMANDS.filter((c) => c.label.toLowerCase().startsWith(q));
+ // 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);
}
-export function createBuiltinCommandSuggestion(): Omit<
- SuggestionOptions<SlashCommandItem>,
- "editor"
-> {
+export interface BuiltinCommandSuggestionOptions {
+ /**
+ * Configured quick actions offered alongside the built-ins. Read lazily on
+ * every keystroke so a newly created action shows up without remounting the
+ * editor.
+ */
+ getQuickActions?: () => { id: string; name: string; description?: string }[];
+ /**
+ * 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.
+ */
+ 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;
+}
+
+export function createBuiltinCommandSuggestion(
+ options: BuiltinCommandSuggestionOptions = {},
+): Omit<SuggestionOptions<SlashCommandItem>, "editor"> {
const pluginKey = new PluginKey("builtinCommandSuggestion");
return {
@@ -283,8 +327,59 @@ export function createBuiltinCommandSuggestion(): Omit<
// 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),
+ 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();
+ })
+ .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);
+ });
+ 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
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 8b1f307a3f..ecae8686e0 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -753,6 +753,13 @@ function CommentRow({
// CommentCard — One Card per thread (parent + all replies flat inside)
// ---------------------------------------------------------------------------
+// A quick action posts an ordinary comment and is rendered as one (MUL-5465).
+// It briefly had a collapsed one-line header that expanded to reveal the
+// prompt, on the theory that repeated runs would bury the discussion. In
+// practice the prompts are short, the header restated what the body already
+// said, and the disclosure only added a click between the reader and the text.
+// Provenance still lives on `quick_action_id`; it is data, not decoration.
+
function CommentCardImpl({
issueId,
entry,
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index 62ead0cbfa..1634cbd4b2 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -12,6 +12,7 @@ import { useT } from "../../i18n";
import { CommentTriggerChips } from "./comment-trigger-chips";
import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
import { useCommentUploads } from "./use-comment-uploads";
+import { useQuickActionMenu } from "../hooks/use-quick-action-menu";
interface CommentInputProps {
issueId: string;
@@ -33,6 +34,9 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
// `defaultValue` at mount time, so this snapshot drives both the editor's
// initial content and the submit-button enable state — without this the
// button would be disabled even though the editor visibly contains text.
+ // Quick actions in the `/` menu: picking one inserts the server-rendered
+ // body so the user can edit before sending, instead of firing immediately.
+ const quickActionMenu = useQuickActionMenu(issueId);
const draftKey = `new:${issueId}` as const;
const [initialDraft] = useState(() =>
useCommentDraftStore.getState().getDraft(draftKey),
@@ -225,6 +229,7 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
attachments={pendingAttachments}
enableSlashCommands
slashCommandMode="command"
+ quickActionMenu={quickActionMenu}
/>
</div>
)}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index dc67eb326c..bb92b3261c 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -68,6 +68,7 @@ import { ThreadMinimap, type ThreadMinimapThread } from "./thread-minimap";
import { collectThreadReplies, deriveThreadResolution } from "./thread-utils";
import { IssueAgentHeaderChip } from "./issue-agent-header-chip";
import { ExecutionLogSection } from "./execution-log-section";
+import { QuickActionsSection } from "./quick-actions-section";
import { PullRequestList } from "./pull-request-list";
import { useGitHubSettings } from "@multica/core/github";
import { useQuery } from "@tanstack/react-query";
@@ -2000,6 +2001,14 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
</div>}
</div>
+ {/* Quick actions — the sidebar's only "do something" block, so it sits
+ directly under Properties and above every read-only section. Renders
+ nothing when the workspace has no active action visible to this
+ member. It is NOT filtered by invoke permission: a member can see and
+ click an action they cannot run, and the refusal is explained at run
+ time rather than by a silently shorter list. */}
+ <QuickActionsSection issueId={issue.id} />
+
{/* Parent issue — standalone section, only when the issue has a
parent. Setting a parent is reachable via the issue actions menu;
this card surfaces an existing parent without occupying sidebar
diff --git a/packages/views/issues/components/quick-actions-section.test.tsx b/packages/views/issues/components/quick-actions-section.test.tsx
new file mode 100644
index 0000000000..e277c957ed
--- /dev/null
+++ b/packages/views/issues/components/quick-actions-section.test.tsx
@@ -0,0 +1,207 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import type { QuickAction } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { QuickActionsSection } from "./quick-actions-section";
+
+// The section's contract (MUL-5465) is mostly about being HONEST with the
+// user, so these tests target exactly that: what gets offered, and what the
+// result claims happened.
+//
+// Two cases are worth locking hardest:
+// - `coalesced` — the DB allows one pending task per (issue, agent), so a
+// click can legitimately start NO new run. Reporting that as success is
+// the bug this feature is most likely to ship with.
+// - a permission refusal — the list is deliberately NOT filtered by invoke
+// permission, so a member CAN click something they cannot run. That must
+// open the explanatory dialog, not a bare error toast.
+
+const runMock = vi.fn();
+let listData: QuickAction[] = [];
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: () => ({ data: listData, isLoading: false }),
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "ws-1" }),
+}));
+
+vi.mock("@multica/core/quick-actions", () => ({
+ quickActionListOptions: () => ({ queryKey: ["quick-actions"], queryFn: vi.fn() }),
+ useRunQuickAction: () => ({ mutateAsync: runMock, isPending: false }),
+}));
+
+let reasonCode: string | undefined;
+vi.mock("@multica/core/api", () => ({
+ dispatchReasonCode: () => reasonCode,
+}));
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: () => <span data-testid="actor-avatar" />,
+}));
+
+const toastCalls: { kind: string; message: string }[] = [];
+vi.mock("sonner", () => ({
+ toast: {
+ success: (m: string) => toastCalls.push({ kind: "success", message: m }),
+ info: (m: string) => toastCalls.push({ kind: "info", message: m }),
+ error: (m: string) => toastCalls.push({ kind: "error", message: m }),
+ },
+}));
+
+function action(overrides: Partial<QuickAction> = {}): QuickAction {
+ return {
+ id: "qa-1",
+ workspace_id: "ws-1",
+ name: "Code Review",
+ description: "",
+ assignee_type: "agent",
+ assignee_id: "agent-1",
+ prompt: "review it",
+ visibility: "public",
+ status: "active",
+ last_used_at: null,
+ use_count: 0,
+ created_by_id: "u-1",
+ created_at: "",
+ updated_at: "",
+ target_name: "Lambda",
+ target_public: true,
+ target_missing: false,
+ ...overrides,
+ };
+}
+
+function outcome(status: string) {
+ return {
+ id: "c-1",
+ trigger_outcomes: [
+ { target_type: "agent", target_id: "agent-1", status, reason_code: status },
+ ],
+ };
+}
+
+describe("QuickActionsSection", () => {
+ beforeEach(() => {
+ runMock.mockReset();
+ toastCalls.length = 0;
+ reasonCode = undefined;
+ listData = [action()];
+ });
+
+ it("renders nothing when the workspace has no actions", () => {
+ listData = [];
+ const { container } = renderWithI18n(<QuickActionsSection issueId="i-1" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("hides archived actions even if the server returned them", () => {
+ listData = [action({ status: "archived" })];
+ const { container } = renderWithI18n(<QuickActionsSection issueId="i-1" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("runs immediately on click when the action takes no input", async () => {
+ runMock.mockResolvedValue(outcome("queued"));
+ renderWithI18n(<QuickActionsSection issueId="i-1" />);
+
+ fireEvent.click(screen.getByText("Code Review"));
+
+ await waitFor(() =>
+ expect(runMock).toHaveBeenCalledWith({ quickActionId: "qa-1" }),
+ );
+ await waitFor(() => expect(toastCalls[0]?.kind).toBe("success"));
+ expect(toastCalls[0]?.message).toContain("Lambda");
+ });
+
+ it("reports a coalesced run as queued-behind, never as a fresh start", async () => {
+ runMock.mockResolvedValue(outcome("coalesced"));
+ renderWithI18n(<QuickActionsSection issueId="i-1" />);
+
+ fireEvent.click(screen.getByText("Code Review"));
+
+ await waitFor(() => expect(toastCalls).toHaveLength(1));
+ expect(toastCalls[0]?.kind).toBe("info");
+ expect(toastCalls[0]?.message.toLowerCase()).toContain("added to");
+ });
+
+ it("reports an offline target as deferred rather than started", async () => {
+ runMock.mockResolvedValue(outcome("deferred"));
+ renderWithI18n(<QuickActionsSection issueId="i-1" />);
+
+ fireEvent.click(screen.getByText("Code Review"));
+
+ await waitFor(() => expect(toastCalls).toHaveLength(1));
+ expect(toastCalls[0]?.kind).toBe("info");
+ expect(toastCalls[0]?.message.toLowerCase()).toContain("offline");
+ });
+
+ it("does not claim success for an unknown server status", async () => {
+ runMock.mockResolvedValue(outcome("some_future_status"));
+ renderWithI18n(<QuickActionsSection issueId="i-1" />);
+
+ fireEvent.click(screen.getByText("Code Review"));
+
+ await waitFor(() => expect(toastCalls).toHaveLength(1));
+ expect(toastCalls[0]?.kind).not.toBe("success");
+ });
+
+ it("still offers an action the viewer cannot run, and explains the refusal in a dialog", async () => {
+ // The list is intentionally unfiltered, so this path is reachable by
+ // design — the explanation is the whole point of not hiding the button.
+ reasonCode = "invocation_not_allowed";
+ runMock.mockRejectedValue(new Error("forbidden"));
+ renderWithI18n(<QuickActionsSection issueId="i-1" />);
+
+ fireEvent.click(screen.getByText("Code Review"));
+
+ await waitFor(() => expect(screen.getByRole("alertdialog")).toBeInTheDocument());
+ expect(screen.getByText(/can’t run this quick action/i)).toBeInTheDocument();
+ // A refusal is explained, not toasted as a transient failure.
+ expect(toastCalls).toHaveLength(0);
+ });
+
+ it("toasts a non-permission failure instead of opening the dialog", async () => {
+ reasonCode = undefined;
+ runMock.mockRejectedValue(new Error("network down"));
+ renderWithI18n(<QuickActionsSection issueId="i-1" />);
+
+ fireEvent.click(screen.getByText("Code Review"));
+
+ await waitFor(() => expect(toastCalls).toHaveLength(1));
+ expect(toastCalls[0]?.kind).toBe("error");
+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
+ });
+
+ it("runs on a single click — there is no per-action input step", () => {
+ // The `/` slash command covers "same action, one detail different" by
+ // dropping the rendered body into the composer, so the sidebar row stays a
+ // plain button with no second interaction tier.
+ runMock.mockResolvedValue(outcome("queued"));
+ renderWithI18n(<QuickActionsSection issueId="i-1" />);
+
+ fireEvent.click(screen.getByText("Code Review"));
+
+ expect(runMock).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ });
+
+ it("collapses everything past the sidebar limit behind More", () => {
+ listData = [
+ action({ id: "a", name: "One" }),
+ action({ id: "b", name: "Two" }),
+ action({ id: "c", name: "Three" }),
+ action({ id: "d", name: "Four" }),
+ action({ id: "e", name: "Five" }),
+ action({ id: "f", name: "Six" }),
+ ];
+ renderWithI18n(<QuickActionsSection issueId="i-1" />);
+
+ expect(screen.getByText("Five")).toBeInTheDocument();
+ expect(screen.queryByText("Six")).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByText(/Show 1 more/i));
+ expect(screen.getByText("Six")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/issues/components/quick-actions-section.tsx b/packages/views/issues/components/quick-actions-section.tsx
new file mode 100644
index 0000000000..0af27340be
--- /dev/null
+++ b/packages/views/issues/components/quick-actions-section.tsx
@@ -0,0 +1,240 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { ChevronRight, Loader2, Zap } from "lucide-react";
+import { toast } from "sonner";
+import { dispatchReasonCode } from "@multica/core/api";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { quickActionListOptions, useRunQuickAction } from "@multica/core/quick-actions";
+import type { Comment, CommentTriggerOutcome, QuickAction } from "@multica/core/types";
+import { QUICK_ACTION_SIDEBAR_LIMIT } from "@multica/core/types";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { useT } from "../../i18n";
+
+// Quick Actions sidebar section (MUL-5465).
+//
+// The list is NOT filtered by invoke permission. An earlier version hid
+// actions the viewer could not run, which meant two people on one issue saw
+// different sidebars with nothing to explain the difference — harder to debug
+// than a button that tells you why it refused. Permission is answered once, by
+// the run endpoint; a refusal opens a dialog.
+//
+// One interaction: click runs it. There is no per-action input field — the `/`
+// slash command already drops a rendered action into the composer for editing,
+// which covers "same action, one detail different" more flexibly than a single
+// fixed field could, so a second UI for it was removed.
+//
+// The result toast is deliberately outcome-specific rather than a generic
+// "done". A second click against an agent that already has a pending task on
+// this issue does NOT start a second run — the DB permits one pending task per
+// (issue, agent) and the comment is merged into the existing one. Reporting
+// that as success would be a lie the user later has to debug.
+
+export function QuickActionsSection({ issueId }: { issueId: string }) {
+ const { t } = useT("issues");
+ // Nullable read, not useWorkspaceId(): this section is an enhancement on the
+ // sidebar and must degrade to "not rendered" outside a workspace route
+ // rather than throwing and taking the whole issue detail down with it.
+ const wsId = useCurrentWorkspace()?.id ?? "";
+ const [open, setOpen] = useState(true);
+ const [showAll, setShowAll] = useState(false);
+ const [blocked, setBlocked] = useState<QuickAction | null>(null);
+
+ const { data = [], isLoading } = useQuery({
+ ...quickActionListOptions(wsId),
+ enabled: wsId !== "",
+ });
+ const actions = useMemo(() => data.filter((a) => a.status === "active"), [data]);
+
+ // Nothing configured renders nothing at all: an empty section header in the
+ // sidebar is pure noise.
+ if (isLoading || actions.length === 0) return null;
+
+ const visible = showAll ? actions : actions.slice(0, QUICK_ACTION_SIDEBAR_LIMIT);
+ const hiddenCount = actions.length - visible.length;
+
+ return (
+ <div>
+ <button
+ type="button"
+ className={cn(
+ "mb-2 flex w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors hover:bg-accent/70",
+ !open && "text-muted-foreground hover:text-foreground",
+ )}
+ onClick={() => setOpen(!open)}
+ >
+ {t(($) => $.detail.section_quick_actions)}
+ <ChevronRight
+ className={cn(
+ "!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform",
+ open && "rotate-90",
+ )}
+ />
+ </button>
+ {open ? (
+ <div className="space-y-0.5 pl-2">
+ {visible.map((action) => (
+ <QuickActionRow
+ key={action.id}
+ action={action}
+ issueId={issueId}
+ onBlocked={() => setBlocked(action)}
+ />
+ ))}
+ {hiddenCount > 0 ? (
+ <button
+ type="button"
+ className="w-full rounded-md px-2 py-1 text-left text-caption text-muted-foreground transition-colors hover:bg-accent/70 hover:text-foreground"
+ onClick={() => setShowAll(true)}
+ >
+ {t(($) => $.detail.quick_actions_more, { count: hiddenCount })}
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+
+ {/* One message for every refusal. The person reading this dialog and the
+ person who can fix the binding are different people — the clicker's
+ next step is the same either way, and the diagnostic detail lives in
+ settings where the owner will act on it. */}
+ <AlertDialog open={blocked !== null} onOpenChange={(v) => !v && setBlocked(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.detail.quick_action_blocked_title)}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.detail.quick_action_blocked_body, { name: blocked?.name ?? "" })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogAction>{t(($) => $.detail.quick_action_blocked_ok)}</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
+/**
+ * Translate the per-target outcome into an honest sentence.
+ *
+ * `coalesced` is the one that matters: the click was accepted but no NEW run
+ * started. "Added to Lambda's current run" is the truth; "Lambda started
+ * working" is not.
+ */
+function outcomeMessage(
+ outcome: CommentTriggerOutcome | undefined,
+ targetName: string,
+ t: ReturnType<typeof useT<"issues">>["t"],
+): { message: string; kind: "success" | "info" | "error" } {
+ if (!outcome) {
+ // No outcome at all means the comment saved but nothing was reported —
+ // surface it as neutral rather than claiming a run.
+ return { message: t(($) => $.detail.quick_action_posted), kind: "info" };
+ }
+ switch (outcome.status) {
+ case "queued":
+ return { message: t(($) => $.detail.quick_action_queued, { name: targetName }), kind: "success" };
+ case "coalesced":
+ return { message: t(($) => $.detail.quick_action_coalesced, { name: targetName }), kind: "info" };
+ case "deferred":
+ return { message: t(($) => $.detail.quick_action_deferred, { name: targetName }), kind: "info" };
+ case "blocked":
+ return { message: t(($) => $.detail.quick_action_blocked, { name: targetName }), kind: "error" };
+ default:
+ // Server-driven enum: an unknown status must not be silently rendered
+ // as success.
+ return { message: t(($) => $.detail.quick_action_posted), kind: "info" };
+ }
+}
+
+function QuickActionRow({
+ action,
+ issueId,
+ onBlocked,
+}: {
+ action: QuickAction;
+ issueId: string;
+ onBlocked: () => void;
+}) {
+ const { t } = useT("issues");
+ const runMutation = useRunQuickAction(issueId);
+ const running = runMutation.isPending;
+
+ const targetName = action.target_name || t(($) => $.detail.quick_action_target_fallback);
+
+ const handleRun = async () => {
+ try {
+ const comment: Comment = await runMutation.mutateAsync({ quickActionId: action.id });
+ const { message, kind } = outcomeMessage(comment.trigger_outcomes?.[0], targetName, t);
+ if (kind === "success") toast.success(message);
+ else if (kind === "error") toast.error(message);
+ else toast.info(message);
+ } catch (error) {
+ // A permission refusal is a structured 403 the user needs explained, not
+ // a transient failure they should retry — it gets the dialog. Everything
+ // else stays a toast.
+ if (dispatchReasonCode(error) === "invocation_not_allowed") {
+ onBlocked();
+ return;
+ }
+ toast.error(error instanceof Error ? error.message : String(error));
+ }
+ };
+
+ const row = (
+ <div>
+ <button
+ type="button"
+ disabled={running}
+ onClick={() => void handleRun()}
+ className={cn(
+ "group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-body transition-colors",
+ "hover:bg-accent/70 disabled:cursor-default disabled:opacity-60",
+ )}
+ >
+ {running ? (
+ <Loader2 className="size-3.5 shrink-0 animate-spin text-muted-foreground" />
+ ) : (
+ <Zap className="size-3.5 shrink-0 text-muted-foreground" />
+ )}
+ <span className="min-w-0 flex-1 truncate">{action.name}</span>
+ {action.target_name ? (
+ <ActorAvatar
+ actorType={action.assignee_type === "squad" ? "squad" : "agent"}
+ actorId={action.assignee_id}
+ size="xs"
+ className="shrink-0"
+ showStatusDot={action.assignee_type === "agent"}
+ />
+ ) : null}
+ </button>
+ </div>
+ );
+
+ return (
+ <Tooltip>
+ <TooltipTrigger render={row} />
+ <TooltipContent side="left">
+ <div className="space-y-0.5">
+ <div className="font-medium">{action.name}</div>
+ {action.description ? <div>{action.description}</div> : null}
+ <div className="text-muted-foreground">
+ {t(($) => $.detail.quick_action_runs_as, { name: targetName })}
+ </div>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/packages/views/issues/hooks/use-quick-action-menu.ts b/packages/views/issues/hooks/use-quick-action-menu.ts
new file mode 100644
index 0000000000..dd815070e7
--- /dev/null
+++ b/packages/views/issues/hooks/use-quick-action-menu.ts
@@ -0,0 +1,64 @@
+"use client";
+
+import { useCallback, useMemo, useRef } 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";
+
+/**
+ * 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
+ * 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.
+ *
+ * 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) {
+ const workspace = useCurrentWorkspace();
+ const wsId = workspace?.id ?? "";
+ const { data = [] } = useQuery({
+ ...quickActionListOptions(wsId),
+ enabled: wsId !== "",
+ });
+
+ // The extension reads through a getter on every keystroke; a ref keeps that
+ // read cheap and current without re-creating the editor.
+ const actionsRef = useRef<{ id: string; name: string; description?: string }[]>([]);
+ actionsRef.current = useMemo(
+ () =>
+ data
+ .filter((a) => a.status === "active")
+ .map((a) => ({ id: a.id, name: a.name, description: a.description || undefined })),
+ [data],
+ );
+
+ const getQuickActions = useCallback(() => actionsRef.current, []);
+ const renderQuickAction = useCallback(
+ (quickActionId: string) => api.renderQuickAction(issueId, quickActionId),
+ [issueId],
+ );
+
+ // 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));
+ }, []);
+
+ return useMemo(
+ () => ({ getQuickActions, renderQuickAction, onRenderError }),
+ [getQuickActions, renderQuickAction, onRenderError],
+ );
+}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 16ca1f033b..59ae4f1138 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -247,6 +247,18 @@
"section_metadata": "Metadata",
"section_details": "Details",
"section_token_usage": "Token usage",
+ "section_quick_actions": "Quick Actions",
+ "quick_actions_more": "Show {{count}} more",
+ "quick_action_runs_as": "Runs as {{name}}",
+ "quick_action_target_fallback": "the agent",
+ "quick_action_queued": "{{name}} started working",
+ "quick_action_coalesced": "Added to {{name}}’s current run",
+ "quick_action_deferred": "{{name}} is offline — it will start once back online",
+ "quick_action_blocked": "{{name}} could not be triggered",
+ "quick_action_posted": "Comment posted",
+ "quick_action_blocked_title": "You can’t run this quick action",
+ "quick_action_blocked_body": "“{{name}}” runs as an agent you’re not allowed to trigger. Ask a workspace admin to make that agent available to the team, or to point this action at a shared one.",
+ "quick_action_blocked_ok": "Got it",
"pull_requests_loading": "Loading…",
"pull_requests_empty": "No linked pull requests yet. Reference this issue's identifier in a PR's branch name, title, or body to auto-link it.",
"pull_request_state_open": "Open",
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index d041c9834b..345d440efe 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1,4 +1,51 @@
{
+ "quick_actions": {
+ "title": "Quick Actions",
+ "description": "Preset an agent and a prompt once, then trigger it from any issue's sidebar with a single click.",
+ "add": "New quick action",
+ "search_placeholder": "Search quick actions",
+ "loading": "Loading quick actions…",
+ "no_results": "No quick actions match your search",
+ "actions_open": "Open actions for {{name}}",
+ "columns": {
+ "name": "Name",
+ "target": "Runs as",
+ "visibility": "Who",
+ "usage": "Used",
+ "updated": "Updated"
+ },
+ "empty_title": "No quick actions yet",
+ "empty_hint": "Create one for the work you ask an agent to do again and again — code review, writing tests, a security pass.",
+ "archived": "Archived",
+ "visibility_public": "Team",
+ "visibility_private": "Just me",
+ "visibility_public_hint": "Everyone in the workspace",
+ "visibility_private_hint": "Only you",
+ "field_visibility": "Who can use it",
+ "public_target_hint": "Must be an agent everyone can trigger.",
+ "target_private": "private",
+ "target_missing": "Target unavailable",
+ "archive": "Archive",
+ "unarchive": "Restore",
+ "edit": "Edit",
+ "delete": "Delete",
+ "cancel": "Cancel",
+ "save": "Save",
+ "never_used": "Never used",
+ "used_count": "Used {{count}}×",
+ "create_title": "New quick action",
+ "edit_title": "Edit quick action",
+ "dialog_description": "Runs as a comment on the issue, like an @mention.",
+ "field_name": "Name",
+ "field_name_placeholder": "Code Review",
+ "field_target": "Runs as",
+ "field_prompt": "Prompt",
+ "field_prompt_placeholder": "Review the code linked to this issue. Focus on correctness and edge cases.",
+ "prompt_hint": "Sent as written. The agent already sees the issue.",
+ "template_not_supported": "Variables aren’t supported yet — remove {{token}}. The agent already reads this issue.",
+ "delete_title": "Delete this quick action?",
+ "delete_description": "It disappears from every issue sidebar. Past runs stay in the execution log. Archive instead if you may want it back."
+ },
"auto_save": {
"saving": "Saving…",
"saved": "Saved",
@@ -135,7 +182,8 @@
"labs": "Labs",
"members": "Members",
"labels": "Labels",
- "properties": "Properties"
+ "properties": "Properties",
+ "quick_actions": "Quick Actions"
}
},
"properties": {
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 4e036c1543..818838eb9b 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -245,6 +245,18 @@
"section_metadata": "メタデータ",
"section_details": "詳細",
"section_token_usage": "トークン使用量",
+ "section_quick_actions": "クイックアクション",
+ "quick_actions_more": "残り {{count}} 件を表示",
+ "quick_action_runs_as": "{{name}} が実行します",
+ "quick_action_target_fallback": "このエージェント",
+ "quick_action_queued": "{{name}} が作業を開始しました",
+ "quick_action_coalesced": "{{name}} の実行中タスクに追加しました",
+ "quick_action_deferred": "{{name}} はオフラインです。復帰後に開始します",
+ "quick_action_blocked": "{{name}} を実行できませんでした",
+ "quick_action_posted": "コメントを投稿しました",
+ "quick_action_blocked_title": "このクイックアクションは実行できません",
+ "quick_action_blocked_body": "「{{name}}」は、あなたが実行を許可されていないエージェントで動作します。ワークスペース管理者にそのエージェントをチームへ公開してもらうか、共有エージェントへの変更を依頼してください。",
+ "quick_action_blocked_ok": "了解",
"pull_requests_loading": "読み込み中...",
"pull_requests_empty": "まだリンクされた Pull request がありません。PR のブランチ名、タイトル、または本文にこのイシューの識別子を入れると、自動的にリンクされます。",
"pull_request_state_open": "オープン",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index cffbb9b6ee..5d46cfea04 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1,4 +1,51 @@
{
+ "quick_actions": {
+ "title": "クイックアクション",
+ "description": "実行するエージェントとプロンプトを事前に設定し、任意の課題のサイドバーからワンクリックで実行します。",
+ "add": "クイックアクションを作成",
+ "search_placeholder": "クイックアクションを検索",
+ "loading": "クイックアクションを読み込んでいます…",
+ "no_results": "一致するクイックアクションはありません",
+ "actions_open": "「{{name}}」のアクションメニューを開く",
+ "columns": {
+ "name": "名前",
+ "target": "実行者",
+ "visibility": "公開範囲",
+ "usage": "使用回数",
+ "updated": "更新日"
+ },
+ "empty_title": "クイックアクションがありません",
+ "empty_hint": "コードレビュー、テスト作成、セキュリティ確認など、繰り返しエージェントに頼む作業を登録しましょう。",
+ "archived": "アーカイブ済み",
+ "visibility_public": "チーム",
+ "visibility_private": "自分のみ",
+ "visibility_public_hint": "ワークスペースの全員",
+ "visibility_private_hint": "自分だけ",
+ "field_visibility": "使用できる範囲",
+ "public_target_hint": "全員が実行できるエージェントのみ指定できます。",
+ "target_private": "非公開",
+ "target_missing": "実行者が利用できません",
+ "archive": "アーカイブ",
+ "unarchive": "復元",
+ "edit": "編集",
+ "delete": "削除",
+ "cancel": "キャンセル",
+ "save": "保存",
+ "never_used": "未使用",
+ "used_count": "{{count}} 回使用",
+ "create_title": "クイックアクションを作成",
+ "edit_title": "クイックアクションを編集",
+ "dialog_description": "@メンションと同じく、課題のコメントとして実行されます。",
+ "field_name": "名前",
+ "field_name_placeholder": "コードレビュー",
+ "field_target": "実行者",
+ "field_prompt": "プロンプト",
+ "field_prompt_placeholder": "この課題に関連するコードをレビューし、正確性とエッジケースを重点的に確認してください。",
+ "prompt_hint": "そのまま送られます。課題の内容は既に読めます。",
+ "template_not_supported": "変数はまだサポートされていません。{{token}} を削除してください。エージェントはこの課題を既に読めます。",
+ "delete_title": "このクイックアクションを削除しますか?",
+ "delete_description": "すべての課題のサイドバーから消えます。過去の実行は実行ログに残ります。後で使う可能性があればアーカイブを選んでください。"
+ },
"auto_save": {
"saving": "保存中…",
"saved": "保存済み",
@@ -132,7 +179,8 @@
"labs": "ラボ",
"members": "メンバー",
"labels": "ラベル",
- "properties": "プロパティ"
+ "properties": "プロパティ",
+ "quick_actions": "クイックアクション"
}
},
"properties": {
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index c89b02f0ee..853e28faef 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -245,6 +245,18 @@
"section_metadata": "메타데이터",
"section_details": "세부 정보",
"section_token_usage": "토큰 사용량",
+ "section_quick_actions": "퀵 액션",
+ "quick_actions_more": "{{count}}개 더 보기",
+ "quick_action_runs_as": "{{name}}이(가) 실행합니다",
+ "quick_action_target_fallback": "이 에이전트",
+ "quick_action_queued": "{{name}}이(가) 작업을 시작했습니다",
+ "quick_action_coalesced": "{{name}}의 현재 실행에 추가했습니다",
+ "quick_action_deferred": "{{name}}이(가) 오프라인입니다. 온라인이 되면 시작합니다",
+ "quick_action_blocked": "{{name}}을(를) 실행할 수 없습니다",
+ "quick_action_posted": "댓글을 게시했습니다",
+ "quick_action_blocked_title": "이 퀵 액션을 실행할 수 없습니다",
+ "quick_action_blocked_body": "“{{name}}”은(는) 트리거 권한이 없는 에이전트로 실행됩니다. 워크스페이스 관리자에게 해당 에이전트를 팀에 공개하거나 공유 에이전트로 변경해 달라고 요청하세요.",
+ "quick_action_blocked_ok": "확인",
"pull_requests_loading": "불러오는 중...",
"pull_requests_empty": "아직 연결된 Pull request가 없습니다. PR 브랜치 이름, 제목 또는 본문에 이 이슈 식별자를 넣으면 자동으로 연결됩니다.",
"pull_request_state_open": "열림",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 78958f4d3e..db174d2bb8 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1,4 +1,51 @@
{
+ "quick_actions": {
+ "title": "퀵 액션",
+ "description": "실행할 에이전트와 프롬프트를 미리 설정한 뒤, 어떤 이슈의 사이드바에서든 한 번의 클릭으로 실행합니다.",
+ "add": "퀵 액션 만들기",
+ "search_placeholder": "퀵 액션 검색",
+ "loading": "퀵 액션을 불러오는 중…",
+ "no_results": "일치하는 퀵 액션이 없습니다",
+ "actions_open": "“{{name}}” 작업 메뉴 열기",
+ "columns": {
+ "name": "이름",
+ "target": "실행자",
+ "visibility": "공개 범위",
+ "usage": "사용",
+ "updated": "업데이트"
+ },
+ "empty_title": "퀵 액션이 없습니다",
+ "empty_hint": "코드 리뷰, 테스트 작성, 보안 점검처럼 에이전트에게 반복해서 맡기는 작업을 등록하세요.",
+ "archived": "보관됨",
+ "visibility_public": "팀",
+ "visibility_private": "나만",
+ "visibility_public_hint": "워크스페이스의 모든 사람",
+ "visibility_private_hint": "나만",
+ "field_visibility": "사용 범위",
+ "public_target_hint": "모두가 트리거할 수 있는 에이전트만 지정할 수 있습니다.",
+ "target_private": "비공개",
+ "target_missing": "실행자를 사용할 수 없음",
+ "archive": "보관",
+ "unarchive": "복원",
+ "edit": "편집",
+ "delete": "삭제",
+ "cancel": "취소",
+ "save": "저장",
+ "never_used": "사용 안 함",
+ "used_count": "{{count}}회 사용",
+ "create_title": "퀵 액션 만들기",
+ "edit_title": "퀵 액션 편집",
+ "dialog_description": "@멘션처럼 이슈 댓글로 실행됩니다.",
+ "field_name": "이름",
+ "field_name_placeholder": "코드 리뷰",
+ "field_target": "실행자",
+ "field_prompt": "프롬프트",
+ "field_prompt_placeholder": "이 이슈에 연결된 코드를 검토하고 정확성과 예외 상황을 중점적으로 확인하세요.",
+ "prompt_hint": "작성한 그대로 전달됩니다. 에이전트는 이슈를 이미 읽을 수 있습니다.",
+ "template_not_supported": "변수는 아직 지원되지 않습니다. {{token}}을(를) 제거하세요. 에이전트는 이미 이 이슈를 읽습니다.",
+ "delete_title": "이 퀵 액션을 삭제할까요?",
+ "delete_description": "모든 이슈 사이드바에서 사라집니다. 과거 실행 기록은 실행 로그에 남습니다. 다시 쓸 수 있다면 보관을 선택하세요."
+ },
"auto_save": {
"saving": "저장 중…",
"saved": "저장됨",
@@ -132,7 +179,8 @@
"labs": "실험실",
"members": "멤버",
"labels": "레이블",
- "properties": "속성"
+ "properties": "속성",
+ "quick_actions": "퀵 액션"
}
},
"properties": {
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 75ad22f7a8..2bd865e880 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -245,6 +245,18 @@
"section_metadata": "元数据",
"section_details": "详情",
"section_token_usage": "Token 用量",
+ "section_quick_actions": "快捷操作",
+ "quick_actions_more": "显示其余 {{count}} 条",
+ "quick_action_runs_as": "由 {{name}} 执行",
+ "quick_action_target_fallback": "该 Agent",
+ "quick_action_queued": "{{name}} 已开始处理",
+ "quick_action_coalesced": "已加入 {{name}} 当前的任务",
+ "quick_action_deferred": "{{name}} 当前离线,上线后开始",
+ "quick_action_blocked": "无法触发 {{name}}",
+ "quick_action_posted": "评论已发布",
+ "quick_action_blocked_title": "你无法执行这条快捷操作",
+ "quick_action_blocked_body": "「{{name}}」由一个你无权触发的 Agent 执行。可以请工作区管理员把该 Agent 开放给团队,或把这条操作改绑一个共享的 Agent。",
+ "quick_action_blocked_ok": "知道了",
"pull_requests_loading": "加载中…",
"pull_requests_empty": "还没有关联的 PR。在 PR 的分支名、标题或正文里引用本 issue 的 identifier 即可自动关联。",
"pull_request_state_open": "Open",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index d4cf7b7be3..3985f807cb 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1,4 +1,51 @@
{
+ "quick_actions": {
+ "title": "快捷操作",
+ "description": "预先配置好执行的 Agent 和提示词,之后在任意 Issue 侧边栏一键触发。",
+ "add": "新建快捷操作",
+ "search_placeholder": "搜索快捷操作",
+ "loading": "正在加载快捷操作…",
+ "no_results": "没有匹配的快捷操作",
+ "actions_open": "打开「{{name}}」的操作菜单",
+ "columns": {
+ "name": "名称",
+ "target": "执行者",
+ "visibility": "可见范围",
+ "usage": "使用",
+ "updated": "更新时间"
+ },
+ "empty_title": "还没有快捷操作",
+ "empty_hint": "把反复交给 Agent 做的事配置成快捷操作——代码审查、补测试、安全检查。",
+ "archived": "已归档",
+ "visibility_public": "团队",
+ "visibility_private": "仅自己",
+ "visibility_public_hint": "工作区所有成员",
+ "visibility_private_hint": "只有你",
+ "field_visibility": "谁可以使用",
+ "public_target_hint": "只能选所有成员都能触发的 Agent。",
+ "target_private": "私有",
+ "target_missing": "执行者不可用",
+ "archive": "归档",
+ "unarchive": "恢复",
+ "edit": "编辑",
+ "delete": "删除",
+ "cancel": "取消",
+ "save": "保存",
+ "never_used": "从未使用",
+ "used_count": "已使用 {{count}} 次",
+ "create_title": "新建快捷操作",
+ "edit_title": "编辑快捷操作",
+ "dialog_description": "以 Issue 评论的形式执行,和 @提及 一样。",
+ "field_name": "名称",
+ "field_name_placeholder": "代码审查",
+ "field_target": "执行者",
+ "field_prompt": "提示词",
+ "field_prompt_placeholder": "请审查这个 Issue 关联的代码,重点关注正确性和边界情况。",
+ "prompt_hint": "原样发送。Agent 本来就能看到这个 Issue。",
+ "template_not_supported": "暂不支持变量,请删除 {{token}}。Agent 本来就能读到这个 Issue。",
+ "delete_title": "删除这条快捷操作?",
+ "delete_description": "它会从所有 Issue 侧边栏消失,历史运行记录仍保留在执行日志中。如果以后可能还要用,建议改为归档。"
+ },
"auto_save": {
"saving": "正在保存…",
"saved": "已保存",
@@ -135,7 +182,8 @@
"labs": "实验室",
"members": "成员",
"labels": "标签",
- "properties": "属性"
+ "properties": "属性",
+ "quick_actions": "快捷操作"
}
},
"properties": {
diff --git a/packages/views/settings/components/quick-actions-tab.tsx b/packages/views/settings/components/quick-actions-tab.tsx
new file mode 100644
index 0000000000..dbc9ce8bfd
--- /dev/null
+++ b/packages/views/settings/components/quick-actions-tab.tsx
@@ -0,0 +1,597 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ Archive,
+ ArchiveRestore,
+ Globe,
+ Info,
+ Lock,
+ MoreHorizontal,
+ Pencil,
+ Plus,
+ Search,
+ Trash2,
+ TriangleAlert,
+ Zap,
+} from "lucide-react";
+import { toast } from "sonner";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ quickActionListOptions,
+ useCreateQuickAction,
+ useDeleteQuickAction,
+ useUpdateQuickAction,
+} from "@multica/core/quick-actions";
+import type {
+ QuickAction,
+ QuickActionAssigneeType,
+ QuickActionVisibility,
+} from "@multica/core/types";
+import { findQuickActionTemplateToken } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { Input } from "@multica/ui/components/ui/input";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import { Label as FieldLabel } from "@multica/ui/components/ui/label";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { cn } from "@multica/ui/lib/utils";
+import { AgentPicker } from "../../autopilots/components/pickers/agent-picker";
+import { useT } from "../../i18n";
+import { SettingsTab } from "./settings-layout";
+
+// Quick Actions catalog (MUL-5465).
+//
+// Ordering is by use_count DESC, not created_at: the list's job is to answer
+// "what does this workspace actually use", and recency of creation says
+// nothing about that. Rows that have never been used sort last, which is also
+// where the "unused" cleanup signal belongs.
+//
+// Layout deliberately mirrors the Labels and Properties tabs: same search +
+// primary-action row, same bordered card, same responsive column grid that
+// collapses to stacked rows under `md`, same overflow menu. These three are
+// the workspace's "catalog of small named things" and reading as one surface
+// matters more than any per-tab cleverness.
+
+const UNUSED_DAYS_THRESHOLD = 90;
+
+/**
+ * A usage figure is only worth flagging once it has had time to be used. A
+ * freshly created action is "never used" by definition, so colouring it on day
+ * one trains people to ignore the colour — the signal has to mean "this has
+ * been sitting here unused", not "this is new".
+ */
+function isStale(action: QuickAction): boolean {
+ const sinceLastUse = daysSince(action.last_used_at);
+ if (sinceLastUse !== null) return sinceLastUse >= UNUSED_DAYS_THRESHOLD;
+ const age = daysSince(action.created_at);
+ return age !== null && age >= UNUSED_DAYS_THRESHOLD;
+}
+
+function daysSince(iso: string | null): number | null {
+ if (!iso) return null;
+ const then = new Date(iso).getTime();
+ if (Number.isNaN(then)) return null;
+ return Math.floor((Date.now() - then) / 86_400_000);
+}
+
+type QuickActionsT = ReturnType<typeof useT<"settings">>["t"];
+
+function VisibilityBadge({ action, t }: { action: QuickAction; t: QuickActionsT }) {
+ // Server-driven enum: an unknown value must land on a generic fallback
+ // rather than rendering nothing (API compatibility rule).
+ switch (action.visibility) {
+ case "public":
+ return (
+ <Badge variant="secondary" className="gap-1 font-normal">
+ <Globe className="size-3" />
+ {t(($) => $.quick_actions.visibility_public)}
+ </Badge>
+ );
+ case "private":
+ return (
+ <Badge variant="outline" className="gap-1 font-normal">
+ <Lock className="size-3" />
+ {t(($) => $.quick_actions.visibility_private)}
+ </Badge>
+ );
+ default:
+ return (
+ <Badge variant="outline" className="font-normal">
+ {action.visibility}
+ </Badge>
+ );
+ }
+}
+
+/**
+ * The bound target plus its CURRENT reachability, as plain metadata.
+ *
+ * This replaces a derived "broken" flag: a `public` action whose agent has
+ * since gone private simply reads wrong here — public badge, "private" target
+ * — without a bespoke error state to maintain. The cost is that nobody is
+ * actively notified; that trade was made deliberately (drift is rare and the
+ * failure is loud at click time, not silent).
+ */
+function TargetLine({ action, t }: { action: QuickAction; t: QuickActionsT }) {
+ if (action.target_missing === true) {
+ return (
+ <span className="inline-flex items-center gap-1 text-destructive">
+ <TriangleAlert className="size-3" />
+ {t(($) => $.quick_actions.target_missing)}
+ </span>
+ );
+ }
+ const mismatched = action.visibility === "public" && action.target_public !== true;
+ return (
+ <span className={cn("inline-flex items-center gap-1", mismatched && "text-warning")}>
+ {mismatched ? <TriangleAlert className="size-3" /> : null}
+ {action.target_name}
+ {action.target_public !== true ? ` · ${t(($) => $.quick_actions.target_private)}` : ""}
+ </span>
+ );
+}
+
+interface FormState {
+ name: string;
+ description: string;
+ assigneeType: QuickActionAssigneeType;
+ assigneeId: string;
+ prompt: string;
+ visibility: QuickActionVisibility;
+}
+
+const EMPTY_FORM: FormState = {
+ name: "",
+ description: "",
+ assigneeType: "agent",
+ assigneeId: "",
+ prompt: "",
+ visibility: "public",
+};
+
+function toFormState(action: QuickAction): FormState {
+ return {
+ name: action.name,
+ description: action.description,
+ assigneeType: action.assignee_type === "squad" ? "squad" : "agent",
+ assigneeId: action.assignee_id,
+ prompt: action.prompt,
+ visibility: action.visibility === "private" ? "private" : "public",
+ };
+}
+
+export function QuickActionsTab() {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const { data: actions = [], isLoading } = useQuery(quickActionListOptions(wsId, true));
+
+ const [query, setQuery] = useState("");
+ const [editing, setEditing] = useState<QuickAction | null>(null);
+ const [creating, setCreating] = useState(false);
+ const [deleteTarget, setDeleteTarget] = useState<QuickAction | null>(null);
+
+ const createMutation = useCreateQuickAction();
+ const updateMutation = useUpdateQuickAction();
+ const deleteMutation = useDeleteQuickAction();
+
+ // Usage-first ordering; never-used rows fall to the bottom where the
+ // "unused" signal is actionable.
+ const sorted = useMemo(
+ () =>
+ [...actions].sort((a, b) => {
+ if (a.status !== b.status) return a.status === "active" ? -1 : 1;
+ if (b.use_count !== a.use_count) return b.use_count - a.use_count;
+ return a.name.localeCompare(b.name);
+ }),
+ [actions],
+ );
+
+ // Name + target search, matching the Labels tab's client-side filter: the
+ // catalog is capped at 30 rows, so there is nothing to gain from a server
+ // round-trip here.
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return sorted;
+ return sorted.filter(
+ (a) =>
+ a.name.toLowerCase().includes(q) ||
+ (a.target_name ?? "").toLowerCase().includes(q),
+ );
+ }, [sorted, query]);
+
+ const handleArchiveToggle = async (action: QuickAction) => {
+ const next = action.status === "active" ? "archived" : "active";
+ try {
+ await updateMutation.mutateAsync({ id: action.id, status: next });
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : String(error));
+ }
+ };
+
+ const handleDelete = async () => {
+ if (!deleteTarget) return;
+ try {
+ await deleteMutation.mutateAsync(deleteTarget.id);
+ setDeleteTarget(null);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : String(error));
+ }
+ };
+
+ return (
+ <SettingsTab
+ title={t(($) => $.quick_actions.title)}
+ description={t(($) => $.quick_actions.description)}
+ >
+ <div className="space-y-5">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="relative w-full sm:max-w-sm">
+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t(($) => $.quick_actions.search_placeholder)}
+ className="pl-9"
+ />
+ </div>
+ <Button className="gap-2" onClick={() => setCreating(true)}>
+ <Plus className="size-4" />
+ {t(($) => $.quick_actions.add)}
+ </Button>
+ </div>
+
+ <div className="overflow-hidden rounded-lg border border-surface-border bg-card">
+ <div className="hidden grid-cols-[minmax(10rem,1fr)_minmax(9rem,1fr)_6rem_5rem_7rem_2rem] gap-4 border-b border-surface-border bg-muted/20 px-4 py-2.5 text-caption font-medium text-muted-foreground md:grid">
+ <span>{t(($) => $.quick_actions.columns.name)}</span>
+ <span>{t(($) => $.quick_actions.columns.target)}</span>
+ <span>{t(($) => $.quick_actions.columns.visibility)}</span>
+ <span>{t(($) => $.quick_actions.columns.usage)}</span>
+ <span>{t(($) => $.quick_actions.columns.updated)}</span>
+ <span />
+ </div>
+
+ {isLoading ? (
+ <div className="px-4 py-12 text-center text-body text-muted-foreground">
+ {t(($) => $.quick_actions.loading)}
+ </div>
+ ) : filtered.length === 0 ? (
+ <div className="px-4 py-12 text-center">
+ <Zap className="mx-auto size-6 text-faint-foreground" />
+ <p className="mt-3 text-body font-medium">
+ {query
+ ? t(($) => $.quick_actions.no_results)
+ : t(($) => $.quick_actions.empty_title)}
+ </p>
+ {!query ? (
+ <p className="mx-auto mt-1 max-w-sm text-caption text-muted-foreground">
+ {t(($) => $.quick_actions.empty_hint)}
+ </p>
+ ) : null}
+ </div>
+ ) : (
+ <div className="divide-y divide-surface-border">
+ {filtered.map((action) => {
+ const stale = isStale(action);
+ return (
+ <div
+ key={action.id}
+ className={cn(
+ "grid gap-2 px-4 py-3 md:grid-cols-[minmax(10rem,1fr)_minmax(9rem,1fr)_6rem_5rem_7rem_2rem] md:items-center md:gap-4",
+ action.status !== "active" && "opacity-60",
+ )}
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <Zap className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate text-body font-medium">{action.name}</span>
+ {action.status !== "active" ? (
+ <Badge variant="outline" className="shrink-0 font-normal">
+ {t(($) => $.quick_actions.archived)}
+ </Badge>
+ ) : null}
+ </div>
+ <div className="min-w-0 truncate text-caption text-muted-foreground md:text-body">
+ <TargetLine action={action} t={t} />
+ </div>
+ <div className="min-w-0">
+ <VisibilityBadge action={action} t={t} />
+ </div>
+ <span
+ className={cn(
+ "text-caption tabular-nums text-muted-foreground md:text-body",
+ stale && "text-warning",
+ )}
+ >
+ {action.use_count === 0
+ ? t(($) => $.quick_actions.never_used)
+ : t(($) => $.quick_actions.used_count, { count: action.use_count })}
+ </span>
+ <span className="text-caption text-muted-foreground">
+ {new Date(action.updated_at).toLocaleDateString()}
+ </span>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.quick_actions.actions_open, { name: action.name })}
+ >
+ <MoreHorizontal className="size-4" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setEditing(action)}>
+ <Pencil className="size-4" />
+ {t(($) => $.quick_actions.edit)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => void handleArchiveToggle(action)}>
+ {action.status === "active" ? (
+ <>
+ <Archive className="size-4" />
+ {t(($) => $.quick_actions.archive)}
+ </>
+ ) : (
+ <>
+ <ArchiveRestore className="size-4" />
+ {t(($) => $.quick_actions.unarchive)}
+ </>
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setDeleteTarget(action)}
+ >
+ <Trash2 className="size-4" />
+ {t(($) => $.quick_actions.delete)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+
+ <QuickActionDialog
+ open={creating || editing !== null}
+ action={editing}
+ onOpenChange={(open) => {
+ if (!open) {
+ setCreating(false);
+ setEditing(null);
+ }
+ }}
+ onSubmit={async (form) => {
+ if (editing) {
+ await updateMutation.mutateAsync({
+ id: editing.id,
+ name: form.name,
+ description: form.description,
+ assignee_type: form.assigneeType,
+ assignee_id: form.assigneeId,
+ prompt: form.prompt,
+ visibility: form.visibility,
+ });
+ } else {
+ await createMutation.mutateAsync({
+ name: form.name,
+ description: form.description,
+ assignee_type: form.assigneeType,
+ assignee_id: form.assigneeId,
+ prompt: form.prompt,
+ visibility: form.visibility,
+ });
+ }
+ }}
+ />
+
+ <AlertDialog open={deleteTarget !== null} onOpenChange={(open) => !open && setDeleteTarget(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.quick_actions.delete_title)}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.quick_actions.delete_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.quick_actions.cancel)}</AlertDialogCancel>
+ <AlertDialogAction onClick={handleDelete}>
+ {t(($) => $.quick_actions.delete)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </SettingsTab>
+ );
+}
+
+function QuickActionDialog({
+ open,
+ action,
+ onOpenChange,
+ onSubmit,
+}: {
+ open: boolean;
+ action: QuickAction | null;
+ onOpenChange: (open: boolean) => void;
+ onSubmit: (form: FormState) => Promise<void>;
+}) {
+ const { t } = useT("settings");
+ const [form, setForm] = useState<FormState>(EMPTY_FORM);
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ if (!open) return;
+ setForm(action ? toFormState(action) : EMPTY_FORM);
+ }, [open, action]);
+
+ // Mirror the server's rejection inline so the author sees it while typing
+ // instead of on submit. The server stays the authority; this is an
+ // affordance.
+ const templateToken = useMemo(() => findQuickActionTemplateToken(form.prompt), [form.prompt]);
+
+ const canSave =
+ form.name.trim().length > 0 &&
+ form.prompt.trim().length > 0 &&
+ form.assigneeId.length > 0 &&
+ templateToken === null;
+
+ const handleSubmit = async () => {
+ if (!canSave) return;
+ setSaving(true);
+ try {
+ await onSubmit(form);
+ onOpenChange(false);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : String(error));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ {action ? t(($) => $.quick_actions.edit_title) : t(($) => $.quick_actions.create_title)}
+ </DialogTitle>
+ <DialogDescription>{t(($) => $.quick_actions.dialog_description)}</DialogDescription>
+ </DialogHeader>
+
+ {/* space-y-5 against space-y-1.5 inside each group: the gap BETWEEN
+ fields has to clearly beat the gap between a label and its own
+ control, or the four groups read as one continuous block of text. */}
+ <div className="space-y-5">
+ <div className="space-y-1.5">
+ <FieldLabel htmlFor="qa-name">{t(($) => $.quick_actions.field_name)}</FieldLabel>
+ <Input
+ id="qa-name"
+ value={form.name}
+ maxLength={32}
+ placeholder={t(($) => $.quick_actions.field_name_placeholder)}
+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
+ />
+ </div>
+
+ {/* Visibility first: it is the one choice that constrains the rest
+ (a public action may only bind a publicly-invocable target), so
+ asking it up front avoids a rejected Save. */}
+ <div className="space-y-1.5">
+ <FieldLabel>{t(($) => $.quick_actions.field_visibility)}</FieldLabel>
+ <div className="grid grid-cols-2 gap-2">
+ {(["public", "private"] as const).map((option) => (
+ <button
+ key={option}
+ type="button"
+ aria-pressed={form.visibility === option}
+ onClick={() => setForm((f) => ({ ...f, visibility: option }))}
+ className={cn(
+ "flex items-start gap-2 rounded-lg border px-3 py-2 text-left transition-colors",
+ form.visibility === option
+ ? "border-primary bg-accent/50"
+ : "border-surface-border hover:bg-accent/30",
+ )}
+ >
+ {option === "public" ? (
+ <Globe className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ ) : (
+ <Lock className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ )}
+ <span className="min-w-0">
+ <span className="block text-body font-medium">
+ {option === "public"
+ ? t(($) => $.quick_actions.visibility_public)
+ : t(($) => $.quick_actions.visibility_private)}
+ </span>
+ <span className="mt-0.5 block text-caption text-muted-foreground">
+ {option === "public"
+ ? t(($) => $.quick_actions.visibility_public_hint)
+ : t(($) => $.quick_actions.visibility_private_hint)}
+ </span>
+ </span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="space-y-1.5">
+ <FieldLabel>{t(($) => $.quick_actions.field_target)}</FieldLabel>
+ <AgentPicker
+ assignee={form.assigneeId ? { type: form.assigneeType, id: form.assigneeId } : null}
+ onChange={(next) =>
+ setForm((f) => ({ ...f, assigneeType: next.type, assigneeId: next.id }))
+ }
+ />
+ {/* Public promises "everyone can run this", so the server refuses a
+ target the team cannot invoke. Saying so here turns a 400 into
+ an expectation set before the user hits Save. */}
+ {form.visibility === "public" ? (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.quick_actions.public_target_hint)}
+ </p>
+ ) : null}
+ </div>
+
+ <div className="space-y-1.5">
+ <FieldLabel htmlFor="qa-prompt">{t(($) => $.quick_actions.field_prompt)}</FieldLabel>
+ <Textarea
+ id="qa-prompt"
+ value={form.prompt}
+ rows={5}
+ placeholder={t(($) => $.quick_actions.field_prompt_placeholder)}
+ onChange={(e) => setForm((f) => ({ ...f, prompt: e.target.value }))}
+ />
+ {templateToken !== null ? (
+ <p className="text-caption text-destructive">
+ {t(($) => $.quick_actions.template_not_supported, { token: templateToken })}
+ </p>
+ ) : (
+ <p className="inline-flex items-center gap-1 text-caption text-muted-foreground">
+ <Info className="size-3" />
+ {t(($) => $.quick_actions.prompt_hint)}
+ </p>
+ )}
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ {t(($) => $.quick_actions.cancel)}
+ </Button>
+ <Button onClick={handleSubmit} disabled={!canSave || saving}>
+ {t(($) => $.quick_actions.save)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index daa83f5c40..1fa9020fc0 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -15,6 +15,7 @@ import {
Tags,
Keyboard,
ListTodo,
+ Zap,
} from "lucide-react";
import { GitHubMark } from "./github-mark";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";
@@ -35,6 +36,7 @@ import { LabsTab } from "./labs-tab";
import { NotificationsTab } from "./notifications-tab";
import { LabelsTab } from "./labels-tab";
import { PropertiesTab } from "./properties-tab";
+import { QuickActionsTab } from "./quick-actions-tab";
import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";
import { useT } from "../../i18n";
@@ -58,6 +60,7 @@ const WORKSPACE_TAB_KEYS = [
"members",
"labels",
"properties",
+ "quick_actions",
] as const;
const WORKSPACE_TAB_VALUES = {
general: "workspace",
@@ -68,6 +71,7 @@ const WORKSPACE_TAB_VALUES = {
members: "members",
labels: "labels",
properties: "properties",
+ quick_actions: "quick-actions",
} as const;
const WORKSPACE_TAB_ICONS = {
general: Settings,
@@ -78,6 +82,7 @@ const WORKSPACE_TAB_ICONS = {
members: Users,
labels: Tags,
properties: SlidersHorizontal,
+ quick_actions: Zap,
} as const;
const DEFAULT_TAB = "profile";
@@ -207,7 +212,9 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
{/* Right content */}
<div className="min-w-0 flex-1 md:overflow-y-auto">
- <div className={`mx-auto w-full p-4 sm:p-6 md:p-8 ${activeTab === "labels" || activeTab === "properties" ? "max-w-5xl" : "max-w-3xl"}`}>
+ <div className={`mx-auto w-full p-4 sm:p-6 md:p-8 ${activeTab === "labels" || activeTab === "properties" || activeTab === "quick-actions"
+ ? "max-w-5xl"
+ : "max-w-3xl"}`}>
<TabsContent value="profile"><AccountTab /></TabsContent>
<TabsContent value="preferences"><PreferencesTab /></TabsContent>
<TabsContent value="shortcuts"><KeyboardShortcutsTab /></TabsContent>
@@ -223,6 +230,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
<TabsContent value="members"><MembersTab /></TabsContent>
<TabsContent value="labels"><LabelsTab /></TabsContent>
<TabsContent value="properties"><PropertiesTab /></TabsContent>
+ <TabsContent value="quick-actions"><QuickActionsTab /></TabsContent>
{extraAccountTabs?.map((tab) => (
<TabsContent key={tab.value} value={tab.value}>{tab.content}</TabsContent>
))}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 8408b22a83..375bb80a5c 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1136,6 +1136,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/active-task", h.GetActiveTaskForIssue)
r.Post("/tasks/{taskId}/cancel", h.CancelTask)
r.Post("/rerun", h.RerunIssue)
+ r.Post("/quick-actions/{quickActionId}/run", h.RunQuickAction)
+ r.Post("/quick-actions/{quickActionId}/render", h.RenderQuickAction)
r.Get("/task-runs", h.ListTasksByIssue)
r.Get("/usage", h.GetIssueUsage)
r.Post("/reactions", h.AddIssueReaction)
@@ -1157,6 +1159,17 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Task messages (user-facing, not daemon auth)
r.Get("/api/tasks/{taskId}/messages", h.ListTaskMessagesByUser)
+ // Issue quick actions (definitions; running one lives under
+ // /api/issues/{id}/quick-actions/{quickActionId}/run)
+ r.Route("/api/quick-actions", func(r chi.Router) {
+ r.Get("/", h.ListQuickActions)
+ r.Post("/", h.CreateQuickAction)
+ r.Route("/{id}", func(r chi.Router) {
+ r.Patch("/", h.UpdateQuickAction)
+ r.Delete("/", h.DeleteQuickAction)
+ })
+ })
+
// Custom issue properties (definitions; values live under /api/issues/{id}/properties)
r.Route("/api/properties", func(r chi.Router) {
r.Get("/", h.ListProperties)
diff --git a/server/internal/handler/activity.go b/server/internal/handler/activity.go
index 2f3c2d38cb..7cbd86e0ee 100644
--- a/server/internal/handler/activity.go
+++ b/server/internal/handler/activity.go
@@ -25,10 +25,13 @@ type TimelineEntry struct {
Details json.RawMessage `json:"details,omitempty"`
// Comment-only fields
- Content *string `json:"content,omitempty"`
- ParentID *string `json:"parent_id,omitempty"`
- UpdatedAt *string `json:"updated_at,omitempty"`
- CommentType *string `json:"comment_type,omitempty"`
+ Content *string `json:"content,omitempty"`
+ ParentID *string `json:"parent_id,omitempty"`
+ UpdatedAt *string `json:"updated_at,omitempty"`
+ CommentType *string `json:"comment_type,omitempty"`
+ // Set only on comments produced by a quick action run. Unforgeable: there
+ // is no request field for it on the generic comment endpoint.
+ QuickActionID *string `json:"quick_action_id,omitempty"`
Reactions []ReactionResponse `json:"reactions,omitempty"`
Attachments []AttachmentResponse `json:"attachments,omitempty"`
ResolvedAt *string `json:"resolved_at,omitempty"`
@@ -181,6 +184,7 @@ func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []Ti
ActorID: uuidToString(c.AuthorID),
Content: &content,
CommentType: &commentType,
+ QuickActionID: uuidToPtr(c.QuickActionID),
ParentID: uuidToPtr(c.ParentID),
CreatedAt: timestampToString(c.CreatedAt),
UpdatedAt: &updatedAt,
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 8c04355cce..cb8d53d6d1 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -22,21 +22,27 @@ import (
)
type CommentResponse struct {
- ID string `json:"id"`
- IssueID string `json:"issue_id"`
- AuthorType string `json:"author_type"`
- AuthorID string `json:"author_id"`
- Content string `json:"content"`
- Type string `json:"type"`
- ParentID *string `json:"parent_id"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
- ResolvedAt *string `json:"resolved_at"`
- ResolvedByType *string `json:"resolved_by_type"`
- ResolvedByID *string `json:"resolved_by_id"`
- SourceTaskID *string `json:"source_task_id,omitempty"`
- Reactions []ReactionResponse `json:"reactions"`
- Attachments []AttachmentResponse `json:"attachments"`
+ ID string `json:"id"`
+ IssueID string `json:"issue_id"`
+ AuthorType string `json:"author_type"`
+ AuthorID string `json:"author_id"`
+ Content string `json:"content"`
+ Type string `json:"type"`
+ ParentID *string `json:"parent_id"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+ ResolvedAt *string `json:"resolved_at"`
+ ResolvedByType *string `json:"resolved_by_type"`
+ ResolvedByID *string `json:"resolved_by_id"`
+ SourceTaskID *string `json:"source_task_id,omitempty"`
+ // QuickActionID marks a comment produced by a quick action run (MUL-5465).
+ // The timeline renders those as a collapsed one-line card instead of the
+ // raw prompt body. It is NOT settable through this endpoint — there is no
+ // request field for it — which is exactly why the card keys off this id
+ // rather than a `type` value the client controls.
+ QuickActionID *string `json:"quick_action_id,omitempty"`
+ Reactions []ReactionResponse `json:"reactions"`
+ Attachments []AttachmentResponse `json:"attachments"`
// Orientation stats — populated only on the roots_only path and omitted in
// every other mode, so the default response shape stays byte-identical for
// existing callers. ReplyCount is the number of descendants in the thread;
@@ -101,6 +107,7 @@ func commentToResponse(c db.Comment, reactions []ReactionResponse, attachments [
ResolvedByType: textToPtr(c.ResolvedByType),
ResolvedByID: uuidToPtr(c.ResolvedByID),
SourceTaskID: uuidToPtr(c.SourceTaskID),
+ QuickActionID: uuidToPtr(c.QuickActionID),
Reactions: reactions,
Attachments: attachments,
}
@@ -1276,6 +1283,16 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
if req.Type == "" {
req.Type = "comment"
}
+ // Validate rather than letting the DB CHECK reject it: an unknown type
+ // previously surfaced as a 500 on a constraint violation, which reads as a
+ // server fault for what is plainly bad input. This is also the explicit
+ // refusal of a client trying to author a machine-written kind (MUL-5465
+ // review): a member must not be able to post a comment that renders as
+ // something the system generated.
+ if !isClientAuthorableCommentType(req.Type) {
+ writeError(w, http.StatusBadRequest, "invalid comment type")
+ return
+ }
var parentID pgtype.UUID
var parentComment *db.Comment
@@ -1438,6 +1455,19 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, resp)
}
+// clientAuthorableCommentTypes is what POST /comments accepts. `status_change`
+// and `system` are platform-generated narration, so a client claiming them
+// would be forging system output; they are deliberately absent.
+var clientAuthorableCommentTypes = map[string]struct{}{
+ "comment": {},
+ "progress_update": {},
+}
+
+func isClientAuthorableCommentType(t string) bool {
+ _, ok := clientAuthorableCommentTypes[t]
+ return ok
+}
+
// noteCommentPrefix marks a comment as a human-only note. A comment whose first
// whitespace-delimited token is this prefix (case-insensitive) is stored like
// any other comment but never triggers an agent.
diff --git a/server/internal/handler/quick_action.go b/server/internal/handler/quick_action.go
new file mode 100644
index 0000000000..45e7f6bab9
--- /dev/null
+++ b/server/internal/handler/quick_action.go
@@ -0,0 +1,931 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "regexp"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/logger"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Issue Quick Actions (MUL-5465): workspace-level presets for "who to call and
+// what to say" on an existing issue.
+//
+// Contract highlights:
+// - Running one is NOT a new dispatch path. It renders the prompt, posts an
+// ordinary comment carrying the target's mention markup (marked with
+// quick_action_id), and hands off to triggerTasksForComment. Permission, attribution, squad routing,
+// the execution log, and pending-task coalescing are inherited from the
+// comment path rather than reimplemented — the MUL-3375 lesson about four
+// drifting copies of one trigger decision.
+// - PERMISSION IS CHECKED IN EXACTLY ONE PLACE: RunQuickAction. The list
+// endpoint does no permission work and hides nothing beyond `private`
+// ownership. Filtering the sidebar by invoke permission was tried and
+// removed: it made two people looking at one issue see different sidebars
+// with no explanation, which is harder to debug than a button that says
+// why it refused.
+// - `visibility` is the author's stated intent, not an authorization
+// decision. A `public` action must bind a target every member can invoke,
+// so it is runnable by construction; the run-time gate still has the final
+// say, so a target that goes private later fails loudly at click time
+// rather than silently granting anything.
+// - The prompt is sent VERBATIM. There is no interpolation and no runtime
+// input: every variable considered ({{issue.title}}, {{issue.identifier}},
+// {{issue.url}}, {{user.name}}, {{date}}) named something the agent
+// already has from the issue context and the comment's own author, and the
+// `/` slash command covers "same action, one detail different" by dropping
+// the rendered body into the composer to edit. Write-time validation still
+// REJECTS any `{{...}}` so a habitual template token cannot land literally
+// in an agent's instructions.
+const (
+ maxActiveQuickActionsPerWorkspace = 30
+ maxQuickActionNameLen = 32
+ maxQuickActionDescriptionLen = 200
+ maxQuickActionPromptLen = 4000
+)
+
+// quickActionTemplateTokenRe catches any `{{...}}` in a prompt.
+//
+// Templating is deliberately unsupported, but silence is not the same as
+// safety: someone carrying the habit over from autopilot's issue-title
+// template would otherwise have `{{issue.title}}` rendered literally into an
+// agent's instructions and never notice. Rejecting at write time is a fraction
+// of the cost of the interpolation engine it replaces, and it keeps the door
+// open to enabling variables later without touching stored data.
+var quickActionTemplateTokenRe = regexp.MustCompile(`\{\{[^}]*\}\}`)
+
+// quickActionSideEffectMentionRe catches mention markup that reaches somebody.
+//
+// The prompt is appended verbatim to a comment that then runs through the
+// normal mention pipeline, so a mention inside it acts on every click:
+//
+// - agent / squad / all -> enqueues a SECOND target beside the configured
+// one, breaking the invariant the permission model rests on (a public
+// action runs exactly the target it was validated against). The sidebar
+// reports only the first outcome, so the extra run is invisible.
+// - member -> notification_listeners.go adds them to the mention recipients
+// and creates an inbox item, so a saved prompt pings that person on every
+// single click. This one was initially allowed on the reasoning that it
+// "only renders a link"; that was wrong.
+//
+// `mention://issue/...` is the sole exception: it renders as a link and
+// reaches nobody, so a prompt may legitimately point at related work.
+var quickActionSideEffectMentionRe = regexp.MustCompile(`mention://(agent|squad|member|all)/`)
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+type QuickActionResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ AssigneeType string `json:"assignee_type"`
+ AssigneeID string `json:"assignee_id"`
+ Prompt string `json:"prompt"`
+ Visibility string `json:"visibility"`
+ Status string `json:"status"`
+ LastUsedAt *string `json:"last_used_at"`
+ UseCount int64 `json:"use_count"`
+ CreatedByID string `json:"created_by_id"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+
+ // Target identity, for display. Always populated when the target resolves:
+ // a `public` action binds a publicly-invocable agent whose name everyone
+ // can already see, and a `private` action is only ever returned to its
+ // creator — so there is nothing left to redact.
+ TargetName string `json:"target_name,omitempty"`
+ // TargetPublic reports whether the bound target is currently invocable by
+ // every workspace member. Plain metadata, not a verdict: settings renders
+ // it beside the binding so a `public` action pointing at a now-private
+ // agent is visibly wrong without a bespoke "broken" state.
+ TargetPublic bool `json:"target_public"`
+ // TargetMissing marks an archived or deleted target.
+ TargetMissing bool `json:"target_missing"`
+}
+
+type CreateQuickActionRequest struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ AssigneeType string `json:"assignee_type"`
+ AssigneeID string `json:"assignee_id"`
+ Prompt string `json:"prompt"`
+ Visibility string `json:"visibility"`
+}
+
+type UpdateQuickActionRequest struct {
+ Name *string `json:"name"`
+ Description *string `json:"description"`
+ AssigneeType *string `json:"assignee_type"`
+ AssigneeID *string `json:"assignee_id"`
+ Prompt *string `json:"prompt"`
+ Visibility *string `json:"visibility"`
+ Status *string `json:"status"`
+}
+
+type ListQuickActionsResponse struct {
+ QuickActions []QuickActionResponse `json:"quick_actions"`
+}
+
+// ---------------------------------------------------------------------------
+// Validation
+// ---------------------------------------------------------------------------
+
+func validateQuickActionName(raw string) (string, error) {
+ name := strings.TrimSpace(raw)
+ if name == "" {
+ return "", fmt.Errorf("name is required")
+ }
+ if utf8.RuneCountInString(name) > maxQuickActionNameLen {
+ return "", fmt.Errorf("name must be at most %d characters", maxQuickActionNameLen)
+ }
+ return name, nil
+}
+
+// validateQuickActionPrompt trims, bounds, and refuses template syntax. See
+// quickActionTemplateTokenRe for why the rejection outlives the feature.
+func validateQuickActionPrompt(raw string) (string, error) {
+ prompt := strings.TrimSpace(raw)
+ if prompt == "" {
+ return "", fmt.Errorf("prompt is required")
+ }
+ if utf8.RuneCountInString(prompt) > maxQuickActionPromptLen {
+ return "", fmt.Errorf("prompt must be at most %d characters", maxQuickActionPromptLen)
+ }
+ if token := quickActionTemplateTokenRe.FindString(prompt); token != "" {
+ return "", fmt.Errorf("template variables are not supported yet; remove %s — the agent already reads this issue", token)
+ }
+ if quickActionSideEffectMentionRe.MatchString(prompt) {
+ return "", fmt.Errorf("the prompt cannot @mention an agent, squad, or person; a quick action reaches exactly the one target it is bound to (an issue link is fine)")
+ }
+ return prompt, nil
+}
+
+func validateQuickActionAssignee(assigneeType, assigneeID string) error {
+ if assigneeType != "agent" && assigneeType != "squad" {
+ return fmt.Errorf("assignee_type must be \"agent\" or \"squad\"")
+ }
+ if strings.TrimSpace(assigneeID) == "" {
+ return fmt.Errorf("assignee_id is required")
+ }
+ return nil
+}
+
+func normalizeQuickActionVisibility(raw string) (string, error) {
+ v := strings.TrimSpace(raw)
+ if v == "" {
+ return "public", nil
+ }
+ if v != "public" && v != "private" {
+ return "", fmt.Errorf("visibility must be \"public\" or \"private\"")
+ }
+ return v, nil
+}
+
+// ---------------------------------------------------------------------------
+// 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.
+func (h *Handler) resolveQuickActionTarget(ctx context.Context, qa db.QuickAction) quickActionTarget {
+ switch qa.AssigneeType {
+ case "squad":
+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: qa.AssigneeID,
+ WorkspaceID: qa.WorkspaceID,
+ })
+ if err != nil || squad.ArchivedAt.Valid {
+ return quickActionTarget{}
+ }
+ leader, err := h.Queries.GetAgent(ctx, squad.LeaderID)
+ if err != nil || leader.ArchivedAt.Valid {
+ return quickActionTarget{}
+ }
+ avatar := ""
+ if squad.AvatarUrl.Valid {
+ avatar = squad.AvatarUrl.String
+ }
+ return quickActionTarget{
+ Agent: leader,
+ Name: squad.Name,
+ AvatarURL: avatar,
+ MentionType: "squad",
+ MentionID: uuidToString(squad.ID),
+ Found: true,
+ }
+ default:
+ agent, err := h.Queries.GetAgent(ctx, qa.AssigneeID)
+ if err != nil || agent.ArchivedAt.Valid || uuidToString(agent.WorkspaceID) != uuidToString(qa.WorkspaceID) {
+ return quickActionTarget{}
+ }
+ avatar := ""
+ if agent.AvatarUrl.Valid {
+ avatar = agent.AvatarUrl.String
+ }
+ return quickActionTarget{
+ Agent: agent,
+ Name: agent.Name,
+ AvatarURL: avatar,
+ MentionType: "agent",
+ MentionID: uuidToString(agent.ID),
+ Found: true,
+ }
+ }
+}
+
+// agentInvocableByEveryone reports whether every workspace member may invoke
+// this agent — `public_to` carrying a `workspace` target.
+//
+// A `public_to` agent whose allow-list names specific members does NOT count:
+// binding one to a public quick action would make the "everyone" promise false
+// for the members left out. Fails closed on a lookup error.
+func (h *Handler) agentInvocableByEveryone(ctx context.Context, agent db.Agent) bool {
+ if agent.PermissionMode != "public_to" {
+ return false
+ }
+ targets, err := h.Queries.ListAgentInvocationTargets(ctx, agent.ID)
+ if err != nil {
+ return false
+ }
+ for _, t := range targets {
+ if t.TargetType == "workspace" {
+ return true
+ }
+ }
+ return false
+}
+
+// quickActionCatalog is a batched resolver for the list endpoint.
+//
+// The single-row path issues a GetAgent (plus GetSquad) AND a
+// ListAgentInvocationTargets per action. At the 30-action cap that is 60-90
+// sequential round-trips on every sidebar and settings load. This loads the
+// workspace's agents, squads, and invocation targets in THREE queries and
+// answers from memory. Workspaces are small-team scale, so listing all agents
+// costs less than thirty point lookups.
+type quickActionCatalog struct {
+ agents map[string]db.Agent
+ squads map[string]db.Squad
+ // publicAgents holds agent ids every workspace member may invoke.
+ publicAgents map[string]bool
+}
+
+func (h *Handler) loadQuickActionCatalog(ctx context.Context, workspaceID pgtype.UUID) quickActionCatalog {
+ cat := quickActionCatalog{
+ agents: map[string]db.Agent{},
+ squads: map[string]db.Squad{},
+ publicAgents: map[string]bool{},
+ }
+
+ agents, err := h.Queries.ListAgents(ctx, workspaceID)
+ if err != nil {
+ // Degrade to "target unresolved" rather than failing the whole list:
+ // the catalog is display metadata, and the run path re-checks
+ // everything that matters anyway.
+ return cat
+ }
+ agentIDs := make([]pgtype.UUID, 0, len(agents))
+ for _, a := range agents {
+ cat.agents[uuidToString(a.ID)] = a
+ agentIDs = append(agentIDs, a.ID)
+ }
+
+ if squads, err := h.Queries.ListSquads(ctx, workspaceID); err == nil {
+ for _, sq := range squads {
+ cat.squads[uuidToString(sq.ID)] = sq
+ }
+ }
+
+ if len(agentIDs) > 0 {
+ targets, err := h.Queries.ListAgentInvocationTargetsByAgentIDs(ctx, agentIDs)
+ if err == nil {
+ for _, t := range targets {
+ if t.TargetType == "workspace" {
+ cat.publicAgents[uuidToString(t.AgentID)] = true
+ }
+ }
+ }
+ }
+ return cat
+}
+
+// resolve mirrors resolveQuickActionTarget + agentInvocableByEveryone, but
+// entirely from the pre-loaded maps. The two must agree; the shared shape of
+// quickActionTarget is what keeps them honest.
+func (c quickActionCatalog) resolve(qa db.QuickAction) (quickActionTarget, bool) {
+ if qa.AssigneeType == "squad" {
+ squad, ok := c.squads[uuidToString(qa.AssigneeID)]
+ if !ok || squad.ArchivedAt.Valid {
+ return quickActionTarget{}, false
+ }
+ leader, ok := c.agents[uuidToString(squad.LeaderID)]
+ if !ok {
+ return quickActionTarget{}, false
+ }
+ name := squad.Name
+ return quickActionTarget{Agent: leader, Name: name, Found: true},
+ c.publicAgents[uuidToString(leader.ID)] && leader.PermissionMode == "public_to"
+ }
+ agent, ok := c.agents[uuidToString(qa.AssigneeID)]
+ if !ok {
+ return quickActionTarget{}, false
+ }
+ return quickActionTarget{Agent: agent, Name: agent.Name, Found: true},
+ c.publicAgents[uuidToString(agent.ID)] && agent.PermissionMode == "public_to"
+}
+
+// quickActionToResponseFrom builds a row's response off the batched catalog.
+func quickActionToResponseFrom(qa db.QuickAction, cat quickActionCatalog) QuickActionResponse {
+ resp := baseQuickActionResponse(qa)
+ target, targetPublic := cat.resolve(qa)
+ resp.TargetMissing = !target.Found
+ if target.Found {
+ resp.TargetName = target.Name
+ resp.TargetPublic = targetPublic
+ }
+ return resp
+}
+
+// baseQuickActionResponse maps the stored columns. Target metadata is layered
+// on by whichever resolver the caller used.
+func baseQuickActionResponse(qa db.QuickAction) QuickActionResponse {
+ return QuickActionResponse{
+ ID: uuidToString(qa.ID),
+ WorkspaceID: uuidToString(qa.WorkspaceID),
+ Name: qa.Name,
+ Description: qa.Description,
+ AssigneeType: qa.AssigneeType,
+ AssigneeID: uuidToString(qa.AssigneeID),
+ Prompt: qa.Prompt,
+ Visibility: qa.Visibility,
+ Status: qa.Status,
+ LastUsedAt: timestampToPtr(qa.LastUsedAt),
+ UseCount: qa.UseCount,
+ CreatedByID: uuidToString(qa.CreatedByID),
+ CreatedAt: timestampToString(qa.CreatedAt),
+ UpdatedAt: timestampToString(qa.UpdatedAt),
+ }
+}
+
+// quickActionToResponse is the single-row path, used by create/update where
+// exactly one action is being returned and a batch would be pointless. The
+// list endpoint uses quickActionToResponseFrom instead.
+func (h *Handler) quickActionToResponse(ctx context.Context, qa db.QuickAction) QuickActionResponse {
+ resp := baseQuickActionResponse(qa)
+ target := h.resolveQuickActionTarget(ctx, qa)
+ resp.TargetMissing = !target.Found
+ if target.Found {
+ resp.TargetName = target.Name
+ resp.TargetPublic = h.agentInvocableByEveryone(ctx, target.Agent)
+ }
+ return resp
+}
+
+// ---------------------------------------------------------------------------
+// Management gate
+// ---------------------------------------------------------------------------
+
+// requireQuickActionActor resolves the acting member. Agents are rejected: an
+// agent inherits its runtime owner's credentials, and without this an admin's
+// agent could mass-produce actions that then appear in everyone's sidebar.
+//
+// The role check is deliberately NOT here — it depends on the visibility being
+// written. A `public` action is workspace furniture and needs owner/admin; a
+// `private` one is personal and any member may create it.
+func (h *Handler) requireQuickActionActor(w http.ResponseWriter, r *http.Request) (workspaceID, userID string, ok bool) {
+ workspaceID = h.resolveWorkspaceID(r)
+ userID, ok = requireUserID(w, r)
+ if !ok {
+ return "", "", false
+ }
+ if actorType, _ := h.resolveActor(r, userID, workspaceID); actorType == "agent" {
+ writeError(w, http.StatusForbidden, "agents cannot manage quick actions")
+ return "", "", false
+ }
+ if _, memberOK := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found"); !memberOK {
+ return "", "", false
+ }
+ return workspaceID, userID, true
+}
+
+// loadReachableQuickAction fetches an action and enforces the ONE rule that
+// governs who may touch a private one: it belongs to its creator and nobody
+// else, whatever they know its id.
+//
+// This exists because the check used to be inline and only in RunQuickAction.
+// Update and Render reached rows by (id, workspace) alone, so any member who
+// learned a UUID — an action-created comment carries one — could rewrite or
+// read back another member's private prompt. Centralizing it means a new
+// endpoint cannot forget the rule by omission.
+//
+// A private action the caller does not own reports 404, not 403: whether a
+// given UUID exists is itself not the caller's business.
+func (h *Handler) loadReachableQuickAction(
+ w http.ResponseWriter,
+ r *http.Request,
+ id, workspaceID pgtype.UUID,
+ userID string,
+) (db.QuickAction, bool) {
+ qa, err := h.Queries.GetQuickAction(r.Context(), db.GetQuickActionParams{ID: id, WorkspaceID: workspaceID})
+ if err != nil {
+ writeError(w, http.StatusNotFound, "quick action not found")
+ return db.QuickAction{}, false
+ }
+ if qa.Visibility == "private" && uuidToString(qa.CreatedByID) != userID {
+ writeError(w, http.StatusNotFound, "quick action not found")
+ return db.QuickAction{}, false
+ }
+ return qa, true
+}
+
+// requirePublicQuickActionRole gates writes that leave an action `public`.
+// Returns false having already written the error response.
+func (h *Handler) requirePublicQuickActionRole(w http.ResponseWriter, r *http.Request, workspaceID string) bool {
+ _, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")
+ return ok
+}
+
+// ---------------------------------------------------------------------------
+// Handlers
+// ---------------------------------------------------------------------------
+
+// ListQuickActions returns the workspace catalog. It performs NO permission
+// work: `private` rows are scoped to their creator by the query (that is what
+// the field means, not a permission check), and every other row is returned to
+// everyone. Whether the caller may RUN one is answered by RunQuickAction.
+func (h *Handler) ListQuickActions(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ viewerUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+
+ includeArchived := r.URL.Query().Get("include_archived") == "true"
+ rows, err := h.Queries.ListQuickActions(r.Context(), db.ListQuickActionsParams{
+ WorkspaceID: wsUUID,
+ IncludeArchived: includeArchived,
+ ViewerID: viewerUUID,
+ })
+ if err != nil {
+ slog.Warn("list quick actions failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to list quick actions")
+ return
+ }
+
+ catalog := h.loadQuickActionCatalog(r.Context(), wsUUID)
+ out := make([]QuickActionResponse, 0, len(rows))
+ for _, qa := range rows {
+ out = append(out, quickActionToResponseFrom(qa, catalog))
+ }
+ writeJSON(w, http.StatusOK, ListQuickActionsResponse{QuickActions: out})
+}
+
+func (h *Handler) CreateQuickAction(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireQuickActionActor(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+
+ var req CreateQuickActionRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ visibility, err := normalizeQuickActionVisibility(req.Visibility)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ if visibility == "public" && !h.requirePublicQuickActionRole(w, r, workspaceID) {
+ return
+ }
+ name, err := validateQuickActionName(req.Name)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ if err := validateQuickActionAssignee(req.AssigneeType, req.AssigneeID); err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ assigneeUUID, ok := parseUUIDOrBadRequest(w, req.AssigneeID, "assignee_id")
+ if !ok {
+ return
+ }
+ prompt, err := validateQuickActionPrompt(req.Prompt)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ description, ok := trimmedWithinLimit(w, req.Description, maxQuickActionDescriptionLen, "description")
+ if !ok {
+ return
+ }
+ if !h.validateQuickActionBinding(w, r, req.AssigneeType, assigneeUUID, wsUUID, visibility) {
+ return
+ }
+
+ count, err := h.Queries.CountActiveQuickActions(r.Context(), wsUUID)
+ if err == nil && count >= maxActiveQuickActionsPerWorkspace {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("a workspace can have at most %d active quick actions; archive one first", maxActiveQuickActionsPerWorkspace))
+ return
+ }
+
+ qa, err := h.Queries.CreateQuickAction(r.Context(), db.CreateQuickActionParams{
+ WorkspaceID: wsUUID,
+ Name: name,
+ Description: description,
+ AssigneeType: req.AssigneeType,
+ AssigneeID: assigneeUUID,
+ Prompt: prompt,
+ Visibility: visibility,
+ CreatedByType: "member",
+ CreatedByID: parseUUID(userID),
+ })
+ if err != nil {
+ slog.Warn("create quick action failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to create quick action")
+ return
+ }
+ writeJSON(w, http.StatusCreated, h.quickActionToResponse(r.Context(), qa))
+}
+
+func (h *Handler) UpdateQuickAction(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireQuickActionActor(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "quick action id")
+ if !ok {
+ return
+ }
+ existing, ok := h.loadReachableQuickAction(w, r, idUUID, wsUUID, userID)
+ if !ok {
+ return
+ }
+
+ var req UpdateQuickActionRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+
+ // The resulting visibility decides the role needed, so resolve it first.
+ // Editing an already-public action also requires the role, otherwise a
+ // member could rewrite the prompt behind a workspace-wide button.
+ visibility := existing.Visibility
+ if req.Visibility != nil {
+ normalized, err := normalizeQuickActionVisibility(*req.Visibility)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ visibility = normalized
+ }
+ if (visibility == "public" || existing.Visibility == "public") && !h.requirePublicQuickActionRole(w, r, workspaceID) {
+ return
+ }
+
+ params := db.UpdateQuickActionParams{ID: idUUID, WorkspaceID: wsUUID}
+ if req.Visibility != nil {
+ params.Visibility = pgtype.Text{String: visibility, Valid: true}
+ }
+
+ if req.Name != nil {
+ name, err := validateQuickActionName(*req.Name)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ params.Name = pgtype.Text{String: name, Valid: true}
+ }
+ if req.Description != nil {
+ description, ok := trimmedWithinLimit(w, *req.Description, maxQuickActionDescriptionLen, "description")
+ if !ok {
+ return
+ }
+ params.Description = pgtype.Text{String: description, Valid: true}
+ }
+
+ // assignee_type and assignee_id move together so a type swap can never
+ // land with a mismatched id (the same rule autopilot enforces). The
+ // binding is re-validated against the RESULTING visibility, so flipping an
+ // action to public with a private agent still bound is caught here.
+ newType := existing.AssigneeType
+ newID := uuidToString(existing.AssigneeID)
+ if req.AssigneeType != nil {
+ newType = *req.AssigneeType
+ }
+ if req.AssigneeID != nil {
+ newID = *req.AssigneeID
+ }
+ if err := validateQuickActionAssignee(newType, newID); err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ newUUID, ok := parseUUIDOrBadRequest(w, newID, "assignee_id")
+ if !ok {
+ return
+ }
+ if req.AssigneeType != nil || req.AssigneeID != nil {
+ params.AssigneeType = pgtype.Text{String: newType, Valid: true}
+ params.AssigneeID = newUUID
+ }
+ if !h.validateQuickActionBinding(w, r, newType, newUUID, wsUUID, visibility) {
+ return
+ }
+
+ if req.Prompt != nil {
+ prompt, err := validateQuickActionPrompt(*req.Prompt)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ params.Prompt = pgtype.Text{String: prompt, Valid: true}
+ }
+ if req.Status != nil {
+ if *req.Status != "active" && *req.Status != "archived" {
+ writeError(w, http.StatusBadRequest, "status must be \"active\" or \"archived\"")
+ return
+ }
+ if *req.Status == "active" && existing.Status != "active" {
+ count, err := h.Queries.CountActiveQuickActions(r.Context(), wsUUID)
+ if err == nil && count >= maxActiveQuickActionsPerWorkspace {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("a workspace can have at most %d active quick actions", maxActiveQuickActionsPerWorkspace))
+ return
+ }
+ }
+ params.Status = pgtype.Text{String: *req.Status, Valid: true}
+ }
+
+ qa, err := h.Queries.UpdateQuickAction(r.Context(), params)
+ if err != nil {
+ slog.Warn("update quick action failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to update quick action")
+ return
+ }
+ writeJSON(w, http.StatusOK, h.quickActionToResponse(r.Context(), qa))
+}
+
+func (h *Handler) DeleteQuickAction(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireQuickActionActor(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "quick action id")
+ if !ok {
+ return
+ }
+ existing, ok := h.loadReachableQuickAction(w, r, idUUID, wsUUID, userID)
+ if !ok {
+ return
+ }
+ // A public action is workspace furniture; a private one belongs to its
+ // creator and nobody else may remove it.
+ if existing.Visibility == "public" {
+ if !h.requirePublicQuickActionRole(w, r, workspaceID) {
+ return
+ }
+ } else if uuidToString(existing.CreatedByID) != userID {
+ writeError(w, http.StatusForbidden, "only the creator can delete a private quick action")
+ return
+ }
+
+ if err := h.Queries.DeleteQuickAction(r.Context(), db.DeleteQuickActionParams{ID: idUUID, WorkspaceID: wsUUID}); err != nil {
+ slog.Warn("delete quick action failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to delete quick action")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// trimmedWithinLimit trims a free-text field and enforces its rune ceiling,
+// writing the 400 itself so callers stay linear.
+func trimmedWithinLimit(w http.ResponseWriter, raw string, limit int, field string) (string, bool) {
+ v := strings.TrimSpace(raw)
+ if utf8.RuneCountInString(v) > limit {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("%s must be at most %d characters", field, limit))
+ return "", false
+ }
+ return v, true
+}
+
+// validateQuickActionBinding checks that the target exists in this workspace
+// and, for a `public` action, that every member can invoke it. Writes the 400
+// itself and returns false when the binding is rejected.
+func (h *Handler) validateQuickActionBinding(w http.ResponseWriter, r *http.Request, assigneeType string, id, workspaceID pgtype.UUID, visibility string) bool {
+ qa := db.QuickAction{AssigneeType: assigneeType, AssigneeID: id, WorkspaceID: workspaceID}
+ target := h.resolveQuickActionTarget(r.Context(), qa)
+ if !target.Found {
+ writeError(w, http.StatusBadRequest, "assignee not found in this workspace")
+ return false
+ }
+ // A public action promises "everyone can run this". Binding a target the
+ // team cannot invoke would make that promise false on the first click, so
+ // it is refused at write time instead.
+ if visibility == "public" && !h.agentInvocableByEveryone(r.Context(), target.Agent) {
+ writeError(w, http.StatusBadRequest, "a public quick action must use an agent every workspace member can trigger; make the agent public or set this action to private")
+ return false
+ }
+ return true
+}
+
+// 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.
+func (h *Handler) RenderQuickAction(w http.ResponseWriter, r *http.Request) {
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := uuidToString(issue.WorkspaceID)
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "quickActionId"), "quick action id")
+ if !ok {
+ return
+ }
+ qa, ok := h.loadReachableQuickAction(w, r, idUUID, issue.WorkspaceID, userID)
+ if !ok {
+ return
+ }
+
+ target := h.resolveQuickActionTarget(r.Context(), qa)
+ if !target.Found {
+ h.writeDispatchBlocked(w, http.StatusConflict, ReasonTargetUnavailable)
+ return
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ // Same gate as the run path: the preview would otherwise hand a user the
+ // exact text needed to trigger an agent they may not invoke.
+ if !h.canInvokeAgent(r.Context(), target.Agent, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {
+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)
+ return
+ }
+
+ writeJSON(w, http.StatusOK, map[string]string{
+ "content": buildQuickActionBody(qa, target),
+ })
+}
+
+// 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 {
+ 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.
+//
+// This is the ONLY place invoke permission is checked. The list endpoint hides
+// nothing beyond `private` ownership, so a member may well click an action
+// they cannot run; that returns a structured 403 the client renders as a
+// dialog, which is more informative than a button that silently was not there.
+//
+// The success response is a CommentResponse carrying trigger_outcomes,
+// identical in shape to POST /comments — so the client reuses one result
+// handler and gets `coalesced` (merged into the target's pending task),
+// `deferred` (runtime offline), and `blocked` for free.
+func (h *Handler) RunQuickAction(w http.ResponseWriter, r *http.Request) {
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := uuidToString(issue.WorkspaceID)
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "quickActionId"), "quick action id")
+ if !ok {
+ return
+ }
+ qa, ok := h.loadReachableQuickAction(w, r, idUUID, issue.WorkspaceID, userID)
+ if !ok {
+ return
+ }
+ if qa.Status != "active" {
+ writeError(w, http.StatusBadRequest, "quick action is archived")
+ return
+ }
+
+ target := h.resolveQuickActionTarget(r.Context(), qa)
+ if !target.Found {
+ h.writeDispatchBlocked(w, http.StatusConflict, ReasonTargetUnavailable)
+ return
+ }
+
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ originatorUserID := h.invokeOriginatorFromRequest(r, actorType, actorID)
+ // The single permission gate. Issue visibility never implies the right to
+ // trigger someone's private agent.
+ if !h.canInvokeAgent(r.Context(), target.Agent, actorType, actorID, originatorUserID, workspaceID) {
+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)
+ return
+ }
+
+ body := sanitizeNullBytes(buildQuickActionBody(qa, target))
+
+ comment, err := h.Queries.CreateComment(r.Context(), db.CreateCommentParams{
+ IssueID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ AuthorType: actorType,
+ AuthorID: parseUUID(actorID),
+ Content: body,
+ // Deliberately an ordinary comment. The collapsed card is driven by
+ // quick_action_id, which no client can set — `type` is client-supplied
+ // on the generic comment endpoint, so a dedicated type value would be
+ // forgeable and would also have cost a CHECK rebuild on a hot table.
+ Type: "comment",
+ QuickActionID: qa.ID,
+ })
+ if err != nil {
+ slog.Warn("quick action comment create failed", append(logger.RequestAttrs(r), "error", err, "quick_action_id", uuidToString(qa.ID))...)
+ writeError(w, http.StatusInternalServerError, "failed to run quick action")
+ return
+ }
+
+ resp := commentToResponse(comment, nil, nil)
+ h.publish(protocol.EventCommentCreated, workspaceID, actorType, actorID, map[string]any{
+ "comment": resp,
+ "issue_title": issue.Title,
+ "issue_assignee_type": textToPtr(issue.AssigneeType),
+ "issue_assignee_id": uuidToPtr(issue.AssigneeID),
+ "issue_status": issue.Status,
+ })
+
+ delegationAuthority := h.autopilotDelegationAuthorityFromRequest(r, issue, actorType, actorID)
+ resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, nil, actorType, actorID, originatorUserID, delegationAuthority, nil)
+
+ // Usage telemetry is best-effort and deliberately outside the run's
+ // success path: a failed counter must never cost the user the run.
+ if err := h.Queries.TouchQuickActionUsage(r.Context(), db.TouchQuickActionUsageParams{ID: qa.ID, WorkspaceID: issue.WorkspaceID}); err != nil {
+ slog.Debug("quick action usage touch failed", "quick_action_id", uuidToString(qa.ID), "error", err)
+ }
+
+ slog.Info("quick action run", append(logger.RequestAttrs(r),
+ "quick_action_id", uuidToString(qa.ID),
+ "issue_id", uuidToString(issue.ID),
+ "comment_id", uuidToString(comment.ID),
+ )...)
+ writeJSON(w, http.StatusCreated, resp)
+}
diff --git a/server/internal/handler/quick_action_access_test.go b/server/internal/handler/quick_action_access_test.go
new file mode 100644
index 0000000000..afa05196fd
--- /dev/null
+++ b/server/internal/handler/quick_action_access_test.go
@@ -0,0 +1,106 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// Cross-member access regression for private quick actions (MUL-5465, review
+// finding #2).
+//
+// The ownership rule used to be enforced inline in RunQuickAction ONLY. Update
+// and Render reached rows by (id, workspace) alone, so any member who learned a
+// UUID — an action-created comment carries one in `quick_action_id` — could
+// rewrite or read back another member's private prompt. The gate now lives in
+// loadReachableQuickAction, and these tests hold every entry point to it.
+//
+// A non-owner gets 404 rather than 403 on purpose: whether a given UUID exists
+// is not their business either.
+
+// seedPrivateQuickActionOwnedByOther inserts a private action attributed to a
+// second member, and returns its id. The row is removed on cleanup.
+func seedPrivateQuickActionOwnedByOther(t *testing.T) string {
+ t.Helper()
+ ctx := context.Background()
+
+ var otherUserID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO "user" (email, name)
+ VALUES ('[email protected]', 'QA Other')
+ ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name
+ RETURNING id
+ `).Scan(&otherUserID); err != nil {
+ t.Fatalf("seed other user: %v", err)
+ }
+
+ agentID := createHandlerTestAgent(t, "QA Access Agent", []byte("null"))
+
+ var actionID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO quick_action (
+ workspace_id, name, description, assignee_type, assignee_id, prompt,
+ visibility, created_by_type, created_by_id
+ ) VALUES ($1, 'Other Private', '', 'agent', $2, 'secret prompt', 'private', 'member', $3)
+ RETURNING id
+ `, testWorkspaceID, agentID, otherUserID).Scan(&actionID); err != nil {
+ t.Fatalf("seed private quick action: %v", err)
+ }
+
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM quick_action WHERE id = $1`, actionID)
+ })
+ return actionID
+}
+
+func TestUpdateQuickActionRejectsNonOwnerOfPrivateAction(t *testing.T) {
+ actionID := seedPrivateQuickActionOwnedByOther(t)
+
+ req := withURLParam(
+ newRequest(http.MethodPatch, "/api/quick-actions/"+actionID, map[string]any{
+ "name": "Hijacked",
+ }),
+ "id", actionID,
+ )
+ rr := httptest.NewRecorder()
+ testHandler.UpdateQuickAction(rr, req)
+
+ if rr.Code != http.StatusNotFound {
+ t.Fatalf("a non-owner must not reach another member's private action: got %d, want 404", rr.Code)
+ }
+
+ // The prompt must be untouched, not merely un-returned.
+ var name string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT name FROM quick_action WHERE id = $1`, actionID).Scan(&name); err != nil {
+ t.Fatalf("re-read action: %v", err)
+ }
+ if name != "Other Private" {
+ t.Fatalf("the refused update still mutated the row: name = %q", name)
+ }
+}
+
+func TestDeleteQuickActionRejectsNonOwnerOfPrivateAction(t *testing.T) {
+ actionID := seedPrivateQuickActionOwnedByOther(t)
+
+ req := withURLParam(
+ newRequest(http.MethodDelete, "/api/quick-actions/"+actionID, nil),
+ "id", actionID,
+ )
+ rr := httptest.NewRecorder()
+ testHandler.DeleteQuickAction(rr, req)
+
+ if rr.Code != http.StatusNotFound {
+ t.Fatalf("a non-owner must not delete another member's private action: got %d, want 404", rr.Code)
+ }
+
+ var alive int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM quick_action WHERE id = $1`, actionID).Scan(&alive); err != nil {
+ t.Fatalf("re-read action: %v", err)
+ }
+ if alive != 1 {
+ t.Fatal("the refused delete still removed the row")
+ }
+}
diff --git a/server/internal/handler/quick_action_test.go b/server/internal/handler/quick_action_test.go
new file mode 100644
index 0000000000..99a7601b68
--- /dev/null
+++ b/server/internal/handler/quick_action_test.go
@@ -0,0 +1,155 @@
+package handler
+
+import (
+ "strings"
+ "testing"
+)
+
+// TestValidateQuickActionPromptRejectsTemplateTokens locks the guard that
+// OUTLIVED the templating feature (MUL-5465).
+//
+// Variables were removed because every one of them named something the agent
+// already had. But someone carrying the habit over from autopilot's title
+// template would otherwise get `{{issue.title}}` rendered literally into an
+// agent's instructions and never notice — the exact silent-typo failure the
+// whitelist existed to prevent. So the rejection stays even though the feature
+// is gone.
+func TestValidateQuickActionPromptRejectsTemplateTokens(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ prompt string
+ wantErr bool
+ }{
+ {"plain text", "review this code", false},
+ {"prose with braces-free punctuation", "review this: correctness, edge cases (all of them)", false},
+ {"former variable", "review {{issue.title}}", true},
+ {"former input slot", "review this. Focus: {{input}}", true},
+ {"whitespace inside braces", "review {{ issue.title }}", true},
+ {"unknown token", "review {{whatever}}", true},
+ {"empty braces", "review {{}}", true},
+ {"empty prompt", " ", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := validateQuickActionPrompt(tc.prompt)
+ if tc.wantErr && err == nil {
+ t.Fatalf("expected %q to be rejected", tc.prompt)
+ }
+ if !tc.wantErr && err != nil {
+ t.Fatalf("expected %q to be accepted, got %v", tc.prompt, err)
+ }
+ })
+ }
+}
+
+// TestValidateQuickActionPromptPassesThroughVerbatim: whatever survives
+// validation is exactly what gets sent. Trimming is the only transformation.
+func TestValidateQuickActionPromptPassesThroughVerbatim(t *testing.T) {
+ const raw = " Review the code linked to this issue.\nFocus on correctness. "
+ got, err := validateQuickActionPrompt(raw)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if want := strings.TrimSpace(raw); got != want {
+ t.Fatalf("prompt must pass through verbatim:\n got: %q\nwant: %q", got, want)
+ }
+}
+
+// TestValidateQuickActionPromptLimits guards the length ceilings so a
+// pathological prompt cannot be stored and then re-rendered on every click.
+func TestValidateQuickActionPromptLimits(t *testing.T) {
+ if _, err := validateQuickActionPrompt(strings.Repeat("x", maxQuickActionPromptLen+1)); err == nil {
+ t.Fatal("an over-long prompt must be rejected")
+ }
+ if _, err := validateQuickActionName(strings.Repeat("x", maxQuickActionNameLen+1)); err == nil {
+ t.Fatal("an over-long name must be rejected")
+ }
+ if _, err := validateQuickActionName(" "); err == nil {
+ t.Fatal("a blank name must be rejected")
+ }
+}
+
+// TestNormalizeQuickActionVisibility locks the two-value intent field. An
+// empty value defaults to public (the common case); anything outside the pair
+// is rejected rather than silently stored.
+func TestNormalizeQuickActionVisibility(t *testing.T) {
+ for _, tc := range []struct {
+ in string
+ want string
+ wantErr bool
+ }{
+ {"", "public", false},
+ {"public", "public", false},
+ {"private", "private", false},
+ {"workspace", "", true},
+ {"owner_only", "", true},
+ } {
+ got, err := normalizeQuickActionVisibility(tc.in)
+ if tc.wantErr {
+ if err == nil {
+ t.Fatalf("expected %q to be rejected", tc.in)
+ }
+ continue
+ }
+ if err != nil {
+ t.Fatalf("expected %q to be accepted, got %v", tc.in, err)
+ }
+ if got != tc.want {
+ t.Fatalf("normalize(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ }
+}
+
+// TestValidateQuickActionAssignee locks the polymorphic binding to the two
+// supported actor kinds; anything else would store a target the run path
+// cannot resolve.
+func TestValidateQuickActionAssignee(t *testing.T) {
+ if err := validateQuickActionAssignee("agent", "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0"); err != nil {
+ t.Fatalf("agent binding must be accepted, got %v", err)
+ }
+ if err := validateQuickActionAssignee("squad", "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0"); err != nil {
+ t.Fatalf("squad binding must be accepted, got %v", err)
+ }
+ if err := validateQuickActionAssignee("member", "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0"); err == nil {
+ t.Fatal("a member binding must be rejected: members are not runnable targets")
+ }
+ if err := validateQuickActionAssignee("agent", " "); err == nil {
+ t.Fatal("a blank assignee id must be rejected")
+ }
+}
+
+// TestValidateQuickActionPromptRejectsSideEffectMentions locks the
+// one-action / one-reached-party invariant (MUL-5465, review findings #3 and
+// round-two #1).
+//
+// The prompt is appended verbatim to a comment that runs through the normal
+// mention pipeline, so every mention inside it acts on every click: agent /
+// squad / all enqueue a second target, and MEMBER creates an inbox
+// notification for that person. Member was allowed in the first pass on the
+// reasoning that it "only renders a link" — notification_listeners.go shows
+// otherwise, so it is refused too. Only issue links reach nobody.
+func TestValidateQuickActionPromptRejectsSideEffectMentions(t *testing.T) {
+ const id = "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0"
+ for _, tc := range []struct {
+ name string
+ prompt string
+ wantErr bool
+ }{
+ {"plain prose", "review this code", false},
+ {"an @ that is not mention markup", "ask @someone on the team", false},
+ {"issue mention reaches nobody", "see [MUL-1](mention://issue/" + id + ")", false},
+ {"member mention pings an inbox on every click", "ask [@Jia](mention://member/" + id + ")", true},
+ {"agent mention would enqueue a second target", "also [@Nova](mention://agent/" + id + ")", true},
+ {"squad mention would enqueue a second target", "also [@Core](mention://squad/" + id + ")", true},
+ {"@all would fan out", "[@all](mention://all/all)", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := validateQuickActionPrompt(tc.prompt)
+ if tc.wantErr && err == nil {
+ t.Fatalf("expected %q to be rejected", tc.prompt)
+ }
+ if !tc.wantErr && err != nil {
+ t.Fatalf("expected %q to be accepted, got %v", tc.prompt, err)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.go
index 0dfca30b8f..a0823b2096 100644
--- a/server/internal/handler/workspace_revoke.go
+++ b/server/internal/handler/workspace_revoke.go
@@ -139,6 +139,18 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID
return empty, err
}
+ // A private quick action is visible and runnable ONLY by its creator
+ // (quick_action carries no FK, so nothing removes it implicitly). Once the
+ // creator is gone the row is unreachable by every remaining member while
+ // still consuming the workspace's active-action limit, so drop those in
+ // the same tx. Public actions are workspace furniture and survive.
+ if err := qtx.DeletePrivateQuickActionsByCreator(ctx, db.DeletePrivateQuickActionsByCreatorParams{
+ WorkspaceID: workspaceID,
+ CreatedByID: userID,
+ }); err != nil {
+ return empty, err
+ }
+
// Member row deletion lives inside the same tx so a successful revoke is
// never followed by a failed member-delete (which would leave the user
// still a member with a dead runtime), and a failed revoke never leaves
diff --git a/server/migrations/237_quick_action.down.sql b/server/migrations/237_quick_action.down.sql
new file mode 100644
index 0000000000..057b9f5d96
--- /dev/null
+++ b/server/migrations/237_quick_action.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS quick_action;
diff --git a/server/migrations/237_quick_action.up.sql b/server/migrations/237_quick_action.up.sql
new file mode 100644
index 0000000000..639e1f18c7
--- /dev/null
+++ b/server/migrations/237_quick_action.up.sql
@@ -0,0 +1,62 @@
+-- Issue Quick Actions (MUL-5465).
+--
+-- A quick action is a workspace-level preset for "who to call and what to say"
+-- on an existing issue. Clicking one renders `prompt` server-side and posts a
+-- `quick_action` comment carrying the target's mention markup, which then runs
+-- through the existing comment -> mention -> task trigger path. There is no
+-- separate dispatch engine: permission (canInvokeAgent), attribution, squad
+-- leader routing, the execution log, and pending-task coalescing are all
+-- inherited from that path by construction.
+--
+-- `visibility` is the AUTHOR'S INTENT, chosen at creation:
+-- - 'public' — meant for the team. The handler requires a target every
+-- workspace member can invoke, so a public action is runnable
+-- by everyone by construction.
+-- - 'private' — meant for its creator only; any target is allowed.
+--
+-- It is intent, NOT an authorization decision: the run path always re-checks
+-- canInvokeAgent, so a target whose permission_mode changes later can never
+-- turn a stale row into an actual privilege. The worst case is a public action
+-- whose agent went private, which then fails loudly at click time.
+--
+-- Deliberately absent columns:
+-- - cron / webhook_token / execution_mode: those belong to autopilot. A
+-- quick action is human-triggered and always acts on an existing issue.
+-- - `position`: ordering is use_count DESC everywhere. A manual order plus a
+-- usage order meant one list with two different sorts, which is its own
+-- source of confusion.
+-- - `input_*`: the `/` slash command already inserts a rendered action into
+-- the composer for editing, which covers "same action, one detail
+-- different" more flexibly than a single fixed field could.
+--
+-- Actions archive (status='archived') instead of deleting so historical
+-- `quick_action` comments stay resolvable to a name.
+CREATE TABLE quick_action (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ name TEXT NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ -- Mirrors autopilot's polymorphic assignee: 'agent' -> agent(id),
+ -- 'squad' -> squad(id), resolved to squad.leader_id at run time.
+ assignee_type TEXT NOT NULL CHECK (assignee_type IN ('agent', 'squad')),
+ assignee_id UUID NOT NULL,
+ -- Stored and sent VERBATIM. No interpolation of any kind: every variable
+ -- we considered ({{issue.title}}, {{issue.identifier}}, {{issue.url}},
+ -- {{user.name}}, {{date}}) names something the agent already has from the
+ -- issue context and from the comment's own author, so none of them changed
+ -- what the agent ATTENDS TO -- only what it was told twice. The handler
+ -- still REJECTS any `{{...}}` at write time so a habitual template token
+ -- cannot land literally in an agent's instructions.
+ prompt TEXT NOT NULL,
+ visibility TEXT NOT NULL DEFAULT 'public' CHECK (visibility IN ('private', 'public')),
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'archived')),
+ last_used_at TIMESTAMPTZ,
+ use_count BIGINT NOT NULL DEFAULT 0,
+ created_by_type TEXT NOT NULL CHECK (created_by_type IN ('member', 'agent')),
+ created_by_id UUID NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- Indexes live in follow-up single-statement migrations: CREATE INDEX
+-- CONCURRENTLY cannot share a migration with other statements.
diff --git a/server/migrations/238_quick_action_workspace_index.down.sql b/server/migrations/238_quick_action_workspace_index.down.sql
new file mode 100644
index 0000000000..e45f82c0f5
--- /dev/null
+++ b/server/migrations/238_quick_action_workspace_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_quick_action_workspace_status_usage;
diff --git a/server/migrations/238_quick_action_workspace_index.up.sql b/server/migrations/238_quick_action_workspace_index.up.sql
new file mode 100644
index 0000000000..71d896ca48
--- /dev/null
+++ b/server/migrations/238_quick_action_workspace_index.up.sql
@@ -0,0 +1,6 @@
+-- Listing index for the settings page and the issue sidebar (MUL-5465). Both
+-- read "the active actions of one workspace", ordered by use_count DESC.
+-- Single-statement migration: CREATE INDEX CONCURRENTLY cannot run inside a
+-- transaction or share a migration file.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_quick_action_workspace_status_usage
+ ON quick_action(workspace_id, status, use_count DESC);
diff --git a/server/migrations/239_comment_quick_action.down.sql b/server/migrations/239_comment_quick_action.down.sql
new file mode 100644
index 0000000000..0484bfcf9b
--- /dev/null
+++ b/server/migrations/239_comment_quick_action.down.sql
@@ -0,0 +1,3 @@
+-- Dropping the column is the whole rollback: no CHECK constraint was touched
+-- on the way up, so there is nothing to narrow back and no rows to rewrite.
+ALTER TABLE comment DROP COLUMN IF EXISTS quick_action_id;
diff --git a/server/migrations/239_comment_quick_action.up.sql b/server/migrations/239_comment_quick_action.up.sql
new file mode 100644
index 0000000000..c85748f8f8
--- /dev/null
+++ b/server/migrations/239_comment_quick_action.up.sql
@@ -0,0 +1,23 @@
+-- Quick-action-triggered comments (MUL-5465).
+--
+-- A quick action posts an ORDINARY comment (type stays 'comment') and marks it
+-- with the action that produced it. The timeline renders the collapsed
+-- one-line card off this column, not off a dedicated comment type.
+--
+-- Two reasons it is an id and NOT a new `type` value:
+--
+-- 1. Adding a type meant dropping and re-adding comment_type_check, and
+-- re-adding a CHECK takes ACCESS EXCLUSIVE on `comment` while it scans
+-- the whole table. `comment` is one of the hottest tables in the product,
+-- so that is a read/write stall for every deploy. Adding a nullable
+-- column with no default is metadata-only and instant.
+--
+-- 2. `type` is client-supplied on the generic POST /comments path, so any
+-- member could post type='quick_action' and have an ordinary comment
+-- render as an action audit record with its body collapsed out of view.
+-- There is no request field for quick_action_id — only the quick-action
+-- run path sets it — so this marker cannot be forged.
+--
+-- No FK per repo policy: actions archive rather than delete, and the render
+-- path treats an unresolvable id as an ordinary comment.
+ALTER TABLE comment ADD COLUMN IF NOT EXISTS quick_action_id UUID;
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index b605e3e2a0..d2c3a0a60e 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -45,7 +45,7 @@ UPDATE comment SET
WHERE comment.id IN (SELECT id FROM descendants)
AND comment.id <> $1
AND comment.resolved_at IS NOT NULL
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id
+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id
`
type ClearOtherThreadResolutionsParams struct {
@@ -88,6 +88,7 @@ func (q *Queries) ClearOtherThreadResolutions(ctx context.Context, arg ClearOthe
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
); err != nil {
return nil, err
}
@@ -157,24 +158,25 @@ func (q *Queries) CountNewCommentsSince(ctx context.Context, arg CountNewComment
const createComment = `-- name: CreateComment :one
WITH touched_issue AS (
UPDATE issue SET updated_at = now()
- WHERE issue.id = $7 AND issue.workspace_id = $8
+ WHERE issue.id = $8 AND issue.workspace_id = $9
RETURNING issue.id, issue.workspace_id
)
-INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id)
-SELECT ti.id, ti.workspace_id, $1, $2, $3, $4, $5, $6
+INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id)
+SELECT ti.id, ti.workspace_id, $1, $2, $3, $4, $5, $6, $7
FROM touched_issue ti
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id
+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id
`
type CreateCommentParams struct {
- AuthorType string `json:"author_type"`
- AuthorID pgtype.UUID `json:"author_id"`
- Content string `json:"content"`
- Type string `json:"type"`
- ParentID pgtype.UUID `json:"parent_id"`
- SourceTaskID pgtype.UUID `json:"source_task_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Content string `json:"content"`
+ Type string `json:"type"`
+ ParentID pgtype.UUID `json:"parent_id"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
}
// A new comment counts as activity on its issue, so the same statement bumps
@@ -201,6 +203,7 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C
arg.Type,
arg.ParentID,
arg.SourceTaskID,
+ arg.QuickActionID,
arg.IssueID,
arg.WorkspaceID,
)
@@ -220,6 +223,7 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
)
return i, err
}
@@ -240,7 +244,7 @@ func (q *Queries) DeleteComment(ctx context.Context, arg DeleteCommentParams) er
}
const getComment = `-- name: GetComment :one
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment
WHERE id = $1
`
@@ -262,12 +266,13 @@ func (q *Queries) GetComment(ctx context.Context, id pgtype.UUID) (Comment, erro
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
)
return i, err
}
const getCommentInWorkspace = `-- name: GetCommentInWorkspace :one
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment
WHERE id = $1 AND workspace_id = $2
`
@@ -294,12 +299,13 @@ func (q *Queries) GetCommentInWorkspace(ctx context.Context, arg GetCommentInWor
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
)
return i, err
}
const getLatestMemberCommentForIssueSince = `-- name: GetLatestMemberCommentForIssueSince :one
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment
WHERE issue_id = $1
AND author_type = 'member'
AND created_at > $2
@@ -339,6 +345,7 @@ func (q *Queries) GetLatestMemberCommentForIssueSince(ctx context.Context, arg G
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
)
return i, err
}
@@ -353,7 +360,7 @@ WITH RECURSIVE root_of AS (
FROM comment p
JOIN root_of r ON p.id = r.parent_id
)
-SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id FROM comment c
+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id FROM comment c
WHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1)
`
@@ -385,6 +392,7 @@ func (q *Queries) GetThreadRoot(ctx context.Context, arg GetThreadRootParams) (C
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
)
return i, err
}
@@ -433,7 +441,7 @@ func (q *Queries) HasAgentRepliedInThread(ctx context.Context, arg HasAgentRepli
}
const listCommentsForIssue = `-- name: ListCommentsForIssue :many
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment
WHERE issue_id = $1 AND workspace_id = $2
ORDER BY created_at ASC, id ASC
LIMIT $3
@@ -472,6 +480,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
); err != nil {
return nil, err
}
@@ -484,7 +493,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI
}
const listCommentsSinceForIssue = `-- name: ListCommentsSinceForIssue :many
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment
WHERE issue_id = $1 AND workspace_id = $2 AND created_at > $3
ORDER BY created_at ASC, id ASC
LIMIT $4
@@ -528,6 +537,7 @@ func (q *Queries) ListCommentsSinceForIssue(ctx context.Context, arg ListComment
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
); err != nil {
return nil, err
}
@@ -680,7 +690,7 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List
}
const listReconcilableCommentsForIssueSince = `-- name: ListReconcilableCommentsForIssueSince :many
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment
WHERE issue_id = $1
AND author_type IN ('member', 'agent')
AND (
@@ -747,6 +757,7 @@ func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
); err != nil {
return nil, err
}
@@ -1235,7 +1246,7 @@ UPDATE comment SET
resolved_by_id = COALESCE(resolved_by_id, $3),
updated_at = CASE WHEN resolved_at IS NULL THEN now() ELSE updated_at END
WHERE id = $1
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id
+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id
`
type ResolveCommentParams struct {
@@ -1264,6 +1275,7 @@ func (q *Queries) ResolveComment(ctx context.Context, arg ResolveCommentParams)
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
)
return i, err
}
@@ -1275,7 +1287,7 @@ UPDATE comment SET
resolved_by_id = NULL,
updated_at = CASE WHEN resolved_at IS NOT NULL THEN now() ELSE updated_at END
WHERE id = $1
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id
+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id
`
// Idempotent: a no-op clear (already unresolved) just returns the row.
@@ -1297,6 +1309,7 @@ func (q *Queries) UnresolveComment(ctx context.Context, id pgtype.UUID) (Comment
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
)
return i, err
}
@@ -1307,7 +1320,7 @@ UPDATE comment SET
source_task_id = $3,
updated_at = now()
WHERE id = $1
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id
+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id
`
type UpdateCommentParams struct {
@@ -1334,6 +1347,7 @@ func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (C
&i.ResolvedByType,
&i.ResolvedByID,
&i.SourceTaskID,
+ &i.QuickActionID,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 4b69ee183a..21b0a965b7 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -446,6 +446,7 @@ type Comment struct {
ResolvedByType pgtype.Text `json:"resolved_by_type"`
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
}
type CommentReaction struct {
@@ -860,6 +861,24 @@ type ProjectResource struct {
CreatedBy pgtype.UUID `json:"created_by"`
}
+type QuickAction struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ AssigneeType string `json:"assignee_type"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ Prompt string `json:"prompt"`
+ Visibility string `json:"visibility"`
+ Status string `json:"status"`
+ LastUsedAt pgtype.Timestamptz `json:"last_used_at"`
+ UseCount int64 `json:"use_count"`
+ CreatedByType string `json:"created_by_type"`
+ CreatedByID pgtype.UUID `json:"created_by_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type RuntimeProfile struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
diff --git a/server/pkg/db/generated/quick_action.sql.go b/server/pkg/db/generated/quick_action.sql.go
new file mode 100644
index 0000000000..e86310b784
--- /dev/null
+++ b/server/pkg/db/generated/quick_action.sql.go
@@ -0,0 +1,295 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: quick_action.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const countActiveQuickActions = `-- name: CountActiveQuickActions :one
+SELECT COUNT(*) FROM quick_action
+WHERE workspace_id = $1 AND status = 'active'
+`
+
+func (q *Queries) CountActiveQuickActions(ctx context.Context, workspaceID pgtype.UUID) (int64, error) {
+ row := q.db.QueryRow(ctx, countActiveQuickActions, workspaceID)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const createQuickAction = `-- name: CreateQuickAction :one
+INSERT INTO quick_action (
+ workspace_id, name, description, assignee_type, assignee_id, prompt,
+ visibility, created_by_type, created_by_id
+) VALUES (
+ $1::uuid,
+ $2::text,
+ $3::text,
+ $4::text,
+ $5::uuid,
+ $6::text,
+ $7::text,
+ $8::text,
+ $9::uuid
+)
+RETURNING id, workspace_id, name, description, assignee_type, assignee_id, prompt, visibility, status, last_used_at, use_count, created_by_type, created_by_id, created_at, updated_at
+`
+
+type CreateQuickActionParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ AssigneeType string `json:"assignee_type"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ Prompt string `json:"prompt"`
+ Visibility string `json:"visibility"`
+ CreatedByType string `json:"created_by_type"`
+ CreatedByID pgtype.UUID `json:"created_by_id"`
+}
+
+func (q *Queries) CreateQuickAction(ctx context.Context, arg CreateQuickActionParams) (QuickAction, error) {
+ row := q.db.QueryRow(ctx, createQuickAction,
+ arg.WorkspaceID,
+ arg.Name,
+ arg.Description,
+ arg.AssigneeType,
+ arg.AssigneeID,
+ arg.Prompt,
+ arg.Visibility,
+ arg.CreatedByType,
+ arg.CreatedByID,
+ )
+ var i QuickAction
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.Prompt,
+ &i.Visibility,
+ &i.Status,
+ &i.LastUsedAt,
+ &i.UseCount,
+ &i.CreatedByType,
+ &i.CreatedByID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const deletePrivateQuickActionsByCreator = `-- name: DeletePrivateQuickActionsByCreator :exec
+DELETE FROM quick_action
+WHERE workspace_id = $1 AND created_by_id = $2 AND visibility = 'private'
+`
+
+type DeletePrivateQuickActionsByCreatorParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ CreatedByID pgtype.UUID `json:"created_by_id"`
+}
+
+// Run when a member leaves or is removed. A private action is visible and
+// runnable ONLY by its creator, so once they are gone nobody can see it, run
+// it, or clean it up — while it still counts against the workspace's active
+// limit. Public actions are workspace furniture and deliberately survive their
+// author's departure.
+func (q *Queries) DeletePrivateQuickActionsByCreator(ctx context.Context, arg DeletePrivateQuickActionsByCreatorParams) error {
+ _, err := q.db.Exec(ctx, deletePrivateQuickActionsByCreator, arg.WorkspaceID, arg.CreatedByID)
+ return err
+}
+
+const deleteQuickAction = `-- name: DeleteQuickAction :exec
+DELETE FROM quick_action WHERE id = $1 AND workspace_id = $2
+`
+
+type DeleteQuickActionParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// workspace_id is a SQL-layer tenant guard, matching DeleteComment.
+func (q *Queries) DeleteQuickAction(ctx context.Context, arg DeleteQuickActionParams) error {
+ _, err := q.db.Exec(ctx, deleteQuickAction, arg.ID, arg.WorkspaceID)
+ return err
+}
+
+const getQuickAction = `-- name: GetQuickAction :one
+SELECT id, workspace_id, name, description, assignee_type, assignee_id, prompt, visibility, status, last_used_at, use_count, created_by_type, created_by_id, created_at, updated_at FROM quick_action
+WHERE id = $1 AND workspace_id = $2
+`
+
+type GetQuickActionParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetQuickAction(ctx context.Context, arg GetQuickActionParams) (QuickAction, error) {
+ row := q.db.QueryRow(ctx, getQuickAction, arg.ID, arg.WorkspaceID)
+ var i QuickAction
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.Prompt,
+ &i.Visibility,
+ &i.Status,
+ &i.LastUsedAt,
+ &i.UseCount,
+ &i.CreatedByType,
+ &i.CreatedByID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const listQuickActions = `-- name: ListQuickActions :many
+SELECT id, workspace_id, name, description, assignee_type, assignee_id, prompt, visibility, status, last_used_at, use_count, created_by_type, created_by_id, created_at, updated_at FROM quick_action
+WHERE workspace_id = $1::uuid
+ AND ($2::bool OR status = 'active')
+ AND (visibility = 'public' OR created_by_id = $3::uuid)
+ORDER BY use_count DESC, LOWER(name) ASC
+`
+
+type ListQuickActionsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IncludeArchived bool `json:"include_archived"`
+ ViewerID pgtype.UUID `json:"viewer_id"`
+}
+
+// One projection for every caller. `private` rows belong to their creator, so
+// they are filtered here rather than in the handler; nothing else is hidden.
+// Permission to actually RUN an action is decided only at run time, so this
+// query does no permission work at all.
+//
+// Ordering is use_count DESC everywhere — the list's job is to answer "what
+// does this workspace actually use". LOWER(name) breaks ties so equal counts
+// never render in random order.
+func (q *Queries) ListQuickActions(ctx context.Context, arg ListQuickActionsParams) ([]QuickAction, error) {
+ rows, err := q.db.Query(ctx, listQuickActions, arg.WorkspaceID, arg.IncludeArchived, arg.ViewerID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []QuickAction{}
+ for rows.Next() {
+ var i QuickAction
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.Prompt,
+ &i.Visibility,
+ &i.Status,
+ &i.LastUsedAt,
+ &i.UseCount,
+ &i.CreatedByType,
+ &i.CreatedByID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const touchQuickActionUsage = `-- name: TouchQuickActionUsage :exec
+UPDATE quick_action
+SET use_count = use_count + 1, last_used_at = now()
+WHERE id = $1 AND workspace_id = $2
+`
+
+type TouchQuickActionUsageParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Best-effort usage telemetry, written after a successful run. Deliberately
+// not part of the run transaction: a failed counter bump must never lose the
+// run the user asked for. It also drives the list order, so it is the one
+// place ordering state changes.
+func (q *Queries) TouchQuickActionUsage(ctx context.Context, arg TouchQuickActionUsageParams) error {
+ _, err := q.db.Exec(ctx, touchQuickActionUsage, arg.ID, arg.WorkspaceID)
+ return err
+}
+
+const updateQuickAction = `-- name: UpdateQuickAction :one
+UPDATE quick_action SET
+ name = COALESCE($3, name),
+ description = COALESCE($4, description),
+ assignee_type = COALESCE($5, assignee_type),
+ assignee_id = COALESCE($6, assignee_id),
+ prompt = COALESCE($7, prompt),
+ visibility = COALESCE($8, visibility),
+ status = COALESCE($9, status),
+ updated_at = now()
+WHERE id = $1 AND workspace_id = $2
+RETURNING id, workspace_id, name, description, assignee_type, assignee_id, prompt, visibility, status, last_used_at, use_count, created_by_type, created_by_id, created_at, updated_at
+`
+
+type UpdateQuickActionParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name pgtype.Text `json:"name"`
+ Description pgtype.Text `json:"description"`
+ AssigneeType pgtype.Text `json:"assignee_type"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ Prompt pgtype.Text `json:"prompt"`
+ Visibility pgtype.Text `json:"visibility"`
+ Status pgtype.Text `json:"status"`
+}
+
+// COALESCE-on-narg partial update: an omitted field keeps its stored value.
+// assignee_type and assignee_id move together (the handler requires both), so
+// a type swap can never land with a mismatched id.
+func (q *Queries) UpdateQuickAction(ctx context.Context, arg UpdateQuickActionParams) (QuickAction, error) {
+ row := q.db.QueryRow(ctx, updateQuickAction,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.Name,
+ arg.Description,
+ arg.AssigneeType,
+ arg.AssigneeID,
+ arg.Prompt,
+ arg.Visibility,
+ arg.Status,
+ )
+ var i QuickAction
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.Prompt,
+ &i.Visibility,
+ &i.Status,
+ &i.LastUsedAt,
+ &i.UseCount,
+ &i.CreatedByType,
+ &i.CreatedByID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index cc221ad1c2..c98bd4efc9 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -113,6 +113,9 @@ cleared_installations AS (
cleared_issue_properties AS (
DELETE FROM issue_property WHERE workspace_id = $1
),
+cleared_quick_actions AS (
+ DELETE FROM quick_action WHERE workspace_id = $1
+),
deleted_pending_check_suites AS (
DELETE FROM github_pending_check_suite WHERE workspace_id = $1
),
@@ -151,8 +154,8 @@ cleared_client_usage_workspace AS (
DELETE FROM workspace WHERE workspace.id = $1
`
-// The channel_* tables (MUL-3515 §4), resource-label junctions, and custom issue
-// property definitions carry NO FK to workspace, so — unlike the CASCADE-backed
+// The channel_* tables (MUL-3515 §4), resource-label junctions, custom issue
+// property definitions, and quick actions carry NO FK to workspace, so — unlike the CASCADE-backed
// tables the DELETE below sweeps — they are not cleaned up implicitly. Remove
// their workspace-owned rows here so they commit or roll back atomically with
// the workspace row.
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index ff6132fef8..8dfceb67cf 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -413,8 +413,8 @@ WITH touched_issue AS (
WHERE issue.id = sqlc.arg(issue_id) AND issue.workspace_id = sqlc.arg(workspace_id)
RETURNING issue.id, issue.workspace_id
)
-INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id)
-SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id)
+INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id)
+SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id), sqlc.narg(quick_action_id)
FROM touched_issue ti
RETURNING *;
diff --git a/server/pkg/db/queries/quick_action.sql b/server/pkg/db/queries/quick_action.sql
new file mode 100644
index 0000000000..18abdb93d8
--- /dev/null
+++ b/server/pkg/db/queries/quick_action.sql
@@ -0,0 +1,77 @@
+-- name: ListQuickActions :many
+-- One projection for every caller. `private` rows belong to their creator, so
+-- they are filtered here rather than in the handler; nothing else is hidden.
+-- Permission to actually RUN an action is decided only at run time, so this
+-- query does no permission work at all.
+--
+-- Ordering is use_count DESC everywhere — the list's job is to answer "what
+-- does this workspace actually use". LOWER(name) breaks ties so equal counts
+-- never render in random order.
+SELECT * FROM quick_action
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND (sqlc.arg('include_archived')::bool OR status = 'active')
+ AND (visibility = 'public' OR created_by_id = sqlc.arg('viewer_id')::uuid)
+ORDER BY use_count DESC, LOWER(name) ASC;
+
+-- name: GetQuickAction :one
+SELECT * FROM quick_action
+WHERE id = $1 AND workspace_id = $2;
+
+-- name: CountActiveQuickActions :one
+SELECT COUNT(*) FROM quick_action
+WHERE workspace_id = $1 AND status = 'active';
+
+-- name: CreateQuickAction :one
+INSERT INTO quick_action (
+ workspace_id, name, description, assignee_type, assignee_id, prompt,
+ visibility, created_by_type, created_by_id
+) VALUES (
+ sqlc.arg('workspace_id')::uuid,
+ sqlc.arg('name')::text,
+ sqlc.arg('description')::text,
+ sqlc.arg('assignee_type')::text,
+ sqlc.arg('assignee_id')::uuid,
+ sqlc.arg('prompt')::text,
+ sqlc.arg('visibility')::text,
+ sqlc.arg('created_by_type')::text,
+ sqlc.arg('created_by_id')::uuid
+)
+RETURNING *;
+
+-- name: UpdateQuickAction :one
+-- COALESCE-on-narg partial update: an omitted field keeps its stored value.
+-- assignee_type and assignee_id move together (the handler requires both), so
+-- a type swap can never land with a mismatched id.
+UPDATE quick_action SET
+ name = COALESCE(sqlc.narg('name'), name),
+ description = COALESCE(sqlc.narg('description'), description),
+ assignee_type = COALESCE(sqlc.narg('assignee_type'), assignee_type),
+ assignee_id = COALESCE(sqlc.narg('assignee_id'), assignee_id),
+ prompt = COALESCE(sqlc.narg('prompt'), prompt),
+ visibility = COALESCE(sqlc.narg('visibility'), visibility),
+ status = COALESCE(sqlc.narg('status'), status),
+ updated_at = now()
+WHERE id = $1 AND workspace_id = $2
+RETURNING *;
+
+-- name: DeleteQuickAction :exec
+-- workspace_id is a SQL-layer tenant guard, matching DeleteComment.
+DELETE FROM quick_action WHERE id = $1 AND workspace_id = $2;
+
+-- name: DeletePrivateQuickActionsByCreator :exec
+-- Run when a member leaves or is removed. A private action is visible and
+-- runnable ONLY by its creator, so once they are gone nobody can see it, run
+-- it, or clean it up — while it still counts against the workspace's active
+-- limit. Public actions are workspace furniture and deliberately survive their
+-- author's departure.
+DELETE FROM quick_action
+WHERE workspace_id = $1 AND created_by_id = $2 AND visibility = 'private';
+
+-- name: TouchQuickActionUsage :exec
+-- Best-effort usage telemetry, written after a successful run. Deliberately
+-- not part of the run transaction: a failed counter bump must never lose the
+-- run the user asked for. It also drives the list order, so it is the one
+-- place ordering state changes.
+UPDATE quick_action
+SET use_count = use_count + 1, last_used_at = now()
+WHERE id = $1 AND workspace_id = $2;
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index 746198202b..351de18606 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -91,8 +91,8 @@ SELECT id FROM workspace WHERE id = $1 FOR UPDATE;
SELECT id FROM workspace WHERE id = $1 FOR KEY SHARE;
-- name: DeleteWorkspace :exec
--- The channel_* tables (MUL-3515 §4), resource-label junctions, and custom issue
--- property definitions carry NO FK to workspace, so — unlike the CASCADE-backed
+-- The channel_* tables (MUL-3515 §4), resource-label junctions, custom issue
+-- property definitions, and quick actions carry NO FK to workspace, so — unlike the CASCADE-backed
-- tables the DELETE below sweeps — they are not cleaned up implicitly. Remove
-- their workspace-owned rows here so they commit or roll back atomically with
-- the workspace row.
@@ -156,6 +156,9 @@ cleared_installations AS (
cleared_issue_properties AS (
DELETE FROM issue_property WHERE workspace_id = $1
),
+cleared_quick_actions AS (
+ DELETE FROM quick_action WHERE workspace_id = $1
+),
deleted_pending_check_suites AS (
DELETE FROM github_pending_check_suite WHERE workspace_id = $1
),