Skip to content

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

Go

MUL-7480: Steer active agent turns from comments (#8605)

Multica Eve8ce795b00718
diff --git a/apps/docs/content/docs/mentioning-agents.mdx b/apps/docs/content/docs/mentioning-agents.mdx
index cfbad275d5..9bd7dc6ff5 100644
--- a/apps/docs/content/docs/mentioning-agents.mdx
+++ b/apps/docs/content/docs/mentioning-agents.mdx
@@ -47,7 +47,11 @@ Replies stay with the target agent even while its runtime is offline or busy. Mu
## Coalescing consecutive comments
-When the same agent already has a waiting run on the issue, new consecutive comments merge into the pending run; if the agent is already running, later comments wait for the current run to finish and merge into a single follow-up run. You can keep adding information without waiting for the agent to reply.
+When the same agent already has a waiting run on the issue, new consecutive comments merge into the pending run. If a human posts in the same thread while that agent has exactly one active Codex or Claude turn on a compatible runtime, Multica delivers the comment to that turn at its next safe boundary. The composer shows this destination before sending, and the saved comment shows a separate receipt for each agent.
+
+If the runtime does not support steering, the route is ambiguous, the turn ends first, or delivery fails or times out, the comment falls back losslessly to the existing single follow-up path. Stop remains independent: stopping a run never starts a replacement run. An instruction that was not delivered stays marked for follow-up and remains in issue history for the agent's next natural run to re-read.
+
+An “already delivered” receipt is historical: its timestamp does not disappear if the turn later fails or is stopped. Editing a comment before it is claimed lets the active turn read the updated text; editing it after claiming has begun does not inject it a second time or start a duplicate follow-up. All steered comments remain in issue history so later natural runs can re-read the current text.
When one comment @-mentions several different agents, each agent gets its own run; multiple mentions resolving to the same agent keep only one.
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index a7446aeeb3..40999cf20c 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -915,6 +915,12 @@ const TimelineEntrySchema = z.object({
reactions: z.array(ReactionSchema).optional(),
attachments: z.array(AttachmentSchema).optional(),
source_task_id: z.string().nullable().optional(),
+ agent_deliveries: z.array(z.object({
+ agent_id: z.string(),
+ agent_name: z.string(),
+ status: z.string(),
+ delivered_at: z.string().nullable().optional(),
+ }).loose()).optional().catch(undefined),
// Tombstone marker (#8296). Lenient: a malformed value reads as a live
// comment instead of failing the whole timeline.
deleted_at: z.string().nullable().optional().catch(undefined),
@@ -1057,6 +1063,12 @@ export const CommentSchema = z.object({
updated_at: z.string(),
revision: z.number().int().positive().optional(),
source_task_id: z.string().nullable().optional(),
+ agent_deliveries: z.array(z.object({
+ agent_id: z.string(),
+ agent_name: z.string(),
+ status: z.string(),
+ delivered_at: z.string().nullable().optional(),
+ }).loose()).optional().catch(undefined),
// Set only on comments a quick action produced (MUL-5465). Server-only.
quick_action_id: z.string().nullable().optional(),
deleted_at: z.string().nullable().optional().catch(undefined),
@@ -1090,6 +1102,7 @@ const CommentTriggerPreviewAgentSchema = z.object({
avatar_url: z.string().optional(),
source: z.string().default(""),
reason: z.string().default(""),
+ delivery: z.string().default("follow_up"),
}).loose();
// Per-target outcome of an explicit @agent / @squad mention (MUL-4525 §2).
diff --git a/packages/core/issues/comment-trigger-outcomes.test.ts b/packages/core/issues/comment-trigger-outcomes.test.ts
index 412224444f..99c0c3baf8 100644
--- a/packages/core/issues/comment-trigger-outcomes.test.ts
+++ b/packages/core/issues/comment-trigger-outcomes.test.ts
@@ -27,11 +27,12 @@ describe("comment trigger outcomes", () => {
expect(parseCommentTriggerOutcomes("nope")).toEqual([]);
});
- it("treats only queued/coalesced/deferred as handled; blocked warns", () => {
+ it("treats queued/coalesced/deferred/steering as handled; blocked warns", () => {
const raw = [
{ target_type: "agent", target_id: "a1", status: "queued", reason_code: "queued" },
{ target_type: "agent", target_id: "a2", status: "coalesced", reason_code: "coalesced" },
{ target_type: "agent", target_id: "a3", status: "deferred", reason_code: "deferred" },
+ { target_type: "agent", target_id: "a4", status: "steering", reason_code: "steering" },
{ target_type: "squad", target_id: "s1", status: "blocked", reason_code: "invocation_not_allowed" },
];
const unhandled = unhandledCommentTriggerOutcomes(raw);
diff --git a/packages/core/issues/comment-trigger-outcomes.ts b/packages/core/issues/comment-trigger-outcomes.ts
index e5cb8ec40a..29d7f3d2af 100644
--- a/packages/core/issues/comment-trigger-outcomes.ts
+++ b/packages/core/issues/comment-trigger-outcomes.ts
@@ -73,7 +73,7 @@ export function parseCommentTriggerOutcomes(raw: unknown): CommentTriggerOutcome
// 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", "steering"]);
// The explicit @agent / @squad mentions that did NOT clearly trigger, so the
// "posted, but N not triggered" warning must cover them: `blocked` plus any
diff --git a/packages/core/types/activity.ts b/packages/core/types/activity.ts
index 7a469e4b01..12de2fce96 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 { CommentAgentDelivery, CommentAuthorType, Reaction } from "./comment";
import type { Attachment } from "./attachment";
export interface AssigneeFrequencyEntry {
@@ -33,6 +33,7 @@ export interface TimelineEntry {
resolved_by_type?: CommentAuthorType | null;
resolved_by_id?: string | null;
source_task_id?: string | null;
+ agent_deliveries?: CommentAgentDelivery[];
/**
* Set only on a comment deleted while it still had replies: the server keeps
* it as an empty tombstone so the replies keep their parent. Read it through
diff --git a/packages/core/types/comment.ts b/packages/core/types/comment.ts
index b0bcf5a8f6..f172274b9f 100644
--- a/packages/core/types/comment.ts
+++ b/packages/core/types/comment.ts
@@ -47,6 +47,14 @@ 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[];
+ agent_deliveries?: CommentAgentDelivery[];
+}
+
+export interface CommentAgentDelivery {
+ agent_id: string;
+ agent_name: string;
+ status: "pending" | "delivered" | "follow_up" | string;
+ delivered_at?: string | null;
}
// The domain result of one explicitly-mentioned trigger target. Success-shaped
@@ -56,6 +64,7 @@ export type CommentTriggerStatus =
| "queued"
| "coalesced"
| "deferred"
+ | "steering"
| "blocked";
export interface CommentTriggerOutcome {
@@ -76,6 +85,7 @@ export interface CommentTriggerPreviewAgent {
avatar_url?: string;
source: CommentTriggerSource | string;
reason: string;
+ delivery?: "current_run" | "follow_up" | string;
}
export interface CommentTriggerPreview {
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 61c113596c..4c2ea20493 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -116,7 +116,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, CommentAgentDelivery, CommentType, CommentAuthorType, 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.test.tsx b/packages/views/issues/components/comment-card.test.tsx
index 9a26340a4e..677f840d84 100644
--- a/packages/views/issues/components/comment-card.test.tsx
+++ b/packages/views/issues/components/comment-card.test.tsx
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import type { ReactElement } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderWithI18n } from "../../test/i18n";
const { getAttachmentTextContentMock } = vi.hoisted(() => ({
getAttachmentTextContentMock: vi.fn(),
@@ -41,7 +42,7 @@ vi.mock("@multica/core/paths", async (importOriginal) => {
};
});
-import { AttachmentList } from "./comment-card";
+import { AttachmentList, CommentDeliveryReceipts } from "./comment-card";
function renderWithQuery(ui: ReactElement) {
const qc = new QueryClient({
@@ -53,6 +54,25 @@ function renderWithQuery(ui: ReactElement) {
beforeEach(() => vi.clearAllMocks());
afterEach(() => vi.restoreAllMocks());
+describe("CommentDeliveryReceipts", () => {
+ it("renders an independent delivery state for every agent recipient", () => {
+ renderWithI18n(
+ <CommentDeliveryReceipts
+ entry={{
+ agent_deliveries: [
+ { agent_id: "a1", agent_name: "Walt", status: "pending" },
+ { agent_id: "a2", agent_name: "Bob", status: "delivered", delivered_at: new Date().toISOString() },
+ { agent_id: "a3", agent_name: "Kim", status: "follow_up" },
+ ],
+ } as any}
+ />,
+ );
+ expect(screen.getByText("Waiting to deliver to Walt's current work")).toBeInTheDocument();
+ expect(screen.getByText(/Delivered to Bob's current work/)).toBeInTheDocument();
+ expect(screen.getByText("Kim will handle this in follow-up work")).toBeInTheDocument();
+ });
+});
+
describe("AttachmentList — standalone HTML attachment routes through AttachmentBlock", () => {
// Regression pin for comment-card.tsx:152. This is the entry point
// MUL-2330 originally regressed on: standalone HTML attachments (not
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 36617fc159..f647e029cc 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -60,6 +60,27 @@ const highlightedCommentBackgroundClass =
const stickyHeaderFadeClass =
"after:pointer-events-none after:absolute after:inset-x-0 after:top-full after:h-1 after:bg-[inherit] after:[mask-image:linear-gradient(to_bottom,#000,transparent)] after:[-webkit-mask-image:linear-gradient(to_bottom,#000,transparent)]";
+export function CommentDeliveryReceipts({ entry, className }: { entry: TimelineEntry; className?: string }) {
+ const { t } = useT("issues");
+ const timeAgo = useTimeAgo();
+ if (!entry.agent_deliveries?.length) return null;
+ return (
+ <div className={cn("mt-1.5 flex flex-col gap-0.5 text-micro text-muted-foreground", className)}>
+ {entry.agent_deliveries.map((delivery) => {
+ const text = delivery.status === "delivered"
+ ? t(($) => $.comment.delivery_delivered, {
+ name: delivery.agent_name,
+ time: delivery.delivered_at ? timeAgo(delivery.delivered_at) : "",
+ })
+ : delivery.status === "pending"
+ ? t(($) => $.comment.delivery_pending, { name: delivery.agent_name })
+ : t(($) => $.comment.delivery_follow_up, { name: delivery.agent_name });
+ return <div key={delivery.agent_id}>{text}</div>;
+ })}
+ </div>
+ );
+}
+
function StickyHeaderShell({
className,
sticky = true,
@@ -870,6 +891,7 @@ function CommentRow({
<ReadonlyContent content={entry.content ?? ""} attachments={entry.attachments} />
</div>
<AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-12 pr-4 max-md:pl-3 max-md:pr-3" />
+ <CommentDeliveryReceipts entry={entry} className="pl-12 pr-4 max-md:pl-3 max-md:pr-3" />
{retryableAgentFailureComment(entry) && (
<TaskCommentRetryButton
issueId={issueId}
@@ -1321,6 +1343,7 @@ function CommentCardImpl({
<ReadonlyContent content={entry.content ?? ""} attachments={entry.attachments} />
</div>
<AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-8 max-md:pl-0" />
+ <CommentDeliveryReceipts entry={entry} className="pl-8 max-md:pl-0" />
{retryableAgentFailureComment(entry) && (
<TaskCommentRetryButton
issueId={issueId}
diff --git a/packages/views/issues/components/comment-trigger-chips.test.tsx b/packages/views/issues/components/comment-trigger-chips.test.tsx
index 6474369de3..6fa96ecfea 100644
--- a/packages/views/issues/components/comment-trigger-chips.test.tsx
+++ b/packages/views/issues/components/comment-trigger-chips.test.tsx
@@ -98,6 +98,17 @@ describe("CommentTriggerChips", () => {
expect(chip).toHaveAttribute("aria-pressed", "true");
});
+ it("previews delivery into the current turn", () => {
+ renderWithI18n(
+ <CommentTriggerChips
+ agents={[{ ...walt, delivery: "current_run" }]}
+ suppressedAgentIds={new Set()}
+ onToggle={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole("button")).toHaveTextContent("Will update current work");
+ });
+
it("collapses several agents into a stack with an active count", () => {
renderWithI18n(
<CommentTriggerChips
@@ -107,7 +118,7 @@ describe("CommentTriggerChips", () => {
/>,
);
- expect(screen.getByRole("button")).toHaveTextContent("2 agents will start when sent");
+ expect(screen.getByRole("button")).toHaveTextContent("2 agents will receive this");
});
it("counts only non-suppressed agents in the sentence", () => {
@@ -119,7 +130,7 @@ describe("CommentTriggerChips", () => {
/>,
);
- expect(screen.getByRole("button")).toHaveTextContent("1 agent will start when sent");
+ expect(screen.getByRole("button")).toHaveTextContent("1 agent will receive this");
});
it("switches to the none-will-trigger state when every agent is suppressed", () => {
diff --git a/packages/views/issues/components/comment-trigger-chips.tsx b/packages/views/issues/components/comment-trigger-chips.tsx
index 90b1457bed..792bf0c97c 100644
--- a/packages/views/issues/components/comment-trigger-chips.tsx
+++ b/packages/views/issues/components/comment-trigger-chips.tsx
@@ -90,6 +90,12 @@ function useTriggerPresenceLine(agentId: string, t: IssuesT): string | null {
: t(($) => $.comment.trigger_starts_when_online);
}
+function deliveryLabel(agent: CommentTriggerPreviewAgent, t: IssuesT): string {
+ return agent.delivery === "current_run"
+ ? t(($) => $.comment.trigger_current_work_short)
+ : t(($) => $.comment.trigger_follow_up_short);
+}
+
// One tooltip body for every trigger surface (single chip, popover rows):
// who · why it fires (+ presence) · what a click does.
function TriggerAgentTooltipBody({
@@ -115,7 +121,10 @@ function TriggerAgentTooltipBody({
{(() => {
// 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(" ");
+ const destination = agent.delivery === "current_run"
+ ? t(($) => $.comment.trigger_current_safe_point)
+ : presenceLine;
+ const line = [sourceReason(agent, t), destination].filter(Boolean).join(" ");
return line ? <div>{line}</div> : null;
})()}
<div className="text-muted-foreground">{t(($) => $.comment.trigger_click_to_skip)}</div>
@@ -246,7 +255,9 @@ function SingleTriggerChip({
// 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);
+ : agent.delivery === "current_run"
+ ? t(($) => $.comment.trigger_will_update_current)
+ : t(($) => $.comment.trigger_will_start);
return (
<Tooltip>
@@ -300,7 +311,7 @@ function MultiTriggerChip({
const sentence =
activeCount === 0
? t(($) => $.comment.trigger_none_will_trigger)
- : t(($) => $.comment.trigger_will_start_count, { count: activeCount });
+ : t(($) => $.comment.trigger_will_receive_count, { count: activeCount });
const popoverTrigger = (
<PopoverTrigger
@@ -364,7 +375,7 @@ function MultiTriggerChip({
const suppressed = suppressedAgentIds.has(agent.id);
const state = suppressed
? t(($) => $.comment.trigger_skipped_label)
- : sourceLabel(agent.source, t);
+ : deliveryLabel(agent, t);
return (
<Tooltip key={agent.id}>
<TooltipTrigger
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 1ee3dde548..946355f808 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -552,6 +552,15 @@
"trigger_reason_mention_squad_leader": "Leads a squad mentioned here.",
"trigger_reason_unknown": "Will start from this comment.",
"trigger_will_start": "Will start when sent",
+ "trigger_will_update_current": "Will update current work",
+ "trigger_will_receive_count_one": "{{count}} agent will receive this",
+ "trigger_will_receive_count_other": "{{count}} agents will receive this",
+ "trigger_current_work_short": "Current work",
+ "trigger_follow_up_short": "Follow-up",
+ "trigger_current_safe_point": "Updates current work at the next safe point.",
+ "delivery_pending": "Waiting to deliver to {{name}}'s current work",
+ "delivery_delivered": "Delivered to {{name}}'s current work · {{time}}",
+ "delivery_follow_up": "{{name}} will handle this in follow-up work",
"trigger_will_start_count_one": "{{count}} agent will start when sent",
"trigger_will_start_count_other": "{{count}} agents will start when sent",
"trigger_starts_now": "Starts right away.",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 91d962a57a..765ab404a3 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -552,6 +552,15 @@
"trigger_reason_mention_squad_leader": "Dirige un squad mentionné ici.",
"trigger_reason_unknown": "Démarrera à partir de ce commentaire.",
"trigger_will_start": "Démarrera à l'envoi",
+ "trigger_will_update_current": "Complétera le travail en cours",
+ "trigger_will_receive_count_one": "{{count}} agent recevra ce message",
+ "trigger_will_receive_count_other": "{{count}} agents recevront ce message",
+ "trigger_current_work_short": "Travail en cours",
+ "trigger_follow_up_short": "Suivi",
+ "trigger_current_safe_point": "Complète le travail en cours au prochain point sûr.",
+ "delivery_pending": "En attente de livraison au travail en cours de {{name}}",
+ "delivery_delivered": "Livré au travail en cours de {{name}} · {{time}}",
+ "delivery_follow_up": "{{name}} le traitera dans un suivi",
"trigger_will_start_count_one": "{{count}} agent démarrera à l'envoi",
"trigger_will_start_count_other": "{{count}} agents démarreront à l'envoi",
"trigger_starts_now": "Démarre immédiatement.",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 71a096dc49..640574274c 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -541,6 +541,14 @@
"trigger_reason_mention_squad_leader": "メンションされた Squad のリーダー。",
"trigger_reason_unknown": "このコメントで開始します。",
"trigger_will_start": "送信後に作業を開始します",
+ "trigger_will_update_current": "現在の作業に追加します",
+ "trigger_will_receive_count_other": "{{count}} 件のエージェントに届きます",
+ "trigger_current_work_short": "現在の作業",
+ "trigger_follow_up_short": "フォローアップ",
+ "trigger_current_safe_point": "次の安全な時点で現在の作業に追加します。",
+ "delivery_pending": "{{name}} の現在の作業への配信を待機中",
+ "delivery_delivered": "{{name}} の現在の作業に配信済み · {{time}}",
+ "delivery_follow_up": "{{name}} がフォローアップで対応します",
"trigger_will_start_count_other": "送信後に {{count}} 体のエージェントが作業を開始します",
"trigger_starts_now": "すぐに開始します。",
"trigger_starts_when_online": "オフライン中。オンラインになり次第開始します。",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 188223a058..cd0b3c7a7e 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -541,6 +541,14 @@
"trigger_reason_mention_squad_leader": "멘션된 Squad의 리더입니다.",
"trigger_reason_unknown": "이 댓글로 시작합니다.",
"trigger_will_start": "전송 후 작업을 시작합니다",
+ "trigger_will_update_current": "현재 작업에 추가됩니다",
+ "trigger_will_receive_count_other": "에이전트 {{count}}명이 받습니다",
+ "trigger_current_work_short": "현재 작업",
+ "trigger_follow_up_short": "후속 작업",
+ "trigger_current_safe_point": "다음 안전 지점에서 현재 작업에 추가됩니다.",
+ "delivery_pending": "{{name}}의 현재 작업에 전달 대기 중",
+ "delivery_delivered": "{{name}}의 현재 작업에 전달됨 · {{time}}",
+ "delivery_follow_up": "{{name}}이 후속 작업에서 처리합니다",
"trigger_will_start_count_other": "전송 후 에이전트 {{count}}개가 작업을 시작합니다",
"trigger_starts_now": "바로 시작합니다.",
"trigger_starts_when_online": "현재 오프라인이며 온라인이 되면 시작합니다.",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 1b037dffdb..8d6a3c444b 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -541,6 +541,14 @@
"trigger_reason_mention_squad_leader": "被 @ 小队的队长。",
"trigger_reason_unknown": "将由这条评论开始。",
"trigger_will_start": "发送后开始",
+ "trigger_will_update_current": "将补充当前工作",
+ "trigger_will_receive_count_other": "{{count}} 个 Agent 将收到此消息",
+ "trigger_current_work_short": "当前工作",
+ "trigger_follow_up_short": "后续工作",
+ "trigger_current_safe_point": "将在下一个安全边界补充当前工作。",
+ "delivery_pending": "等待送达 {{name}} 的当前工作",
+ "delivery_delivered": "已送达 {{name}} 的当前工作 · {{time}}",
+ "delivery_follow_up": "{{name}} 将在后续工作中处理",
"trigger_will_start_count_other": "发送后 {{count}} 个智能体开始工作",
"trigger_starts_now": "立即开始。",
"trigger_starts_when_online": "当前离线,上线后开始。",
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 0623d6a1ea..32ea66f26c 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,7 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "508_comment_agent_delivery_pending_index": "idx_comment_agent_delivery_task_pending",
"503_channel_reply_delivery_turn_index": "idx_channel_reply_delivery_turn",
"504_channel_reply_delivery_installation_index": "idx_channel_reply_delivery_installation",
"505_channel_reply_delivery_binding_index": "idx_channel_reply_delivery_binding",
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index cdb844560d..002e56bc5b 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1491,6 +1491,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/tasks/{taskId}/messages", h.ReportTaskMessages)
r.Get("/tasks/{taskId}/messages", h.ListTaskMessages)
r.Post("/tasks/{taskId}/cancel-ack", h.AckTaskCancelled)
+ r.Post("/tasks/{taskId}/steers/claim", h.ClaimCommentSteer)
+ r.Post("/tasks/{taskId}/steers/{commentId}/ack", h.AckCommentSteer)
r.Post("/workspaces/{workspaceId}/issues/gc-check", h.BatchIssueGCCheck)
r.Get("/issues/{issueId}/gc-check", h.GetIssueGCCheck)
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 3e770fcef1..9e7063124a 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -211,6 +211,7 @@ func daemonCommonCapabilities() []string {
protocol.DaemonCapabilityRPCV1,
protocol.DaemonCapabilityPlatformSkillV1,
protocol.DaemonCapabilityCheckoutKeepsWorkV1,
+ protocol.DaemonCapabilityTaskSteerV1,
}
}
@@ -438,6 +439,34 @@ func (c *Client) StartTask(ctx context.Context, taskID string) error {
return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/start", taskID), map[string]any{}, nil)
}
+type CommentSteer struct {
+ CommentID string `json:"comment_id"`
+ AuthorName string `json:"author_name"`
+ Content string `json:"content"`
+}
+
+func (c *Client) ClaimCommentSteer(ctx context.Context, taskID string) (*CommentSteer, error) {
+ var steer CommentSteer
+ if err := c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/steers/claim", taskID), map[string]any{}, &steer); err != nil {
+ return nil, err
+ }
+ if steer.CommentID == "" {
+ return nil, nil
+ }
+ return &steer, nil
+}
+
+func (c *Client) AckCommentSteer(ctx context.Context, taskID, commentID string, delivered bool, errText string) (string, error) {
+ var response struct {
+ Status string `json:"status"`
+ }
+ err := c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/steers/%s/ack", taskID, commentID), map[string]any{
+ "delivered": delivered,
+ "error": errText,
+ }, &response, []time.Duration{0, 100 * time.Millisecond, 300 * time.Millisecond})
+ return response.Status, err
+}
+
// MarkTaskWaitingLocalDirectory parks a freshly-dispatched task in the
// waiting_local_directory state on the server. The daemon calls this after
// it has claimed a task whose project carries a local_directory resource
diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.go
index d6058fcdfc..e807b3c554 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -55,6 +55,7 @@ func TestClient_IdentityHeaders_PostJSON(t *testing.T) {
// (MUL-7034). Dropping it silently sends those retries back to a
// fresh directory, losing the continuity nothing else would flag.
protocol.DaemonCapabilityCheckoutKeepsWorkV1,
+ protocol.DaemonCapabilityTaskSteerV1,
} {
if !capabilities[want] {
t.Errorf("X-Client-Capabilities missing %q: %v", want, capabilities)
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 30601888c3..205622fd45 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -32,6 +32,7 @@ import (
"github.com/multica-ai/multica/server/internal/daemon/repocache"
"github.com/multica-ai/multica/server/internal/selfexec"
"github.com/multica-ai/multica/server/pkg/agent"
+ "github.com/multica-ai/multica/server/pkg/protocol"
"github.com/multica-ai/multica/server/pkg/redact"
"github.com/multica-ai/multica/server/pkg/skillbundle"
"github.com/multica-ai/multica/server/pkg/taskfailure"
@@ -580,6 +581,11 @@ type Daemon struct {
pendingWorkMu sync.Mutex
pendingWorkInflight map[string]struct{} // runtime_id -> hint-driven heartbeat in flight
pendingWorkLastRun map[string]time.Time // runtime_id -> when the last hint-driven heartbeat started
+ // Negotiated from heartbeat acknowledgements or a server-originated steer
+ // hint. Until then a new daemon must not poll an older server's missing API.
+ taskSteerServerSupported atomic.Bool
+ taskSteerWakeMu sync.Mutex
+ taskSteerWakeups map[string]map[chan struct{}]struct{} // runtime_id -> active provider sessions
cancelFunc context.CancelFunc // set by Run(); called by triggerRestart
rootCtx context.Context // set by Run(); used by long-running recoveries that must survive per-runtime ctx cancellation
@@ -729,6 +735,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {
runtimeGoneInflight: make(map[string]struct{}),
pendingWorkInflight: make(map[string]struct{}),
pendingWorkLastRun: make(map[string]time.Time),
+ taskSteerWakeups: make(map[string]map[chan struct{}]struct{}),
reregisterNextAttempt: make(map[string]time.Time),
reregisterLastCompletedAt: make(map[string]time.Time),
cancelPollInterval: 5 * time.Second,
@@ -4558,6 +4565,14 @@ func (d *Daemon) handleHeartbeatActions(ctx context.Context, runtimeID string, r
if resp == nil {
return
}
+ steerSupported := false
+ for _, capability := range resp.ServerCapabilities {
+ if capability == protocol.DaemonCapabilityTaskSteerV1 {
+ steerSupported = true
+ break
+ }
+ }
+ d.taskSteerServerSupported.Store(steerSupported)
if resp.PendingUpdate != nil || resp.PendingModelList != nil || resp.PendingLocalSkills != nil || resp.PendingLocalSkillImport != nil {
d.logger.Debug("heartbeat: pending actions",
"runtime_id", runtimeID,
@@ -4620,6 +4635,16 @@ func (d *Daemon) handlePendingWorkHint(runtimeID, kind string) {
// Not one of ours (stale relay fanout, or the runtime was just pruned).
return
}
+ if kind == protocol.PendingWorkKindTaskSteer {
+ // Receiving this server-owned hint is itself positive feature
+ // negotiation; old servers cannot emit the new kind.
+ d.taskSteerServerSupported.Store(true)
+ d.signalTaskSteerWakeups(runtimeID)
+ // Wake active provider sessions directly. Their low-frequency durable
+ // poll remains only as recovery if this best-effort hint is lost; this
+ // kind must not turn into a generic heartbeat/claim cycle here.
+ return
+ }
d.pendingWorkMu.Lock()
if d.pendingWorkInflight == nil {
@@ -4689,6 +4714,38 @@ func (d *Daemon) handlePendingWorkHint(runtimeID, kind string) {
d.handleHeartbeatActions(ctx, runtimeID, resp)
}
+func (d *Daemon) registerTaskSteerWakeup(runtimeID string) (chan struct{}, func()) {
+ wake := make(chan struct{}, 1)
+ d.taskSteerWakeMu.Lock()
+ if d.taskSteerWakeups == nil {
+ d.taskSteerWakeups = make(map[string]map[chan struct{}]struct{})
+ }
+ if d.taskSteerWakeups[runtimeID] == nil {
+ d.taskSteerWakeups[runtimeID] = make(map[chan struct{}]struct{})
+ }
+ d.taskSteerWakeups[runtimeID][wake] = struct{}{}
+ d.taskSteerWakeMu.Unlock()
+ return wake, func() {
+ d.taskSteerWakeMu.Lock()
+ delete(d.taskSteerWakeups[runtimeID], wake)
+ if len(d.taskSteerWakeups[runtimeID]) == 0 {
+ delete(d.taskSteerWakeups, runtimeID)
+ }
+ d.taskSteerWakeMu.Unlock()
+ }
+}
+
+func (d *Daemon) signalTaskSteerWakeups(runtimeID string) {
+ d.taskSteerWakeMu.Lock()
+ defer d.taskSteerWakeMu.Unlock()
+ for wake := range d.taskSteerWakeups[runtimeID] {
+ select {
+ case wake <- struct{}{}:
+ default:
+ }
+ }
+}
+
// handleModelList resolves the provider's supported models (via static
// catalog or by shelling out to the agent CLI) and reports the result
// back to the server.
@@ -8735,7 +8792,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// Shared across the resume-retry below so the retry's transcript rows
// keep ascending seq values for the same task.
var msgSeq atomic.Int32
- result, tools, err := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
+ execCtx := context.WithValue(ctx, taskSteerRuntimeIDContextKey{}, task.RuntimeID)
+ result, tools, err := d.executeAndDrain(execCtx, backend, prompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
if err != nil {
return TaskResult{}, err
}
@@ -8791,7 +8849,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
freshPrompt := BuildPrompt(task, provider, promptOptions...)
- retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, freshPrompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
+ retryResult, retryTools, retryErr := d.executeAndDrain(execCtx, backend, freshPrompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
if retryErr != nil {
taskLog.Error("fresh session also failed to start; keeping the original poisoned result", "error", retryErr)
} else if retryResult.Status != "completed" && retryResult.SessionID == "" {
@@ -9246,6 +9304,16 @@ func freshSessionMayHelp(errText string) bool {
// messages and is owned by the caller so a same-task retry continues the
// sequence instead of restarting at 1 — the server orders the transcript by
// seq alone, and duplicate seqs would interleave the two attempts' rows.
+type taskSteerRuntimeIDContextKey struct{}
+
+func formatCommentSteerInstruction(authorName, content string) string {
+ authorName = strings.Join(strings.Fields(authorName), " ")
+ if authorName == "" {
+ authorName = "a user"
+ }
+ return fmt.Sprintf("[STEER] Human %s left a new comment while you were working:\n\n%s", strconv.Quote(authorName), content)
+}
+
func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, prompt string, opts agent.ExecOptions, taskLog *slog.Logger, taskID, codexHome string, msgSeq *atomic.Int32) (agent.Result, int32, error) {
phaseRecorder := taskPhaseRecorderFromContext(ctx)
// Wrap the caller's ctx so the idle watchdog (below) can interrupt both
@@ -9273,6 +9341,71 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
phaseRecorder.Mark(taskPhaseRuntimeStarted)
taskLog.Debug("backend started, draining messages")
+ // Pull steering instructions while this exact provider session is alive.
+ // Server hints wake matching runtime sessions immediately; the low-frequency
+ // poll is only a recovery path when a best-effort hint is lost.
+ steerCtx, cancelSteer := context.WithCancel(agentCtx)
+ steerDone := make(chan struct{})
+ if session.Steer != nil {
+ runtimeID, _ := ctx.Value(taskSteerRuntimeIDContextKey{}).(string)
+ steerWake, unregisterSteerWake := d.registerTaskSteerWakeup(runtimeID)
+ defer unregisterSteerWake()
+ go func() {
+ defer close(steerDone)
+ ticker := time.NewTicker(15 * time.Second)
+ defer ticker.Stop()
+ for {
+ if !d.taskSteerServerSupported.Load() {
+ select {
+ case <-steerCtx.Done():
+ return
+ case <-steerWake:
+ case <-ticker.C:
+ }
+ continue
+ }
+ claimCtx, cancel := context.WithTimeout(steerCtx, 3*time.Second)
+ steer, claimErr := d.client.ClaimCommentSteer(claimCtx, taskID)
+ cancel()
+ if claimErr != nil {
+ if steerCtx.Err() != nil {
+ return
+ }
+ taskLog.Debug("comment steer claim failed", "error", claimErr)
+ } else if steer != nil {
+ injectCtx, cancelInject := context.WithTimeout(steerCtx, 5*time.Second)
+ injectErr := session.Steer(injectCtx, formatCommentSteerInstruction(steer.AuthorName, steer.Content))
+ cancelInject()
+ injectErrText := ""
+ if injectErr != nil {
+ injectErrText = injectErr.Error()
+ }
+ ackCtx, cancelAck := context.WithTimeout(context.Background(), 5*time.Second)
+ _, ackErr := d.client.AckCommentSteer(ackCtx, taskID, steer.CommentID, injectErr == nil, injectErrText)
+ cancelAck()
+ if ackErr != nil {
+ taskLog.Warn("comment steer acknowledgement failed", "comment_id", steer.CommentID, "error", ackErr)
+ }
+ // Drain all currently pending rows before sleeping so several
+ // comments retain their database order at one safe boundary.
+ continue
+ }
+ select {
+ case <-steerCtx.Done():
+ return
+ case <-steerWake:
+ case <-ticker.C:
+ }
+ }
+ }()
+ } else {
+ close(steerDone)
+ }
+ defer func() {
+ cancelSteer()
+ <-steerDone
+ }()
+
// Bound the drain loop only when there is a wall-clock cap. With a positive
// opts.Timeout, give the drain a slightly longer deadline than the backend
// so it can still collect the backend's own timeout Result if the scanner
diff --git a/server/internal/daemon/execenv/runtime_config_kind_test.go b/server/internal/daemon/execenv/runtime_config_kind_test.go
index b66903240e..8256f73727 100644
--- a/server/internal/daemon/execenv/runtime_config_kind_test.go
+++ b/server/internal/daemon/execenv/runtime_config_kind_test.go
@@ -74,6 +74,10 @@ func TestBuildMetaSkillContentBriefContent(t *testing.T) {
if strings.Contains(out, "Get full issue details.") {
t.Errorf("brief still carries the retired legacy `issue get` description\n---\n%s", out)
}
+ if !strings.Contains(out, "A `[STEER]` message is a human comment delivered while this turn is active") ||
+ !strings.Contains(out, "preserving the original objective unless the message explicitly changes it") {
+ t.Errorf("brief is missing active-turn steer framing\n---\n%s", out)
+ }
}
// TestBuildMetaSkillContentIssueBodyFormatting pins the shared issue-body
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 21ca3b92f3..05a97fbe72 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -767,6 +767,7 @@ func writeWorkflowAutopilot(b *strings.Builder) {
// worker the next. Owner-accepted tradeoff; decision recorded in MUL-5811.
func writeWorkflowIssue(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("**Every issue turn runs the same workflow.** The per-turn user message carries what triggered this run — an assignment handoff, or a triggering comment with its id and your `--parent` value — plus this issue's real id and ready-to-run context-read commands; assemble other calls from `## Available Commands`.\n\n")
+ b.WriteString("A `[STEER]` message is a human comment delivered while this turn is active. Apply it at the next safe boundary as additional guidance for the current task, preserving the original objective unless the message explicitly changes it.\n\n")
b.WriteString("1. Read the issue (`multica issue get`) to understand the context.\n")
b.WriteString(" The per-turn message may report that the server compared the issue against your last run; when it says the issue is unchanged, that report is this step's answer and you continue from your resumed context. Only that explicit report waives the read — a message that says nothing about the issue record has not compared it.\n")
diff --git a/server/internal/daemon/pending_work_hint_test.go b/server/internal/daemon/pending_work_hint_test.go
index ea4c920a30..3dc77a64af 100644
--- a/server/internal/daemon/pending_work_hint_test.go
+++ b/server/internal/daemon/pending_work_hint_test.go
@@ -91,6 +91,52 @@ func TestHandlePendingWorkHint_IgnoresUnknownRuntime(t *testing.T) {
}
}
+func TestHandlePendingWorkHint_TaskSteerUsesActiveSessionPoll(t *testing.T) {
+ d, calls := pendingWorkHintDaemon(t, func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ wake, unregister := d.registerTaskSteerWakeup("rt-1")
+ defer unregister()
+ d.handlePendingWorkHint("rt-1", protocol.PendingWorkKindTaskSteer)
+ if !d.taskSteerServerSupported.Load() {
+ t.Fatal("task steer hint did not negotiate server support")
+ }
+ select {
+ case <-wake:
+ case <-time.After(time.Second):
+ t.Fatal("task steer hint did not wake the active provider session")
+ }
+
+ if got := atomic.LoadInt32(calls); got != 0 {
+ t.Fatalf("task steer hint sent %d heartbeat calls, want active-session poll only", got)
+ }
+}
+
+func TestHandleHeartbeatActionsNegotiatesTaskSteerServerCapability(t *testing.T) {
+ d := &Daemon{logger: slog.Default()}
+ d.handleHeartbeatActions(t.Context(), "rt-1", &HeartbeatResponse{
+ ServerCapabilities: []string{protocol.DaemonCapabilityTaskSteerV1},
+ })
+ if !d.taskSteerServerSupported.Load() {
+ t.Fatal("current server capability was not enabled")
+ }
+
+ // Absence is authoritative and fail-safe for a downgrade or old server.
+ d.handleHeartbeatActions(t.Context(), "rt-1", &HeartbeatResponse{})
+ if d.taskSteerServerSupported.Load() {
+ t.Fatal("missing server capability left steering enabled")
+ }
+}
+
+func TestFormatCommentSteerInstructionCarriesHumanSource(t *testing.T) {
+ got := formatCommentSteerInstruction("Alice\nAdmin", "keep the migration reversible")
+ want := "[STEER] Human \"Alice Admin\" left a new comment while you were working:\n\nkeep the migration reversible"
+ if got != want {
+ t.Fatalf("steer instruction = %q, want %q", got, want)
+ }
+}
+
// TestHandlePendingWorkHint_CoalescesConcurrentHints pins the stampede guard:
// several UI surfaces (model picker, thinking level, service tier) each request
// the catalog for the same runtime within milliseconds, and one heartbeat
diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.go
index 935cd90544..cab1c5e380 100644
--- a/server/internal/dispatch/reason.go
+++ b/server/internal/dispatch/reason.go
@@ -15,10 +15,11 @@ package dispatch
type ReasonCode string
const (
- // ReasonQueued / ReasonCoalesced / ReasonDeferred are the success-path codes.
+ // ReasonQueued / ReasonCoalesced / ReasonDeferred / ReasonSteering are the success-path codes.
ReasonQueued ReasonCode = "queued"
ReasonCoalesced ReasonCode = "coalesced"
ReasonDeferred ReasonCode = "deferred"
+ ReasonSteering ReasonCode = "steering"
// ReasonInvocationNotAllowed: the acting principal may not trigger this
// target under the invocation-permission model. Deliberately generic — it
diff --git a/server/internal/handler/activity.go b/server/internal/handler/activity.go
index 06bffb593b..db195837c5 100644
--- a/server/internal/handler/activity.go
+++ b/server/internal/handler/activity.go
@@ -47,7 +47,8 @@ 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"`
+ DeletedAt *string `json:"deleted_at,omitempty"`
+ AgentDeliveries []CommentAgentDeliveryResponse `json:"agent_deliveries,omitempty"`
}
// timelineHardCap bounds the per-issue timeline payload. Sized as a defensive
@@ -283,6 +284,7 @@ func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []Ti
}
reactions := h.groupReactions(r, ids)
attachments := h.groupAttachments(r, ids)
+ deliveries := h.groupCommentAgentDeliveries(r.Context(), ids)
out := make([]TimelineEntry, len(comments))
for i, c := range comments {
@@ -291,24 +293,25 @@ func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []Ti
updatedAt := timestampToString(c.UpdatedAt)
cid := uuidToString(c.ID)
out[i] = TimelineEntry{
- Type: "comment",
- ID: cid,
- ActorType: c.AuthorType,
- ActorID: uuidToString(c.AuthorID),
- Content: &content,
- CommentType: &commentType,
- QuickActionID: uuidToPtr(c.QuickActionID),
- ParentID: uuidToPtr(c.ParentID),
- CreatedAt: timestampToString(c.CreatedAt),
- UpdatedAt: &updatedAt,
- Revision: c.Revision,
- Reactions: reactions[cid],
- Attachments: attachments[cid],
- ResolvedAt: timestampToPtr(c.ResolvedAt),
- ResolvedByType: textToPtr(c.ResolvedByType),
- ResolvedByID: uuidToPtr(c.ResolvedByID),
- SourceTaskID: uuidToPtr(c.SourceTaskID),
- DeletedAt: timestampToPtr(c.DeletedAt),
+ Type: "comment",
+ ID: cid,
+ ActorType: c.AuthorType,
+ ActorID: uuidToString(c.AuthorID),
+ Content: &content,
+ CommentType: &commentType,
+ QuickActionID: uuidToPtr(c.QuickActionID),
+ ParentID: uuidToPtr(c.ParentID),
+ CreatedAt: timestampToString(c.CreatedAt),
+ UpdatedAt: &updatedAt,
+ Revision: c.Revision,
+ Reactions: reactions[cid],
+ Attachments: attachments[cid],
+ ResolvedAt: timestampToPtr(c.ResolvedAt),
+ ResolvedByType: textToPtr(c.ResolvedByType),
+ ResolvedByID: uuidToPtr(c.ResolvedByID),
+ SourceTaskID: uuidToPtr(c.SourceTaskID),
+ DeletedAt: timestampToPtr(c.DeletedAt),
+ AgentDeliveries: deliveries[cid],
}
}
return out
diff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.go
index df2bac855c..6312bd1436 100644
--- a/server/internal/handler/admission.go
+++ b/server/internal/handler/admission.go
@@ -37,6 +37,8 @@ const (
// DispatchDeferred: admitted but intentionally not started yet (e.g. a
// backlog issue parked until promotion, or suppress_run).
DispatchDeferred DispatchStatus = "deferred"
+ // DispatchSteering: the comment was durably assigned to the current turn.
+ DispatchSteering DispatchStatus = "steering"
// DispatchBlocked: the run was refused. ReasonCode carries why.
DispatchBlocked DispatchStatus = "blocked"
)
@@ -53,6 +55,7 @@ const (
ReasonQueued = dispatch.ReasonQueued
ReasonCoalesced = dispatch.ReasonCoalesced
ReasonDeferred = dispatch.ReasonDeferred
+ ReasonSteering = dispatch.ReasonSteering
ReasonInvocationNotAllowed = dispatch.ReasonInvocationNotAllowed
ReasonTargetUnavailable = dispatch.ReasonTargetUnavailable
ReasonRuntimeOffline = dispatch.ReasonRuntimeOffline
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index fe447b17e5..1449affc64 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -1880,7 +1880,6 @@ func (h *Handler) CancelTaskByUser(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
-
resp := CancelTaskByUserResponse{
AgentTaskResponse: taskToResponse(cancelled.Task, workspaceID),
}
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 20dbe45249..9649d2706a 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -82,7 +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"`
+ TriggerOutcomes []CommentTriggerOutcome `json:"trigger_outcomes,omitempty"`
+ AgentDeliveries []CommentAgentDeliveryResponse `json:"agent_deliveries,omitempty"`
+}
+
+type CommentAgentDeliveryResponse struct {
+ AgentID string `json:"agent_id"`
+ AgentName string `json:"agent_name"`
+ Status string `json:"status"` // pending | delivered | follow_up
+ DeliveredAt *string `json:"delivered_at,omitempty"`
}
// CommentTriggerOutcome is the per-target result of an explicit @agent / @squad
@@ -644,11 +652,13 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {
}
grouped := h.groupReactions(r, commentIDs)
groupedAtt := h.groupAttachments(r, commentIDs)
+ deliveries := h.groupCommentAgentDeliveries(r.Context(), commentIDs)
resp := make([]CommentResponse, len(result.Comments))
for i, c := range result.Comments {
cid := uuidToString(c.ID)
resp[i] = commentToResponse(c, grouped[cid], groupedAtt[cid])
+ resp[i].AgentDeliveries = deliveries[cid]
// Attach roots_only orientation stats when present (nil map elsewhere).
if st, ok := result.RootStats[cid]; ok {
rc := st.ReplyCount
@@ -1502,6 +1512,7 @@ type CommentTriggerAgentResponse struct {
AvatarURL *string `json:"avatar_url,omitempty"`
Source string `json:"source"`
Reason string `json:"reason"`
+ Delivery string `json:"delivery"` // current_run | follow_up
}
type commentAgentTriggerSource string
@@ -1553,13 +1564,14 @@ func commentAgentTriggerReason(trigger commentAgentTrigger) string {
}
}
-func (h *Handler) commentAgentTriggerToResponse(trigger commentAgentTrigger) CommentTriggerAgentResponse {
+func (h *Handler) commentAgentTriggerToResponse(trigger commentAgentTrigger, delivery string) CommentTriggerAgentResponse {
return CommentTriggerAgentResponse{
ID: uuidToString(trigger.Agent.ID),
Name: trigger.Agent.Name,
AvatarURL: h.resolveAvatarURLPtr(textToPtr(trigger.Agent.AvatarUrl)),
Source: string(trigger.Source),
Reason: commentAgentTriggerReason(trigger),
+ Delivery: delivery,
}
}
@@ -1644,8 +1656,21 @@ func (h *Handler) PreviewCommentTriggers(w http.ResponseWriter, r *http.Request)
Agents: make([]CommentTriggerAgentResponse, 0, len(triggers)),
Blocked: commentBlockedTargetOutcomes(targets),
}
+ steerHeadSHA := pgtype.Text{}
+ if actorType == "member" && editingComment == nil && parentID.Valid {
+ steerHeadSHA = h.TaskService.ResolveIssueReviewSHAParam(r.Context(), issue.ID)
+ }
for _, trigger := range triggers {
- resp.Agents = append(resp.Agents, h.commentAgentTriggerToResponse(trigger))
+ delivery := "follow_up"
+ if actorType == "member" && editingComment == nil && parentID.Valid {
+ count, err := h.Queries.CountSteerableTasksForComment(r.Context(), db.CountSteerableTasksForCommentParams{
+ IssueID: issue.ID, AgentID: trigger.Agent.ID, CommentID: parentID, HeadSha: steerHeadSHA,
+ })
+ if err == nil && count == 1 {
+ delivery = "current_run"
+ }
+ }
+ resp.Agents = append(resp.Agents, h.commentAgentTriggerToResponse(trigger, delivery))
}
writeJSON(w, http.StatusOK, resp)
}
@@ -1951,10 +1976,63 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
// 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.AgentDeliveries = h.groupCommentAgentDeliveries(r.Context(), []pgtype.UUID{comment.ID})[uuidToString(comment.ID)]
+ if len(resp.AgentDeliveries) > 0 {
+ h.publish(protocol.EventCommentUpdated, uuidToString(issue.WorkspaceID), "system", "", map[string]any{
+ "comment": resp, "issue_revision": created.IssueRevision,
+ })
+ }
writeJSON(w, http.StatusCreated, resp)
}
+func (h *Handler) groupCommentAgentDeliveries(ctx context.Context, commentIDs []pgtype.UUID) map[string][]CommentAgentDeliveryResponse {
+ grouped := make(map[string][]CommentAgentDeliveryResponse)
+ if len(commentIDs) == 0 {
+ return grouped
+ }
+ rows, err := h.Queries.ListCommentAgentDeliveries(ctx, commentIDs)
+ if err != nil {
+ slog.Warn("list comment agent deliveries failed", "error", err)
+ return grouped
+ }
+ for _, row := range rows {
+ status := row.Status
+ if status == "steering" {
+ status = "pending"
+ }
+ grouped[uuidToString(row.CommentID)] = append(grouped[uuidToString(row.CommentID)], CommentAgentDeliveryResponse{
+ AgentID: uuidToString(row.AgentID), AgentName: row.AgentName, Status: status,
+ DeliveredAt: timestampToPtr(row.DeliveredAt),
+ })
+ }
+ return grouped
+}
+
+func (h *Handler) publishCommentDeliveryUpdate(r *http.Request, commentID pgtype.UUID) {
+ comment, err := h.Queries.GetComment(r.Context(), commentID)
+ if err != nil {
+ return
+ }
+ issue, err := h.Queries.GetIssue(r.Context(), comment.IssueID)
+ if err != nil {
+ return
+ }
+ id := uuidToString(comment.ID)
+ resp := commentToResponse(comment, h.groupReactions(r, []pgtype.UUID{comment.ID})[id], h.groupAttachments(r, []pgtype.UUID{comment.ID})[id])
+ resp.IssueRevision = issue.Revision
+ resp.AgentDeliveries = h.groupCommentAgentDeliveries(r.Context(), []pgtype.UUID{comment.ID})[id]
+ h.publish(protocol.EventCommentUpdated, uuidToString(issue.WorkspaceID), "system", "", map[string]any{
+ "comment": resp, "issue_revision": issue.Revision,
+ })
+}
+
+func (h *Handler) publishCommentDeliveryUpdates(r *http.Request, commentIDs []pgtype.UUID) {
+ for _, commentID := range commentIDs {
+ h.publishCommentDeliveryUpdate(r, commentID)
+ }
+}
+
// clientAuthorableCommentTypes is what POST /comments accepts. `status_change`
// and `system` are platform-generated narration, so a client claiming them
// would be forging system output; they are deliberately absent.
@@ -2001,7 +2079,7 @@ func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, co
})
triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)
h.noteBlockedRuntimeTargets(ctx, issue, targets)
- enqueued := h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
+ enqueued := h.enqueueCommentAgentTriggersWithSteer(ctx, issue, comment.ID, triggers, actorType == "member")
return commentTriggerOutcomes(targets, enqueued)
}
@@ -2069,10 +2147,18 @@ type commentEnqueueResult struct {
// executing agent) and returns the result keyed by executing agent id
// (MUL-4525 §2). Outcomes are later fanned from these to every explicit mention
// target that resolved to the agent, so coalescing a run never drops a named
-// target's outcome. queued / coalesced / deferred are success-shaped (the run
-// was handled, no duplicate task); only a real enqueue failure is blocked.
+// target's outcome. steering / queued / coalesced / deferred are success-shaped
+// (the run was handled, no duplicate task); only a real enqueue failure is blocked.
func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, triggers []commentAgentTrigger) map[string]commentEnqueueResult {
+ return h.enqueueCommentAgentTriggersWithSteer(ctx, issue, triggerCommentID, triggers, false)
+}
+
+func (h *Handler) enqueueCommentAgentTriggersWithSteer(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, triggers []commentAgentTrigger, allowSteer bool) map[string]commentEnqueueResult {
results := make(map[string]commentEnqueueResult, len(triggers))
+ steerHeadSHA := pgtype.Text{}
+ if allowSteer {
+ steerHeadSHA = h.TaskService.ResolveIssueReviewSHAParam(ctx, issue.ID)
+ }
record := func(trigger commentAgentTrigger, status DispatchStatus, reason DispatchReasonCode) {
execSquadID := ""
if trigger.Squad != nil {
@@ -2081,7 +2167,59 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu
results[uuidToString(trigger.Agent.ID)] = commentEnqueueResult{status: status, reason: reason, execSquadID: execSquadID}
}
for _, trigger := range triggers {
+ if allowSteer {
+ row, err := h.Queries.RegisterCommentSteer(ctx, db.RegisterCommentSteerParams{
+ CommentID: triggerCommentID,
+ AgentID: trigger.Agent.ID,
+ IssueID: issue.ID,
+ HeadSha: steerHeadSHA,
+ })
+ if err == nil && row.Status != "follow_up" {
+ h.requestDaemonPendingWork(uuidToString(row.RuntimeID), protocol.PendingWorkKindTaskSteer)
+ record(trigger, DispatchSteering, ReasonSteering)
+ continue
+ }
+ if errors.Is(err, pgx.ErrNoRows) {
+ // Registration is intentionally idempotent. A create retry or a
+ // comment edit can find the same delivery already pending, claimed,
+ // or delivered. None may fall through to the follow-up enqueue path:
+ // a claimed edit could otherwise inject the old body now and enqueue
+ // the edited body for a second run, while rewriting its receipt.
+ existing, loadErr := h.Queries.GetCommentAgentDelivery(ctx, db.GetCommentAgentDeliveryParams{
+ CommentID: triggerCommentID,
+ AgentID: trigger.Agent.ID,
+ })
+ if loadErr == nil {
+ switch existing.Status {
+ case "pending":
+ h.requestDaemonPendingWork(uuidToString(existing.RuntimeID), protocol.PendingWorkKindTaskSteer)
+ fallthrough
+ case "steering", "delivered":
+ record(trigger, DispatchSteering, ReasonSteering)
+ continue
+ }
+ } else if !errors.Is(loadErr, pgx.ErrNoRows) {
+ slog.Warn("load existing comment steer failed; falling back to follow-up",
+ "issue_id", uuidToString(issue.ID), "agent_id", uuidToString(trigger.Agent.ID), "error", loadErr)
+ }
+ } else if err != nil {
+ slog.Warn("register comment steer failed; falling back to follow-up",
+ "issue_id", uuidToString(issue.ID), "agent_id", uuidToString(trigger.Agent.ID), "error", err)
+ }
+ }
status, reason := h.resolveCommentTriggerEnqueue(ctx, issue, trigger, triggerCommentID)
+ if allowSteer && status != DispatchBlocked {
+ if err := h.Queries.RecordCommentFollowUpDelivery(ctx, db.RecordCommentFollowUpDeliveryParams{
+ CommentID: triggerCommentID,
+ AgentID: trigger.Agent.ID,
+ FailureReason: pgtype.Text{
+ String: string(reason), Valid: true,
+ },
+ }); err != nil {
+ slog.Warn("record comment follow-up receipt failed",
+ "issue_id", uuidToString(issue.ID), "agent_id", uuidToString(trigger.Agent.ID), "error", err)
+ }
+ }
record(trigger, status, reason)
}
return results
@@ -3405,7 +3543,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
// revision writes defer cancellation until the conditional UPDATE wins,
// so a race that returns 409 cannot mutate the task queue.
if !strictContentEdit {
- cancelled, err = h.TaskService.CancelTasksByTriggerComment(r.Context(), existing.ID)
+ cancelled, err = h.TaskService.CancelTasksByEditedComment(r.Context(), existing.ID)
if err != nil {
slog.Warn("cancel tasks for edited comment failed", "comment_id", uuidToString(existing.ID), "error", err)
writeError(w, http.StatusInternalServerError, "failed to prepare comment edit")
@@ -3448,7 +3586,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
issueRevision = updated.IssueRevision
}
if err == nil && oldContent != req.Content && strictContentEdit {
- cancelled, err = qtx.CancelAgentTasksByTriggerComment(r.Context(), existing.ID)
+ cancelled, err = qtx.CancelAgentTasksByEditedComment(r.Context(), existing.ID)
if err == nil {
err = service.SettleDeliveredDelegatedFailureRecoveries(r.Context(), qtx, cancelled...)
}
diff --git a/server/internal/handler/comment_steer_test.go b/server/internal/handler/comment_steer_test.go
new file mode 100644
index 0000000000..ea56e02d30
--- /dev/null
+++ b/server/internal/handler/comment_steer_test.go
@@ -0,0 +1,298 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type commentSteerFixture struct {
+ agentID, runtimeID, issueID, rootID, taskID string
+}
+
+func newCommentSteerFixture(t *testing.T, suffix string) commentSteerFixture {
+ t.Helper()
+ runtimeID := dbfx.Runtime(t, "comment-steer-"+suffix, testutil.Cols{
+ "provider": "codex",
+ "metadata": testutil.Raw(`jsonb_build_object('capabilities', jsonb_build_array('task-steer-v1'))`),
+ })
+ agentID := dbfx.Agent(t, "comment-steer-"+suffix, runtimeID, testutil.Cols{"max_concurrent_tasks": 2})
+ issueID := dbfx.Issue(t, "comment steer "+suffix, testutil.Cols{
+ "status": "in_progress", "assignee_type": "agent", "assignee_id": agentID,
+ })
+ rootID := dbfx.Comment(t, issueID, "initial instruction", testutil.Cols{
+ "created_at": testutil.Raw("now() - interval '10 minutes'"),
+ })
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "issue_id": issueID, "trigger_comment_id": rootID,
+ "comment_thread_id": rootID, "status": "running",
+ "created_at": testutil.Raw("now() - interval '9 minutes'"),
+ "started_at": testutil.Raw("now() - interval '8 minutes'"),
+ "delivered_comment_ids": testutil.Raw("ARRAY['" + rootID + "'::uuid]"),
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM comment_agent_delivery WHERE agent_id = $1`, agentID)
+ })
+ return commentSteerFixture{agentID: agentID, runtimeID: runtimeID, issueID: issueID, rootID: rootID, taskID: taskID}
+}
+
+func (f commentSteerFixture) reply(t *testing.T, content, age string) string {
+ t.Helper()
+ return dbfx.Comment(t, f.issueID, content, testutil.Cols{
+ "parent_id": f.rootID, "created_at": testutil.Raw("now() - interval '" + age + "'"),
+ })
+}
+
+func registerCommentSteer(t *testing.T, f commentSteerFixture, commentID string) db.RegisterCommentSteerRow {
+ t.Helper()
+ row, err := testHandler.Queries.RegisterCommentSteer(context.Background(), db.RegisterCommentSteerParams{
+ CommentID: util.MustParseUUID(commentID), AgentID: util.MustParseUUID(f.agentID), IssueID: util.MustParseUUID(f.issueID),
+ })
+ if err != nil {
+ t.Fatalf("register steer: %v", err)
+ }
+ return row
+}
+
+func TestCommentSteerRegistrationIsUniqueCapabilityGatedAndIdempotent(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ t.Run("unique supported task", func(t *testing.T) {
+ f := newCommentSteerFixture(t, "unique")
+ commentID := f.reply(t, "apply this constraint", "2 minutes")
+ row := registerCommentSteer(t, f, commentID)
+ if got := uuidToString(row.TaskID); got != f.taskID {
+ t.Fatalf("registered task = %s, want %s", got, f.taskID)
+ }
+ var planned, delivered bool
+ dbfx.QueryRow(t, `
+ SELECT $2::uuid = ANY(coalesced_comment_ids), $2::uuid = ANY(delivered_comment_ids)
+ FROM agent_task_queue WHERE id = $1
+ `, f.taskID, commentID).Scan(&planned, &delivered)
+ if !planned || delivered {
+ t.Fatalf("planned=%v delivered=%v, want true/false (option A)", planned, delivered)
+ }
+
+ // A transport retry cannot create a second receipt or mutate the task.
+ _, err := testHandler.Queries.RegisterCommentSteer(context.Background(), db.RegisterCommentSteerParams{
+ CommentID: util.MustParseUUID(commentID), AgentID: util.MustParseUUID(f.agentID), IssueID: util.MustParseUUID(f.issueID),
+ })
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("duplicate registration error = %v, want pgx.ErrNoRows", err)
+ }
+ var receiptCount, plannedCount int
+ dbfx.QueryRow(t, `SELECT count(*) FROM comment_agent_delivery WHERE comment_id=$1 AND agent_id=$2`, commentID, f.agentID).Scan(&receiptCount)
+ dbfx.QueryRow(t, `SELECT count(*) FROM unnest((SELECT coalesced_comment_ids FROM agent_task_queue WHERE id=$1)) id WHERE id=$2`, f.taskID, commentID).Scan(&plannedCount)
+ if receiptCount != 1 || plannedCount != 1 {
+ t.Fatalf("receipt count=%d planned count=%d, want 1/1", receiptCount, plannedCount)
+ }
+ })
+
+ t.Run("unsupported runtime", func(t *testing.T) {
+ f := newCommentSteerFixture(t, "unsupported")
+ commentID := f.reply(t, "must follow up", "2 minutes")
+ dbfx.Exec(t, `UPDATE agent_runtime SET metadata='{}'::jsonb WHERE id=$1`, f.runtimeID)
+ _, err := testHandler.Queries.RegisterCommentSteer(context.Background(), db.RegisterCommentSteerParams{
+ CommentID: util.MustParseUUID(commentID), AgentID: util.MustParseUUID(f.agentID), IssueID: util.MustParseUUID(f.issueID),
+ })
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("unsupported registration error = %v, want pgx.ErrNoRows", err)
+ }
+ if err := testHandler.Queries.RecordCommentFollowUpDelivery(context.Background(), db.RecordCommentFollowUpDeliveryParams{
+ CommentID: util.MustParseUUID(commentID), AgentID: util.MustParseUUID(f.agentID),
+ FailureReason: pgtype.Text{String: "runtime_unsupported", Valid: true},
+ }); err != nil {
+ t.Fatalf("record follow-up receipt: %v", err)
+ }
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM comment_agent_delivery WHERE comment_id=$1 AND agent_id=$2`, commentID, f.agentID).Scan(&status)
+ if status != "follow_up" {
+ t.Fatalf("unsupported receipt status = %s, want follow_up", status)
+ }
+ })
+
+ t.Run("OpenCode 2.x remains deny by default", func(t *testing.T) {
+ f := newCommentSteerFixture(t, "opencode-v2")
+ commentID := f.reply(t, "must follow up", "2 minutes")
+ // OpenCode 2.x is still provider=opencode. Even a new daemon advertising
+ // task-steer-v1 globally must not make this non-steerable Session eligible.
+ dbfx.Exec(t, `UPDATE agent_runtime SET provider='opencode' WHERE id=$1`, f.runtimeID)
+ _, err := testHandler.Queries.RegisterCommentSteer(context.Background(), db.RegisterCommentSteerParams{
+ CommentID: util.MustParseUUID(commentID), AgentID: util.MustParseUUID(f.agentID), IssueID: util.MustParseUUID(f.issueID),
+ })
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("OpenCode registration error = %v, want pgx.ErrNoRows", err)
+ }
+ })
+
+ t.Run("ambiguous active tasks", func(t *testing.T) {
+ f := newCommentSteerFixture(t, "ambiguous")
+ commentID := f.reply(t, "route only when unique", "2 minutes")
+ dbfx.Task(t, f.agentID, testutil.Cols{
+ "runtime_id": f.runtimeID, "issue_id": f.issueID, "trigger_comment_id": f.rootID,
+ "comment_thread_id": f.rootID, "status": "running", "started_at": testutil.Raw("now()"),
+ })
+ _, err := testHandler.Queries.RegisterCommentSteer(context.Background(), db.RegisterCommentSteerParams{
+ CommentID: util.MustParseUUID(commentID), AgentID: util.MustParseUUID(f.agentID), IssueID: util.MustParseUUID(f.issueID),
+ })
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("ambiguous registration error = %v, want pgx.ErrNoRows", err)
+ }
+ var receipts int
+ dbfx.QueryRow(t, `SELECT count(*) FROM comment_agent_delivery WHERE comment_id=$1`, commentID).Scan(&receipts)
+ if receipts != 0 {
+ t.Fatalf("ambiguous route created %d receipts, want 0", receipts)
+ }
+ })
+}
+
+func TestCommentSteerClaimsChronologicallyAndFallsBackAcrossTerminalRace(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ f := newCommentSteerFixture(t, "ordering")
+ olderID := f.reply(t, "older constraint", "4 minutes")
+ newerID := f.reply(t, "newer constraint", "2 minutes")
+ // Register out of order; claim order is the comments' durable chronology.
+ registerCommentSteer(t, f, newerID)
+ registerCommentSteer(t, f, olderID)
+
+ first, err := testHandler.Queries.ClaimNextCommentSteer(context.Background(), util.MustParseUUID(f.taskID))
+ if err != nil {
+ t.Fatalf("claim first: %v", err)
+ }
+ if got := uuidToString(first.CommentID); got != olderID {
+ t.Fatalf("first claim = %s, want older %s", got, olderID)
+ }
+ if _, err := testHandler.Queries.AckCommentSteerDelivered(context.Background(), db.AckCommentSteerDeliveredParams{
+ TaskID: util.MustParseUUID(f.taskID), CommentID: util.MustParseUUID(olderID),
+ }); err != nil {
+ t.Fatalf("ack first: %v", err)
+ }
+
+ second, err := testHandler.Queries.ClaimNextCommentSteer(context.Background(), util.MustParseUUID(f.taskID))
+ if err != nil {
+ t.Fatalf("claim second: %v", err)
+ }
+ if got := uuidToString(second.CommentID); got != newerID {
+ t.Fatalf("second claim = %s, want newer %s", got, newerID)
+ }
+ // Completion wins before the daemon's acknowledgement. The ack cannot claim
+ // success, and terminal reconciliation turns the instruction into follow-up.
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='completed', completed_at=now() WHERE id=$1`, f.taskID)
+ if _, err := testHandler.Queries.FinalizeUndeliveredCommentSteers(context.Background(), util.MustParseUUID(f.taskID)); err != nil {
+ t.Fatalf("finalize completed task: %v", err)
+ }
+ _, err = testHandler.Queries.AckCommentSteerDelivered(context.Background(), db.AckCommentSteerDeliveredParams{
+ TaskID: util.MustParseUUID(f.taskID), CommentID: util.MustParseUUID(newerID),
+ })
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("late ack error = %v, want pgx.ErrNoRows", err)
+ }
+ var olderStatus, newerStatus string
+ dbfx.QueryRow(t, `SELECT status FROM comment_agent_delivery WHERE comment_id=$1 AND agent_id=$2`, olderID, f.agentID).Scan(&olderStatus)
+ dbfx.QueryRow(t, `SELECT status FROM comment_agent_delivery WHERE comment_id=$1 AND agent_id=$2`, newerID, f.agentID).Scan(&newerStatus)
+ if olderStatus != "delivered" || newerStatus != "follow_up" {
+ t.Fatalf("receipt statuses = %s/%s, want delivered/follow_up", olderStatus, newerStatus)
+ }
+
+}
+
+func TestUpdateCommentDuringSteeringDoesNotQueueDuplicateOrRewriteReceipt(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ f := newCommentSteerFixture(t, "edit-in-flight")
+ commentID := f.reply(t, "old constraint", "2 minutes")
+ registerCommentSteer(t, f, commentID)
+ claimed, err := testHandler.Queries.ClaimNextCommentSteer(context.Background(), util.MustParseUUID(f.taskID))
+ if err != nil {
+ t.Fatalf("claim steer: %v", err)
+ }
+ if claimed.Content != "old constraint" {
+ t.Fatalf("claimed content = %q, want old constraint", claimed.Content)
+ }
+
+ updateCommentForTriggerPreviewTest(t, commentID, map[string]any{
+ "content": "edited constraint",
+ "expected_revision": 1,
+ })
+
+ var taskCount int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id=$1 AND agent_id=$2`, f.issueID, f.agentID).Scan(&taskCount)
+ if taskCount != 1 {
+ t.Fatalf("task count after in-flight edit = %d, want the original task only", taskCount)
+ }
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM comment_agent_delivery WHERE comment_id=$1 AND agent_id=$2`, commentID, f.agentID).Scan(&status)
+ if status != "steering" {
+ t.Fatalf("receipt after in-flight edit = %s, want steering", status)
+ }
+ if err := testHandler.Queries.RecordCommentFollowUpDelivery(context.Background(), db.RecordCommentFollowUpDeliveryParams{
+ CommentID: util.MustParseUUID(commentID), AgentID: util.MustParseUUID(f.agentID),
+ FailureReason: pgtype.Text{String: "stale_edit_fallback", Valid: true},
+ }); err != nil {
+ t.Fatalf("record stale follow-up: %v", err)
+ }
+ dbfx.QueryRow(t, `SELECT status FROM comment_agent_delivery WHERE comment_id=$1 AND agent_id=$2`, commentID, f.agentID).Scan(&status)
+ if status != "steering" {
+ t.Fatalf("stale fallback rewrote in-flight receipt to %s", status)
+ }
+ if _, err := testHandler.Queries.AckCommentSteerDelivered(context.Background(), db.AckCommentSteerDeliveredParams{
+ TaskID: util.MustParseUUID(f.taskID), CommentID: util.MustParseUUID(commentID),
+ }); err != nil {
+ t.Fatalf("ack historical delivery: %v", err)
+ }
+ dbfx.QueryRow(t, `SELECT status FROM comment_agent_delivery WHERE comment_id=$1 AND agent_id=$2`, commentID, f.agentID).Scan(&status)
+ if status != "delivered" {
+ t.Fatalf("historical receipt after ack = %s, want delivered", status)
+ }
+}
+
+func TestCancelTaskSettlesUndeliveredSteersWithoutStartingRun(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ f := newCommentSteerFixture(t, "stop")
+ deliveredID := f.reply(t, "already injected", "4 minutes")
+ pendingID := f.reply(t, "claimed but not injected", "2 minutes")
+ registerCommentSteer(t, f, deliveredID)
+ registerCommentSteer(t, f, pendingID)
+ if _, err := testHandler.Queries.ClaimNextCommentSteer(context.Background(), util.MustParseUUID(f.taskID)); err != nil {
+ t.Fatalf("claim delivered steer: %v", err)
+ }
+ if _, err := testHandler.Queries.AckCommentSteerDelivered(context.Background(), db.AckCommentSteerDeliveredParams{
+ TaskID: util.MustParseUUID(f.taskID), CommentID: util.MustParseUUID(deliveredID),
+ }); err != nil {
+ t.Fatalf("ack delivered steer: %v", err)
+ }
+ if _, err := testHandler.Queries.ClaimNextCommentSteer(context.Background(), util.MustParseUUID(f.taskID)); err != nil {
+ t.Fatalf("claim pending steer: %v", err)
+ }
+
+ req := newRequest(http.MethodPost, "/api/issues/"+f.issueID+"/tasks/"+f.taskID+"/cancel", nil)
+ req = withURLParams(req, "id", f.issueID, "taskId", f.taskID)
+ testutil.Call(t, testHandler.CancelTask, req).Want(http.StatusOK)
+
+ var deliveredStatus, pendingStatus string
+ var deliveredTimestampPreserved bool
+ dbfx.QueryRow(t, `SELECT status, delivered_at IS NOT NULL FROM comment_agent_delivery WHERE comment_id=$1 AND agent_id=$2`, deliveredID, f.agentID).Scan(&deliveredStatus, &deliveredTimestampPreserved)
+ dbfx.QueryRow(t, `SELECT status FROM comment_agent_delivery WHERE comment_id=$1 AND agent_id=$2`, pendingID, f.agentID).Scan(&pendingStatus)
+ if deliveredStatus != "delivered" || !deliveredTimestampPreserved || pendingStatus != "follow_up" {
+ t.Fatalf("receipts after Stop = delivered %s (timestamp=%v), pending %s; want delivered/true/follow_up",
+ deliveredStatus, deliveredTimestampPreserved, pendingStatus)
+ }
+ var taskCount int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id=$1 AND agent_id=$2`, f.issueID, f.agentID).Scan(&taskCount)
+ if taskCount != 1 {
+ t.Fatalf("task count after Stop = %d, want no replacement run", taskCount)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 4f21ab707a..eea44cce59 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1374,9 +1374,12 @@ func (h *Handler) processHeartbeat(ctx context.Context, runtimeID string, suppor
slog.Debug("daemon heartbeat", "runtime_id", runtimeID)
ack := &protocol.DaemonHeartbeatAckPayload{
- RuntimeID: runtimeID,
- Status: "ok",
- ServerCapabilities: []string{protocol.DaemonCapabilityRPCV1},
+ RuntimeID: runtimeID,
+ Status: "ok",
+ ServerCapabilities: []string{
+ protocol.DaemonCapabilityRPCV1,
+ protocol.DaemonCapabilityTaskSteerV1,
+ },
}
probeUpdateCtx, cancelProbeUpdate := context.WithTimeout(ctx, heartbeatHasPendingTimeout)
@@ -4082,6 +4085,106 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, taskToResponse(*task, workspaceID))
}
+// ClaimCommentSteer atomically claims the oldest pending human instruction for
+// an active task. Capability gating makes a mixed-version daemon fail safe:
+// old daemons never call this route and new daemons refuse to infer support
+// from a server version.
+func (h *Handler) ClaimCommentSteer(w http.ResponseWriter, r *http.Request) {
+ if !requestHasClientCapability(r, protocol.DaemonCapabilityTaskSteerV1) {
+ writeError(w, http.StatusPreconditionFailed, "task steering capability required")
+ return
+ }
+ taskID := chi.URLParam(r, "taskId")
+ if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {
+ return
+ }
+ row, err := h.Queries.ClaimNextCommentSteer(r.Context(), parseUUID(taskID))
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeJSON(w, http.StatusOK, map[string]any{})
+ return
+ }
+ if err != nil {
+ slog.Warn("claim comment steer failed", "task_id", taskID, "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to claim comment steer")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "comment_id": uuidToString(row.CommentID),
+ "author_name": row.AuthorName,
+ "content": row.Content,
+ })
+}
+
+type ackCommentSteerRequest struct {
+ Delivered bool `json:"delivered"`
+ Error string `json:"error,omitempty"`
+}
+
+// AckCommentSteer commits a receipt only while the target task is still
+// running. If completion won the race, the row becomes follow_up and normal
+// reconciliation remains responsible for it.
+func (h *Handler) AckCommentSteer(w http.ResponseWriter, r *http.Request) {
+ if !requestHasClientCapability(r, protocol.DaemonCapabilityTaskSteerV1) {
+ writeError(w, http.StatusPreconditionFailed, "task steering capability required")
+ return
+ }
+ taskID := chi.URLParam(r, "taskId")
+ if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {
+ return
+ }
+ commentID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "commentId"), "comment_id")
+ if !ok {
+ return
+ }
+ var req ackCommentSteerRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ status := "follow_up"
+ if req.Delivered {
+ if _, err := h.Queries.AckCommentSteerDelivered(r.Context(), db.AckCommentSteerDeliveredParams{
+ TaskID: parseUUID(taskID), CommentID: commentID,
+ }); err == nil {
+ status = "delivered"
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ slog.Warn("ack comment steer failed", "task_id", taskID, "comment_id", chi.URLParam(r, "commentId"), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to acknowledge comment steer")
+ return
+ }
+ }
+ if status == "follow_up" {
+ reason := strings.TrimSpace(req.Error)
+ if reason == "" {
+ reason = "turn_ended"
+ }
+ if _, err := h.Queries.MarkCommentSteerFollowUp(r.Context(), db.MarkCommentSteerFollowUpParams{
+ TaskID: parseUUID(taskID), CommentID: commentID, FailureReason: pgtype.Text{String: reason, Valid: true},
+ }); err != nil {
+ if !errors.Is(err, pgx.ErrNoRows) {
+ slog.Warn("mark comment steer follow-up failed", "task_id", taskID, "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to acknowledge comment steer")
+ return
+ }
+ existing, loadErr := h.Queries.GetCommentSteerDeliveryForTask(r.Context(), db.GetCommentSteerDeliveryForTaskParams{
+ TaskID: parseUUID(taskID), CommentID: commentID,
+ })
+ if errors.Is(loadErr, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "comment steer not found")
+ return
+ }
+ if loadErr != nil {
+ slog.Warn("load comment steer acknowledgement failed", "task_id", taskID, "error", loadErr)
+ writeError(w, http.StatusInternalServerError, "failed to acknowledge comment steer")
+ return
+ }
+ status = existing.Status
+ }
+ }
+ h.publishCommentDeliveryUpdate(r, commentID)
+ writeJSON(w, http.StatusOK, map[string]any{"status": status})
+}
+
// TaskWaitLocalDirectoryRequest is the body the daemon POSTs when it parks
// a freshly-dispatched task on a busy local_directory path.
type TaskWaitLocalDirectoryRequest struct {
@@ -4290,7 +4393,7 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
// it after its context was built), schedule a single follow-up so the
// input is not silently dropped. Agent replays are restricted to explicit
// mentions and recorded worker inputs; see reconcileCommentsOnCompletion.
- h.reconcileCommentsOnCompletion(r.Context(), task)
+ h.publishCommentDeliveryUpdates(r, h.reconcileCommentsOnCompletion(r.Context(), task))
// The terminal transaction and completion reconciliation are committed.
// Wake the owning runtime now so queued work that was blocked by this
// task's agent capacity or serialization key is re-claimed immediately.
@@ -4352,6 +4455,23 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A
))
}
+// finalizeUndeliveredCommentSteers settles only the receipt. It never schedules
+// work: completion reconciliation owns that behavior, while cancellation and
+// failure must preserve Stop semantics and any retry policy already committed
+// by TaskService. Delivered is a historical fact and is deliberately immutable.
+func (h *Handler) finalizeUndeliveredCommentSteers(ctx context.Context, taskID pgtype.UUID) []pgtype.UUID {
+ rows, err := h.Queries.FinalizeUndeliveredCommentSteers(ctx, taskID)
+ if err != nil {
+ slog.Warn("finalize comment steers failed", "task_id", uuidToString(taskID), "error", err)
+ return nil
+ }
+ updates := make([]pgtype.UUID, 0, len(rows))
+ for _, row := range rows {
+ updates = append(updates, row.CommentID)
+ }
+ return updates
+}
+
// reconcileCommentsOnCompletion closes the at-least-once gap for member
// comments a completing run did NOT deliver (MUL-4195).
//
@@ -4392,10 +4512,14 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A
// run, and terminating: the follow-up's own created_at is later than all of
// these comments and its delivered set will contain them, so its completion
// finds nothing to re-schedule.
-func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.AgentTaskQueue) {
+func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.AgentTaskQueue) []pgtype.UUID {
if task == nil || !task.IssueID.Valid || !task.AgentID.Valid || !task.CreatedAt.Valid {
- return
+ return nil
}
+ // Anything not acknowledged before completion keeps the old lossless
+ // follow-up semantics. Delivered steer receipts remain separate from
+ // delivered_comment_ids (approved option A).
+ deliveryUpdates := h.finalizeUndeliveredCommentSteers(ctx, task.ID)
plannedCommentIDs := append([]pgtype.UUID{}, task.CoalescedCommentIds...)
if task.TriggerCommentID.Valid {
plannedCommentIDs = append(plannedCommentIDs, task.TriggerCommentID)
@@ -4409,10 +4533,10 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
if err != nil {
slog.Warn("reconcile comments on completion: list comments failed",
"issue_id", uuidToString(task.IssueID), "task_id", uuidToString(task.ID), "error", err)
- return
+ return deliveryUpdates
}
if len(comments) == 0 {
- return
+ return deliveryUpdates
}
// The delivered set is the claim-time receipt, not the enqueue-time plan.
// Legacy tasks backfill only the primary trigger, deliberately replaying
@@ -4423,11 +4547,21 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
delivered[uuidToString(id)] = struct{}{}
}
}
+ if steered, err := h.Queries.ListDeliveredSteerCommentIDs(ctx, task.ID); err != nil {
+ slog.Warn("list delivered comment steers failed; preserving follow-up fallback",
+ "task_id", uuidToString(task.ID), "error", err)
+ } else {
+ for _, id := range steered {
+ if id.Valid {
+ delivered[uuidToString(id)] = struct{}{}
+ }
+ }
+ }
issue, err := h.Queries.GetIssue(ctx, task.IssueID)
if err != nil {
slog.Warn("reconcile comments on completion: load issue failed",
"issue_id", uuidToString(task.IssueID), "error", err)
- return
+ return deliveryUpdates
}
agentID := uuidToString(task.AgentID)
scheduled := 0
@@ -4539,6 +4673,7 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
"agent_id", agentID,
"undelivered_comments", scheduled)
}
+ return deliveryUpdates
}
// keepReplayableAgentTriggers preserves explicit mentions (MUL-4304) and
@@ -4986,6 +5121,9 @@ func (h *Handler) failTask(w http.ResponseWriter, r *http.Request, taskID, works
writeJSON(w, http.StatusOK, taskToResponse(*task, workspaceID))
return
}
+ // Failure may already have committed its own retry. Settle only undelivered
+ // steer receipts here; generic comment reconciliation is completion-only.
+ h.publishCommentDeliveryUpdates(r, h.finalizeUndeliveredCommentSteers(r.Context(), task.ID))
h.TaskService.NotifyTaskFinished(*task)
// Best-effort revoke of the mat_ task token minted at claim. Same
@@ -5438,6 +5576,10 @@ func (h *Handler) CancelTask(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
+ // Stop must not enqueue a replacement run. Pending/claimed steer receipts
+ // still become follow_up so the UI records that this turn did not receive
+ // them; delivered receipts remain immutable history.
+ h.publishCommentDeliveryUpdates(r, h.finalizeUndeliveredCommentSteers(r.Context(), task.ID))
slog.Info("task cancelled by user", "task_id", taskID, "issue_id", uuidToString(task.IssueID))
resp := taskToResponse(*task, workspaceID)
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 39ab0ebc84..bac1ad642a 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -54,6 +54,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"chat_session": workspaceDelete,
"client_usage_daily": workspaceDeleteDetach,
"comment": workspaceDelete,
+ "comment_agent_delivery": workspaceDelete,
"comment_reaction": workspaceDelete,
"contact_sales_inquiry": workspaceDeleteKeep,
"daemon_connection": workspaceDelete,
diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.go
index 748b68c1dd..cbd9917f09 100644
--- a/server/internal/handler/workspace_test.go
+++ b/server/internal/handler/workspace_test.go
@@ -536,6 +536,7 @@ RETURNING id
`, neighborSlug).Scan(&neighborWorkspaceID)
t.Cleanup(func() {
for _, workspaceID := range []string{targetWorkspaceID, neighborWorkspaceID} {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM comment_agent_delivery WHERE comment_id IN (SELECT id FROM comment WHERE workspace_id = $1)`, workspaceID)
_, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID)
_, _ = testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1`, workspaceID)
_, _ = testPool.Exec(context.Background(), `DELETE FROM runtime_profile WHERE workspace_id = $1`, workspaceID)
@@ -552,6 +553,7 @@ VALUES ($1, $2, 'owner')
workspaceID string
mediaKey string
issueID string
+ commentID string
}
fixtures := []*tenantFixture{
{workspaceID: targetWorkspaceID, mediaKey: targetMediaKey},
@@ -563,10 +565,15 @@ INSERT INTO issue (workspace_id, title, creator_type, creator_id)
VALUES ($1, 'Workspace delete tenant isolation', 'member', $2)
RETURNING id
`, fixture.workspaceID, testUserID).Scan(&fixture.issueID)
- dbfx.Exec(t, `
+ dbfx.QueryRow(t, `
INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
VALUES ($1, $2, 'member', $3, 'Workspace delete tenant isolation')
-`, fixture.issueID, fixture.workspaceID, testUserID)
+RETURNING id
+`, fixture.issueID, fixture.workspaceID, testUserID).Scan(&fixture.commentID)
+ dbfx.Exec(t, `
+INSERT INTO comment_agent_delivery (comment_id, agent_id, status)
+VALUES ($1, gen_random_uuid(), 'follow_up')
+`, fixture.commentID)
dbfx.Exec(t, `
INSERT INTO inbox_item (
workspace_id, recipient_type, recipient_id, type, issue_id, title
@@ -615,6 +622,20 @@ SELECT COUNT(*) FROM `+table+` WHERE `+predicate+` = $1
}
}
+ var targetDeliveryCount, neighborDeliveryCount int
+ dbfx.QueryRow(t, `
+SELECT COUNT(*) FROM comment_agent_delivery WHERE comment_id = $1
+`, fixtures[0].commentID).Scan(&targetDeliveryCount)
+ dbfx.QueryRow(t, `
+SELECT COUNT(*) FROM comment_agent_delivery WHERE comment_id = $1
+`, fixtures[1].commentID).Scan(&neighborDeliveryCount)
+ if targetDeliveryCount != 0 {
+ t.Fatalf("target comment delivery rows = %d, want 0", targetDeliveryCount)
+ }
+ if neighborDeliveryCount != 1 {
+ t.Fatalf("neighbor comment delivery rows = %d, want 1", neighborDeliveryCount)
+ }
+
var neighborMediaState string
dbfx.QueryRow(t, `
SELECT state
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 92810814e5..011f561797 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2704,6 +2704,33 @@ func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentID
return cancelled, nil
}
+// CancelTasksByEditedComment is the edit-specific counterpart to
+// CancelTasksByTriggerComment. It preserves a task that already owns a durable
+// steer receipt for the edited comment so the edit cannot inject the old body
+// and enqueue the new body as a second run.
+func (s *TaskService) CancelTasksByEditedComment(ctx context.Context, commentID pgtype.UUID) ([]db.AgentTaskQueue, error) {
+ var cancelled []db.AgentTaskQueue
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ var err error
+ cancelled, err = qtx.CancelAgentTasksByEditedComment(ctx, commentID)
+ if err != nil {
+ return err
+ }
+ return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...)
+ }); err != nil {
+ return nil, err
+ }
+ for _, t := range cancelled {
+ s.captureTaskCancelled(ctx, t)
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
+ }
+ for _, agentID := range distinctAgentIDs(cancelled) {
+ s.ReconcileAgentStatus(ctx, agentID)
+ }
+ s.notifyTasksFinished(cancelled)
+ return cancelled, nil
+}
+
// BroadcastCancelledTasks reconciles each affected agent's status and emits
// task:cancelled for every row. Callers must invoke this AFTER committing the
// cancellation so subscribers don't observe a "cancelled" event for a row
diff --git a/server/migrations/507_comment_agent_delivery.down.sql b/server/migrations/507_comment_agent_delivery.down.sql
new file mode 100644
index 0000000000..b5a0720927
--- /dev/null
+++ b/server/migrations/507_comment_agent_delivery.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS comment_agent_delivery;
diff --git a/server/migrations/507_comment_agent_delivery.up.sql b/server/migrations/507_comment_agent_delivery.up.sql
new file mode 100644
index 0000000000..6d289a13a9
--- /dev/null
+++ b/server/migrations/507_comment_agent_delivery.up.sql
@@ -0,0 +1,17 @@
+-- A delivery row is the durable receipt for one comment/agent steering
+-- decision. It deliberately has no foreign keys: issue, comment, task and
+-- runtime deletion must not turn terminal cleanup into a cascading lock tree.
+CREATE TABLE comment_agent_delivery (
+ comment_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ -- Follow-up receipts have no active target task/runtime. Steering rows do.
+ task_id UUID,
+ runtime_id UUID,
+ status TEXT NOT NULL CHECK (status IN ('pending', 'steering', 'delivered', 'follow_up')),
+ failure_reason TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ claimed_at TIMESTAMPTZ,
+ delivered_at TIMESTAMPTZ,
+ PRIMARY KEY (comment_id, agent_id)
+);
diff --git a/server/migrations/508_comment_agent_delivery_pending_index.down.sql b/server/migrations/508_comment_agent_delivery_pending_index.down.sql
new file mode 100644
index 0000000000..66f16f6419
--- /dev/null
+++ b/server/migrations/508_comment_agent_delivery_pending_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_agent_delivery_task_pending;
diff --git a/server/migrations/508_comment_agent_delivery_pending_index.up.sql b/server/migrations/508_comment_agent_delivery_pending_index.up.sql
new file mode 100644
index 0000000000..96ad954c21
--- /dev/null
+++ b/server/migrations/508_comment_agent_delivery_pending_index.up.sql
@@ -0,0 +1,3 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comment_agent_delivery_task_pending
+ ON comment_agent_delivery (task_id, created_at, comment_id)
+ WHERE status IN ('pending', 'steering');
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 2658bb445b..b0fee08034 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -147,6 +147,11 @@ func runContext(ctx context.Context, timeout time.Duration) (context.Context, co
// Session represents a running agent execution.
type Session struct {
+ // Steer delivers an additional human instruction to the currently active
+ // provider turn. Implementations must serialize writes with the provider's
+ // control protocol and fail once the authoritative terminal boundary has
+ // been observed. Nil means this backend cannot steer an active turn.
+ Steer func(context.Context, string) error
// ToolActivity optionally reports backend-owned tool accounting and its last
// transition time, independent of the best-effort transcript. Nil uses the
// daemon's message-based accounting. The timestamp gives completed tools a
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index f66bae1211..ac9b3439fd 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -103,8 +103,10 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
cancel()
return nil, fmt.Errorf("claude stdin pipe: %w", err)
}
+ input := &claudeInputStream{writer: stdin, closer: stdin}
+ var terminalResultObserved atomic.Bool
var closeStdinOnce sync.Once
- closeStdin := func() { closeStdinOnce.Do(func() { _ = stdin.Close() }) }
+ closeStdin := func() { closeStdinOnce.Do(func() { _ = input.Close() }) }
// Capture stderr into both the daemon log (as before) and a bounded tail
// buffer so we can include the last few KB in Result.Error when claude
// exits unexpectedly. Without the tail, an exit-code-only failure looks
@@ -147,7 +149,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
// timeout.
writeDone := make(chan error, 1)
go func() {
- err := writeClaudeInput(stdin, prompt)
+ err := writeClaudeInput(input, prompt)
if err != nil {
closeStdin()
}
@@ -244,6 +246,13 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})
case "result":
+ // Close the input stream at the authoritative boundary before parsing
+ // any result detail. Close flips its atomic gate before touching the
+ // descriptor, so an already-blocked write is interrupted and every
+ // later write is rejected. Only then publish the boundary to the
+ // daemon's terminal watchdog.
+ closeStdin()
+ terminalResultObserved.Store(true)
sawResult = true
finalResultText = msg.ResultText
resultIsError = msg.IsError
@@ -252,7 +261,6 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
if resultUsage := claudeResultUsage(msg, opts.Model); len(resultUsage) > 0 {
usage = resultUsage
}
- closeStdin()
case "log":
if msg.Log != nil {
trySend(msgCh, Message{
@@ -262,7 +270,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
})
}
case "control_request":
- b.handleControlRequest(msg, stdin)
+ b.handleControlRequest(msg, input)
}
}
scanErr := scanner.Err()
@@ -361,7 +369,21 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
}()
- return &Session{Messages: msgCh, Result: resCh}, nil
+ steer := func(ctx context.Context, instruction string) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if terminalResultObserved.Load() {
+ return errors.New("claude turn has already produced its terminal result")
+ }
+ return writeClaudeInput(input, instruction)
+ }
+ return &Session{
+ Steer: steer,
+ TerminalObserved: terminalResultObserved.Load,
+ Messages: msgCh,
+ Result: resCh,
+ }, nil
}
func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage, seenUsage map[string]struct{}) assistantTurn {
@@ -798,6 +820,36 @@ func writeClaudeInput(w io.Writer, prompt string) error {
return nil
}
+// claudeInputStream keeps user steer frames and control responses from
+// interleaving on Claude's shared stream-json stdin. Close atomically shuts the
+// gate before closing the descriptor, so a blocked write is interrupted and a
+// later steer fails without writing a partial frame.
+type claudeInputStream struct {
+ writeMu sync.Mutex
+ writer io.Writer
+ closer io.Closer
+ closed atomic.Bool
+}
+
+func (s *claudeInputStream) Write(data []byte) (int, error) {
+ s.writeMu.Lock()
+ defer s.writeMu.Unlock()
+ if s.closed.Load() {
+ return 0, errors.New("claude turn is no longer active")
+ }
+ return s.writer.Write(data)
+}
+
+func (s *claudeInputStream) Close() error {
+ // Do not wait for writeMu: Claude can emit before reading stdin, leaving the
+ // initial pipe Write blocked. Closing the descriptor is what releases that
+ // write during cancellation. The atomic gate prevents every later frame.
+ if s.closed.Swap(true) {
+ return nil
+ }
+ return s.closer.Close()
+}
+
func buildClaudeInput(prompt string) ([]byte, error) {
payload := map[string]any{
"type": "user",
diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.go
index cb794797a5..a7fad53076 100644
--- a/server/pkg/agent/claude_test.go
+++ b/server/pkg/agent/claude_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "io"
"log/slog"
"os"
"path/filepath"
@@ -1321,3 +1322,82 @@ func TestBuildClaudeArgsManagedSkillSettingsWins(t *testing.T) {
t.Fatalf("unrelated custom arg was dropped: %v", args)
}
}
+
+func TestClaudeInputStreamCloseUnblocksWriteAndRejectsLaterFrames(t *testing.T) {
+ reader, writer := io.Pipe()
+ defer reader.Close()
+ stream := &claudeInputStream{writer: writer, closer: writer}
+ written := make(chan error, 1)
+ go func() {
+ _, err := stream.Write([]byte("blocked"))
+ written <- err
+ }()
+ time.Sleep(10 * time.Millisecond)
+ if err := stream.Close(); err != nil {
+ t.Fatalf("close: %v", err)
+ }
+ select {
+ case <-written:
+ case <-time.After(time.Second):
+ t.Fatal("close did not unblock the active stdin write")
+ }
+ if _, err := stream.Write([]byte("late")); err == nil {
+ t.Fatal("write after terminal close succeeded")
+ }
+}
+
+func TestClaudeSteerRejectsAfterTerminalResultBeforeProcessExit(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ // Keep the process alive after its authoritative result so the test covers
+ // the exact window where the task row can still be running even though
+ // Claude will never consume another stdin frame.
+ fakePath := filepath.Join(t.TempDir(), "claude")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `echo '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-terminal","result":"done"}'` + "\n" +
+ "sleep 1\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("claude", Config{
+ ExecutablePath: fakePath,
+ Env: map[string]string{"IS_SANDBOX": "1"},
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new claude backend: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ session, err := backend.Execute(ctx, "initial prompt", ExecOptions{Timeout: 4 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ if session.TerminalObserved == nil {
+ t.Fatal("Claude session did not expose its terminal boundary")
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for !session.TerminalObserved() && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if !session.TerminalObserved() {
+ t.Fatal("Claude terminal result was not observed")
+ }
+ if err := session.Steer(context.Background(), "late instruction"); err == nil {
+ t.Fatal("steer succeeded after Claude's terminal result")
+ }
+ select {
+ case result := <-session.Result:
+ if result.Status != "completed" {
+ t.Fatalf("terminal fixture status = %q, want completed", result.Status)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("timeout waiting for Claude process cleanup")
+ }
+}
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 05f29185f4..7d0e511f4b 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -937,8 +937,24 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
}
msgCh := make(chan Message, 256)
resCh := make(chan Result, 1)
+ var sessionMu sync.RWMutex
+ currentSession := firstSession
+ steer := func(steerCtx context.Context, instruction string) error {
+ sessionMu.RLock()
+ session := currentSession
+ sessionMu.RUnlock()
+ if session == nil || session.Steer == nil {
+ return errors.New("codex turn is not steerable")
+ }
+ return session.Steer(steerCtx, instruction)
+ }
go func() {
+ defer func() {
+ sessionMu.Lock()
+ currentSession = nil
+ sessionMu.Unlock()
+ }()
defer close(msgCh)
defer close(resCh)
session := firstSession
@@ -951,6 +967,9 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
resCh <- Result{Status: "failed", Error: err.Error()}
return
}
+ sessionMu.Lock()
+ currentSession = session
+ sessionMu.Unlock()
}
// Hold back the leading session-pin status messages until this
// attempt proves it made real progress. A retry never continues the
@@ -1028,7 +1047,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
}
}()
- return &Session{Messages: msgCh, Result: resCh}, nil
+ return &Session{Steer: steer, Messages: msgCh, Result: resCh}, nil
}
func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecOptions, attempt int) (*Session, error) {
@@ -1906,7 +1925,24 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
}()
- return &Session{Messages: msgCh, Result: resCh}, nil
+ steer := func(steerCtx context.Context, instruction string) error {
+ return steerCodexTurn(steerCtx, c, instruction)
+ }
+ return &Session{Steer: steer, Messages: msgCh, Result: resCh}, nil
+}
+
+func steerCodexTurn(ctx context.Context, c *codexClient, instruction string) error {
+ threadID := c.getThreadID()
+ turnID := c.activeTurnID()
+ if threadID == "" || turnID == "" {
+ return errors.New("codex turn has not started")
+ }
+ _, err := c.request(ctx, "turn/steer", map[string]any{
+ "threadId": threadID,
+ "expectedTurnId": turnID,
+ "input": []map[string]any{{"type": "text", "text": instruction}},
+ })
+ return err
}
func resolveCodexHandshakeTimeouts(opts ExecOptions) (time.Duration, time.Duration) {
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index dd5f404a11..5a9a0233a7 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -42,6 +42,46 @@ func newTestCodexClient(t *testing.T) (*codexClient, *fakeStdin, []Message) {
return c, fs, messages
}
+func TestSteerCodexTurnUsesExpectedActiveTurn(t *testing.T) {
+ c, stdin, _ := newTestCodexClient(t)
+ c.setThreadID("thread-current")
+ c.setActiveTurnID("turn-current")
+ done := make(chan error, 1)
+ go func() { done <- steerCodexTurn(context.Background(), c, "new constraint") }()
+
+ deadline := time.Now().Add(time.Second)
+ for len(stdin.Lines()) == 0 && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ lines := stdin.Lines()
+ if len(lines) != 1 {
+ t.Fatalf("steer requests = %d, want 1", len(lines))
+ }
+ var request map[string]any
+ if err := json.Unmarshal([]byte(lines[0]), &request); err != nil {
+ t.Fatalf("decode request: %v", err)
+ }
+ if request["method"] != "turn/steer" {
+ t.Fatalf("method = %v", request["method"])
+ }
+ params := request["params"].(map[string]any)
+ if params["threadId"] != "thread-current" || params["expectedTurnId"] != "turn-current" {
+ t.Fatalf("params = %+v", params)
+ }
+ input, ok := params["input"].([]any)
+ if !ok || len(input) != 1 {
+ t.Fatalf("input = %#v, want one text item", params["input"])
+ }
+ item, ok := input[0].(map[string]any)
+ if !ok || item["type"] != "text" || item["text"] != "new constraint" {
+ t.Fatalf("input item = %#v", input[0])
+ }
+ c.handleLine(`{"jsonrpc":"2.0","id":1,"result":{}}`)
+ if err := <-done; err != nil {
+ t.Fatalf("steer: %v", err)
+ }
+}
+
type fakeStdin struct {
mu sync.Mutex
data []byte
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 8b31e59e25..51e486ee58 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -804,6 +804,109 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
return items, nil
}
+const cancelAgentTasksByEditedComment = `-- name: CancelAgentTasksByEditedComment :many
+UPDATE agent_task_queue t
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
+ cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL,
+ context = COALESCE(t.context, '{}'::jsonb) || jsonb_build_object('comment_change_cancelled_task_id', t.id::text)
+WHERE (t.trigger_comment_id = $1 OR $1 = ANY(t.coalesced_comment_ids))
+ AND t.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comment_agent_delivery d
+ WHERE d.comment_id = $1
+ AND d.agent_id = t.agent_id
+ AND d.task_id = t.id
+ AND d.status IN ('pending', 'steering', 'delivered')
+ )
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot
+`
+
+// Content edits normally invalidate tasks whose prompt may contain the old
+// body. A task with a durable steer receipt is the exception: pending claims
+// read the current body, while claimed/delivered rows must not be retriggered
+// because doing so executes both the old and edited instruction. Deletion keeps
+// using CancelAgentTasksByTriggerComment and cancels every matching task.
+func (q *Queries) CancelAgentTasksByEditedComment(ctx context.Context, commentID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelAgentTasksByEditedComment, commentID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 067434ef0a..2be181d149 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -585,6 +585,19 @@ type Comment struct {
DeletedAt pgtype.Timestamptz `json:"deleted_at"`
}
+type CommentAgentDelivery struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Status string `json:"status"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ ClaimedAt pgtype.Timestamptz `json:"claimed_at"`
+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`
+}
+
type CommentReaction struct {
ID pgtype.UUID `json:"id"`
CommentID pgtype.UUID `json:"comment_id"`
diff --git a/server/pkg/db/generated/steer.sql.go b/server/pkg/db/generated/steer.sql.go
new file mode 100644
index 0000000000..2c09f83a7d
--- /dev/null
+++ b/server/pkg/db/generated/steer.sql.go
@@ -0,0 +1,442 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: steer.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const ackCommentSteerDelivered = `-- name: AckCommentSteerDelivered :one
+WITH active_task AS (
+ SELECT id FROM agent_task_queue
+ WHERE id = $1 AND status = 'running'
+ FOR UPDATE
+)
+UPDATE comment_agent_delivery d
+SET status = 'delivered', delivered_at = COALESCE(delivered_at, now()), updated_at = now(), failure_reason = NULL
+FROM active_task t
+WHERE d.task_id = $1
+ AND d.comment_id = $2
+ AND d.status IN ('steering', 'delivered')
+ AND t.id = d.task_id
+RETURNING comment_id, agent_id, task_id, runtime_id, status, delivered_at
+`
+
+type AckCommentSteerDeliveredParams struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+}
+
+type AckCommentSteerDeliveredRow struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Status string `json:"status"`
+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`
+}
+
+func (q *Queries) AckCommentSteerDelivered(ctx context.Context, arg AckCommentSteerDeliveredParams) (AckCommentSteerDeliveredRow, error) {
+ row := q.db.QueryRow(ctx, ackCommentSteerDelivered, arg.TaskID, arg.CommentID)
+ var i AckCommentSteerDeliveredRow
+ err := row.Scan(
+ &i.CommentID,
+ &i.AgentID,
+ &i.TaskID,
+ &i.RuntimeID,
+ &i.Status,
+ &i.DeliveredAt,
+ )
+ return i, err
+}
+
+const claimNextCommentSteer = `-- name: ClaimNextCommentSteer :one
+WITH next_delivery AS (
+ SELECT d.comment_id, d.agent_id
+ FROM comment_agent_delivery d
+ JOIN comment c ON c.id = d.comment_id
+ JOIN agent_task_queue t ON t.id = d.task_id
+ WHERE d.task_id = $1
+ AND d.status = 'pending'
+ AND c.author_type = 'member'
+ AND t.status = 'running'
+ ORDER BY c.created_at, c.id
+ FOR UPDATE OF d SKIP LOCKED
+ LIMIT 1
+), claimed AS (
+ UPDATE comment_agent_delivery d
+ SET status = 'steering', claimed_at = now(), updated_at = now()
+ FROM next_delivery n
+ WHERE d.comment_id = n.comment_id AND d.agent_id = n.agent_id
+ RETURNING d.comment_id, d.agent_id, d.task_id
+)
+SELECT claimed.comment_id, claimed.agent_id, claimed.task_id, c.content,
+ COALESCE(NULLIF(btrim(u.name), ''), 'a user')::text AS author_name
+FROM claimed
+JOIN comment c ON c.id = claimed.comment_id
+LEFT JOIN "user" u ON u.id = c.author_id
+`
+
+type ClaimNextCommentSteerRow struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ Content string `json:"content"`
+ AuthorName string `json:"author_name"`
+}
+
+func (q *Queries) ClaimNextCommentSteer(ctx context.Context, taskID pgtype.UUID) (ClaimNextCommentSteerRow, error) {
+ row := q.db.QueryRow(ctx, claimNextCommentSteer, taskID)
+ var i ClaimNextCommentSteerRow
+ err := row.Scan(
+ &i.CommentID,
+ &i.AgentID,
+ &i.TaskID,
+ &i.Content,
+ &i.AuthorName,
+ )
+ return i, err
+}
+
+const countSteerableTasksForComment = `-- name: CountSteerableTasksForComment :one
+SELECT count(*)
+FROM agent_task_queue t
+JOIN agent_runtime r ON r.id = t.runtime_id
+WHERE t.issue_id = $1
+ AND t.agent_id = $2
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($3::uuid)
+ AND t.status = 'running'
+ AND (
+ COALESCE($4::text, '') = ''
+ OR t.context->>'head_sha' = $4::text
+ )
+ AND r.provider IN ('codex', 'claude')
+ AND COALESCE(r.metadata->'capabilities', '[]'::jsonb) ? 'task-steer-v1'
+`
+
+type CountSteerableTasksForCommentParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ HeadSha pgtype.Text `json:"head_sha"`
+}
+
+func (q *Queries) CountSteerableTasksForComment(ctx context.Context, arg CountSteerableTasksForCommentParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countSteerableTasksForComment,
+ arg.IssueID,
+ arg.AgentID,
+ arg.CommentID,
+ arg.HeadSha,
+ )
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const finalizeUndeliveredCommentSteers = `-- name: FinalizeUndeliveredCommentSteers :many
+UPDATE comment_agent_delivery
+SET status = 'follow_up', failure_reason = 'turn_ended', updated_at = now()
+WHERE task_id = $1 AND status IN ('pending', 'steering')
+RETURNING comment_id, agent_id
+`
+
+type FinalizeUndeliveredCommentSteersRow struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+func (q *Queries) FinalizeUndeliveredCommentSteers(ctx context.Context, taskID pgtype.UUID) ([]FinalizeUndeliveredCommentSteersRow, error) {
+ rows, err := q.db.Query(ctx, finalizeUndeliveredCommentSteers, taskID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []FinalizeUndeliveredCommentSteersRow{}
+ for rows.Next() {
+ var i FinalizeUndeliveredCommentSteersRow
+ if err := rows.Scan(&i.CommentID, &i.AgentID); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const getCommentAgentDelivery = `-- name: GetCommentAgentDelivery :one
+SELECT comment_id, agent_id, task_id, runtime_id, status, delivered_at
+FROM comment_agent_delivery
+WHERE comment_id = $1 AND agent_id = $2
+`
+
+type GetCommentAgentDeliveryParams struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+type GetCommentAgentDeliveryRow struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Status string `json:"status"`
+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`
+}
+
+func (q *Queries) GetCommentAgentDelivery(ctx context.Context, arg GetCommentAgentDeliveryParams) (GetCommentAgentDeliveryRow, error) {
+ row := q.db.QueryRow(ctx, getCommentAgentDelivery, arg.CommentID, arg.AgentID)
+ var i GetCommentAgentDeliveryRow
+ err := row.Scan(
+ &i.CommentID,
+ &i.AgentID,
+ &i.TaskID,
+ &i.RuntimeID,
+ &i.Status,
+ &i.DeliveredAt,
+ )
+ return i, err
+}
+
+const getCommentSteerDeliveryForTask = `-- name: GetCommentSteerDeliveryForTask :one
+SELECT comment_id, agent_id, task_id, runtime_id, status, delivered_at
+FROM comment_agent_delivery
+WHERE task_id = $1 AND comment_id = $2
+`
+
+type GetCommentSteerDeliveryForTaskParams struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+}
+
+type GetCommentSteerDeliveryForTaskRow struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Status string `json:"status"`
+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`
+}
+
+func (q *Queries) GetCommentSteerDeliveryForTask(ctx context.Context, arg GetCommentSteerDeliveryForTaskParams) (GetCommentSteerDeliveryForTaskRow, error) {
+ row := q.db.QueryRow(ctx, getCommentSteerDeliveryForTask, arg.TaskID, arg.CommentID)
+ var i GetCommentSteerDeliveryForTaskRow
+ err := row.Scan(
+ &i.CommentID,
+ &i.AgentID,
+ &i.TaskID,
+ &i.RuntimeID,
+ &i.Status,
+ &i.DeliveredAt,
+ )
+ return i, err
+}
+
+const listCommentAgentDeliveries = `-- name: ListCommentAgentDeliveries :many
+SELECT d.comment_id, d.agent_id, a.name AS agent_name, d.status, d.delivered_at
+FROM comment_agent_delivery d
+JOIN agent a ON a.id = d.agent_id
+WHERE d.comment_id = ANY($1::uuid[])
+ORDER BY d.created_at, d.agent_id
+`
+
+type ListCommentAgentDeliveriesRow struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ AgentName string `json:"agent_name"`
+ Status string `json:"status"`
+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`
+}
+
+func (q *Queries) ListCommentAgentDeliveries(ctx context.Context, commentIds []pgtype.UUID) ([]ListCommentAgentDeliveriesRow, error) {
+ rows, err := q.db.Query(ctx, listCommentAgentDeliveries, commentIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListCommentAgentDeliveriesRow{}
+ for rows.Next() {
+ var i ListCommentAgentDeliveriesRow
+ if err := rows.Scan(
+ &i.CommentID,
+ &i.AgentID,
+ &i.AgentName,
+ &i.Status,
+ &i.DeliveredAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listDeliveredSteerCommentIDs = `-- name: ListDeliveredSteerCommentIDs :many
+SELECT comment_id
+FROM comment_agent_delivery
+WHERE task_id = $1 AND status = 'delivered'
+`
+
+func (q *Queries) ListDeliveredSteerCommentIDs(ctx context.Context, taskID pgtype.UUID) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listDeliveredSteerCommentIDs, taskID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var comment_id pgtype.UUID
+ if err := rows.Scan(&comment_id); err != nil {
+ return nil, err
+ }
+ items = append(items, comment_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const markCommentSteerFollowUp = `-- name: MarkCommentSteerFollowUp :one
+UPDATE comment_agent_delivery
+SET status = 'follow_up', failure_reason = $1, updated_at = now()
+WHERE task_id = $2
+ AND comment_id = $3
+ AND status IN ('pending', 'steering')
+RETURNING comment_id, agent_id, task_id, runtime_id, status, delivered_at
+`
+
+type MarkCommentSteerFollowUpParams struct {
+ FailureReason pgtype.Text `json:"failure_reason"`
+ TaskID pgtype.UUID `json:"task_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+}
+
+type MarkCommentSteerFollowUpRow struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Status string `json:"status"`
+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`
+}
+
+func (q *Queries) MarkCommentSteerFollowUp(ctx context.Context, arg MarkCommentSteerFollowUpParams) (MarkCommentSteerFollowUpRow, error) {
+ row := q.db.QueryRow(ctx, markCommentSteerFollowUp, arg.FailureReason, arg.TaskID, arg.CommentID)
+ var i MarkCommentSteerFollowUpRow
+ err := row.Scan(
+ &i.CommentID,
+ &i.AgentID,
+ &i.TaskID,
+ &i.RuntimeID,
+ &i.Status,
+ &i.DeliveredAt,
+ )
+ return i, err
+}
+
+const recordCommentFollowUpDelivery = `-- name: RecordCommentFollowUpDelivery :exec
+INSERT INTO comment_agent_delivery (
+ comment_id, agent_id, task_id, runtime_id, status, failure_reason
+)
+VALUES ($1, $2, NULL, NULL, 'follow_up', $3)
+ON CONFLICT (comment_id, agent_id) DO NOTHING
+`
+
+type RecordCommentFollowUpDeliveryParams struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+}
+
+// Human comment recipients always get a durable per-agent receipt. This is
+// recorded after the existing enqueue/coalescing path succeeds when steering
+// is unsupported, ambiguous, or loses its registration race.
+func (q *Queries) RecordCommentFollowUpDelivery(ctx context.Context, arg RecordCommentFollowUpDeliveryParams) error {
+ _, err := q.db.Exec(ctx, recordCommentFollowUpDelivery, arg.CommentID, arg.AgentID, arg.FailureReason)
+ return err
+}
+
+const registerCommentSteer = `-- name: RegisterCommentSteer :one
+WITH candidates AS MATERIALIZED (
+ SELECT t.id, t.runtime_id
+ FROM agent_task_queue t
+ JOIN agent_runtime r ON r.id = t.runtime_id
+ WHERE t.issue_id = $1
+ AND t.agent_id = $2
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($3::uuid)
+ AND t.status = 'running'
+ AND (
+ COALESCE($4::text, '') = ''
+ OR t.context->>'head_sha' = $4::text
+ )
+ AND r.provider IN ('codex', 'claude')
+ AND COALESCE(r.metadata->'capabilities', '[]'::jsonb) ? 'task-steer-v1'
+ FOR UPDATE OF t
+), winner AS (
+ SELECT id, runtime_id FROM candidates
+ WHERE (SELECT count(*) FROM candidates) = 1
+ LIMIT 1
+), reserved AS (
+ INSERT INTO comment_agent_delivery (comment_id, agent_id, task_id, runtime_id, status)
+ SELECT $3, $2, id, runtime_id, 'pending' FROM winner
+ ON CONFLICT (comment_id, agent_id) DO NOTHING
+ RETURNING comment_id, agent_id, task_id, runtime_id, status, delivered_at
+), attached AS (
+ UPDATE agent_task_queue t
+ SET coalesced_comment_ids = (
+ SELECT COALESCE(array_agg(DISTINCT e), '{}')
+ FROM unnest(array_append(t.coalesced_comment_ids, $3::uuid)) AS e
+ WHERE e IS NOT NULL
+ )
+ FROM reserved r
+ WHERE t.id = r.task_id AND t.status = 'running'
+ RETURNING t.id
+)
+SELECT r.comment_id, r.agent_id, r.task_id, r.runtime_id, r.status, r.delivered_at
+FROM reserved r JOIN attached a ON a.id = r.task_id
+`
+
+type RegisterCommentSteerParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ HeadSha pgtype.Text `json:"head_sha"`
+}
+
+type RegisterCommentSteerRow struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Status string `json:"status"`
+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`
+}
+
+func (q *Queries) RegisterCommentSteer(ctx context.Context, arg RegisterCommentSteerParams) (RegisterCommentSteerRow, error) {
+ row := q.db.QueryRow(ctx, registerCommentSteer,
+ arg.IssueID,
+ arg.AgentID,
+ arg.CommentID,
+ arg.HeadSha,
+ )
+ var i RegisterCommentSteerRow
+ err := row.Scan(
+ &i.CommentID,
+ &i.AgentID,
+ &i.TaskID,
+ &i.RuntimeID,
+ &i.Status,
+ &i.DeliveredAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 90db014839..dbcdc013b1 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -182,9 +182,20 @@ func (q *Queries) DeleteWorkspaceChatMessages(ctx context.Context, workspaceID p
}
const deleteWorkspaceComments = `-- name: DeleteWorkspaceComments :exec
-DELETE FROM comment WHERE comment.workspace_id = $1
+WITH
+ws_comments AS MATERIALIZED (
+ SELECT id FROM comment WHERE comment.workspace_id = $1
+),
+deleted_comment_agent_deliveries AS (
+ DELETE FROM comment_agent_delivery
+ WHERE comment_id IN (SELECT id FROM ws_comments)
+)
+DELETE FROM comment WHERE id IN (SELECT id FROM ws_comments)
`
+// Steering receipts intentionally have no foreign key so terminal task cleanup
+// cannot cascade through issue history. Remove them explicitly through their
+// canonical owner (the comment) before deleting the workspace's comments.
func (q *Queries) DeleteWorkspaceComments(ctx context.Context, workspaceID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteWorkspaceComments, workspaceID)
return err
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 440426fd7e..e70c6c1980 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -686,6 +686,28 @@ WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
+-- name: CancelAgentTasksByEditedComment :many
+-- Content edits normally invalidate tasks whose prompt may contain the old
+-- body. A task with a durable steer receipt is the exception: pending claims
+-- read the current body, while claimed/delivered rows must not be retriggered
+-- because doing so executes both the old and edited instruction. Deletion keeps
+-- using CancelAgentTasksByTriggerComment and cancels every matching task.
+UPDATE agent_task_queue t
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
+ cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL,
+ context = COALESCE(t.context, '{}'::jsonb) || jsonb_build_object('comment_change_cancelled_task_id', t.id::text)
+WHERE (t.trigger_comment_id = @comment_id OR @comment_id = ANY(t.coalesced_comment_ids))
+ AND t.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comment_agent_delivery d
+ WHERE d.comment_id = @comment_id
+ AND d.agent_id = t.agent_id
+ AND d.task_id = t.id
+ AND d.status IN ('pending', 'steering', 'delivered')
+ )
+RETURNING t.*;
+
-- name: CancelAgentTasksByChatSession :many
-- Cancels active tasks belonging to a chat session. Called from
-- DeleteChatSession so the daemon doesn't keep running work whose result
diff --git a/server/pkg/db/queries/steer.sql b/server/pkg/db/queries/steer.sql
new file mode 100644
index 0000000000..c432145032
--- /dev/null
+++ b/server/pkg/db/queries/steer.sql
@@ -0,0 +1,140 @@
+-- name: CountSteerableTasksForComment :one
+SELECT count(*)
+FROM agent_task_queue t
+JOIN agent_runtime r ON r.id = t.runtime_id
+WHERE t.issue_id = @issue_id
+ AND t.agent_id = @agent_id
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(@comment_id::uuid)
+ AND t.status = 'running'
+ AND (
+ COALESCE(sqlc.narg('head_sha')::text, '') = ''
+ OR t.context->>'head_sha' = sqlc.narg('head_sha')::text
+ )
+ AND r.provider IN ('codex', 'claude')
+ AND COALESCE(r.metadata->'capabilities', '[]'::jsonb) ? 'task-steer-v1';
+
+-- name: RegisterCommentSteer :one
+WITH candidates AS MATERIALIZED (
+ SELECT t.id, t.runtime_id
+ FROM agent_task_queue t
+ JOIN agent_runtime r ON r.id = t.runtime_id
+ WHERE t.issue_id = @issue_id
+ AND t.agent_id = @agent_id
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(@comment_id::uuid)
+ AND t.status = 'running'
+ AND (
+ COALESCE(sqlc.narg('head_sha')::text, '') = ''
+ OR t.context->>'head_sha' = sqlc.narg('head_sha')::text
+ )
+ AND r.provider IN ('codex', 'claude')
+ AND COALESCE(r.metadata->'capabilities', '[]'::jsonb) ? 'task-steer-v1'
+ FOR UPDATE OF t
+), winner AS (
+ SELECT id, runtime_id FROM candidates
+ WHERE (SELECT count(*) FROM candidates) = 1
+ LIMIT 1
+), reserved AS (
+ INSERT INTO comment_agent_delivery (comment_id, agent_id, task_id, runtime_id, status)
+ SELECT @comment_id, @agent_id, id, runtime_id, 'pending' FROM winner
+ ON CONFLICT (comment_id, agent_id) DO NOTHING
+ RETURNING comment_id, agent_id, task_id, runtime_id, status, delivered_at
+), attached AS (
+ UPDATE agent_task_queue t
+ SET coalesced_comment_ids = (
+ SELECT COALESCE(array_agg(DISTINCT e), '{}')
+ FROM unnest(array_append(t.coalesced_comment_ids, @comment_id::uuid)) AS e
+ WHERE e IS NOT NULL
+ )
+ FROM reserved r
+ WHERE t.id = r.task_id AND t.status = 'running'
+ RETURNING t.id
+)
+SELECT r.comment_id, r.agent_id, r.task_id, r.runtime_id, r.status, r.delivered_at
+FROM reserved r JOIN attached a ON a.id = r.task_id;
+
+-- name: RecordCommentFollowUpDelivery :exec
+-- Human comment recipients always get a durable per-agent receipt. This is
+-- recorded after the existing enqueue/coalescing path succeeds when steering
+-- is unsupported, ambiguous, or loses its registration race.
+INSERT INTO comment_agent_delivery (
+ comment_id, agent_id, task_id, runtime_id, status, failure_reason
+)
+VALUES (@comment_id, @agent_id, NULL, NULL, 'follow_up', @failure_reason)
+ON CONFLICT (comment_id, agent_id) DO NOTHING;
+
+-- name: GetCommentAgentDelivery :one
+SELECT comment_id, agent_id, task_id, runtime_id, status, delivered_at
+FROM comment_agent_delivery
+WHERE comment_id = @comment_id AND agent_id = @agent_id;
+
+-- name: ClaimNextCommentSteer :one
+WITH next_delivery AS (
+ SELECT d.comment_id, d.agent_id
+ FROM comment_agent_delivery d
+ JOIN comment c ON c.id = d.comment_id
+ JOIN agent_task_queue t ON t.id = d.task_id
+ WHERE d.task_id = @task_id
+ AND d.status = 'pending'
+ AND c.author_type = 'member'
+ AND t.status = 'running'
+ ORDER BY c.created_at, c.id
+ FOR UPDATE OF d SKIP LOCKED
+ LIMIT 1
+), claimed AS (
+ UPDATE comment_agent_delivery d
+ SET status = 'steering', claimed_at = now(), updated_at = now()
+ FROM next_delivery n
+ WHERE d.comment_id = n.comment_id AND d.agent_id = n.agent_id
+ RETURNING d.comment_id, d.agent_id, d.task_id
+)
+SELECT claimed.comment_id, claimed.agent_id, claimed.task_id, c.content,
+ COALESCE(NULLIF(btrim(u.name), ''), 'a user')::text AS author_name
+FROM claimed
+JOIN comment c ON c.id = claimed.comment_id
+LEFT JOIN "user" u ON u.id = c.author_id;
+
+-- name: AckCommentSteerDelivered :one
+WITH active_task AS (
+ SELECT id FROM agent_task_queue
+ WHERE id = @task_id AND status = 'running'
+ FOR UPDATE
+)
+UPDATE comment_agent_delivery d
+SET status = 'delivered', delivered_at = COALESCE(delivered_at, now()), updated_at = now(), failure_reason = NULL
+FROM active_task t
+WHERE d.task_id = @task_id
+ AND d.comment_id = @comment_id
+ AND d.status IN ('steering', 'delivered')
+ AND t.id = d.task_id
+RETURNING comment_id, agent_id, task_id, runtime_id, status, delivered_at;
+
+-- name: MarkCommentSteerFollowUp :one
+UPDATE comment_agent_delivery
+SET status = 'follow_up', failure_reason = @failure_reason, updated_at = now()
+WHERE task_id = @task_id
+ AND comment_id = @comment_id
+ AND status IN ('pending', 'steering')
+RETURNING comment_id, agent_id, task_id, runtime_id, status, delivered_at;
+
+-- name: GetCommentSteerDeliveryForTask :one
+SELECT comment_id, agent_id, task_id, runtime_id, status, delivered_at
+FROM comment_agent_delivery
+WHERE task_id = @task_id AND comment_id = @comment_id;
+
+-- name: FinalizeUndeliveredCommentSteers :many
+UPDATE comment_agent_delivery
+SET status = 'follow_up', failure_reason = 'turn_ended', updated_at = now()
+WHERE task_id = @task_id AND status IN ('pending', 'steering')
+RETURNING comment_id, agent_id;
+
+-- name: ListDeliveredSteerCommentIDs :many
+SELECT comment_id
+FROM comment_agent_delivery
+WHERE task_id = @task_id AND status = 'delivered';
+
+-- name: ListCommentAgentDeliveries :many
+SELECT d.comment_id, d.agent_id, a.name AS agent_name, d.status, d.delivered_at
+FROM comment_agent_delivery d
+JOIN agent a ON a.id = d.agent_id
+WHERE d.comment_id = ANY(@comment_ids::uuid[])
+ORDER BY d.created_at, d.agent_id;
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 49d8876ff0..82d8d4bf50 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -530,7 +530,18 @@ deleted_channel_installations AS (
DELETE FROM lark_installation WHERE lark_installation.workspace_id = $1;
-- name: DeleteWorkspaceComments :exec
-DELETE FROM comment WHERE comment.workspace_id = $1;
+-- Steering receipts intentionally have no foreign key so terminal task cleanup
+-- cannot cascade through issue history. Remove them explicitly through their
+-- canonical owner (the comment) before deleting the workspace's comments.
+WITH
+ws_comments AS MATERIALIZED (
+ SELECT id FROM comment WHERE comment.workspace_id = $1
+),
+deleted_comment_agent_deliveries AS (
+ DELETE FROM comment_agent_delivery
+ WHERE comment_id IN (SELECT id FROM ws_comments)
+)
+DELETE FROM comment WHERE id IN (SELECT id FROM ws_comments);
-- name: DeleteWorkspaceIssueRoots :exec
WITH
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 664400c8c2..e19586e4ab 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -61,6 +61,10 @@ const (
// work, so such a daemon keeps getting a fresh directory and the parent's
// stays untouched on disk.
DaemonCapabilityCheckoutKeepsWorkV1 = "checkout-keeps-work-v1"
+ // DaemonCapabilityTaskSteerV1 advertises lossless human-comment delivery to
+ // an already-running Codex or Claude turn. Servers must fall back to the
+ // existing follow-up path when this capability is absent.
+ DaemonCapabilityTaskSteerV1 = "task-steer-v1"
// AppCapabilityChatDraftRestoreV1 is advertised (X-Client-Capabilities) by
// app clients that understand the durable draft-restore recovery path:
@@ -151,6 +155,7 @@ const (
PendingWorkKindModelList = "model_list"
PendingWorkKindLocalSkills = "local_skills"
PendingWorkKindLocalSkillImport = "local_skill_import"
+ PendingWorkKindTaskSteer = "task_steer"
)
// PendingWorkPayload is sent from server to daemon as a wakeup hint when a