Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: steer a running agent from the normal composer, per recipient (MUL-7631) (#8760)
Jiayuan Zhange2f4a2203017
diff --git a/e2e/comment-steering.spec.ts b/e2e/comment-steering.spec.tsnew file mode 100644index 0000000000..8188aa1685--- /dev/null+++ b/e2e/comment-steering.spec.ts@@ -0,0 +1,98 @@+import "./env";++import { expect, test } from "@playwright/test";+import pg from "pg";+import { createTestApi } from "./helpers";++// Steering matrices live in the Go handler and composer tests. This browser+// regression covers the real path: a reply in a running agent's thread goes+// into that turn by default, and its receipt follows delivery.+test("a reply steers the thread agent's running turn and shows its receipt", async ({ page }, testInfo) => {+ test.setTimeout(120_000);+ const api = await createTestApi();+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ let runtimeId: string | undefined;+ let agentId: string | undefined;+ try {+ const workspace = (await api.getWorkspaces())[0]!;+ const user = await db.query<{ id: string }>(`SELECT id FROM "user" WHERE email = $1`, [api.getEmail()]);+ const userId = user.rows[0]!.id;+ const runtime = await db.query<{ id: string }>(+ `INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)+ VALUES ($1, 'Steering verification', 'cloud', 'codex', 'online', 'E2E fixture', '{}'::jsonb, $2, now()) RETURNING id`,+ [workspace.id, userId],+ );+ runtimeId = runtime.rows[0]!.id;+ const agent = await db.query<{ id: string }>(+ `INSERT INTO agent (workspace_id, name, description, instructions, runtime_mode, runtime_config, runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id)+ VALUES ($1, 'Lambda', '', '', 'cloud', '{}'::jsonb, $2, 'private', 'private', 1, $3) RETURNING id`,+ [workspace.id, runtimeId, userId],+ );+ agentId = agent.rows[0]!.id;+ const issue = await api.createIssue("Fix the Safari 17 login page");+ const root = await db.query<{ id: string }>(+ `INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, $4) RETURNING id`,+ [workspace.id, issue.id, userId, `[@Lambda](mention://agent/${agentId}) The login page is blank in Safari 17. Find the cause and fix it.`],+ );+ const rootId = root.rows[0]!.id;+ const turn = await db.query<{ id: string }>(+ `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, dispatched_at, started_at)+ VALUES ($1, $2, $3, $4, ARRAY[$4]::uuid[], 'running', now() - interval '2 minutes', now() - interval '2 minutes') RETURNING id`,+ [agentId, runtimeId, issue.id, rootId],+ );+ const turnId = turn.rows[0]!.id;+ await db.query(+ `INSERT INTO task_supplement_capability (task_id, workspace_id, issue_id, capability) VALUES ($1, $2, $3, 'task-supplement-v1')`,+ [turnId, workspace.id, issue.id],+ );++ await page.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, api.getToken());+ await page.setViewportSize({ width: 1440, height: 1000 });+ await page.goto(`/${workspace.slug}/issues/${issue.id}`, { waitUntil: "domcontentloaded" });+ await expect(page.locator(`[data-run-id="${turnId}"]`)).toBeVisible({ timeout: 45_000 });++ const shell = page.getByTestId("reply-composer-shell").first();+ // The empty box makes no claim about who a reply goes to; the chip says+ // so once there is text and the recipient is known.+ await expect(shell).toHaveText("Leave a reply...");+ await shell.click();+ const placeholder = "Leave a reply...";+ const editor = page.locator(`.ProseMirror[data-placeholder="${placeholder}"], .ProseMirror:has([data-placeholder="${placeholder}"])`).first();+ await editor.fill("This PR only fixes web; leave the desktop login page alone.");+ const chip = page.getByRole("button", { name: "Lambda trigger: Add to current run" });+ await expect(chip).toBeVisible({ timeout: 15_000 });+ await page.screenshot({ path: testInfo.outputPath("steer-composer.png") });+ await chip.click();+ await expect(page.getByRole("menuitemradio", { name: /Stop and start over/ })).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath("steer-menu.png") });+ await page.keyboard.press("Escape");++ const posted = page.waitForResponse((response) => response.request().method() === "POST" && response.url().endsWith(`/api/issues/${issue.id}/comments`));+ await page.getByRole("button", { name: "Send", exact: true }).first().click();+ const response = await posted;+ expect(response.status()).toBe(201);+ const reply = await response.json();+ expect(reply.supplements).toEqual([expect.objectContaining({ task_id: turnId, agent_id: agentId, status: "pending" })]);+ const runs = await db.query(`SELECT id FROM agent_task_queue WHERE issue_id = $1`, [issue.id]);+ expect(runs.rows).toHaveLength(1);+ await expect(page.getByText("Waiting for Lambda to read it")).toBeVisible();+ await expect(page.getByText("Added to Lambda's run")).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath("steer-sent.png") });++ await db.query(`UPDATE task_supplement SET status = 'delivered', delivered_at = now() WHERE comment_id = $1`, [reply.id]);+ await page.reload({ waitUntil: "domcontentloaded" });+ await expect(page.getByText("Read by Lambda")).toBeVisible({ timeout: 30_000 });+ await page.screenshot({ path: testInfo.outputPath("steer-delivered.png") });+ } finally {+ await api.cleanup();+ if (agentId) await db.query(`DELETE FROM agent_task_queue WHERE agent_id = $1`, [agentId]);+ if (agentId) await db.query(`DELETE FROM agent WHERE id = $1`, [agentId]);+ if (runtimeId) await db.query(`DELETE FROM agent_runtime WHERE id = $1`, [runtimeId]);+ await db.end();+ }+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex a53f706d3f..bfe821ea42 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1541,6 +1541,7 @@ export class ApiClient {parentId?: string,attachmentIds?: string[],suppressAgentIds?: string[],+ steerTaskIds?: string[],): Promise<Comment> {return this.fetch(`/api/issues/${issueId}/comments`, {method: "POST",@@ -1550,6 +1551,7 @@ export class ApiClient {...(parentId ? { parent_id: parentId } : {}),...(attachmentIds?.length ? { attachment_ids: attachmentIds } : {}),...(suppressAgentIds?.length ? { suppress_agent_ids: suppressAgentIds } : {}),+ ...(steerTaskIds?.length ? { steer_task_ids: steerTaskIds } : {}),}),});}@@ -2692,18 +2694,6 @@ export class ApiClient {});}- async createTaskSupplement(issueId: string, taskId: string, content: string, clientRequestId: string): Promise<Comment> {- const raw = await this.fetch<unknown>(`/api/issues/${issueId}/tasks/${taskId}/supplements`, {- method: "POST",- body: JSON.stringify({ content, client_request_id: clientRequestId }),- });- const comment = parseWithFallback<Comment>(raw, CommentSchema, EMPTY_COMMENT, {- endpoint: "POST /api/issues/:id/tasks/:taskId/supplements",- });- if (!comment.id) throw new Error("Invalid additional-message response");- return comment;- }-async retryTaskSupplement(issueId: string, taskId: string, commentId: string): Promise<void> {await this.fetch(`/api/issues/${issueId}/tasks/${taskId}/supplements/${commentId}/retry`, {method: "POST",diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 1be3216a9c..6efded1c7d 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -912,6 +912,22 @@ export const EMPTY_ATTACHMENT: Attachment = {// wasn't updated in lock-step. `.loose()` removes that synchronisation// hazard — the schema validates the shape it knows about and leaves the// rest alone.+// One receipt per running turn a comment steered. A malformed receipt is+// dropped on its own rather than failing the whole comment.+const CommentSupplementReceiptSchema = z.object({+ task_id: z.string(),+ agent_id: z.string().optional().catch(undefined),+ status: z.enum(["pending", "delivering", "delivered", "failed"]),+ failure_reason: z.string().optional().catch(undefined),+ delivered_at: z.string().optional().catch(undefined),+});++const CommentSupplementReceiptsSchema = z.array(z.unknown()).optional().catch(undefined)+ .transform((raw) => raw?.flatMap((item) => {+ const parsed = CommentSupplementReceiptSchema.safeParse(item);+ return parsed.success ? [parsed.data] : [];+ }));+const TimelineEntrySchema = z.object({type: z.string(),id: z.string(),@@ -930,6 +946,7 @@ const TimelineEntrySchema = z.object({reactions: z.array(ReactionSchema).optional(),attachments: z.array(AttachmentSchema).optional(),source_task_id: z.string().nullable().optional(),+ supplements: CommentSupplementReceiptsSchema,supplement_task_id: z.string().optional().catch(undefined),supplement_status: z.enum(["pending", "delivering", "delivered", "failed"]).optional().catch(undefined),supplement_failure_reason: z.string().optional().catch(undefined),@@ -1079,6 +1096,7 @@ export const CommentSchema = z.object({updated_at: z.string(),revision: z.number().int().positive().optional(),source_task_id: z.string().nullable().optional(),+ supplements: CommentSupplementReceiptsSchema,supplement_task_id: z.string().optional().catch(undefined),supplement_status: z.enum(["pending", "delivering", "delivered", "failed"]).optional().catch(undefined),supplement_failure_reason: z.string().optional().catch(undefined),diff --git a/packages/core/drafts/register-all-drafts.ts b/packages/core/drafts/register-all-drafts.tsindex 5996800153..1f7e399d6c 100644--- a/packages/core/drafts/register-all-drafts.ts+++ b/packages/core/drafts/register-all-drafts.ts@@ -17,7 +17,16 @@import "../issues/stores/draft-store";import "../issues/stores/quick-create-store";import "../issues/stores/comment-draft-store";-import "../issues/stores/task-supplement-draft-store";import "../projects/draft-store";import "../feedback/draft-store";import "../agents/manual-draft-store";+import { registerDraftCleanup } from "./cleanup-registry";++// Retired: drafts for a running turn now live in the thread's reply draft.+// Keep clearing the old persisted key so text written before the move never+// outlives logout or workspace removal.+registerDraftCleanup({+ storageKey: "multica_task_supplement_drafts",+ workspaceScoped: true,+ resetInMemory: () => {},+});diff --git a/packages/core/issues/comment-trigger-outcomes.ts b/packages/core/issues/comment-trigger-outcomes.tsindex e5cb8ec40a..95540b8a1f 100644--- a/packages/core/issues/comment-trigger-outcomes.ts+++ b/packages/core/issues/comment-trigger-outcomes.ts@@ -69,11 +69,12 @@ export function parseCommentTriggerOutcomes(raw: unknown): CommentTriggerOutcome}// The only success-shaped outcome statuses: the mention WAS handled (a run was-// queued, coalesced into an existing run, or intentionally deferred). Success is+// queued, coalesced into an existing run, intentionally deferred, or the comment+// went into the target's running turn). Success is// a WHITELIST, not "anything that isn't blocked", so an unknown/future status —// or the empty status the schema defaults for a malformed entry — never passes// as success (MUL-4525; mirrors the Run now whitelist).-const HANDLED_TRIGGER_STATUSES = new Set(["queued", "coalesced", "deferred"]);+const HANDLED_TRIGGER_STATUSES = new Set(["queued", "coalesced", "deferred", "steered"]);// The explicit @agent / @squad mentions that did NOT clearly trigger, so the// "posted, but N not triggered" warning must cover them: `blocked` plus anydiff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex a2cdaf0ac4..5dfc3cc81d 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -37,7 +37,7 @@ import {} from "./delete-cache";import { useWorkspaceId } from "../hooks";import { useRecentContextStore } from "../chat/recent-context-store";-import { useRecentIssuesStore, useTaskSupplementDraftStore } from "./stores";+import { useRecentIssuesStore } from "./stores";import type { InboxItem, Issue, IssueReaction } from "../types";import type {CreateCommentSubIssueManualRequest,@@ -832,13 +832,16 @@ export function useCreateComment(issueId: string) {parentId,attachmentIds,suppressAgentIds,+ steerTaskIds,}: {content: string;type?: string;parentId?: string;attachmentIds?: string[];suppressAgentIds?: string[];- }) => api.createComment(issueId, content, type, parentId, attachmentIds, suppressAgentIds),+ /** Running turns this comment goes into instead of a follow-up run. */+ steerTaskIds?: string[];+ }) => api.createComment(issueId, content, type, parentId, attachmentIds, suppressAgentIds, steerTaskIds),onSuccess: (comment) => {if (comment.issue_revision) {onIssueAuxiliaryRevision(qc, wsId, issueId, comment.issue_revision);@@ -858,15 +861,24 @@ export function useCreateComment(issueId: string) {attachments: comment.attachments ?? [],created_at: comment.created_at,updated_at: comment.updated_at,+ supplements: comment.supplements,};+ const steered = !!comment.supplements?.length;// Dedupe by id: the `comment:created` WS event may have already added// this entry from the broadcast path before this onSuccess fires. Skip- // the append if the entry is already in the cache.+ // the append if the entry is already in the cache — but keep the+ // steering receipts, which that broadcast predates.qc.setQueryData<TimelineCache>(issueKeys.timeline(issueId), (old) => {if (!old) return [entry];- if (old.some((e) => e.id === entry.id)) return old;+ if (old.some((e) => e.id === entry.id)) {+ return steered+ ? old.map((e) => (e.id === entry.id && !e.supplements?.length ? { ...e, supplements: entry.supplements } : e))+ : old;+ }return sortTimelineEntriesAsc([...old, entry]);});+ // A steered turn now lists this comment among its inputs.+ if (steered) qc.invalidateQueries({ queryKey: issueKeys.tasks(issueId) });// 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.@@ -1208,48 +1220,6 @@ export function useCancelIssueRun(issueId: string) {});}-export function useCreateTaskSupplement(issueId: string) {- const client = useQueryClient();- return useMutation({- mutationFn: ({ taskId, content, clientRequestId }: {- taskId: string;- content: string;- clientRequestId: string;- }) => api.createTaskSupplement(issueId, taskId, content, clientRequestId),- onSuccess: (comment, { taskId, clientRequestId }) => {- // Re-anchoring the run can unmount its composer before this response.- // Clear the submitted draft here, without discarding any newer edits.- const drafts = useTaskSupplementDraftStore.getState();- if (drafts.drafts[taskId]?.clientRequestId === clientRequestId) {- drafts.clear(taskId);- }- const entry: TimelineEntry = {- type: "comment",- id: comment.id,- actor_type: comment.author_type,- actor_id: comment.author_id,- content: comment.content,- parent_id: comment.parent_id,- comment_type: comment.type,- reactions: comment.reactions ?? [],- attachments: comment.attachments ?? [],- created_at: comment.created_at,- updated_at: comment.updated_at,- supplement_task_id: comment.supplement_task_id,- supplement_status: comment.supplement_status,- supplement_failure_reason: comment.supplement_failure_reason,- supplement_delivered_at: comment.supplement_delivered_at,- };- client.setQueryData<TimelineCache>(issueKeys.timeline(issueId), (old) => {- if (!old) return [entry];- if (old.some((item) => item.id === entry.id)) return old;- return sortTimelineEntriesAsc([...old, entry]);- });- client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) });- },- });-}-export function useRetryTaskSupplement(issueId: string) {const client = useQueryClient();return useMutation({diff --git a/packages/core/issues/run-steering.test.ts b/packages/core/issues/run-steering.test.tsnew file mode 100644index 0000000000..743ee47a44--- /dev/null+++ b/packages/core/issues/run-steering.test.ts@@ -0,0 +1,86 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { AgentTask } from "../types";+import { agentRunState, commentSupplementReceipts, recipientActions, recipientRouting, resolveRecipientAction, TASK_SUPPLEMENT_CAPABILITY } from "./run-steering";++function task(over: Partial<AgentTask>): AgentTask {+ return {+ id: "task", agent_id: "agent", issue_id: "issue", status: "running", priority: 0,+ dispatched_at: null, started_at: null, completed_at: null, result: null, error: null,+ created_at: "2026-09-23T00:00:00Z", ...over,+ } as AgentTask;+}++describe("agentRunState", () => {+ it("reports a steerable running turn only with the negotiated capability and permission", () => {+ const steerable = task({ supplement_capability: TASK_SUPPLEMENT_CAPABILITY, can_supplement: true });+ expect(agentRunState([steerable], "agent")).toEqual({ kind: "running", task: steerable, steerable: true });+ const unsupported = task({ can_supplement: true });+ expect(agentRunState([unsupported], "agent")).toMatchObject({ kind: "running", steerable: false });+ const forbidden = task({ supplement_capability: TASK_SUPPLEMENT_CAPABILITY, can_supplement: false });+ expect(agentRunState([forbidden], "agent")).toMatchObject({ kind: "running", steerable: false });+ });++ it("prefers the running turn over a queued follow-up for the same agent", () => {+ const queued = task({ id: "next", status: "queued" });+ const running = task({ id: "now" });+ expect(agentRunState([queued, running], "agent")).toMatchObject({ kind: "running", task: { id: "now" } });+ });++ it("separates a starting turn from a queued one and ignores other agents", () => {+ expect(agentRunState([task({ status: "dispatched" })], "agent").kind).toBe("starting");+ expect(agentRunState([task({ status: "waiting_local_directory" })], "agent").kind).toBe("starting");+ expect(agentRunState([task({ status: "deferred" })], "agent").kind).toBe("queued");+ expect(agentRunState([task({ status: "completed" }), task({ agent_id: "other" })], "agent").kind).toBe("idle");+ });+});++describe("commentSupplementReceipts", () => {+ it("returns the receipt list, or the single receipt an older server sent", () => {+ const receipts = [{ task_id: "a", agent_id: "x", status: "pending" as const }, { task_id: "b", status: "delivered" as const }];+ expect(commentSupplementReceipts({ supplements: receipts, supplement_task_id: "a", supplement_status: "pending" })).toBe(receipts);+ expect(commentSupplementReceipts({ supplement_task_id: "a", supplement_status: "failed", supplement_failure_reason: "turn_ended" }))+ .toEqual([{ task_id: "a", status: "failed", failure_reason: "turn_ended", delivered_at: undefined }]);+ expect(commentSupplementReceipts({})).toEqual([]);+ });+});++describe("recipient actions", () => {+ const steerable = { kind: "running", task: task({}), steerable: true } as const;+ const busy = { kind: "running", task: task({}), steerable: false } as const;+ const inThread = { canSteer: true, canRestart: true, steerByDefault: true };++ it("offers steering only to a steerable running turn", () => {+ expect(recipientActions(steerable, inThread)).toEqual(["steer", "after_run", "restart", "skip"]);+ expect(recipientActions(busy, inThread)).toEqual(["after_run", "restart", "skip"]);+ expect(recipientActions({ kind: "starting", task: task({ status: "dispatched" }) }, inThread)).toEqual(["after_run", "restart", "skip"]);+ expect(recipientActions({ kind: "idle" }, inThread)).toEqual(["start", "skip"]);+ expect(recipientActions({ kind: "queued", task: task({ status: "queued" }) }, inThread)).toEqual(["start", "skip"]);+ });++ it("defaults to steering only in the running turn's own thread", () => {+ expect(resolveRecipientAction(steerable, undefined, inThread)).toBe("steer");+ expect(resolveRecipientAction(steerable, undefined, { ...inThread, steerByDefault: false })).toBe("after_run");+ expect(resolveRecipientAction(steerable, "steer", { ...inThread, steerByDefault: false })).toBe("steer");+ });++ it("drops a choice that is no longer available", () => {+ // Files cannot go into a running turn.+ expect(resolveRecipientAction(steerable, "steer", { ...inThread, canSteer: false })).toBe("after_run");+ // The turn ended while the message was being written.+ expect(resolveRecipientAction({ kind: "idle" }, "steer", inThread)).toBe("start");+ expect(resolveRecipientAction({ kind: "idle" }, "skip", inThread)).toBe("skip");+ // Editing never stops a run.+ expect(recipientActions(steerable, { canSteer: false, canRestart: false, steerByDefault: false })).toEqual(["after_run", "skip"]);+ });++ it("maps actions to request routing", () => {+ const routing = recipientRouting([+ { agentId: "a", action: "steer", state: steerable },+ { agentId: "b", action: "skip", state: { kind: "idle" } },+ { agentId: "c", action: "restart", state: { kind: "running", task: task({ id: "turn-c" }), steerable: false } },+ { agentId: "d", action: "after_run", state: busy },+ ]);+ expect(routing).toEqual({ steerTaskIds: [steerable.task.id], suppressAgentIds: ["b"], restartTaskIds: ["turn-c"] });+ });+});diff --git a/packages/core/issues/run-steering.ts b/packages/core/issues/run-steering.tsnew file mode 100644index 0000000000..65710adf16--- /dev/null+++ b/packages/core/issues/run-steering.ts@@ -0,0 +1,126 @@+import type { AgentTask, CommentSupplementReceipt, TimelineEntry } from "../types";++/** The run-scoped capability that lets a running turn take additional input. */+export const TASK_SUPPLEMENT_CAPABILITY = "task-supplement-v1";++type ReceiptFields = Pick<+ TimelineEntry,+ "supplements" | "supplement_task_id" | "supplement_status" | "supplement_failure_reason" | "supplement_delivered_at"+>;++/**+ * Every running turn a comment steered. Servers that predate multi-run+ * steering send only the single supplement_* fields, without the agent.+ */+export function commentSupplementReceipts(entry: ReceiptFields): CommentSupplementReceipt[] {+ if (entry.supplements?.length) return entry.supplements;+ if (!entry.supplement_task_id || !entry.supplement_status) return [];+ return [{+ task_id: entry.supplement_task_id,+ status: entry.supplement_status,+ failure_reason: entry.supplement_failure_reason,+ delivered_at: entry.supplement_delivered_at,+ }];+}++/** A receipt whose turn has not received it yet. */+export function isSupplementInFlight(receipt: CommentSupplementReceipt): boolean {+ return receipt.status === "pending" || receipt.status === "delivering";+}++/**+ * What one recipient is doing on this issue right now, which decides how a+ * message to it can be handled: steer a running turn, fold into a queued run,+ * or start a new one.+ */+export type AgentRunState =+ | { kind: "idle" }+ | { kind: "queued"; task: AgentTask }+ | { kind: "starting"; task: AgentTask }+ | { kind: "running"; task: AgentTask; steerable: boolean };++/** Whether this member can add a message to the task's running turn. */+export function isSteerableTask(task: AgentTask): boolean {+ return task.status === "running"+ && task.supplement_capability === TASK_SUPPLEMENT_CAPABILITY+ && task.can_supplement === true;+}++export function agentRunState(tasks: readonly AgentTask[], agentId: string): AgentRunState {+ // A running turn wins over a queued follow-up: it is what a message reaches now.+ let queued: AgentTask | undefined;+ let starting: AgentTask | undefined;+ for (const task of tasks) {+ if (task.agent_id !== agentId) continue;+ if (task.status === "running") return { kind: "running", task, steerable: isSteerableTask(task) };+ if (task.status === "dispatched" || task.status === "waiting_local_directory") starting ??= task;+ else if (task.status === "queued" || task.status === "deferred") queued ??= task;+ }+ if (starting) return { kind: "starting", task: starting };+ if (queued) return { kind: "queued", task: queued };+ return { kind: "idle" };+}++/** How a message reaches one recipient. */+export type RecipientAction =+ /** Into the running turn, read at its next step. */+ | "steer"+ /** Normal trigger while the recipient is busy: handled once this turn ends. */+ | "after_run"+ /** Stop the current turn, then start over with this message. */+ | "restart"+ /** Normal trigger for an idle recipient, or one whose run is still queued. */+ | "start"+ /** Post without triggering this recipient. */+ | "skip";++export interface RecipientActionOptions {+ /** False while editing, or when the message carries files: a running turn takes text only. */+ canSteer: boolean;+ /** False while editing: an edit never stops a run. */+ canRestart: boolean;+ /** Steer by default. The composer sets this for the running turn's own thread. */+ steerByDefault: boolean;+}++export function recipientActions(state: AgentRunState, opts: RecipientActionOptions): RecipientAction[] {+ if (state.kind === "idle" || state.kind === "queued") return ["start", "skip"];+ const actions: RecipientAction[] = [];+ if (state.kind === "running" && state.steerable && opts.canSteer) actions.push("steer");+ actions.push("after_run");+ if (opts.canRestart) actions.push("restart");+ actions.push("skip");+ return actions;+}++/** The chosen action while it is still available, otherwise the default. */+export function resolveRecipientAction(+ state: AgentRunState,+ chosen: RecipientAction | undefined,+ opts: RecipientActionOptions,+): RecipientAction {+ const actions = recipientActions(state, opts);+ if (chosen && actions.includes(chosen)) return chosen;+ if (opts.steerByDefault && actions.includes("steer")) return "steer";+ return actions.find((action) => action !== "steer")!;+}++export interface RecipientRouting {+ suppressAgentIds: string[];+ /** The exact running turns chosen: a turn that ends first is never swapped for another. */+ steerTaskIds: string[];+ /** Turns to stop before the comment is posted, so it starts a fresh run. */+ restartTaskIds: string[];+}++export function recipientRouting(+ recipients: readonly { agentId: string; action: RecipientAction; state: AgentRunState }[],+): RecipientRouting {+ const routing: RecipientRouting = { suppressAgentIds: [], steerTaskIds: [], restartTaskIds: [] };+ for (const { agentId, action, state } of recipients) {+ if (action === "skip") routing.suppressAgentIds.push(agentId);+ else if (action === "steer" && state.kind === "running") routing.steerTaskIds.push(state.task.id);+ else if (action === "restart" && state.kind !== "idle") routing.restartTaskIds.push(state.task.id);+ }+ return routing;+}diff --git a/packages/core/issues/stores/comment-composer-store.test.ts b/packages/core/issues/stores/comment-composer-store.test.tsindex 7e727f0523..f33335aa59 100644--- a/packages/core/issues/stores/comment-composer-store.test.ts+++ b/packages/core/issues/stores/comment-composer-store.test.ts@@ -23,7 +23,7 @@ beforeAll(() => {describe("comment composer store", () => {beforeEach(() => {- useCommentComposerStore.setState({ sticky: true });+ useCommentComposerStore.setState({ sticky: true, runningAgentReply: "steer" });});it("toggleSticky flips the preference", () => {@@ -33,4 +33,17 @@ describe("comment composer store", () => {useCommentComposerStore.getState().toggleSticky();expect(useCommentComposerStore.getState().sticky).toBe(true);});++ it("steers a running agent by default and remembers starting after the run", () => {+ expect(useCommentComposerStore.getState().runningAgentReply).toBe("steer");+ useCommentComposerStore.getState().setRunningAgentReply("after_run");+ expect(useCommentComposerStore.getState().runningAgentReply).toBe("after_run");+ expect(JSON.parse(localStorage.getItem("multica_comment_composer")!).state.runningAgentReply).toBe("after_run");+ });++ it("keeps steering as the default for preferences saved before the option existed", async () => {+ localStorage.setItem("multica_comment_composer", JSON.stringify({ state: { sticky: false }, version: 0 }));+ await useCommentComposerStore.persist.rehydrate();+ expect(useCommentComposerStore.getState()).toMatchObject({ sticky: false, runningAgentReply: "steer" });+ });});diff --git a/packages/core/issues/stores/comment-composer-store.ts b/packages/core/issues/stores/comment-composer-store.tsindex b93a1eef18..bad9558132 100644--- a/packages/core/issues/stores/comment-composer-store.ts+++ b/packages/core/issues/stores/comment-composer-store.ts@@ -3,23 +3,36 @@ import { createJSONStorage, persist } from "zustand/middleware";import { defaultStorage } from "../../platform/storage";/**- * Display preferences for the issue-detail comment composer.+ * What a reply does by default when it reaches a running agent that would+ * otherwise take it in its current turn: `steer` adds it to that turn,+ * `after_run` starts a new run once the current one ends. Either way the+ * composer's recipient chip can change it for a single message.+ */+export type RunningAgentReply = "steer" | "after_run";++/**+ * Personal preferences for the issue-detail comment composer.** `sticky` pins the bottom comment bar to the scroll viewport so it stays- * reachable while reading a long timeline. It's a personal reading-ergonomics- * preference (like theme), so it persists globally via `defaultStorage`- * rather than per-workspace storage.+ * reachable while reading a long timeline. `runningAgentReply` picks the+ * default for a reply to a running agent. Both are personal habits (like+ * theme), so they persist globally via `defaultStorage` rather than+ * per-workspace storage.*/interface CommentComposerStore {sticky: boolean;+ runningAgentReply: RunningAgentReply;toggleSticky: () => void;+ setRunningAgentReply: (value: RunningAgentReply) => void;}export const useCommentComposerStore = create<CommentComposerStore>()(persist((set) => ({sticky: true,+ runningAgentReply: "steer",toggleSticky: () => set((s) => ({ sticky: !s.sticky })),+ setRunningAgentReply: (runningAgentReply) => set({ runningAgentReply }),}),{name: "multica_comment_composer",diff --git a/packages/core/issues/stores/index.ts b/packages/core/issues/stores/index.tsindex d721815240..2995aae741 100644--- a/packages/core/issues/stores/index.ts+++ b/packages/core/issues/stores/index.ts@@ -26,9 +26,8 @@ export {useResolvedExpandStore,selectExpandedResolved,} from "./resolved-expand-store";-export { useCommentComposerStore } from "./comment-composer-store";+export { useCommentComposerStore, type RunningAgentReply } from "./comment-composer-store";export { useCommentDraftStore, type CommentDraftKey } from "./comment-draft-store";-export { useTaskSupplementDraftStore, type TaskSupplementDraft } from "./task-supplement-draft-store";export {myIssuesViewStore,type MyIssuesViewState,diff --git a/packages/core/issues/stores/task-supplement-draft-store.test.ts b/packages/core/issues/stores/task-supplement-draft-store.test.tsdeleted file mode 100644index 5fc88848f2..0000000000--- a/packages/core/issues/stores/task-supplement-draft-store.test.ts+++ /dev/null@@ -1,43 +0,0 @@-// @vitest-environment jsdom-import { beforeEach, describe, expect, it } from "vitest";-import { useTaskSupplementDraftStore } from "./task-supplement-draft-store";--describe("task supplement draft store", () => {- beforeEach(() => useTaskSupplementDraftStore.setState({ drafts: {} }));-- it.each(["", " \n "])("clears an empty terminal draft (%j)", (content) => {- const store = useTaskSupplementDraftStore.getState();- store.setContent("task-1", "issue-1", content);- store.markEnded("task-1");- expect(useTaskSupplementDraftStore.getState().drafts["task-1"]).toBeUndefined();- });-- it("clears a previously ended draft after its text is erased", () => {- const store = useTaskSupplementDraftStore.getState();- store.setContent("task-1", "issue-1", "retained");- store.markEnded("task-1");- store.setContent("task-1", "issue-1", "");- store.markEnded("task-1");- expect(useTaskSupplementDraftStore.getState().drafts["task-1"]).toBeUndefined();- });-- it("does not let another task consume or clear the draft", () => {- const store = useTaskSupplementDraftStore.getState();- store.setContent("task-1", "issue-1", "first");- store.setContent("task-2", "issue-1", "second");- store.clear("task-2");- expect(useTaskSupplementDraftStore.getState().drafts["task-1"]?.content).toBe("first");- });-- it("changes request identity only when the user changes text", () => {- const store = useTaskSupplementDraftStore.getState();- store.setContent("task-1", "issue-1", "same text");- store.setRequestId("task-1", "request-1");- store.markEnded("task-1");- expect(useTaskSupplementDraftStore.getState().drafts["task-1"]).toMatchObject({- content: "same text", clientRequestId: "request-1", ended: true,- });- store.setContent("task-1", "issue-1", "edited text");- expect(useTaskSupplementDraftStore.getState().drafts["task-1"]?.clientRequestId).toBeUndefined();- });-});diff --git a/packages/core/issues/stores/task-supplement-draft-store.ts b/packages/core/issues/stores/task-supplement-draft-store.tsdeleted file mode 100644index 85f893fd24..0000000000--- a/packages/core/issues/stores/task-supplement-draft-store.ts+++ /dev/null@@ -1,106 +0,0 @@-import { create } from "zustand";-import { createJSONStorage, persist } from "zustand/middleware";-import { registerDraftCleanup } from "../../drafts/cleanup-registry";-import { defaultStorage } from "../../platform/storage";-import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";--export interface TaskSupplementDraft {- issueId: string;- content: string;- open: boolean;- ended: boolean;- clientRequestId?: string;- updatedAt: number;-}--interface TaskSupplementDraftStore {- drafts: Record<string, TaskSupplementDraft>;- open: (taskId: string, issueId: string) => void;- setContent: (taskId: string, issueId: string, content: string) => void;- setRequestId: (taskId: string, clientRequestId: string) => void;- markEnded: (taskId: string) => void;- clear: (taskId: string) => void;-}--const TTL_MS = 30 * 24 * 60 * 60 * 1000;--function prune(drafts: Record<string, TaskSupplementDraft>): Record<string, TaskSupplementDraft> {- const cutoff = Date.now() - TTL_MS;- return Object.fromEntries(Object.entries(drafts).filter(([, draft]) =>- draft.updatedAt >= cutoff && (!!draft.content.trim() || draft.open),- ));-}--export const useTaskSupplementDraftStore = create<TaskSupplementDraftStore>()(- persist(- (set) => ({- drafts: {},- open: (taskId, issueId) => set((state) => ({- drafts: {- ...state.drafts,- [taskId]: {- issueId,- content: state.drafts[taskId]?.content ?? "",- clientRequestId: state.drafts[taskId]?.clientRequestId,- ended: state.drafts[taskId]?.ended ?? false,- open: true,- updatedAt: Date.now(),- },- },- })),- setContent: (taskId, issueId, content) => set((state) => ({- drafts: {- ...state.drafts,- [taskId]: {- issueId,- content,- open: true,- ended: state.drafts[taskId]?.ended ?? false,- // Editing creates a new logical request; retries of unchanged text- // keep the prior id through setRequestId instead.- clientRequestId: undefined,- updatedAt: Date.now(),- },- },- })),- setRequestId: (taskId, clientRequestId) => set((state) => {- const draft = state.drafts[taskId];- if (!draft) return state;- return { drafts: { ...state.drafts, [taskId]: { ...draft, clientRequestId, updatedAt: Date.now() } } };- }),- markEnded: (taskId) => set((state) => {- const draft = state.drafts[taskId];- if (!draft) return state;- if (!draft.content.trim()) {- const drafts = { ...state.drafts };- delete drafts[taskId];- return { drafts };- }- if (draft.ended) return state;- return { drafts: { ...state.drafts, [taskId]: { ...draft, open: true, ended: true, updatedAt: Date.now() } } };- }),- clear: (taskId) => set((state) => {- if (!(taskId in state.drafts)) return state;- const drafts = { ...state.drafts };- delete drafts[taskId];- return { drafts };- }),- }),- {- name: "multica_task_supplement_drafts",- storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),- merge: (persisted, current) => ({- ...current,- drafts: prune((persisted as { drafts?: Record<string, TaskSupplementDraft> } | undefined)?.drafts ?? {}),- }),- },- ),-);--registerForWorkspaceRehydration(() => useTaskSupplementDraftStore.persist.rehydrate());--registerDraftCleanup({- storageKey: "multica_task_supplement_drafts",- workspaceScoped: true,- resetInMemory: () => useTaskSupplementDraftStore.setState({ drafts: {} }),-});diff --git a/packages/core/package.json b/packages/core/package.jsonindex 09c5537723..856ba91028 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -42,6 +42,7 @@"./issues/timeline-sort": "./issues/timeline-sort.ts","./issues/comment-deletion": "./issues/comment-deletion.ts","./issues/comment-trigger-outcomes": "./issues/comment-trigger-outcomes.ts",+ "./issues/run-steering": "./issues/run-steering.ts","./issues/date": "./issues/date.ts","./issues/ws-updaters": "./issues/ws-updaters.ts","./issues/surface/*": "./issues/surface/*.ts",diff --git a/packages/core/types/activity.ts b/packages/core/types/activity.tsindex b17bc0f857..2e66480eac 100644--- a/packages/core/types/activity.ts+++ b/packages/core/types/activity.ts@@ -1,4 +1,4 @@-import type { CommentAuthorType, Reaction } from "./comment";+import type { CommentAuthorType, CommentSupplementReceipt, Reaction } from "./comment";import type { Attachment } from "./attachment";export interface AssigneeFrequencyEntry {@@ -33,7 +33,9 @@ export interface TimelineEntry {resolved_by_type?: CommentAuthorType | null;resolved_by_id?: string | null;source_task_id?: string | null;- /** Delivery receipt for a member message explicitly bound to one live run. */+ /** Every running turn this comment steered, one receipt per run. */+ supplements?: CommentSupplementReceipt[];+ /** Mirrors the first receipt; servers that predate `supplements` send only these. */supplement_task_id?: string;supplement_status?: "pending" | "delivering" | "delivered" | "failed";supplement_failure_reason?: string;diff --git a/packages/core/types/comment.ts b/packages/core/types/comment.tsindex aaca94eeb8..00ad8e39d2 100644--- a/packages/core/types/comment.ts+++ b/packages/core/types/comment.ts@@ -47,19 +47,35 @@ export interface Comment {// Per-target result of every explicit @agent / @squad mention in this comment// (MUL-4525 §2). Present only on create/edit responses; older servers omit it.trigger_outcomes?: CommentTriggerOutcome[];+ /** Every running turn this comment steered, one receipt per run. */+ supplements?: CommentSupplementReceipt[];+ /** Mirrors the first receipt; servers that predate `supplements` send only these. */supplement_task_id?: string;supplement_status?: "pending" | "delivering" | "delivered" | "failed";supplement_failure_reason?: string;supplement_delivered_at?: string;}+export type CommentSupplementStatus = "pending" | "delivering" | "delivered" | "failed";++/** Delivery receipt of a comment that steered one agent's running turn. */+export interface CommentSupplementReceipt {+ task_id: string;+ agent_id?: string;+ status: CommentSupplementStatus;+ failure_reason?: string;+ delivered_at?: string;+}+// The domain result of one explicitly-mentioned trigger target. Success-shaped-// statuses (queued/coalesced/deferred) mean the mention was handled; `blocked`+// statuses (queued/coalesced/deferred/steered) mean the mention was handled;+// `steered` means the comment went into the target's running turn. `blocked`// means it was refused with an enumeration-safe reason_code.export type CommentTriggerStatus =| "queued"| "coalesced"| "deferred"+ | "steered"| "blocked";export interface CommentTriggerOutcome {diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex c80945219a..2dd4557c25 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -118,7 +118,7 @@ export type {} from "./plugin";export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread, ArchivedInboxPage, ArchivedInboxFacets } from "./inbox";export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";-export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";+export type { Comment, CommentType, CommentAuthorType, CommentSupplementReceipt, CommentSupplementStatus, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";export type { IssueProperty, IssuePropertyType, ScalarIssuePropertyType, IssuePropertyOption, IssuePropertyConfig, IssuePropertyValue, IssuePropertyValues, CreatePropertyRequest, UpdatePropertyRequest, ListPropertiesResponse, IssuePropertiesResponse, IssuePropertyActorKind, IssuePropertyActorRef, PropertyFilterOp, PropertyOperatorFilter, PropertyFilterValue } from "./property";export { ISSUE_PROPERTY_TYPES, isKnownPropertyType, ISSUE_PROPERTY_ACTOR_KINDS, MAX_ISSUE_PROPERTY_ACTOR_VALUES, isActorPropertyType, isFilterablePropertyType, isScalarPropertyType, formatActorRef, parseActorRef, actorRefsFromValue, actorRefValuesFromValue, hasUnknownActorRef, isPropertyOperatorFilter, isKnownPropertyFilterOp, propertyFilterValueKey, PROPERTY_FILTER_OP_SYMBOLS, PROPERTY_FILTER_OPS_BY_TYPE } from "./property";diff --git a/packages/views/issues/components/comment-card-edit-gate.test.tsx b/packages/views/issues/components/comment-card-edit-gate.test.tsxindex 6a8c7143a0..57a9242fa1 100644--- a/packages/views/issues/components/comment-card-edit-gate.test.tsx+++ b/packages/views/issues/components/comment-card-edit-gate.test.tsx@@ -406,7 +406,7 @@ describe("comment thread — selection reply", () => {expect(screen.queryByRole("button", { name: "Preview reply" })).not.toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Send" }));await waitFor(() => expect(onReply).toHaveBeenCalledTimes(1));- expect(onReply).toHaveBeenCalledWith("agent-child", "> Selected agent text\n\nReply-specific note", undefined, undefined);+ expect(onReply).toHaveBeenCalledWith("agent-child", "> Selected agent text\n\nReply-specific note", undefined, undefined, undefined);await waitFor(() => {expect(useCommentDraftStore.getState().getAnnotations("reply:issue-1:comment-1")).toHaveLength(0);expect(document.querySelector("[data-reply-annotation-overlay]")).not.toBeInTheDocument();diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex a846ed3ac1..a344365eca 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -1,7 +1,6 @@"use client";import { Fragment, memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";-import { useQuery } from "@tanstack/react-query";import { CheckCircle2, ChevronRight, CornerUpLeft, ListChevronsDownUp, Copy, Link2, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "lucide-react";import { toast } from "sonner";import { Card } from "@multica/ui/components/ui/card";@@ -38,11 +37,12 @@ import { api, dispatchReasonCode, errorCode } 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 { useRecipientActions } from "../hooks/use-recipient-actions";+import { SteerBadge, SteerReceipts } from "./steer-receipts";+import type { AgentTask, TimelineEntry, Attachment } from "@multica/core/types";import { contentReferencesAttachment } from "@multica/core/types";import { isDeletedComment } from "@multica/core/issues/comment-deletion";-import { useRetryTaskSupplement } from "@multica/core/issues/mutations";-import { issueTasksOptions } from "@multica/core/issues/queries";+import { commentSupplementReceipts, isSupplementInFlight } from "@multica/core/issues/run-steering";import { useConfigStore } from "@multica/core/config";import { selectStandaloneAttachments } from "@multica/core/attachments/image-sequence";import { useCommentCollapseStore, useCommentDraftStore } from "@multica/core/issues/stores";@@ -124,7 +124,7 @@ interface CommentCardProps {* `CommentRow` has to rerun the rule per row.*/canModerate?: boolean;- onReply: (parentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<string | boolean>;+ onReply: (parentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[], steerTaskIds?: string[]) => Promise<string | boolean>;onReplyAccepted?: (commentId: string) => void;onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[], contentBase?: string) => Promise<void>;onDelete: (commentId: string) => void;@@ -329,6 +329,8 @@ function TaskCommentRetryButton({// Shared edit-attachment state hook// ---------------------------------------------------------------------------+const NEVER_STEER = () => false;+function useEditAttachmentState(issueId: string,entry: TimelineEntry,@@ -346,7 +348,6 @@ function useEditAttachmentState(const uploadGate = useUploadGate(editorRef);const cancelledRef = useRef(false);const [content, setContent] = useState(entry.content ?? "");- const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());// Uploads for this edit session (MUL-5181) — coordinator-owned, persisted in// the draft store keyed by the edit draft so scroll-out/close no longer drops// an in-flight upload.@@ -362,14 +363,19 @@ function useEditAttachmentState(editingCommentId: entry.id,content: editing ? content : "",});+ // An edit neither steers nor stops a run: it can only skip a recipient.+ const { recipients, routing, setAction: setRecipientAction, reset: resetRecipients } = useRecipientActions({+ issueId,+ agents: triggerPreview.agents,+ allowSteer: false,+ steerByDefault: NEVER_STEER,+ resetKey: `${issueId}:${entry.id}:${entry.parent_id ?? ""}`,+ });const editorAttachments = pendingAttachments.length > 0? [...(entry.attachments ?? []), ...pendingAttachments]: entry.attachments;- useEffect(() => {- setSuppressedAgentIds(new Set());- }, [issueId, entry.id, entry.parent_id]);useEffect(() => {if (revisionConflict) setInitialContentBase(entry.content ?? "");}, [entry.content, revisionConflict]);@@ -383,23 +389,6 @@ function useEditAttachmentState(const setDraft = useCommentDraftStore((s) => s.setDraft);const clearDraft = useCommentDraftStore((s) => s.clearDraft);- 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),);@@ -408,7 +397,7 @@ function useEditAttachmentState(setEditing(false);setRevisionConflict(false);setContent(entry.content ?? "");- setSuppressedAgentIds(new Set());+ resetRecipients();setRetainedStandaloneIds(null);// clearDraft drops both the edit text and its pending attachments.clearDraft(draftKey);@@ -483,9 +472,7 @@ function useEditAttachmentState(if (trimmed === (entry.content ?? "").trim() && !attachmentsChanged) {return true;}- const suppressAgentIds = triggerPreview.agents- .filter((agent) => suppressedAgentIds.has(agent.id))- .map((agent) => agent.id);+ const { suppressAgentIds } = routing;try {await onEdit(entry.id,@@ -542,8 +529,8 @@ function useEditAttachmentState(dropZoneProps,triggerPreview,content,- suppressedAgentIds,- toggleSuppressedAgent,+ recipients,+ setRecipientAction,draftKey,setDraft,setContent,@@ -611,55 +598,6 @@ function CommentRevisionConflict({// Single comment row (used for both parent and replies within the same Card)// ----------------------------------------------------------------------------export function SupplementReceipt({ issueId, entry }: {- issueId: string;- entry: TimelineEntry;-}) {- if (!entry.supplement_task_id || !entry.supplement_status || entry.supplement_status === "delivered") return null;- return <ActiveSupplementReceipt issueId={issueId} entry={entry} />;-}--function ActiveSupplementReceipt({ issueId, entry }: { issueId: string; entry: TimelineEntry }) {- const { t } = useT("issues");- const retry = useRetryTaskSupplement(issueId);- // Run placement belongs to one card, but every bound supplement must observe- // the task's terminal state, including earlier top-level comments.- const { data: taskStatus } = useQuery({- ...issueTasksOptions(issueId),- enabled: !!issueId && !!entry.supplement_task_id && !!entry.supplement_status,- select: (tasks) => tasks.find((task) => task.id === entry.supplement_task_id)?.status,- });- if (!entry.supplement_task_id || !entry.supplement_status || entry.supplement_status === "delivered") return null;- const terminal = taskStatus === "completed" || taskStatus === "failed" || taskStatus === "cancelled";- const endedBeforeDelivery = terminal- && (entry.supplement_status === "pending" || entry.supplement_status === "delivering");- if (!endedBeforeDelivery && (entry.supplement_status === "pending" || entry.supplement_status === "delivering")) {- return <p role="status" className="mt-1.5 text-caption text-muted-foreground">- {t(($) => $.inline_run.supplement_waiting_delivery)}- </p>;- }- const reasonCode = endedBeforeDelivery ? "turn_ended" : entry.supplement_failure_reason;- const reason = reasonCode === "turn_ended"- ? t(($) => $.inline_run.supplement_failure_turn_ended)- : reasonCode === "turn_not_started"- ? t(($) => $.inline_run.supplement_failure_turn_not_started)- : reasonCode === "provider_rejected"- ? t(($) => $.inline_run.supplement_failure_provider_rejected)- : reasonCode === "timeout"- ? t(($) => $.inline_run.supplement_failure_timeout)- : t(($) => $.inline_run.supplement_failure_unknown);- return <div role="alert" className="mt-1.5 flex items-center gap-2 text-caption text-destructive">- <span>{t(($) => $.inline_run.supplement_not_delivered, { reason })}</span>- {!terminal && reasonCode !== "turn_ended" && <Button type="button" size="xs" variant="outline" disabled={retry.isPending}- onClick={() => retry.mutate({ taskId: entry.supplement_task_id!, commentId: entry.id }, {- onError: () => toast.error(t(($) => $.inline_run.supplement_retry_failed)),- })}>- {retry.isPending && <Loader2 className="size-3 animate-spin motion-reduce:animate-none" />}- {t(($) => $.inline_run.supplement_retry)}- </Button>}- </div>;-}-function CommentRow({runHeader,runMetadata,@@ -706,9 +644,11 @@ function CommentRow({const edit = useEditAttachmentState(issueId, entry, onEdit);const isOwn = entry.actor_type === "member" && entry.actor_id === currentUserId;- const canEditEntry = !entry.supplement_task_id && (isOwn || (canModerate && entry.actor_type === "member"));- const supplementInFlight = entry.supplement_task_id && (entry.supplement_status === "pending" || entry.supplement_status === "delivering");- const canDeleteEntry = !supplementInFlight && (isOwn || canModerate);+ // A message that steered a run is part of that run's input: it cannot be+ // rewritten, and it cannot be removed while a turn is still receiving it.+ const receipts = commentSupplementReceipts(entry);+ const canEditEntry = receipts.length === 0 && (isOwn || (canModerate && entry.actor_type === "member"));+ const canDeleteEntry = !receipts.some(isSupplementInFlight) && (isOwn || canModerate);const [confirmDelete, setConfirmDelete] = useState(false);const reactions = entry.reactions ?? [];@@ -757,6 +697,7 @@ function CommentRow({</TooltipContent></Tooltip>+ <SteerBadge issueId={issueId} entry={entry} />{runHeader}{isResolution && (@@ -897,12 +838,11 @@ function CommentRow({<div className="flex items-center justify-between gap-2 mt-2"><div className="min-w-0 flex-1"><CommentTriggerChips- agents={edit.triggerPreview.agents}+ recipients={edit.recipients}blocked={edit.triggerPreview.blocked}hasAllMembersMention={edit.triggerPreview.hasAllMembersMention}draftContent={edit.content}- suppressedAgentIds={edit.suppressedAgentIds}- onToggle={edit.toggleSuppressedAgent}+ onActionChange={edit.setRecipientAction}/></div><div className="flex shrink-0 items-center gap-2">@@ -936,7 +876,7 @@ function CommentRow({</div><AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-12 pr-4 max-md:pl-3 max-md:pr-3" /><div className="pl-12 pr-4 max-md:pl-3 max-md:pr-3">- <SupplementReceipt issueId={issueId} entry={entry} />+ <SteerReceipts issueId={issueId} entry={entry} /></div>{retryableAgentFailureComment(entry) && (<TaskCommentRetryButton@@ -1085,10 +1025,16 @@ function CommentCardImpl({const edit = useEditAttachmentState(issueId, entry, onEdit);const isOwn = entry.actor_type === "member" && entry.actor_id === currentUserId;- const canEditEntry = !entry.supplement_task_id && (isOwn || (canModerate && entry.actor_type === "member"));- const supplementInFlight = entry.supplement_status === "pending" || entry.supplement_status === "delivering";- const canDeleteEntry = !supplementInFlight && (isOwn || canModerate);+ const receipts = commentSupplementReceipts(entry);+ const canEditEntry = receipts.length === 0 && (isOwn || (canModerate && entry.actor_type === "member"));+ const canDeleteEntry = !receipts.some(isSupplementInFlight) && (isOwn || canModerate);const [confirmDelete, setConfirmDelete] = useState(false);+ // A reply here goes into the running turn of a run that belongs to this+ // thread by default; another thread's turn is only reached by choice.+ const steerThreadRunByDefault = useCallback(+ (task: AgentTask) => runs.some((run) => run.task.id === task.id),+ [runs],+ );const allNestedReplies = replies;// What the thread shows. Tombstones are excluded from display and counts but@@ -1256,6 +1202,7 @@ function CommentCardImpl({</TooltipContent></Tooltip>+ <SteerBadge issueId={issueId} entry={entry} />{renderRuns(entry.id, "header")}</>)}@@ -1425,12 +1372,11 @@ function CommentCardImpl({/>)}<CommentTriggerChips- agents={edit.triggerPreview.agents}+ recipients={edit.recipients}blocked={edit.triggerPreview.blocked}hasAllMembersMention={edit.triggerPreview.hasAllMembersMention}draftContent={edit.content}- suppressedAgentIds={edit.suppressedAgentIds}- onToggle={edit.toggleSuppressedAgent}+ onActionChange={edit.setRecipientAction}/><FileUploadButtonsize="sm"@@ -1464,7 +1410,7 @@ function CommentCardImpl({</div><AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-8 max-md:pl-0" /><div className="pl-8 max-md:pl-0">- <SupplementReceipt issueId={issueId} entry={entry} />+ <SteerReceipts issueId={issueId} entry={entry} /></div>{retryableAgentFailureComment(entry) && (<TaskCommentRetryButton@@ -1536,7 +1482,8 @@ function CommentCardImpl({avatarId={currentUserId ?? ""}draftKey={`reply:${issueId}:${entry.id}`}onEditAnnotation={(id) => annotation.editAnnotation(id, true)}- onSubmit={(content, attachmentIds, suppressAgentIds) => replyTargetMissing ? Promise.resolve(false) : onReply(replyTargetId, content, attachmentIds, suppressAgentIds)}+ steerByDefault={steerThreadRunByDefault}+ onSubmit={(content, attachmentIds, suppressAgentIds, steerTaskIds) => replyTargetMissing ? Promise.resolve(false) : onReply(replyTargetId, content, attachmentIds, suppressAgentIds, steerTaskIds)}onAccepted={onReplyAccepted}/></div>diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsxindex d74bb2d90e..5bc2edb251 100644--- a/packages/views/issues/components/comment-composers.test.tsx+++ b/packages/views/issues/components/comment-composers.test.tsx@@ -24,6 +24,9 @@ const apiUploadFile = vi.hoisted(() => vi.fn());const apiListWorkspaces = vi.hoisted(() => vi.fn());const apiListQuickActions = vi.hoisted(() => vi.fn());const apiRenderQuickAction = vi.hoisted(() => vi.fn());+const apiPreviewCommentTriggers = vi.hoisted(() => vi.fn());+const apiListTasksByIssue = vi.hoisted(() => vi.fn());+const apiCancelTask = vi.hoisted(() => vi.fn());const uploadWithToast = vi.hoisted(() => vi.fn());const editorDefaultValues = vi.hoisted(() => ({values: [] as Array<string | undefined>,@@ -59,6 +62,9 @@ vi.mock("@multica/core/api", () => ({listWorkspaces: apiListWorkspaces,listQuickActions: apiListQuickActions,renderQuickAction: apiRenderQuickAction,+ previewCommentTriggers: apiPreviewCommentTriggers,+ listTasksByIssue: apiListTasksByIssue,+ cancelTask: apiCancelTask,},}));@@ -75,6 +81,12 @@ vi.mock("../../common/actor-avatar", () => ({{actorType}:{actorId}</span>),+ AgentStatusDot: () => null,+}));++vi.mock("@multica/core/agents", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/agents")>()),+ useAgentPresenceDetail: () => "loading",}));vi.mock("../../editor", async () => ({@@ -276,11 +288,14 @@ beforeEach(() => {apiListWorkspaces.mockReset();apiListQuickActions.mockReset();apiRenderQuickAction.mockReset();+ apiPreviewCommentTriggers.mockReset();+ apiListTasksByIssue.mockReset();+ apiCancelTask.mockReset();insertMarkdownSpy.mockReset();insertPlaceholderSpy.mockReset();insertMarkdownBehavior.succeed = true;localStorage.clear();- useCommentComposerStore.setState({ sticky: true });+ useCommentComposerStore.setState({ sticky: true, runningAgentReply: "steer" });// The composer's pinning (and the height cap that follows it) is viewport// dependent, so a narrow-viewport test must not leak into the next one.Object.defineProperty(window, "innerWidth", { configurable: true, value: 1280 });@@ -412,10 +427,132 @@ describe("comment composers", () => {fireEvent.click(getSubmitButton(container));await waitFor(() => {- expect(onSubmit).toHaveBeenCalledWith("hello from composer", undefined, undefined);+ expect(onSubmit).toHaveBeenCalledWith("hello from composer", undefined, undefined, undefined);});});+ it("steers the thread's running turn by default, and stops it first to start over", async () => {+ const turn = {+ id: "turn-1", agent_id: "agent-1", issue_id: "issue-1", status: "running", priority: 0,+ created_at: "2026-09-23T00:00:00Z", dispatched_at: null, started_at: "2026-09-23T00:00:01Z",+ completed_at: null, result: null, error: null,+ supplement_capability: "task-supplement-v1", can_supplement: true,+ };+ apiListTasksByIssue.mockResolvedValue([turn]);+ apiPreviewCommentTriggers.mockResolvedValue({+ agents: [{ id: "agent-1", name: "Lambda", source: "thread_parent", reason: "" }],+ });+ apiCancelTask.mockResolvedValue({ ...turn, status: "cancelled" });+ const onSubmit = vi.fn().mockResolvedValue("reply-new");+ const { container } = renderWithProviders(+ <ReplyInput issueId="issue-1" parentId="comment-1" avatarType="member" avatarId="user-1"+ onSubmit={onSubmit} steerByDefault={(task) => task.id === "turn-1"} />,+ );++ activateComposer("reply-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "only fix web" } });+ await screen.findByText("Add to current run", {}, { timeout: 5000 });+ fireEvent.click(getSubmitButton(container));+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("only fix web", undefined, undefined,+ ["turn-1"]));+ expect(apiCancelTask).not.toHaveBeenCalled();++ fireEvent.change(screen.getByTestId("editor"), { target: { value: "start over on web" } });+ fireEvent.click(await screen.findByRole("button", { name: "Lambda trigger: Add to current run" }, { timeout: 5000 }));+ fireEvent.click(await screen.findByRole("menuitemradio", { name: /Stop and start over/ }));+ fireEvent.click(await screen.findByRole("button", { name: "Stop and send" }));+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("start over on web", undefined, undefined, undefined));+ expect(apiCancelTask).toHaveBeenCalledWith("issue-1", "turn-1");+ expect(apiCancelTask.mock.invocationCallOrder[0]!).toBeLessThan(onSubmit.mock.invocationCallOrder[1]!);+ });++ it("starts after the run by default when the personal preference says so", async () => {+ useCommentComposerStore.setState({ runningAgentReply: "after_run" });+ const turn = {+ id: "turn-1", agent_id: "agent-1", issue_id: "issue-1", status: "running", priority: 0,+ created_at: "2026-09-23T00:00:00Z", dispatched_at: null, started_at: "2026-09-23T00:00:01Z",+ completed_at: null, result: null, error: null,+ supplement_capability: "task-supplement-v1", can_supplement: true,+ };+ apiListTasksByIssue.mockResolvedValue([turn]);+ apiPreviewCommentTriggers.mockResolvedValue({ agents: [{ id: "agent-1", name: "Lambda", source: "thread_parent", reason: "" }] });+ const onSubmit = vi.fn().mockResolvedValue("reply-new");+ const { container } = renderWithProviders(+ <ReplyInput issueId="issue-1" parentId="comment-1" avatarType="member" avatarId="user-1"+ onSubmit={onSubmit} steerByDefault={(task) => task.id === "turn-1"} />,+ );++ activateComposer("reply-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "only fix web" } });+ await screen.findByRole("button", { name: "Lambda trigger: Start after this run" }, { timeout: 5000 });+ fireEvent.click(getSubmitButton(container));+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("only fix web", undefined, undefined, undefined));++ // One message can still go into the running turn.+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "and keep desktop as is" } });+ fireEvent.click(await screen.findByRole("button", { name: "Lambda trigger: Start after this run" }, { timeout: 5000 }));+ fireEvent.click(await screen.findByRole("menuitemradio", { name: /Add to current run/ }));+ await screen.findByRole("button", { name: "Lambda trigger: Add to current run" });+ fireEvent.click(getSubmitButton(container));+ await waitFor(() => expect(onSubmit).toHaveBeenLastCalledWith("and keep desktop as is", undefined, undefined,+ ["turn-1"]));+ });++ it("steers every running recipient the message addresses", async () => {+ const turn = (id: string, agentId: string) => ({+ id, agent_id: agentId, issue_id: "issue-1", status: "running", priority: 0,+ created_at: "2026-09-23T00:00:00Z", dispatched_at: null, started_at: "2026-09-23T00:00:01Z",+ completed_at: null, result: null, error: null,+ supplement_capability: "task-supplement-v1", can_supplement: true,+ });+ apiListTasksByIssue.mockResolvedValue([turn("turn-1", "agent-1"), turn("turn-2", "agent-2")]);+ apiPreviewCommentTriggers.mockResolvedValue({ agents: [+ { id: "agent-1", name: "Lambda", source: "mention_agent", reason: "" },+ { id: "agent-2", name: "Orion", source: "mention_agent", reason: "" },+ ] });+ const onSubmit = vi.fn().mockResolvedValue("reply-new");+ const { container } = renderWithProviders(+ <ReplyInput issueId="issue-1" parentId="comment-1" avatarType="member" avatarId="user-1"+ onSubmit={onSubmit} steerByDefault={() => true} />,+ );+ activateComposer("reply-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "only fix web" } });+ fireEvent.click(await screen.findByText("2 agents will receive this", {}, { timeout: 5000 }));+ expect(await screen.findByRole("button", { name: "Lambda trigger: Add to current run" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Orion trigger: Add to current run" })).toBeInTheDocument();+ fireEvent.click(getSubmitButton(container));+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith("only fix web", undefined, undefined,+ ["turn-1", "turn-2"]));+ });++ it("never stops the previous recipient after the mentions change under a stale preview", async () => {+ const turn = {+ id: "turn-1", agent_id: "agent-1", issue_id: "issue-1", status: "running", priority: 0,+ created_at: "2026-09-23T00:00:00Z", dispatched_at: null, started_at: "2026-09-23T00:00:01Z",+ completed_at: null, result: null, error: null,+ supplement_capability: "task-supplement-v1", can_supplement: true,+ };+ apiListTasksByIssue.mockResolvedValue([turn]);+ apiPreviewCommentTriggers.mockResolvedValue({ agents: [{ id: "agent-1", name: "Lambda", source: "thread_parent", reason: "" }] });+ apiCancelTask.mockResolvedValue({ ...turn, status: "cancelled" });+ const onSubmit = vi.fn().mockResolvedValue("reply-new");+ renderWithProviders(<ReplyInput issueId="issue-1" parentId="comment-1" avatarType="member" avatarId="user-1"+ onSubmit={onSubmit} steerByDefault={(task) => task.id === "turn-1"} />);+ activateComposer("reply-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "start over" } });+ fireEvent.click(await screen.findByRole("button", { name: "Lambda trigger: Add to current run" }, { timeout: 5000 }));+ fireEvent.click(await screen.findByRole("menuitemradio", { name: /Stop and start over/ }));+ // A slow preview still holds Lambda's restart, though the comment now+ // explicitly addresses only a different agent.+ apiPreviewCommentTriggers.mockImplementation(() => new Promise(() => {}));+ fireEvent.change(screen.getByTestId("editor"), {+ target: { value: "[@Orion](mention://agent/11111111-1111-4111-8111-111111111111) review desktop" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Stop and send" }));+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());+ expect(apiCancelTask).not.toHaveBeenCalled();+ });+it("keeps reply submission wired after removing expand", async () => {const { container, onSubmit } = renderReplyInput();@@ -426,7 +563,7 @@ describe("comment composers", () => {fireEvent.click(getSubmitButton(container));await waitFor(() => {- expect(onSubmit).toHaveBeenCalledWith("thread reply", undefined, undefined);+ expect(onSubmit).toHaveBeenCalledWith("thread reply", undefined, undefined, undefined);});});@@ -476,7 +613,7 @@ describe("comment composers", () => {"true",),);- expect(onSubmit).toHaveBeenCalledWith("sending", undefined, undefined);+ expect(onSubmit).toHaveBeenCalledWith("sending", undefined, undefined, undefined);resolveSubmit(true);@@ -965,6 +1102,7 @@ describe("comment composers — upload submit gate", () => {expect.stringContaining("https://cdn.example/att-9.png"),["att-9"],undefined,+ undefined,),);});@@ -986,7 +1124,7 @@ describe("comment composers — upload submit gate", () => {fireEvent.keyDown(editor, { key: "Enter", metaKey: true });await waitFor(() => expect(onSubmit).toHaveBeenCalled());- expect(onSubmit).toHaveBeenCalledWith("keep this, dropped the image", undefined, undefined);+ expect(onSubmit).toHaveBeenCalledWith("keep this, dropped the image", undefined, undefined, undefined);});it("writes the finished upload's link into the persisted draft after the composer unmounts", async () => {diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsxindex ed8a1a6e13..b0561feb5b 100644--- a/packages/views/issues/components/comment-input.tsx+++ b/packages/views/issues/components/comment-input.tsx@@ -1,11 +1,12 @@"use client";-import { useRef, useState, useCallback, useEffect, useMemo } from "react";+import { useRef, useState, useEffect, useMemo } from "react";import { cn } from "@multica/ui/lib/utils";import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { SubmitButton } from "@multica/ui/components/common/submit-button";-import { contentReferencesAttachment } from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import { contentReferencesAttachment, type AgentTask } from "@multica/core/types";import { formatShortcut, useShortcut } from "@multica/core/shortcuts";import { useCommentDraftStore } from "@multica/core/issues/stores";import { composeAnnotatedReply, hasReplyIntent } from "@multica/core/drafts/reply-annotation";@@ -13,6 +14,9 @@ import { ReplyAnnotations } from "./reply-annotations";import { useT } from "../../i18n";import { CommentTriggerChips } from "./comment-trigger-chips";import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";+import { useRecipientActions } from "../hooks/use-recipient-actions";+import { SteerAttachmentNotice } from "./steer-attachment-notice";+import { useStopRunsBeforeSend } from "./use-stop-runs-before-send";import { useCommentUploads } from "./use-comment-uploads";import { useQuickActionMenu } from "../hooks/use-quick-action-menu";import { useStickyComposer } from "../hooks/use-sticky-composer";@@ -22,12 +26,18 @@ interface CommentInputProps {/** Resolves true on success, false on failure. The composer keeps the text* (editor locked + button spinning) until this settles, then clears only on* success — a failed send must not silently discard the user's draft. */- onSubmit: (content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<string | boolean>;+ onSubmit: (content: string, attachmentIds?: string[], suppressAgentIds?: string[], steerTaskIds?: string[]) => Promise<string | boolean>;/** Called after the server accepts the comment and the composer is cleared. */onAccepted?: (commentId: string) => void;onEditAnnotation?: (id: string) => boolean;}+// A top-level comment belongs to no thread, so it takes a running turn by+// default only when that turn has no thread of its own (an assignment run).+function steerTopLevelByDefault(task: AgentTask): boolean {+ return !task.trigger_comment_id;+}+function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: CommentInputProps) {const { t } = useT("issues");const { t: tEditor } = useT("editor");@@ -36,8 +46,8 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme// Sending mid-upload would strip the pending image's blob URL out of the// markdown and bind no attachment id — the comment posts without the file.const uploadGate = useUploadGate(editorRef);- // Subscribe to the persisted draft so an explicit recovery action from a- // completed run can move text here even while this composer is mounted.+ // Subscribe to the persisted draft so text written into it from outside+ // this composer shows up even while it is mounted.// Quick actions in the `/` menu: picking one inserts the server-rendered// body so the user can edit before sending, instead of firing immediately.const quickActionMenu = useQuickActionMenu(issueId);@@ -48,7 +58,6 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Commeconst persistedDraft = useCommentDraftStore((store) => store.getDraft(draftKey));const [content, setContent] = useState(initialDraft ?? "");const [isEmpty, setIsEmpty] = useState(() => !initialDraft?.trim());- const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());const annotations = useCommentDraftStore((s) => s.getAnnotations(draftKey));const composedContent = useMemo(() => composeAnnotatedReply(content, annotations), [content, annotations]);const canSend = annotations.length ? hasReplyIntent(content, annotations) : !isEmpty;@@ -63,6 +72,19 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme// composer reopened over a still-in-flight upload cannot send past it.const { attachments: pendingAttachments, handleUpload, gate } =useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);+ const hasAttachments = useMemo(+ () => pendingAttachments.some((a) => contentReferencesAttachment(content, a)) || gate.uploading,+ [pendingAttachments, content, gate.uploading],+ );+ const { recipients, attachmentsBlockSteer, routing, setAction, reset: resetRecipients } = useRecipientActions({+ issueId,+ agents: triggerPreview.agents,+ allowSteer: true,+ hasAttachments,+ steerByDefault: steerTopLevelByDefault,+ resetKey: issueId,+ });+ const stopRunsBeforeSend = useStopRunsBeforeSend(issueId);// Readonly-first: the composer renders as a same-looking static shell until// the user shows intent (click / keyboard / file drop). An unsent draft is@@ -112,27 +134,6 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme};}, [draftKey, setDraft]);- useEffect(() => {- setSuppressedAgentIds(new Set());- }, [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;- });- }, []);-// Await-then-render send (MUL-5181): the shared hook reads the markdown,// guards empty/in-flight, re-checks the upload gate, locks + spins via// `submitting`, and clears only once the server accepts — a failed send keeps@@ -166,8 +167,13 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme// so the composer stops reading as "still writing" once the comment is// posted above it. Thread replies are the opposite — see ReplyInput.afterAccepted: () => (editorScrubbedRef.current ? "blur" : "none"),- onSubmit: (content) => {+ onSubmit: async (content) => {editorScrubbedRef.current = false;+ const { suppressAgentIds, steerTaskIds } = routing;+ // A preview still catching up with an edited @mention can name a+ // recipient this comment no longer addresses: never stop a run on it.+ const restartTaskIds = triggerPreview.isCurrent ? routing.restartTaskIds : [];+ if (!(await stopRunsBeforeSend(restartTaskIds))) return false;// Flush the editor's pending debounce before snapshotting — a late flush// of pre-submit typing must not read as an edit made during the request.const pending = editorRef.current?.flushPendingUpdate?.();@@ -180,13 +186,11 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Commeconst 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);return onSubmit(content,activeIds.length > 0 ? activeIds : undefined,suppressAgentIds.length > 0 ? suppressAgentIds : undefined,+ steerTaskIds.length > 0 ? steerTaskIds : undefined,).then((commentId) => {acceptedCommentIdRef.current = typeof commentId === "string" ? commentId : null;return !!commentId;@@ -208,7 +212,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: CommeeditorRef.current?.clearContent();setContent("");setIsEmpty(true);- setSuppressedAgentIds(new Set());+ resetRecipients();editorScrubbedRef.current = true;if (acceptedCommentIdRef.current) onAccepted?.(acceptedCommentIdRef.current);},@@ -219,6 +223,9 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme{...dropZoneProps}className="relative flex flex-col rounded-lg bg-card pb-8 ring-1 ring-border">+ {attachmentsBlockSteer && <div className="px-3 pt-2">+ <SteerAttachmentNotice />+ </div>}{annotations.length > 0 && <div className="px-3 pt-2"><ReplyAnnotations draftKey={draftKey} annotations={annotations} disabled={submitting}onEditAnnotation={onEditAnnotation} />@@ -294,12 +301,11 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme)}<div className="absolute bottom-1 left-2 right-28 min-w-0"><CommentTriggerChips- agents={triggerPreview.agents}+ recipients={recipients}blocked={triggerPreview.blocked}hasAllMembersMention={triggerPreview.hasAllMembersMention}draftContent={composedContent}- suppressedAgentIds={suppressedAgentIds}- onToggle={toggleSuppressedAgent}+ onActionChange={setAction}/></div><div className="absolute bottom-1 right-1.5 flex items-center gap-1">@@ -308,7 +314,17 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: CommemultipleonSelect={(file) => lazy.uploadOrQueue([file])}/>- <SubmitButton+ {routing.restartTaskIds.length > 0 ? (+ <Button+ size="sm"+ variant="destructive"+ className="rounded-full"+ onClick={submit}+ disabled={!canSend || submitting || gate.uploading}+ >+ {t(($) => $.comment.restart_send)}+ </Button>+ ) : <SubmitButtononClick={submit}disabled={!canSend}loading={submitting}@@ -323,7 +339,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: CommeariaLabel={gate.uploading? tEditor(($) => $.upload.in_progress): t(($) => $.comment.send_tooltip)}- />+ />}</div>{isDragOver && <FileDropOverlay />}</div>diff --git a/packages/views/issues/components/comment-runs.ts b/packages/views/issues/components/comment-runs.tsindex 3acd52bd65..6fe63e3d88 100644--- a/packages/views/issues/components/comment-runs.ts+++ b/packages/views/issues/components/comment-runs.ts@@ -1,5 +1,6 @@import type { AgentTask, TimelineEntry } from "@multica/core/types";import { isDeletedComment } from "@multica/core/issues/comment-deletion";+import { commentSupplementReceipts } from "@multica/core/issues/run-steering";export interface CommentRun {task: AgentTask;@@ -59,10 +60,12 @@ export function buildCommentRunView(const comments = new Map(timeline.filter((entry) => entry.type === "comment").map((entry) => [entry.id, entry]));const supplementalByTask = new Map<string, string[]>();for (const entry of comments.values()) {- if (!entry.supplement_task_id) continue;- const ids = supplementalByTask.get(entry.supplement_task_id) ?? [];- ids.push(entry.id);- supplementalByTask.set(entry.supplement_task_id, ids);+ // One message can steer several turns; it is input to each of them.+ for (const receipt of commentSupplementReceipts(entry)) {+ const ids = supplementalByTask.get(receipt.task_id) ?? [];+ ids.push(entry.id);+ supplementalByTask.set(receipt.task_id, ids);+ }}const timelineOrder = new Map(timeline.map((entry, index) => [entry.id, index]));const threadRoot = (id: string): string | undefined => {diff --git a/packages/views/issues/components/comment-trigger-chips.test.tsx b/packages/views/issues/components/comment-trigger-chips.test.tsxindex 6474369de3..d5c584af4d 100644--- a/packages/views/issues/components/comment-trigger-chips.test.tsx+++ b/packages/views/issues/components/comment-trigger-chips.test.tsx@@ -1,6 +1,13 @@import { describe, expect, it, vi } from "vitest";-import { fireEvent, screen } from "@testing-library/react";-import type { CommentTriggerPreviewAgent } from "@multica/core/types";+import { fireEvent, screen, within } from "@testing-library/react";+import type { AgentTask, CommentTriggerPreviewAgent } from "@multica/core/types";+import {+ recipientActions,+ resolveRecipientAction,+ type AgentRunState,+ type RecipientAction,+} from "@multica/core/issues/run-steering";+import type { RecipientEntry } from "../hooks/use-recipient-actions";import { renderWithI18n } from "../../test/i18n";import { CommentTriggerChips } from "./comment-trigger-chips";@@ -30,132 +37,100 @@ const bob: CommentTriggerPreviewAgent = {reason: "",};++function turn(status: AgentTask["status"]): AgentTask {+ return { id: `turn-${status}`, agent_id: "agent-1", issue_id: "issue", status, priority: 0,+ created_at: "2026-09-23T00:00:00Z", dispatched_at: null, started_at: null, completed_at: null,+ result: null, error: null } as AgentTask;+}+const running: AgentRunState = { kind: "running", task: turn("running"), steerable: true };+const idle: AgentRunState = { kind: "idle" };++function entry(agent: CommentTriggerPreviewAgent, state: AgentRunState, chosen?: RecipientAction): RecipientEntry {+ const opts = { canSteer: true, canRestart: true, steerByDefault: true };+ return { agent, state, action: resolveRecipientAction(state, chosen, opts), actions: recipientActions(state, opts) };+}+describe("CommentTriggerChips", () => {- it("renders nothing without agents", () => {- const { container } = renderWithI18n(- <CommentTriggerChips agents={[]} suppressedAgentIds={new Set()} onToggle={vi.fn()} />,- );+ it("renders nothing without recipients", () => {+ const { container } = renderWithI18n(<CommentTriggerChips recipients={[]} onActionChange={vi.fn()} />);expect(container).toBeEmptyDOMElement();});it("describes @all semantics without promising any recipients", () => {- renderWithI18n(- <CommentTriggerChips- agents={[]}- hasAllMembersMention- suppressedAgentIds={new Set()}- onToggle={vi.fn()}- />,- );-- expect(- screen.getByText("Member broadcast · @all does not start agents"),- ).toBeInTheDocument();+ renderWithI18n(<CommentTriggerChips recipients={[]} hasAllMembersMention onActionChange={vi.fn()} />);+ expect(screen.getByText("Member broadcast · @all does not start agents")).toBeInTheDocument();expect(screen.queryByText(/notif/i)).not.toBeInTheDocument();});it("keeps explicit agent triggers visible alongside @all semantics", () => {- renderWithI18n(- <CommentTriggerChips- agents={[bob]}- hasAllMembersMention- suppressedAgentIds={new Set()}- onToggle={vi.fn()}- />,- );-- expect(- screen.getByText("Member broadcast · @all does not start agents"),- ).toBeInTheDocument();- expect(screen.getByRole("button")).toHaveTextContent("Will start when sent");+ renderWithI18n(<CommentTriggerChips recipients={[entry(bob, idle)]} hasAllMembersMention onActionChange={vi.fn()} />);+ expect(screen.getByText("Member broadcast · @all does not start agents")).toBeInTheDocument();+ expect(screen.getByText("Will start when sent")).toBeInTheDocument();});- 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("Will start when sent");- expect(chip).toHaveAttribute("aria-pressed", "false");-- fireEvent.click(chip);- expect(onToggle).toHaveBeenCalledWith("agent-1");+ it("offers an idle recipient only to start or skip — never to add to a run", async () => {+ const onActionChange = vi.fn();+ renderWithI18n(<CommentTriggerChips recipients={[entry(walt, idle)]} onActionChange={onActionChange} />);+ fireEvent.click(screen.getByRole("button", { name: "Walt trigger: Will start when sent" }));+ const menu = await screen.findByRole("menu");+ expect(within(menu).queryByText("Add to current run")).not.toBeInTheDocument();+ expect(within(menu).getAllByRole("menuitemradio").map((item) => item.textContent)).toEqual([+ expect.stringContaining("Will start when sent"),+ expect.stringContaining("Won't start this time"),+ ]);+ fireEvent.click(within(menu).getByRole("menuitemradio", { name: /Won't start this time/ }));+ expect(onActionChange).toHaveBeenCalledWith("agent-1", "skip");});- it("dims a suppressed single agent into the skip state", () => {- renderWithI18n(- <CommentTriggerChips- agents={[walt]}- suppressedAgentIds={new Set(["agent-1"])}- onToggle={vi.fn()}- />,- );-- const chip = screen.getByRole("button");- expect(chip).toHaveTextContent("Won't start this time");- expect(chip).toHaveAttribute("aria-pressed", "true");+ it("defaults a running recipient to its turn and explains each choice", async () => {+ const onActionChange = vi.fn();+ renderWithI18n(<CommentTriggerChips recipients={[entry(walt, running)]} onActionChange={onActionChange} />);+ fireEvent.click(screen.getByRole("button", { name: "Walt trigger: Add to current run" }));+ const menu = await screen.findByRole("menu");+ expect(within(menu).getByText("Running")).toBeInTheDocument();+ expect(within(menu).getByText("Walt reads it after the current step and keeps working on the original task. Text only.")).toBeInTheDocument();+ expect(within(menu).getByText("Stops the current run now and starts over from this message.")).toBeInTheDocument();+ fireEvent.click(within(menu).getByRole("menuitemradio", { name: /Start after this run/ }));+ expect(onActionChange).toHaveBeenCalledWith("agent-1", "after_run");});- 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 when sent");+ it("folds a message into a queued run instead of starting another", () => {+ const queued: AgentRunState = { kind: "queued", task: turn("queued") };+ renderWithI18n(<CommentTriggerChips recipients={[entry(walt, queued)]} onActionChange={vi.fn()} />);+ expect(screen.getByText("Include when it starts")).toBeInTheDocument();});- 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 when sent");+ it("dims a skipped recipient", () => {+ renderWithI18n(<CommentTriggerChips recipients={[entry(walt, idle, "skip")]} onActionChange={vi.fn()} />);+ expect(screen.getByText("Won't start this time")).toBeInTheDocument();});- it("switches to the none-will-trigger state when every agent is suppressed", () => {- renderWithI18n(- <CommentTriggerChips- agents={[walt, bob]}- suppressedAgentIds={new Set(["agent-1", "agent-2"])}- onToggle={vi.fn()}- />,- );-- expect(screen.getByRole("button")).toHaveTextContent("No agents will start");+ it("stacks several recipients, counting only those that will receive the message", () => {+ renderWithI18n(<CommentTriggerChips recipients={[entry(walt, running), entry(bob, idle, "skip")]} onActionChange={vi.fn()} />);+ expect(screen.getByText("1 agent will receive this")).toBeInTheDocument();});- 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"));+ it("switches to the none-will-trigger state when every recipient is skipped", () => {+ renderWithI18n(<CommentTriggerChips recipients={[entry(walt, idle, "skip"), entry(bob, idle, "skip")]} onActionChange={vi.fn()} />);+ expect(screen.getByText("No agents will start")).toBeInTheDocument();+ });- const row = screen.getByRole("button", { name: /Bob/ });- expect(row).toHaveTextContent("Bob");- fireEvent.click(row);- expect(onToggle).toHaveBeenCalledWith("agent-2");+ it("gives each stacked recipient its own state and choice", async () => {+ const onActionChange = vi.fn();+ renderWithI18n(<CommentTriggerChips recipients={[entry(walt, running), entry(bob, idle)]} onActionChange={onActionChange} />);+ fireEvent.click(screen.getByText("2 agents will receive this"));+ expect(await screen.findByText(/· Running/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Bob trigger: Will start when sent" }));+ const menu = await screen.findByRole("menu");+ fireEvent.click(within(menu).getByRole("menuitemradio", { name: /Won't start this time/ }));+ expect(onActionChange).toHaveBeenCalledWith("agent-2", "skip");});it("names a blocked mention with an error reason instead of a count", () => {renderWithI18n(<CommentTriggerChips- agents={[]}+ recipients={[]}blocked={[{target_type: "agent",@@ -165,8 +140,7 @@ describe("CommentTriggerChips", () => {},]}draftContent="[@Go](mention://agent/deadbeef-0001) hi"- suppressedAgentIds={new Set()}- onToggle={vi.fn()}+ onActionChange={vi.fn()}/>,);@@ -181,7 +155,7 @@ describe("CommentTriggerChips", () => {it("falls back to the reason alone when the label can't be correlated", () => {renderWithI18n(<CommentTriggerChips- agents={[]}+ recipients={[]}blocked={[{target_type: "agent",@@ -192,8 +166,7 @@ describe("CommentTriggerChips", () => {]}// No matching mention markup for the blocked target → no label available.draftContent="plain text"- suppressedAgentIds={new Set()}- onToggle={vi.fn()}+ onActionChange={vi.fn()}/>,);@@ -204,14 +177,13 @@ describe("CommentTriggerChips", () => {it("renders one named chip per blocked mention", () => {renderWithI18n(<CommentTriggerChips- agents={[]}+ recipients={[]}blocked={[{ target_type: "agent", target_id: "deadbeef-0001", status: "blocked", reason_code: "invocation_not_allowed" },{ target_type: "squad", target_id: "cafef00d-0002", status: "blocked", reason_code: "runtime_offline" },]}draftContent="[@Go](mention://agent/deadbeef-0001) [@Ops](mention://squad/cafef00d-0002)"- suppressedAgentIds={new Set()}- onToggle={vi.fn()}+ onActionChange={vi.fn()}/>,);diff --git a/packages/views/issues/components/comment-trigger-chips.tsx b/packages/views/issues/components/comment-trigger-chips.tsxindex 90b1457bed..93ca9f43ae 100644--- a/packages/views/issues/components/comment-trigger-chips.tsx+++ b/packages/views/issues/components/comment-trigger-chips.tsx@@ -1,13 +1,22 @@"use client";-import { useMemo, useState } from "react";-import { TriangleAlert, Users } from "lucide-react";+import { useMemo, useState, type ReactElement } from "react";+import { ChevronDown, TriangleAlert, Users } from "lucide-react";import type { CommentTriggerPreviewAgent, CommentTriggerOutcome } from "@multica/core/types";+import type { AgentRunState, RecipientAction } from "@multica/core/issues/run-steering";import { useAgentPresenceDetail } from "@multica/core/agents";import { mentionLabelsByTarget } from "@multica/core/issues/comment-trigger-outcomes";import { useCurrentWorkspace } from "@multica/core/paths";import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";import { AVATAR_SIZE_PX } from "@multica/ui/lib/avatar-size";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";import {Popover,PopoverContent,@@ -18,22 +27,22 @@ import { cn } from "@multica/ui/lib/utils";import { AgentStatusDot } from "../../common/actor-avatar";import { useT } from "../../i18n";import { blockedReasonLabel, blockedShortReasonLabel } from "../blocked-trigger-copy";+import type { RecipientEntry } from "../hooks/use-recipient-actions";-// 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.-// The single-agent avatar renders at the `xs` tier; the `+N` overflow chip-// and stack overlap below reuse that tier's pixel diameter so the collapsed-// stack lines up exactly with the avatars.+// Each recipient's chip says what Send will do to it, and its menu offers only+// what that recipient's current state allows: a running turn can take the+// message now, after the turn, or instead of it; an idle or queued agent can+// only start (or fold the message into its queued run) or be skipped.+// One recipient renders as a single chip. Several collapse to an overlapping+// avatar stack, mirroring WorkspaceAgentWorkingChip on the issues header, with+// one row and menu per agent in a click-opened Popover.+// The avatars render at the `xs` tier; the `+N` overflow chip and stack+// overlap reuse that tier's pixel diameter so the stack lines up exactly.const AVATAR_SIZE = AVATAR_SIZE_PX.xs;const MAX_STACK_HEADS = 4;interface CommentTriggerChipsProps {- agents: CommentTriggerPreviewAgent[];+ recipients: RecipientEntry[];// Explicit @agent / @squad mentions that will NOT trigger if posted as-is// (MUL-4525 §2). Each renders as a named warning chip so the user sees WHICH// target won't run and why, not a silent no-op after sending.@@ -44,8 +53,7 @@ interface CommentTriggerChipsProps {// user typed in its mention markup. The server omits blocked target names// (enumeration-safety); this is the user's own text, so it discloses nothing new.draftContent?: string;- suppressedAgentIds: Set<string>;- onToggle: (agentId: string) => void;+ onActionChange: (agentId: string, action: RecipientAction) => void;}type IssuesT = ReturnType<typeof useT<"issues">>["t"];@@ -63,22 +71,6 @@ function sourceLabel(source: string, t: IssuesT): string {}}-// Assignee / @mention reasons are intentionally omitted: the header-// (name · source) already says why they fire, so a reason line there would-// just restate it. Only the squad-leader link (non-obvious) and the unknown-// fallback carry information the header doesn't.-function sourceReason(agent: CommentTriggerPreviewAgent, t: IssuesT): string | null {- switch (agent.source) {- case "issue_assignee":- case "mention_agent":- return null;- case "mention_squad_leader":- return t(($) => $.comment.trigger_reason_mention_squad_leader);- default:- return agent.reason || t(($) => $.comment.trigger_reason_unknown);- }-}-// 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 {@@ -90,48 +82,69 @@ function useTriggerPresenceLine(agentId: string, t: IssuesT): string | null {: 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-micro text-muted-foreground">{sourceLabel(agent.source, t)}</span>- </div>- {suppressed ? (- <div>{t(($) => $.comment.trigger_click_to_restore)}</div>- ) : (- <>- {(() => {- // Reason (when present) and presence share one line; either may be- // absent, so join only the parts that exist to avoid a stray space.- const line = [sourceReason(agent, t), presenceLine].filter(Boolean).join(" ");- return line ? <div>{line}</div> : null;- })()}- <div className="text-muted-foreground">{t(($) => $.comment.trigger_click_to_skip)}</div>- </>- )}- </div>- );+function stateLabel(state: AgentRunState, t: IssuesT): string | null {+ switch (state.kind) {+ case "running":+ return t(($) => $.comment.recipient_state_running);+ case "starting":+ return t(($) => $.comment.recipient_state_starting);+ case "queued":+ return t(($) => $.comment.recipient_state_queued);+ default:+ return null;+ }+}++function actionLabel(action: RecipientAction, state: AgentRunState, t: IssuesT): string {+ switch (action) {+ case "steer":+ return t(($) => $.comment.recipient_steer);+ case "after_run":+ return t(($) => $.comment.recipient_after_run);+ case "restart":+ return t(($) => $.comment.recipient_restart);+ case "skip":+ return t(($) => $.comment.trigger_wont_trigger);+ default:+ return state.kind === "queued"+ ? t(($) => $.comment.recipient_join)+ : t(($) => $.comment.trigger_will_start);+ }+}++// Only choices whose consequence is not obvious from the label carry a line.+function actionDescription(action: RecipientAction, entry: RecipientEntry, presenceLine: string | null, t: IssuesT): string | null {+ const name = entry.agent.name;+ switch (action) {+ case "steer":+ return t(($) => $.comment.recipient_steer_desc, { name });+ case "after_run":+ return t(($) => $.comment.recipient_after_run_desc);+ case "restart":+ return t(($) => $.comment.recipient_restart_desc);+ case "start":+ return entry.state.kind === "queued" ? t(($) => $.comment.recipient_join_desc, { name }) : presenceLine;+ default:+ return null;+ }+}++function chipToneClass(action: RecipientAction): string {+ if (action === "steer") {+ return "border-brand/28 bg-brand/7 text-foreground hover:bg-brand/12 aria-expanded:bg-brand/12 dark:border-brand/45 dark:bg-brand/12 dark:hover:bg-brand/18";+ }+ if (action === "restart") {+ return "text-destructive hover:bg-destructive/10 hover:text-destructive aria-expanded:bg-destructive/10";+ }+ return "text-muted-foreground hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground";}export function CommentTriggerChips({- agents,+ recipients,blocked = [],hasAllMembersMention = false,draftContent = "",- suppressedAgentIds,- onToggle,+ onActionChange,}: CommentTriggerChipsProps) {const { t } = useT("issues");// Blocked outcomes carry no name (enumeration-safety); recover the label the@@ -140,23 +153,13 @@ export function CommentTriggerChips({// Loading and errors render nothing: the preview is an enhancement, and// any interim chrome here reads as composer noise.- if (agents.length === 0 && blocked.length === 0 && !hasAllMembersMention) return null;+ if (recipients.length === 0 && blocked.length === 0 && !hasAllMembersMention) return null;const allowed =- agents.length === 1 ? (- <SingleTriggerChip- agent={agents[0]!}- suppressed={suppressedAgentIds.has(agents[0]!.id)}- onToggle={onToggle}- t={t}- />- ) : agents.length > 1 ? (- <MultiTriggerChip- agents={agents}- suppressedAgentIds={suppressedAgentIds}- onToggle={onToggle}- t={t}- />+ recipients.length === 1 ? (+ <SingleRecipientChip entry={recipients[0]!} onActionChange={onActionChange} t={t} />+ ) : recipients.length > 1 ? (+ <MultiRecipientChip recipients={recipients} onActionChange={onActionChange} t={t} />) : null;if (blocked.length === 0 && !hasAllMembersMention) return allowed;@@ -228,105 +231,134 @@ function BlockedTriggerChip({);}-function SingleTriggerChip({- agent,- suppressed,- onToggle,+// The per-recipient choice menu. `trigger` is the element that opens it: the+// chip itself for a single recipient, a row button inside the stack popover.+function RecipientActionMenu({+ entry,+ onActionChange,+ trigger,t,}: {- agent: CommentTriggerPreviewAgent;- suppressed: boolean;- onToggle: (agentId: string) => void;+ entry: RecipientEntry;+ onActionChange: (agentId: string, action: RecipientAction) => void;+ trigger: ReactElement;t: IssuesT;}) {- const state = suppressed- ? t(($) => $.comment.trigger_skipped_label)- : sourceLabel(agent.source, t);- // The avatar carries "who"; the sentence carries only condition + outcome,- // so it stays fixed-width and never truncates on long agent names.- const sentence = suppressed- ? t(($) => $.comment.trigger_wont_trigger)- : t(($) => $.comment.trigger_will_start);+ const presenceLine = useTriggerPresenceLine(entry.agent.id, t);+ const state = stateLabel(entry.state, t);+ return (+ <DropdownMenu>+ <DropdownMenuTrigger render={trigger} />+ <DropdownMenuContent side="top" align="start" className="w-80">+ <div className="flex min-w-0 items-center gap-2 px-1.5 pt-1 pb-1.5 text-caption text-muted-foreground">+ <TriggerAgentAvatar agent={entry.agent} suppressed={false} />+ <span className="min-w-0 truncate font-medium text-foreground">{entry.agent.name}</span>+ <span className="shrink-0">{state ?? sourceLabel(entry.agent.source, t)}</span>+ </div>+ <DropdownMenuRadioGroup+ value={entry.action}+ onValueChange={(value) => onActionChange(entry.agent.id, value as RecipientAction)}+ >+ {entry.actions.map((action) => {+ const description = actionDescription(action, entry, presenceLine, t);+ return (+ <div key={action}>+ {action === "skip" && <DropdownMenuSeparator />}+ <DropdownMenuRadioItem value={action} className="items-start py-1.5">+ <span className="flex min-w-0 flex-col gap-0.5">+ <span>{actionLabel(action, entry.state, t)}</span>+ {description && <span className="text-caption text-muted-foreground">{description}</span>}+ </span>+ </DropdownMenuRadioItem>+ </div>+ );+ })}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}+function SingleRecipientChip({+ entry,+ onActionChange,+ t,+}: {+ entry: RecipientEntry;+ onActionChange: (agentId: string, action: RecipientAction) => void;+ t: IssuesT;+}) {+ const label = actionLabel(entry.action, entry.state, t);+ // The avatar carries "who"; the sentence carries only the outcome, so it+ // stays fixed-width and never truncates on long agent names.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(- // Sidebar-style resting state: muted until hover so the strip- // reads as metadata, not content (see app-sidebar nav items).- "inline-flex h-6 min-w-0 max-w-full animate-in fade-in cursor-pointer items-center gap-1.5 rounded-md px-1.5 text-micro font-medium text-muted-foreground transition-colors duration-200 hover:bg-muted hover:text-foreground",- )}- >- <TriggerAgentAvatar agent={agent} suppressed={suppressed} />- <span className="truncate">{sentence}</span>- </button>- }- />- <TooltipContent side="top" className="max-w-72 text-caption">- <TriggerAgentTooltipBody agent={agent} suppressed={suppressed} t={t} />- </TooltipContent>- </Tooltip>+ <RecipientActionMenu+ entry={entry}+ onActionChange={onActionChange}+ t={t}+ trigger={+ <button+ type="button"+ aria-label={t(($) => $.comment.trigger_chip_aria, { name: entry.agent.name, state: label })}+ className={cn(+ "inline-flex h-6 min-w-0 max-w-full animate-in fade-in cursor-pointer items-center gap-1.5 rounded-md border border-transparent px-1.5 text-micro font-medium transition-colors duration-200",+ chipToneClass(entry.action),+ )}+ >+ <TriggerAgentAvatar agent={entry.agent} suppressed={entry.action === "skip"} />+ <span className="truncate">{label}</span>+ <ChevronDown aria-hidden className="size-3 shrink-0 text-faint-foreground" />+ </button>+ }+ />);}-function MultiTriggerChip({- agents,- suppressedAgentIds,- onToggle,+function MultiRecipientChip({+ recipients,+ onActionChange,t,}: {- agents: CommentTriggerPreviewAgent[];- suppressedAgentIds: Set<string>;- onToggle: (agentId: string) => void;+ recipients: RecipientEntry[];+ onActionChange: (agentId: string, action: RecipientAction) => 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;+ const activeCount = recipients.filter((r) => r.action !== "skip").length;+ const heads = recipients.slice(0, MAX_STACK_HEADS);+ const overflow = recipients.length - heads.length;// Mirror AgentAvatarStack: ~30% overlap reads as "stacked" without// obscuring the next avatar.const overlap = Math.round(AVATAR_SIZE * 0.3);- // The avatar stack shows who; the sentence promises only what WILL happen,- // so the count covers non-suppressed agents — skipped ones read as the- // dimmed heads right next to the number.const sentence =activeCount === 0? t(($) => $.comment.trigger_none_will_trigger)- : t(($) => $.comment.trigger_will_start_count, { count: activeCount });+ : t(($) => $.comment.recipient_count, { count: activeCount });+ const tone = recipients.some((r) => r.action === "restart")+ ? "restart"+ : recipients.some((r) => r.action === "steer") ? "steer" : "start";const popoverTrigger = (<PopoverTriggerrender={- // Ghost-button affordance (hover fill + aria-expanded pin) so the- // stack reads as clickable, matching pickers across the app.<buttontype="button"className={cn(- "inline-flex h-6 min-w-0 max-w-full animate-in fade-in cursor-pointer items-center gap-1.5 rounded-md px-1.5 text-micro font-medium text-muted-foreground transition-colors duration-200 hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground",+ "inline-flex h-6 min-w-0 max-w-full animate-in fade-in cursor-pointer items-center gap-1.5 rounded-md border border-transparent px-1.5 text-micro font-medium transition-colors duration-200",+ chipToneClass(tone),)}/>}><span className="inline-flex items-center">- {heads.map((agent, i) => (+ {heads.map((entry, i) => (<span- key={agent.id}+ key={entry.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}- />+ <TriggerAgentAvatar agent={entry.agent} suppressed={entry.action === "skip"} showDot={false} /></span>))}{overflow > 0 && (@@ -355,46 +387,40 @@ function MultiTriggerChip({{t(($) => $.comment.trigger_click_to_manage)}</TooltipContent></Tooltip>- <PopoverContent align="start" className="w-64 p-2">+ <PopoverContent align="start" className="w-80 p-2"><div className="px-1.5 pb-1 text-caption 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_skipped_label)- : sourceLabel(agent.source, t);+ {recipients.map((entry) => {+ const label = actionLabel(entry.action, entry.state, t);+ const state = stateLabel(entry.state, t);return (- <Tooltip key={agent.id}>- <TooltipTrigger- render={+ <div key={entry.agent.id} className="flex min-w-0 items-center gap-2 rounded-md px-1.5 py-1">+ <TriggerAgentAvatar agent={entry.agent} suppressed={entry.action === "skip"} />+ <span className="min-w-0 flex-1 truncate text-caption">+ {entry.agent.name}+ {state && <span className="text-muted-foreground"> · {state}</span>}+ </span>+ <RecipientActionMenu+ entry={entry}+ onActionChange={onActionChange}+ t={t}+ trigger={<buttontype="button"- aria-pressed={suppressed}- aria-label={t(($) => $.comment.trigger_chip_aria, { name: agent.name, state })}- onClick={() => onToggle(agent.id)}+ aria-label={t(($) => $.comment.trigger_chip_aria, { name: entry.agent.name, state: label })}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",+ "inline-flex h-6 max-w-40 shrink-0 cursor-pointer items-center gap-1 rounded-md border border-transparent px-1.5 text-micro font-medium transition-colors",+ chipToneClass(entry.action),)}>- <TriggerAgentAvatar agent={agent} suppressed={suppressed} />- <span- className={cn(- "min-w-0 flex-1 truncate text-caption",- suppressed && "text-muted-foreground",- )}- >- {agent.name}- </span>- <span className="shrink-0 text-micro text-muted-foreground">{state}</span>+ <span className="truncate">{label}</span>+ <ChevronDown aria-hidden className="size-3 shrink-0 text-faint-foreground" /></button>}/>- <TooltipContent side="right" className="max-w-72 text-caption">- <TriggerAgentTooltipBody agent={agent} suppressed={suppressed} t={t} />- </TooltipContent>- </Tooltip>+ </div>);})}</div>diff --git a/packages/views/issues/components/inline-comment-run.test.tsx b/packages/views/issues/components/inline-comment-run.test.tsxindex 91ad9fa3c3..66acafa5a1 100644--- a/packages/views/issues/components/inline-comment-run.test.tsx+++ b/packages/views/issues/components/inline-comment-run.test.tsx@@ -6,18 +6,16 @@ import type { ReactNode } from "react";import { api } from "@multica/core/api";import { chatKeys } from "@multica/core/chat/queries";import { issueKeys } from "@multica/core/issues/queries";-import { useCommentDraftStore, useTaskSupplementDraftStore } from "@multica/core/issues/stores";import type { AgentTask, TimelineEntry } from "@multica/core/types";import type { TaskMessagePayload } from "@multica/core/types/events";import { renderWithI18n } from "../../test/i18n";-import { InlineCommentRun, PlacedInlineCommentRun } from "./inline-comment-run";-import { SupplementReceipt } from "./comment-card";+import { InlineCommentRun } from "./inline-comment-run";const dispatchReasonCodeMock = vi.hoisted(() => vi.fn());vi.mock("@multica/core/api", () => ({ api: {getIssue: vi.fn(), listTaskMessages: vi.fn(), cancelTask: vi.fn(), rerunIssue: vi.fn(),- createTaskSupplement: vi.fn(), retryTaskSupplement: vi.fn(), listTasksByIssue: vi.fn(),+ listTasksByIssue: vi.fn(),}, dispatchReasonCode: dispatchReasonCodeMock }));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace" }));vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Reviewer" }) }));@@ -41,8 +39,6 @@ const messages: TaskMessagePayload[] = [afterEach(() => {cleanup();vi.clearAllMocks();- useTaskSupplementDraftStore.setState({ drafts: {} });- useCommentDraftStore.setState({ drafts: {} });});function setup(initialTask: AgentTask, hasReply = false, presentation: "inline" | "header" = "inline") {@@ -55,208 +51,35 @@ function setup(initialTask: AgentTask, hasReply = false, presentation: "inline"}describe("InlineCommentRun", () => {- it("creates no receipt observers for ordinary or delivered comments", () => {- const client = new QueryClient();- const entry = { id: "comment", type: "comment" } as TimelineEntry;- renderWithI18n(<QueryClientProvider client={client}>- <SupplementReceipt issueId="issue" entry={entry} />- <SupplementReceipt issueId="issue" entry={{ ...entry, supplement_task_id: id, supplement_status: "delivered" }} />- </QueryClientProvider>);- expect(client.getQueryCache().getAll()).toHaveLength(0);- });-- it.each(["toggle", "cancel", "escape"])("closes and clears a running draft with %s", (action) => {- vi.mocked(api.listTaskMessages).mockResolvedValue([]);- setup(task({ supplement_capability: "task-supplement-v1", can_supplement: true }));- fireEvent.click(screen.getByRole("button", { name: "Add message" }));- const input = screen.getByPlaceholderText("Add guidance for this running turn");- fireEvent.change(input, { target: { value: "Discard this draft." } });- if (action === "escape") fireEvent.keyDown(input, { key: "Escape" });- else fireEvent.click(screen.getByRole("button", { name: action === "toggle" ? "Add message" : "Cancel" }));- expect(screen.queryByPlaceholderText("Add guidance for this running turn")).not.toBeInTheDocument();- expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();- expect(api.createTaskSupplement).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole("button", { name: "Add message" }));- expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("");- });-- it.each(["completed", "cancelled", "failed"] as const)("removes an empty panel when the run becomes %s", (status) => {- vi.mocked(api.listTaskMessages).mockResolvedValue([]);- const current = task({ supplement_capability: "task-supplement-v1", can_supplement: true });- const { rerender } = setup(current);- fireEvent.click(screen.getByRole("button", { name: "Add message" }));- rerender({ ...current, status });- expect(screen.queryByPlaceholderText("Add guidance for this running turn")).not.toBeInTheDocument();- expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();- });-- it.each(["Move to new message", "Discard"])("lets a terminal draft %s and restores the reply header", (action) => {- vi.mocked(api.listTaskMessages).mockResolvedValue([]);- const current = task({ supplement_capability: "task-supplement-v1", can_supplement: true });- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });- const view = (status: AgentTask["status"], hasReply: boolean) => <QueryClientProvider client={client}>- <PlacedInlineCommentRun run={{ task: { ...current, status }, commentId: "reply", hasReply }} presentation="header" />- <PlacedInlineCommentRun run={{ task: { ...current, status }, commentId: "reply", hasReply }} />- </QueryClientProvider>;- const rendered = renderWithI18n(view("running", false));- fireEvent.click(screen.getByRole("button", { name: "Add message" }));- fireEvent.change(screen.getByPlaceholderText("Add guidance for this running turn"), { target: { value: "Preserve this only on move." } });- rendered.rerender(view("completed", true));- expect(screen.getByRole("button", { name: "Move to new message" })).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Discard" })).toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: action }));- expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();- expect(useCommentDraftStore.getState().getDraft("new:issue")).toBe(action === "Discard" ? undefined : "Preserve this only on move.");- expect(screen.queryByPlaceholderText("Add guidance for this running turn")).not.toBeInTheDocument();- expect(screen.getByRole("button", { name: "Open full log" })).toBeInTheDocument();- expect(api.createTaskSupplement).not.toHaveBeenCalled();- });-- it("hides additional messages without negotiated support", () => {+ it("places a delivered steer between the steps it arrived between", async () => {+ vi.mocked(api.listTaskMessages).mockResolvedValue([+ { task_id: id, issue_id: "issue", seq: 1, type: "tool_use", tool: "exec_command", input: { command: "cat login.tsx" }, created_at: "2026-09-07T00:00:05Z" },+ { task_id: id, issue_id: "issue", seq: 2, type: "tool_result", tool: "exec_command", output: "ok", created_at: "2026-09-07T00:00:06Z" },+ { task_id: id, issue_id: "issue", seq: 3, type: "text", content: "Only touching web now.", created_at: "2026-09-07T00:00:20Z" },+ ]);const { client } = setup(task());- expect(screen.queryByRole("button", { name: "Add message" })).not.toBeInTheDocument();- client.clear();- });-- it("disables additional messages when support is negotiated but permission is denied", () => {- const { client } = setup(task({ supplement_capability: "task-supplement-v1", can_supplement: false }));- expect(screen.getByRole("button", { name: "Add message" })).toBeDisabled();- client.clear();- });- it("preserves additional-message text when delivery submission fails", async () => {- vi.mocked(api.listTaskMessages).mockResolvedValue([]);- vi.mocked(api.createTaskSupplement).mockRejectedValue(new Error("run ended"));- setup(task({ supplement_capability: "task-supplement-v1", can_supplement: true }));- fireEvent.click(screen.getByRole("button", { name: "Add message" }));- const input = screen.getByPlaceholderText("Add guidance for this running turn");- fireEvent.change(input, { target: { value: "preserve this draft" } });- fireEvent.click(screen.getByRole("button", { name: "Send" }));- await waitFor(() => expect(api.createTaskSupplement).toHaveBeenCalled());- expect(input).toHaveValue("preserve this draft");- });-- it.each([false, true])("settles a sent draft after the run remounts (edited: %s)", async (edited) => {- vi.mocked(api.listTaskMessages).mockResolvedValue([]);- const comment = {- id: "supplement-comment", issue_id: "issue", author_type: "member" as const, author_id: "user",- content: "Create a rollback note.", type: "comment" as const, parent_id: null, reactions: [], attachments: [],- created_at: "2026-09-07T00:00:10Z", updated_at: "2026-09-07T00:00:10Z",- resolved_at: null, resolved_by_type: null, resolved_by_id: null,- supplement_task_id: id, supplement_status: "pending" as const,- };- let resolveRequest!: (value: typeof comment) => void;- const request = new Promise<typeof comment>((resolve) => { resolveRequest = resolve; });- vi.mocked(api.createTaskSupplement).mockReturnValue(request);- const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });- const current = task({ supplement_capability: "task-supplement-v1", can_supplement: true });- const view = (commentId: string) => <QueryClientProvider client={client}>- <PlacedInlineCommentRun key={commentId} run={{ task: current, commentId, hasReply: false }} />- </QueryClientProvider>;- const rendered = renderWithI18n(view("comment"));- fireEvent.click(screen.getByRole("button", { name: "Add message" }));- const input = screen.getByPlaceholderText("Add guidance for this running turn");- fireEvent.change(input, { target: { value: comment.content } });- fireEvent.click(screen.getByRole("button", { name: "Send" }));- await waitFor(() => expect(api.createTaskSupplement).toHaveBeenCalledWith(- "issue", id, comment.content, expect.any(String),- ));-- // A realtime comment can re-anchor the run before the send response arrives.- rendered.rerender(view(comment.id));- const remountedInput = screen.getByPlaceholderText("Add guidance for this running turn");- expect(remountedInput).not.toBe(input);- expect(remountedInput).toHaveValue(comment.content);- if (edited) fireEvent.change(remountedInput, { target: { value: "A newer unsent draft." } });-- await act(async () => resolveRequest(comment));- await waitFor(() => expect(client.getMutationCache().getAll()[0]?.state.status).toBe("success"));- if (edited) {- expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("A newer unsent draft.");- } else {- expect(screen.queryByPlaceholderText("Add guidance for this running turn")).not.toBeInTheDocument();- expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();- fireEvent.click(screen.getByRole("button", { name: "Add message" }));- expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("");- }- client.clear();- });-- it("keeps the task draft through reply placement changes and a full remount", () => {- vi.mocked(api.listTaskMessages).mockResolvedValue([]);- const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });- const view = (hasReply: boolean) => <QueryClientProvider client={client}>- <PlacedInlineCommentRun run={{ task: task({ supplement_capability: "task-supplement-v1", can_supplement: true }), commentId: "reply", hasReply }} presentation="header" />- <PlacedInlineCommentRun run={{ task: task({ supplement_capability: "task-supplement-v1", can_supplement: true }), commentId: "reply", hasReply }} />- </QueryClientProvider>;- const rendered = renderWithI18n(view(false));- fireEvent.click(screen.getByRole("button", { name: "Add message" }));- fireEvent.change(screen.getByPlaceholderText("Add guidance for this running turn"), {- target: { value: "Create remount-proof evidence." },- });-- rendered.rerender(view(true));- expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("Create remount-proof evidence.");- rendered.unmount();-- renderWithI18n(view(true));- expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("Create remount-proof evidence.");- expect(screen.queryByRole("button", { name: "Open full log" })).not.toBeInTheDocument();+ client.setQueryData<TimelineEntry[]>(issueKeys.timeline("issue"), [{+ id: "steer", type: "comment", actor_type: "member", actor_id: "user",+ content: "Leave desktop alone.", created_at: "2026-09-07T00:00:08Z",+ supplements: [{ task_id: id, agent_id: "agent", status: "delivered", delivered_at: "2026-09-07T00:00:10Z" }],+ }]);+ await screen.findByText("Only touching web now.");+ fireEvent.click(screen.getByRole("button", { name: /View activity/ }));+ const steer = await screen.findByText("Reviewer added");+ const row = steer.closest("[data-steer-comment]")!;+ expect(row).toHaveTextContent("Leave desktop alone.");+ const before = screen.getAllByText("cat login.tsx").find((node) => node.closest("summary"))!;+ const after = screen.getAllByText("Only touching web now.").find((node) => node.closest("summary"))!;+ expect(before.compareDocumentPosition(row) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(row.compareDocumentPosition(after) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();});- it("keeps a 409 draft and moves it explicitly to the new-message composer", async () => {- vi.mocked(api.listTaskMessages).mockResolvedValue([]);- dispatchReasonCodeMock.mockReturnValue("task_supplement_turn_ended");- vi.mocked(api.createTaskSupplement).mockRejectedValue(new Error("ended"));+ it("offers no run-level message box: messages go through the thread composer", async () => {+ vi.mocked(api.listTaskMessages).mockResolvedValue(messages);setup(task({ supplement_capability: "task-supplement-v1", can_supplement: true }));- fireEvent.click(screen.getByRole("button", { name: "Add message" }));- const input = screen.getByPlaceholderText("Add guidance for this running turn");- fireEvent.change(input, { target: { value: "Create retained.txt." } });- fireEvent.click(screen.getByRole("button", { name: "Send" }));- const move = await screen.findByRole("button", { name: "Move to new message" });- expect(input).toHaveValue("Create retained.txt.");- fireEvent.click(move);- expect(useCommentDraftStore.getState().getDraft("new:issue")).toBe("Create retained.txt.");- expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();- });-- it.each(["completed", "cancelled", "failed"] as const)("settles a pending receipt immediately when the run becomes %s", async (status) => {- const entry = {- id: "supplement-comment", issue_id: "issue", actor_type: "member", actor_id: "user",- content: "Create receipt evidence.", type: "comment", created_at: "2026-09-07T00:00:10Z",- supplement_task_id: id, supplement_status: "pending",- } as TimelineEntry;- const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });- client.setQueryData(issueKeys.tasks("issue"), [task()]);- renderWithI18n(<QueryClientProvider client={client}>- <SupplementReceipt issueId="issue" entry={entry} />- </QueryClientProvider>);- expect(screen.getByRole("status")).toHaveTextContent("Waiting for delivery");- act(() => client.setQueryData(issueKeys.tasks("issue"), [task({ status })]));- await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Not delivered · the run ended before delivery"));- expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument();- });-- it("localizes a stable injection failure and retries the same bound comment", async () => {- vi.mocked(api.retryTaskSupplement).mockResolvedValue();- vi.mocked(api.listTasksByIssue).mockResolvedValue([task()]);- const entry = {- id: "supplement-comment", issue_id: "issue", actor_type: "member", actor_id: "user",- content: "Create receipt evidence.", type: "comment", created_at: "2026-09-07T00:00:10Z",- supplement_task_id: id, supplement_status: "failed", supplement_failure_reason: "provider_rejected",- } as TimelineEntry;- const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });- client.setQueryData(issueKeys.tasks("issue"), [task()]);- renderWithI18n(<QueryClientProvider client={client}>- <SupplementReceipt issueId="issue" entry={entry} />- </QueryClientProvider>);-- expect(screen.getByRole("alert")).toHaveTextContent("Not delivered · the agent rejected the message");- fireEvent.click(screen.getByRole("button", { name: "Retry" }));- await waitFor(() => expect(api.retryTaskSupplement).toHaveBeenCalledWith("issue", id, "supplement-comment"));- await waitFor(() => expect(screen.getByRole("button", { name: "Retry" })).not.toBeDisabled());- act(() => client.setQueryData(issueKeys.tasks("issue"), [task({ status: "completed" })]));- await waitFor(() => expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument());- expect(screen.getByRole("alert")).toHaveTextContent("Not delivered · the agent rejected the message");+ await screen.findByText("pnpm test");+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /message/i })).not.toBeInTheDocument();});it("previews streamed agent messages in collapsed steps and expands the full body", async () => {diff --git a/packages/views/issues/components/inline-comment-run.tsx b/packages/views/issues/components/inline-comment-run.tsxindex 67350e2b50..84ce8f6fa5 100644--- a/packages/views/issues/components/inline-comment-run.tsx+++ b/packages/views/issues/components/inline-comment-run.tsx@@ -1,19 +1,20 @@"use client";import { useEffect, useId, useMemo, useState, type ReactNode } from "react";-import { AlertCircle, Brain, ChevronRight, CirclePause, Clock3, ExternalLink, Loader2, MessageSquare, MessageSquarePlus, RotateCcw, ScrollText, Send, Square, Terminal } from "lucide-react";+import { AlertCircle, Brain, Check, ChevronRight, CirclePause, Clock3, CornerDownRight, ExternalLink, Loader2, MessageSquare, RotateCcw, ScrollText, Square, Terminal } from "lucide-react";+import { useQuery } from "@tanstack/react-query";import { toast } from "sonner";import { useWorkspaceId } from "@multica/core/hooks";import { useTraceIssueLabels } from "../../common/task-transcript/use-trace-issue-labels";import { useActorName } from "@multica/core/workspace/hooks";import { useTaskMessages } from "@multica/core/chat/queries";-import { useCancelIssueRun, useCreateTaskSupplement, useRetryIssueRun } from "@multica/core/issues/mutations";-import { useCommentDraftStore, useTaskSupplementDraftStore } from "@multica/core/issues/stores";+import { useCancelIssueRun, useRetryIssueRun } from "@multica/core/issues/mutations";+import { issueTimelineOptions } from "@multica/core/issues/queries";+import { commentSupplementReceipts } from "@multica/core/issues/run-steering";import { dispatchReasonCode } from "@multica/core/api";-import type { AgentTask } from "@multica/core/types";+import type { AgentTask, TimelineEntry } from "@multica/core/types";import { ActorAvatar } from "../../common/actor-avatar";import { Button } from "@multica/ui/components/ui/button";-import { Textarea } from "@multica/ui/components/ui/textarea";import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";import { cn } from "@multica/ui/lib/utils";import { AgentTranscriptDialog, StepBody } from "../../common/task-transcript/agent-transcript-dialog";@@ -55,12 +56,8 @@ export function useInlineCommentRunState() {export type InlineCommentRunState = ReturnType<typeof useInlineCommentRunState>;export function PlacedInlineCommentRun({ presentation = "inline", ...props }: Parameters<typeof InlineCommentRun>[0]) {- const draft = useTaskSupplementDraftStore((store) => store.drafts[props.run.task.id]);- // A live reply normally compacts its run into the comment header. Once the- // user opens a task draft, keep the full run mounted at its timeline slot so- // reply arrival and supplement-driven re-anchoring cannot discard the text.- const inHeader = showCommentRunInHeader(props.run) && !draft?.open;- if ((presentation === "header") !== inHeader) return null;+ // A live reply compacts its run into the comment header.+ if ((presentation === "header") !== showCommentRunInHeader(props.run)) return null;return <InlineCommentRun {...props} presentation={presentation} />;}@@ -99,11 +96,9 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = falconst [confirmStop, setConfirmStop] = useState(false);const [now, setNow] = useState(Date.now);const [visibleCount, setVisibleCount] = useState(12);- const supplementDraft = useTaskSupplementDraftStore((store) => store.drafts[task.id]);const animationVisibility = useRunAnimationVisibility<HTMLDivElement>();const cancel = useCancelIssueRun(task.issue_id);const retry = useRetryIssueRun(task.issue_id);- const supplement = useCreateTaskSupplement(task.issue_id);const regionId = useId();// Keep one disclosure button mounted across queued, live, and historical states.// Historical, collapsed runs still don't fetch transcripts.@@ -113,6 +108,12 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = falconst formatText = useTraceIssueLabels(useWorkspaceId(), task.issue_id, items, loadTranscript);const steps = useMemo(() => buildSteps(items), [items]);const rows = useMemo(() => groupSteps(steps), [steps]);+ // Messages that steered this turn, placed in its step list where it read them.+ const { data: steers = NO_STEERS } = useQuery({+ ...issueTimelineOptions(task.issue_id),+ enabled: false,+ select: (entries: TimelineEntry[]) => deliveredSteers(entries, task.id),+ });useEffect(() => {if (!active) return;const timer = setInterval(() => setNow(Date.now()), 1000);@@ -141,42 +142,6 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = falconst activityLabel = t(($) => $.inline_run.view_activity);const stepLabel = steps.length > 0 ? t(($) => $.inline_run.steps, { count: steps.length }) : "";const stopLabel = cancel.isPending || cancel.isSuccess ? t(($) => $.inline_run.stopping) : t(($) => $.inline_run.stop);- const canSupplement = task.status === "running"- && task.supplement_capability === "task-supplement-v1"- && task.can_supplement === true- && !supplementDraft?.ended;- const supplementDisabledReason = supplementDraft?.ended- ? t(($) => $.inline_run.supplement_ended)- : t(($) => $.inline_run.supplement_forbidden);- useEffect(() => {- if (supplementDraft && task.status !== "running" && !active) {- useTaskSupplementDraftStore.getState().markEnded(task.id);- }- }, [active, supplementDraft, task.id, task.status]);- const closeSupplement = () => {- if (!supplement.isPending) useTaskSupplementDraftStore.getState().clear(task.id);- };- const submitSupplement = () => {- const content = supplementDraft?.content.trim() ?? "";- if (!content || !canSupplement || supplement.isPending) return;- const clientRequestId = supplementDraft?.clientRequestId ?? crypto.randomUUID();- useTaskSupplementDraftStore.getState().setRequestId(task.id, clientRequestId);- supplement.mutate({ taskId: task.id, content, clientRequestId }, {- onError: (error) => {- const code = dispatchReasonCode(error);- if (code === "task_supplement_turn_ended") {- useTaskSupplementDraftStore.getState().markEnded(task.id);- }- toast.error(code === "task_supplement_turn_ended"- ? t(($) => $.inline_run.supplement_ended)- : code === "task_supplement_unsupported"- ? t(($) => $.inline_run.supplement_unsupported)- : code === "invocation_not_allowed"- ? t(($) => $.inline_run.supplement_forbidden)- : t(($) => $.inline_run.supplement_failed));- },- });- };const transcript = fullLogOpen && <AgentTranscriptDialog open onOpenChange={setFullLogOpen}task={task} items={items} agentName={name} isLive={active} finalFocus={logFromKeyboard}contentState={isPending ? <p role="status" className="text-body text-muted-foreground">{t(($) => $.inline_run.loading)}</p>@@ -188,21 +153,6 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = falonClick={() => setConfirmStop(true)}>{cancel.isPending || cancel.isSuccess ? <Loader2 className="size-3.5 animate-spin motion-reduce:animate-none" /> : <Square className="size-3.5" />}</Button>;- const supplementButton = active- && task.supplement_capability === "task-supplement-v1"- && <Tooltip>- <TooltipTrigger render={<span className="inline-flex">- <Button type="button" size="sm" variant="ghost" className="text-muted-foreground"- aria-label={t(($) => $.inline_run.supplement_action)}- aria-expanded={!!supplementDraft?.open}- disabled={supplement.isPending || (!supplementDraft?.open && !canSupplement)}- onClick={() => supplementDraft?.open ? closeSupplement() : useTaskSupplementDraftStore.getState().open(task.id, task.issue_id)}>- <MessageSquarePlus className="size-3.5" />- <span className="@max-[32rem]/run:sr-only">{t(($) => $.inline_run.supplement_action)}</span>- </Button>- </span>} />- <TooltipContent>{canSupplement ? t(($) => $.inline_run.supplement_action) : supplementDisabledReason}</TooltipContent>- </Tooltip>;const stopDialog = <TerminateTaskConfirmDialog open={confirmStop} onOpenChange={setConfirmStop}showRunningNote={task.status !== "queued"}onConfirm={() => cancel.mutate(task.id, { onError: () => toast.error(t(($) => $.execution_log.cancel_failed)) })} />;@@ -262,7 +212,6 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = fal<ChevronRight ref={state.disclosure.chevronRef} aria-hidden className={cn("size-3.5 shrink-0", expanded && "rotate-90")} /></button><span className={cn("shrink-0 whitespace-nowrap text-caption tabular-nums text-muted-foreground", showIdentity && !active && "@max-[32rem]/run:hidden")}>{elapsed}</span>- {supplementButton}{stopButton}{(!hasReply || replacesFailureNotice) && ended && <Buttonsize="xs" variant="outline" className={cn(showIdentity && "@max-[32rem]/run:size-6 @max-[32rem]/run:p-0")} disabled={retry.isPending || retry.isSuccess}@@ -274,51 +223,6 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = fal</div><div className={cn(showIdentity && "pl-8")}>{replyTo}- {supplementDraft?.open && <div className="mt-2 space-y-2 rounded-md border bg-muted/20 p-2"- onKeyDown={(event) => {- if (event.key === "Escape") {- event.preventDefault();- event.stopPropagation();- closeSupplement();- }- }}>- <Textarea value={supplementDraft.content} autoFocus rows={3}- placeholder={t(($) => $.inline_run.supplement_placeholder)}- disabled={supplement.isPending}- onChange={(event) => {- useTaskSupplementDraftStore.getState().setContent(task.id, task.issue_id, event.target.value);- }}- onKeyDown={(event) => {- if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {- event.preventDefault();- submitSupplement();- }- }} />- <div className="flex items-center justify-between gap-2">- <p className="text-micro text-muted-foreground">{canSupplement- ? t(($) => $.inline_run.supplement_notice)- : supplementDraft.ended || task.status !== "running" ? t(($) => $.inline_run.supplement_ended) : supplementDisabledReason}</p>- <div className="flex shrink-0 items-center gap-2">- <Button type="button" size="sm" variant="outline" disabled={supplement.isPending} onClick={closeSupplement}>- {supplementDraft.ended ? t(($) => $.inline_run.supplement_discard) : t(($) => $.comment.cancel_action)}- </Button>- {supplementDraft.ended && supplementDraft.content.trim() && <Button type="button" size="sm" variant="outline"- disabled={supplement.isPending}- onClick={() => {- useCommentDraftStore.getState().appendToDraftContent(`new:${task.issue_id}`, supplementDraft.content);- useTaskSupplementDraftStore.getState().clear(task.id);- toast.success(t(($) => $.inline_run.supplement_moved));- }}>- {t(($) => $.inline_run.supplement_move_to_new)}- </Button>}- {!supplementDraft.ended && <Button type="button" size="sm" disabled={!supplementDraft.content.trim() || supplement.isPending || !canSupplement}- onClick={submitSupplement}>- {supplement.isPending ? <Loader2 className="size-3.5 animate-spin motion-reduce:animate-none" /> : <Send className="size-3.5" />}- {t(($) => $.inline_run.supplement_send)}- </Button>}- </div>- </div>- </div>}{output && <div className="mt-2 text-body"><ReadonlyContent content={redactSecrets(output)} /></div>}{needsAction && rawError && <p title={rawError}className="mt-1.5 line-clamp-4 whitespace-pre-wrap break-words rounded-md border bg-muted/50 px-2.5 py-1.5 font-mono text-caption text-muted-foreground">@@ -331,7 +235,9 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = fal{!isPending && !isError && rows.length === 0 && <p className="text-caption text-muted-foreground">{t(($) => $.inline_run.empty)}</p>}{rows.length > visibleCount && <button type="button" className="py-1 text-caption text-muted-foreground hover:text-foreground"onClick={() => setVisibleCount((count) => count + 12)}>{t(($) => $.inline_run.show_earlier, { count: rows.length - visibleCount })}</button>}- {rows.slice(-visibleCount).map((row) => <InlineStep key={row.seq} row={row} live={active} formatText={formatText} />)}+ {interleaveSteers(rows.slice(-visibleCount), steers, rows.length > visibleCount).map((item) => "steer" in item+ ? <InlineSteer key={`steer:${item.steer.id}`} steer={item.steer} />+ : <InlineStep key={item.row.seq} row={item.row} live={active} formatText={formatText} />)}<button type="button" className="flex items-center gap-1.5 rounded-xs py-2 text-caption text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"onClick={openFullLog}>{t(($) => $.inline_run.full_log)}<ExternalLink className="size-3" /></button></div>}@@ -342,6 +248,73 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = fal);}+interface DeliveredSteer {+ id: string;+ actorType: string;+ actorId: string;+ content: string;+ deliveredAt: string;+}++const NO_STEERS: DeliveredSteer[] = [];++function deliveredSteers(entries: TimelineEntry[], taskId: string): DeliveredSteer[] {+ const out: DeliveredSteer[] = [];+ for (const entry of entries) {+ if (entry.type !== "comment") continue;+ const receipt = commentSupplementReceipts(entry)+ .find((r) => r.task_id === taskId && r.status === "delivered" && r.delivered_at);+ if (!receipt) continue;+ out.push({ id: entry.id, actorType: entry.actor_type, actorId: entry.actor_id, content: entry.content ?? "", deliveredAt: receipt.delivered_at! });+ }+ return out.length ? out : NO_STEERS;+}++function rowStartedAt(row: TraceRow): number {+ const at = isGroupRow(row) ? row.steps[0]?.startedAt : row.startedAt;+ return at ? Date.parse(at) : Number.NaN;+}++// A steer sits right before the first step that started after the turn read+// it. With earlier steps folded away, a steer read before the first visible+// step folds away with them.+function interleaveSteers(rows: TraceRow[], steers: DeliveredSteer[], hasEarlier: boolean): ({ row: TraceRow } | { steer: DeliveredSteer })[] {+ if (steers.length === 0) return rows.map((row) => ({ row }));+ const pending = [...steers].sort((a, b) => Date.parse(a.deliveredAt) - Date.parse(b.deliveredAt));+ const firstVisible = rows.length ? rowStartedAt(rows[0]!) : Number.NaN;+ const out: ({ row: TraceRow } | { steer: DeliveredSteer })[] = [];+ let next = 0;+ if (hasEarlier && Number.isFinite(firstVisible)) {+ while (next < pending.length && Date.parse(pending[next]!.deliveredAt) < firstVisible) next++;+ }+ for (const row of rows) {+ const started = rowStartedAt(row);+ while (next < pending.length && Number.isFinite(started) && Date.parse(pending[next]!.deliveredAt) < started) {+ out.push({ steer: pending[next++]! });+ }+ out.push({ row });+ }+ while (next < pending.length) out.push({ steer: pending[next++]! });+ return out;+}++function InlineSteer({ steer }: { steer: DeliveredSteer }) {+ const { t } = useT("issues");+ const { getActorName } = useActorName();+ const name = getActorName(steer.actorType, steer.actorId);+ const summary = traceEventSummary({ type: "text", content: steer.content });+ return <div className="flex min-w-0 items-center gap-2 rounded-xs bg-brand/7 px-1 py-1.5 text-caption dark:bg-brand/12" data-steer-comment={steer.id}>+ <CornerDownRight aria-hidden className="size-3.5 shrink-0 text-brand" />+ <span className="min-w-0 flex-1 truncate" title={steer.content}>+ <span className="font-medium">{t(($) => $.inline_run.steer_step, { name })}</span>+ <span className="text-muted-foreground"> · {summary}</span>+ </span>+ <span className="inline-flex shrink-0 items-center gap-0.5 text-micro text-success">+ <Check aria-hidden className="size-3" />{t(($) => $.inline_run.steer_step_read)}+ </span>+ </div>;+}+function InlineStep({ row, live, formatText }: { row: TraceRow; live: boolean; formatText: (text: string) => string }) {const { t } = useT("issues");const [open, setOpen] = useState(false);diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 6aa8c70cd8..487b5fc99c 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -439,17 +439,13 @@ vi.mock("@multica/core/issues/stores", async () => ({}),},),- useTaskSupplementDraftStore: (await import("zustand")).create(() => ({- drafts: {}, open: vi.fn(), setContent: vi.fn(), setRequestId: vi.fn(),- markEnded: vi.fn(), clear: vi.fn(),- })),useCommentComposerStore: Object.assign((selector?: any) => {- const state = { sticky: true, toggleSticky: () => {} };+ const state = { sticky: true, runningAgentReply: "steer", toggleSticky: () => {} };return selector ? selector(state) : state;},{- getState: () => ({ sticky: true, toggleSticky: () => {} }),+ getState: () => ({ sticky: true, runningAgentReply: "steer", toggleSticky: () => {} }),},),}));diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsxindex 2d740fab71..ae07aed8f8 100644--- a/packages/views/issues/components/reply-input.tsx+++ b/packages/views/issues/components/reply-input.tsx@@ -2,12 +2,13 @@import { composeAnnotatedReply, EMPTY_REPLY_ANNOTATIONS, hasReplyIntent } from "@multica/core/drafts/reply-annotation";import { ReplyAnnotations } from "./reply-annotations";-import { useRef, useState, useCallback, useEffect, useMemo } from "react";+import { useRef, useState, useEffect, useMemo } from "react";import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { SubmitButton } from "@multica/ui/components/common/submit-button";+import { Button } from "@multica/ui/components/ui/button";import { ActorAvatar } from "../../common/actor-avatar";-import { contentReferencesAttachment } from "@multica/core/types";+import { contentReferencesAttachment, type AgentTask } from "@multica/core/types";import { formatShortcut, useShortcut } from "@multica/core/shortcuts";import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issues/stores";import { cn } from "@multica/ui/lib/utils";@@ -15,6 +16,9 @@ import type { AvatarSize } from "@multica/ui/lib/avatar-size";import { useT } from "../../i18n";import { CommentTriggerChips } from "./comment-trigger-chips";import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";+import { useRecipientActions } from "../hooks/use-recipient-actions";+import { SteerAttachmentNotice } from "./steer-attachment-notice";+import { useStopRunsBeforeSend } from "./use-stop-runs-before-send";import { useCommentUploads } from "./use-comment-uploads";import { useQuickActionMenu } from "../hooks/use-quick-action-menu";@@ -30,7 +34,7 @@ interface ReplyInputProps {avatarId: string;/** Resolves true on success, false on failure — the reply box keeps its text* (locked + spinning) until then, clearing only on success. */- onSubmit: (content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<string | boolean>;+ onSubmit: (content: string, attachmentIds?: string[], suppressAgentIds?: string[], steerTaskIds?: string[]) => Promise<string | boolean>;/** Called after the server accepts the reply and the composer is cleared. */onAccepted?: (commentId: string) => void;size?: "sm" | "default";@@ -40,8 +44,13 @@ interface ReplyInputProps {draftKey?: CommentDraftKey;targetMissing?: boolean;onEditAnnotation?: (id: string) => boolean;+ /** Whether a running turn takes this reply by default: true for the turn+ * that belongs to this thread. Other recipients' turns can still be chosen. */+ steerByDefault?: (task: AgentTask) => boolean;}+const NEVER_STEER_BY_DEFAULT = () => false;+// ---------------------------------------------------------------------------// ReplyInput// ---------------------------------------------------------------------------@@ -58,6 +67,7 @@ function ReplyInput({draftKey,onEditAnnotation,targetMissing = false,+ steerByDefault = NEVER_STEER_BY_DEFAULT,}: ReplyInputProps) {const { t } = useT("issues");const { t: tEditor } = useT("editor");@@ -79,7 +89,6 @@ function ReplyInput({const [content, setContent] = useState(initialDraft ?? "");const setDraft = useCommentDraftStore((s) => s.setDraft);const [isEmpty, setIsEmpty] = useState(!initialDraft?.trim());- const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());const annotations = useCommentDraftStore((s) => draftKey ? s.getAnnotations(draftKey) : EMPTY_REPLY_ANNOTATIONS);const composedContent = useMemo(() => composeAnnotatedReply(content, annotations), [content, annotations]);const canSend = !targetMissing && (annotations.length ? hasReplyIntent(content, annotations) : !isEmpty);@@ -92,6 +101,19 @@ function ReplyInput({// CommentInput.const { uploads, attachments: pendingAttachments, handleUpload, removeUpload, gate } =useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);+ const hasAttachments = useMemo(+ () => pendingAttachments.some((a) => contentReferencesAttachment(content, a)) || gate.uploading,+ [pendingAttachments, content, gate.uploading],+ );+ const { recipients, attachmentsBlockSteer, routing, setAction, reset: resetRecipients } = useRecipientActions({+ issueId,+ agents: triggerPreview.agents,+ allowSteer: true,+ hasAttachments,+ steerByDefault,+ resetKey: `${issueId}:${parentId}`,+ });+ const stopRunsBeforeSend = useStopRunsBeforeSend(issueId);// Readonly-first: static shell until intent; an unsent draft mounts the// real editor immediately (see CommentInput). This is also what keeps the@@ -124,27 +146,6 @@ function ReplyInput({};}, [draftKey, setDraft]);- useEffect(() => {- setSuppressedAgentIds(new Set());- }, [issueId, parentId]);-- 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;- });- }, []);-// Await-then-render send (see CommentInput): the shared hook keeps the text,// locks + spins, and clears only once the server accepts it.// Stale-submit guard — see CommentInput.@@ -175,8 +176,13 @@ function ReplyInput({// to pull the eye elsewhere. `containerRef` keeps this from stealing focus// if the user moved to another composer while the reply was in flight.afterAccepted: () => (editorScrubbedRef.current ? "refocus" : "none"),- onSubmit: (content) => {+ onSubmit: async (content) => {editorScrubbedRef.current = false;+ const { suppressAgentIds, steerTaskIds } = routing;+ // A preview still catching up with an edited @mention can name a+ // recipient this comment no longer addresses: never stop a run on it.+ const restartTaskIds = triggerPreview.isCurrent ? routing.restartTaskIds : [];+ if (!(await stopRunsBeforeSend(restartTaskIds))) return false;if (draftKey) {// Flush pending debounce before snapshotting — see CommentInput.const pending = editorRef.current?.flushPendingUpdate?.();@@ -189,13 +195,11 @@ 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);return onSubmit(content,activeIds.length > 0 ? activeIds : undefined,suppressAgentIds.length > 0 ? suppressAgentIds : undefined,+ steerTaskIds.length > 0 ? steerTaskIds : undefined,).then((commentId) => {acceptedCommentIdRef.current = typeof commentId === "string" ? commentId : null;return !!commentId;@@ -218,7 +222,7 @@ function ReplyInput({editorRef.current?.clearContent();setContent("");setIsEmpty(true);- setSuppressedAgentIds(new Set());+ resetRecipients();editorScrubbedRef.current = true;if (acceptedCommentIdRef.current) onAccepted?.(acceptedCommentIdRef.current);},@@ -242,6 +246,7 @@ function ReplyInput({(!isEmpty || annotations.length > 0) && "pb-9",)}>+ {attachmentsBlockSteer && <SteerAttachmentNotice />}{draftKey && annotations.length > 0 && <>{targetMissing && <p role="alert" className="mb-2 text-caption text-destructive">{t(($) => $.reply.annotations.target_deleted)}</p>}<ReplyAnnotations draftKey={draftKey} annotations={annotations}@@ -305,12 +310,11 @@ function ReplyInput({)}<div className="absolute bottom-0 left-0 right-24 min-w-0"><CommentTriggerChips- agents={triggerPreview.agents}+ recipients={recipients}blocked={triggerPreview.blocked}hasAllMembersMention={triggerPreview.hasAllMembersMention}draftContent={composedContent}- suppressedAgentIds={suppressedAgentIds}- onToggle={toggleSuppressedAgent}+ onActionChange={setAction}/></div><div className="absolute bottom-0 right-0 flex items-center gap-1">@@ -319,7 +323,17 @@ function ReplyInput({multipleonSelect={(file) => lazy.uploadOrQueue([file])}/>- <SubmitButton+ {routing.restartTaskIds.length > 0 ? (+ <Button+ size="sm"+ variant="destructive"+ className="rounded-full"+ onClick={submit}+ disabled={!canSend || submitting || gate.uploading}+ >+ {t(($) => $.comment.restart_send)}+ </Button>+ ) : <SubmitButtononClick={submit}disabled={!canSend}loading={submitting}@@ -334,7 +348,7 @@ function ReplyInput({ariaLabel={gate.uploading? tEditor(($) => $.upload.in_progress): t(($) => $.comment.send_tooltip)}- />+ />}</div>{isDragOver && <FileDropOverlay />}</div>diff --git a/packages/views/issues/components/steer-attachment-notice.tsx b/packages/views/issues/components/steer-attachment-notice.tsxnew file mode 100644index 0000000000..fe5481e6db--- /dev/null+++ b/packages/views/issues/components/steer-attachment-notice.tsx@@ -0,0 +1,15 @@+"use client";++import { Info } from "lucide-react";+import { useT } from "../../i18n";++/** Why a message with files starts after the run instead of joining it. */+export function SteerAttachmentNotice() {+ const { t } = useT("issues");+ return (+ <p role="status" className="mb-2 flex items-start gap-1.5 rounded-md bg-muted px-2 py-1.5 text-caption text-muted-foreground">+ <Info aria-hidden className="mt-px size-3.5 shrink-0" />+ <span>{t(($) => $.comment.steer_attachment_notice)}</span>+ </p>+ );+}diff --git a/packages/views/issues/components/steer-receipts.test.tsx b/packages/views/issues/components/steer-receipts.test.tsxnew file mode 100644index 0000000000..19111dc946--- /dev/null+++ b/packages/views/issues/components/steer-receipts.test.tsx@@ -0,0 +1,127 @@+import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, describe, expect, it, vi } from "vitest";+import { api } from "@multica/core/api";+import { issueKeys } from "@multica/core/issues/queries";+import type { AgentTask, Comment, TimelineEntry } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { formatAgentNames, SteerBadge, SteerReceipts } from "./steer-receipts";++vi.mock("@multica/core/api", () => ({ api: {+ retryTaskSupplement: vi.fn(), createComment: vi.fn(), listTasksByIssue: vi.fn(),+ previewCommentTriggers: vi.fn(),+} }));++function recipients(...ids: string[]) {+ return { agents: ids.map((id) => ({ id, name: id, source: "mention_agent", reason: "" })) };+}+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace" }));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: (_type: string, id: string) => (id === "orion" ? "Orion" : "Lambda") }),+}));++const turn = "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc";++function task(overrides: Partial<AgentTask> = {}): AgentTask {+ return { id: turn, agent_id: "lambda", runtime_id: "runtime", issue_id: "issue", status: "running", priority: 0,+ created_at: "2026-09-07T00:00:00Z", started_at: "2026-09-07T00:00:00Z", dispatched_at: null,+ completed_at: null, result: null, error: null, ...overrides };+}++function entry(overrides: Partial<TimelineEntry> = {}): TimelineEntry {+ return { id: "steer", type: "comment", actor_type: "member", actor_id: "user", content: "Only fix web.",+ parent_id: "thread", created_at: "2026-09-07T00:00:10Z", ...overrides };+}++function render(node: React.ReactNode, tasks: AgentTask[] = [task()]) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ client.setQueryData(issueKeys.tasks("issue"), tasks);+ renderWithI18n(<QueryClientProvider client={client}>{node}</QueryClientProvider>);+ return client;+}++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("SteerReceipts", () => {+ it("renders nothing, and observes nothing, for a comment that steered no turn", () => {+ const client = new QueryClient();+ renderWithI18n(<QueryClientProvider client={client}>+ <SteerReceipts issueId="issue" entry={entry()} />+ <SteerBadge issueId="issue" entry={entry()} />+ </QueryClientProvider>);+ expect(client.getQueryCache().getAll()).toHaveLength(0);+ expect(document.body).toHaveTextContent("");+ });++ it("follows one receipt per steered turn, naming each agent", () => {+ const other = { ...task(), id: "other-turn", agent_id: "orion" };+ render(<>+ <SteerBadge issueId="issue" entry={entry({ supplements: [+ { task_id: turn, agent_id: "lambda", status: "pending" },+ { task_id: "other-turn", agent_id: "orion", status: "delivered", delivered_at: "2026-09-07T00:00:12Z" },+ ] })} />+ <SteerReceipts issueId="issue" entry={entry({ supplements: [+ { task_id: turn, agent_id: "lambda", status: "pending" },+ { task_id: "other-turn", agent_id: "orion", status: "delivered", delivered_at: "2026-09-07T00:00:12Z" },+ ] })} />+ </>, [task(), other]);+ expect(screen.getByText("Added to Lambda and Orion's run")).toBeInTheDocument();+ expect(screen.getByRole("status")).toHaveTextContent("Waiting for Lambda to read it");+ expect(screen.getByText("Read by Orion")).toBeInTheDocument();+ });++ it("settles a pending receipt when its run ends first and offers a new run instead", async () => {+ vi.mocked(api.createComment).mockResolvedValue({ id: "resent" } as Comment);+ vi.mocked(api.previewCommentTriggers).mockResolvedValue(recipients("lambda"));+ const client = render(<SteerReceipts issueId="issue" entry={entry({+ supplement_task_id: turn, supplement_status: "pending",+ })} />);+ expect(screen.getByRole("status")).toHaveTextContent("Waiting for Lambda to read it");+ act(() => client.setQueryData(issueKeys.tasks("issue"), [task({ status: "completed" })]));+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Lambda didn't get it · the run ended before delivery"));+ expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Send as a new run" }));+ await waitFor(() => expect(api.createComment).toHaveBeenCalledWith(+ "issue", "Only fix web.", undefined, "thread", undefined, undefined, undefined,+ ));+ await waitFor(() => expect(screen.queryByRole("button", { name: "Send as a new run" })).not.toBeInTheDocument());+ });++ it("resends a failed receipt only to its own agent", async () => {+ vi.mocked(api.createComment).mockResolvedValue({ id: "resent" } as Comment);+ vi.mocked(api.previewCommentTriggers).mockResolvedValue(recipients("lambda", "orion"));+ render(<SteerReceipts issueId="issue" entry={entry({+ content: "[@Lambda](mention://agent/lambda) fix web; [@Orion](mention://agent/orion) check desktop",+ supplements: [+ { task_id: turn, agent_id: "lambda", status: "failed", failure_reason: "turn_ended" },+ { task_id: "other-turn", agent_id: "orion", status: "delivered" },+ ],+ })} />, [task({ status: "completed" }), task({ id: "other-turn", agent_id: "orion", status: "completed" })]);+ fireEvent.click(screen.getByRole("button", { name: "Send as a new run" }));+ await waitFor(() => expect(api.createComment).toHaveBeenCalled());+ const suppressed = vi.mocked(api.createComment).mock.calls[0]![5];+ expect(suppressed).toEqual(["orion"]);+ });++ it("retries a stable delivery failure into the same running turn", async () => {+ vi.mocked(api.retryTaskSupplement).mockResolvedValue();+ render(<SteerReceipts issueId="issue" entry={entry({ supplements: [+ { task_id: turn, agent_id: "lambda", status: "failed", failure_reason: "provider_rejected" },+ ] })} />);+ expect(screen.getByRole("alert")).toHaveTextContent("Lambda didn't get it · the agent rejected the message");+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ await waitFor(() => expect(api.retryTaskSupplement).toHaveBeenCalledWith("issue", turn, "steer"));+ });+});++describe("formatAgentNames", () => {+ it("spaces Latin names from the Chinese joiner but not from the enumeration comma", () => {+ expect(formatAgentNames("zh-Hans", ["Lambda", "Orion"])).toBe("Lambda 和 Orion");+ expect(formatAgentNames("zh-Hans", ["Lambda", "Orion", "Kappa"])).toBe("Lambda、Orion 和 Kappa");+ expect(formatAgentNames("zh-Hans", ["小助手", "Orion"])).toBe("小助手和 Orion");+ expect(formatAgentNames("en", ["Lambda", "Orion"])).toBe("Lambda and Orion");+ });+});diff --git a/packages/views/issues/components/steer-receipts.tsx b/packages/views/issues/components/steer-receipts.tsxnew file mode 100644index 0000000000..2565c5e25a--- /dev/null+++ b/packages/views/issues/components/steer-receipts.tsx@@ -0,0 +1,183 @@+"use client";++import { useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { AlertCircle, Check, CornerDownRight, Loader2, RotateCcw } from "lucide-react";+import { toast } from "sonner";+import { useCreateComment, useRetryTaskSupplement } from "@multica/core/issues/mutations";+import { api } from "@multica/core/api";+import { issueKeys, issueTasksOptions } from "@multica/core/issues/queries";+import { commentSupplementReceipts, isSupplementInFlight } from "@multica/core/issues/run-steering";+import type { AgentTask, CommentSupplementReceipt, TimelineEntry } from "@multica/core/types";+import { useActorName } from "@multica/core/workspace/hooks";+import { Button } from "@multica/ui/components/ui/button";+import { useLocale, useT } from "../../i18n";++const TERMINAL = new Set<AgentTask["status"]>(["completed", "failed", "cancelled"]);++function useReceiptAgentName(issueId: string, receipt: CommentSupplementReceipt) {+ const { getActorName } = useActorName();+ // Servers that predate multi-run receipts omit the agent; the run knows it.+ const { data: task } = useQuery({+ ...issueTasksOptions(issueId),+ enabled: !!issueId,+ select: (tasks) => tasks.find((candidate) => candidate.id === receipt.task_id),+ });+ const agentId = receipt.agent_id || task?.agent_id;+ return { name: agentId ? getActorName("agent", agentId) : "", task };+}++const HAN = /\p{Script=Han}/u;++/**+ * Agent names joined for the badge. Chinese copy spaces a Latin name from the+ * Chinese joiner ("Lambda 和 Orion"), which Intl.ListFormat does not; the+ * enumeration comma stays unspaced.+ */+export function formatAgentNames(locale: string, names: string[]): string {+ const parts = new Intl.ListFormat(locale, { type: "conjunction" }).formatToParts(names);+ if (!locale.startsWith("zh")) return parts.map((part) => part.value).join("");+ return parts.map((part, i) => {+ if (part.type !== "literal" || !HAN.test(part.value)) return part.value;+ const before = parts[i - 1]?.value.slice(-1) ?? "";+ const after = parts[i + 1]?.value.charAt(0) ?? "";+ return `${before && !HAN.test(before) ? " " : ""}${part.value}${after && !HAN.test(after) ? " " : ""}`;+ }).join("");+}++/** "Added to Lambda's run": marks a message that steered a running turn. */+export function SteerBadge({ issueId, entry }: { issueId: string; entry: TimelineEntry }) {+ const { t } = useT("issues");+ const locale = useLocale();+ const receipts = commentSupplementReceipts(entry);+ const { getActorName } = useActorName();+ if (receipts.length === 0) return null;+ // Every receipt from a current server names its agent; the legacy single+ // receipt resolves the name from its run instead.+ const names = receipts.every((receipt) => receipt.agent_id)+ ? formatAgentNames(locale, receipts.map((receipt) => getActorName("agent", receipt.agent_id!)))+ : null;+ return (+ <span className="inline-flex min-w-0 items-center gap-1 text-caption text-muted-foreground">+ <CornerDownRight aria-hidden className="size-3 shrink-0" />+ <span className="truncate">+ {names !== null+ ? t(($) => $.inline_run.steer_badge, { names })+ : <BadgeLegacyName issueId={issueId} receipt={receipts[0]!} />}+ </span>+ </span>+ );+}++function BadgeLegacyName({ issueId, receipt }: { issueId: string; receipt: CommentSupplementReceipt }) {+ const { t } = useT("issues");+ const { name } = useReceiptAgentName(issueId, receipt);+ return <>{t(($) => $.inline_run.steer_badge, { names: name })}</>;+}++/** One line per running turn the message steered, following its delivery. */+export function SteerReceipts({ issueId, entry }: { issueId: string; entry: TimelineEntry }) {+ const receipts = commentSupplementReceipts(entry);+ if (receipts.length === 0) return null;+ return (+ <div className="mt-1.5 flex flex-col gap-1">+ {receipts.map((receipt) => (+ <SteerReceipt key={receipt.task_id} issueId={issueId} entry={entry} receipt={receipt} />+ ))}+ </div>+ );+}++function SteerReceipt({ issueId, entry, receipt }: {+ issueId: string;+ entry: TimelineEntry;+ receipt: CommentSupplementReceipt;+}) {+ const { t } = useT("issues");+ const { name, task } = useReceiptAgentName(issueId, receipt);+ const retry = useRetryTaskSupplement(issueId);+ const resend = useCreateComment(issueId);+ const [resent, setResent] = useState(false);+ const terminal = !!task && TERMINAL.has(task.status);+ const inFlight = isSupplementInFlight(receipt);+ const queryClient = useQueryClient();+ const [resending, setResending] = useState(false);+ // Only this receipt's agent missed the message: the same text as a new+ // comment must not reach anyone it already served, or who chose to skip it.+ const resendToAgent = async () => {+ const content = entry.content ?? "";+ const parentId = entry.parent_id ?? undefined;+ const agentId = receipt.agent_id || task?.agent_id;+ setResending(true);+ try {+ const preview = await queryClient.fetchQuery({+ queryKey: [...issueKeys.commentTriggerPreview(issueId), parentId ?? "", "", `resend:${entry.id}`],+ queryFn: () => api.previewCommentTriggers(issueId, content, parentId),+ staleTime: 0,+ });+ if (!agentId || !preview.agents.some((agent) => agent.id === agentId)) throw new Error("recipient unavailable");+ const others = preview.agents.filter((agent) => agent.id !== agentId).map((agent) => agent.id);+ await resend.mutateAsync({ content, parentId, suppressAgentIds: others.length > 0 ? others : undefined });+ setResent(true);+ } catch {+ toast.error(t(($) => $.inline_run.steer_resend_failed));+ } finally {+ setResending(false);+ }+ };++ if (inFlight && !terminal) {+ return (+ <p role="status" className="flex items-center gap-1.5 text-caption text-muted-foreground">+ <Loader2 aria-hidden className="size-3.5 shrink-0 motion-safe:animate-spin" />+ <span>{t(($) => $.inline_run.steer_waiting, { name })}</span>+ </p>+ );+ }+ if (receipt.status === "delivered") {+ return (+ <p className="flex items-center gap-1.5 text-caption text-muted-foreground">+ <Check aria-hidden className="size-3.5 shrink-0 text-success" />+ <span>{t(($) => $.inline_run.steer_read, { name })}</span>+ </p>+ );+ }++ // A run that ended before delivery settles the receipt as turn_ended; the+ // task status can show it before the receipt update arrives.+ const reasonCode = inFlight ? "turn_ended" : receipt.failure_reason;+ const reason = reasonCode === "turn_ended"+ ? t(($) => $.inline_run.supplement_failure_turn_ended)+ : reasonCode === "turn_not_started"+ ? t(($) => $.inline_run.supplement_failure_turn_not_started)+ : reasonCode === "provider_rejected"+ ? t(($) => $.inline_run.supplement_failure_provider_rejected)+ : reasonCode === "timeout"+ ? t(($) => $.inline_run.supplement_failure_timeout)+ : t(($) => $.inline_run.supplement_failure_unknown);+ const canRetry = !terminal && reasonCode !== "turn_ended";+ return (+ <div role="alert" className="flex flex-wrap items-center gap-x-2 gap-y-1 text-caption text-destructive">+ <span className="inline-flex items-center gap-1.5">+ <AlertCircle aria-hidden className="size-3.5 shrink-0" />+ {t(($) => $.inline_run.steer_not_received, { name, reason })}+ </span>+ {canRetry && (+ <Button type="button" size="xs" variant="outline" className="text-foreground" disabled={retry.isPending}+ onClick={() => retry.mutate({ taskId: receipt.task_id, commentId: entry.id }, {+ onError: () => toast.error(t(($) => $.inline_run.supplement_retry_failed)),+ })}>+ {retry.isPending ? <Loader2 className="size-3 motion-safe:animate-spin" /> : <RotateCcw className="size-3" />}+ {t(($) => $.inline_run.supplement_retry)}+ </Button>+ )}+ {!resent && (+ <Button type="button" size="xs" variant="outline" className="text-foreground" disabled={resending || resend.isPending}+ onClick={() => void resendToAgent()}>+ {resending || resend.isPending ? <Loader2 className="size-3 motion-safe:animate-spin" /> : <CornerDownRight className="size-3" />}+ {t(($) => $.inline_run.steer_resend)}+ </Button>+ )}+ </div>+ );+}diff --git a/packages/views/issues/components/use-stop-runs-before-send.ts b/packages/views/issues/components/use-stop-runs-before-send.tsnew file mode 100644index 0000000000..a70d63462f--- /dev/null+++ b/packages/views/issues/components/use-stop-runs-before-send.ts@@ -0,0 +1,27 @@+"use client";++import { useCallback } from "react";+import { toast } from "sonner";+import { useCancelIssueRun } from "@multica/core/issues/mutations";+import { useT } from "../../i18n";++/**+ * "Stop and start over": the chosen turns are stopped first, so the message+ * that follows starts a fresh run instead of waiting behind them. Resolves+ * false (and keeps the draft) when a turn could not be stopped.+ */+export function useStopRunsBeforeSend(issueId: string) {+ const { t } = useT("issues");+ const cancel = useCancelIssueRun(issueId);+ const { mutateAsync } = cancel;+ return useCallback(async (taskIds: string[]): Promise<boolean> => {+ if (taskIds.length === 0) return true;+ try {+ await Promise.all(taskIds.map((taskId) => mutateAsync(taskId)));+ return true;+ } catch {+ toast.error(t(($) => $.comment.restart_failed));+ return false;+ }+ }, [mutateAsync, t]);+}diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.test.ts b/packages/views/issues/hooks/use-comment-trigger-preview.test.tsindex 75cd7e8e5a..165f800815 100644--- a/packages/views/issues/hooks/use-comment-trigger-preview.test.ts+++ b/packages/views/issues/hooks/use-comment-trigger-preview.test.ts@@ -278,6 +278,7 @@ describe("useCommentTriggerPreview", () => {agents: [],blocked: [],hasAllMembersMention: false,+ isCurrent: true,});expect(previewCommentTriggers).not.toHaveBeenCalled();});@@ -297,6 +298,7 @@ describe("useCommentTriggerPreview", () => {agents: [],blocked: [],hasAllMembersMention: true,+ isCurrent: true,});expect(previewCommentTriggers).not.toHaveBeenCalled();});diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.ts b/packages/views/issues/hooks/use-comment-trigger-preview.tsindex 94110a7788..380885fc34 100644--- a/packages/views/issues/hooks/use-comment-trigger-preview.ts+++ b/packages/views/issues/hooks/use-comment-trigger-preview.ts@@ -19,6 +19,12 @@ export interface UseCommentTriggerPreviewResult {// by itself. This is static mention semantics, not a delivery guarantee:// edits do not notify, and a new comment may have no eligible recipients.hasAllMembersMention: boolean;+ /**+ * Whether `agents` answers the draft's current mentions. While a changed+ * @mention is still debouncing or loading, the previous answer is shown;+ * nothing destructive may act on it.+ */+ isCurrent: boolean;}export function isNoteCommentDraft(content: string): boolean {@@ -122,12 +128,13 @@ export function useCommentTriggerPreview({// 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: [], blocked: [], hasAllMembersMention };+ return { agents: [], blocked: [], hasAllMembersMention, isCurrent: signature === "empty" };}return {agents: previewQuery.data?.agents ?? [],blocked: previewQuery.data?.blocked ?? [],hasAllMembersMention,+ isCurrent: signature === debouncedSignature && previewQuery.isSuccess && !previewQuery.isPlaceholderData,};}diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.tsindex 0fbef1ab23..edfa7cd8ef 100644--- a/packages/views/issues/hooks/use-issue-timeline.ts+++ b/packages/views/issues/hooks/use-issue-timeline.ts@@ -65,6 +65,7 @@ function commentToTimelineEntry(c: Comment): TimelineEntry {resolved_by_type: c.resolved_by_type,resolved_by_id: c.resolved_by_id,source_task_id: c.source_task_id,+ supplements: c.supplements,supplement_task_id: c.supplement_task_id,supplement_status: c.supplement_status,supplement_failure_reason: c.supplement_failure_reason,@@ -354,10 +355,10 @@ export function useIssueTimeline(issueId: string, userId?: string) {// on success — so a slow send no longer leaves the box full next to an// already-posted comment, and a failed send keeps the draft.const submitComment = useCallback(- async (content: string, attachmentIds?: string[], suppressAgentIds?: string[]): Promise<string | false> => {+ async (content: string, attachmentIds?: string[], suppressAgentIds?: string[], steerTaskIds?: string[]): Promise<string | false> => {if (!content.trim() || !userId) return false;try {- const comment = await createComment({ content, attachmentIds, suppressAgentIds });+ const comment = await createComment({ content, attachmentIds, suppressAgentIds, steerTaskIds });warnUnhandledTriggers(comment?.trigger_outcomes, comment?.content);return comment.id;} catch (err) {@@ -373,7 +374,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {);const submitReply = useCallback(- async (parentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[]): Promise<string | false> => {+ async (parentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[], steerTaskIds?: string[]): Promise<string | false> => {if (!content.trim() || !userId) return false;try {const comment = await createComment({@@ -382,6 +383,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {parentId,attachmentIds,suppressAgentIds,+ steerTaskIds,});warnUnhandledTriggers(comment?.trigger_outcomes, comment?.content);return comment.id;diff --git a/packages/views/issues/hooks/use-recipient-actions.ts b/packages/views/issues/hooks/use-recipient-actions.tsnew file mode 100644index 0000000000..1aef02514f--- /dev/null+++ b/packages/views/issues/hooks/use-recipient-actions.ts@@ -0,0 +1,121 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { issueTasksOptions } from "@multica/core/issues/queries";+import { useCommentComposerStore } from "@multica/core/issues/stores";+import {+ agentRunState,+ recipientActions,+ recipientRouting,+ resolveRecipientAction,+ type AgentRunState,+ type RecipientAction,+ type RecipientRouting,+} from "@multica/core/issues/run-steering";+import type { AgentTask, CommentTriggerPreviewAgent } from "@multica/core/types";++const NO_TASKS: AgentTask[] = [];+const ACTIVE_STATUSES = new Set<AgentTask["status"]>(["queued", "deferred", "dispatched", "waiting_local_directory", "running"]);+const NO_CHOICES: Record<string, RecipientAction> = {};++export interface RecipientEntry {+ agent: CommentTriggerPreviewAgent;+ state: AgentRunState;+ action: RecipientAction;+ actions: RecipientAction[];+}++/**+ * The composer's per-recipient choice. The preview decides WHO receives the+ * message (existing trigger rules); each recipient's live run on this issue+ * decides what can happen to it: steer a running turn, fold into a queued+ * run, or start a new one.+ */+export function useRecipientActions({+ issueId,+ agents,+ allowSteer,+ hasAttachments = false,+ steerByDefault: steerHere,+ resetKey,+}: {+ issueId: string;+ agents: CommentTriggerPreviewAgent[];+ /** False for edits: an edit neither steers nor stops a run. */+ allowSteer: boolean;+ hasAttachments?: boolean;+ /** Whether a running turn takes the message by default from this composer. */+ steerByDefault: (task: AgentTask) => boolean;+ /** Choices reset when the composer's context changes. */+ resetKey: string;+}) {+ // Every comment row mounts this hook for its edit composer, so it reads only+ // the active runs of its own recipients: with none (the usual idle row) it+ // neither fetches nor re-renders on unrelated task events.+ const agentKey = agents.map((agent) => agent.id).join(",");+ const selectActive = useCallback((all: AgentTask[]) => {+ const ids = new Set(agentKey.split(","));+ return all.filter((task) => ids.has(task.agent_id) && ACTIVE_STATUSES.has(task.status));+ }, [agentKey]);+ const { data: tasks = NO_TASKS } = useQuery({+ ...issueTasksOptions(issueId),+ enabled: !!issueId && agents.length > 0,+ select: selectActive,+ });+ // The personal default can turn steering off for every composer; it only+ // decides what happens without a per-message choice.+ const steerWithoutChoice = useCommentComposerStore((s) => s.runningAgentReply !== "after_run");+ const steerByDefault = useCallback(+ (task: AgentTask) => steerWithoutChoice && steerHere(task),+ [steerWithoutChoice, steerHere],+ );+ const [chosen, setChosen] = useState<Record<string, RecipientAction>>(NO_CHOICES);++ useEffect(() => {+ setChosen(NO_CHOICES);+ }, [resetKey]);++ // Forget choices for agents that are no longer recipients (an @mention removed).+ useEffect(() => {+ const visible = new Set(agents.map((agent) => agent.id));+ setChosen((prev) => {+ const next = Object.fromEntries(Object.entries(prev).filter(([id]) => visible.has(id)));+ return Object.keys(next).length === Object.keys(prev).length ? prev : next;+ });+ }, [agents]);++ const recipients = useMemo<RecipientEntry[]>(() => agents.map((agent) => {+ const state = agentRunState(tasks, agent.id);+ const opts = {+ canSteer: allowSteer && !hasAttachments,+ canRestart: allowSteer,+ steerByDefault: state.kind === "running" && steerByDefault(state.task),+ };+ return {+ agent,+ state,+ action: resolveRecipientAction(state, chosen[agent.id], opts),+ actions: recipientActions(state, opts),+ };+ }), [agents, tasks, chosen, allowSteer, hasAttachments, steerByDefault]);++ // A recipient would take this in its running turn, but files cannot go there.+ const attachmentsBlockSteer = allowSteer && hasAttachments && recipients.some((r) =>+ r.state.kind === "running" && r.state.steerable+ && (chosen[r.agent.id] === "steer" || (!chosen[r.agent.id] && steerByDefault(r.state.task))));++ const setAction = useCallback((agentId: string, action: RecipientAction) => {+ setChosen((prev) => (prev[agentId] === action ? prev : { ...prev, [agentId]: action }));+ }, []);++ const reset = useCallback(() => {+ setChosen(NO_CHOICES);+ }, []);++ const routing = useMemo<RecipientRouting>(() => recipientRouting(recipients.map((r) => ({+ agentId: r.agent.id, action: r.action, state: r.state,+ }))), [recipients]);++ return { recipients, attachmentsBlockSteer, routing, setAction, reset };+}diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 0bd4260829..2f2965eda1 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -20,26 +20,21 @@"message": "Agent message","error": "Error","waiting_result": "Waiting for the tool result...",- "supplement_action": "Add message",- "supplement_placeholder": "Add guidance for this running turn",- "supplement_send": "Send",- "supplement_notice": "The agent keeps working on the original goal.",- "supplement_unsupported": "This run did not negotiate support for additional messages.",- "supplement_forbidden": "You do not have permission to run this agent.",- "supplement_ended": "This run has ended. Your text is preserved; start another run explicitly to send it.",- "supplement_failed": "Could not send the message. Your text is preserved.",- "supplement_waiting_delivery": "Waiting for delivery",- "supplement_not_delivered": "Not delivered · {{reason}}","supplement_failure_turn_ended": "the run ended before delivery","supplement_failure_turn_not_started": "the agent was not ready","supplement_failure_provider_rejected": "the agent rejected the message","supplement_failure_timeout": "delivery timed out","supplement_failure_unknown": "unknown reason",- "supplement_move_to_new": "Move to new message",- "supplement_discard": "Discard",- "supplement_moved": "Moved to the new message box.","supplement_retry": "Retry",- "supplement_retry_failed": "Could not retry delivery."+ "supplement_retry_failed": "Could not retry delivery.",+ "steer_badge": "Added to {{names}}'s run",+ "steer_waiting": "Waiting for {{name}} to read it",+ "steer_read": "Read by {{name}}",+ "steer_not_received": "{{name}} didn't get it · {{reason}}",+ "steer_resend": "Send as a new run",+ "steer_resend_failed": "Couldn't send it as a new run.",+ "steer_step": "{{name}} added",+ "steer_step_read": "Read"},"status_catalog_error": {"title": "Couldn't load the status list",@@ -591,9 +586,9 @@"trigger_starts_now": "Starts right away.","trigger_starts_when_online": "Offline now — starts once online.","trigger_click_to_skip": "Click to skip this time.",- "trigger_click_to_manage": "Click to choose who runs this time.",+ "trigger_click_to_manage": "Click to choose what each agent does with this message.","trigger_click_to_restore": "Won't start this time. Click to restore.",- "trigger_preview_title": "Will start when sent",+ "trigger_preview_title": "Recipients","trigger_chip_aria": "{{name}} trigger: {{state}}","resolve": {"resolve_thread_action": "Resolve thread",@@ -611,7 +606,23 @@"bar_authors_more_other": "{{names}} and {{count}} others","resolve_failed": "Failed to resolve thread","unresolve_failed": "Failed to unresolve thread"- }+ },+ "recipient_steer": "Add to current run",+ "recipient_steer_desc": "{{name}} reads it after the current step and keeps working on the original task. Text only.",+ "recipient_after_run": "Start after this run",+ "recipient_after_run_desc": "Doesn't interrupt the current run; it's handled in a new run afterwards.",+ "recipient_restart": "Stop and start over",+ "recipient_restart_desc": "Stops the current run now and starts over from this message.",+ "recipient_join": "Include when it starts",+ "recipient_join_desc": "{{name}}'s run is still queued and will handle this message when it starts.",+ "recipient_state_running": "Running",+ "recipient_state_starting": "Starting",+ "recipient_state_queued": "Queued",+ "recipient_count_one": "{{count}} agent will receive this",+ "recipient_count_other": "{{count}} agents will receive this",+ "steer_attachment_notice": "Only text can join a running run, so a message with files is handled after it.",+ "restart_send": "Stop and send",+ "restart_failed": "Couldn't stop the current run. Your message wasn't sent."},"reply": {"placeholder": "Leave a reply...",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 866c25f5b4..bf50be59eb 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -168,6 +168,12 @@"sticky_comment_bar": {"title": "Pin comment bar to bottom"},+ "running_agent_reply": {+ "title": "When replying to a running agent",+ "steer": "Add to current run",+ "after_run": "Start after this run",+ "hint": "Sets the default only. You can still change it for any message before sending."+ },"issue_title": "Issue creation","comments_title": "Comments","device_hint": "Saved on this device.",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 6a6f687d4d..5e8e95bd16 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -20,26 +20,21 @@"message": "Message de l'agent","error": "Erreur","waiting_result": "En attente du résultat de l'outil...",- "supplement_action": "Ajouter un message",- "supplement_placeholder": "Ajouter une consigne à cette exécution",- "supplement_send": "Envoyer",- "supplement_notice": "L'agent poursuit l'objectif initial.",- "supplement_unsupported": "Cette exécution ne prend pas en charge les messages supplémentaires.",- "supplement_forbidden": "Vous n'êtes pas autorisé à exécuter cet agent.",- "supplement_ended": "Cette exécution est terminée. Votre texte est conservé ; lancez explicitement une autre exécution pour l'envoyer.",- "supplement_failed": "Impossible d'envoyer le message. Votre texte est conservé.",- "supplement_waiting_delivery": "En attente de livraison",- "supplement_not_delivered": "Non livré · {{reason}}","supplement_failure_turn_ended": "l'exécution s'est terminée avant la livraison","supplement_failure_turn_not_started": "l’agent n’était pas prêt","supplement_failure_provider_rejected": "l’agent a refusé le message","supplement_failure_timeout": "la livraison a expiré","supplement_failure_unknown": "raison inconnue",- "supplement_move_to_new": "Déplacer vers un nouveau message",- "supplement_discard": "Abandonner",- "supplement_moved": "Déplacé vers la zone de nouveau message.","supplement_retry": "Réessayer",- "supplement_retry_failed": "Impossible de réessayer la livraison."+ "supplement_retry_failed": "Impossible de réessayer la livraison.",+ "steer_badge": "Ajouté à l'exécution de {{names}}",+ "steer_waiting": "En attente de lecture par {{name}}",+ "steer_read": "Lu par {{name}}",+ "steer_not_received": "{{name}} ne l'a pas reçu · {{reason}}",+ "steer_resend": "Envoyer comme nouvelle exécution",+ "steer_resend_failed": "Impossible de l'envoyer comme nouvelle exécution.",+ "steer_step": "{{name}} a ajouté",+ "steer_step_read": "Lu"},"status_catalog_error": {"title": "Impossible de charger la liste des états",@@ -591,9 +586,9 @@"trigger_starts_now": "Démarre immédiatement.","trigger_starts_when_online": "Hors ligne — démarrera dès la reconnexion.","trigger_click_to_skip": "Cliquez pour ignorer cette fois.",- "trigger_click_to_manage": "Cliquez pour choisir qui s'exécute cette fois.",+ "trigger_click_to_manage": "Cliquez pour choisir ce que chaque agent fait de ce message.","trigger_click_to_restore": "Ne démarrera pas cette fois. Cliquez pour rétablir.",- "trigger_preview_title": "Démarrera à l'envoi",+ "trigger_preview_title": "Destinataires","trigger_chip_aria": "Déclenchement de {{name}} : {{state}}","resolve": {"resolve_thread_action": "Résoudre le fil",@@ -611,7 +606,23 @@"bar_authors_more_other": "{{names}} et {{count}} autres","resolve_failed": "Échec de la résolution du fil","unresolve_failed": "Échec de la réouverture du fil"- }+ },+ "recipient_steer": "Ajouter à l'exécution en cours",+ "recipient_steer_desc": "{{name}} le lit après l'étape en cours et poursuit la tâche d'origine. Texte uniquement.",+ "recipient_after_run": "Démarrer après cette exécution",+ "recipient_after_run_desc": "N'interrompt pas l'exécution en cours ; traité ensuite dans une nouvelle exécution.",+ "recipient_restart": "Arrêter et recommencer",+ "recipient_restart_desc": "Arrête l'exécution en cours et recommence à partir de ce message.",+ "recipient_join": "Inclure au démarrage",+ "recipient_join_desc": "L'exécution de {{name}} est encore en file ; elle traitera ce message à son démarrage.",+ "recipient_state_running": "En cours",+ "recipient_state_starting": "Démarrage",+ "recipient_state_queued": "En file",+ "recipient_count_one": "{{count}} agent recevra ce message",+ "recipient_count_other": "{{count}} agents recevront ce message",+ "steer_attachment_notice": "Seul du texte peut rejoindre une exécution en cours : un message avec des fichiers sera traité après.",+ "restart_send": "Arrêter et envoyer",+ "restart_failed": "Impossible d'arrêter l'exécution en cours. Votre message n'a pas été envoyé."},"reply": {"placeholder": "Laisser une réponse...",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 80bd0c75cb..7e06ad84b1 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -168,6 +168,12 @@"sticky_comment_bar": {"title": "Épingler la barre de commentaire en bas"},+ "running_agent_reply": {+ "title": "En répondant à un agent en cours d'exécution",+ "steer": "Ajouter à l'exécution en cours",+ "after_run": "Démarrer après cette exécution",+ "hint": "Définit seulement le choix par défaut. Vous pouvez le modifier pour chaque message avant l'envoi."+ },"issue_title": "Création de tâches","comments_title": "Commentaires","device_hint": "Enregistré sur cet appareil.",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex f3ed9e8eae..ac2796b90e 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -19,26 +19,21 @@"message": "エージェントのメッセージ","error": "エラー","waiting_result": "ツールの結果を待っています...",- "supplement_action": "メッセージを追加",- "supplement_placeholder": "この実行に追加の指示を入力",- "supplement_send": "送信",- "supplement_notice": "エージェントは元の目標を継続します。",- "supplement_unsupported": "この実行は追加メッセージに対応していません。",- "supplement_forbidden": "このエージェントを実行する権限がありません。",- "supplement_ended": "この実行は終了しました。入力は保持されています。送信するには明示的に別の実行を開始してください。",- "supplement_failed": "メッセージを送信できませんでした。入力は保持されています。",- "supplement_waiting_delivery": "配信待ち",- "supplement_not_delivered": "未配信 · {{reason}}","supplement_failure_turn_ended": "配信前に実行が終了しました","supplement_failure_turn_not_started": "エージェントの準備ができていませんでした","supplement_failure_provider_rejected": "エージェントがメッセージを拒否しました","supplement_failure_timeout": "配信がタイムアウトしました","supplement_failure_unknown": "原因不明",- "supplement_move_to_new": "新しいメッセージへ移動",- "supplement_discard": "破棄",- "supplement_moved": "新しいメッセージ入力欄へ移動しました。","supplement_retry": "再試行",- "supplement_retry_failed": "配信を再試行できませんでした。"+ "supplement_retry_failed": "配信を再試行できませんでした。",+ "steer_badge": "{{names}} の実行に追加",+ "steer_waiting": "{{name}} が読むのを待っています",+ "steer_read": "{{name}} が読みました",+ "steer_not_received": "{{name}} は受け取れませんでした · {{reason}}",+ "steer_resend": "新しい実行として送信",+ "steer_resend_failed": "新しい実行として送信できませんでした。",+ "steer_step": "{{name}} が追加",+ "steer_step_read": "既読"},"status_catalog_error": {"title": "ステータス一覧を読み込めませんでした",@@ -579,9 +574,9 @@"trigger_starts_now": "すぐに開始します。","trigger_starts_when_online": "オフライン中。オンラインになり次第開始します。","trigger_click_to_skip": "クリックで今回はスキップ。",- "trigger_click_to_manage": "クリックして今回実行する対象を選択。",+ "trigger_click_to_manage": "クリックして、エージェントごとにこのメッセージの扱いを選択。","trigger_click_to_restore": "今回は開始しません。クリックで元に戻せます。",- "trigger_preview_title": "送信後に開始する対象",+ "trigger_preview_title": "受け取るエージェント","trigger_chip_aria": "{{name}} のトリガー: {{state}}","resolve": {"resolve_thread_action": "スレッドを解決",@@ -596,7 +591,22 @@"bar_authors_more_other": "{{names}} 他 {{count}} 名","resolve_failed": "スレッドを解決できませんでした","unresolve_failed": "スレッドの解決を取り消せませんでした"- }+ },+ "recipient_steer": "現在の実行に追加",+ "recipient_steer_desc": "{{name}} は現在のステップの後に読み、元のタスクを続けます。テキストのみ。",+ "recipient_after_run": "この実行の後に開始",+ "recipient_after_run_desc": "現在の実行は止めず、終了後に新しい実行で扱います。",+ "recipient_restart": "停止してやり直す",+ "recipient_restart_desc": "現在の実行をすぐに停止し、このメッセージからやり直します。",+ "recipient_join": "開始時に一緒に処理",+ "recipient_join_desc": "{{name}} の実行はまだ待機中です。開始時にこのメッセージも一緒に処理します。",+ "recipient_state_running": "実行中",+ "recipient_state_starting": "起動中",+ "recipient_state_queued": "待機中",+ "recipient_count_other": "{{count}} 個のエージェントが受け取ります",+ "steer_attachment_notice": "実行中に追加できるのはテキストのみのため、ファイル付きのメッセージはこの実行の後に処理されます。",+ "restart_send": "停止して送信",+ "restart_failed": "現在の実行を停止できませんでした。メッセージは送信されていません。"},"reply": {"placeholder": "返信を残す...",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 49843162a0..fe9211c02a 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -168,6 +168,12 @@"sticky_comment_bar": {"title": "コメント欄を下部に固定"},+ "running_agent_reply": {+ "title": "実行中のエージェントに返信するとき",+ "steer": "現在の実行に追加",+ "after_run": "この実行の後に開始",+ "hint": "既定の動作だけを決めます。送信前にメッセージごとに変更できます。"+ },"issue_title": "タスク作成","comments_title": "コメント","device_hint": "このデバイスに保存されます。",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex a373cc74ee..db5d028bb1 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -19,26 +19,21 @@"message": "에이전트 메시지","error": "오류","waiting_result": "도구 결과를 기다리고 있습니다...",- "supplement_action": "메시지 추가",- "supplement_placeholder": "이 실행에 추가 지침 입력",- "supplement_send": "보내기",- "supplement_notice": "에이전트는 원래 목표를 계속 처리합니다.",- "supplement_unsupported": "이 실행은 추가 메시지를 지원하도록 협상되지 않았습니다.",- "supplement_forbidden": "이 에이전트를 실행할 권한이 없습니다.",- "supplement_ended": "이 실행은 종료되었습니다. 입력은 보존되며, 보내려면 새 실행을 명시적으로 시작하세요.",- "supplement_failed": "메시지를 보내지 못했습니다. 입력은 보존됩니다.",- "supplement_waiting_delivery": "전달 대기 중",- "supplement_not_delivered": "전달되지 않음 · {{reason}}","supplement_failure_turn_ended": "전달 전에 실행이 종료됨","supplement_failure_turn_not_started": "에이전트가 준비되지 않음","supplement_failure_provider_rejected": "에이전트가 메시지를 거부함","supplement_failure_timeout": "전달 시간 초과","supplement_failure_unknown": "알 수 없는 이유",- "supplement_move_to_new": "새 메시지로 이동",- "supplement_discard": "버리기",- "supplement_moved": "새 메시지 입력란으로 이동했습니다.","supplement_retry": "다시 시도",- "supplement_retry_failed": "전달을 다시 시도하지 못했습니다."+ "supplement_retry_failed": "전달을 다시 시도하지 못했습니다.",+ "steer_badge": "{{names}}의 실행에 추가",+ "steer_waiting": "{{name}}이(가) 읽기를 기다리는 중",+ "steer_read": "{{name}}이(가) 읽음",+ "steer_not_received": "{{name}}이(가) 받지 못함 · {{reason}}",+ "steer_resend": "새 실행으로 보내기",+ "steer_resend_failed": "새 실행으로 보내지 못했습니다.",+ "steer_step": "{{name}}이(가) 추가",+ "steer_step_read": "읽음"},"status_catalog_error": {"title": "상태 목록을 불러오지 못했습니다",@@ -579,9 +574,9 @@"trigger_starts_now": "바로 시작합니다.","trigger_starts_when_online": "현재 오프라인이며 온라인이 되면 시작합니다.","trigger_click_to_skip": "클릭하면 이번에는 건너뜁니다.",- "trigger_click_to_manage": "클릭하여 이번에 실행할 대상을 선택합니다.",+ "trigger_click_to_manage": "클릭하여 에이전트별로 이 메시지의 처리 방식을 선택합니다.","trigger_click_to_restore": "이번에는 시작하지 않습니다. 클릭하면 복원됩니다.",- "trigger_preview_title": "전송 후 시작할 대상",+ "trigger_preview_title": "받는 에이전트","trigger_chip_aria": "{{name}} 트리거: {{state}}","resolve": {"resolve_thread_action": "스레드 해결",@@ -596,7 +591,22 @@"bar_authors_more_other": "{{names}} 외 {{count}}명","resolve_failed": "스레드를 해결하지 못했습니다","unresolve_failed": "스레드 해결을 취소하지 못했습니다"- }+ },+ "recipient_steer": "현재 실행에 추가",+ "recipient_steer_desc": "{{name}}이(가) 현재 단계가 끝난 뒤 읽고 원래 작업을 계속합니다. 텍스트만 가능합니다.",+ "recipient_after_run": "이번 실행 후 시작",+ "recipient_after_run_desc": "현재 실행을 방해하지 않고, 끝난 뒤 새 실행에서 처리합니다.",+ "recipient_restart": "중지하고 다시 시작",+ "recipient_restart_desc": "현재 실행을 즉시 중지하고 이 메시지로 처음부터 다시 시작합니다.",+ "recipient_join": "시작할 때 함께 처리",+ "recipient_join_desc": "{{name}}의 실행이 아직 대기 중이며, 시작할 때 이 메시지도 함께 처리합니다.",+ "recipient_state_running": "실행 중",+ "recipient_state_starting": "시작 중",+ "recipient_state_queued": "대기 중",+ "recipient_count_other": "에이전트 {{count}}개가 받습니다",+ "steer_attachment_notice": "실행 중에는 텍스트만 추가할 수 있어, 파일이 있는 메시지는 이번 실행 후에 처리됩니다.",+ "restart_send": "중지하고 보내기",+ "restart_failed": "현재 실행을 중지하지 못했습니다. 메시지는 보내지 않았습니다."},"reply": {"placeholder": "답글 남기기...",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 9ef4e7882f..ffc28d6a87 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -168,6 +168,12 @@"sticky_comment_bar": {"title": "댓글 입력란을 하단에 고정"},+ "running_agent_reply": {+ "title": "실행 중인 에이전트에 답장할 때",+ "steer": "현재 실행에 추가",+ "after_run": "이번 실행 후 시작",+ "hint": "기본값만 정합니다. 보내기 전에 메시지마다 바꿀 수 있습니다."+ },"issue_title": "태스크 생성","comments_title": "댓글","device_hint": "현재 기기에 저장됩니다.",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex cc5b4cf8ef..d70e7a8bcb 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -19,26 +19,21 @@"message": "智能体消息","error": "错误","waiting_result": "等待工具返回结果...",- "supplement_action": "补充消息",- "supplement_placeholder": "为本次运行补充纯文字要求",- "supplement_send": "发送",- "supplement_notice": "智能体会继续处理原目标。",- "supplement_unsupported": "本次运行未协商支持补充消息。",- "supplement_forbidden": "你无权运行这个智能体。",- "supplement_ended": "本次运行已结束。输入已保留;如需发送,请显式另起一轮。",- "supplement_failed": "消息发送失败,输入已保留。",- "supplement_waiting_delivery": "等待送达",- "supplement_not_delivered": "未送达 · {{reason}}","supplement_failure_turn_ended": "送达前运行已结束","supplement_failure_turn_not_started": "智能体尚未就绪","supplement_failure_provider_rejected": "智能体拒绝了该消息","supplement_failure_timeout": "送达超时","supplement_failure_unknown": "原因未知",- "supplement_move_to_new": "移到新消息",- "supplement_discard": "丢弃",- "supplement_moved": "已移到新消息输入框。","supplement_retry": "重试",- "supplement_retry_failed": "无法重试送达。"+ "supplement_retry_failed": "无法重试送达。",+ "steer_badge": "插话给 {{names}}",+ "steer_waiting": "等待 {{name}} 读取",+ "steer_read": "{{name}} 已读取",+ "steer_not_received": "{{name}} 未收到 · {{reason}}",+ "steer_resend": "作为新一轮发送",+ "steer_resend_failed": "没能作为新一轮发送。",+ "steer_step": "{{name}} 插话",+ "steer_step_read": "已读取"},"status_catalog_error": {"title": "状态列表加载失败",@@ -564,8 +559,8 @@"replying_to": "回复 {{name}}:{{preview}}","leave_comment_placeholder": "留下评论...","send_tooltip": "发送",- "trigger_source_issue_assignee": "assignee",- "trigger_source_mention_agent": "@mention",+ "trigger_source_issue_assignee": "负责人",+ "trigger_source_mention_agent": "@提及","trigger_source_mention_squad_leader": "小队","trigger_source_unknown": "将触发","trigger_skipped_label": "已跳过",@@ -579,9 +574,9 @@"trigger_starts_now": "立即开始。","trigger_starts_when_online": "当前离线,上线后开始。","trigger_click_to_skip": "点击本次跳过。",- "trigger_click_to_manage": "点击选择本次运行的对象。",+ "trigger_click_to_manage": "点击为每个智能体选择这条消息的处理方式。","trigger_click_to_restore": "本次不会开始,点击恢复。",- "trigger_preview_title": "发送后开始",+ "trigger_preview_title": "接收方","trigger_chip_aria": "{{name}} 触发状态:{{state}}","resolve": {"resolve_thread_action": "解决该讨论",@@ -596,7 +591,22 @@"bar_authors_more_other": "{{names}} 等 {{count}} 人","resolve_failed": "标记已解决失败","unresolve_failed": "重新打开失败"- }+ },+ "recipient_steer": "插话到当前运行",+ "recipient_steer_desc": "{{name}} 会在当前步骤结束后读到,并继续完成原任务。仅支持文字。",+ "recipient_after_run": "本轮结束后开始",+ "recipient_after_run_desc": "不打断当前运行,结束后作为新一轮处理。",+ "recipient_restart": "停止并重新开始",+ "recipient_restart_desc": "立即停止当前运行,按这条消息从头开始。",+ "recipient_join": "开始时一并处理",+ "recipient_join_desc": "{{name}} 的运行还在排队,开始时会连同这条消息一起处理。",+ "recipient_state_running": "正在运行",+ "recipient_state_starting": "正在启动",+ "recipient_state_queued": "排队中",+ "recipient_count_other": "{{count}} 个智能体会收到",+ "steer_attachment_notice": "插话只支持文字,带附件的消息会在本轮结束后处理。",+ "restart_send": "停止并发送",+ "restart_failed": "没能停止当前运行,消息还没有发送。"},"reply": {"placeholder": "回复...",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex b384bb9aac..759d1ad37a 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -168,6 +168,12 @@"sticky_comment_bar": {"title": "固定底部评论栏"},+ "running_agent_reply": {+ "title": "回复正在运行的智能体时",+ "steer": "插话到当前运行",+ "after_run": "本轮结束后开始",+ "hint": "只决定默认选项,每条消息发送前仍可单独修改。"+ },"issue_title": "任务创建","comments_title": "评论","device_hint": "保存在当前设备上。",diff --git a/packages/views/settings/components/preferences-tab.test.tsx b/packages/views/settings/components/preferences-tab.test.tsxindex 7943bb2d23..7f2787f357 100644--- a/packages/views/settings/components/preferences-tab.test.tsx+++ b/packages/views/settings/components/preferences-tab.test.tsx@@ -324,6 +324,33 @@ describe("PreferencesTab — Timezone section", () => {});});+describe("PreferencesTab — Replying to a running agent", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ userRef.current = null;+ useCommentComposerStore.setState({ runningAgentReply: "steer" });+ });++ afterEach(() => {+ cleanup();+ });++ it("defaults to adding the reply to the current run and saves starting after it", async () => {+ const user = userEvent.setup();+ render(<PreferencesTab />, { wrapper: I18nWrapper });++ const select = screen.getByRole("combobox", { name: "When replying to a running agent" });+ expect(select).toHaveTextContent("Add to current run");++ await user.click(select);+ await user.click(await screen.findByRole("option", { name: "Start after this run" }));++ expect(useCommentComposerStore.getState().runningAgentReply).toBe("after_run");+ expect(select).toHaveTextContent("Start after this run");+ expect(mockToastSuccess).toHaveBeenCalledTimes(1);+ });+});+describe("PreferencesTab — Sticky comment bar", () => {beforeEach(() => {vi.clearAllMocks();diff --git a/packages/views/settings/components/preferences-tab.tsx b/packages/views/settings/components/preferences-tab.tsxindex 91d6a477d6..a2cf2b5b92 100644--- a/packages/views/settings/components/preferences-tab.tsx+++ b/packages/views/settings/components/preferences-tab.tsx@@ -18,7 +18,7 @@ import {} from "@multica/core/i18n";import { useLocaleAdapter } from "@multica/core/i18n/react";import { useAuthStore } from "@multica/core/auth";-import { useCommentComposerStore } from "@multica/core/issues/stores";+import { useCommentComposerStore, type RunningAgentReply } from "@multica/core/issues/stores";import { api } from "@multica/core/api";import { browserTimezone, timezoneOptions } from "../../common/timezone-select";import {@@ -241,6 +241,7 @@ function GeneralPreferences() {><SettingsCard><StickyCommentBarRow />+ <RunningAgentReplyRow /></SettingsCard></SettingsSection></>@@ -273,6 +274,56 @@ function StickyCommentBarRow() {);}+function RunningAgentReplyRow() {+ const { t } = useT("settings");+ const value = useCommentComposerStore((s) => s.runningAgentReply);+ const setValue = useCommentComposerStore((s) => s.setRunningAgentReply);+ const options: { value: RunningAgentReply; label: string }[] = [+ { value: "steer", label: t(($) => $.preferences.running_agent_reply.steer) },+ { value: "after_run", label: t(($) => $.preferences.running_agent_reply.after_run) },+ ];++ return (+ <SettingsRow+ label={t(($) => $.preferences.running_agent_reply.title)}+ description={t(($) => $.preferences.running_agent_reply.hint)}+ size="select"+ >+ <Select+ items={options}+ value={value}+ onValueChange={(next) => {+ if (!next || next === value) return;+ setValue(next as RunningAgentReply);+ toast.success(+ t(($) => $.auto_save.toast_saved),+ {+ id: "settings-auto-save",+ },+ );+ }}+ >+ <SelectTrigger+ size="sm"+ className="w-full"+ aria-label={t(($) => $.preferences.running_agent_reply.title)}+ >+ <SelectValue>+ {options.find((option) => option.value === value)?.label}+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="end">+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ );+}+// Base UI rejects "" as a SelectItem value, so route the "no preference"// state through this sentinel and translate at the wire boundary.const BROWSER_TZ_VALUE = "__browser__";diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 7eb4c160e1..1ce9147ead 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -146,6 +146,7 @@ var concurrentIndexCleanups = map[string]string{"541_task_supplement_comment_index": "task_supplement_comment_uidx","546_issue_pr_automation_workspace_index": "idx_issue_pr_automation_workspace","547_issue_pull_request_exclusion_workspace_index": "idx_issue_pull_request_exclusion_workspace",+ "548_task_supplement_comment_task_index": "task_supplement_comment_task_uidx","510_wakeup_id": "issue_wakeup_id_idx","511_wakeup_issue": "issue_wakeup_issue_idx","512_wakeup_due": "issue_wakeup_due_idx",@@ -365,6 +366,7 @@ var concurrentDownIndexCleanups = map[string]string{"437_drop_agent_runtime_last_seen_at_index": "idx_agent_runtime_last_seen_at","450_drop_comment_delegated_failure_pending_index": "idx_comment_delegated_failure_pending","453_drop_pending_issue_agent_unique": "idx_one_pending_task_per_issue_agent_v2",+ "548_task_supplement_comment_task_index": "task_supplement_comment_uidx","454_drop_comment_content_bigm_index": "idx_comment_content_bigm","455_drop_comment_content_trgm_index": "idx_comment_content_trgm","463_drop_issue_description_bigm_index": "idx_issue_description_bigm",diff --git a/server/cmd/migrate/migrate_comment_suppressed_agents_test.go b/server/cmd/migrate/migrate_comment_suppressed_agents_test.gonew file mode 100644index 0000000000..e0cab3a858--- /dev/null+++ b/server/cmd/migrate/migrate_comment_suppressed_agents_test.go@@ -0,0 +1,42 @@+package main++import (+ "context"+ "math/rand/v2"+ "testing"+ "time"+)++func TestCommentSuppressedAgentsMigrationUpDownUpInIsolatedSchema(t *testing.T) {+ base := openTestPool(t)+ ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)+ defer cancel()+ schema := createScratchSchema(t, ctx, base, "comment_suppressed_agents_")+ pool := openTestPoolWithSearchPath(t, schema)+ if _, err := pool.Exec(ctx, `CREATE TABLE comment (id UUID PRIMARY KEY)`); err != nil {+ t.Fatal(err)+ }++ for _, direction := range []string{"up", "down", "up"} {+ if err := runMigrations(ctx, pool, runOptions{+ Direction: direction,+ Files: realMigrationFiles(t, []string{"550_comment_suppressed_agents"}, direction),+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: hooksForDirection(direction),+ Conditions: conditionsForDirection(direction),+ }); err != nil {+ t.Fatalf("migrate %s: %v", direction, err)+ }+ var columns int+ if err := pool.QueryRow(ctx, `+ SELECT count(*) FROM information_schema.columns+ WHERE table_schema = $1 AND table_name = 'comment' AND column_name = 'suppressed_agent_ids'+ `, schema).Scan(&columns); err != nil {+ t.Fatal(err)+ }+ if want := map[string]int{"up": 1, "down": 0}[direction]; columns != want {+ t.Fatalf("after %s, suppressed_agent_ids columns = %d, want %d", direction, columns, want)+ }+ }+}diff --git a/server/cmd/migrate/migrate_task_supplement_test.go b/server/cmd/migrate/migrate_task_supplement_test.goindex e4e96bc677..dfeced9551 100644--- a/server/cmd/migrate/migrate_task_supplement_test.go+++ b/server/cmd/migrate/migrate_task_supplement_test.go@@ -27,6 +27,8 @@ func TestTaskSupplementMigrationsUpDownUpInIsolatedSchema(t *testing.T) {"542_task_supplement_primary_key","543_task_supplement_teardown_guard","544_task_supplement_application_settlement",+ "548_task_supplement_comment_task_index",+ "549_task_supplement_comment_task_primary_key",}if direction == "down" {slices.Reverse(versions)@@ -92,6 +94,30 @@ func TestTaskSupplementMigrationsUpDownUpInIsolatedSchema(t *testing.T) {if err != nil || status != "pending" {t.Fatalf("task update had hidden receipt settlement: %s, %v", status, err)}+ // One comment may steer several runs, but never the same run twice.+ var receipts int+ tx, err = pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ _, err = tx.Exec(ctx, `+ INSERT INTO task_supplement (task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status)+ SELECT task_id, gen_random_uuid(), gen_random_uuid(), '00000000-0000-0000-0000-0000000000c1', gen_random_uuid(), gen_random_uuid(), 'pending'+ FROM (VALUES ('00000000-0000-0000-0000-00000000000a'::uuid), ('00000000-0000-0000-0000-00000000000b'::uuid)) AS runs(task_id)`)+ if err == nil {+ err = tx.QueryRow(ctx, `SELECT count(*) FROM task_supplement WHERE comment_id = '00000000-0000-0000-0000-0000000000c1'`).Scan(&receipts)+ }+ if err != nil || receipts != 2 {+ _ = tx.Rollback(ctx)+ t.Fatalf("one comment bound to two runs: %d receipts, %v", receipts, err)+ }+ _, err = tx.Exec(ctx, `+ INSERT INTO task_supplement (task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status)+ VALUES ('00000000-0000-0000-0000-00000000000a', gen_random_uuid(), gen_random_uuid(), '00000000-0000-0000-0000-0000000000c1', gen_random_uuid(), gen_random_uuid(), 'pending')`)+ _ = tx.Rollback(ctx)+ if err == nil {+ t.Fatal("the same comment was bound to the same run twice")+ }}}}diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.goindex 935cd90544..d02911b3cc 100644--- a/server/internal/dispatch/reason.go+++ b/server/internal/dispatch/reason.go@@ -19,6 +19,8 @@ const (ReasonQueued ReasonCode = "queued"ReasonCoalesced ReasonCode = "coalesced"ReasonDeferred ReasonCode = "deferred"+ // ReasonSteered: the comment went into the target's running turn.+ ReasonSteered ReasonCode = "steered"// ReasonInvocationNotAllowed: the acting principal may not trigger this// target under the invocation-permission model. Deliberately generic — itdiff --git a/server/internal/handler/activity.go b/server/internal/handler/activity.goindex f1591de932..f38f20b00e 100644--- a/server/internal/handler/activity.go+++ b/server/internal/handler/activity.go@@ -47,11 +47,14 @@ type TimelineEntry struct {ResolvedByID *string `json:"resolved_by_id,omitempty"`SourceTaskID *string `json:"source_task_id,omitempty"`// Set only on a tombstone: a comment deleted while it still had replies.- DeletedAt *string `json:"deleted_at,omitempty"`- SupplementTaskID string `json:"supplement_task_id,omitempty"`- SupplementStatus string `json:"supplement_status,omitempty"`- SupplementFailureReason *string `json:"supplement_failure_reason,omitempty"`- SupplementDeliveredAt *string `json:"supplement_delivered_at,omitempty"`+ DeletedAt *string `json:"deleted_at,omitempty"`+ // Supplements lists every running turn this comment steered; the single+ // supplement_* fields mirror the first receipt for older clients.+ Supplements []CommentSupplementResponse `json:"supplements,omitempty"`+ SupplementTaskID string `json:"supplement_task_id,omitempty"`+ SupplementStatus string `json:"supplement_status,omitempty"`+ SupplementFailureReason *string `json:"supplement_failure_reason,omitempty"`+ SupplementDeliveredAt *string `json:"supplement_delivered_at,omitempty"`}// timelineHardCap bounds the per-issue timeline payload. Sized as a defensive@@ -287,14 +290,7 @@ func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []Ti}reactions := h.groupReactions(r, ids)attachments := h.groupAttachments(r, ids)- supplements := make(map[string]db.TaskSupplement)- if rows, err := h.Queries.ListTaskSupplementsByCommentIDs(r.Context(), db.ListTaskSupplementsByCommentIDsParams{- WorkspaceID: comments[0].WorkspaceID, CommentIds: ids,- }); err == nil {- for _, row := range rows {- supplements[uuidToString(row.CommentID)] = row- }- }+ supplements := h.listCommentSupplements(r.Context(), comments[0].WorkspaceID, ids)out := make([]TimelineEntry, len(comments))for i, c := range comments {@@ -322,11 +318,12 @@ func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []TiSourceTaskID: uuidToPtr(c.SourceTaskID),DeletedAt: timestampToPtr(c.DeletedAt),}- if supplement, ok := supplements[cid]; ok {- out[i].SupplementTaskID = uuidToString(supplement.TaskID)- out[i].SupplementStatus = supplement.Status- out[i].SupplementFailureReason = textToPtr(supplement.FailureReason)- out[i].SupplementDeliveredAt = timestampToPtr(supplement.DeliveredAt)+ if receipts := supplements[cid]; len(receipts) > 0 {+ out[i].Supplements = receipts+ out[i].SupplementTaskID = receipts[0].TaskID+ out[i].SupplementStatus = receipts[0].Status+ out[i].SupplementFailureReason = receipts[0].FailureReason+ out[i].SupplementDeliveredAt = receipts[0].DeliveredAt}}return outdiff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.goindex df2bac855c..9d8ae503f5 100644--- a/server/internal/handler/admission.go+++ b/server/internal/handler/admission.go@@ -37,6 +37,9 @@ const (// DispatchDeferred: admitted but intentionally not started yet (e.g. a// backlog issue parked until promotion, or suppress_run).DispatchDeferred DispatchStatus = "deferred"+ // DispatchSteered: the comment was bound to the target's running turn+ // instead of starting a run. Only returned when the author asked to steer.+ DispatchSteered DispatchStatus = "steered"// DispatchBlocked: the run was refused. ReasonCode carries why.DispatchBlocked DispatchStatus = "blocked")@@ -53,6 +56,7 @@ const (ReasonQueued = dispatch.ReasonQueuedReasonCoalesced = dispatch.ReasonCoalescedReasonDeferred = dispatch.ReasonDeferred+ ReasonSteered = dispatch.ReasonSteeredReasonInvocationNotAllowed = dispatch.ReasonInvocationNotAllowedReasonTargetUnavailable = dispatch.ReasonTargetUnavailableReasonRuntimeOffline = dispatch.ReasonRuntimeOfflinediff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 745ade041a..89539197a2 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -82,11 +82,15 @@ type CommentResponse struct {// was blocked (no invoke permission, target unavailable, runtime offline) now// reports that here instead of silently dropping the trigger, so the client// can show "comment posted, but N targets were not triggered".- TriggerOutcomes []CommentTriggerOutcome `json:"trigger_outcomes,omitempty"`- SupplementTaskID string `json:"supplement_task_id,omitempty"`- SupplementStatus string `json:"supplement_status,omitempty"`- SupplementFailureReason *string `json:"supplement_failure_reason,omitempty"`- SupplementDeliveredAt *string `json:"supplement_delivered_at,omitempty"`+ TriggerOutcomes []CommentTriggerOutcome `json:"trigger_outcomes,omitempty"`+ // Supplements lists every running turn this comment steered, one receipt+ // per run. The single supplement_* fields mirror the first receipt for+ // clients that predate multi-run steering.+ Supplements []CommentSupplementResponse `json:"supplements,omitempty"`+ SupplementTaskID string `json:"supplement_task_id,omitempty"`+ SupplementStatus string `json:"supplement_status,omitempty"`+ SupplementFailureReason *string `json:"supplement_failure_reason,omitempty"`+ SupplementDeliveredAt *string `json:"supplement_delivered_at,omitempty"`}// CommentTriggerOutcome is the per-target result of an explicit @agent / @squad@@ -1486,6 +1490,11 @@ type CreateCommentRequest struct {ParentID *string `json:"parent_id"`AttachmentIDs []string `json:"attachment_ids"`SuppressAgentIDs []string `json:"suppress_agent_ids"`+ // SteerTaskIDs are the running turns the author chose to add this comment+ // to, instead of starting a follow-up run for their agents. A turn that+ // has ended, or cannot take additional input, is never swapped for another+ // one: its agent keeps the normal trigger.+ SteerTaskIDs []string `json:"steer_task_ids"`}type CommentTriggerPreviewRequest struct {@@ -1761,6 +1770,15 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {if !ok {return}+ steerTaskIDs, ok := parseUUIDSliceOrBadRequest(w, req.SteerTaskIDs, "steer_task_ids")+ if !ok {+ return+ }+ // A running turn receives text only, so a comment that carries files is+ // always a normal trigger.+ if len(attachmentIDs) > 0 {+ steerTaskIDs = nil+ }// Determine author identity: agent (via X-Agent-ID header) or member.authorType, authorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))@@ -1876,6 +1894,9 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {Type: req.Type,ParentID: parentID,SourceTaskID: sourceTaskID,+ // The author's "don't start" choices outlive this call: completion+ // replay skips the agents it names.+ SuppressedAgentIds: suppressAgentIDs,}var created db.CreateCommentRowvar err error@@ -1966,7 +1987,10 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// The comment is already saved; a blocked mention must not fail the whole// request. Surface the per-target outcomes so the client can show partial// success instead of a silent no-op (MUL-4525 §2).- resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, originatorUserID, suppressAgentIDs)+ resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, originatorUserID, suppressAgentIDs, steerTaskIDs)+ if len(steerTaskIDs) > 0 {+ applyCommentSupplements(&resp, h.listCommentSupplements(r.Context(), issue.WorkspaceID, []pgtype.UUID{comment.ID})[uuidToString(comment.ID)])+ }writeJSON(w, http.StatusCreated, resp)}@@ -2007,7 +2031,10 @@ func isNoteComment(content string) bool {// (MUL-4525 §2): blocked mentions from resolution plus queued / coalesced /// deferred / blocked from enqueue. UI-suppressed triggers (the user unchecked// them) are removed before enqueue and produce no outcome.-func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID, originatorUserID string, suppressAgentIDs []pgtype.UUID) []CommentTriggerOutcome {+//+// steerTaskIDs are the running turns the author chose: a recipient whose chosen+// turn is still running receives this comment there instead of a follow-up run.+func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID, originatorUserID string, suppressAgentIDs, steerTaskIDs []pgtype.UUID) []CommentTriggerOutcome {if isNoteComment(comment.Content) {return nil}@@ -2018,7 +2045,11 @@ func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, co})triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)h.noteBlockedRuntimeTargets(ctx, issue, targets)+ triggers, steered := h.steerCommentAgentTriggers(ctx, issue, comment, actorType, triggers, steerTaskIDs)enqueued := h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)+ for agentID, result := range steered {+ enqueued[agentID] = result+ }return commentTriggerOutcomes(targets, enqueued)}@@ -3353,14 +3384,14 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "comment not found")return}- if _, err := h.Queries.GetTaskSupplementByComment(r.Context(), db.GetTaskSupplementByCommentParams{+ if bound, err := h.Queries.CommentHasTaskSupplement(r.Context(), db.CommentHasTaskSupplementParams{CommentID: existing.ID, WorkspaceID: wsUUID,- }); err == nil {- writeError(w, http.StatusConflict, "additional messages cannot be edited")- return- } else if !errors.Is(err, pgx.ErrNoRows) {+ }); err != nil {writeError(w, http.StatusInternalServerError, "failed to verify additional message")return+ } else if bound {+ writeError(w, http.StatusConflict, "additional messages cannot be edited")+ return}member, ok := h.workspaceMember(w, r, workspaceID)@@ -3475,6 +3506,8 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {ID: commentUUID,Content: req.Content,SourceTaskID: sourceTaskID,+ // New text replaces the "don't start" choices completion replay keeps.+ SuppressedAgentIds: suppressAgentIDs,}if req.ContentBase != nil {updateParams.ContentBase = pgtype.Text{String: *req.ContentBase, Valid: true}@@ -3580,7 +3613,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {}h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, existing.ID)- return h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), suppressAgentIDs)+ return h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), suppressAgentIDs, nil)}// Fetch reactions and attachments for the updated comment.@@ -3818,20 +3851,23 @@ func (h *Handler) deleteComment(ctx context.Context, commentID, workspaceID pgty}// Keep receipt admission locked through deletion so a concurrent retry// cannot resurrect or deliver the content being removed.- receipt, receiptErr := qtx.LockTaskSupplementByComment(ctx, db.LockTaskSupplementByCommentParams{+ receipts, receiptErr := qtx.LockTaskSupplementsByComment(ctx, db.LockTaskSupplementsByCommentParams{CommentID: commentID, WorkspaceID: workspaceID,})- if receiptErr == nil {+ if receiptErr != nil {+ return out, receiptErr+ }+ for _, receipt := range receipts {if receipt.Status == "pending" || receipt.Status == "delivering" {return out, errTaskSupplementInFlight}+ }+ if len(receipts) > 0 {if err := qtx.DeleteTaskSupplementByComment(ctx, db.DeleteTaskSupplementByCommentParams{CommentID: commentID, WorkspaceID: workspaceID,}); err != nil {return out, err}- } else if !errors.Is(receiptErr, pgx.ErrNoRows) {- return out, receiptErr}// Separate statement on purpose: its snapshot postdates the locks above,// so it sees every committed reply, and none can be added while they arediff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.goindex faf911b762..0a6de2c0be 100644--- a/server/internal/handler/comment_reconcile_test.go+++ b/server/internal/handler/comment_reconcile_test.go@@ -353,7 +353,7 @@ func TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent(t *testing.if err != nil {t.Fatalf("setup: load mention comment: %v", err)}- testHandler.triggerTasksForComment(ctx, issue, mentionComment, nil, "agent", agentA, "", nil)+ testHandler.triggerTasksForComment(ctx, issue, mentionComment, nil, "agent", agentA, "", nil, nil)// Drop happened: the mention found no queued task to merge into and an// active (dispatched) task exists, so NO fresh queued follow-up was created.@@ -553,7 +553,7 @@ func TestConsecutiveCommentsDifferentOriginatorsFullEnqueuePath(t *testing.T) {// A's comment → creates the queued task (originator A).cA := insertMemberComment(testUserID, "first, from A")- testHandler.triggerTasksForComment(ctx, issue, cA, nil, "member", testUserID, testUserID, nil)+ testHandler.triggerTasksForComment(ctx, issue, cA, nil, "member", testUserID, testUserID, nil, nil)if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {t.Fatalf("after A's comment expected exactly 1 queued task, got %d", n)}@@ -562,7 +562,7 @@ func TestConsecutiveCommentsDifferentOriginatorsFullEnqueuePath(t *testing.T) {cB := insertMemberComment(userB, "second, from B — different user")dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE id=$1`, cB.ID, cA.ID)cB.ParentID = cA.ID- testHandler.triggerTasksForComment(ctx, issue, cB, nil, "member", userB, userB, nil)+ testHandler.triggerTasksForComment(ctx, issue, cB, nil, "member", userB, userB, nil, nil)// Still exactly one task (bounded concurrency, no unique-index collision).if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {diff --git a/server/internal/handler/comment_steer_test.go b/server/internal/handler/comment_steer_test.gonew file mode 100644index 0000000000..15bb00c4bf--- /dev/null+++ b/server/internal/handler/comment_steer_test.go@@ -0,0 +1,308 @@+package handler++import (+ "context"+ "fmt"+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func agentMention(name, id string) string {+ return fmt.Sprintf("[@%s](mention://agent/%s)", name, id)+}++func postSteeredComment(t *testing.T, issueID, parentID, content string, steerTaskIDs ...string) *testutil.Response {+ t.Helper()+ body := map[string]any{"content": content, "steer_task_ids": steerTaskIDs}+ if parentID != "" {+ body["parent_id"] = parentID+ }+ return testutil.Call(t, testHandler.CreateComment, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", body), "id", issueID))+}++// runningSteerableTask starts another agent's running, steer-capable turn on+// the fixture's issue.+func runningSteerableTask(t *testing.T, f supplementFixture, name string) (agentID, taskID string) {+ t.Helper()+ runtimeID := dbfx.Runtime(t, "steer-"+name, testutil.Cols{"provider": "claude"})+ agentID = dbfx.Agent(t, name, runtimeID)+ taskID = dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": f.issueID, "runtime_id": runtimeID, "status": "running", "started_at": testutil.Raw("now()"),+ })+ dbfx.Exec(t, `INSERT INTO task_supplement_capability (task_id, workspace_id, issue_id, capability) VALUES ($1, $2, $3, $4)`,+ taskID, testWorkspaceID, f.issueID, protocol.DaemonCapabilityTaskSupplementV1)+ dbfx.Cleanup(t, `DELETE FROM task_supplement_capability WHERE task_id = $1`, taskID)+ dbfx.Cleanup(t, `DELETE FROM task_supplement WHERE task_id = $1`, taskID)+ return agentID, taskID+}++func completeTaskViaDaemon(t *testing.T, taskID string) {+ t.Helper()+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/complete",+ map[string]any{"output": "done"}, testWorkspaceID, "legit-daemon")+ testutil.Call(t, testHandler.CompleteTask, withURLParam(req, "taskId", taskID)).Want(http.StatusOK)+}++func outcomeFor(outcomes []CommentTriggerOutcome, agentID string) (CommentTriggerOutcome, bool) {+ for _, outcome := range outcomes {+ if outcome.TargetType == "agent" && outcome.TargetID == agentID {+ return outcome, true+ }+ }+ return CommentTriggerOutcome{}, false+}++func TestCreateCommentSteersTheThreadAgentsRunningTurn(t *testing.T) {+ f := newSupplementFixture(t, "codex", "running", true)+ dbfx.Exec(t, `UPDATE comment SET content = $2 WHERE id = $1`, f.triggerID,+ agentMention("Supplement", f.agentID)+" original objective")+ dbfx.Exec(t, `UPDATE agent_task_queue SET delivered_comment_ids = ARRAY[trigger_comment_id] WHERE id = $1`, f.taskID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)++ var created CommentResponse+ postSteeredComment(t, f.issueID, f.triggerID, "Only fix web.", f.taskID).Want(http.StatusCreated).JSON(&created)+ if len(created.Supplements) != 1 {+ t.Fatalf("receipts = %+v, want one for the running turn", created.Supplements)+ }+ receipt := created.Supplements[0]+ if receipt.TaskID != f.taskID || receipt.AgentID != f.agentID || receipt.Status != "pending" {+ t.Fatalf("receipt = %+v, want pending for task %s / agent %s", receipt, f.taskID, f.agentID)+ }+ if created.SupplementTaskID != f.taskID || created.SupplementStatus != "pending" {+ t.Fatalf("legacy receipt fields = %s/%s, want the first receipt", created.SupplementTaskID, created.SupplementStatus)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, f.issueID); n != 1 {+ t.Fatalf("steering created %d runs, want the running turn only", n)+ }++ completeTaskViaDaemon(t, f.taskID)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, f.issueID); n != 1 {+ t.Fatalf("completion replayed a steered comment into %d runs", n)+ }+}++func TestCreateCommentSteerKeepsTheNormalTriggerWhenTheTurnCannotTakeInput(t *testing.T) {+ for _, tc := range []struct {+ name string+ status string+ negotiated bool+ }{+ {name: "turn without the capability", status: "running", negotiated: false},+ {name: "turn not started", status: "dispatched", negotiated: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ f := newSupplementFixture(t, "codex", tc.status, tc.negotiated)+ dbfx.Exec(t, `UPDATE comment SET content = $2 WHERE id = $1`, f.triggerID,+ agentMention("Supplement", f.agentID)+" original objective")+ dbfx.Exec(t, `UPDATE agent_task_queue SET delivered_comment_ids = ARRAY[trigger_comment_id] WHERE id = $1`, f.taskID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)++ var created CommentResponse+ postSteeredComment(t, f.issueID, f.triggerID, "Only fix web.", f.taskID).Want(http.StatusCreated).JSON(&created)+ if len(created.Supplements) != 0 {+ t.Fatalf("bound a turn that cannot take input: %+v", created.Supplements)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM task_supplement WHERE comment_id = $1`, created.ID); n != 0 {+ t.Fatalf("stored %d receipts", n)+ }+ if tc.status != "running" {+ return+ }+ // The comment keeps its deferred trigger and becomes the follow-up.+ completeTaskViaDaemon(t, f.taskID)+ var trigger string+ dbfx.QueryRow(t, `SELECT trigger_comment_id FROM agent_task_queue WHERE issue_id = $1 AND id <> $2`,+ f.issueID, f.taskID).Scan(&trigger)+ if trigger != created.ID {+ t.Fatalf("follow-up trigger = %s, want the unsteered comment %s", trigger, created.ID)+ }+ })+ }+}++func TestCreateCommentSteersOnlyRunningRecipients(t *testing.T) {+ f := newSupplementFixture(t, "codex", "running", true)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)+ idleAgentID := dbfx.Agent(t, "Idle recipient", f.runtimeID)+ content := agentMention("Supplement", f.agentID) + " only web; " + agentMention("Idle recipient", idleAgentID) + " check desktop"++ var created CommentResponse+ postSteeredComment(t, f.issueID, "", content, f.taskID).Want(http.StatusCreated).JSON(&created)+ if len(created.Supplements) != 1 || created.Supplements[0].AgentID != f.agentID {+ t.Fatalf("receipts = %+v, want the running agent only", created.Supplements)+ }+ if outcome, ok := outcomeFor(created.TriggerOutcomes, f.agentID); !ok || outcome.Status != DispatchSteered || outcome.ReasonCode != ReasonSteered {+ t.Fatalf("running recipient outcome = %+v (%v), want steered", outcome, ok)+ }+ if outcome, ok := outcomeFor(created.TriggerOutcomes, idleAgentID); !ok || outcome.Status == DispatchSteered || outcome.Status == DispatchBlocked {+ t.Fatalf("idle recipient outcome = %+v (%v), want a normal trigger", outcome, ok)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1 AND trigger_comment_id = $2`, idleAgentID, created.ID); n != 1 {+ t.Fatalf("idle recipient has %d runs for the comment, want 1", n)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1`, f.agentID); n != 1 {+ t.Fatalf("steered recipient has %d runs, want its running turn only", n)+ }+}++func TestCreateCommentSteersSeveralRunningTurns(t *testing.T) {+ f := newSupplementFixture(t, "codex", "running", true)+ otherAgentID, otherTaskID := runningSteerableTask(t, f, "Second runner")+ content := agentMention("Supplement", f.agentID) + " and " + agentMention("Second runner", otherAgentID) + " stop touching desktop"++ var created CommentResponse+ postSteeredComment(t, f.issueID, "", content, f.taskID, otherTaskID).Want(http.StatusCreated).JSON(&created)+ got := map[string]string{}+ for _, receipt := range created.Supplements {+ got[receipt.AgentID] = receipt.TaskID+ }+ if len(created.Supplements) != 2 || got[f.agentID] != f.taskID || got[otherAgentID] != otherTaskID {+ t.Fatalf("receipts = %+v, want one per running turn", created.Supplements)+ }++ var timeline []TimelineEntry+ testutil.Call(t, testHandler.ListTimeline, withURLParam(+ newRequest(http.MethodGet, "/api/issues/"+f.issueID+"/timeline", nil), "id", f.issueID)).Want(http.StatusOK).JSON(&timeline)+ for _, entry := range timeline {+ if entry.ID == created.ID && len(entry.Supplements) != 2 {+ t.Fatalf("timeline receipts = %+v, want both runs", entry.Supplements)+ }+ }+}++func TestCompletionReplaysASteeredCommentOnlyForAgentsItDidNotSteer(t *testing.T) {+ f := newSupplementFixture(t, "codex", "running", true)+ dbfx.Exec(t, `UPDATE agent_task_queue SET delivered_comment_ids = ARRAY[trigger_comment_id] WHERE id = $1`, f.taskID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)+ otherAgentID, otherTaskID := runningSteerableTask(t, f, "Waits its turn")+ content := agentMention("Supplement", f.agentID) + " only web; " + agentMention("Waits its turn", otherAgentID) + " next round"++ var created CommentResponse+ postSteeredComment(t, f.issueID, "", content, f.taskID).Want(http.StatusCreated).JSON(&created)+ if len(created.Supplements) != 1 || created.Supplements[0].AgentID != f.agentID {+ t.Fatalf("receipts = %+v, want the steered agent only", created.Supplements)+ }++ completeTaskViaDaemon(t, otherTaskID)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1 AND trigger_comment_id = $2`, otherAgentID, created.ID); n != 1 {+ t.Fatalf("unsteered recipient got %d follow-ups, want 1", n)+ }+ completeTaskViaDaemon(t, f.taskID)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1`, f.agentID); n != 1 {+ t.Fatalf("steered recipient has %d runs, want no follow-up", n)+ }+}++func TestCreateCommentSteerNeverRetargetsAnotherTurn(t *testing.T) {+ f := newSupplementFixture(t, "codex", "running", true)+ dbfx.Exec(t, `UPDATE comment SET content = $2 WHERE id = $1`, f.triggerID, agentMention("A", f.agentID)+" original thread")+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)+ // The chosen turn ends before the send arrives, and the same agent has+ // meanwhile started a turn for another thread.+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, f.taskID)+ otherRoot := dbfx.Comment(t, f.issueID, agentMention("A", f.agentID)+" unrelated thread")+ successor := dbfx.Task(t, f.agentID, testutil.Cols{+ "issue_id": f.issueID, "runtime_id": f.runtimeID, "trigger_comment_id": otherRoot,+ "status": "running", "started_at": testutil.Raw("now()"),+ })+ dbfx.Exec(t, `INSERT INTO task_supplement_capability (task_id, workspace_id, issue_id, capability) VALUES ($1, $2, $3, $4)`,+ successor, testWorkspaceID, f.issueID, protocol.DaemonCapabilityTaskSupplementV1)+ dbfx.Cleanup(t, `DELETE FROM task_supplement_capability WHERE task_id = $1`, successor)+ dbfx.Cleanup(t, `DELETE FROM task_supplement WHERE task_id = $1`, successor)++ var sent CommentResponse+ postSteeredComment(t, f.issueID, f.triggerID, "Only change the original task", f.taskID).Want(http.StatusCreated).JSON(&sent)+ if len(sent.Supplements) != 0 {+ t.Fatalf("the chosen turn ended, but the send steered another turn: %+v", sent.Supplements)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM task_supplement WHERE task_id = $1`, successor); n != 0 {+ t.Fatalf("successor turn received %d steered messages", n)+ }+}++func TestCompletionKeepsAnAgentTheAuthorChoseNotToStart(t *testing.T) {+ f := newSupplementFixture(t, "codex", "running", true)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)+ otherAgent, otherTask := runningSteerableTask(t, f, "Other recipient")+ content := agentMention("A", f.agentID) + " and " + agentMention("B", otherAgent) + " only do this once"+ dbfx.Exec(t, `UPDATE comment SET content = $2 WHERE id = $1`, f.triggerID, content)+ dbfx.Exec(t, `UPDATE agent_task_queue SET trigger_comment_id = $2, comment_thread_id = $2, delivered_comment_ids = ARRAY[$2::uuid] WHERE id = $1`, otherTask, f.triggerID)+ // B is working in this thread; the reply goes to A only ("Won't start+ // this time" for B, or "Send as a new run" for a receipt A missed).+ body := map[string]any{"content": content, "parent_id": f.triggerID, "suppress_agent_ids": []string{otherAgent}}+ testutil.Call(t, testHandler.CreateComment, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+f.issueID+"/comments", body), "id", f.issueID)).Want(http.StatusCreated)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1`, otherAgent); n != 1 {+ t.Fatalf("the reply started another B run: %d", n)+ }+ completeTaskViaDaemon(t, otherTask)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1`, otherAgent); n != 1 {+ t.Fatalf("B's completion replayed the reply into %d runs, want 1", n)+ }+}++func TestCreateCommentSteerIgnoresATurnOfAnotherIssue(t *testing.T) {+ f := newSupplementFixture(t, "codex", "running", true)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)+ // The same agent is also running on another issue.+ otherIssueID := dbfx.Issue(t, "Another issue")+ elsewhere := dbfx.Task(t, f.agentID, testutil.Cols{+ "issue_id": otherIssueID, "runtime_id": f.runtimeID, "status": "running", "started_at": testutil.Raw("now()"),+ })+ dbfx.Exec(t, `INSERT INTO task_supplement_capability (task_id, workspace_id, issue_id, capability) VALUES ($1, $2, $3, $4)`,+ elsewhere, testWorkspaceID, otherIssueID, protocol.DaemonCapabilityTaskSupplementV1)+ dbfx.Cleanup(t, `DELETE FROM task_supplement_capability WHERE task_id = $1`, elsewhere)+ content := agentMention("Supplement", f.agentID) + " only web"++ var created CommentResponse+ postSteeredComment(t, f.issueID, "", content, elsewhere).Want(http.StatusCreated).JSON(&created)+ if len(created.Supplements) != 0 {+ t.Fatalf("receipts = %+v, want none for a turn of another issue", created.Supplements)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM task_supplement WHERE task_id = $1`, elsewhere); n != 0 {+ t.Fatalf("another issue's turn received %d messages", n)+ }+ if outcome, ok := outcomeFor(created.TriggerOutcomes, f.agentID); !ok || outcome.Status == DispatchSteered {+ t.Fatalf("recipient outcome = %+v (%v), want its normal trigger", outcome, ok)+ }+}++func TestUpdateCommentKeepsTheLatestEditsSuppression(t *testing.T) {+ f := newSupplementFixture(t, "codex", "running", true)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)+ commentID := dbfx.Comment(t, f.issueID, "initial body")+ h := *testHandler+ h.Bus = events.New()+ laterContent := agentMention("A", f.agentID) + " latest edit"+ nested := false+ h.Bus.Subscribe(protocol.EventCommentUpdated, func(events.Event) {+ if nested {+ return+ }+ nested = true+ // A second editor saves right after the first edit's text commits.+ later := withURLParam(newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{+ "content": laterContent, "expected_revision": 2, "suppress_agent_ids": []string{},+ }), "commentId", commentID)+ testutil.Call(t, h.UpdateComment, later).Want(http.StatusOK)+ })+ first := withURLParam(newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{+ "content": agentMention("A", f.agentID) + " first edit", "expected_revision": 1, "suppress_agent_ids": []string{f.agentID},+ }), "commentId", commentID)+ testutil.Call(t, h.UpdateComment, first).Want(http.StatusOK)+ saved, err := testHandler.Queries.GetComment(context.Background(), parseUUID(commentID))+ if err != nil {+ t.Fatal(err)+ }+ if saved.Content != laterContent || saved.Revision != 3 {+ t.Fatalf("latest body/revision = %q/%d", saved.Content, saved.Revision)+ }+ if len(saved.SuppressedAgentIds) != 0 {+ t.Fatalf("the latest edit starts A, but an earlier edit's choice stayed: %v", saved.SuppressedAgentIds)+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex e8b9c49902..d973a10222 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -4457,6 +4457,7 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.AgIssueID: task.IssueID,Since: task.CreatedAt,PlannedCommentIds: plannedCommentIDs,+ AgentID: task.AgentID,})if err != nil {slog.Warn("reconcile comments on completion: list comments failed",diff --git a/server/internal/handler/quick_action.go b/server/internal/handler/quick_action.goindex 7a664c309a..57655ec32e 100644--- a/server/internal/handler/quick_action.go+++ b/server/internal/handler/quick_action.go@@ -931,7 +931,7 @@ func (h *Handler) RunQuickAction(w http.ResponseWriter, r *http.Request) {"issue_revision": created.IssueRevision,})- resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, nil, actorType, actorID, originatorUserID, nil)+ resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, nil, actorType, actorID, originatorUserID, nil, nil)// Usage telemetry is best-effort and deliberately outside the run's// success path: a failed counter must never cost the user the run.diff --git a/server/internal/handler/task_supplement.go b/server/internal/handler/task_supplement.goindex 2a64df7dfa..89d9dc0594 100644--- a/server/internal/handler/task_supplement.go+++ b/server/internal/handler/task_supplement.go@@ -4,6 +4,7 @@ import ("context""encoding/json""errors"+ "log/slog""net/http""strings"@@ -80,12 +81,106 @@ func supplementReceipt(s db.TaskSupplement) taskSupplementReceiptResponse {}}-func applySupplementReceipt(resp *CommentResponse, s db.TaskSupplement) {- receipt := supplementReceipt(s)- resp.SupplementTaskID = receipt.TaskID- resp.SupplementStatus = receipt.Status- resp.SupplementFailureReason = receipt.FailureReason- resp.SupplementDeliveredAt = receipt.DeliveredAt+// CommentSupplementResponse is one delivery receipt of a comment that steered+// a running turn. A comment can steer several agents' turns at once.+type CommentSupplementResponse struct {+ TaskID string `json:"task_id"`+ AgentID string `json:"agent_id,omitempty"`+ Status string `json:"status"`+ FailureReason *string `json:"failure_reason,omitempty"`+ DeliveredAt *string `json:"delivered_at,omitempty"`+}++// listCommentSupplements groups every receipt by comment id, oldest first.+// Receipts are optional metadata: a failed read leaves comments without them.+func (h *Handler) listCommentSupplements(ctx context.Context, workspaceID pgtype.UUID, commentIDs []pgtype.UUID) map[string][]CommentSupplementResponse {+ out := make(map[string][]CommentSupplementResponse)+ if len(commentIDs) == 0 {+ return out+ }+ rows, err := h.Queries.ListTaskSupplementsByCommentIDs(ctx, db.ListTaskSupplementsByCommentIDsParams{+ WorkspaceID: workspaceID, CommentIds: commentIDs,+ })+ if err != nil {+ return out+ }+ for _, row := range rows {+ id := uuidToString(row.CommentID)+ out[id] = append(out[id], CommentSupplementResponse{+ TaskID: uuidToString(row.TaskID),+ AgentID: uuidToString(row.AgentID),+ Status: row.Status,+ FailureReason: textToPtr(row.FailureReason),+ DeliveredAt: timestampToPtr(row.DeliveredAt),+ })+ }+ return out+}++// applyCommentSupplements sets the receipt list and mirrors its first entry+// into the single-receipt fields older clients read.+func applyCommentSupplements(resp *CommentResponse, receipts []CommentSupplementResponse) {+ if len(receipts) == 0 {+ return+ }+ resp.Supplements = receipts+ resp.SupplementTaskID = receipts[0].TaskID+ resp.SupplementStatus = receipts[0].Status+ resp.SupplementFailureReason = receipts[0].FailureReason+ resp.SupplementDeliveredAt = receipts[0].DeliveredAt+}++// steerCommentAgentTriggers binds a member comment to the turn its author+// chose for each recipient. A bound agent leaves the enqueue list: that turn+// receives the comment instead of a follow-up run. A chosen turn that has+// ended, has not started, or cannot take additional input is never swapped+// for another turn of the same agent; that recipient keeps its normal+// queued / coalesced / deferred handling, so losing a race never drops or+// misdirects the comment.+func (h *Handler) steerCommentAgentTriggers(ctx context.Context, issue db.Issue, comment db.Comment, actorType string, triggers []commentAgentTrigger, steerTaskIDs []pgtype.UUID) ([]commentAgentTrigger, map[string]commentEnqueueResult) {+ if len(steerTaskIDs) == 0 || len(triggers) == 0 || actorType != "member" {+ return triggers, nil+ }+ // Each chosen turn names its agent; only a turn of this issue counts.+ chosen := make(map[string]pgtype.UUID, len(steerTaskIDs))+ for _, taskID := range steerTaskIDs {+ task, err := h.Queries.GetAgentTask(ctx, taskID)+ if err != nil || task.IssueID != issue.ID {+ continue+ }+ chosen[uuidToString(task.AgentID)] = task.ID+ }+ kept := make([]commentAgentTrigger, 0, len(triggers))+ steered := make(map[string]commentEnqueueResult)+ for _, trigger := range triggers {+ agentID := uuidToString(trigger.Agent.ID)+ taskID, ok := chosen[agentID]+ if !ok {+ kept = append(kept, trigger)+ continue+ }+ // The comment is its own request id: it binds to a turn at most once.+ bound, err := h.Queries.BindCommentTaskSupplement(ctx, db.BindCommentTaskSupplementParams{+ TaskID: taskID, IssueID: issue.ID, AgentID: trigger.Agent.ID, WorkspaceID: issue.WorkspaceID,+ CommentID: comment.ID, AuthorID: comment.AuthorID, ClientRequestID: comment.ID,+ })+ if err != nil {+ if !errors.Is(err, pgx.ErrNoRows) {+ slog.Warn("steer comment into running turn failed",+ "issue_id", uuidToString(issue.ID), "comment_id", uuidToString(comment.ID), "task_id", uuidToString(taskID), "error", err)+ }+ kept = append(kept, trigger)+ continue+ }+ steered[agentID] = commentEnqueueResult{status: DispatchSteered, reason: ReasonSteered}+ if h.DaemonTaskSupplement != nil && bound.RuntimeID.Valid {+ h.DaemonTaskSupplement.NotifyTaskSupplementAvailable(uuidToString(bound.RuntimeID), uuidToString(bound.TaskID))+ }+ }+ if len(steered) > 0 {+ h.publishCommentSupplementUpdate(ctx, issue.WorkspaceID, comment.ID)+ }+ return kept, steered}func (h *Handler) loadTaskSupplementTarget(w http.ResponseWriter, r *http.Request) (db.Issue, db.AgentTaskQueue, pgtype.UUID, bool) {@@ -212,10 +307,13 @@ func (h *Handler) CreateTaskSupplement(w http.ResponseWriter, r *http.Request) {}resp := commentToResponse(comment, nil, nil)resp.IssueRevision = created.IssueRevision- resp.SupplementTaskID = uuidToString(created.SupplementTaskID)- resp.SupplementStatus = created.SupplementStatus- resp.SupplementFailureReason = textToPtr(created.SupplementFailureReason)- resp.SupplementDeliveredAt = timestampToPtr(created.SupplementDeliveredAt)+ applyCommentSupplements(&resp, []CommentSupplementResponse{{+ TaskID: uuidToString(created.SupplementTaskID),+ AgentID: uuidToString(task.AgentID),+ Status: created.SupplementStatus,+ FailureReason: textToPtr(created.SupplementFailureReason),+ DeliveredAt: timestampToPtr(created.SupplementDeliveredAt),+ }})h.publish(protocol.EventCommentCreated, uuidToString(issue.WorkspaceID), "member", uuidToString(authorID), map[string]any{"comment": resp, "issue_title": issue.Title, "issue_revision": created.IssueRevision,})@@ -239,7 +337,7 @@ func (h *Handler) writeExistingTaskSupplement(w http.ResponseWriter, r *http.Reqreturn}resp := commentToResponse(comment, nil, nil)- applySupplementReceipt(&resp, existing)+ applyCommentSupplements(&resp, h.listCommentSupplements(r.Context(), existing.WorkspaceID, []pgtype.UUID{existing.CommentID})[uuidToString(existing.CommentID)])writeJSON(w, http.StatusOK, resp)}@@ -256,10 +354,10 @@ func (h *Handler) RetryTaskSupplement(w http.ResponseWriter, r *http.Request) {CommentID: commentID, WorkspaceID: issue.WorkspaceID, TaskID: task.ID, IssueID: issue.ID,})if errors.Is(err, pgx.ErrNoRows) {- existing, loadErr := h.Queries.GetTaskSupplementByComment(r.Context(), db.GetTaskSupplementByCommentParams{- CommentID: commentID, WorkspaceID: issue.WorkspaceID,+ existing, loadErr := h.Queries.GetTaskSupplementForRun(r.Context(), db.GetTaskSupplementForRunParams{+ CommentID: commentID, TaskID: task.ID, WorkspaceID: issue.WorkspaceID,})- if loadErr == nil && existing.TaskID == task.ID && existing.Status == "pending" {+ if loadErr == nil && existing.Status == "pending" {row = existing // duplicate retry is an idempotent successerr = nil}@@ -354,13 +452,19 @@ func stableTaskSupplementFailureReason(reason string) string {}func (h *Handler) publishTaskSupplementUpdate(r *http.Request, row db.TaskSupplement) {- comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{- ID: row.CommentID, WorkspaceID: row.WorkspaceID,+ h.publishCommentSupplementUpdate(r.Context(), row.WorkspaceID, row.CommentID)+}++// publishCommentSupplementUpdate rebroadcasts a comment with every receipt it+// carries, so a change to one run's delivery never hides another run's.+func (h *Handler) publishCommentSupplementUpdate(ctx context.Context, workspaceID, commentID pgtype.UUID) {+ comment, err := h.Queries.GetCommentInWorkspace(ctx, db.GetCommentInWorkspaceParams{+ ID: commentID, WorkspaceID: workspaceID,})if err != nil {return}resp := commentToResponse(comment, nil, nil)- applySupplementReceipt(&resp, row)- h.publish(protocol.EventCommentUpdated, uuidToString(row.WorkspaceID), "system", "", map[string]any{"comment": resp})+ applyCommentSupplements(&resp, h.listCommentSupplements(ctx, workspaceID, []pgtype.UUID{commentID})[uuidToString(commentID)])+ h.publish(protocol.EventCommentUpdated, uuidToString(workspaceID), "system", "", map[string]any{"comment": resp})}diff --git a/server/internal/handler/task_supplement_test.go b/server/internal/handler/task_supplement_test.goindex 728192cdc0..eefd59f04a 100644--- a/server/internal/handler/task_supplement_test.go+++ b/server/internal/handler/task_supplement_test.go@@ -266,8 +266,8 @@ func TestTaskSupplementCompletionDoesNotReplayBoundComments(t *testing.T) {map[string]any{"output": "done"}, testWorkspaceID, "legit-daemon")testutil.Call(t, testHandler.CompleteTask, withURLParam(req, "taskId", fixture.taskID)).Want(http.StatusOK)if status == "pending" || status == "delivering" {- receipt, err := testHandler.Queries.GetTaskSupplementByComment(t.Context(), db.GetTaskSupplementByCommentParams{- CommentID: parseUUID(supplement.ID), WorkspaceID: parseUUID(testWorkspaceID),+ receipt, err := testHandler.Queries.GetTaskSupplementForRun(t.Context(), db.GetTaskSupplementForRunParams{+ CommentID: parseUUID(supplement.ID), TaskID: parseUUID(fixture.taskID), WorkspaceID: parseUUID(testWorkspaceID),})if err != nil || receipt.Status != "failed" || receipt.FailureReason.String != protocol.TaskSupplementFailureTurnEnded {t.Fatalf("completion did not settle pending delivery: %#v: %v", receipt, err)@@ -530,8 +530,8 @@ func TestTaskSupplementStopRemainsIndependent(t *testing.T) {cancelReq := withURLParams(newRequest(http.MethodPost, "/cancel", nil),"id", fixture.issueID, "taskId", fixture.taskID)testutil.Call(t, testHandler.CancelTask, cancelReq).Want(http.StatusOK)- receipt, err := testHandler.Queries.GetTaskSupplementByComment(context.Background(), db.GetTaskSupplementByCommentParams{- CommentID: parseUUID(comment.ID), WorkspaceID: parseUUID(testWorkspaceID),+ receipt, err := testHandler.Queries.GetTaskSupplementForRun(context.Background(), db.GetTaskSupplementForRunParams{+ CommentID: parseUUID(comment.ID), TaskID: parseUUID(fixture.taskID), WorkspaceID: parseUUID(testWorkspaceID),})if err != nil || receipt.Status != "failed" || receipt.FailureReason.String != "turn_ended" {t.Fatalf("stop receipt = %#v, err %v", receipt, err)@@ -551,8 +551,8 @@ func TestTaskSupplementFailureSettlesPendingReceipt(t *testing.T) {if w := failTaskViaHandler(t, fixture.taskID); w.Code != http.StatusOK {t.Fatalf("fail task: status %d: %s", w.Code, w.Body.String())}- receipt, err := testHandler.Queries.GetTaskSupplementByComment(t.Context(), db.GetTaskSupplementByCommentParams{- CommentID: parseUUID(comment.ID), WorkspaceID: parseUUID(testWorkspaceID),+ receipt, err := testHandler.Queries.GetTaskSupplementForRun(t.Context(), db.GetTaskSupplementForRunParams{+ CommentID: parseUUID(comment.ID), TaskID: parseUUID(fixture.taskID), WorkspaceID: parseUUID(testWorkspaceID),})if err != nil || receipt.Status != "failed" || receipt.FailureReason.String != protocol.TaskSupplementFailureTurnEnded {t.Fatalf("failed task receipt = %#v, err %v", receipt, err)diff --git a/server/internal/handler/trigger_test.go b/server/internal/handler/trigger_test.goindex 61295747d5..4aa58c402d 100644--- a/server/internal/handler/trigger_test.go+++ b/server/internal/handler/trigger_test.go@@ -113,5 +113,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, memberID, nil)+ h.triggerTasksForComment(context.Background(), issue, comment, nil, "member", memberID, memberID, nil, nil)}diff --git a/server/migrations/548_task_supplement_comment_task_index.down.sql b/server/migrations/548_task_supplement_comment_task_index.down.sqlnew file mode 100644index 0000000000..c30435a8d5--- /dev/null+++ b/server/migrations/548_task_supplement_comment_task_index.down.sql@@ -0,0 +1,4 @@+-- Restore single-comment uniqueness. This fails while any comment is still+-- bound to several runs; remove those extra receipts before rolling back.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS task_supplement_comment_uidx+ ON task_supplement (comment_id);diff --git a/server/migrations/548_task_supplement_comment_task_index.up.sql b/server/migrations/548_task_supplement_comment_task_index.up.sqlnew file mode 100644index 0000000000..cacd84dab3--- /dev/null+++ b/server/migrations/548_task_supplement_comment_task_index.up.sql@@ -0,0 +1,4 @@+-- One comment can steer several running agents at once, so a delivery receipt+-- is identified by the (comment, run) pair instead of by the comment alone.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS task_supplement_comment_task_uidx+ ON task_supplement (comment_id, task_id);diff --git a/server/migrations/549_task_supplement_comment_task_primary_key.down.sql b/server/migrations/549_task_supplement_comment_task_primary_key.down.sqlnew file mode 100644index 0000000000..fdfccd0fd1--- /dev/null+++ b/server/migrations/549_task_supplement_comment_task_primary_key.down.sql@@ -0,0 +1,3 @@+-- PostgreSQL drops the attached (comment_id, task_id) index with the constraint;+-- 548 down then restores single-comment uniqueness.+ALTER TABLE task_supplement DROP CONSTRAINT IF EXISTS task_supplement_pkey;diff --git a/server/migrations/549_task_supplement_comment_task_primary_key.up.sql b/server/migrations/549_task_supplement_comment_task_primary_key.up.sqlnew file mode 100644index 0000000000..dfe0f02416--- /dev/null+++ b/server/migrations/549_task_supplement_comment_task_primary_key.up.sql@@ -0,0 +1,12 @@+-- Reuse the concurrently built index. Dropping the old constraint also drops+-- its single-column index; lookups by comment_id use the new key's prefix.+-- Daemons claim receipts continuously, so fail fast and retry on the next run+-- rather than queueing their claims behind a pending ACCESS EXCLUSIVE lock.+SET LOCAL lock_timeout = '2s';+SET LOCAL statement_timeout = '10s';++ALTER TABLE task_supplement+ DROP CONSTRAINT IF EXISTS task_supplement_pkey,+ ADD CONSTRAINT task_supplement_pkey PRIMARY KEY USING INDEX task_supplement_comment_task_uidx;+-- Left behind by a previous rollback (548 down); it would keep one run per comment.+DROP INDEX IF EXISTS task_supplement_comment_uidx;diff --git a/server/migrations/550_comment_suppressed_agents.down.sql b/server/migrations/550_comment_suppressed_agents.down.sqlnew file mode 100644index 0000000000..9dbb6992b3--- /dev/null+++ b/server/migrations/550_comment_suppressed_agents.down.sql@@ -0,0 +1 @@+ALTER TABLE comment DROP COLUMN IF EXISTS suppressed_agent_ids;diff --git a/server/migrations/550_comment_suppressed_agents.up.sql b/server/migrations/550_comment_suppressed_agents.up.sqlnew file mode 100644index 0000000000..5292cb5781--- /dev/null+++ b/server/migrations/550_comment_suppressed_agents.up.sql@@ -0,0 +1,11 @@+-- The agents an author chose not to start for this comment, so completion+-- replay honors that choice too instead of waking them once their run ends.+--+-- Nullable with no default, so this is a metadata-only change. The runner+-- sends this file as one implicit transaction: bound lock acquisition and+-- execution so it fails fast and retries on the next run rather than parking a+-- pending ACCESS EXCLUSIVE lock in front of every comment query.+SET LOCAL lock_timeout = '2s';+SET LOCAL statement_timeout = '10s';++ALTER TABLE comment ADD COLUMN IF NOT EXISTS suppressed_agent_ids UUID[] NULL;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex f920a9d111..0fb50fe8ac 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -5775,7 +5775,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC}const listPendingDelegatedFailureRecoveries = `-- name: ListPendingDelegatedFailureRecoveries :many-SELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id, recovery.via_plugin_id, recovery.revision, recovery.recovery_settled_at, recovery.deleted_at+SELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id, recovery.via_plugin_id, recovery.revision, recovery.recovery_settled_at, recovery.deleted_at, recovery.suppressed_agent_idsFROM comment recoveryJOIN agent_task_queue failed ON failed.id = recovery.source_task_idJOIN agent_task_queue source ON source.id = failed.delegated_from_task_id@@ -5893,6 +5893,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,); err != nil {return nil, err}diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex 754ba567b0..330803cb5c 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -17,7 +17,7 @@ SET revision = revision + 1,updated_at = now()WHERE id = $1AND workspace_id = $2-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids`type BumpCommentRevisionParams struct {@@ -48,6 +48,7 @@ func (q *Queries) BumpCommentRevision(ctx context.Context, arg BumpCommentRevisi&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}@@ -87,7 +88,7 @@ UPDATE comment SETWHERE comment.id IN (SELECT id FROM descendants)AND comment.id <> $1AND comment.resolved_at IS NOT NULL-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids`type ClearOtherThreadResolutionsParams struct {@@ -135,6 +136,7 @@ func (q *Queries) ClearOtherThreadResolutions(ctx context.Context, arg ClearOthe&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,); err != nil {return nil, err}@@ -230,51 +232,53 @@ WITH touched_issue AS (WHERE issue.id = $1 AND issue.workspace_id = $2RETURNING issue.id, issue.workspace_id, issue.revision), inserted_comment AS (- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id, id)- SELECT ti.id, ti.workspace_id, $3, $4, $5, $6, $7, $8, $9, $10, COALESCE($11::uuid, gen_random_uuid())+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id, suppressed_agent_ids, id)+ SELECT ti.id, ti.workspace_id, $3, $4, $5, $6, $7, $8, $9, $10, $11::uuid[], COALESCE($12::uuid, gen_random_uuid())FROM touched_issue ti- RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at+ RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids)-SELECT inserted_comment.id, inserted_comment.issue_id, inserted_comment.author_type, inserted_comment.author_id, inserted_comment.content, inserted_comment.type, inserted_comment.created_at, inserted_comment.updated_at, inserted_comment.parent_id, inserted_comment.workspace_id, inserted_comment.resolved_at, inserted_comment.resolved_by_type, inserted_comment.resolved_by_id, inserted_comment.source_task_id, inserted_comment.quick_action_id, inserted_comment.via_plugin_id, inserted_comment.revision, inserted_comment.recovery_settled_at, inserted_comment.deleted_at, touched_issue.revision AS issue_revision+SELECT inserted_comment.id, inserted_comment.issue_id, inserted_comment.author_type, inserted_comment.author_id, inserted_comment.content, inserted_comment.type, inserted_comment.created_at, inserted_comment.updated_at, inserted_comment.parent_id, inserted_comment.workspace_id, inserted_comment.resolved_at, inserted_comment.resolved_by_type, inserted_comment.resolved_by_id, inserted_comment.source_task_id, inserted_comment.quick_action_id, inserted_comment.via_plugin_id, inserted_comment.revision, inserted_comment.recovery_settled_at, inserted_comment.deleted_at, inserted_comment.suppressed_agent_ids, touched_issue.revision AS issue_revisionFROM inserted_commentJOIN touched_issue ON touched_issue.id = inserted_comment.issue_id`type CreateCommentParams struct {- IssueID pgtype.UUID `json:"issue_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- AuthorType string `json:"author_type"`- AuthorID pgtype.UUID `json:"author_id"`- Content string `json:"content"`- Type string `json:"type"`- ParentID pgtype.UUID `json:"parent_id"`- SourceTaskID pgtype.UUID `json:"source_task_id"`- QuickActionID pgtype.UUID `json:"quick_action_id"`- ViaPluginID pgtype.UUID `json:"via_plugin_id"`- ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ ParentID pgtype.UUID `json:"parent_id"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ QuickActionID pgtype.UUID `json:"quick_action_id"`+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`+ SuppressedAgentIds []pgtype.UUID `json:"suppressed_agent_ids"`+ ID pgtype.UUID `json:"id"`}type CreateCommentRow struct {- ID pgtype.UUID `json:"id"`- IssueID pgtype.UUID `json:"issue_id"`- AuthorType string `json:"author_type"`- AuthorID pgtype.UUID `json:"author_id"`- Content string `json:"content"`- Type string `json:"type"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`- ParentID pgtype.UUID `json:"parent_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- ResolvedAt pgtype.Timestamptz `json:"resolved_at"`- ResolvedByType pgtype.Text `json:"resolved_by_type"`- ResolvedByID pgtype.UUID `json:"resolved_by_id"`- SourceTaskID pgtype.UUID `json:"source_task_id"`- QuickActionID pgtype.UUID `json:"quick_action_id"`- ViaPluginID pgtype.UUID `json:"via_plugin_id"`- Revision int64 `json:"revision"`- RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`- DeletedAt pgtype.Timestamptz `json:"deleted_at"`- IssueRevision int64 `json:"issue_revision"`+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ParentID pgtype.UUID `json:"parent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`+ ResolvedByType pgtype.Text `json:"resolved_by_type"`+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ QuickActionID pgtype.UUID `json:"quick_action_id"`+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`+ Revision int64 `json:"revision"`+ RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`+ SuppressedAgentIds []pgtype.UUID `json:"suppressed_agent_ids"`+ IssueRevision int64 `json:"issue_revision"`}// A new comment counts as activity on its issue, so the same statement bumps@@ -305,6 +309,7 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (Carg.SourceTaskID,arg.QuickActionID,arg.ViaPluginID,+ arg.SuppressedAgentIds,arg.ID,)var i CreateCommentRow@@ -328,6 +333,7 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,&i.IssueRevision,)return i, err@@ -389,7 +395,7 @@ func (q *Queries) DeleteReplylessCommentTombstone(ctx context.Context, arg Delet}const getComment = `-- name: GetComment :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM commentWHERE id = $1`@@ -416,12 +422,13 @@ func (q *Queries) GetComment(ctx context.Context, id pgtype.UUID) (Comment, erro&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}const getCommentInWorkspace = `-- name: GetCommentInWorkspace :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM commentWHERE id = $1 AND workspace_id = $2`@@ -453,12 +460,13 @@ func (q *Queries) GetCommentInWorkspace(ctx context.Context, arg GetCommentInWor&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}const getDelegatedFailureRecoveryComment = `-- name: GetDelegatedFailureRecoveryComment :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM commentWHERE issue_id = $1AND workspace_id = $2AND author_type = 'system'@@ -501,12 +509,13 @@ func (q *Queries) GetDelegatedFailureRecoveryComment(ctx context.Context, arg Ge&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}const getDelegatedFailureRecoveryExhaustionComment = `-- name: GetDelegatedFailureRecoveryExhaustionComment :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM commentWHERE issue_id = $1AND workspace_id = $2AND author_type = 'system'@@ -549,12 +558,13 @@ func (q *Queries) GetDelegatedFailureRecoveryExhaustionComment(ctx context.Conte&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}const getLatestMemberCommentForIssueSince = `-- name: GetLatestMemberCommentForIssueSince :one-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM commentWHERE issue_id = $1AND author_type = 'member'AND created_at > $2@@ -600,6 +610,7 @@ func (q *Queries) GetLatestMemberCommentForIssueSince(ctx context.Context, arg G&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}@@ -614,7 +625,7 @@ WITH RECURSIVE root_of AS (FROM comment pJOIN root_of r ON p.id = r.parent_id)-SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at FROM comment c+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at, c.suppressed_agent_ids FROM comment cWHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1)`@@ -651,6 +662,7 @@ func (q *Queries) GetThreadRoot(ctx context.Context, arg GetThreadRootParams) (C&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}@@ -700,7 +712,7 @@ func (q *Queries) HasAgentRepliedInThread(ctx context.Context, arg HasAgentRepli}const listChildCommentsForParents = `-- name: ListChildCommentsForParents :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM commentWHERE parent_id = ANY($1::uuid[])AND issue_id = $2AND workspace_id = $3@@ -763,6 +775,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChild&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,); err != nil {return nil, err}@@ -776,7 +789,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChildconst listCommentAncestorPath = `-- name: ListCommentAncestorPath :manyWITH RECURSIVE ancestor_path AS (- SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at, ARRAY[c.id]::uuid[] AS visited_ids, 1::integer AS depth, false AS cycle+ SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at, c.suppressed_agent_ids, ARRAY[c.id]::uuid[] AS visited_ids, 1::integer AS depth, false AS cycleFROM comment cWHERE c.id = $1AND c.workspace_id = $2@@ -784,7 +797,7 @@ WITH RECURSIVE ancestor_path AS (UNION ALL- SELECT parent.id, parent.issue_id, parent.author_type, parent.author_id, parent.content, parent.type, parent.created_at, parent.updated_at, parent.parent_id, parent.workspace_id, parent.resolved_at, parent.resolved_by_type, parent.resolved_by_id, parent.source_task_id, parent.quick_action_id, parent.via_plugin_id, parent.revision, parent.recovery_settled_at, parent.deleted_at,+ SELECT parent.id, parent.issue_id, parent.author_type, parent.author_id, parent.content, parent.type, parent.created_at, parent.updated_at, parent.parent_id, parent.workspace_id, parent.resolved_at, parent.resolved_by_type, parent.resolved_by_id, parent.source_task_id, parent.quick_action_id, parent.via_plugin_id, parent.revision, parent.recovery_settled_at, parent.deleted_at, parent.suppressed_agent_ids,path.visited_ids || parent.id,path.depth + 1,parent.id = ANY(path.visited_ids)@@ -875,7 +888,7 @@ func (q *Queries) ListCommentAncestorPath(ctx context.Context, arg ListCommentAnconst listCommentThreadHistory = `-- name: ListCommentThreadHistory :manyWITH RECURSIVE thread_history AS (- SELECT root.id, root.issue_id, root.author_type, root.author_id, root.content, root.type, root.created_at, root.updated_at, root.parent_id, root.workspace_id, root.resolved_at, root.resolved_by_type, root.resolved_by_id, root.source_task_id, root.quick_action_id, root.via_plugin_id, root.revision, root.recovery_settled_at, root.deleted_at+ SELECT root.id, root.issue_id, root.author_type, root.author_id, root.content, root.type, root.created_at, root.updated_at, root.parent_id, root.workspace_id, root.resolved_at, root.resolved_by_type, root.resolved_by_id, root.source_task_id, root.quick_action_id, root.via_plugin_id, root.revision, root.recovery_settled_at, root.deleted_at, root.suppressed_agent_idsFROM comment rootWHERE root.id = $2AND root.workspace_id = $3@@ -888,7 +901,7 @@ WITH RECURSIVE thread_history AS (UNION ALL- SELECT child.id, child.issue_id, child.author_type, child.author_id, child.content, child.type, child.created_at, child.updated_at, child.parent_id, child.workspace_id, child.resolved_at, child.resolved_by_type, child.resolved_by_id, child.source_task_id, child.quick_action_id, child.via_plugin_id, child.revision, child.recovery_settled_at, child.deleted_at+ SELECT child.id, child.issue_id, child.author_type, child.author_id, child.content, child.type, child.created_at, child.updated_at, child.parent_id, child.workspace_id, child.resolved_at, child.resolved_by_type, child.resolved_by_id, child.source_task_id, child.quick_action_id, child.via_plugin_id, child.revision, child.recovery_settled_at, child.deleted_at, child.suppressed_agent_idsFROM comment childJOIN thread_history parent ON child.parent_id = parent.idWHERE child.workspace_id = $3@@ -898,7 +911,7 @@ WITH RECURSIVE thread_history AS ($6::uuid))-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_idsFROM thread_historyORDER BY created_at, idLIMIT $1@@ -914,25 +927,26 @@ type ListCommentThreadHistoryParams struct {}type ListCommentThreadHistoryRow struct {- ID pgtype.UUID `json:"id"`- IssueID pgtype.UUID `json:"issue_id"`- AuthorType string `json:"author_type"`- AuthorID pgtype.UUID `json:"author_id"`- Content string `json:"content"`- Type string `json:"type"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`- ParentID pgtype.UUID `json:"parent_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- ResolvedAt pgtype.Timestamptz `json:"resolved_at"`- ResolvedByType pgtype.Text `json:"resolved_by_type"`- ResolvedByID pgtype.UUID `json:"resolved_by_id"`- SourceTaskID pgtype.UUID `json:"source_task_id"`- QuickActionID pgtype.UUID `json:"quick_action_id"`- ViaPluginID pgtype.UUID `json:"via_plugin_id"`- Revision int64 `json:"revision"`- RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`- DeletedAt pgtype.Timestamptz `json:"deleted_at"`+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ParentID pgtype.UUID `json:"parent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`+ ResolvedByType pgtype.Text `json:"resolved_by_type"`+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ QuickActionID pgtype.UUID `json:"quick_action_id"`+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`+ Revision int64 `json:"revision"`+ RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`+ SuppressedAgentIds []pgtype.UUID `json:"suppressed_agent_ids"`}// Capture the anchor comment's complete chronological thread through that@@ -974,6 +988,7 @@ func (q *Queries) ListCommentThreadHistory(ctx context.Context, arg ListCommentT&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,); err != nil {return nil, err}@@ -986,7 +1001,7 @@ func (q *Queries) ListCommentThreadHistory(ctx context.Context, arg ListCommentT}const listCommentsByIDsForIssue = `-- name: ListCommentsByIDsForIssue :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM commentWHERE id = ANY($1::uuid[])AND issue_id = $2AND workspace_id = $3@@ -1037,6 +1052,7 @@ func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListComment&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,); err != nil {return nil, err}@@ -1049,8 +1065,8 @@ func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListComment}const listCommentsForIssue = `-- name: ListCommentsForIssue :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM (- SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM (+ SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM commentWHERE issue_id = $1 AND workspace_id = $2ORDER BY created_at DESC, id DESCLIMIT $3@@ -1110,6 +1126,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,); err != nil {return nil, err}@@ -1122,7 +1139,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI}const listCommentsSinceForIssue = `-- name: ListCommentsSinceForIssue :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids FROM commentWHERE issue_id = $1 AND workspace_id = $2 AND created_at > $3ORDER BY created_at ASC, id ASCLIMIT $4@@ -1171,6 +1188,7 @@ func (q *Queries) ListCommentsSinceForIssue(ctx context.Context, arg ListComment&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,); err != nil {return nil, err}@@ -1332,22 +1350,28 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List}const listReconcilableCommentsForIssueSince = `-- name: ListReconcilableCommentsForIssueSince :many-SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at FROM comment c+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at, c.suppressed_agent_ids FROM comment cWHERE c.issue_id = $1AND (c.id = ANY($2::uuid[])OR comment_thread_root_id(c.id) = $3::uuid)-- A deleted comment is no longer input, even when replies keep its row.AND c.deleted_at IS NULL- -- Explicit supplements belong only to their bound run, regardless of- -- delivery status. Failed delivery must not become an automatic new run.+ -- A comment that steered this agent's running turn belongs to that turn,+ -- regardless of delivery status: failed delivery must not become an automatic+ -- new run. The same comment still reconciles normally for any other agent+ -- it addressed without steering.AND NOT EXISTS (SELECT 1 FROM task_supplement s+ JOIN agent_task_queue bound ON bound.id = s.task_idWHERE s.comment_id = c.id AND s.workspace_id = c.workspace_id+ AND bound.agent_id = $4)+ -- Nor does a comment whose author chose not to start this agent for it.+ AND NOT COALESCE($4::uuid = ANY(c.suppressed_agent_ids), false)AND ((c.author_type IN ('member', 'agent')- AND (c.created_at > $4 OR c.id = ANY($2::uuid[]))+ AND (c.created_at > $5 OR c.id = ANY($2::uuid[])))OR (c.author_type = 'system'@@ -1363,6 +1387,7 @@ type ListReconcilableCommentsForIssueSinceParams struct {IssueID pgtype.UUID `json:"issue_id"`PlannedCommentIds []pgtype.UUID `json:"planned_comment_ids"`CommentThreadID pgtype.UUID `json:"comment_thread_id"`+ AgentID pgtype.UUID `json:"agent_id"`Since pgtype.Timestamptz `json:"since"`}@@ -1397,6 +1422,7 @@ func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, argarg.IssueID,arg.PlannedCommentIds,arg.CommentThreadID,+ arg.AgentID,arg.Since,)if err != nil {@@ -1426,6 +1452,7 @@ func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,); err != nil {return nil, err}@@ -1898,7 +1925,7 @@ WITH locked_issue AS MATERIALIZED (-- folding/re-evaluation and is not, by itself, a lock-order guarantee.SELECT count(*) AS locked_count FROM locked_issue)-SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at, comment.deleted_at+SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at, comment.deleted_at, comment.suppressed_agent_idsFROM commentCROSS JOIN issue_fenceWHERE comment.id = $1 AND comment.workspace_id = $2@@ -1947,6 +1974,7 @@ func (q *Queries) LockCommentForDelete(ctx context.Context, arg LockCommentForDe&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}@@ -1962,7 +1990,7 @@ WITH locked_issue AS MATERIALIZED (), issue_fence AS MATERIALIZED (SELECT count(*) AS locked_count FROM locked_issue)-SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at, comment.deleted_at+SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at, comment.deleted_at, comment.suppressed_agent_idsFROM commentCROSS JOIN issue_fenceWHERE comment.id = $1 AND comment.workspace_id = $2@@ -2005,6 +2033,7 @@ func (q *Queries) LockLiveComment(ctx context.Context, arg LockLiveCommentParams&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}@@ -2018,7 +2047,7 @@ UPDATE comment SETupdated_at = CASE WHEN resolved_at IS NULL THEN now() ELSE updated_at ENDWHERE id = $1AND deleted_at IS NULL-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids`type ResolveCommentParams struct {@@ -2053,6 +2082,7 @@ func (q *Queries) ResolveComment(ctx context.Context, arg ResolveCommentParams)&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}@@ -2068,7 +2098,7 @@ UPDATE comment SETupdated_at = now()WHERE id = $1 AND workspace_id = $2AND deleted_at IS NULL-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids`type TombstoneCommentParams struct {@@ -2104,6 +2134,7 @@ func (q *Queries) TombstoneComment(ctx context.Context, arg TombstoneCommentPara&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}@@ -2139,7 +2170,7 @@ UPDATE comment SETrevision = revision + CASE WHEN resolved_at IS NOT NULL THEN 1 ELSE 0 END,updated_at = CASE WHEN resolved_at IS NOT NULL THEN now() ELSE updated_at ENDWHERE id = $1-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids`// Idempotent: a no-op clear (already unresolved) just returns the row.@@ -2166,6 +2197,7 @@ func (q *Queries) UnresolveComment(ctx context.Context, id pgtype.UUID) (Comment&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,)return i, err}@@ -2188,7 +2220,7 @@ WITH locked_issue AS MATERIALIZED (-- prevents folding/re-evaluation; it does not itself establish lock order.SELECT count(*) AS locked_count FROM locked_issue), target AS MATERIALIZED (- SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at, comment.deleted_at,+ SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at, comment.deleted_at, comment.suppressed_agent_ids,ROW(comment.content, comment.source_task_id) IS DISTINCT FROMROW($2, $3::uuid) AS did_changeFROM comment@@ -2208,6 +2240,11 @@ WITH locked_issue AS MATERIALIZED (UPDATE comment SETcontent = $2,source_task_id = $3::uuid,+ -- New text re-decides which agents it must not start, under the same+ -- revision check as the text itself.+ suppressed_agent_ids = CASE WHEN target.content IS DISTINCT FROM $2+ THEN $6::uuid[]+ ELSE comment.suppressed_agent_ids END,revision = comment.revision + CASE WHEN target.did_change THEN 1 ELSE 0 END,updated_at = CASE WHEN target.did_change THEN now() ELSE comment.updated_at ENDFROM target@@ -2241,11 +2278,12 @@ FROM updated_comment`type UpdateCommentParams struct {- ID pgtype.UUID `json:"id"`- Content string `json:"content"`- SourceTaskID pgtype.UUID `json:"source_task_id"`- ExpectedRevision pgtype.Int8 `json:"expected_revision"`- ContentBase pgtype.Text `json:"content_base"`+ ID pgtype.UUID `json:"id"`+ Content string `json:"content"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ ExpectedRevision pgtype.Int8 `json:"expected_revision"`+ ContentBase pgtype.Text `json:"content_base"`+ SuppressedAgentIds []pgtype.UUID `json:"suppressed_agent_ids"`}type UpdateCommentRow struct {@@ -2277,6 +2315,7 @@ func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (Uarg.SourceTaskID,arg.ExpectedRevision,arg.ContentBase,+ arg.SuppressedAgentIds,)var i UpdateCommentRowerr := row.Scan(diff --git a/server/pkg/db/generated/comment_row.go b/server/pkg/db/generated/comment_row.goindex 1037b591d5..848e43b138 100644--- a/server/pkg/db/generated/comment_row.go+++ b/server/pkg/db/generated/comment_row.go@@ -5,24 +5,25 @@ package db// row's IssueRevision remains available separately for owner-cache coherence.func (r CreateCommentRow) Comment() Comment {return Comment{- ID: r.ID,- IssueID: r.IssueID,- AuthorType: r.AuthorType,- AuthorID: r.AuthorID,- Content: r.Content,- Type: r.Type,- CreatedAt: r.CreatedAt,- UpdatedAt: r.UpdatedAt,- ParentID: r.ParentID,- WorkspaceID: r.WorkspaceID,- ResolvedAt: r.ResolvedAt,- ResolvedByType: r.ResolvedByType,- ResolvedByID: r.ResolvedByID,- SourceTaskID: r.SourceTaskID,- QuickActionID: r.QuickActionID,- ViaPluginID: r.ViaPluginID,- Revision: r.Revision,- DeletedAt: r.DeletedAt,+ ID: r.ID,+ IssueID: r.IssueID,+ AuthorType: r.AuthorType,+ AuthorID: r.AuthorID,+ Content: r.Content,+ Type: r.Type,+ CreatedAt: r.CreatedAt,+ UpdatedAt: r.UpdatedAt,+ ParentID: r.ParentID,+ WorkspaceID: r.WorkspaceID,+ ResolvedAt: r.ResolvedAt,+ ResolvedByType: r.ResolvedByType,+ ResolvedByID: r.ResolvedByID,+ SourceTaskID: r.SourceTaskID,+ QuickActionID: r.QuickActionID,+ ViaPluginID: r.ViaPluginID,+ Revision: r.Revision,+ DeletedAt: r.DeletedAt,+ SuppressedAgentIds: r.SuppressedAgentIds,}}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 50d6cdce97..29f6808ce4 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -564,25 +564,26 @@ type ClientUsageDaily struct {}type Comment struct {- ID pgtype.UUID `json:"id"`- IssueID pgtype.UUID `json:"issue_id"`- AuthorType string `json:"author_type"`- AuthorID pgtype.UUID `json:"author_id"`- Content string `json:"content"`- Type string `json:"type"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`- ParentID pgtype.UUID `json:"parent_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- ResolvedAt pgtype.Timestamptz `json:"resolved_at"`- ResolvedByType pgtype.Text `json:"resolved_by_type"`- ResolvedByID pgtype.UUID `json:"resolved_by_id"`- SourceTaskID pgtype.UUID `json:"source_task_id"`- QuickActionID pgtype.UUID `json:"quick_action_id"`- ViaPluginID pgtype.UUID `json:"via_plugin_id"`- Revision int64 `json:"revision"`- RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`- DeletedAt pgtype.Timestamptz `json:"deleted_at"`+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ParentID pgtype.UUID `json:"parent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`+ ResolvedByType pgtype.Text `json:"resolved_by_type"`+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ QuickActionID pgtype.UUID `json:"quick_action_id"`+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`+ Revision int64 `json:"revision"`+ RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`+ SuppressedAgentIds []pgtype.UUID `json:"suppressed_agent_ids"`}type CommentReaction struct {diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.goindex 2bae874854..5ebd1c864e 100644--- a/server/pkg/db/generated/supplement.sql.go+++ b/server/pkg/db/generated/supplement.sql.go@@ -92,9 +92,98 @@ func (q *Queries) AckTaskSupplementFailed(ctx context.Context, arg AckTaskSupplereturn i, err}+const bindCommentTaskSupplement = `-- name: BindCommentTaskSupplement :one+WITH locked_task AS MATERIALIZED (+ SELECT t.id, t.issue_id, t.runtime_id+ FROM agent_task_queue t+ JOIN agent_runtime r ON r.id = t.runtime_id+ JOIN task_supplement_capability cap ON cap.task_id = t.id+ WHERE t.id = $1+ AND t.issue_id = $2+ AND t.agent_id = $3+ AND r.workspace_id = $4+ AND t.status = 'running'+ AND cap.capability = 'task-supplement-v1'+ AND r.provider IN ('codex', 'claude')+ FOR UPDATE OF t+), inserted AS (+ INSERT INTO task_supplement (+ task_id, workspace_id, issue_id, comment_id, author_id,+ client_request_id, status+ )+ SELECT t.id, $4, t.issue_id, $5, $6,+ $7, 'pending'+ FROM locked_task t+ RETURNING task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at+)+SELECT inserted.task_id, inserted.workspace_id, inserted.issue_id, inserted.comment_id, inserted.author_id, inserted.client_request_id, inserted.status, inserted.failure_reason, inserted.attempt_count, inserted.created_at, inserted.updated_at, inserted.delivered_at, locked_task.runtime_id+FROM inserted+JOIN locked_task ON locked_task.id = inserted.task_id+`++type BindCommentTaskSupplementParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ CommentID pgtype.UUID `json:"comment_id"`+ AuthorID pgtype.UUID `json:"author_id"`+ ClientRequestID pgtype.UUID `json:"client_request_id"`+}++type BindCommentTaskSupplementRow struct {+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ CommentID pgtype.UUID `json:"comment_id"`+ AuthorID pgtype.UUID `json:"author_id"`+ ClientRequestID pgtype.UUID `json:"client_request_id"`+ Status string `json:"status"`+ FailureReason pgtype.Text `json:"failure_reason"`+ AttemptCount int32 `json:"attempt_count"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+}++// Binds an ordinary member comment, already created through the normal comment+// path, to the exact running turn its author chose. Locking the task+// serializes against terminal transitions: when that turn ended first nothing+// is bound — never a later turn of the same agent — and the caller keeps the+// comment's normal trigger instead.+func (q *Queries) BindCommentTaskSupplement(ctx context.Context, arg BindCommentTaskSupplementParams) (BindCommentTaskSupplementRow, error) {+ row := q.db.QueryRow(ctx, bindCommentTaskSupplement,+ arg.TaskID,+ arg.IssueID,+ arg.AgentID,+ arg.WorkspaceID,+ arg.CommentID,+ arg.AuthorID,+ arg.ClientRequestID,+ )+ var i BindCommentTaskSupplementRow+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ &i.RuntimeID,+ )+ return i, err+}+const claimNextTaskSupplement = `-- name: ClaimNextTaskSupplement :oneWITH next AS MATERIALIZED (- SELECT s.comment_id+ SELECT s.comment_id, s.task_idFROM task_supplement sJOIN agent_task_queue t ON t.id = s.task_idJOIN task_supplement_capability cap ON cap.task_id = t.id@@ -113,6 +202,7 @@ WITH next AS MATERIALIZED (updated_at = now()FROM nextWHERE s.comment_id = next.comment_id+ AND s.task_id = next.task_idRETURNING s.task_id, s.workspace_id, s.issue_id, s.comment_id, s.author_id, s.client_request_id, s.status, s.failure_reason, s.attempt_count, s.created_at, s.updated_at, s.delivered_at)SELECT claimed.comment_id, claimed.attempt_count, c.content,@@ -141,6 +231,25 @@ func (q *Queries) ClaimNextTaskSupplement(ctx context.Context, taskID pgtype.UUIreturn i, err}+const commentHasTaskSupplement = `-- name: CommentHasTaskSupplement :one+SELECT EXISTS (+ SELECT 1 FROM task_supplement+ WHERE comment_id = $1 AND workspace_id = $2+) AS bound+`++type CommentHasTaskSupplementParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) CommentHasTaskSupplement(ctx context.Context, arg CommentHasTaskSupplementParams) (bool, error) {+ row := q.db.QueryRow(ctx, commentHasTaskSupplement, arg.CommentID, arg.WorkspaceID)+ var bound bool+ err := row.Scan(&bound)+ return bound, err+}+const createTaskSupplement = `-- name: CreateTaskSupplement :oneWITH locked_task AS MATERIALIZED (SELECT t.id, t.issue_id, t.agent_id, t.trigger_comment_id@@ -169,7 +278,7 @@ WITH locked_task AS MATERIALIZED (SELECT i.id, i.workspace_id, 'member', $4, $5, 'comment', t.trigger_comment_idFROM touched_issue iJOIN locked_task t ON t.issue_id = i.id- RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at+ RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at, suppressed_agent_ids), inserted_supplement AS (INSERT INTO task_supplement (task_id, workspace_id, issue_id, comment_id, author_id,@@ -183,7 +292,7 @@ WITH locked_task AS MATERIALIZED (JOIN inserted_comment c ON c.issue_id = i.idRETURNING task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at)-SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at, i.revision AS issue_revision,+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at, c.suppressed_agent_ids, i.revision AS issue_revision,s.task_id AS supplement_task_id, s.status AS supplement_status,s.failure_reason AS supplement_failure_reason,s.delivered_at AS supplement_delivered_at@@ -221,6 +330,7 @@ type CreateTaskSupplementRow struct {Revision int64 `json:"revision"`RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`DeletedAt pgtype.Timestamptz `json:"deleted_at"`+ SuppressedAgentIds []pgtype.UUID `json:"suppressed_agent_ids"`IssueRevision int64 `json:"issue_revision"`SupplementTaskID pgtype.UUID `json:"supplement_task_id"`SupplementStatus string `json:"supplement_status"`@@ -261,6 +371,7 @@ func (q *Queries) CreateTaskSupplement(ctx context.Context, arg CreateTaskSupple&i.Revision,&i.RecoverySettledAt,&i.DeletedAt,+ &i.SuppressedAgentIds,&i.IssueRevision,&i.SupplementTaskID,&i.SupplementStatus,@@ -285,36 +396,6 @@ func (q *Queries) DeleteTaskSupplementByComment(ctx context.Context, arg DeleteTreturn err}-const getTaskSupplementByComment = `-- name: GetTaskSupplementByComment :one-SELECT task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at FROM task_supplement-WHERE comment_id = $1 AND workspace_id = $2-`--type GetTaskSupplementByCommentParams struct {- CommentID pgtype.UUID `json:"comment_id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`-}--func (q *Queries) GetTaskSupplementByComment(ctx context.Context, arg GetTaskSupplementByCommentParams) (TaskSupplement, error) {- row := q.db.QueryRow(ctx, getTaskSupplementByComment, arg.CommentID, arg.WorkspaceID)- var i TaskSupplement- err := row.Scan(- &i.TaskID,- &i.WorkspaceID,- &i.IssueID,- &i.CommentID,- &i.AuthorID,- &i.ClientRequestID,- &i.Status,- &i.FailureReason,- &i.AttemptCount,- &i.CreatedAt,- &i.UpdatedAt,- &i.DeliveredAt,- )- return i, err-}-const getTaskSupplementByRequest = `-- name: GetTaskSupplementByRequest :oneSELECT s.task_id, s.workspace_id, s.issue_id, s.comment_id, s.author_id, s.client_request_id, s.status, s.failure_reason, s.attempt_count, s.created_at, s.updated_at, s.delivered_atFROM task_supplement s@@ -373,6 +454,37 @@ func (q *Queries) GetTaskSupplementCapability(ctx context.Context, taskID pgtypereturn i, err}+const getTaskSupplementForRun = `-- name: GetTaskSupplementForRun :one+SELECT task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at FROM task_supplement+WHERE comment_id = $1 AND task_id = $2 AND workspace_id = $3+`++type GetTaskSupplementForRunParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetTaskSupplementForRun(ctx context.Context, arg GetTaskSupplementForRunParams) (TaskSupplement, error) {+ row := q.db.QueryRow(ctx, getTaskSupplementForRun, arg.CommentID, arg.TaskID, arg.WorkspaceID)+ var i TaskSupplement+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ )+ return i, err+}+const listTaskSupplementMetadata = `-- name: ListTaskSupplementMetadata :manySELECT cap.task_id, cap.capability,COALESCE(array_agg(s.comment_id ORDER BY s.created_at, s.comment_id)@@ -416,9 +528,12 @@ func (q *Queries) ListTaskSupplementMetadata(ctx context.Context, arg ListTaskSu}const listTaskSupplementsByCommentIDs = `-- name: ListTaskSupplementsByCommentIDs :many-SELECT task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at FROM task_supplement-WHERE workspace_id = $1- AND comment_id = ANY($2::uuid[])+SELECT s.task_id, s.workspace_id, s.issue_id, s.comment_id, s.author_id, s.client_request_id, s.status, s.failure_reason, s.attempt_count, s.created_at, s.updated_at, s.delivered_at, t.agent_id+FROM task_supplement s+LEFT JOIN agent_task_queue t ON t.id = s.task_id+WHERE s.workspace_id = $1+ AND s.comment_id = ANY($2::uuid[])+ORDER BY s.created_at, s.task_id`type ListTaskSupplementsByCommentIDsParams struct {@@ -426,15 +541,33 @@ type ListTaskSupplementsByCommentIDsParams struct {CommentIds []pgtype.UUID `json:"comment_ids"`}-func (q *Queries) ListTaskSupplementsByCommentIDs(ctx context.Context, arg ListTaskSupplementsByCommentIDsParams) ([]TaskSupplement, error) {+type ListTaskSupplementsByCommentIDsRow struct {+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ CommentID pgtype.UUID `json:"comment_id"`+ AuthorID pgtype.UUID `json:"author_id"`+ ClientRequestID pgtype.UUID `json:"client_request_id"`+ Status string `json:"status"`+ FailureReason pgtype.Text `json:"failure_reason"`+ AttemptCount int32 `json:"attempt_count"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`+ AgentID pgtype.UUID `json:"agent_id"`+}++// One comment may steer several runs; receipts carry the run's agent so a+// client can say whose turn received it.+func (q *Queries) ListTaskSupplementsByCommentIDs(ctx context.Context, arg ListTaskSupplementsByCommentIDsParams) ([]ListTaskSupplementsByCommentIDsRow, error) {rows, err := q.db.Query(ctx, listTaskSupplementsByCommentIDs, arg.WorkspaceID, arg.CommentIds)if err != nil {return nil, err}defer rows.Close()- items := []TaskSupplement{}+ items := []ListTaskSupplementsByCommentIDsRow{}for rows.Next() {- var i TaskSupplement+ var i ListTaskSupplementsByCommentIDsRowif err := rows.Scan(&i.TaskID,&i.WorkspaceID,@@ -448,6 +581,7 @@ func (q *Queries) ListTaskSupplementsByCommentIDs(ctx context.Context, arg ListT&i.CreatedAt,&i.UpdatedAt,&i.DeliveredAt,+ &i.AgentID,); err != nil {return nil, err}@@ -459,35 +593,48 @@ func (q *Queries) ListTaskSupplementsByCommentIDs(ctx context.Context, arg ListTreturn items, nil}-const lockTaskSupplementByComment = `-- name: LockTaskSupplementByComment :one+const lockTaskSupplementsByComment = `-- name: LockTaskSupplementsByComment :manySELECT task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at FROM task_supplementWHERE comment_id = $1 AND workspace_id = $2FOR UPDATE`-type LockTaskSupplementByCommentParams struct {+type LockTaskSupplementsByCommentParams struct {CommentID pgtype.UUID `json:"comment_id"`WorkspaceID pgtype.UUID `json:"workspace_id"`}-func (q *Queries) LockTaskSupplementByComment(ctx context.Context, arg LockTaskSupplementByCommentParams) (TaskSupplement, error) {- row := q.db.QueryRow(ctx, lockTaskSupplementByComment, arg.CommentID, arg.WorkspaceID)- var i TaskSupplement- err := row.Scan(- &i.TaskID,- &i.WorkspaceID,- &i.IssueID,- &i.CommentID,- &i.AuthorID,- &i.ClientRequestID,- &i.Status,- &i.FailureReason,- &i.AttemptCount,- &i.CreatedAt,- &i.UpdatedAt,- &i.DeliveredAt,- )- return i, err+func (q *Queries) LockTaskSupplementsByComment(ctx context.Context, arg LockTaskSupplementsByCommentParams) ([]TaskSupplement, error) {+ rows, err := q.db.Query(ctx, lockTaskSupplementsByComment, arg.CommentID, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []TaskSupplement{}+ for rows.Next() {+ var i TaskSupplement+ if err := rows.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil}const retryTaskSupplement = `-- name: RetryTaskSupplement :onediff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex f12db9a127..eec4dba3e2 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -381,12 +381,18 @@ WHERE c.issue_id = @issue_idOR comment_thread_root_id(c.id) = sqlc.narg('comment_thread_id')::uuid)-- A deleted comment is no longer input, even when replies keep its row.AND c.deleted_at IS NULL- -- Explicit supplements belong only to their bound run, regardless of- -- delivery status. Failed delivery must not become an automatic new run.+ -- A comment that steered this agent's running turn belongs to that turn,+ -- regardless of delivery status: failed delivery must not become an automatic+ -- new run. The same comment still reconciles normally for any other agent+ -- it addressed without steering.AND NOT EXISTS (SELECT 1 FROM task_supplement s+ JOIN agent_task_queue bound ON bound.id = s.task_idWHERE s.comment_id = c.id AND s.workspace_id = c.workspace_id+ AND bound.agent_id = @agent_id)+ -- Nor does a comment whose author chose not to start this agent for it.+ AND NOT COALESCE(@agent_id::uuid = ANY(c.suppressed_agent_ids), false)AND ((c.author_type IN ('member', 'agent')@@ -451,8 +457,8 @@ WITH touched_issue AS (WHERE issue.id = sqlc.arg(issue_id) AND issue.workspace_id = sqlc.arg(workspace_id)RETURNING issue.id, issue.workspace_id, issue.revision), inserted_comment AS (- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id, id)- SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id), sqlc.narg(quick_action_id), sqlc.narg(via_plugin_id), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id, suppressed_agent_ids, id)+ SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.arg(content), sqlc.arg(type), sqlc.narg(parent_id), sqlc.narg(source_task_id), sqlc.narg(quick_action_id), sqlc.narg(via_plugin_id), sqlc.narg(suppressed_agent_ids)::uuid[], COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())FROM touched_issue tiRETURNING *)@@ -526,6 +532,11 @@ WITH locked_issue AS MATERIALIZED (UPDATE comment SETcontent = $2,source_task_id = sqlc.narg(source_task_id)::uuid,+ -- New text re-decides which agents it must not start, under the same+ -- revision check as the text itself.+ suppressed_agent_ids = CASE WHEN target.content IS DISTINCT FROM $2+ THEN sqlc.narg(suppressed_agent_ids)::uuid[]+ ELSE comment.suppressed_agent_ids END,revision = comment.revision + CASE WHEN target.did_change THEN 1 ELSE 0 END,updated_at = CASE WHEN target.did_change THEN now() ELSE comment.updated_at ENDFROM targetdiff --git a/server/pkg/db/queries/supplement.sql b/server/pkg/db/queries/supplement.sqlindex b82e4abbf7..17606d4ed6 100644--- a/server/pkg/db/queries/supplement.sql+++ b/server/pkg/db/queries/supplement.sql@@ -92,17 +92,61 @@ WHERE s.task_id = @task_idAND s.author_id = @author_idAND s.client_request_id = @client_request_id;--- name: GetTaskSupplementByComment :one+-- name: BindCommentTaskSupplement :one+-- Binds an ordinary member comment, already created through the normal comment+-- path, to the exact running turn its author chose. Locking the task+-- serializes against terminal transitions: when that turn ended first nothing+-- is bound — never a later turn of the same agent — and the caller keeps the+-- comment's normal trigger instead.+WITH locked_task AS MATERIALIZED (+ SELECT t.id, t.issue_id, t.runtime_id+ FROM agent_task_queue t+ JOIN agent_runtime r ON r.id = t.runtime_id+ JOIN task_supplement_capability cap ON cap.task_id = t.id+ WHERE t.id = @task_id+ AND t.issue_id = @issue_id+ AND t.agent_id = @agent_id+ AND r.workspace_id = @workspace_id+ AND t.status = 'running'+ AND cap.capability = 'task-supplement-v1'+ AND r.provider IN ('codex', 'claude')+ FOR UPDATE OF t+), inserted AS (+ INSERT INTO task_supplement (+ task_id, workspace_id, issue_id, comment_id, author_id,+ client_request_id, status+ )+ SELECT t.id, @workspace_id, t.issue_id, @comment_id, @author_id,+ @client_request_id, 'pending'+ FROM locked_task t+ RETURNING *+)+SELECT inserted.*, locked_task.runtime_id+FROM inserted+JOIN locked_task ON locked_task.id = inserted.task_id;++-- name: GetTaskSupplementForRun :oneSELECT * FROM task_supplement-WHERE comment_id = @comment_id AND workspace_id = @workspace_id;+WHERE comment_id = @comment_id AND task_id = @task_id AND workspace_id = @workspace_id;++-- name: CommentHasTaskSupplement :one+SELECT EXISTS (+ SELECT 1 FROM task_supplement+ WHERE comment_id = @comment_id AND workspace_id = @workspace_id+) AS bound;-- name: GetTaskSupplementCapability :oneSELECT * FROM task_supplement_capability WHERE task_id = @task_id;-- name: ListTaskSupplementsByCommentIDs :many-SELECT * FROM task_supplement-WHERE workspace_id = @workspace_id- AND comment_id = ANY(@comment_ids::uuid[]);+-- One comment may steer several runs; receipts carry the run's agent so a+-- client can say whose turn received it.+SELECT s.*, t.agent_id+FROM task_supplement s+LEFT JOIN agent_task_queue t ON t.id = s.task_id+WHERE s.workspace_id = @workspace_id+ AND s.comment_id = ANY(@comment_ids::uuid[])+ORDER BY s.created_at, s.task_id;-- name: ListTaskSupplementMetadata :manySELECT cap.task_id, cap.capability,@@ -131,7 +175,7 @@ WHERE supplement.task_id = task.id-- name: ClaimNextTaskSupplement :oneWITH next AS MATERIALIZED (- SELECT s.comment_id+ SELECT s.comment_id, s.task_idFROM task_supplement sJOIN agent_task_queue t ON t.id = s.task_idJOIN task_supplement_capability cap ON cap.task_id = t.id@@ -150,6 +194,7 @@ WITH next AS MATERIALIZED (updated_at = now()FROM nextWHERE s.comment_id = next.comment_id+ AND s.task_id = next.task_idRETURNING s.*)SELECT claimed.comment_id, claimed.attempt_count, c.content,@@ -215,7 +260,7 @@ WHERE s.task_id = t.idAND s.status = 'failed'RETURNING s.*;--- name: LockTaskSupplementByComment :one+-- name: LockTaskSupplementsByComment :manySELECT * FROM task_supplementWHERE comment_id = @comment_id AND workspace_id = @workspace_idFOR UPDATE;