Skip to content

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

Go

Add comment trigger preview suppression (#3792)

Naiyuan Qing906f70a3e205
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index e3f9517aea..563653a61a 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -152,6 +152,69 @@ describe("ApiClient", () => {
expect(headers["X-Client-OS"]).toBeUndefined();
});
+ it("uses the expected HTTP contract for comment trigger preview and suppress", async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ agents: [] }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({
+ id: "comment-1",
+ issue_id: "issue-1",
+ author_type: "member",
+ author_id: "user-1",
+ content: "hello",
+ type: "comment",
+ parent_id: null,
+ reactions: [],
+ attachments: [],
+ created_at: "2026-06-05T00:00:00Z",
+ updated_at: "2026-06-05T00:00:00Z",
+ }), {
+ status: 201,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await client.previewCommentTriggers("issue-1", "hello", "parent-1");
+ await client.createComment(
+ "issue-1",
+ "hello",
+ "comment",
+ "parent-1",
+ ["attachment-1"],
+ ["agent-1"],
+ );
+
+ expect(fetchMock.mock.calls.map(([url, init]) => ({
+ url,
+ method: init?.method,
+ body: init?.body,
+ }))).toMatchObject([
+ {
+ url: "https://api.example.test/api/issues/issue-1/comments/trigger-preview",
+ method: "POST",
+ body: JSON.stringify({ content: "hello", parent_id: "parent-1" }),
+ },
+ {
+ url: "https://api.example.test/api/issues/issue-1/comments",
+ method: "POST",
+ body: JSON.stringify({
+ content: "hello",
+ type: "comment",
+ parent_id: "parent-1",
+ attachment_ids: ["attachment-1"],
+ suppress_agent_ids: ["agent-1"],
+ }),
+ },
+ ]);
+ });
+
it("uses the Cloud Runtime node API contract", async () => {
const node = {
id: "node-1",
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index d5891db668..d367e9292f 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -27,6 +27,7 @@ import type {
InboxItem,
IssueSubscriber,
Comment,
+ CommentTriggerPreview,
Reaction,
IssueReaction,
Workspace,
@@ -133,6 +134,7 @@ import {
AttachmentResponseSchema,
ChildIssuesResponseSchema,
CommentsListSchema,
+ CommentTriggerPreviewSchema,
CloudRuntimeNodeListSchema,
CloudRuntimeNodeSchema,
CreateAgentFromTemplateResponseSchema,
@@ -635,7 +637,14 @@ export class ApiClient {
});
}
- async createComment(issueId: string, content: string, type?: string, parentId?: string, attachmentIds?: string[]): Promise<Comment> {
+ async createComment(
+ issueId: string,
+ content: string,
+ type?: string,
+ parentId?: string,
+ attachmentIds?: string[],
+ suppressAgentIds?: string[],
+ ): Promise<Comment> {
return this.fetch(`/api/issues/${issueId}/comments`, {
method: "POST",
body: JSON.stringify({
@@ -643,10 +652,24 @@ export class ApiClient {
type: type ?? "comment",
...(parentId ? { parent_id: parentId } : {}),
...(attachmentIds?.length ? { attachment_ids: attachmentIds } : {}),
+ ...(suppressAgentIds?.length ? { suppress_agent_ids: suppressAgentIds } : {}),
}),
});
}
+ async previewCommentTriggers(issueId: string, content: string, parentId?: string): Promise<CommentTriggerPreview> {
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/comments/trigger-preview`, {
+ method: "POST",
+ body: JSON.stringify({
+ content,
+ ...(parentId ? { parent_id: parentId } : {}),
+ }),
+ });
+ return parseWithFallback(raw, CommentTriggerPreviewSchema, { agents: [] }, {
+ endpoint: "POST /api/issues/:id/comments/trigger-preview",
+ });
+ }
+
async listTimeline(issueId: string): Promise<TimelineEntry[]> {
const raw = await this.fetch<unknown>(
`/api/issues/${issueId}/timeline`,
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 4bc8398863..af0e1848ba 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -127,6 +127,15 @@ describe("ApiClient schema fallback", () => {
});
});
+ describe("previewCommentTriggers", () => {
+ it("returns an empty agent list when the response is malformed", async () => {
+ stubFetchJson({ agents: "not-an-array" });
+ const client = new ApiClient("https://api.example.test");
+ const preview = await client.previewCommentTriggers("issue-1", "hello");
+ expect(preview).toEqual({ agents: [] });
+ });
+ });
+
describe("listIssueSubscribers", () => {
it("returns [] when the response is null", async () => {
stubFetchJson(null);
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 33953a917b..225bd6cb6d 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -198,6 +198,18 @@ export const CommentSchema = z.object({
export const CommentsListSchema = z.array(CommentSchema);
+const CommentTriggerPreviewAgentSchema = z.object({
+ id: z.string(),
+ name: z.string().default(""),
+ avatar_url: z.string().optional(),
+ source: z.string().default(""),
+ reason: z.string().default(""),
+}).loose();
+
+export const CommentTriggerPreviewSchema = z.object({
+ agents: z.array(CommentTriggerPreviewAgentSchema).default([]),
+}).loose();
+
// Metadata is primitive-only by API/DB contract. Stay lenient on shape:
// unknown keys land as `unknown` to a caller, but the field itself defaults
// to {} so consumers never need to nil-guard `issue.metadata`.
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index f1fee46764..806789f031 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -598,12 +598,14 @@ export function useCreateComment(issueId: string) {
type,
parentId,
attachmentIds,
+ suppressAgentIds,
}: {
content: string;
type?: string;
parentId?: string;
attachmentIds?: string[];
- }) => api.createComment(issueId, content, type, parentId, attachmentIds),
+ suppressAgentIds?: string[];
+ }) => api.createComment(issueId, content, type, parentId, attachmentIds, suppressAgentIds),
onSuccess: (comment) => {
const entry: TimelineEntry = {
type: "comment",
@@ -626,6 +628,10 @@ export function useCreateComment(issueId: string) {
if (old.some((e) => e.id === entry.id)) return old;
return sortTimelineEntriesAsc([...old, entry]);
});
+ // Posting a comment changes the trigger answer itself (the enqueued
+ // task now dedupes follow-up triggers), so cached previews for this
+ // issue are stale the moment the create lands.
+ qc.invalidateQueries({ queryKey: issueKeys.commentTriggerPreview(issueId) });
},
// No onSettled invalidate. The `comment:created` WS broadcast keeps
// the timeline cache fresh after a successful create, and reconnect
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index aefd544d7b..e2d902bba3 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -73,6 +73,9 @@ export const issueKeys = {
/** Full-issue timeline (single TanStack Query, no cursor). */
timeline: (issueId: string) =>
[...issueKeys.timelineAll(), issueId] as const,
+ /** PREFIX for invalidation — the composer hook appends parent + content signature. */
+ commentTriggerPreview: (issueId: string) =>
+ ["issues", "comment-trigger-preview", issueId] as const,
reactionsAll: () => ["issues", "reactions"] as const,
reactions: (issueId: string) =>
[...issueKeys.reactionsAll(), issueId] as const,
diff --git a/packages/core/types/comment.ts b/packages/core/types/comment.ts
index a8b0a1bc3d..665766b720 100644
--- a/packages/core/types/comment.ts
+++ b/packages/core/types/comment.ts
@@ -30,3 +30,20 @@ export interface Comment {
resolved_by_type: CommentAuthorType | null;
resolved_by_id: string | null;
}
+
+export type CommentTriggerSource =
+ | "issue_assignee"
+ | "mention_agent"
+ | "mention_squad_leader";
+
+export interface CommentTriggerPreviewAgent {
+ id: string;
+ name: string;
+ avatar_url?: string;
+ source: CommentTriggerSource | string;
+ reason: string;
+}
+
+export interface CommentTriggerPreview {
+ agents: CommentTriggerPreviewAgent[];
+}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 083dd88d82..7da9709fec 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -55,7 +55,7 @@ export type {
export type { Workspace, WorkspaceRepo, Member, MemberRole, User, MemberWithUser, Invitation } from "./workspace";
export type { InboxItem, InboxSeverity, InboxItemType } from "./inbox";
export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";
-export type { Comment, CommentType, CommentAuthorType, Reaction } from "./comment";
+export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, Reaction } from "./comment";
export type { Label, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse } from "./label";
export type {
TimelineEntry,
diff --git a/packages/views/common/actor-avatar.tsx b/packages/views/common/actor-avatar.tsx
index ccceb3e4de..3aa3648128 100644
--- a/packages/views/common/actor-avatar.tsx
+++ b/packages/views/common/actor-avatar.tsx
@@ -193,7 +193,9 @@ function ActorAvatarProfileLink({
// 14 px owner sub-avatar in agents-list rows) stay visually clean. The dot
// scales with the avatar size — anything ≥24 px gets the standard 8 px dot,
// smaller avatars use a 6 px dot so the indicator doesn't overwhelm them.
-function AgentStatusDot({ agentId, size }: { agentId: string; size?: number }) {
+// Exported for surfaces that render the base avatar directly (e.g. comment
+// trigger chips) but still want the standard presence dot.
+export function AgentStatusDot({ agentId, size }: { agentId: string; size?: number }) {
const ws = useCurrentWorkspace();
const detail = useAgentPresenceDetail(ws?.id, agentId);
if (detail === "loading") return null;
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index d20e027af3..8ddbea5783 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -102,7 +102,7 @@ interface CommentCardProps {
* `CommentRow` has to rerun the rule per row.
*/
canModerate?: boolean;
- onReply: (parentId: string, content: string, attachmentIds?: string[]) => Promise<void>;
+ onReply: (parentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<void>;
onEdit: (commentId: string, content: string, attachmentIds: string[]) => Promise<void>;
onDelete: (commentId: string) => void;
onToggleReaction: (commentId: string, emoji: string) => void;
@@ -922,12 +922,13 @@ function CommentCardImpl({
<div className="border-t border-border/50 px-4 py-2.5">
<ReplyInput
issueId={issueId}
+ parentId={entry.id}
placeholder={t(($) => $.reply.placeholder)}
size="sm"
avatarType="member"
avatarId={currentUserId ?? ""}
draftKey={`reply:${issueId}:${entry.id}`}
- onSubmit={(content, attachmentIds) => onReply(entry.id, content, attachmentIds)}
+ onSubmit={(content, attachmentIds, suppressAgentIds) => onReply(entry.id, content, attachmentIds, suppressAgentIds)}
/>
</div>
</>
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index 399e2b418b..0121e6816e 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -1,4 +1,5 @@
-import { forwardRef, useImperativeHandle, useRef, type Ref } from "react";
+import { forwardRef, useImperativeHandle, useRef, type ReactNode, type Ref } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { fireEvent, screen, waitFor } from "@testing-library/react";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
@@ -76,8 +77,19 @@ vi.mock("../../editor", () => ({
}),
}));
+function renderWithProviders(ui: ReactNode) {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ },
+ });
+ return renderWithI18n(
+ <QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>,
+ );
+}
+
function renderCommentInput(onSubmit = vi.fn().mockResolvedValue(undefined)) {
- const view = renderWithI18n(<CommentInput issueId="issue-1" onSubmit={onSubmit} />);
+ const view = renderWithProviders(<CommentInput issueId="issue-1" onSubmit={onSubmit} />);
return { ...view, onSubmit };
}
@@ -85,12 +97,13 @@ function renderReplyInput({
onSubmit = vi.fn().mockResolvedValue(undefined),
size = "sm",
}: {
- onSubmit?: (content: string, attachmentIds?: string[]) => Promise<void>;
+ onSubmit?: (content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<void>;
size?: "sm" | "default";
} = {}) {
- const view = renderWithI18n(
+ const view = renderWithProviders(
<ReplyInput
issueId="issue-1"
+ parentId="comment-1"
avatarType="member"
avatarId="user-1"
onSubmit={onSubmit}
@@ -155,7 +168,7 @@ describe("comment composers", () => {
fireEvent.click(getSubmitButton(container));
await waitFor(() => {
- expect(onSubmit).toHaveBeenCalledWith("hello from composer", undefined);
+ expect(onSubmit).toHaveBeenCalledWith("hello from composer", undefined, undefined);
});
});
@@ -168,7 +181,7 @@ describe("comment composers", () => {
fireEvent.click(getSubmitButton(container));
await waitFor(() => {
- expect(onSubmit).toHaveBeenCalledWith("thread reply", undefined);
+ expect(onSubmit).toHaveBeenCalledWith("thread reply", undefined, undefined);
});
});
});
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index 73a07b2c63..5ef8509f32 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -11,10 +11,12 @@ import { contentReferencesAttachment } from "@multica/core/types";
import { enterKey, formatShortcut, modKey } from "@multica/core/platform";
import { useCommentDraftStore } from "@multica/core/issues/stores";
import { useT } from "../../i18n";
+import { CommentTriggerChips } from "./comment-trigger-chips";
+import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
interface CommentInputProps {
issueId: string;
- onSubmit: (content: string, attachmentIds?: string[]) => Promise<void>;
+ onSubmit: (content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<void>;
}
function CommentInput({ issueId, onSubmit }: CommentInputProps) {
@@ -26,8 +28,11 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
// button would be disabled even though the editor visibly contains text.
const draftKey = `new:${issueId}` as const;
const initialDraft = useCommentDraftStore.getState().getDraft(draftKey);
+ const [content, setContent] = useState(initialDraft ?? "");
const [isEmpty, setIsEmpty] = useState(() => !initialDraft?.trim());
const [submitting, setSubmitting] = useState(false);
+ const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());
+ const triggerPreview = useCommentTriggerPreview({ issueId, content });
// Attachments uploaded in this composer session. Drives both:
// - submit-time `attachment_ids` payload (filtered to URLs still in markdown)
// - the editor's AttachmentDownloadProvider, so file-card Eye buttons can
@@ -66,6 +71,23 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
return result;
}, [uploadWithToast, issueId]);
+ useEffect(() => {
+ const visible = new Set(triggerPreview.agents.map((agent) => agent.id));
+ setSuppressedAgentIds((prev) => {
+ const next = new Set([...prev].filter((id) => visible.has(id)));
+ return next.size === prev.size ? prev : next;
+ });
+ }, [triggerPreview.agents]);
+
+ const toggleSuppressedAgent = useCallback((agentId: string) => {
+ setSuppressedAgentIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(agentId)) next.delete(agentId);
+ else next.add(agentId);
+ return next;
+ });
+ }, []);
+
const handleSubmit = async () => {
const content = editorRef.current?.getMarkdown()?.replace(/(\n\s*)+$/, "").trim();
if (!content || submitting) return;
@@ -76,11 +98,20 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
const activeIds = pendingAttachments
.filter((a) => contentReferencesAttachment(content, a))
.map((a) => a.id);
+ const suppressAgentIds = triggerPreview.agents
+ .filter((agent) => suppressedAgentIds.has(agent.id))
+ .map((agent) => agent.id);
setSubmitting(true);
try {
- await onSubmit(content, activeIds.length > 0 ? activeIds : undefined);
+ await onSubmit(
+ content,
+ activeIds.length > 0 ? activeIds : undefined,
+ suppressAgentIds.length > 0 ? suppressAgentIds : undefined,
+ );
editorRef.current?.clearContent();
+ setContent("");
setIsEmpty(true);
+ setSuppressedAgentIds(new Set());
setPendingAttachments([]);
clearDraft(draftKey);
} finally {
@@ -99,6 +130,7 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
defaultValue={initialDraft}
placeholder={t(($) => $.comment.leave_comment_placeholder)}
onUpdate={(md) => {
+ setContent(md);
setIsEmpty(!md.trim());
// Debounced upstream (debounceMs=100). Persist on every tick so a
// reload or scroll-out-of-viewport restores work to the keystroke.
@@ -114,6 +146,13 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
slashCommandMode="command"
/>
</div>
+ <div className="absolute bottom-1 left-2 right-28 min-w-0">
+ <CommentTriggerChips
+ agents={triggerPreview.agents}
+ suppressedAgentIds={suppressedAgentIds}
+ onToggle={toggleSuppressedAgent}
+ />
+ </div>
<div className="absolute bottom-1 right-1.5 flex items-center gap-1">
<FileUploadButton
size="sm"
diff --git a/packages/views/issues/components/comment-trigger-chips.test.tsx b/packages/views/issues/components/comment-trigger-chips.test.tsx
new file mode 100644
index 0000000000..0d2ac559f8
--- /dev/null
+++ b/packages/views/issues/components/comment-trigger-chips.test.tsx
@@ -0,0 +1,110 @@
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, screen } from "@testing-library/react";
+import type { CommentTriggerPreviewAgent } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { CommentTriggerChips } from "./comment-trigger-chips";
+
+vi.mock("@multica/core/agents", () => ({
+ useAgentPresenceDetail: () => ({ availability: "online", workload: "idle" }),
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "ws-1" }),
+}));
+
+vi.mock("../../common/actor-avatar", () => ({
+ AgentStatusDot: () => <span data-testid="status-dot" />,
+}));
+
+const walt: CommentTriggerPreviewAgent = {
+ id: "agent-1",
+ name: "Walt",
+ source: "issue_assignee",
+ reason: "",
+};
+
+const bob: CommentTriggerPreviewAgent = {
+ id: "agent-2",
+ name: "Bob",
+ source: "mention_agent",
+ reason: "",
+};
+
+describe("CommentTriggerChips", () => {
+ it("renders nothing without agents", () => {
+ const { container } = renderWithI18n(
+ <CommentTriggerChips agents={[]} suppressedAgentIds={new Set()} onToggle={vi.fn()} />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders a single agent as a full sentence and toggles on click", () => {
+ const onToggle = vi.fn();
+ renderWithI18n(
+ <CommentTriggerChips agents={[walt]} suppressedAgentIds={new Set()} onToggle={onToggle} />,
+ );
+
+ const chip = screen.getByRole("button");
+ expect(chip).toHaveTextContent("Walt will start working");
+ expect(chip).toHaveAttribute("aria-pressed", "false");
+
+ fireEvent.click(chip);
+ expect(onToggle).toHaveBeenCalledWith("agent-1");
+ });
+
+ it("dims a suppressed single agent into the skip sentence", () => {
+ renderWithI18n(
+ <CommentTriggerChips
+ agents={[walt]}
+ suppressedAgentIds={new Set(["agent-1"])}
+ onToggle={vi.fn()}
+ />,
+ );
+
+ const chip = screen.getByRole("button");
+ expect(chip).toHaveTextContent("Walt won't be triggered this time");
+ expect(chip).toHaveAttribute("aria-pressed", "true");
+ });
+
+ it("collapses several agents into a stack with an active count", () => {
+ renderWithI18n(
+ <CommentTriggerChips
+ agents={[walt, bob]}
+ suppressedAgentIds={new Set()}
+ onToggle={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByRole("button")).toHaveTextContent("2 agents will start working");
+ });
+
+ it("counts only non-suppressed agents in the sentence", () => {
+ renderWithI18n(
+ <CommentTriggerChips
+ agents={[walt, bob]}
+ suppressedAgentIds={new Set(["agent-2"])}
+ onToggle={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByRole("button")).toHaveTextContent("1 agent will start working");
+ });
+
+ it("opens the popover on click and toggles a row", () => {
+ const onToggle = vi.fn();
+ renderWithI18n(
+ <CommentTriggerChips
+ agents={[walt, bob]}
+ suppressedAgentIds={new Set()}
+ onToggle={onToggle}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button"));
+
+ const row = screen.getByRole("button", { name: /Bob/ });
+ expect(row).toHaveTextContent("Bob");
+ fireEvent.click(row);
+ expect(onToggle).toHaveBeenCalledWith("agent-2");
+ });
+});
diff --git a/packages/views/issues/components/comment-trigger-chips.tsx b/packages/views/issues/components/comment-trigger-chips.tsx
new file mode 100644
index 0000000000..941f98f915
--- /dev/null
+++ b/packages/views/issues/components/comment-trigger-chips.tsx
@@ -0,0 +1,334 @@
+"use client";
+
+import { useState } from "react";
+import type { CommentTriggerPreviewAgent } from "@multica/core/types";
+import { useAgentPresenceDetail } from "@multica/core/agents";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@multica/ui/components/ui/popover";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";
+import { cn } from "@multica/ui/lib/utils";
+import { AgentStatusDot } from "../../common/actor-avatar";
+import { useT } from "../../i18n";
+
+// One agent renders in full ("Walt will start working", avatar + presence
+// dot, click toggles). Several agents collapse to an overlapping avatar
+// stack + count sentence, mirroring WorkspaceAgentWorkingChip on the issues
+// header. Hover layers stay read-only (Tooltip); per-agent toggling lives in
+// a click-opened Popover so the layer survives consecutive clicks.
+// Suppression is communicated by brightness alone: lit = will trigger,
+// dimmed = skipped.
+const AVATAR_SIZE = 16;
+const MAX_STACK_HEADS = 4;
+
+interface CommentTriggerChipsProps {
+ agents: CommentTriggerPreviewAgent[];
+ suppressedAgentIds: Set<string>;
+ onToggle: (agentId: string) => void;
+}
+
+type IssuesT = ReturnType<typeof useT<"issues">>["t"];
+
+function sourceLabel(source: string, t: IssuesT): string {
+ switch (source) {
+ case "issue_assignee":
+ return t(($) => $.comment.trigger_source_issue_assignee);
+ case "mention_agent":
+ return t(($) => $.comment.trigger_source_mention_agent);
+ case "mention_squad_leader":
+ return t(($) => $.comment.trigger_source_mention_squad_leader);
+ default:
+ return t(($) => $.comment.trigger_source_unknown);
+ }
+}
+
+function sourceReason(agent: CommentTriggerPreviewAgent, t: IssuesT): string {
+ switch (agent.source) {
+ case "issue_assignee":
+ return t(($) => $.comment.trigger_reason_issue_assignee, { name: agent.name });
+ case "mention_agent":
+ return t(($) => $.comment.trigger_reason_mention_agent, { name: agent.name });
+ case "mention_squad_leader":
+ return t(($) => $.comment.trigger_reason_mention_squad_leader, { name: agent.name });
+ default:
+ return agent.reason || t(($) => $.comment.trigger_reason_unknown, { name: agent.name });
+ }
+}
+
+// Presence is display metadata only — the trigger list itself is always the
+// backend preview. Online-ish agents start right away; offline ones queue.
+function useTriggerPresenceLine(agentId: string, t: IssuesT): string | null {
+ const ws = useCurrentWorkspace();
+ const detail = useAgentPresenceDetail(ws?.id, agentId);
+ if (detail === "loading") return null;
+ return detail.availability === "online" || detail.availability === "unstable"
+ ? t(($) => $.comment.trigger_starts_now)
+ : t(($) => $.comment.trigger_starts_when_online);
+}
+
+// One tooltip body for every trigger surface (single chip, popover rows):
+// who · why it fires (+ presence) · what a click does.
+function TriggerAgentTooltipBody({
+ agent,
+ suppressed,
+ t,
+}: {
+ agent: CommentTriggerPreviewAgent;
+ suppressed: boolean;
+ t: IssuesT;
+}) {
+ const presenceLine = useTriggerPresenceLine(agent.id, t);
+ return (
+ <div className="space-y-0.5">
+ <div className="flex items-baseline gap-1.5">
+ <span className="font-medium">{agent.name}</span>
+ <span className="text-[10px] text-muted-foreground">{sourceLabel(agent.source, t)}</span>
+ </div>
+ {suppressed ? (
+ <div>{t(($) => $.comment.trigger_click_to_restore)}</div>
+ ) : (
+ <>
+ <div>
+ {sourceReason(agent, t)}
+ {presenceLine ? ` ${presenceLine}` : ""}
+ </div>
+ <div className="text-muted-foreground">{t(($) => $.comment.trigger_click_to_skip)}</div>
+ </>
+ )}
+ </div>
+ );
+}
+
+export function CommentTriggerChips({
+ agents,
+ suppressedAgentIds,
+ onToggle,
+}: CommentTriggerChipsProps) {
+ const { t } = useT("issues");
+
+ // Loading and errors render nothing: the preview is an enhancement, and
+ // any interim chrome here reads as composer noise.
+ if (agents.length === 0) return null;
+
+ if (agents.length === 1) {
+ const agent = agents[0]!;
+ return (
+ <SingleTriggerChip
+ agent={agent}
+ suppressed={suppressedAgentIds.has(agent.id)}
+ onToggle={onToggle}
+ t={t}
+ />
+ );
+ }
+
+ return (
+ <MultiTriggerChip
+ agents={agents}
+ suppressedAgentIds={suppressedAgentIds}
+ onToggle={onToggle}
+ t={t}
+ />
+ );
+}
+
+function SingleTriggerChip({
+ agent,
+ suppressed,
+ onToggle,
+ t,
+}: {
+ agent: CommentTriggerPreviewAgent;
+ suppressed: boolean;
+ onToggle: (agentId: string) => void;
+ t: IssuesT;
+}) {
+ const state = suppressed ? t(($) => $.comment.trigger_suppressed) : sourceLabel(agent.source, t);
+ const sentence = suppressed
+ ? t(($) => $.comment.trigger_will_skip, { name: agent.name })
+ : t(($) => $.comment.trigger_will_start, { name: agent.name });
+
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-pressed={suppressed}
+ aria-label={t(($) => $.comment.trigger_chip_aria, { name: agent.name, state })}
+ onClick={() => onToggle(agent.id)}
+ className={cn(
+ "inline-flex h-6 min-w-0 max-w-full animate-in fade-in slide-in-from-bottom-1 cursor-pointer items-center gap-1.5 rounded-md px-1.5 text-[11px] font-medium transition-colors duration-200 hover:bg-muted hover:text-foreground",
+ suppressed ? "text-muted-foreground opacity-60" : "text-foreground",
+ )}
+ >
+ <TriggerAgentAvatar agent={agent} suppressed={suppressed} />
+ <span className="truncate">{sentence}</span>
+ </button>
+ }
+ />
+ <TooltipContent side="top" className="max-w-72 text-xs">
+ <TriggerAgentTooltipBody agent={agent} suppressed={suppressed} t={t} />
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+function MultiTriggerChip({
+ agents,
+ suppressedAgentIds,
+ onToggle,
+ t,
+}: {
+ agents: CommentTriggerPreviewAgent[];
+ suppressedAgentIds: Set<string>;
+ onToggle: (agentId: string) => void;
+ t: IssuesT;
+}) {
+ const [open, setOpen] = useState(false);
+ const [tooltipHover, setTooltipHover] = useState(false);
+ const activeCount = agents.filter((a) => !suppressedAgentIds.has(a.id)).length;
+ const heads = agents.slice(0, MAX_STACK_HEADS);
+ const overflow = agents.length - heads.length;
+ // Mirror AgentAvatarStack: ~30% overlap reads as "stacked" without
+ // obscuring the next avatar.
+ const overlap = Math.round(AVATAR_SIZE * 0.3);
+ const sentence =
+ activeCount === 0
+ ? t(($) => $.comment.trigger_suppressed)
+ : t(($) => $.comment.trigger_will_start_count, { count: activeCount });
+
+ const popoverTrigger = (
+ <PopoverTrigger
+ render={
+ // Ghost-button affordance (hover fill + aria-expanded pin) so the
+ // stack reads as clickable, matching pickers across the app.
+ <button
+ type="button"
+ className={cn(
+ "inline-flex h-6 min-w-0 max-w-full animate-in fade-in slide-in-from-bottom-1 cursor-pointer items-center gap-1.5 rounded-md px-1.5 text-[11px] font-medium transition-colors duration-200 hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground",
+ activeCount === 0 ? "text-muted-foreground opacity-60" : "text-foreground",
+ )}
+ />
+ }
+ >
+ <span className="inline-flex items-center">
+ {heads.map((agent, i) => (
+ <span
+ key={agent.id}
+ style={{ marginLeft: i === 0 ? 0 : -overlap }}
+ className="inline-flex rounded-full ring-2 ring-background"
+ >
+ <TriggerAgentAvatar
+ agent={agent}
+ suppressed={suppressedAgentIds.has(agent.id)}
+ showDot={false}
+ />
+ </span>
+ ))}
+ {overflow > 0 && (
+ <span
+ style={{
+ marginLeft: -overlap,
+ width: AVATAR_SIZE,
+ height: AVATAR_SIZE,
+ fontSize: Math.max(9, Math.round(AVATAR_SIZE * 0.45)),
+ }}
+ className="inline-flex items-center justify-center rounded-full bg-muted font-medium tabular-nums text-muted-foreground ring-2 ring-background"
+ >
+ +{overflow}
+ </span>
+ )}
+ </span>
+ <span className="truncate">{sentence}</span>
+ </PopoverTrigger>
+ );
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <Tooltip open={tooltipHover && !open} onOpenChange={setTooltipHover}>
+ <TooltipTrigger render={popoverTrigger} />
+ <TooltipContent side="top" className="text-xs">
+ {t(($) => $.comment.trigger_click_to_manage)}
+ </TooltipContent>
+ </Tooltip>
+ <PopoverContent align="start" className="w-64 p-2">
+ <div className="px-1.5 pb-1 text-xs font-medium text-muted-foreground">
+ {t(($) => $.comment.trigger_preview_title)}
+ </div>
+ <div className="flex flex-col">
+ {agents.map((agent) => {
+ const suppressed = suppressedAgentIds.has(agent.id);
+ const state = suppressed
+ ? t(($) => $.comment.trigger_suppressed)
+ : sourceLabel(agent.source, t);
+ return (
+ <Tooltip key={agent.id}>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-pressed={suppressed}
+ aria-label={t(($) => $.comment.trigger_chip_aria, { name: agent.name, state })}
+ onClick={() => onToggle(agent.id)}
+ className={cn(
+ "flex w-full cursor-pointer items-center gap-2 rounded-md px-1.5 py-1 text-left transition-colors hover:bg-muted",
+ suppressed && "opacity-60",
+ )}
+ >
+ <TriggerAgentAvatar agent={agent} suppressed={suppressed} />
+ <span
+ className={cn(
+ "min-w-0 flex-1 truncate text-xs",
+ suppressed && "text-muted-foreground",
+ )}
+ >
+ {agent.name}
+ </span>
+ <span className="shrink-0 text-[10px] text-muted-foreground">{state}</span>
+ </button>
+ }
+ />
+ <TooltipContent side="right" className="max-w-72 text-xs">
+ <TriggerAgentTooltipBody agent={agent} suppressed={suppressed} t={t} />
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+function TriggerAgentAvatar({
+ agent,
+ suppressed,
+ showDot = true,
+}: {
+ agent: CommentTriggerPreviewAgent;
+ suppressed: boolean;
+ showDot?: boolean;
+}) {
+ return (
+ <span
+ className={cn(
+ "relative inline-flex shrink-0",
+ suppressed && "opacity-40 grayscale",
+ )}
+ >
+ <ActorAvatarBase
+ name={agent.name}
+ initials=""
+ avatarUrl={agent.avatar_url}
+ isAgent
+ size={AVATAR_SIZE}
+ />
+ {showDot && !suppressed && <AgentStatusDot agentId={agent.id} size={AVATAR_SIZE} />}
+ </span>
+ );
+}
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index caaa909ae9..b880a5247c 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -12,6 +12,8 @@ import { contentReferencesAttachment } from "@multica/core/types";
import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issues/stores";
import { cn } from "@multica/ui/lib/utils";
import { useT } from "../../i18n";
+import { CommentTriggerChips } from "./comment-trigger-chips";
+import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
// ---------------------------------------------------------------------------
// Types
@@ -19,10 +21,11 @@ import { useT } from "../../i18n";
interface ReplyInputProps {
issueId: string;
+ parentId: string;
placeholder?: string;
avatarType: string;
avatarId: string;
- onSubmit: (content: string, attachmentIds?: string[]) => Promise<void>;
+ onSubmit: (content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<void>;
size?: "sm" | "default";
/** When set, hydrates/persists the in-progress reply via the draft store.
* Required for replies inside virtualized timeline threads, where the
@@ -36,6 +39,7 @@ interface ReplyInputProps {
function ReplyInput({
issueId,
+ parentId,
placeholder,
avatarType,
avatarId,
@@ -51,10 +55,13 @@ function ReplyInput({
const initialDraft = draftKey
? useCommentDraftStore.getState().getDraft(draftKey)
: undefined;
+ const [content, setContent] = useState(initialDraft ?? "");
const setDraft = useCommentDraftStore((s) => s.setDraft);
const clearDraft = useCommentDraftStore((s) => s.clearDraft);
const [isEmpty, setIsEmpty] = useState(!initialDraft?.trim());
const [submitting, setSubmitting] = useState(false);
+ const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());
+ const triggerPreview = useCommentTriggerPreview({ issueId, parentId, content });
// Attachments uploaded in this composer session — see CommentInput for the
// rationale (drives both submit-time attachment_ids and editor previews).
const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);
@@ -87,6 +94,23 @@ function ReplyInput({
return result;
}, [uploadWithToast, issueId]);
+ useEffect(() => {
+ const visible = new Set(triggerPreview.agents.map((agent) => agent.id));
+ setSuppressedAgentIds((prev) => {
+ const next = new Set([...prev].filter((id) => visible.has(id)));
+ return next.size === prev.size ? prev : next;
+ });
+ }, [triggerPreview.agents]);
+
+ const toggleSuppressedAgent = useCallback((agentId: string) => {
+ setSuppressedAgentIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(agentId)) next.delete(agentId);
+ else next.add(agentId);
+ return next;
+ });
+ }, []);
+
const handleSubmit = async () => {
const content = editorRef.current?.getMarkdown()?.replace(/(\n\s*)+$/, "").trim();
if (!content || submitting) return;
@@ -96,11 +120,20 @@ function ReplyInput({
const activeIds = pendingAttachments
.filter((a) => contentReferencesAttachment(content, a))
.map((a) => a.id);
+ const suppressAgentIds = triggerPreview.agents
+ .filter((agent) => suppressedAgentIds.has(agent.id))
+ .map((agent) => agent.id);
setSubmitting(true);
try {
- await onSubmit(content, activeIds.length > 0 ? activeIds : undefined);
+ await onSubmit(
+ content,
+ activeIds.length > 0 ? activeIds : undefined,
+ suppressAgentIds.length > 0 ? suppressAgentIds : undefined,
+ );
editorRef.current?.clearContent();
+ setContent("");
setIsEmpty(true);
+ setSuppressedAgentIds(new Set());
setPendingAttachments([]);
if (draftKey) clearDraft(draftKey);
} finally {
@@ -131,6 +164,7 @@ function ReplyInput({
defaultValue={initialDraft}
placeholder={placeholderText}
onUpdate={(md) => {
+ setContent(md);
setIsEmpty(!md.trim());
if (draftKey) {
if (md.trim().length > 0) setDraft(draftKey, md);
@@ -146,6 +180,13 @@ function ReplyInput({
slashCommandMode="command"
/>
</div>
+ <div className="absolute bottom-0 left-0 right-24 min-w-0">
+ <CommentTriggerChips
+ agents={triggerPreview.agents}
+ suppressedAgentIds={suppressedAgentIds}
+ onToggle={toggleSuppressedAgent}
+ />
+ </div>
<div className="absolute bottom-0 right-0 flex items-center gap-1">
<FileUploadButton
size="sm"
diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.test.ts b/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
new file mode 100644
index 0000000000..2bc9b53a89
--- /dev/null
+++ b/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
@@ -0,0 +1,175 @@
+import { createElement, type ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { api } from "@multica/core/api";
+import {
+ commentTriggerPreviewSignature,
+ isNoteCommentDraft,
+ useCommentTriggerPreview,
+} from "./use-comment-trigger-preview";
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ previewCommentTriggers: vi.fn(),
+ },
+}));
+
+const previewCommentTriggers = vi.mocked(api.previewCommentTriggers);
+
+function createWrapper() {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ },
+ });
+
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return createElement(QueryClientProvider, { client: queryClient }, children);
+ };
+}
+
+async function advancePreviewDebounce() {
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ await act(async () => {});
+}
+
+describe("useCommentTriggerPreview", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ previewCommentTriggers.mockResolvedValue({ agents: [] });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ previewCommentTriggers.mockReset();
+ });
+
+ it("debounces preview and sends the latest content for an unchanged signature", async () => {
+ const { rerender } = renderHook(
+ ({ content }) => useCommentTriggerPreview({ issueId: "issue-1", content }),
+ {
+ wrapper: createWrapper(),
+ initialProps: { content: "hello" },
+ },
+ );
+
+ rerender({ content: "hello with more ordinary text" });
+ expect(previewCommentTriggers).not.toHaveBeenCalled();
+
+ await advancePreviewDebounce();
+
+ expect(previewCommentTriggers).toHaveBeenCalledTimes(1);
+ expect(previewCommentTriggers).toHaveBeenCalledWith(
+ "issue-1",
+ "hello with more ordinary text",
+ undefined,
+ );
+ });
+
+ it("uses the TanStack Query cache when the debounced signature repeats", async () => {
+ const agentA = "00000000-0000-0000-0000-000000000001";
+ const content = `[@A](mention://agent/${agentA})`;
+ const { rerender } = renderHook(
+ ({ content }) => useCommentTriggerPreview({ issueId: "issue-1", content }),
+ {
+ wrapper: createWrapper(),
+ initialProps: { content },
+ },
+ );
+
+ await advancePreviewDebounce();
+ expect(previewCommentTriggers).toHaveBeenCalledTimes(1);
+
+ rerender({ content: "" });
+ rerender({ content });
+ await advancePreviewDebounce();
+
+ expect(previewCommentTriggers).toHaveBeenCalledTimes(1);
+ });
+
+ it("fetches again when routing mention tokens change", async () => {
+ const agentA = "00000000-0000-0000-0000-000000000001";
+ const agentB = "00000000-0000-0000-0000-000000000002";
+ const { rerender } = renderHook(
+ ({ content }) => useCommentTriggerPreview({ issueId: "issue-1", content }),
+ {
+ wrapper: createWrapper(),
+ initialProps: { content: `[@A](mention://agent/${agentA})` },
+ },
+ );
+
+ await advancePreviewDebounce();
+ expect(previewCommentTriggers).toHaveBeenCalledTimes(1);
+
+ rerender({ content: `[@A](mention://agent/${agentA}) [@B](mention://agent/${agentB})` });
+ await advancePreviewDebounce();
+
+ expect(previewCommentTriggers).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not preview note drafts", async () => {
+ const agentA = "00000000-0000-0000-0000-000000000001";
+ const { result } = renderHook(
+ () => useCommentTriggerPreview({
+ issueId: "issue-1",
+ content: `/note [@A](mention://agent/${agentA})`,
+ }),
+ { wrapper: createWrapper() },
+ );
+
+ await advancePreviewDebounce();
+
+ expect(result.current).toEqual({ agents: [] });
+ expect(previewCommentTriggers).not.toHaveBeenCalled();
+ });
+});
+
+describe("commentTriggerPreviewSignature", () => {
+ it("ignores ordinary text changes", () => {
+ expect(commentTriggerPreviewSignature("hello")).toBe(
+ commentTriggerPreviewSignature("hello with more ordinary text"),
+ );
+ });
+
+ it("changes when routing mentions change", () => {
+ const agentA = "00000000-0000-0000-0000-000000000001";
+ const agentB = "00000000-0000-0000-0000-000000000002";
+
+ expect(commentTriggerPreviewSignature(`[@A](mention://agent/${agentA})`)).not.toBe(
+ commentTriggerPreviewSignature(`[@A](mention://agent/${agentA}) [@B](mention://agent/${agentB})`),
+ );
+ });
+
+ it("tracks @all but ignores issue cross-references", () => {
+ const issueID = "00000000-0000-0000-0000-000000000003";
+
+ expect(commentTriggerPreviewSignature(`See [MUL-1](mention://issue/${issueID})`)).toBe(
+ commentTriggerPreviewSignature("plain text"),
+ );
+ expect(commentTriggerPreviewSignature("[@all](mention://all/all)")).not.toBe(
+ commentTriggerPreviewSignature("plain text"),
+ );
+ });
+
+ it("treats note commands as empty", () => {
+ const agentA = "00000000-0000-0000-0000-000000000001";
+
+ expect(commentTriggerPreviewSignature(`/note [@A](mention://agent/${agentA})`)).toBe("empty");
+ expect(commentTriggerPreviewSignature(` /NOTE\n[@A](mention://agent/${agentA})`)).toBe("empty");
+ expect(commentTriggerPreviewSignature(`/notes [@A](mention://agent/${agentA})`)).not.toBe("empty");
+ expect(commentTriggerPreviewSignature(`/ note [@A](mention://agent/${agentA})`)).not.toBe("empty");
+ });
+});
+
+describe("isNoteCommentDraft", () => {
+ it("matches the reserved note prefix only as the first token", () => {
+ expect(isNoteCommentDraft("/note")).toBe(true);
+ expect(isNoteCommentDraft(" \t/Note keep this human-only")).toBe(true);
+ expect(isNoteCommentDraft("/notes keep this routable")).toBe(false);
+ expect(isNoteCommentDraft("/ note keep this routable")).toBe(false);
+ expect(isNoteCommentDraft("please /note later")).toBe(false);
+ });
+});
diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.ts b/packages/views/issues/hooks/use-comment-trigger-preview.ts
new file mode 100644
index 0000000000..60aaf2a0da
--- /dev/null
+++ b/packages/views/issues/hooks/use-comment-trigger-preview.ts
@@ -0,0 +1,90 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { api } from "@multica/core/api";
+import { issueKeys } from "@multica/core/issues/queries";
+import type { CommentTriggerPreviewAgent } from "@multica/core/types";
+
+const COMMENT_TRIGGER_PREVIEW_DEBOUNCE_MS = 300;
+const MENTION_RE = /\[@?(.+?)\]\(mention:\/\/(member|agent|squad|issue|all)\/([0-9a-fA-F-]+|all)\)/g;
+const NOTE_COMMAND_RE = /^\/note(?:$|\s)/i;
+
+export interface UseCommentTriggerPreviewResult {
+ agents: CommentTriggerPreviewAgent[];
+}
+
+export function isNoteCommentDraft(content: string): boolean {
+ return NOTE_COMMAND_RE.test(content.replace(/^[ \t\r\n]+/, ""));
+}
+
+export function commentTriggerPreviewSignature(content: string): string {
+ if (!content.trim() || isNoteCommentDraft(content)) return "empty";
+
+ const seen = new Set<string>();
+ const tokens: string[] = [];
+ for (const match of content.matchAll(MENTION_RE)) {
+ const type = match[2];
+ const id = match[3];
+ if (!type || !id || type === "issue") continue;
+ const token = `${type}:${id}`;
+ if (seen.has(token)) continue;
+ seen.add(token);
+ tokens.push(token);
+ }
+
+ return `nonempty|${tokens.join(",")}`;
+}
+
+function useDebouncedSignature(signature: string) {
+ const [debouncedSignature, setDebouncedSignature] = useState("empty");
+
+ useEffect(() => {
+ if (signature === "empty") {
+ setDebouncedSignature("empty");
+ return;
+ }
+
+ const timer = window.setTimeout(() => {
+ setDebouncedSignature(signature);
+ }, COMMENT_TRIGGER_PREVIEW_DEBOUNCE_MS);
+
+ return () => window.clearTimeout(timer);
+ }, [signature]);
+
+ return debouncedSignature;
+}
+
+export function useCommentTriggerPreview({
+ issueId,
+ parentId,
+ content,
+}: {
+ issueId: string;
+ parentId?: string;
+ content: string;
+}): UseCommentTriggerPreviewResult {
+ const signature = useMemo(() => commentTriggerPreviewSignature(content), [content]);
+ const debouncedSignature = useDebouncedSignature(signature);
+ const contentRef = useRef(content);
+
+ useEffect(() => {
+ contentRef.current = content;
+ }, [content]);
+
+ const previewQuery = useQuery({
+ queryKey: [...issueKeys.commentTriggerPreview(issueId), parentId ?? "", debouncedSignature],
+ queryFn: () => api.previewCommentTriggers(issueId, contentRef.current, parentId),
+ enabled: signature !== "empty" && debouncedSignature !== "empty",
+ retry: false,
+ staleTime: Infinity,
+ });
+
+ // Loading and errors intentionally surface as "no agents": the preview is
+ // an enhancement, and the composer renders nothing for an empty list.
+ if (signature === "empty" || debouncedSignature === "empty") {
+ return { agents: [] };
+ }
+
+ return { agents: previewQuery.data?.agents ?? [] };
+}
diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.ts
index 21b09fa659..ccef7e4809 100644
--- a/packages/views/issues/hooks/use-issue-timeline.ts
+++ b/packages/views/issues/hooks/use-issue-timeline.ts
@@ -259,10 +259,10 @@ export function useIssueTimeline(issueId: string, userId?: string) {
// --- Mutation functions ---
const submitComment = useCallback(
- async (content: string, attachmentIds?: string[]) => {
+ async (content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => {
if (!content.trim() || !userId) return;
try {
- await createComment({ content, attachmentIds });
+ await createComment({ content, attachmentIds, suppressAgentIds });
} catch (err) {
toast.error(
err instanceof Error && err.message
@@ -275,7 +275,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {
);
const submitReply = useCallback(
- async (parentId: string, content: string, attachmentIds?: string[]) => {
+ async (parentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => {
if (!content.trim() || !userId) return;
try {
await createComment({
@@ -283,6 +283,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {
type: "comment",
parentId,
attachmentIds,
+ suppressAgentIds,
});
} catch (err) {
toast.error(
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 0865d11051..c61559fe6e 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -275,6 +275,26 @@
"reply_count_other": "{{count}} replies",
"leave_comment_placeholder": "Leave a comment...",
"send_tooltip": "Send",
+ "trigger_source_issue_assignee": "assignee",
+ "trigger_source_mention_agent": "@mention",
+ "trigger_source_mention_squad_leader": "squad",
+ "trigger_source_unknown": "trigger",
+ "trigger_suppressed": "not this time",
+ "trigger_reason_issue_assignee": "{{name}} is assigned here and will be notified by this comment.",
+ "trigger_reason_mention_agent": "{{name}} is mentioned in this comment.",
+ "trigger_reason_mention_squad_leader": "{{name}} leads a squad mentioned in this comment.",
+ "trigger_reason_unknown": "{{name}} will be triggered by this comment.",
+ "trigger_will_start": "{{name}} will start working",
+ "trigger_will_skip": "{{name}} won't be triggered this time",
+ "trigger_will_start_count_one": "{{count}} agent will start working",
+ "trigger_will_start_count_other": "{{count}} agents will start working",
+ "trigger_starts_now": "It will start working right away.",
+ "trigger_starts_when_online": "It is offline now and will start once online.",
+ "trigger_click_to_skip": "Click to skip triggering this time.",
+ "trigger_click_to_manage": "Click to manage who gets triggered this time.",
+ "trigger_click_to_restore": "Won't be triggered this time. Click to restore.",
+ "trigger_preview_title": "This comment will trigger",
+ "trigger_chip_aria": "{{name}} trigger: {{state}}",
"resolve": {
"resolve_thread_action": "Resolve thread",
"unresolve_thread_action": "Unresolve thread",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index f974a61445..22fe5b3422 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -267,6 +267,25 @@
"reply_count_other": "返信 {{count}} 件",
"leave_comment_placeholder": "コメントを残す...",
"send_tooltip": "送信",
+ "trigger_source_issue_assignee": "担当",
+ "trigger_source_mention_agent": "@メンション",
+ "trigger_source_mention_squad_leader": "Squad",
+ "trigger_source_unknown": "トリガー",
+ "trigger_suppressed": "今回は実行しない",
+ "trigger_reason_issue_assignee": "{{name}} はこのイシューの担当で、このコメントで通知されます。",
+ "trigger_reason_mention_agent": "このコメントで {{name}} がメンションされています。",
+ "trigger_reason_mention_squad_leader": "{{name}} はメンションされた Squad のリーダーです。",
+ "trigger_reason_unknown": "このコメントで {{name}} がトリガーされます。",
+ "trigger_will_start": "{{name}} が作業を開始します",
+ "trigger_will_skip": "{{name}} は今回トリガーされません",
+ "trigger_will_start_count_other": "{{count}} 体のエージェントが作業を開始します",
+ "trigger_starts_now": "すぐに作業を開始します。",
+ "trigger_starts_when_online": "現在オフラインのため、オンラインになり次第開始します。",
+ "trigger_click_to_skip": "クリックすると今回はトリガーされません。",
+ "trigger_click_to_manage": "クリックして今回のトリガー対象を管理します。",
+ "trigger_click_to_restore": "今回はトリガーされません。クリックで元に戻せます。",
+ "trigger_preview_title": "このコメントでトリガーされる対象",
+ "trigger_chip_aria": "{{name}} のトリガー: {{state}}",
"resolve": {
"resolve_thread_action": "スレッドを解決",
"unresolve_thread_action": "スレッドの解決を取り消す",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index ffad6150b7..6e0a474672 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -275,6 +275,25 @@
"reply_count_other": "답글 {{count}}개",
"leave_comment_placeholder": "댓글 남기기...",
"send_tooltip": "보내기",
+ "trigger_source_issue_assignee": "담당자",
+ "trigger_source_mention_agent": "@멘션",
+ "trigger_source_mention_squad_leader": "Squad",
+ "trigger_source_unknown": "트리거",
+ "trigger_suppressed": "이번에는 실행 안 함",
+ "trigger_reason_issue_assignee": "{{name}}님은 이 이슈의 담당자이며 이 댓글로 알림을 받습니다.",
+ "trigger_reason_mention_agent": "이 댓글에서 {{name}}님을 멘션했습니다.",
+ "trigger_reason_mention_squad_leader": "{{name}}님은 멘션된 Squad의 리더입니다.",
+ "trigger_reason_unknown": "이 댓글로 {{name}}님이 트리거됩니다.",
+ "trigger_will_start": "{{name}}이(가) 작업을 시작합니다",
+ "trigger_will_skip": "{{name}}은(는) 이번에 트리거되지 않습니다",
+ "trigger_will_start_count_other": "에이전트 {{count}}개가 작업을 시작합니다",
+ "trigger_starts_now": "바로 작업을 시작합니다.",
+ "trigger_starts_when_online": "현재 오프라인이며 온라인이 되면 시작합니다.",
+ "trigger_click_to_skip": "클릭하면 이번에는 트리거되지 않습니다.",
+ "trigger_click_to_manage": "클릭하여 이번 트리거 대상을 관리합니다.",
+ "trigger_click_to_restore": "이번에는 트리거되지 않습니다. 클릭하면 복원됩니다.",
+ "trigger_preview_title": "이 댓글로 트리거되는 대상",
+ "trigger_chip_aria": "{{name}} 트리거: {{state}}",
"resolve": {
"resolve_thread_action": "스레드 해결",
"unresolve_thread_action": "스레드 해결 취소",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index de08d639d4..f8a4820a8f 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -272,6 +272,25 @@
"reply_count_other": "{{count}} 条回复",
"leave_comment_placeholder": "留下评论...",
"send_tooltip": "发送",
+ "trigger_source_issue_assignee": "assignee",
+ "trigger_source_mention_agent": "@mention",
+ "trigger_source_mention_squad_leader": "squad",
+ "trigger_source_unknown": "将触发",
+ "trigger_suppressed": "本次不触发",
+ "trigger_reason_issue_assignee": "{{name}} 是当前 issue 的 assignee,这条评论会唤醒它。",
+ "trigger_reason_mention_agent": "这条评论 @ 了 {{name}}。",
+ "trigger_reason_mention_squad_leader": "{{name}} 是被 @ Squad 的 leader。",
+ "trigger_reason_unknown": "这条评论会触发 {{name}}。",
+ "trigger_will_start": "{{name}} 将开始工作",
+ "trigger_will_skip": "{{name}} 本次不触发",
+ "trigger_will_start_count_other": "{{count}} 个智能体将开始工作",
+ "trigger_starts_now": "将立即开始工作。",
+ "trigger_starts_when_online": "当前离线,上线后开始。",
+ "trigger_click_to_skip": "点击后本次不触发。",
+ "trigger_click_to_manage": "点击管理本次触发对象。",
+ "trigger_click_to_restore": "本次不触发,点击恢复。",
+ "trigger_preview_title": "这条评论将触发",
+ "trigger_chip_aria": "{{name}} 触发状态:{{state}}",
"resolve": {
"resolve_thread_action": "解决该讨论",
"unresolve_thread_action": "重新打开讨论",
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index d2674d634a..3033ad0121 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -704,6 +704,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.GetIssue)
r.Put("/", h.UpdateIssue)
r.Delete("/", h.DeleteIssue)
+ r.Post("/comments/trigger-preview", h.PreviewCommentTriggers)
r.Post("/comments", h.CreateComment)
r.Get("/comments", h.ListComments)
r.Get("/timeline", h.ListTimeline)
diff --git a/server/internal/handler/agent_access_test.go b/server/internal/handler/agent_access_test.go
index 26b2e5c44b..6540c7adc3 100644
--- a/server/internal/handler/agent_access_test.go
+++ b/server/internal/handler/agent_access_test.go
@@ -487,7 +487,7 @@ func TestMentionAgent_RejectsCrossWorkspaceAgentUUID(t *testing.T) {
t.Fatalf("count tasks before: %v", err)
}
- testHandler.enqueueMentionedAgentTasks(ctx, issue, comment, nil, "member", testUserID)
+ enqueueMentionedAgentTasksForTest(t, ctx, issue, comment, nil, "member", testUserID)
var afterCount int
if err := testPool.QueryRow(ctx,
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index f0089218f8..019a42612b 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -768,10 +768,112 @@ func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsAr
}
type CreateCommentRequest struct {
- Content string `json:"content"`
- Type string `json:"type"`
- ParentID *string `json:"parent_id"`
- AttachmentIDs []string `json:"attachment_ids"`
+ Content string `json:"content"`
+ Type string `json:"type"`
+ ParentID *string `json:"parent_id"`
+ AttachmentIDs []string `json:"attachment_ids"`
+ SuppressAgentIDs []string `json:"suppress_agent_ids"`
+}
+
+type CommentTriggerPreviewRequest struct {
+ Content string `json:"content"`
+ ParentID *string `json:"parent_id"`
+}
+
+type CommentTriggerPreviewResponse struct {
+ Agents []CommentTriggerAgentResponse `json:"agents"`
+}
+
+type CommentTriggerAgentResponse struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ AvatarURL *string `json:"avatar_url,omitempty"`
+ Source string `json:"source"`
+ Reason string `json:"reason"`
+}
+
+type commentAgentTriggerSource string
+
+const (
+ commentTriggerSourceIssueAssignee commentAgentTriggerSource = "issue_assignee"
+ commentTriggerSourceMentionAgent commentAgentTriggerSource = "mention_agent"
+ commentTriggerSourceMentionSquadLeader commentAgentTriggerSource = "mention_squad_leader"
+)
+
+type commentAgentTrigger struct {
+ Agent db.Agent
+ Source commentAgentTriggerSource
+ Squad *db.Squad
+}
+
+func commentAgentTriggerReason(trigger commentAgentTrigger) string {
+ switch trigger.Source {
+ case commentTriggerSourceIssueAssignee:
+ return "Current issue assignment will trigger this agent."
+ case commentTriggerSourceMentionAgent:
+ return "This agent was mentioned in the comment."
+ case commentTriggerSourceMentionSquadLeader:
+ return "A mentioned squad will trigger its leader."
+ default:
+ return "This comment will trigger this agent."
+ }
+}
+
+func commentAgentTriggerToResponse(trigger commentAgentTrigger) CommentTriggerAgentResponse {
+ return CommentTriggerAgentResponse{
+ ID: uuidToString(trigger.Agent.ID),
+ Name: trigger.Agent.Name,
+ AvatarURL: textToPtr(trigger.Agent.AvatarUrl),
+ Source: string(trigger.Source),
+ Reason: commentAgentTriggerReason(trigger),
+ }
+}
+
+func (h *Handler) PreviewCommentTriggers(w http.ResponseWriter, r *http.Request) {
+ issueID := chi.URLParam(r, "id")
+ issue, ok := h.loadIssueForUser(w, r, issueID)
+ if !ok {
+ return
+ }
+
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ var req CommentTriggerPreviewRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+
+ var parentComment *db.Comment
+ if req.ParentID != nil {
+ parentID, ok := parseUUIDOrBadRequest(w, *req.ParentID, "parent_id")
+ if !ok {
+ return
+ }
+ parent, err := h.Queries.GetComment(r.Context(), parentID)
+ if err != nil || uuidToString(parent.IssueID) != uuidToString(issue.ID) {
+ writeError(w, http.StatusBadRequest, "invalid parent comment")
+ return
+ }
+ parentComment = &parent
+ }
+
+ content := mention.ExpandIssueIdentifiers(r.Context(), h.Queries, issue.WorkspaceID, req.Content)
+ if content == "" {
+ writeJSON(w, http.StatusOK, CommentTriggerPreviewResponse{Agents: []CommentTriggerAgentResponse{}})
+ return
+ }
+
+ actorType, actorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))
+ triggers := h.computeCommentAgentTriggers(r.Context(), issue, content, parentComment, actorType, actorID)
+ resp := CommentTriggerPreviewResponse{Agents: make([]CommentTriggerAgentResponse, 0, len(triggers))}
+ for _, trigger := range triggers {
+ resp.Agents = append(resp.Agents, commentAgentTriggerToResponse(trigger))
+ }
+ writeJSON(w, http.StatusOK, resp)
}
func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
@@ -821,6 +923,10 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ suppressAgentIDs, ok := parseUUIDSliceOrBadRequest(w, req.SuppressAgentIDs, "suppress_agent_ids")
+ if !ok {
+ return
+ }
// Determine author identity: agent (via X-Agent-ID header) or member.
authorType, authorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))
@@ -925,14 +1031,14 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
// must keep the resolved root in sync.
h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(issue.WorkspaceID), authorType, authorID)
- h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID)
+ h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, suppressAgentIDs)
writeJSON(w, http.StatusCreated, resp)
}
// 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 — see triggerTasksForComment.
+// any other comment but never triggers an agent.
const noteCommentPrefix = "/note"
// isNoteComment reports whether content opts out of agent triggering via the
@@ -948,30 +1054,147 @@ func isNoteComment(content string) bool {
return strings.EqualFold(firstToken, noteCommentPrefix)
}
-func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID string) {
- // A comment opening with the reserved /note prefix is a human-only note: it
- // is recorded like any other comment but must not wake ANY agent. This guard
- // lives at the single chokepoint so it covers all three trigger paths below
- // (assignee, squad leader, and @mentioned agents). Gating only
- // shouldEnqueueOnComment would still let "/note @agent ..." reach an agent
- // through the mention path.
+func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID string, suppressAgentIDs []pgtype.UUID) {
if isNoteComment(comment.Content) {
return
}
+ triggers := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID)
+ triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)
+ h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
+}
+
+func filterSuppressedCommentAgentTriggers(triggers []commentAgentTrigger, suppressAgentIDs []pgtype.UUID) []commentAgentTrigger {
+ if len(triggers) == 0 || len(suppressAgentIDs) == 0 {
+ return triggers
+ }
+ suppressed := make(map[string]struct{}, len(suppressAgentIDs))
+ for _, id := range suppressAgentIDs {
+ if id.Valid {
+ suppressed[uuidToString(id)] = struct{}{}
+ }
+ }
+ if len(suppressed) == 0 {
+ return triggers
+ }
+ filtered := make([]commentAgentTrigger, 0, len(triggers))
+ for _, trigger := range triggers {
+ if _, ok := suppressed[uuidToString(trigger.Agent.ID)]; ok {
+ continue
+ }
+ filtered = append(filtered, trigger)
+ }
+ return filtered
+}
+
+func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, triggers []commentAgentTrigger) {
+ for _, trigger := range triggers {
+ switch trigger.Source {
+ case commentTriggerSourceIssueAssignee:
+ if trigger.Squad != nil {
+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {
+ slog.Warn("enqueue squad leader task failed",
+ "issue_id", uuidToString(issue.ID),
+ "squad_id", uuidToString(trigger.Squad.ID),
+ "leader_id", uuidToString(trigger.Agent.ID),
+ "error", err)
+ }
+ continue
+ }
+ if _, err := h.TaskService.EnqueueTaskForIssue(ctx, issue, triggerCommentID); err != nil {
+ slog.Warn("enqueue agent task on comment failed", "issue_id", uuidToString(issue.ID), "error", err)
+ }
+ case commentTriggerSourceMentionSquadLeader:
+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {
+ slog.Warn("enqueue squad leader mention task failed",
+ "issue_id", uuidToString(issue.ID),
+ "agent_id", uuidToString(trigger.Agent.ID),
+ "error", err)
+ }
+ case commentTriggerSourceMentionAgent:
+ if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {
+ slog.Warn("enqueue mention agent task failed",
+ "issue_id", uuidToString(issue.ID),
+ "agent_id", uuidToString(trigger.Agent.ID),
+ "error", err)
+ }
+ }
+ }
+}
+
+func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, actorType, actorID string) []commentAgentTrigger {
+ if isNoteComment(content) {
+ return nil
+ }
+
+ seen := make(map[string]struct{})
+ triggers := make([]commentAgentTrigger, 0, 2)
+ add := func(trigger commentAgentTrigger) {
+ id := uuidToString(trigger.Agent.ID)
+ if _, ok := seen[id]; ok {
+ return
+ }
+ seen[id] = struct{}{}
+ triggers = append(triggers, trigger)
+ }
if actorType == "member" && h.shouldEnqueueOnComment(ctx, issue, actorType, actorID) &&
- !h.commentMentionsOthersButNotAssignee(comment.Content, issue) &&
- !h.isReplyToMemberThread(ctx, parentComment, comment.Content, issue) {
- if _, err := h.TaskService.EnqueueTaskForIssue(ctx, issue, comment.ID); err != nil {
- slog.Warn("enqueue agent task on comment failed", "issue_id", uuidToString(issue.ID), "error", err)
+ !h.commentMentionsOthersButNotAssignee(content, issue) &&
+ !h.isReplyToMemberThread(ctx, parentComment, content, issue) {
+ if agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
+ ID: issue.AssigneeID,
+ WorkspaceID: issue.WorkspaceID,
+ }); err == nil {
+ add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceIssueAssignee})
}
}
- if h.shouldEnqueueSquadLeaderOnComment(ctx, issue, comment.Content, actorType, actorID) {
- h.enqueueSquadLeaderTask(ctx, issue, comment.ID, actorType, actorID)
+ if trigger, ok := h.computeAssignedSquadLeaderCommentTrigger(ctx, issue, content, actorType, actorID); ok {
+ add(trigger)
}
- h.enqueueMentionedAgentTasks(ctx, issue, comment, parentComment, actorType, actorID)
+ for _, trigger := range h.computeMentionedAgentCommentTriggers(ctx, issue, content, parentComment, actorType, actorID) {
+ add(trigger)
+ }
+
+ return triggers
+}
+
+func (h *Handler) computeAssignedSquadLeaderCommentTrigger(ctx context.Context, issue db.Issue, content, authorType, authorID string) (commentAgentTrigger, bool) {
+ if !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {
+ return commentAgentTrigger{}, false
+ }
+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: issue.AssigneeID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ return commentAgentTrigger{}, false
+ }
+ if authorType == "agent" && authorID == uuidToString(squad.LeaderID) &&
+ h.lastTaskWasLeader(ctx, issue.ID, squad.LeaderID) {
+ return commentAgentTrigger{}, false
+ }
+ if authorType == "member" && commentMentionsAnyone(content) {
+ return commentAgentTrigger{}, false
+ }
+ agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
+ ID: squad.LeaderID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
+ return commentAgentTrigger{}, false
+ }
+ if !h.canAccessPrivateAgent(ctx, agent, authorType, authorID, uuidToString(issue.WorkspaceID)) {
+ return commentAgentTrigger{}, false
+ }
+ hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
+ IssueID: issue.ID,
+ AgentID: squad.LeaderID,
+ })
+ if err != nil || hasPending {
+ return commentAgentTrigger{}, false
+ }
+ return commentAgentTrigger{Agent: agent, Source: commentTriggerSourceIssueAssignee, Squad: &squad}, true
}
// commentMentionsOthersButNotAssignee returns true if the comment @mentions
@@ -1093,11 +1316,11 @@ func shouldInheritParentMentions(parentComment *db.Comment, replyMentions []util
return parentComment.AuthorType == "member"
}
-// enqueueMentionedAgentTasks parses @agent mentions from comment content and
-// enqueues a task for each mentioned agent. When parentComment is non-nil
-// (i.e. the comment is a reply), mentions from the parent (thread root) are
-// also included so that agents mentioned in the top-level comment are
-// re-triggered by subsequent replies in the same thread — unless the reply
+// computeMentionedAgentCommentTriggers parses @agent mentions from comment
+// content and returns a trigger for each mentioned agent. When parentComment
+// is non-nil (i.e. the comment is a reply), mentions from the parent (thread
+// root) are also included so that agents mentioned in the top-level comment
+// are re-triggered by subsequent replies in the same thread — unless the reply
// explicitly @mentions only non-agent entities (members, issues), which
// signals the user is talking to other people and not the agent.
// Skips agents with on_mention trigger disabled, and private agents mentioned
@@ -1109,12 +1332,22 @@ func shouldInheritParentMentions(parentComment *db.Comment, replyMentions []util
// dedupe and the natural queued/dispatched coalescing of the task queue.
// Note: no status gate here — @mention is an explicit action and should work
// even on done/cancelled issues (the agent can reopen the issue if needed).
-func (h *Handler) enqueueMentionedAgentTasks(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, authorType, authorID string) {
+func (h *Handler) computeMentionedAgentCommentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, authorType, authorID string) []commentAgentTrigger {
wsID := uuidToString(issue.WorkspaceID)
- mentions := util.ParseMentions(comment.Content)
+ mentions := util.ParseMentions(content)
if shouldInheritParentMentions(parentComment, mentions, authorType) {
mentions = util.ParseMentions(parentComment.Content)
}
+ triggers := make([]commentAgentTrigger, 0, len(mentions))
+ seen := make(map[string]struct{}, len(mentions))
+ add := func(trigger commentAgentTrigger) {
+ id := uuidToString(trigger.Agent.ID)
+ if _, ok := seen[id]; ok {
+ return
+ }
+ seen[id] = struct{}{}
+ triggers = append(triggers, trigger)
+ }
for _, m := range mentions {
if m.Type == "squad" {
// @squad mention → trigger the squad's leader agent.
@@ -1155,9 +1388,7 @@ func (h *Handler) enqueueMentionedAgentTasks(ctx context.Context, issue db.Issue
if err != nil || hasPending {
continue
}
- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, leaderID, comment.ID); err != nil {
- slog.Warn("enqueue squad leader mention task failed", "issue_id", uuidToString(issue.ID), "squad_id", m.ID, "error", err)
- }
+ add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionSquadLeader, Squad: &squad})
continue
}
if m.Type != "agent" {
@@ -1190,12 +1421,9 @@ func (h *Handler) enqueueMentionedAgentTasks(ctx context.Context, issue db.Issue
if err != nil || hasPending {
continue
}
- // Always use the current comment as the trigger so the agent reads the
- // actual reply that mentioned it, not the thread root.
- if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, agentUUID, comment.ID); err != nil {
- slog.Warn("enqueue mention agent task failed", "issue_id", uuidToString(issue.ID), "agent_id", m.ID, "error", err)
- }
+ add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent})
}
+ return triggers
}
func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
@@ -1318,7 +1546,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
}
- h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID)
+ h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, nil)
}
}
diff --git a/server/internal/handler/comment_trigger_preview_test.go b/server/internal/handler/comment_trigger_preview_test.go
new file mode 100644
index 0000000000..cc3ce5bb26
--- /dev/null
+++ b/server/internal/handler/comment_trigger_preview_test.go
@@ -0,0 +1,322 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func createCommentTriggerPreviewIssue(t *testing.T, title string, assigneeType, assigneeID string) string {
+ t.Helper()
+ ctx := context.Background()
+
+ var number int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 1
+ WHERE id = $1 RETURNING issue_counter
+ `, testWorkspaceID).Scan(&number); err != nil {
+ t.Fatalf("next issue number: %v", err)
+ }
+
+ var assigneeTypeArg any
+ var assigneeIDArg any
+ if assigneeType != "" {
+ assigneeTypeArg = assigneeType
+ }
+ if assigneeID != "" {
+ assigneeIDArg = assigneeID
+ }
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, creator_type, creator_id, title, assignee_type, assignee_id, number)
+ VALUES ($1, 'member', $2, $3, $4, $5, $6)
+ RETURNING id
+ `, testWorkspaceID, testUserID, title, assigneeTypeArg, assigneeIDArg, number).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ return issueID
+}
+
+func previewCommentTriggersForTest(t *testing.T, issueID string, body map[string]any) CommentTriggerPreviewResponse {
+ t.Helper()
+
+ w := httptest.NewRecorder()
+ r := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments/trigger-preview", body)
+ r = withURLParam(r, "id", issueID)
+ testHandler.PreviewCommentTriggers(w, r)
+ if w.Code != http.StatusOK {
+ t.Fatalf("PreviewCommentTriggers: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp CommentTriggerPreviewResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode preview response: %v", err)
+ }
+ return resp
+}
+
+func postCommentForTriggerPreviewTest(t *testing.T, issueID string, body map[string]any) {
+ t.Helper()
+
+ w := httptest.NewRecorder()
+ r := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", body)
+ r = withURLParam(r, "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func countQueuedCommentTriggerTasks(t *testing.T, issueID, agentID string) int {
+ t.Helper()
+
+ var n int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, agentID).Scan(&n); err != nil {
+ t.Fatalf("count queued tasks: %v", err)
+ }
+ return n
+}
+
+func TestPreviewCommentTriggers_ReturnsMentionedAgentsAndSuppressFiltersCreate(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ agentA := createHandlerTestAgent(t, "Preview Mention A", nil)
+ agentB := createHandlerTestAgent(t, "Preview Mention B", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "comment trigger preview mentions", "", "")
+ content := fmt.Sprintf("[@A](mention://agent/%s) [@B](mention://agent/%s) please inspect", agentA, agentB)
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": content})
+ if got := len(preview.Agents); got != 2 {
+ t.Fatalf("expected 2 preview agents, got %d: %+v", got, preview.Agents)
+ }
+ for _, agent := range preview.Agents {
+ if agent.Source != string(commentTriggerSourceMentionAgent) {
+ t.Fatalf("preview source = %q, want %q", agent.Source, commentTriggerSourceMentionAgent)
+ }
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": content,
+ "suppress_agent_ids": []string{agentB},
+ })
+
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentA); got != 1 {
+ t.Fatalf("unsuppressed mentioned agent queued tasks = %d, want 1", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentB); got != 0 {
+ t.Fatalf("suppressed mentioned agent queued tasks = %d, want 0", got)
+ }
+}
+
+func TestCreateComment_SuppressUnknownAgentIDIsNoop(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "Suppress Noop Agent", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "comment trigger suppress noop", "", "")
+ content := fmt.Sprintf("[@Agent](mention://agent/%s) please inspect", agentID)
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": content,
+ "suppress_agent_ids": []string{
+ "00000000-0000-0000-0000-000000000001",
+ },
+ })
+
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 1 {
+ t.Fatalf("mentioned agent queued tasks = %d, want 1", got)
+ }
+}
+
+func TestPreviewCommentTriggers_NoteReturnsNoAgents(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "Preview Note Agent", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "comment trigger note", "agent", agentID)
+ content := fmt.Sprintf("/note [@Agent](mention://agent/%s) human-only context", agentID)
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": content})
+ if got := len(preview.Agents); got != 0 {
+ t.Fatalf("note preview agents = %d, want 0: %+v", got, preview.Agents)
+ }
+}
+
+func TestCreateComment_NoteMentionDoesNotQueueAgent(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "Create Note Agent", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "comment trigger create note", "agent", agentID)
+ content := fmt.Sprintf("/note [@Agent](mention://agent/%s) human-only context", agentID)
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{"content": content})
+
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 0 {
+ t.Fatalf("note create queued tasks = %d, want 0", got)
+ }
+}
+
+func TestPreviewCommentTriggers_AssigneeAndSuppress(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "Preview Assignee", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "comment trigger assignee", "agent", agentID)
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": "can you continue here?"})
+ if got := len(preview.Agents); got != 1 {
+ t.Fatalf("expected 1 assignee preview agent, got %d: %+v", got, preview.Agents)
+ }
+ if preview.Agents[0].ID != agentID {
+ t.Fatalf("preview agent id = %s, want %s", preview.Agents[0].ID, agentID)
+ }
+ if preview.Agents[0].Source != string(commentTriggerSourceIssueAssignee) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceIssueAssignee)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "can you continue here?",
+ "suppress_agent_ids": []string{agentID},
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 0 {
+ t.Fatalf("suppressed assignee queued tasks = %d, want 0", got)
+ }
+}
+
+func TestPreviewCommentTriggers_AllSuppressesAssigneeAndPendingDedupes(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ agentID := createHandlerTestAgent(t, "Preview Dedup Assignee", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "comment trigger all pending", "agent", agentID)
+
+ allPreview := previewCommentTriggersForTest(t, issueID, map[string]any{
+ "content": "FYI [@all](mention://all/all)",
+ })
+ if got := len(allPreview.Agents); got != 0 {
+ t.Fatalf("@all preview agents = %d, want 0: %+v", got, allPreview.Agents)
+ }
+
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status)
+ VALUES ($1, $2, $3, 'queued')
+ `, agentID, handlerTestRuntimeID(t), issueID); err != nil {
+ t.Fatalf("seed queued task: %v", err)
+ }
+
+ pendingPreview := previewCommentTriggersForTest(t, issueID, map[string]any{
+ "content": "can you continue here?",
+ })
+ if got := len(pendingPreview.Agents); got != 0 {
+ t.Fatalf("pending preview agents = %d, want 0: %+v", got, pendingPreview.Agents)
+ }
+}
+
+func TestPreviewCommentTriggers_AssignedSquadLeaderAndSuppress(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ leaderID := createHandlerTestAgent(t, "Preview Squad Leader", nil)
+
+ var squadID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
+ VALUES ($1, $2, '', $3, $4)
+ RETURNING id
+ `, testWorkspaceID, "Preview Trigger Squad", leaderID, testUserID).Scan(&squadID); err != nil {
+ t.Fatalf("create squad: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID)
+ })
+
+ issueID := createCommentTriggerPreviewIssue(t, "comment trigger squad assignee", "squad", squadID)
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": "please coordinate this"})
+ if got := len(preview.Agents); got != 1 {
+ t.Fatalf("expected 1 squad leader preview agent, got %d: %+v", got, preview.Agents)
+ }
+ if preview.Agents[0].ID != leaderID {
+ t.Fatalf("preview leader id = %s, want %s", preview.Agents[0].ID, leaderID)
+ }
+ if preview.Agents[0].Source != string(commentTriggerSourceIssueAssignee) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceIssueAssignee)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "please coordinate this",
+ "suppress_agent_ids": []string{leaderID},
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, leaderID); got != 0 {
+ t.Fatalf("suppressed squad leader queued tasks = %d, want 0", got)
+ }
+}
+
+func TestPreviewCommentTriggers_MentionedSquadLeaderAndSuppress(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ leaderID := createHandlerTestAgent(t, "Preview Mentioned Squad Leader", nil)
+
+ var squadID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
+ VALUES ($1, $2, '', $3, $4)
+ RETURNING id
+ `, testWorkspaceID, "Preview Mentioned Trigger Squad", leaderID, testUserID).Scan(&squadID); err != nil {
+ t.Fatalf("create squad: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID)
+ })
+
+ issueID := createCommentTriggerPreviewIssue(t, "comment trigger mentioned squad", "", "")
+ content := fmt.Sprintf("[@Squad](mention://squad/%s) please take this", squadID)
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": content})
+ if got := len(preview.Agents); got != 1 {
+ t.Fatalf("expected 1 mentioned squad leader preview agent, got %d: %+v", got, preview.Agents)
+ }
+ if preview.Agents[0].ID != leaderID {
+ t.Fatalf("preview leader id = %s, want %s", preview.Agents[0].ID, leaderID)
+ }
+ if preview.Agents[0].Source != string(commentTriggerSourceMentionSquadLeader) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceMentionSquadLeader)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": content,
+ "suppress_agent_ids": []string{leaderID},
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, leaderID); got != 0 {
+ t.Fatalf("suppressed mentioned squad leader queued tasks = %d, want 0", got)
+ }
+}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index f010dbe2c3..3e7830cfc2 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -2561,7 +2561,7 @@ func (h *Handler) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bo
// conversational and can happen at any stage, including after completion
// (e.g. follow-up questions on a done issue).
//
-// Mirrors the private-agent gate that enqueueMentionedAgentTasks applies on the
+// Mirrors the private-agent gate that computeMentionedAgentCommentTriggers applies on the
// @mention path: once an owner/admin assigns a private agent to an issue, the
// agent's UUID is "welded" onto the issue and remains visible to every member
// who can view it. Without this check any of those members could dispatch a new
diff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.go
index 73c7e711e7..0482e5795b 100644
--- a/server/internal/handler/issue_child_done.go
+++ b/server/internal/handler/issue_child_done.go
@@ -230,14 +230,14 @@ func sanitizeMentionLabel(name string) string {
// the same squad, or its effective owner is the parent squad's leader. A
// squad leader already observes same-squad work through its own
// coordination cycle — the worker's completion comment wakes the leader
-// via shouldEnqueueSquadLeaderOnComment — so the child-done trigger would
+// via computeAssignedSquadLeaderCommentTrigger — so the child-done trigger would
// be redundant; this also closes the cross-squad shared-leader loop. The
// AGENT parent path intentionally has NO such guard (MUL-2808): a lone
// agent that decomposes its parent into sub-issues it owns itself has no
// other wake path, and waking the parent agent when its child finishes is
// a serial sub-task handoff across two DIFFERENT issues — explicitly not a
// self-loop per isAgentRunningOnIssue, and consistent with the @mention
-// self-trigger path (enqueueMentionedAgentTasks). Runaway re-triggering is
+// self-trigger path (computeMentionedAgentCommentTriggers). Runaway re-triggering is
// bounded by the idempotency guard below, not by suppressing the trigger.
// - Idempotency: HasPendingTaskForIssueAndAgent dedupes rapid-fire enqueues
// for the same parent (e.g. two children finishing back-to-back).
@@ -268,7 +268,7 @@ func (h *Handler) dispatchParentAssigneeTrigger(ctx context.Context, parent, chi
// other wake path, so the old "child owner == parent agent" guard silently
// stranded those parents (MUL-2808). Runaway re-triggering is prevented by
// the HasPendingTaskForIssueAndAgent dedup below, exactly as the @mention
-// self-trigger path relies on it (see enqueueMentionedAgentTasks).
+// self-trigger path relies on it (see computeMentionedAgentCommentTriggers).
func (h *Handler) triggerChildDoneAgent(ctx context.Context, parent db.Issue, triggerCommentID pgtype.UUID) {
agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
ID: parent.AssigneeID,
diff --git a/server/internal/handler/mention_self_trigger_test.go b/server/internal/handler/mention_self_trigger_test.go
index 63882dbb43..6a633a1853 100644
--- a/server/internal/handler/mention_self_trigger_test.go
+++ b/server/internal/handler/mention_self_trigger_test.go
@@ -8,10 +8,20 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
+// enqueueMentionedAgentTasksForTest mirrors the production comment path for
+// @mention triggers: compute the mention trigger set, then enqueue it. Kept as
+// a test helper so these integration tests keep asserting enqueue side effects
+// without preserving a production wrapper that nothing else calls.
+func enqueueMentionedAgentTasksForTest(t *testing.T, ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, authorType, authorID string) {
+ t.Helper()
+ triggers := testHandler.computeMentionedAgentCommentTriggers(ctx, issue, comment.Content, parentComment, authorType, authorID)
+ testHandler.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
+}
+
// selfMentionFixture wires the seeded "Handler Test Agent" as J plus two
// fresh issues so we can exercise the agent-self-mention path on the @mention
-// branch of enqueueMentionedAgentTasks. The three tests below cover the
-// behavior we want post-MUL-2338:
+// branch of computeMentionedAgentCommentTriggers. The three tests below cover
+// the behavior we want post-MUL-2338:
//
// - cross-issue self-mention enqueues (child→parent handoff between issues
// assigned to the same agent must not be swallowed)
@@ -158,7 +168,7 @@ func TestEnqueueMentionedAgentTasks_SelfMentionCrossIssueEnqueues(t *testing.T)
t.Fatalf("before: expected 0 pending tasks on parent issue, got %d", got)
}
- testHandler.enqueueMentionedAgentTasks(ctx, fx.IssueB, fx.CommentB, nil, "agent", fx.JID)
+ enqueueMentionedAgentTasksForTest(t, ctx, fx.IssueB, fx.CommentB, nil, "agent", fx.JID)
if got := countQueuedOrDispatched(t, fx.JID, fx.IssueBID); got != 1 {
t.Fatalf("after self-mention from another issue: expected 1 queued task on parent issue, got %d", got)
@@ -189,7 +199,7 @@ func TestEnqueueMentionedAgentTasks_SelfMentionWhileRunningQueuesFollowup(t *tes
t.Fatalf("before: expected 0 queued/dispatched tasks (only the running task), got %d", got)
}
- testHandler.enqueueMentionedAgentTasks(ctx, fx.IssueA, fx.CommentA, nil, "agent", fx.JID)
+ enqueueMentionedAgentTasksForTest(t, ctx, fx.IssueA, fx.CommentA, nil, "agent", fx.JID)
if got := countQueuedOrDispatched(t, fx.JID, fx.IssueAID); got != 1 {
t.Fatalf("after self-mention while running: expected 1 new queued follow-up, got %d", got)
@@ -232,7 +242,7 @@ func TestEnqueueMentionedAgentTasks_SelfMentionDedupesAgainstPendingTask(t *test
t.Fatalf("before: expected 1 pre-existing %s task, got %d", tc.status, before)
}
- testHandler.enqueueMentionedAgentTasks(ctx, fx.IssueA, fx.CommentA, nil, "agent", fx.JID)
+ enqueueMentionedAgentTasksForTest(t, ctx, fx.IssueA, fx.CommentA, nil, "agent", fx.JID)
after := countQueuedOrDispatched(t, fx.JID, fx.IssueAID)
if after != 1 {
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index 719e98b173..c94aba5073 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -905,58 +905,6 @@ func (h *Handler) RecordSquadLeaderEvaluation(w http.ResponseWriter, r *http.Req
// ── Squad Trigger Logic ─────────────────────────────────────────────────────
-// shouldEnqueueSquadLeaderOnComment returns true if the issue is assigned to a
-// squad and the comment author is NOT a member of that squad (anti-loop).
-// commentContent is the new comment's markdown body; when a member explicitly
-// @mentions anyone (agent, member, squad, or @all) in that body, the leader
-// is skipped — the @ marks deliberate routing and the leader would otherwise
-// just observe and record no_action. Issue cross-reference mentions
-// (mention://issue/...) are NOT a routing signal and do not suppress the
-// leader. Agent-authored comments always go through the leader (subject to
-// the leader self-trigger guard) so agent updates still drive coordination.
-func (h *Handler) shouldEnqueueSquadLeaderOnComment(ctx context.Context, issue db.Issue, commentContent, authorType, authorID string) bool {
- if !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {
- return false
- }
-
- // Load the squad.
- squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
- ID: issue.AssigneeID,
- WorkspaceID: issue.WorkspaceID,
- })
- if err != nil {
- return false
- }
-
- // Skip if the comment author is the squad leader itself AND the agent's
- // last activity on this issue was in the leader role (prevent self-trigger
- // loop). An agent that is simultaneously the squad's leader and one of its
- // workers must still wake the leader role after posting a comment from
- // its worker task — role is inferred from the agent's most recent task
- // on the issue, not from author ID alone.
- if authorType == "agent" && authorID == uuidToString(squad.LeaderID) &&
- h.lastTaskWasLeader(ctx, issue.ID, squad.LeaderID) {
- return false
- }
-
- // Member explicitly @mentioned someone → that someone owns the next step,
- // skip the leader. Covers @agent / @member / @squad / @all; issue
- // cross-references do NOT count as routing. Agent-authored comments are
- // intentionally exempt: when an agent posts a result that @mentions
- // another agent, the leader still needs to coordinate the thread.
- if authorType == "member" && commentMentionsAnyone(commentContent) {
- return false
- }
-
- // Verify leader agent is ready (has runtime, not archived).
- agent, err := h.Queries.GetAgent(ctx, squad.LeaderID)
- if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
- return false
- }
-
- return true
-}
-
// lastTaskWasLeader returns true when the agent's most recent task on the
// issue was enqueued in the squad-leader role. Used by the self-trigger
// guards to tell apart a comment posted while the agent was acting as
@@ -1031,7 +979,10 @@ func (h *Handler) isSquadLeaderReady(ctx context.Context, issue db.Issue) bool {
return ready
}
-// enqueueSquadLeaderTask triggers the squad leader agent for an issue assigned to a squad.
+// enqueueSquadLeaderTask triggers the squad leader agent for an issue assigned
+// to a squad. Assign and backlog-promotion paths use this directly; comment
+// paths go through computeCommentAgentTriggers so preview and create share the
+// same trigger set.
func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, authorType, authorID string) {
squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
ID: issue.AssigneeID,
@@ -1041,12 +992,10 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, tr
return
}
- // Private-leader gate: deny if the actor cannot access the leader.
if !h.canEnqueueSquadLeader(ctx, squad.LeaderID, authorType, authorID, uuidToString(issue.WorkspaceID)) {
return
}
- // Dedup: skip if leader already has a pending task for this issue.
hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
IssueID: issue.ID,
AgentID: squad.LeaderID,
diff --git a/server/internal/handler/squad_comment_trigger_test.go b/server/internal/handler/squad_comment_trigger_test.go
index 99b4a5cc5b..39f448a1a1 100644
--- a/server/internal/handler/squad_comment_trigger_test.go
+++ b/server/internal/handler/squad_comment_trigger_test.go
@@ -42,9 +42,17 @@ func TestCommentMentionsAnyone(t *testing.T) {
}
}
+// shouldEnqueueSquadLeaderOnCommentForTest reports whether the shared comment
+// trigger computation would wake the issue's assigned squad leader — the
+// boolean view these integration tests assert on.
+func shouldEnqueueSquadLeaderOnCommentForTest(ctx context.Context, issue db.Issue, content, authorType, authorID string) bool {
+ _, ok := testHandler.computeAssignedSquadLeaderCommentTrigger(ctx, issue, content, authorType, authorID)
+ return ok
+}
+
// squadCommentTriggerFixture wires a squad assigned to a fresh issue and
// returns the loaded db.Issue plus the leader agent UUID for use in
-// shouldEnqueueSquadLeaderOnComment integration tests.
+// computeAssignedSquadLeaderCommentTrigger integration tests.
type squadCommentTriggerFixture struct {
Issue db.Issue
SquadID string
@@ -193,7 +201,7 @@ func TestShouldEnqueueSquadLeaderOnComment_SkipsWhenMemberMentionsAnyone(t *test
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- got := testHandler.shouldEnqueueSquadLeaderOnComment(ctx, fx.Issue, tc.content, tc.authorType, tc.authorID)
+ got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, tc.content, tc.authorType, tc.authorID)
if got != tc.want {
t.Fatalf("%s\n content=%q author=%s/%s\n got=%v want=%v",
tc.description, tc.content, tc.authorType, tc.authorID, got, tc.want)
@@ -241,7 +249,7 @@ func TestShouldEnqueueSquadLeaderOnComment_LeaderSelfTriggerByRole(t *testing.T)
t.Run("no prior task wakes leader (fresh external trigger)", func(t *testing.T) {
clearTasks()
- if got := testHandler.shouldEnqueueSquadLeaderOnComment(ctx, fx.Issue, "noted", "agent", fx.LeaderID); !got {
+ if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "noted", "agent", fx.LeaderID); !got {
t.Fatalf("no prior task: expected leader to be enqueued, got skip")
}
})
@@ -249,7 +257,7 @@ func TestShouldEnqueueSquadLeaderOnComment_LeaderSelfTriggerByRole(t *testing.T)
t.Run("prior leader task suppresses self-trigger", func(t *testing.T) {
clearTasks()
insertTask(true, "completed")
- if got := testHandler.shouldEnqueueSquadLeaderOnComment(ctx, fx.Issue, "noted", "agent", fx.LeaderID); got {
+ if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "noted", "agent", fx.LeaderID); got {
t.Fatalf("after leader task: expected skip (anti-loop), got enqueue")
}
})
@@ -257,7 +265,7 @@ func TestShouldEnqueueSquadLeaderOnComment_LeaderSelfTriggerByRole(t *testing.T)
t.Run("prior worker task still wakes leader (dual-role agent)", func(t *testing.T) {
clearTasks()
insertTask(false, "completed")
- if got := testHandler.shouldEnqueueSquadLeaderOnComment(ctx, fx.Issue, "result", "agent", fx.LeaderID); !got {
+ if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "result", "agent", fx.LeaderID); !got {
t.Fatalf("after worker task: expected leader to be enqueued (MUL-2218), got skip")
}
})
@@ -266,7 +274,7 @@ func TestShouldEnqueueSquadLeaderOnComment_LeaderSelfTriggerByRole(t *testing.T)
clearTasks()
insertTask(true, "completed") // older leader task
insertTask(false, "completed") // newer worker task
- if got := testHandler.shouldEnqueueSquadLeaderOnComment(ctx, fx.Issue, "result", "agent", fx.LeaderID); !got {
+ if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "result", "agent", fx.LeaderID); !got {
t.Fatalf("latest task is worker: expected leader to be enqueued, got skip")
}
})
@@ -423,7 +431,7 @@ func TestCreateComment_DualRoleAgentWorkerCommentWakesLeader(t *testing.T) {
// MUL-2218: auto-retry of a leader-role task must produce a child task that is
// also is_leader_task=true. Without this, MaybeRetryFailedTask silently
// demotes a retried leader task to a worker task, and the self-trigger guard
-// in shouldEnqueueSquadLeaderOnComment / comment.go stops recognising the
+// in computeAssignedSquadLeaderCommentTrigger / comment.go stops recognising the
// retried leader's own comments — re-opening the bug this issue fixes.
func TestCreateRetryTask_InheritsIsLeaderTask(t *testing.T) {
if testHandler == nil || testPool == nil {
diff --git a/server/internal/handler/trigger_test.go b/server/internal/handler/trigger_test.go
index e5c5b2a530..4e3be4b60e 100644
--- a/server/internal/handler/trigger_test.go
+++ b/server/internal/handler/trigger_test.go
@@ -352,11 +352,12 @@ func TestIsNoteComment(t *testing.T) {
}
// TestTriggerTasksForComment_NoteShortCircuits proves a /note comment returns
-// before any of the three enqueue paths run. shouldEnqueueOnComment,
-// shouldEnqueueSquadLeaderOnComment, and enqueueMentionedAgentTasks all
-// dereference h.Queries, so a nil-Queries Handler would panic if the /note
-// guard were missing or moved below them. The comment also @mentions an agent
-// to exercise the mention path specifically.
+// before any of the three trigger paths run. shouldEnqueueOnComment,
+// computeAssignedSquadLeaderCommentTrigger, and
+// computeMentionedAgentCommentTriggers all dereference h.Queries, so a
+// nil-Queries Handler would panic if the /note guard were missing or moved
+// below them. The comment also @mentions an agent to exercise the mention
+// path specifically.
func TestTriggerTasksForComment_NoteShortCircuits(t *testing.T) {
h := &Handler{} // nil Queries / TaskService on purpose
issue := issueWithAgentAssignee()
@@ -365,5 +366,5 @@ func TestTriggerTasksForComment_NoteShortCircuits(t *testing.T) {
}
// Must not panic — the guard short-circuits before any DB access.
- h.triggerTasksForComment(context.Background(), issue, comment, nil, "member", memberID)
+ h.triggerTasksForComment(context.Background(), issue, comment, nil, "member", memberID, nil)
}
diff --git a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md b/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
index 845bb0b220..2293e4ff1b 100644
--- a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
@@ -57,19 +57,32 @@ match, or the link resolves to the wrong entity (or to nothing).
| link a person | `member` | member.user_id | renders a link; enqueues NOTHING — no agent run |
| reference an issue | `issue` | issue.id | renders a link; enqueues NOTHING — always safe |
-The enqueue logic lives in `enqueueMentionedAgentTasks`
-(`server/internal/handler/comment.go`). It iterates the parsed mentions and
-acts on two types only: the `squad` branch resolves the squad and enqueues its
-leader; everything that is not `agent` after that is skipped
-(`if m.Type != "agent" { continue }`), then the `agent` branch enqueues the
-run. A `member` or `issue` mention reaches neither branch, so it enqueues no
-task.
+The mention trigger set is computed by `computeMentionedAgentCommentTriggers`
+(`server/internal/handler/comment.go`); the comment path folds that result into
+`computeCommentAgentTriggers` and enqueues it via `enqueueCommentAgentTriggers`.
+It acts on two types only: the `squad` branch resolves the squad and adds its
+leader to the trigger set; everything that is not `agent` after that is skipped
+(`if m.Type != "agent" { continue }`), then the `agent` branch adds that agent.
+A `member` or `issue` mention reaches neither branch, so it enqueues no task.
A `member` mention therefore does NOT make a person "run", and this skill does
NOT claim it delivers a notification through the Go comment handler — there is
no such code path in that handler (see the source map). What is verified is the
contract above: only `agent` and `squad` mentions enqueue work.
+## Preview and per-comment suppression
+
+Newer clients can call `POST /api/issues/{id}/comments/trigger-preview` before
+submitting a comment. The preview endpoint uses the same
+`computeCommentAgentTriggers` function as `CreateComment`, so the displayed
+agent chips come from backend rules, not from a client-side reimplementation.
+
+When creating a comment, clients may send an optional `suppress_agent_ids`
+array. The server still computes the full trigger set first, then removes those
+agent IDs as a post-filter. A missing or empty field preserves the old behavior.
+A valid UUID that is not in the computed trigger set is a no-op; a malformed
+UUID is rejected at the request boundary.
+
## @all is the broadcast type
`@all` uses the literal `all`, never a UUID:
diff --git a/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md b/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md
index ed5701ff9e..9844503af4 100644
--- a/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md
+++ b/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md
@@ -30,25 +30,37 @@ a pointer. Branch where verified: `feat/builtin-skills`.
| Fact | Source |
| --- | --- |
-| `enqueueMentionedAgentTasks` is the dispatch loop over parsed mentions | `server/internal/handler/comment.go:1082` |
-| It is called for every comment via `triggerTasksForComment` | `server/internal/handler/comment.go:944` |
-| `squad` branch: resolve squad in workspace, read `LeaderID`, enqueue the leader | `server/internal/handler/comment.go:1089-1128` |
-| `squad` → `EnqueueTaskForSquadLeader` | `server/internal/handler/comment.go:1128` |
-| Everything not `agent` after the squad branch is skipped: `if m.Type != "agent" { continue }` | `server/internal/handler/comment.go:1133` |
-| `agent` branch: load agent in workspace, then enqueue | `server/internal/handler/comment.go:1143-1167` |
-| `agent` → `EnqueueTaskForMention` (a run for that agent) | `server/internal/handler/comment.go:1165` |
-| **`member` and `issue` mentions reach neither branch — they enqueue NOTHING.** A `member` mention fails the `!= "agent"` skip at line 1133 (the squad branch above it only matches `squad`); an `issue` mention does the same. | `server/internal/handler/comment.go:1089,1133` |
+| `computeCommentAgentTriggers` is the shared comment trigger computation used before enqueueing | `server/internal/handler/comment.go:1124-1160` |
+| `computeMentionedAgentCommentTriggers` builds the mention trigger set; `enqueueCommentAgentTriggers` is the shared enqueue helper | `server/internal/handler/comment.go:1335,1089` |
+| Comment creation runs `triggerTasksForComment`, which computes triggers, applies suppressions, then enqueues | `server/internal/handler/comment.go:1057-1064` |
+| `squad` branch: resolve squad in workspace, read `LeaderID`, add the leader trigger | `server/internal/handler/comment.go:1352-1391` |
+| `squad` → shared enqueue helper calls `EnqueueTaskForSquadLeader` | `server/internal/handler/comment.go:1104-1112` |
+| Everything not `agent` after the squad branch is skipped: `if m.Type != "agent" { continue }` | `server/internal/handler/comment.go:1394-1396` |
+| `agent` branch: load agent in workspace, then add the agent trigger | `server/internal/handler/comment.go:1397-1424` |
+| `agent` → shared enqueue helper calls `EnqueueTaskForMention` (a run for that agent) | `server/internal/handler/comment.go:1113-1119` |
+| **`member` and `issue` mentions reach neither branch — they enqueue NOTHING.** A `member` mention fails the `!= "agent"` skip at lines 1394-1396 (the squad branch above it only matches `squad`); an `issue` mention does the same. | `server/internal/handler/comment.go:1352,1394-1396` |
+
+## Preview and suppression
+
+| Fact | Source |
+| --- | --- |
+| Preview route: `POST /api/issues/{id}/comments/trigger-preview` | `server/cmd/server/router.go:707` |
+| Preview handler loads the issue and parent comment, expands issue identifiers, then calls `computeCommentAgentTriggers` | `server/internal/handler/comment.go:832-877` |
+| Preview response returns agent `id`, `name`, optional `avatar_url`, `source`, and `reason` | `server/internal/handler/comment.go:783-793` |
+| `CreateCommentRequest` accepts optional `suppress_agent_ids` | `server/internal/handler/comment.go:770-776` |
+| `suppress_agent_ids` is parsed as request-boundary UUID input | `server/internal/handler/comment.go:925-928` |
+| Create comment computes the full trigger set, then applies `filterSuppressedCommentAgentTriggers` before enqueueing | `server/internal/handler/comment.go:1057-1087` |
## Guards that make a valid mention a silent no-op
| Guard | Source |
| --- | --- |
-| agent archived / no runtime → `continue` (`RuntimeID` invalid or `ArchivedAt` set) | `server/internal/handler/comment.go:1147` |
-| squad leader archived / no runtime → `continue` | `server/internal/handler/comment.go:1113` |
-| private agent the actor cannot access → `continue` (`canAccessPrivateAgent`) | `server/internal/handler/comment.go:1152` |
-| private squad leader the actor cannot trigger → `continue` (`canAccessPrivateAgent` via squad gate) | `server/internal/handler/comment.go:1117` |
-| already-pending dedup (agent) → `HasPendingTaskForIssueAndAgent` → `continue` | `server/internal/handler/comment.go:1156-1162` |
-| already-pending dedup (squad leader) → `continue` | `server/internal/handler/comment.go:1121-1127` |
+| agent archived / no runtime → `continue` (`RuntimeID` invalid or `ArchivedAt` set) | `server/internal/handler/comment.go:1408-1410` |
+| squad leader archived / no runtime → `continue` | `server/internal/handler/comment.go:1376-1378` |
+| private agent the actor cannot access → `continue` (`canAccessPrivateAgent`) | `server/internal/handler/comment.go:1413-1415` |
+| private squad leader the actor cannot trigger → `continue` (`canAccessPrivateAgent`) | `server/internal/handler/comment.go:1380-1382` |
+| already-pending dedup (agent) → `HasPendingTaskForIssueAndAgent` → `continue` | `server/internal/handler/comment.go:1417-1423` |
+| already-pending dedup (squad leader) → `continue` | `server/internal/handler/comment.go:1384-1390` |
| `canAccessPrivateAgent` definition | `server/internal/handler/agent_access.go` (search `func (h *Handler) canAccessPrivateAgent`) |
| `canEnqueueSquadLeader` (loads leader, delegates to `canAccessPrivateAgent`) | `server/internal/handler/agent_access.go:82-91` |
@@ -56,10 +68,10 @@ a pointer. Branch where verified: `feat/builtin-skills`.
| Fact | Source |
| --- | --- |
-| `commentMentionsOthersButNotAssignee` — decides whether to suppress the assignee's on-comment trigger | `server/internal/handler/comment.go:953` |
-| `@all` is treated as a broadcast → returns true → assignee auto-trigger suppressed | `server/internal/handler/comment.go:967-969` |
-| Comment-flow call site that consults it | `server/internal/handler/comment.go:933` |
-| `@all` never enqueues a specific agent: it is neither `squad` nor `agent`, so it is skipped in the enqueue loop | `server/internal/handler/comment.go:1133` |
+| `commentMentionsOthersButNotAssignee` — decides whether to suppress the assignee's on-comment trigger | `server/internal/handler/comment.go:1206` |
+| `@all` is treated as a broadcast → returns true → assignee auto-trigger suppressed | `server/internal/handler/comment.go:1217-1221` |
+| Comment-flow computation that consults it | `server/internal/handler/comment.go:1140-1142` |
+| `@all` never enqueues a specific agent: it is neither `squad` nor `agent`, so it is skipped in the mention trigger computation | `server/internal/handler/comment.go:1394-1396` |
## CLI id sources (where the UUID comes from)
@@ -75,9 +87,9 @@ a pointer. Branch where verified: `feat/builtin-skills`.
The skill deliberately does **not** assert that a `member` mention "sends a
notification." `server/internal/handler/comment.go` has no notification
-delivery path for member (or issue) mentions: `enqueueMentionedAgentTasks`
+delivery path for member (or issue) mentions: `computeMentionedAgentCommentTriggers`
branches only on `squad` and `agent`
-(`server/internal/handler/comment.go:1089,1133`), and a grep of the file for
+(`server/internal/handler/comment.go:1352,1394-1396`), and a grep of the file for
`notif` returns only an unrelated comment about avoiding "log spam" on
unchanged threads — no member-notification call. The verified contract is
narrow: a `member` or `issue` mention renders as a link and enqueues no agent
diff --git a/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md b/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md
index a5a43a78e8..206893a745 100644
--- a/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md
+++ b/server/internal/service/builtin_skills/multica-squads/references/squad-source-map.md
@@ -121,23 +121,26 @@ Contracts:
Source:
```text
-server/internal/handler/comment.go # comment-trigger ~940-941, squad mention ~1089
-server/internal/handler/squad.go # shouldEnqueueSquadLeaderOnComment ~909, enqueueSquadLeaderTask ~1027
+server/internal/handler/comment.go # comment triggers ~1057-1199, squad mention branch ~1352
+server/internal/handler/squad.go # enqueueSquadLeaderTask ~986 (assign/backlog paths), lastTaskWasLeader ~915
server/internal/service/task.go # EnqueueTaskForSquadLeader
```
Contracts:
-- commenting on a squad-assigned issue can wake the leader
- (comment.go:940-941 → shouldEnqueueSquadLeaderOnComment at squad.go:909);
-- explicit `mention://squad/<id>` resolves squad and enqueues leader
- (comment.go:1089);
+- commenting on a squad-assigned issue can wake the leader — the comment path
+ computes triggers via `computeCommentAgentTriggers` (comment.go:1124), whose
+ assigned-squad branch is `computeAssignedSquadLeaderCommentTrigger`
+ (comment.go:1162-1199); the same computation backs the trigger-preview
+ endpoint;
+- explicit `mention://squad/<id>` resolves squad and adds the leader trigger
+ (comment.go:1352-1391);
- squad mention does not fan out to members — enqueue targets `squad.LeaderID`
- only (squad.go:1050);
+ only (comment.go:1104-1112, and squad.go:1007 on the assign/backlog paths);
- leader task uses `is_leader_task=true` (via `EnqueueTaskForSquadLeader`);
- leader self-trigger loops are guarded — same-leader / last-task-was-leader
- guards (squad.go:929-932, lastTaskWasLeader at squad.go:959) and member
- explicit-mention skip (squad.go:939-941).
+ guards (comment.go:1173-1176, lastTaskWasLeader at squad.go:915) and member
+ explicit-mention skip (comment.go:1177-1179).
## Autopilot