Skip to content

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

Go

fix(comments): support edit trigger suppression (#4136)

Naiyuan Qingea4f816ce2bd
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index f5cfd0a899..cf0f047b43 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -177,11 +177,29 @@ describe("ApiClient", () => {
status: 201,
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: "updated",
+ type: "comment",
+ parent_id: null,
+ reactions: [],
+ attachments: [],
+ created_at: "2026-06-05T00:00:00Z",
+ updated_at: "2026-06-05T00:01:00Z",
+ }), {
+ status: 200,
+ 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.previewCommentTriggers("issue-1", "hello", "parent-1", "comment-1");
await client.createComment(
"issue-1",
"hello",
@@ -190,6 +208,7 @@ describe("ApiClient", () => {
["attachment-1"],
["agent-1"],
);
+ await client.updateComment("comment-1", "updated", ["attachment-1"], ["agent-1"]);
expect(fetchMock.mock.calls.map(([url, init]) => ({
url,
@@ -199,7 +218,7 @@ describe("ApiClient", () => {
{
url: "https://api.example.test/api/issues/issue-1/comments/trigger-preview",
method: "POST",
- body: JSON.stringify({ content: "hello", parent_id: "parent-1" }),
+ body: JSON.stringify({ content: "hello", parent_id: "parent-1", editing_comment_id: "comment-1" }),
},
{
url: "https://api.example.test/api/issues/issue-1/comments",
@@ -212,6 +231,15 @@ describe("ApiClient", () => {
suppress_agent_ids: ["agent-1"],
}),
},
+ {
+ url: "https://api.example.test/api/comments/comment-1",
+ method: "PUT",
+ body: JSON.stringify({
+ content: "updated",
+ attachment_ids: ["attachment-1"],
+ suppress_agent_ids: ["agent-1"],
+ }),
+ },
]);
});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 2b92306853..fc288162f9 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -663,12 +663,13 @@ export class ApiClient {
});
}
- async previewCommentTriggers(issueId: string, content: string, parentId?: string): Promise<CommentTriggerPreview> {
+ async previewCommentTriggers(issueId: string, content: string, parentId?: string, editingCommentId?: 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 } : {}),
+ ...(editingCommentId ? { editing_comment_id: editingCommentId } : {}),
}),
});
return parseWithFallback(raw, CommentTriggerPreviewSchema, { agents: [] }, {
@@ -689,10 +690,14 @@ export class ApiClient {
return this.fetch("/api/assignee-frequency");
}
- async updateComment(commentId: string, content: string, attachmentIds?: string[]): Promise<Comment> {
+ async updateComment(commentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[]): Promise<Comment> {
return this.fetch(`/api/comments/${commentId}`, {
method: "PUT",
- body: JSON.stringify({ content, attachment_ids: attachmentIds }),
+ body: JSON.stringify({
+ content,
+ attachment_ids: attachmentIds,
+ ...(suppressAgentIds?.length ? { suppress_agent_ids: suppressAgentIds } : {}),
+ }),
});
}
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 806789f031..e072ce94a2 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -646,8 +646,17 @@ export function useCreateComment(issueId: string) {
export function useUpdateComment(issueId: string) {
const qc = useQueryClient();
return useMutation({
- mutationFn: ({ commentId, content, attachmentIds }: { commentId: string; content: string; attachmentIds: string[] }) =>
- api.updateComment(commentId, content, attachmentIds),
+ mutationFn: ({
+ commentId,
+ content,
+ attachmentIds,
+ suppressAgentIds,
+ }: {
+ commentId: string;
+ content: string;
+ attachmentIds: string[];
+ suppressAgentIds?: string[];
+ }) => api.updateComment(commentId, content, attachmentIds, suppressAgentIds),
onMutate: async ({ commentId, content, attachmentIds }) => {
await qc.cancelQueries({ queryKey: issueKeys.timeline(issueId) });
const prev = qc.getQueryData<TimelineCache>(issueKeys.timeline(issueId));
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index b7f36b8639..9f0e5829e2 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -1,6 +1,6 @@
"use client";
-import { memo, useCallback, useRef, useState, type ReactNode } from "react";
+import { memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { CheckCircle2, ChevronRight, ListChevronsDownUp, Copy, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Card } from "@multica/ui/components/ui/card";
@@ -35,6 +35,8 @@ import { FileUploadButton } from "@multica/ui/components/common/file-upload-butt
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { api } from "@multica/core/api";
import { ReplyInput } from "./reply-input";
+import { CommentTriggerChips } from "./comment-trigger-chips";
+import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
import type { TimelineEntry, Attachment } from "@multica/core/types";
import { contentReferencesAttachment } from "@multica/core/types";
import { useCommentCollapseStore, useCommentDraftStore } from "@multica/core/issues/stores";
@@ -102,7 +104,7 @@ interface CommentCardProps {
*/
canModerate?: boolean;
onReply: (parentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<void>;
- onEdit: (commentId: string, content: string, attachmentIds: string[]) => Promise<void>;
+ onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => Promise<void>;
onDelete: (commentId: string) => void;
onToggleReaction: (commentId: string, emoji: string) => void;
/** Resolve/unresolve any comment in this thread (commentId = the target row). */
@@ -253,15 +255,23 @@ function initialStandaloneAttachmentIds(entry: TimelineEntry): Set<string> {
function useEditAttachmentState(
issueId: string,
entry: TimelineEntry,
- onEdit: (commentId: string, content: string, attachmentIds: string[]) => Promise<void>,
+ onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => Promise<void>,
) {
const { t } = useT("issues");
const { uploadWithToast } = useFileUpload(api);
const [editing, setEditing] = useState(false);
const editorRef = useRef<ContentEditorRef>(null);
const cancelledRef = useRef(false);
+ const [content, setContent] = useState(entry.content ?? "");
+ const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());
const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);
const [retainedStandaloneIds, setRetainedStandaloneIds] = useState<Set<string> | null>(null);
+ const triggerPreview = useCommentTriggerPreview({
+ issueId,
+ parentId: entry.parent_id ?? undefined,
+ editingCommentId: entry.id,
+ content: editing ? content : "",
+ });
const editorAttachments = pendingAttachments.length > 0
? [...(entry.attachments ?? []), ...pendingAttachments]
@@ -287,12 +297,31 @@ function useEditAttachmentState(
? (getDraft(draftKey) ?? entry.content ?? "")
: (entry.content ?? "");
+ 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 standaloneEditAttachments = (entry.attachments ?? []).filter((a) =>
retainedStandaloneIds?.has(a.id),
);
const resetState = () => {
setEditing(false);
+ setContent(entry.content ?? "");
+ setSuppressedAgentIds(new Set());
setPendingAttachments([]);
setRetainedStandaloneIds(null);
clearDraft(draftKey);
@@ -300,6 +329,7 @@ function useEditAttachmentState(
const startEdit = () => {
cancelledRef.current = false;
+ setContent(getDraft(draftKey) ?? entry.content ?? "");
setRetainedStandaloneIds(initialStandaloneAttachmentIds(entry));
setEditing(true);
};
@@ -326,8 +356,16 @@ function useEditAttachmentState(
resetState();
return;
}
+ const suppressAgentIds = triggerPreview.agents
+ .filter((agent) => suppressedAgentIds.has(agent.id))
+ .map((agent) => agent.id);
try {
- await onEdit(entry.id, trimmed, activeIds);
+ await onEdit(
+ entry.id,
+ trimmed,
+ activeIds,
+ suppressAgentIds.length > 0 ? suppressAgentIds : undefined,
+ );
resetState();
} catch (err) {
toast.error(
@@ -345,8 +383,12 @@ function useEditAttachmentState(
handleUpload,
isDragOver,
dropZoneProps,
+ triggerPreview,
+ suppressedAgentIds,
+ toggleSuppressedAgent,
draftKey,
setDraft,
+ setContent,
clearDraft,
initialValue,
standaloneEditAttachments,
@@ -382,7 +424,7 @@ function CommentRow({
isResolution?: boolean;
/** True when this row is the deep-link target currently being highlighted. */
isHighlighted?: boolean;
- onEdit: (commentId: string, content: string, attachmentIds: string[]) => Promise<void>;
+ onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => Promise<void>;
onDelete: (commentId: string) => void;
onToggleReaction: (commentId: string, emoji: string) => void;
onResolveToggle?: (commentId: string, resolved: boolean) => void;
@@ -507,6 +549,7 @@ function CommentRow({
defaultValue={edit.initialValue}
placeholder={t(($) => $.comment.edit_placeholder)}
onUpdate={(md) => {
+ edit.setContent(md);
if (md.trim().length > 0) edit.setDraft(edit.draftKey, md);
else edit.clearDraft(edit.draftKey);
}}
@@ -530,8 +573,13 @@ function CommentRow({
return next;
})
}
- />
- )}
+ />
+ )}
+ <CommentTriggerChips
+ agents={edit.triggerPreview.agents}
+ suppressedAgentIds={edit.suppressedAgentIds}
+ onToggle={edit.toggleSuppressedAgent}
+ />
<FileUploadButton
size="sm"
multiple
@@ -781,6 +829,7 @@ function CommentCardImpl({
defaultValue={edit.initialValue}
placeholder={t(($) => $.comment.edit_placeholder)}
onUpdate={(md) => {
+ edit.setContent(md);
if (md.trim().length > 0) edit.setDraft(edit.draftKey, md);
else edit.clearDraft(edit.draftKey);
}}
@@ -804,8 +853,13 @@ function CommentCardImpl({
return next;
})
}
- />
- )}
+ />
+ )}
+ <CommentTriggerChips
+ agents={edit.triggerPreview.agents}
+ suppressedAgentIds={edit.suppressedAgentIds}
+ onToggle={edit.toggleSuppressedAgent}
+ />
<FileUploadButton
size="sm"
multiple
diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.test.ts b/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
index 238e2556b6..7ab499b622 100644
--- a/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
+++ b/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
@@ -66,6 +66,44 @@ describe("useCommentTriggerPreview", () => {
"issue-1",
"hello with more ordinary text",
undefined,
+ undefined,
+ );
+ });
+
+ it("passes editing comment context and refetches when it changes", async () => {
+ const agentA = "00000000-0000-0000-0000-000000000001";
+ const content = `[@A](mention://agent/${agentA})`;
+ const { rerender } = renderHook(
+ ({ editingCommentId }) =>
+ useCommentTriggerPreview({
+ issueId: "issue-1",
+ parentId: "parent-1",
+ editingCommentId,
+ content,
+ }),
+ {
+ wrapper: createWrapper(),
+ initialProps: { editingCommentId: "comment-1" },
+ },
+ );
+
+ await advancePreviewDebounce();
+ expect(previewCommentTriggers).toHaveBeenCalledWith(
+ "issue-1",
+ content,
+ "parent-1",
+ "comment-1",
+ );
+
+ rerender({ editingCommentId: "comment-2" });
+ await advancePreviewDebounce();
+
+ expect(previewCommentTriggers).toHaveBeenCalledTimes(2);
+ expect(previewCommentTriggers).toHaveBeenLastCalledWith(
+ "issue-1",
+ content,
+ "parent-1",
+ "comment-2",
);
});
diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.ts b/packages/views/issues/hooks/use-comment-trigger-preview.ts
index 048cb52237..2b83855070 100644
--- a/packages/views/issues/hooks/use-comment-trigger-preview.ts
+++ b/packages/views/issues/hooks/use-comment-trigger-preview.ts
@@ -58,10 +58,12 @@ function useDebouncedSignature(signature: string) {
export function useCommentTriggerPreview({
issueId,
parentId,
+ editingCommentId,
content,
}: {
issueId: string;
parentId?: string;
+ editingCommentId?: string;
content: string;
}): UseCommentTriggerPreviewResult {
const signature = useMemo(() => commentTriggerPreviewSignature(content), [content]);
@@ -73,8 +75,8 @@ export function useCommentTriggerPreview({
}, [content]);
const previewQuery = useQuery({
- queryKey: [...issueKeys.commentTriggerPreview(issueId), parentId ?? "", debouncedSignature],
- queryFn: () => api.previewCommentTriggers(issueId, contentRef.current, parentId),
+ queryKey: [...issueKeys.commentTriggerPreview(issueId), parentId ?? "", editingCommentId ?? "", debouncedSignature],
+ queryFn: () => api.previewCommentTriggers(issueId, contentRef.current, parentId, editingCommentId),
enabled: signature !== "empty" && debouncedSignature !== "empty",
retry: false,
// The answer depends on live queue state (pending-task dedup), not just
diff --git a/packages/views/issues/hooks/use-issue-timeline.test.tsx b/packages/views/issues/hooks/use-issue-timeline.test.tsx
index d5a5cbfe76..c5132e39b4 100644
--- a/packages/views/issues/hooks/use-issue-timeline.test.tsx
+++ b/packages/views/issues/hooks/use-issue-timeline.test.tsx
@@ -110,6 +110,11 @@ import { useIssueTimeline } from "./use-issue-timeline";
describe("useIssueTimeline", () => {
beforeEach(() => {
wsHandlers.clear();
+ stableHandles.createMutateAsync.mockClear();
+ stableHandles.updateMutateAsync.mockClear();
+ stableHandles.deleteMutateAsync.mockClear();
+ stableHandles.resolveMutateAsync.mockClear();
+ stableHandles.toggleMutate.mockClear();
queryState.data = [];
queryState.isLoading = false;
cacheUpdates.last = null;
@@ -152,6 +157,21 @@ describe("useIssueTimeline", () => {
expect(result.current.timeline.map((e) => e.id)).toEqual(["c1", "c2", "c3"]);
});
+ it("passes suppressed agent ids through editComment", async () => {
+ const { result } = renderHook(() => useIssueTimeline("issue-1", "user-1"));
+
+ await act(async () => {
+ await result.current.editComment("comment-1", "updated", ["attachment-1"], ["agent-1"]);
+ });
+
+ expect(stableHandles.updateMutateAsync).toHaveBeenCalledWith({
+ commentId: "comment-1",
+ content: "updated",
+ attachmentIds: ["attachment-1"],
+ suppressAgentIds: ["agent-1"],
+ });
+ });
+
it("comment:created appends the new entry to the cache", () => {
queryState.data = [];
renderHook(() => useIssueTimeline("issue-1", "user-1"));
diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.ts
index ccef7e4809..6d232c5b16 100644
--- a/packages/views/issues/hooks/use-issue-timeline.ts
+++ b/packages/views/issues/hooks/use-issue-timeline.ts
@@ -297,9 +297,9 @@ export function useIssueTimeline(issueId: string, userId?: string) {
);
const editComment = useCallback(
- async (commentId: string, content: string, attachmentIds: string[]) => {
+ async (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => {
try {
- await updateComment({ commentId, content, attachmentIds });
+ await updateComment({ commentId, content, attachmentIds, suppressAgentIds });
} catch (err) {
toast.error(
err instanceof Error && err.message
diff --git a/server/internal/handler/agent_access_test.go b/server/internal/handler/agent_access_test.go
index 6540c7adc3..b35db45bc4 100644
--- a/server/internal/handler/agent_access_test.go
+++ b/server/internal/handler/agent_access_test.go
@@ -546,11 +546,11 @@ func TestShouldEnqueueOnComment_PrivateAgentGate(t *testing.T) {
}
cases := []struct {
- name string
- actorType string
- actorID string
- want bool
- reason string
+ name string
+ actorType string
+ actorID string
+ want bool
+ reason string
}{
{
name: "plain member — denied",
@@ -584,7 +584,7 @@ func TestShouldEnqueueOnComment_PrivateAgentGate(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- got := testHandler.shouldEnqueueOnComment(ctx, issue, tc.actorType, tc.actorID)
+ got := testHandler.shouldEnqueueOnComment(ctx, issue, tc.actorType, tc.actorID, commentTriggerComputeOptions{})
if got != tc.want {
t.Fatalf("%s\n actor=%s/%s got=%v want=%v",
tc.reason, tc.actorType, tc.actorID, got, tc.want)
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 019a42612b..9d822688cb 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -776,8 +776,9 @@ type CreateCommentRequest struct {
}
type CommentTriggerPreviewRequest struct {
- Content string `json:"content"`
- ParentID *string `json:"parent_id"`
+ Content string `json:"content"`
+ ParentID *string `json:"parent_id"`
+ EditingCommentID *string `json:"editing_comment_id"`
}
type CommentTriggerPreviewResponse struct {
@@ -806,6 +807,10 @@ type commentAgentTrigger struct {
Squad *db.Squad
}
+type commentTriggerComputeOptions struct {
+ ExcludeTriggerCommentID pgtype.UUID
+}
+
func commentAgentTriggerReason(trigger commentAgentTrigger) string {
switch trigger.Source {
case commentTriggerSourceIssueAssignee:
@@ -847,12 +852,42 @@ func (h *Handler) PreviewCommentTriggers(w http.ResponseWriter, r *http.Request)
return
}
- var parentComment *db.Comment
+ var editingComment *db.Comment
+ var opts commentTriggerComputeOptions
+ if req.EditingCommentID != nil {
+ editingID, ok := parseUUIDOrBadRequest(w, *req.EditingCommentID, "editing_comment_id")
+ if !ok {
+ return
+ }
+ comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{
+ ID: editingID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil || uuidToString(comment.IssueID) != uuidToString(issue.ID) {
+ writeError(w, http.StatusBadRequest, "invalid editing comment")
+ return
+ }
+ editingComment = &comment
+ opts.ExcludeTriggerCommentID = editingID
+ }
+
+ var parentID pgtype.UUID
if req.ParentID != nil {
parentID, ok := parseUUIDOrBadRequest(w, *req.ParentID, "parent_id")
if !ok {
return
}
+
+ if editingComment != nil && uuidToString(parentID) != uuidToString(editingComment.ParentID) {
+ writeError(w, http.StatusBadRequest, "parent_id does not match editing comment")
+ return
+ }
+ } else if editingComment != nil && editingComment.ParentID.Valid {
+ parentID = editingComment.ParentID
+ }
+
+ var parentComment *db.Comment
+ if parentID.Valid {
parent, err := h.Queries.GetComment(r.Context(), parentID)
if err != nil || uuidToString(parent.IssueID) != uuidToString(issue.ID) {
writeError(w, http.StatusBadRequest, "invalid parent comment")
@@ -868,7 +903,7 @@ func (h *Handler) PreviewCommentTriggers(w http.ResponseWriter, r *http.Request)
}
actorType, actorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))
- triggers := h.computeCommentAgentTriggers(r.Context(), issue, content, parentComment, actorType, actorID)
+ triggers := h.computeCommentAgentTriggers(r.Context(), issue, content, parentComment, actorType, actorID, opts)
resp := CommentTriggerPreviewResponse{Agents: make([]CommentTriggerAgentResponse, 0, len(triggers))}
for _, trigger := range triggers {
resp.Agents = append(resp.Agents, commentAgentTriggerToResponse(trigger))
@@ -1058,7 +1093,7 @@ func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, co
if isNoteComment(comment.Content) {
return
}
- triggers := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID)
+ triggers := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{})
triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)
h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
}
@@ -1121,7 +1156,7 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu
}
}
-func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, actorType, actorID string) []commentAgentTrigger {
+func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, actorType, actorID string, opts commentTriggerComputeOptions) []commentAgentTrigger {
if isNoteComment(content) {
return nil
}
@@ -1137,7 +1172,7 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
triggers = append(triggers, trigger)
}
- if actorType == "member" && h.shouldEnqueueOnComment(ctx, issue, actorType, actorID) &&
+ if actorType == "member" && h.shouldEnqueueOnComment(ctx, issue, actorType, actorID, opts) &&
!h.commentMentionsOthersButNotAssignee(content, issue) &&
!h.isReplyToMemberThread(ctx, parentComment, content, issue) {
if agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
@@ -1148,18 +1183,18 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
}
}
- if trigger, ok := h.computeAssignedSquadLeaderCommentTrigger(ctx, issue, content, actorType, actorID); ok {
+ if trigger, ok := h.computeAssignedSquadLeaderCommentTrigger(ctx, issue, content, actorType, actorID, opts); ok {
add(trigger)
}
- for _, trigger := range h.computeMentionedAgentCommentTriggers(ctx, issue, content, parentComment, actorType, actorID) {
+ for _, trigger := range h.computeMentionedAgentCommentTriggers(ctx, issue, content, parentComment, actorType, actorID, opts) {
add(trigger)
}
return triggers
}
-func (h *Handler) computeAssignedSquadLeaderCommentTrigger(ctx context.Context, issue db.Issue, content, authorType, authorID string) (commentAgentTrigger, bool) {
+func (h *Handler) computeAssignedSquadLeaderCommentTrigger(ctx context.Context, issue db.Issue, content, authorType, authorID string, opts commentTriggerComputeOptions) (commentAgentTrigger, bool) {
if !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {
return commentAgentTrigger{}, false
}
@@ -1187,16 +1222,27 @@ func (h *Handler) computeAssignedSquadLeaderCommentTrigger(ctx context.Context,
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,
- })
+ hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, squad.LeaderID, opts)
if err != nil || hasPending {
return commentAgentTrigger{}, false
}
return commentAgentTrigger{Agent: agent, Source: commentTriggerSourceIssueAssignee, Squad: &squad}, true
}
+func (h *Handler) hasPendingTaskForIssueAndAgent(ctx context.Context, issueID, agentID pgtype.UUID, opts commentTriggerComputeOptions) (bool, error) {
+ if opts.ExcludeTriggerCommentID.Valid {
+ return h.Queries.HasPendingTaskForIssueAndAgentExcludingTriggerComment(ctx, db.HasPendingTaskForIssueAndAgentExcludingTriggerCommentParams{
+ IssueID: issueID,
+ AgentID: agentID,
+ ExcludeTriggerCommentID: opts.ExcludeTriggerCommentID,
+ })
+ }
+ return h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
+ IssueID: issueID,
+ AgentID: agentID,
+ })
+}
+
// commentMentionsOthersButNotAssignee returns true if the comment @mentions
// anyone but does NOT @mention the issue's assignee agent. This is used to
// suppress the on_comment trigger when the user is directing their comment at
@@ -1332,7 +1378,7 @@ 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) computeMentionedAgentCommentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, authorType, authorID string) []commentAgentTrigger {
+func (h *Handler) computeMentionedAgentCommentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, authorType, authorID string, opts commentTriggerComputeOptions) []commentAgentTrigger {
wsID := uuidToString(issue.WorkspaceID)
mentions := util.ParseMentions(content)
if shouldInheritParentMentions(parentComment, mentions, authorType) {
@@ -1381,10 +1427,7 @@ func (h *Handler) computeMentionedAgentCommentTriggers(ctx context.Context, issu
continue
}
// Dedup: skip if leader already has a pending task for this issue.
- hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
- IssueID: issue.ID,
- AgentID: leaderID,
- })
+ hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, leaderID, opts)
if err != nil || hasPending {
continue
}
@@ -1414,10 +1457,7 @@ func (h *Handler) computeMentionedAgentCommentTriggers(ctx context.Context, issu
continue
}
// Dedup: skip if this agent already has a pending task for this issue.
- hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
- IssueID: issue.ID,
- AgentID: agentUUID,
- })
+ hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, agentUUID, opts)
if err != nil || hasPending {
continue
}
@@ -1467,8 +1507,9 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
var req struct {
- Content string `json:"content"`
- AttachmentIDs *[]string `json:"attachment_ids"`
+ Content string `json:"content"`
+ AttachmentIDs *[]string `json:"attachment_ids"`
+ SuppressAgentIDs []string `json:"suppress_agent_ids"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
@@ -1488,6 +1529,10 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
return
}
}
+ suppressAgentIDs, ok := parseUUIDSliceOrBadRequest(w, req.SuppressAgentIDs, "suppress_agent_ids")
+ if !ok {
+ return
+ }
// NOTE: See CreateComment — Markdown is sanitized at render/edit time, not here.
@@ -1546,7 +1591,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
}
- h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, nil)
+ h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, suppressAgentIDs)
}
}
diff --git a/server/internal/handler/comment_trigger_preview_test.go b/server/internal/handler/comment_trigger_preview_test.go
index cc3ce5bb26..2711bd6f7c 100644
--- a/server/internal/handler/comment_trigger_preview_test.go
+++ b/server/internal/handler/comment_trigger_preview_test.go
@@ -67,7 +67,7 @@ func previewCommentTriggersForTest(t *testing.T, issueID string, body map[string
return resp
}
-func postCommentForTriggerPreviewTest(t *testing.T, issueID string, body map[string]any) {
+func postCommentForTriggerPreviewTest(t *testing.T, issueID string, body map[string]any) string {
t.Helper()
w := httptest.NewRecorder()
@@ -77,6 +77,24 @@ func postCommentForTriggerPreviewTest(t *testing.T, issueID string, body map[str
if w.Code != http.StatusCreated {
t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
}
+
+ var resp CommentResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode created comment: %v", err)
+ }
+ return resp.ID
+}
+
+func updateCommentForTriggerPreviewTest(t *testing.T, commentID string, body map[string]any) {
+ t.Helper()
+
+ w := httptest.NewRecorder()
+ r := newRequest(http.MethodPut, "/api/comments/"+commentID, body)
+ r = withURLParam(r, "commentId", commentID)
+ testHandler.UpdateComment(w, r)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateComment: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
}
func countQueuedCommentTriggerTasks(t *testing.T, issueID, agentID string) int {
@@ -92,6 +110,39 @@ func countQueuedCommentTriggerTasks(t *testing.T, issueID, agentID string) int {
return n
}
+func createCommentTriggerPreviewSquad(t *testing.T, name, leaderID string) string {
+ t.Helper()
+
+ var squadID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
+ VALUES ($1, $2, '', $3, $4)
+ RETURNING id
+ `, testWorkspaceID, name, 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)
+ })
+ return squadID
+}
+
+func requirePreviewAgents(t *testing.T, preview CommentTriggerPreviewResponse, wantIDs ...string) {
+ t.Helper()
+ if len(preview.Agents) != len(wantIDs) {
+ t.Fatalf("preview agents = %+v, want ids %v", preview.Agents, wantIDs)
+ }
+ got := make(map[string]struct{}, len(preview.Agents))
+ for _, agent := range preview.Agents {
+ got[agent.ID] = struct{}{}
+ }
+ for _, want := range wantIDs {
+ if _, ok := got[want]; !ok {
+ t.Fatalf("preview agents = %+v, missing id %s", preview.Agents, want)
+ }
+ }
+}
+
func TestPreviewCommentTriggers_ReturnsMentionedAgentsAndSuppressFiltersCreate(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -125,6 +176,145 @@ func TestPreviewCommentTriggers_ReturnsMentionedAgentsAndSuppressFiltersCreate(t
}
}
+func TestPreviewCommentTriggers_EditExcludesSameCommentPendingTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "Edit Preview Exclude Agent", nil)
+
+ t.Run("agent assignee on-comment", func(t *testing.T) {
+ issueID := createCommentTriggerPreviewIssue(t, "edit preview assignee", "agent", agentID)
+ commentID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "please start here",
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 1 {
+ t.Fatalf("queued tasks before edit preview = %d, want 1", got)
+ }
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{
+ "content": "actually start over here",
+ "editing_comment_id": commentID,
+ })
+ requirePreviewAgents(t, preview, agentID)
+ if preview.Agents[0].Source != string(commentTriggerSourceIssueAssignee) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceIssueAssignee)
+ }
+ })
+
+ t.Run("squad assignee on-comment", func(t *testing.T) {
+ squadID := createCommentTriggerPreviewSquad(t, "Edit Preview Assignee Squad", agentID)
+ issueID := createCommentTriggerPreviewIssue(t, "edit preview squad assignee", "squad", squadID)
+ commentID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "please coordinate this",
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 1 {
+ t.Fatalf("queued tasks before edit preview = %d, want 1", got)
+ }
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{
+ "content": "actually coordinate this instead",
+ "editing_comment_id": commentID,
+ })
+ requirePreviewAgents(t, preview, agentID)
+ if preview.Agents[0].Source != string(commentTriggerSourceIssueAssignee) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceIssueAssignee)
+ }
+ })
+
+ t.Run("direct agent mention", func(t *testing.T) {
+ issueID := createCommentTriggerPreviewIssue(t, "edit preview agent mention", "", "")
+ content := fmt.Sprintf("[@Agent](mention://agent/%s) inspect this", agentID)
+ commentID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": content,
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 1 {
+ t.Fatalf("queued tasks before edit preview = %d, want 1", got)
+ }
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{
+ "content": content + " again",
+ "editing_comment_id": commentID,
+ })
+ requirePreviewAgents(t, preview, agentID)
+ if preview.Agents[0].Source != string(commentTriggerSourceMentionAgent) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceMentionAgent)
+ }
+ })
+
+ t.Run("squad mention leader", func(t *testing.T) {
+ squadID := createCommentTriggerPreviewSquad(t, "Edit Preview Mention Squad", agentID)
+ issueID := createCommentTriggerPreviewIssue(t, "edit preview squad mention", "", "")
+ content := fmt.Sprintf("[@Squad](mention://squad/%s) inspect this", squadID)
+ commentID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": content,
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 1 {
+ t.Fatalf("queued tasks before edit preview = %d, want 1", got)
+ }
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{
+ "content": content + " again",
+ "editing_comment_id": commentID,
+ })
+ requirePreviewAgents(t, preview, agentID)
+ if preview.Agents[0].Source != string(commentTriggerSourceMentionSquadLeader) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceMentionSquadLeader)
+ }
+ })
+}
+
+func TestPreviewCommentTriggers_EditExclusionDoesNotIgnoreOtherCommentPendingTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "Edit Preview Other Pending Agent", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "edit preview other pending", "", "")
+ content := fmt.Sprintf("[@Agent](mention://agent/%s) inspect this", agentID)
+ _ = postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": content,
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 1 {
+ t.Fatalf("queued tasks before edit preview = %d, want 1", got)
+ }
+ editingCommentID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "plain follow-up with no mention",
+ })
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{
+ "content": content,
+ "editing_comment_id": editingCommentID,
+ })
+ requirePreviewAgents(t, preview)
+}
+
+func TestUpdateComment_SuppressAgentIDsFiltersEditRetrigger(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ agentA := createHandlerTestAgent(t, "Edit Suppress A", nil)
+ agentB := createHandlerTestAgent(t, "Edit Suppress B", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "edit suppress agent ids", "", "")
+ commentID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "plain comment",
+ })
+ content := fmt.Sprintf("[@A](mention://agent/%s) [@B](mention://agent/%s) inspect this", agentA, agentB)
+
+ updateCommentForTriggerPreviewTest(t, commentID, map[string]any{
+ "content": content,
+ "suppress_agent_ids": []string{agentB},
+ })
+
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentA); got != 1 {
+ t.Fatalf("unsuppressed agent queued tasks = %d, want 1", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentB); got != 0 {
+ t.Fatalf("suppressed agent queued tasks = %d, want 0", got)
+ }
+}
+
func TestCreateComment_SuppressUnknownAgentIDIsNoop(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index aee2a12560..7b2be7c54e 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -2573,7 +2573,7 @@ func (h *Handler) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bo
// 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
// task to the private agent simply by commenting (#3300).
-func (h *Handler) shouldEnqueueOnComment(ctx context.Context, issue db.Issue, actorType, actorID string) bool {
+func (h *Handler) shouldEnqueueOnComment(ctx context.Context, issue db.Issue, actorType, actorID string, opts commentTriggerComputeOptions) bool {
if !issue.AssigneeType.Valid || issue.AssigneeType.String != "agent" || !issue.AssigneeID.Valid {
return false
}
@@ -2587,10 +2587,7 @@ func (h *Handler) shouldEnqueueOnComment(ctx context.Context, issue db.Issue, ac
// Coalescing queue: allow enqueue when a task is running (so the agent
// picks up new comments on the next cycle) but skip if this agent already
// has a pending task (natural dedup for rapid-fire comments).
- hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
- IssueID: issue.ID,
- AgentID: issue.AssigneeID,
- })
+ hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, issue.AssigneeID, opts)
if err != nil || hasPending {
return false
}
diff --git a/server/internal/handler/mention_self_trigger_test.go b/server/internal/handler/mention_self_trigger_test.go
index 6a633a1853..a4e7ae27bc 100644
--- a/server/internal/handler/mention_self_trigger_test.go
+++ b/server/internal/handler/mention_self_trigger_test.go
@@ -14,7 +14,7 @@ import (
// 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)
+ triggers := testHandler.computeMentionedAgentCommentTriggers(ctx, issue, comment.Content, parentComment, authorType, authorID, commentTriggerComputeOptions{})
testHandler.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
}
diff --git a/server/internal/handler/squad_comment_trigger_test.go b/server/internal/handler/squad_comment_trigger_test.go
index 39f448a1a1..2004313fac 100644
--- a/server/internal/handler/squad_comment_trigger_test.go
+++ b/server/internal/handler/squad_comment_trigger_test.go
@@ -46,7 +46,7 @@ func TestCommentMentionsAnyone(t *testing.T) {
// 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)
+ _, ok := testHandler.computeAssignedSquadLeaderCommentTrigger(ctx, issue, content, authorType, authorID, commentTriggerComputeOptions{})
return ok
}
diff --git a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md b/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
index 2293e4ff1b..f92fd30fe3 100644
--- a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
@@ -1,6 +1,6 @@
---
name: multica-mentioning
-description: "Use when an issue comment needs to @mention someone — link to a person, trigger another agent, hand work to a squad, or broadcast with @all. Documents the verified mention contract: how a mention link is built from a real UUID, the four mention types and exactly what each one enqueues (agent → a run for that agent, squad → a run for the squad leader, member and issue → a rendered link with NO run), the @all broadcast and how it suppresses the assignee's auto-trigger, and the silent no-op cases (a name where a UUID belongs, a bad/unknown UUID, an already-pending task, an archived agent, a private agent you cannot access). WHETHER to mention — loop avoidance, staying silent on acknowledgements — lives in the runtime brief's Mentions section, not here. This skill is the backend contract only, traced to server/internal/util/mention.go and server/internal/handler/comment.go."
+description: "Use when an issue comment needs to @mention someone — link to a person, trigger another agent, hand work to a squad, or broadcast with @all. Documents the verified mention contract: how a mention link is built from a real UUID, the four mention types and exactly what each one enqueues (agent → a run for that agent, squad → a run for the squad leader, member and issue → a rendered link with NO run), comment create/edit preview and suppression, the @all broadcast and how it suppresses the assignee's auto-trigger, and the silent no-op cases (a name where a UUID belongs, a bad/unknown UUID, an already-pending task, an archived agent, a private agent you cannot access). WHETHER to mention — loop avoidance, staying silent on acknowledgements — lives in the runtime brief's Mentions section, not here. This skill is the backend contract only, traced to server/internal/util/mention.go and server/internal/handler/comment.go."
user-invocable: false
allowed-tools: Bash(multica *)
---
@@ -73,15 +73,22 @@ 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.
+creating or editing a comment. The preview endpoint uses the same
+`computeCommentAgentTriggers` function as create and edit re-triggering, so the
+displayed agent chips come from backend rules, not from a client-side
+reimplementation.
+
+When previewing an edit, clients may send `editing_comment_id`. The server
+validates that the comment belongs to the same workspace and issue, derives or
+checks the edit's parent comment context, and excludes only pending tasks whose
+`trigger_comment_id` is that same comment. Pending tasks from any other comment
+on the issue still dedupe the preview.
+
+When creating or editing 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
@@ -109,8 +116,10 @@ These are all silent no-ops — no error, no run:
mechanism is the lookup miss, not a parse failure.
- **An already-pending task.** Even a correct `@agent`/`@squad` is skipped when
the target already has a pending task on this issue
- (`HasPendingTaskForIssueAndAgent` → `continue`). This is the loop guard — do
- not retry.
+ (`HasPendingTaskForIssueAndAgent` → `continue`). Edit preview is the only
+ exception: `editing_comment_id` ignores pending tasks from the same comment
+ being edited, because save cancels those old tasks before it re-computes
+ triggers. It is still comment-scoped, not an agent-wide bypass.
- **An archived agent**, or a squad whose leader is archived: skipped
(`RuntimeID` invalid or `ArchivedAt` set).
- **A private agent you cannot access:** skipped — the mention path gates on
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 9844503af4..134a6507fb 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
@@ -2,7 +2,7 @@
Every claim in `SKILL.md` traces to a line below. Re-derive against the current
tree before trusting any line number; the behavior is the contract, the line is
-a pointer. Branch where verified: `feat/builtin-skills`.
+a pointer.
## The mention grammar (what parses)
@@ -30,37 +30,62 @@ a pointer. Branch where verified: `feat/builtin-skills`.
| Fact | Source |
| --- | --- |
-| `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` |
+| `computeCommentAgentTriggers` is the shared comment trigger computation used by preview and enqueueing | `server/internal/handler/comment.go:1159-1195` |
+| `computeMentionedAgentCommentTriggers` builds the mention trigger set; `enqueueCommentAgentTriggers` is the shared enqueue helper | `server/internal/handler/comment.go:1381-1467,1124-1157` |
+| Comment creation runs `triggerTasksForComment`, which computes triggers, applies suppressions, then enqueues | `server/internal/handler/comment.go:1069,1092-1098` |
+| Comment edit re-triggering also runs `triggerTasksForComment` after cancelling old tasks for the edited comment | `server/internal/handler/comment.go:1577-1594` |
+| `squad` branch: resolve squad in workspace, read `LeaderID`, add the leader trigger | `server/internal/handler/comment.go:1397-1435` |
+| `squad` → shared enqueue helper calls `EnqueueTaskForSquadLeader` | `server/internal/handler/comment.go:1141-1147` |
+| Everything not `agent` after the squad branch is skipped: `if m.Type != "agent" { continue }` | `server/internal/handler/comment.go:1437-1439` |
+| `agent` branch: load agent in workspace, then add the agent trigger | `server/internal/handler/comment.go:1440-1464` |
+| `agent` → shared enqueue helper calls `EnqueueTaskForMention` (a run for that agent) | `server/internal/handler/comment.go:1148-1154` |
+| **`member` and `issue` mentions reach neither branch — they enqueue NOTHING.** A `member` mention fails the `!= "agent"` skip at lines 1437-1439 (the squad branch above it only matches `squad`); an `issue` mention does the same. | `server/internal/handler/comment.go:1397,1437-1439` |
## 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` |
+| Preview handler loads the issue, expands issue identifiers, then calls `computeCommentAgentTriggers` | `server/internal/handler/comment.go:837-911` |
+| Preview request accepts `content`, optional `parent_id`, and optional `editing_comment_id` | `server/internal/handler/comment.go:778-782` |
+| Preview response returns agent `id`, `name`, optional `avatar_url`, `source`, and `reason` | `server/internal/handler/comment.go:784-793` |
+| `editing_comment_id` is parsed as UUID input, scoped to the same workspace and issue, and used as `ExcludeTriggerCommentID` | `server/internal/handler/comment.go:855-872` |
+| Preview validates or derives the parent context for an edit | `server/internal/handler/comment.go:874-897` |
| `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` |
+| `UpdateComment` accepts optional `suppress_agent_ids` | `server/internal/handler/comment.go:1509-1513` |
+| Create-comment `suppress_agent_ids` is parsed as request-boundary UUID input | `server/internal/handler/comment.go:957-964` |
+| Update-comment `suppress_agent_ids` is parsed as request-boundary UUID input | `server/internal/handler/comment.go:1523-1535` |
+| Create and edit trigger paths compute the full trigger set, then apply `filterSuppressedCommentAgentTriggers` before enqueueing | `server/internal/handler/comment.go:1092-1122,1594` |
+| Frontend API sends `editing_comment_id` for preview and `suppress_agent_ids` for update when present | `packages/core/api/client.ts:664-700` |
+| Edit UI calls preview with `editingCommentId`, renders trigger chips, tracks suppressed agents, and submits suppressions on save | `packages/views/issues/components/comment-card.tsx:269-274,300-315,359-367,578-582,858-862` |
+| Preview hook includes `editingCommentId` in its query key and sends it to the API | `packages/views/issues/hooks/use-comment-trigger-preview.ts:58-80` |
+| Timeline edit mutation passes suppressed agent IDs through to the API layer | `packages/views/issues/hooks/use-issue-timeline.ts:299-302` |
+
+## Edit-preview pending-task dedup
+
+| Fact | Source |
+| --- | --- |
+| Default dedup query skips any queued or dispatched task for the issue and agent | `server/pkg/db/queries/agent.sql:544-548` |
+| Edit-preview dedup query excludes only tasks whose `trigger_comment_id` equals the edited comment | `server/pkg/db/queries/agent.sql:550-558` |
+| `hasPendingTaskForIssueAndAgent` selects the comment-scoped exclusion only when `ExcludeTriggerCommentID` is valid | `server/internal/handler/comment.go:1232-1244` |
+| Agent-assignee on-comment dedup uses the shared helper | `server/internal/handler/issue.go:2576-2594` |
+| Assigned squad leader on-comment dedup uses the shared helper | `server/internal/handler/comment.go:1197-1229` |
+| Mentioned squad leader dedup uses the shared helper | `server/internal/handler/comment.go:1397-1435` |
+| Direct agent mention dedup uses the shared helper | `server/internal/handler/comment.go:1440-1464` |
+| Positive regression test covers all four edit-preview trigger sources | `server/internal/handler/comment_trigger_preview_test.go:179-265` |
+| Negative regression test proves another comment's pending task still dedupes the preview | `server/internal/handler/comment_trigger_preview_test.go:267-290` |
+| Edit-submit regression test proves `suppress_agent_ids` filters update-triggered tasks | `server/internal/handler/comment_trigger_preview_test.go:292-316` |
## 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: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` |
+| agent archived / no runtime → `continue` (`RuntimeID` invalid or `ArchivedAt` set) | `server/internal/handler/comment.go:1451-1452` |
+| squad leader archived / no runtime → `continue` | `server/internal/handler/comment.go:1417-1423` |
+| private agent the actor cannot access → `continue` (`canAccessPrivateAgent`) | `server/internal/handler/comment.go:1454-1458` |
+| private squad leader the actor cannot trigger → `continue` (`canAccessPrivateAgent`) | `server/internal/handler/comment.go:1425-1428` |
+| already-pending dedup (agent) → shared pending-task helper → `continue` | `server/internal/handler/comment.go:1459-1463` |
+| already-pending dedup (squad leader) → shared pending-task helper → `continue` | `server/internal/handler/comment.go:1429-1433` |
| `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` |
@@ -68,10 +93,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: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` |
+| `commentMentionsOthersButNotAssignee` — decides whether to suppress the assignee's on-comment trigger | `server/internal/handler/comment.go:1246-1288` |
+| `@all` is treated as a broadcast → returns true → assignee auto-trigger suppressed | `server/internal/handler/comment.go:1257-1261` |
+| Comment-flow computation that consults it | `server/internal/handler/comment.go:1175-1177` |
+| `@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:1437-1439` |
## CLI id sources (where the UUID comes from)
@@ -89,7 +114,7 @@ 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: `computeMentionedAgentCommentTriggers`
branches only on `squad` and `agent`
-(`server/internal/handler/comment.go:1352,1394-1396`), and a grep of the file for
+(`server/internal/handler/comment.go:1397,1437-1439`), 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/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index c7e2c191e2..bf8e7648c1 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -1671,6 +1671,30 @@ func (q *Queries) HasPendingTaskForIssueAndAgent(ctx context.Context, arg HasPen
return has_pending, err
}
+const hasPendingTaskForIssueAndAgentExcludingTriggerComment = `-- name: HasPendingTaskForIssueAndAgentExcludingTriggerComment :one
+SELECT count(*) > 0 AS has_pending FROM agent_task_queue
+WHERE issue_id = $1
+ AND agent_id = $2
+ AND status IN ('queued', 'dispatched')
+ AND trigger_comment_id IS DISTINCT FROM $3::uuid
+`
+
+type HasPendingTaskForIssueAndAgentExcludingTriggerCommentParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ ExcludeTriggerCommentID pgtype.UUID `json:"exclude_trigger_comment_id"`
+}
+
+// Same as HasPendingTaskForIssueAndAgent, but ignores tasks triggered by the
+// current comment being edited. Edit preview needs this because save cancels
+// that comment's old queued/dispatched tasks before re-computing triggers.
+func (q *Queries) HasPendingTaskForIssueAndAgentExcludingTriggerComment(ctx context.Context, arg HasPendingTaskForIssueAndAgentExcludingTriggerCommentParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasPendingTaskForIssueAndAgentExcludingTriggerComment, arg.IssueID, arg.AgentID, arg.ExcludeTriggerCommentID)
+ var has_pending bool
+ err := row.Scan(&has_pending)
+ return has_pending, err
+}
+
const linkTaskToIssue = `-- name: LinkTaskToIssue :exec
UPDATE agent_task_queue
SET issue_id = $2
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 558fd99fdc..0d867f0c1f 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -547,6 +547,16 @@ WHERE issue_id = $1 AND status IN ('queued', 'dispatched');
SELECT count(*) > 0 AS has_pending FROM agent_task_queue
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched');
+-- name: HasPendingTaskForIssueAndAgentExcludingTriggerComment :one
+-- Same as HasPendingTaskForIssueAndAgent, but ignores tasks triggered by the
+-- current comment being edited. Edit preview needs this because save cancels
+-- that comment's old queued/dispatched tasks before re-computing triggers.
+SELECT count(*) > 0 AS has_pending FROM agent_task_queue
+WHERE issue_id = @issue_id
+ AND agent_id = @agent_id
+ AND status IN ('queued', 'dispatched')
+ AND trigger_comment_id IS DISTINCT FROM @exclude_trigger_comment_id::uuid;
+
-- name: GetLatestTaskIsLeaderForIssueAndAgent :one
-- Returns the is_leader_task flag of the agent's most recent task on this
-- issue, or NULL if the agent has never had a task on this issue. Used by