Skip to content

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

Go

MUL-7480: Revert comment steering feature (#8648)

Multica Eve8c9f865e3ec7
diff --git a/apps/docs/content/docs/mentioning-agents.mdx b/apps/docs/content/docs/mentioning-agents.mdx
index aad643c650..cfbad275d5 100644
--- a/apps/docs/content/docs/mentioning-agents.mdx
+++ b/apps/docs/content/docs/mentioning-agents.mdx
@@ -47,13 +47,7 @@ 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 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.
-
-After that run publishes its final reply, the delivered receipt adds **View final reply**. Use it to scroll to and highlight the run's single answer in the original discussion. Receipts do not show this link while the run is still working, when the comment is waiting for follow-up work, or when the run ended without an answer.
+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 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.test.ts b/packages/core/api/schemas.test.ts
index 8d8eeb39f2..62163e9954 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -29,7 +29,6 @@ import {
ChatPendingTaskSchema,
ChatSessionListSchema,
ChatSessionSchema,
- CommentSchema,
PrioritizeQueuedChatTaskResponseSchema,
CreateFeedbackResponseSchema,
DuplicateIssueErrorBodySchema,
@@ -542,54 +541,6 @@ describe("IssueTriggerPreviewSchema", () => {
});
describe("TimelineEntriesSchema", () => {
- it("preserves optional and nullable delivery task ids across server versions", () => {
- const baseComment = {
- type: "comment",
- id: "comment-1",
- actor_type: "member",
- actor_id: "user-1",
- created_at: "2026-01-01T00:00:00Z",
- content: "Steered input",
- };
- const parsed = TimelineEntriesSchema.parse([
- {
- ...baseComment,
- agent_deliveries: [
- { agent_id: "a1", agent_name: "Walt", task_id: "task-1", status: "delivered" },
- { agent_id: "a2", agent_name: "Bob", task_id: null, status: "follow_up" },
- { agent_id: "a3", agent_name: "Kim", status: "pending" },
- ],
- },
- ]);
-
- expect(parsed[0]?.agent_deliveries?.map((delivery) => delivery.task_id)).toEqual([
- "task-1",
- null,
- undefined,
- ]);
- });
-
- it("keeps old comment responses valid when delivery task_id is absent", () => {
- const parsed = CommentSchema.parse({
- id: "comment-1",
- issue_id: "issue-1",
- author_type: "member",
- author_id: "user-1",
- content: "Legacy receipt",
- type: "comment",
- parent_id: null,
- reactions: [],
- attachments: [],
- created_at: "2026-01-01T00:00:00Z",
- updated_at: "2026-01-01T00:00:00Z",
- agent_deliveries: [
- { agent_id: "a1", agent_name: "Walt", status: "delivered" },
- ],
- });
-
- expect(parsed.agent_deliveries?.[0]?.task_id).toBeUndefined();
- });
-
it("preserves source_task_id for agent failure comments", () => {
const parsed = TimelineEntriesSchema.parse([
{
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 3aa6bdc83b..6edb9541a1 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -915,13 +915,6 @@ 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(),
- task_id: z.string().nullable().optional(),
- 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),
@@ -1064,13 +1057,6 @@ 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(),
- task_id: z.string().nullable().optional(),
- 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),
@@ -1104,7 +1090,6 @@ 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 99c0c3baf8..412224444f 100644
--- a/packages/core/issues/comment-trigger-outcomes.test.ts
+++ b/packages/core/issues/comment-trigger-outcomes.test.ts
@@ -27,12 +27,11 @@ describe("comment trigger outcomes", () => {
expect(parseCommentTriggerOutcomes("nope")).toEqual([]);
});
- it("treats queued/coalesced/deferred/steering as handled; blocked warns", () => {
+ it("treats only queued/coalesced/deferred 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 29d7f3d2af..e5cb8ec40a 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", "steering"]);
+const HANDLED_TRIGGER_STATUSES = new Set(["queued", "coalesced", "deferred"]);
// 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 12de2fce96..7a469e4b01 100644
--- a/packages/core/types/activity.ts
+++ b/packages/core/types/activity.ts
@@ -1,4 +1,4 @@
-import type { CommentAgentDelivery, CommentAuthorType, Reaction } from "./comment";
+import type { CommentAuthorType, Reaction } from "./comment";
import type { Attachment } from "./attachment";
export interface AssigneeFrequencyEntry {
@@ -33,7 +33,6 @@ 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 e9d63d37a8..b0bcf5a8f6 100644
--- a/packages/core/types/comment.ts
+++ b/packages/core/types/comment.ts
@@ -47,19 +47,6 @@ 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;
- /**
- * Run associated with this receipt. Older servers omit it and receipts
- * created directly as follow-up have no task, so accept both forms.
- */
- task_id?: string | null;
- status: "pending" | "delivered" | "follow_up" | string;
- delivered_at?: string | null;
}
// The domain result of one explicitly-mentioned trigger target. Success-shaped
@@ -69,7 +56,6 @@ export type CommentTriggerStatus =
| "queued"
| "coalesced"
| "deferred"
- | "steering"
| "blocked";
export interface CommentTriggerOutcome {
@@ -90,7 +76,6 @@ 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 b936d51aca..ba3c091e15 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, CommentAgentDelivery, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";
+export type { Comment, 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 b365567147..9a26340a4e 100644
--- a/packages/views/issues/components/comment-card.test.tsx
+++ b/packages/views/issues/components/comment-card.test.tsx
@@ -1,8 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+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(),
@@ -42,7 +41,7 @@ vi.mock("@multica/core/paths", async (importOriginal) => {
};
});
-import { AttachmentList, CommentDeliveryReceipts } from "./comment-card";
+import { AttachmentList } from "./comment-card";
function renderWithQuery(ui: ReactElement) {
const qc = new QueryClient({
@@ -54,68 +53,6 @@ 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();
- expect(screen.queryByRole("button")).toBeNull();
- });
-
- it("locates only delivered recipients that already have a final reply", () => {
- const onLocateComment = vi.fn();
- const repliesByTask = new Map([
- ["task-1", { id: "reply-1", comment_type: "comment" } as any],
- ["task-2", { id: "reply-2", comment_type: "comment" } as any],
- ["task-deleted", { id: "reply-deleted", comment_type: "comment", deleted_at: "2026-01-01T00:00:00Z" } as any],
- ["task-failed", { id: "failure-comment", comment_type: "system" } as any],
- ]);
- renderWithI18n(
- <CommentDeliveryReceipts
- entry={{
- agent_deliveries: [
- { agent_id: "a1", agent_name: "Walt", task_id: "task-1", status: "delivered" },
- { agent_id: "a2", agent_name: "Bob", task_id: "task-2", status: "delivered" },
- { agent_id: "a3", agent_name: "Kim", task_id: "task-1", status: "pending" },
- { agent_id: "a4", agent_name: "Eve", task_id: "task-2", status: "follow_up" },
- { agent_id: "a5", agent_name: "Running", task_id: "task-running", status: "delivered" },
- { agent_id: "a6", agent_name: "Deleted", task_id: "task-deleted", status: "delivered" },
- { agent_id: "a7", agent_name: "Failed", task_id: "task-failed", status: "delivered" },
- { agent_id: "a8", agent_name: "Cancelled", task_id: "task-cancelled", status: "delivered" },
- { agent_id: "a9", agent_name: "Edited", task_id: "task-edited", status: "delivered" },
- ],
- } as any}
- repliesByTask={repliesByTask}
- onLocateComment={onLocateComment}
- />,
- );
-
- const links = screen.getAllByRole("button", { name: /View final reply/ });
- expect(links).toHaveLength(2);
- fireEvent.click(links[0]!);
- fireEvent.click(links[1]!);
- expect(onLocateComment.mock.calls).toEqual([["reply-1"], ["reply-2"]]);
- expect(screen.getByText("Waiting to deliver to Kim's current work")).toBeInTheDocument();
- expect(screen.getByText("Eve will handle this in follow-up work")).toBeInTheDocument();
- expect(screen.getByText(/Delivered to Running's current work/).closest("button")).toBeNull();
- expect(screen.getByText(/Delivered to Deleted's current work/).closest("button")).toBeNull();
- expect(screen.getByText(/Delivered to Failed's current work/).closest("button")).toBeNull();
- expect(screen.getByText(/Delivered to Cancelled's current work/).closest("button")).toBeNull();
- expect(screen.getByText(/Delivered to Edited's current work/).closest("button")).toBeNull();
- });
-});
-
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 32b48cb4a9..04e6450088 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { Fragment, memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { CheckCircle2, ChevronRight, ListChevronsDownUp, Copy, Link2, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Card } from "@multica/ui/components/ui/card";
@@ -48,7 +48,7 @@ import { CommentsFoldBar } from "./resolved-thread-bar";
import { deriveThreadResolution } from "./thread-utils";
import { RevisionConflictCompare } from "./revision-conflict-compare";
import { InlineCommentRun, useInlineCommentRunState, type InlineCommentRunState } from "./inline-comment-run";
-import { EMPTY_COMMENT_RUNS, finalAgentReplyByTask, showCommentRunInHeader, type CommentRun } from "./comment-runs";
+import { EMPTY_COMMENT_RUNS, showCommentRunInHeader, type CommentRun } from "./comment-runs";
import { useCommentAnnotations } from "./use-comment-annotations";
import { useRunCommentMotion } from "./use-run-comment-motion";
@@ -60,52 +60,6 @@ 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,
- repliesByTask,
- onLocateComment,
- className,
-}: {
- entry: TimelineEntry;
- repliesByTask?: ReadonlyMap<string, TimelineEntry>;
- onLocateComment?: (commentId: string) => void;
- 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 });
- const reply = delivery.status === "delivered" && delivery.task_id
- ? repliesByTask?.get(delivery.task_id)
- : undefined;
- if (!reply || reply.comment_type !== "comment" || reply.deleted_at || !onLocateComment) {
- return <div key={delivery.agent_id}>{text}</div>;
- }
- return (
- <button
- type="button"
- key={delivery.agent_id}
- onClick={() => onLocateComment(reply.id)}
- className="w-fit cursor-pointer text-left hover:text-foreground hover:underline"
- >
- {text} · {t(($) => $.comment.delivery_view_reply)}
- </button>
- );
- })}
- </div>
- );
-}
-
function StickyHeaderShell({
className,
sticky = true,
@@ -189,8 +143,6 @@ interface CommentCardProps {
*/
expandedResolvedIds?: ReadonlySet<string>;
onResolvedExpandChange?: (rootId: string, expand: boolean) => void;
- /** Scroll and flash a delivered steer run's existing final reply. */
- onLocateComment?: (commentId: string) => void;
/** ID of the comment to highlight (flash animation). */
highlightedCommentId?: string | null;
}
@@ -669,8 +621,6 @@ function CommentRow({
onCreateSubIssue,
onResolveToggle,
onCopyLink,
- deliveryRepliesByTask,
- onLocateComment,
}: {
runHeader?: ReactNode;
runMetadata?: ReactNode;
@@ -690,8 +640,6 @@ function CommentRow({
onCreateSubIssue?: (commentId: string) => void;
onResolveToggle?: (commentId: string, resolved: boolean) => void;
onCopyLink?: (commentId: string) => void;
- deliveryRepliesByTask?: ReadonlyMap<string, TimelineEntry>;
- onLocateComment?: (commentId: string) => void;
}) {
const { t } = useT("issues");
const locale = useLocale();
@@ -932,12 +880,6 @@ 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}
- repliesByTask={deliveryRepliesByTask}
- onLocateComment={onLocateComment}
- className="pl-12 pr-4 max-md:pl-3 max-md:pr-3"
- />
{retryableAgentFailureComment(entry) && (
<TaskCommentRetryButton
issueId={issueId}
@@ -1029,7 +971,6 @@ function CommentCardImpl({
onCollapseResolved,
expandedResolvedIds,
onResolvedExpandChange,
- onLocateComment,
highlightedCommentId,
}: CommentCardProps) {
const { t } = useT("issues");
@@ -1064,10 +1005,6 @@ function CommentCardImpl({
const [confirmDelete, setConfirmDelete] = useState(false);
const allNestedReplies = replies;
- const deliveryRepliesByTask = useMemo(
- () => finalAgentReplyByTask([entry, ...allNestedReplies]),
- [entry, allNestedReplies],
- );
// What the thread shows. Tombstones are excluded from display and counts but
// stay in `allNestedReplies`, which run anchoring and "has replies" reason
// over. Every tombstone has at least one live descendant (the server prunes
@@ -1096,7 +1033,6 @@ function CommentCardImpl({
<AgentRunComment run={run} entering={enteringRunIds?.has(run.task.id)} commentProps={reply ? {
issueId, entry: reply, replies: [], currentUserId, canModerate, onReply, onEdit, onDelete,
onToggleReaction, onCreateSubIssue, onResolveToggle, onCopyLink, highlightedCommentId, enteringRunIds,
- onLocateComment,
} : undefined} />{reply && reply.id !== commentId && renderAnchoredRuns(reply.id)}</Fragment>;
});
@@ -1128,8 +1064,6 @@ function CommentCardImpl({
onCreateSubIssue={onCreateSubIssue}
onResolveToggle={onResolveToggle}
onCopyLink={onCopyLink}
- deliveryRepliesByTask={deliveryRepliesByTask}
- onLocateComment={onLocateComment}
/>
</div>
)}
@@ -1448,12 +1382,6 @@ 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}
- repliesByTask={deliveryRepliesByTask}
- onLocateComment={onLocateComment}
- className="pl-8 max-md:pl-0"
- />
{retryableAgentFailureComment(entry) && (
<TaskCommentRetryButton
issueId={issueId}
@@ -1518,8 +1446,6 @@ function CommentCardImpl({
onCreateSubIssue={onCreateSubIssue}
onResolveToggle={onResolveToggle}
onCopyLink={onCopyLink}
- deliveryRepliesByTask={deliveryRepliesByTask}
- onLocateComment={onLocateComment}
/>
</div>
{renderAnchoredRuns(resolutionReply.id)}
diff --git a/packages/views/issues/components/comment-runs.test.ts b/packages/views/issues/components/comment-runs.test.ts
index 813b430919..d314fe28ea 100644
--- a/packages/views/issues/components/comment-runs.test.ts
+++ b/packages/views/issues/components/comment-runs.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import type { AgentTask, TimelineEntry } from "@multica/core/types";
-import { commentRunOutput, buildCommentRunView, finalAgentReplyByTask, orderTimelineWithRuns, type CommentRun } from "./comment-runs";
+import { commentRunOutput, buildCommentRunView, orderTimelineWithRuns, type CommentRun } from "./comment-runs";
const groupCommentRuns = (...args: Parameters<typeof buildCommentRunView>) => buildCommentRunView(...args).runs;
@@ -13,31 +13,6 @@ function comment(id: string, overrides: Partial<TimelineEntry> = {}): TimelineEn
return { id, type: "comment", actor_type: "member", actor_id: "user", created_at: "2026-09-07T00:00:00Z", ...overrides };
}
-describe("finalAgentReplyByTask", () => {
- it("keeps the latest eligible answer when newer task-owned rows are system or deleted comments", () => {
- const answer = comment("answer", {
- actor_type: "agent",
- source_task_id: "run",
- comment_type: "comment",
- });
- const failure = comment("failure", {
- actor_type: "agent",
- source_task_id: "run",
- comment_type: "system",
- created_at: "2026-09-07T00:01:00Z",
- });
- const deleted = comment("deleted", {
- actor_type: "agent",
- source_task_id: "run",
- comment_type: "comment",
- deleted_at: "2026-09-07T00:03:00Z",
- created_at: "2026-09-07T00:02:00Z",
- });
-
- expect(finalAgentReplyByTask([answer, failure, deleted]).get("run")).toBe(answer);
- });
-});
-
describe("groupCommentRuns", () => {
it.each(["queued", "dispatched", "running", "completed"] as const)("waits for a missing trigger before placing a %s run and its reply", (status) => {
const run = task("run", { status, trigger_comment_id: "trigger",
diff --git a/packages/views/issues/components/comment-runs.ts b/packages/views/issues/components/comment-runs.ts
index f9d5f02653..b73a4b034c 100644
--- a/packages/views/issues/components/comment-runs.ts
+++ b/packages/views/issues/components/comment-runs.ts
@@ -22,45 +22,6 @@ export function isActiveCommentRun(task: AgentTask): boolean {
return ["queued", "dispatched", "waiting_local_directory", "running"].includes(task.status);
}
-/**
- * Index the published agent reply for each task. A run has one final comment,
- * but choosing the latest row keeps mixed-version and retry data deterministic
- * in the same way as the existing run projection.
- */
-export function agentReplyByTask(
- timeline: readonly TimelineEntry[],
-): ReadonlyMap<string, TimelineEntry> {
- const replies = new Map<string, TimelineEntry>();
- for (const entry of timeline) {
- if (entry.type !== "comment" || !entry.source_task_id || entry.actor_type !== "agent") continue;
- const prior = replies.get(entry.source_task_id);
- if (!prior || entry.created_at > prior.created_at || (entry.created_at === prior.created_at && entry.id > prior.id)) {
- replies.set(entry.source_task_id, entry);
- }
- }
- return replies;
-}
-
-/**
- * Index replies that can be a delivered steer receipt's final-answer target.
- * Filter before choosing the latest row so a later task-owned system failure
- * or deleted comment cannot hide an earlier published answer for that task.
- */
-export function finalAgentReplyByTask(
- timeline: readonly TimelineEntry[],
-): ReadonlyMap<string, TimelineEntry> {
- const replies = new Map<string, TimelineEntry>();
- for (const entry of timeline) {
- if (entry.type !== "comment" || !entry.source_task_id || entry.actor_type !== "agent"
- || entry.comment_type !== "comment" || entry.deleted_at) continue;
- const prior = replies.get(entry.source_task_id);
- if (!prior || entry.created_at > prior.created_at || (entry.created_at === prior.created_at && entry.id > prior.id)) {
- replies.set(entry.source_task_id, entry);
- }
- }
- return replies;
-}
-
/** Published replies own their log entry even while the agent finishes its run. */
export function showCommentRunInHeader(run: CommentRun): boolean {
return run.hasReply && (isActiveCommentRun(run.task) || run.task.status === "completed");
@@ -94,7 +55,14 @@ export function buildCommentRunView(
}
return entry?.id;
};
- const replies = agentReplyByTask(timeline);
+ const replies = new Map<string, TimelineEntry>();
+ for (const entry of comments.values()) {
+ if (!entry.source_task_id || entry.actor_type !== "agent") continue;
+ const prior = replies.get(entry.source_task_id);
+ if (!prior || entry.created_at > prior.created_at || (entry.created_at === prior.created_at && entry.id > prior.id)) {
+ replies.set(entry.source_task_id, entry);
+ }
+ }
const topLevelOutputs = new Map<string, TimelineEntry[]>();
for (const entry of comments.values()) {
if (!entry.source_task_id || entry.actor_type !== "agent" || entry.parent_id) continue;
diff --git a/packages/views/issues/components/comment-trigger-chips.test.tsx b/packages/views/issues/components/comment-trigger-chips.test.tsx
index 6fa96ecfea..6474369de3 100644
--- a/packages/views/issues/components/comment-trigger-chips.test.tsx
+++ b/packages/views/issues/components/comment-trigger-chips.test.tsx
@@ -98,17 +98,6 @@ 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
@@ -118,7 +107,7 @@ describe("CommentTriggerChips", () => {
/>,
);
- expect(screen.getByRole("button")).toHaveTextContent("2 agents will receive this");
+ expect(screen.getByRole("button")).toHaveTextContent("2 agents will start when sent");
});
it("counts only non-suppressed agents in the sentence", () => {
@@ -130,7 +119,7 @@ describe("CommentTriggerChips", () => {
/>,
);
- expect(screen.getByRole("button")).toHaveTextContent("1 agent will receive this");
+ expect(screen.getByRole("button")).toHaveTextContent("1 agent will start when sent");
});
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 792bf0c97c..90b1457bed 100644
--- a/packages/views/issues/components/comment-trigger-chips.tsx
+++ b/packages/views/issues/components/comment-trigger-chips.tsx
@@ -90,12 +90,6 @@ 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({
@@ -121,10 +115,7 @@ 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 destination = agent.delivery === "current_run"
- ? t(($) => $.comment.trigger_current_safe_point)
- : presenceLine;
- const line = [sourceReason(agent, t), destination].filter(Boolean).join(" ");
+ const line = [sourceReason(agent, t), presenceLine].filter(Boolean).join(" ");
return line ? <div>{line}</div> : null;
})()}
<div className="text-muted-foreground">{t(($) => $.comment.trigger_click_to_skip)}</div>
@@ -255,9 +246,7 @@ function SingleTriggerChip({
// so it stays fixed-width and never truncates on long agent names.
const sentence = suppressed
? t(($) => $.comment.trigger_wont_trigger)
- : agent.delivery === "current_run"
- ? t(($) => $.comment.trigger_will_update_current)
- : t(($) => $.comment.trigger_will_start);
+ : t(($) => $.comment.trigger_will_start);
return (
<Tooltip>
@@ -311,7 +300,7 @@ function MultiTriggerChip({
const sentence =
activeCount === 0
? t(($) => $.comment.trigger_none_will_trigger)
- : t(($) => $.comment.trigger_will_receive_count, { count: activeCount });
+ : t(($) => $.comment.trigger_will_start_count, { count: activeCount });
const popoverTrigger = (
<PopoverTrigger
@@ -375,7 +364,7 @@ function MultiTriggerChip({
const suppressed = suppressedAgentIds.has(agent.id);
const state = suppressed
? t(($) => $.comment.trigger_skipped_label)
- : deliveryLabel(agent, t);
+ : sourceLabel(agent.source, t);
return (
<Tooltip key={agent.id}>
<TooltipTrigger
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 4d8f907ef9..a29559e515 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -1279,149 +1279,6 @@ describe("IssueDetail (shared)", () => {
expect(mockApiObj.listTaskMessages).toHaveBeenCalledWith(taskId);
});
- it("scrolls to and highlights the final reply from a delivered steer receipt", async () => {
- const taskId = "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc";
- const root: TimelineEntry = {
- ...mockTimeline[0]!,
- id: "steer-root",
- parent_id: null,
- created_at: "2026-01-16T00:00:00Z",
- };
- const steer: TimelineEntry = {
- ...mockTimeline[0]!,
- id: "steer-input",
- parent_id: root.id,
- content: "Also include the deployment risk",
- created_at: "2026-01-16T00:01:00Z",
- agent_deliveries: [
- { agent_id: "agent-1", agent_name: "Claude Agent", task_id: taskId, status: "delivered" },
- ],
- };
- const finalReply: TimelineEntry = {
- ...mockTimeline[1]!,
- id: "steer-final-reply",
- parent_id: root.id,
- source_task_id: taskId,
- content: "Original answer with the deployment risk included",
- created_at: "2026-01-16T00:02:00Z",
- };
- const laterFailure: TimelineEntry = {
- ...mockTimeline[1]!,
- id: "steer-later-failure",
- parent_id: root.id,
- source_task_id: taskId,
- content: "The already-published task later reported a failure",
- comment_type: "system",
- created_at: "2026-01-16T00:03:00Z",
- };
- mockApiObj.listTimeline.mockResolvedValue([root, steer, finalReply, laterFailure]);
- mockApiObj.listTasksByIssue.mockResolvedValue([{
- id: taskId,
- agent_id: "agent-1",
- runtime_id: "runtime-1",
- issue_id: "issue-1",
- status: "completed",
- priority: 0,
- created_at: root.created_at,
- started_at: root.created_at,
- dispatched_at: root.created_at,
- completed_at: finalReply.created_at,
- result: { comment: finalReply.content },
- error: null,
- trigger_comment_id: root.id,
- delivered_comment_ids: [root.id],
- } as AgentTask]);
-
- renderIssueDetail();
- const locate = await screen.findByRole("button", { name: /View final reply/ });
- fireEvent.click(locate);
-
- await waitFor(() => {
- expect(hasHighlightedCommentBackground(document.getElementById("comment-steer-final-reply"))).toBe(true);
- });
- expect(scrollToIndexSpy).toHaveBeenCalledWith({ index: 0, align: "start", offset: -16 });
- expect(scrollIntoViewSpy).not.toHaveBeenCalled();
- });
-
- it("expands a folded reply-resolution thread before locating the delivered steer answer", async () => {
- const taskId = "5a2e8d1c-7f9b-4e2a-9c1d-123456789abc";
- const root: TimelineEntry = {
- ...mockTimeline[0]!,
- id: "folded-steer-root",
- parent_id: null,
- created_at: "2026-01-16T00:00:00Z",
- agent_deliveries: [
- { agent_id: "agent-1", agent_name: "Claude Agent", task_id: taskId, status: "delivered" },
- ],
- };
- const finalReply: TimelineEntry = {
- ...mockTimeline[1]!,
- id: "folded-steer-final-reply",
- parent_id: root.id,
- source_task_id: taskId,
- content: "Final answer hidden behind the resolution fold",
- created_at: "2026-01-16T00:01:00Z",
- };
- const resolution: TimelineEntry = {
- ...mockTimeline[0]!,
- id: "folded-steer-resolution",
- parent_id: root.id,
- content: "Resolved after the answer",
- created_at: "2026-01-16T00:02:00Z",
- resolved_at: "2026-01-16T00:03:00Z",
- };
- mockApiObj.listTimeline.mockResolvedValue([root, finalReply, resolution]);
-
- renderIssueDetail();
- const locate = await screen.findByRole("button", { name: /View final reply/ });
- expect(document.getElementById(`comment-${finalReply.id}`)).toBeNull();
-
- fireEvent.click(locate);
-
- await waitFor(() => {
- expect(hasHighlightedCommentBackground(document.getElementById(`comment-${finalReply.id}`))).toBe(true);
- });
- expect(screen.getByRole("button", { name: "Collapse" })).toBeInTheDocument();
- expect(scrollToIndexSpy).toHaveBeenCalledWith({ index: 0, align: "start", offset: -16 });
- });
-
- it("locates a delivered steer answer in flat deep-link mode", async () => {
- const taskId = "6a2e8d1c-7f9b-4e2a-9c1d-123456789abc";
- const root: TimelineEntry = {
- ...mockTimeline[0]!,
- id: "flat-steer-root",
- parent_id: null,
- created_at: "2026-01-16T00:00:00Z",
- agent_deliveries: [
- { agent_id: "agent-1", agent_name: "Claude Agent", task_id: taskId, status: "delivered" },
- ],
- };
- const finalReply: TimelineEntry = {
- ...mockTimeline[1]!,
- id: "flat-steer-final-reply",
- parent_id: root.id,
- source_task_id: taskId,
- content: "Final answer in the flat timeline",
- created_at: "2026-01-16T00:01:00Z",
- };
- mockApiObj.listTimeline.mockResolvedValue([root, finalReply]);
-
- renderIssueDetailWithHighlight(root.id);
- const locate = await screen.findByRole("button", { name: /View final reply/ });
- await waitFor(() => {
- expect(hasHighlightedCommentBackground(document.getElementById(`comment-${root.id}`))).toBe(true);
- });
-
- scrollToIndexSpy.mockClear();
- fireEvent.click(locate);
-
- await waitFor(() => {
- expect(hasHighlightedCommentBackground(document.getElementById(`comment-${finalReply.id}`))).toBe(true);
- });
- expect(scrollToIndexSpy).not.toHaveBeenCalled();
- expect(scrollIntoViewSpy).not.toHaveBeenCalled();
- });
-
it("places one coalesced queued block after the batch's latest reply", async () => {
const root = mockTimeline[0]!;
const first = { ...mockTimeline[1]!, id: "queued-first", parent_id: root.id,
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 7b3393c4a8..1802d033cc 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -1736,11 +1736,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
return () => cancelAnimationFrame(rafId);
}, [pendingPostedCommentId, items, replyToRoot, isFlatTimeline, scrollContainerEl]);
const jumpFlashTimerRef = useRef<number | null>(null);
- const locateCommentRafRef = useRef<number | null>(null);
useEffect(
() => () => {
if (jumpFlashTimerRef.current !== null) window.clearTimeout(jumpFlashTimerRef.current);
- if (locateCommentRafRef.current !== null) cancelAnimationFrame(locateCommentRafRef.current);
},
[],
);
@@ -1773,56 +1771,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
[isFlatTimeline, items, scrollContainerEl],
);
- const locateTimelineComment = useCallback(
- (commentId: string) => {
- const rootId = replyToRoot.get(commentId) ?? commentId;
- const index = items.findIndex((item) => item.id === rootId);
- if (index < 0) return;
-
- // The receipt is visible, so its thread is mounted and expanded. The
- // answer can still be behind a reply-resolution fold; open that fold
- // before waiting for React to materialize the target row.
- if (!document.getElementById(`comment-${commentId}`) && rootId !== commentId) {
- toggleResolvedExpand(rootId, true);
- }
- if (!isFlatTimeline) {
- virtuosoRef.current?.scrollToIndex({ index, align: "start", offset: -16 });
- }
-
- setHighlightedId(commentId);
- if (jumpFlashTimerRef.current !== null) window.clearTimeout(jumpFlashTimerRef.current);
- jumpFlashTimerRef.current = window.setTimeout(() => setHighlightedId(null), 2500);
- if (locateCommentRafRef.current !== null) cancelAnimationFrame(locateCommentRafRef.current);
-
- let attempts = 0;
- let last = -1;
- const center = () => {
- const element = document.getElementById(`comment-${commentId}`);
- const container = scrollContainerEl;
- if (!element || !container) {
- if (++attempts < 30) locateCommentRafRef.current = requestAnimationFrame(center);
- return;
- }
- const containerRect = container.getBoundingClientRect();
- const elementRect = element.getBoundingClientRect();
- const target = Math.max(
- 0,
- container.scrollTop + (elementRect.top - containerRect.top)
- - (container.clientHeight - elementRect.height) / 2,
- );
- container.scrollTop = target;
- if (Math.abs(target - last) > 1 && ++attempts < 30) {
- last = target;
- locateCommentRafRef.current = requestAnimationFrame(center);
- } else {
- locateCommentRafRef.current = null;
- }
- };
- locateCommentRafRef.current = requestAnimationFrame(center);
- },
- [isFlatTimeline, items, replyToRoot, scrollContainerEl, toggleResolvedExpand],
- );
-
const {
reactions: issueReactions,
toggleReaction: handleToggleIssueReaction,
@@ -2716,7 +2664,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
onCopyLink: actions.copyCommentLink,
onCollapseResolved: reply.resolved_at ? () => toggleResolvedExpand(reply.id, false) : undefined,
expandedResolvedIds: expandedResolved, onResolvedExpandChange: toggleResolvedExpand,
- onLocateComment: locateTimelineComment,
highlightedCommentId: highlightedId,
runs: commentRuns.get(reply.id) ?? EMPTY_COMMENT_RUNS, enteringRunIds,
} : undefined} />}
@@ -2756,7 +2703,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
onCollapseResolved={isResolved ? () => toggleResolvedExpand(item.id, false) : undefined}
expandedResolvedIds={expandedResolved}
onResolvedExpandChange={toggleResolvedExpand}
- onLocateComment={locateTimelineComment}
highlightedCommentId={highlightedId}
/>
</div>
diff --git a/packages/views/issues/hooks/use-issue-timeline.test.tsx b/packages/views/issues/hooks/use-issue-timeline.test.tsx
index 254f396fa5..73be2991e3 100644
--- a/packages/views/issues/hooks/use-issue-timeline.test.tsx
+++ b/packages/views/issues/hooks/use-issue-timeline.test.tsx
@@ -380,60 +380,6 @@ describe("useIssueTimeline", () => {
]);
});
- it("preserves delivery task ids from realtime receipt updates", () => {
- queryState.data = [
- {
- type: "comment",
- id: "c1",
- actor_type: "member",
- actor_id: "user-1",
- content: "steer this run",
- parent_id: null,
- created_at: "2026-05-06T01:00:00Z",
- updated_at: "2026-05-06T01:00:00Z",
- revision: 1,
- reactions: [],
- attachments: [],
- },
- ];
- renderHook(() => useIssueTimeline("issue-1", "user-1"));
-
- act(() => {
- wsHandlers.get("comment:updated")!({
- comment: {
- id: "c1",
- issue_id: "issue-1",
- author_type: "member",
- author_id: "user-1",
- content: "steer this run",
- parent_id: null,
- created_at: "2026-05-06T01:00:00Z",
- updated_at: "2026-05-06T02:00:00Z",
- revision: 2,
- type: "comment",
- reactions: [],
- attachments: [],
- agent_deliveries: [
- {
- agent_id: "agent-1",
- agent_name: "Walt",
- task_id: "task-1",
- status: "delivered",
- },
- ],
- },
- });
- });
-
- expect(cacheUpdates.last).toMatchObject([
- {
- agent_deliveries: [
- { agent_id: "agent-1", task_id: "task-1", status: "delivered" },
- ],
- },
- ]);
- });
-
it("refetches instead of applying an unversioned event over versioned cache state", () => {
queryState.data = [{
type: "comment",
diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.ts
index c191422b4b..cee70faf44 100644
--- a/packages/views/issues/hooks/use-issue-timeline.ts
+++ b/packages/views/issues/hooks/use-issue-timeline.ts
@@ -65,7 +65,6 @@ function commentToTimelineEntry(c: Comment): TimelineEntry {
resolved_by_type: c.resolved_by_type,
resolved_by_id: c.resolved_by_id,
source_task_id: c.source_task_id,
- agent_deliveries: c.agent_deliveries,
deleted_at: c.deleted_at,
};
}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 161615fe9b..14cc50d662 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -555,16 +555,6 @@
"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_view_reply": "View final reply",
- "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 18a3e9c46f..49b73b2065 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -555,16 +555,6 @@
"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_view_reply": "Voir la réponse finale",
- "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 2e7e7823eb..76ceebd5ab 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -544,15 +544,6 @@
"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_view_reply": "最終回答を表示",
- "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 fac1e8ddf6..b1ea52789c 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -544,15 +544,6 @@
"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_view_reply": "최종 답변 보기",
- "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 eb5a66a42e..aeeeea963e 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -544,15 +544,6 @@
"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_view_reply": "查看最终回复",
- "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 bcc95f45c9..358eb2b8d1 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -154,7 +154,6 @@ var concurrentIndexCleanups = map[string]string{
"526_wakeup_terminal_runs": "agent_task_wakeup_terminal_idx",
"527_wakeup_receipt_expiry": "issue_wakeup_receipt_expiry_idx",
"529_wakeup_pending_event": "issue_wakeup_pending_event_idx",
- "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 ae1c75ebf3..e1e9992d6e 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1560,8 +1560,6 @@ 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 9e7063124a..3e770fcef1 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -211,7 +211,6 @@ func daemonCommonCapabilities() []string {
protocol.DaemonCapabilityRPCV1,
protocol.DaemonCapabilityPlatformSkillV1,
protocol.DaemonCapabilityCheckoutKeepsWorkV1,
- protocol.DaemonCapabilityTaskSteerV1,
}
}
@@ -439,34 +438,6 @@ 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 e807b3c554..d6058fcdfc 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -55,7 +55,6 @@ 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 1005e14eaa..30601888c3 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -32,7 +32,6 @@ 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"
@@ -581,11 +580,6 @@ 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
@@ -735,7 +729,6 @@ 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,
@@ -4565,14 +4558,6 @@ 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,
@@ -4635,16 +4620,6 @@ 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 {
@@ -4714,38 +4689,6 @@ 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.
@@ -8792,8 +8735,7 @@ 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
- execCtx := context.WithValue(ctx, taskSteerRuntimeIDContextKey{}, task.RuntimeID)
- result, tools, err := d.executeAndDrain(execCtx, backend, prompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
+ result, tools, err := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
if err != nil {
return TaskResult{}, err
}
@@ -8849,7 +8791,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
freshPrompt := BuildPrompt(task, provider, promptOptions...)
- retryResult, retryTools, retryErr := d.executeAndDrain(execCtx, backend, freshPrompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
+ retryResult, retryTools, retryErr := d.executeAndDrain(ctx, 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 == "" {
@@ -9304,25 +9246,6 @@ 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.
-
-Treat this comment as additional guidance for the same active task, not as a replacement:
-- Preserve and complete the original objective.
-- Merge this comment into the work and the turn's single final response.
-- Do not send a separate acknowledgement.
-- Replace or cancel the original objective only if the human explicitly asks for replacement or cancellation.
-
-Human comment:
-%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
@@ -9350,71 +9273,6 @@ 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 8256f73727..b66903240e 100644
--- a/server/internal/daemon/execenv/runtime_config_kind_test.go
+++ b/server/internal/daemon/execenv/runtime_config_kind_test.go
@@ -74,10 +74,6 @@ 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 c87701a6a9..a2e4a0aefe 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -768,7 +768,6 @@ 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 8a600d6f19..ea4c920a30 100644
--- a/server/internal/daemon/pending_work_hint_test.go
+++ b/server/internal/daemon/pending_work_hint_test.go
@@ -91,61 +91,6 @@ 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 TestFormatCommentSteerInstructionPreservesActiveTaskContract(t *testing.T) {
- got := formatCommentSteerInstruction("Alice\nAdmin", "keep the migration reversible")
- want := `[STEER] Human "Alice Admin" left a new comment while you were working.
-
-Treat this comment as additional guidance for the same active task, not as a replacement:
-- Preserve and complete the original objective.
-- Merge this comment into the work and the turn's single final response.
-- Do not send a separate acknowledgement.
-- Replace or cancel the original objective only if the human explicitly asks for replacement or cancellation.
-
-Human comment:
-keep 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 cab1c5e380..935cd90544 100644
--- a/server/internal/dispatch/reason.go
+++ b/server/internal/dispatch/reason.go
@@ -15,11 +15,10 @@ package dispatch
type ReasonCode string
const (
- // ReasonQueued / ReasonCoalesced / ReasonDeferred / ReasonSteering are the success-path codes.
+ // ReasonQueued / ReasonCoalesced / ReasonDeferred 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 db195837c5..06bffb593b 100644
--- a/server/internal/handler/activity.go
+++ b/server/internal/handler/activity.go
@@ -47,8 +47,7 @@ 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"`
- AgentDeliveries []CommentAgentDeliveryResponse `json:"agent_deliveries,omitempty"`
+ DeletedAt *string `json:"deleted_at,omitempty"`
}
// timelineHardCap bounds the per-issue timeline payload. Sized as a defensive
@@ -284,7 +283,6 @@ 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 {
@@ -293,25 +291,24 @@ 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),
- AgentDeliveries: deliveries[cid],
+ 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),
}
}
return out
diff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.go
index 6312bd1436..df2bac855c 100644
--- a/server/internal/handler/admission.go
+++ b/server/internal/handler/admission.go
@@ -37,8 +37,6 @@ 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"
)
@@ -55,7 +53,6 @@ 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 1449affc64..fe447b17e5 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -1880,6 +1880,7 @@ 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 2aad3d3655..4c2c8070bd 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -82,20 +82,7 @@ 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"`
- AgentDeliveries []CommentAgentDeliveryResponse `json:"agent_deliveries,omitempty"`
-}
-
-type CommentAgentDeliveryResponse struct {
- AgentID string `json:"agent_id"`
- AgentName string `json:"agent_name"`
- // TaskID links a delivered steer receipt to the final comment whose
- // source_task_id names the same run. It is nullable for receipts created
- // directly as follow-up and omitted by older servers, so mixed-version
- // clients must treat it as optional read-side metadata rather than state.
- TaskID *string `json:"task_id,omitempty"`
- Status string `json:"status"` // pending | delivered | follow_up
- DeliveredAt *string `json:"delivered_at,omitempty"`
+ TriggerOutcomes []CommentTriggerOutcome `json:"trigger_outcomes,omitempty"`
}
// CommentTriggerOutcome is the per-target result of an explicit @agent / @squad
@@ -657,13 +644,11 @@ 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
@@ -1517,7 +1502,6 @@ 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
@@ -1569,14 +1553,13 @@ func commentAgentTriggerReason(trigger commentAgentTrigger) string {
}
}
-func (h *Handler) commentAgentTriggerToResponse(trigger commentAgentTrigger, delivery string) CommentTriggerAgentResponse {
+func (h *Handler) commentAgentTriggerToResponse(trigger commentAgentTrigger) 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,
}
}
@@ -1661,21 +1644,8 @@ 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 {
- 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))
+ resp.Agents = append(resp.Agents, h.commentAgentTriggerToResponse(trigger))
}
writeJSON(w, http.StatusOK, resp)
}
@@ -1984,63 +1954,10 @@ 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, TaskID: uuidToPtr(row.TaskID), 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.
@@ -2087,7 +2004,7 @@ func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, co
})
triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)
h.noteBlockedRuntimeTargets(ctx, issue, targets)
- enqueued := h.enqueueCommentAgentTriggersWithSteer(ctx, issue, comment.ID, triggers, actorType == "member")
+ enqueued := h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
return commentTriggerOutcomes(targets, enqueued)
}
@@ -2155,18 +2072,10 @@ 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. steering / queued / coalesced / deferred are success-shaped
-// (the run was handled, no duplicate task); only a real enqueue failure is blocked.
+// target's outcome. 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 {
@@ -2175,59 +2084,7 @@ func (h *Handler) enqueueCommentAgentTriggersWithSteer(ctx context.Context, 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
@@ -3552,7 +3409,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.CancelTasksByEditedComment(r.Context(), existing.ID)
+ cancelled, err = h.TaskService.CancelTasksByTriggerComment(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")
@@ -3595,7 +3452,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
issueRevision = updated.IssueRevision
}
if err == nil && oldContent != req.Content && strictContentEdit {
- cancelled, err = qtx.CancelAgentTasksByEditedComment(r.Context(), existing.ID)
+ cancelled, err = qtx.CancelAgentTasksByTriggerComment(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
deleted file mode 100644
index 4b6dbda9d2..0000000000
--- a/server/internal/handler/comment_steer_test.go
+++ /dev/null
@@ -1,346 +0,0 @@
-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)
- }
-}
-
-func TestCommentSteerDeliveryReadModelIncludesNullableTaskID(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
- f := newCommentSteerFixture(t, "read-model-task")
- deliveredID := f.reply(t, "injected constraint", "4 minutes")
- followUpID := f.reply(t, "future work", "2 minutes")
- registerCommentSteer(t, f, deliveredID)
- if _, err := testHandler.Queries.ClaimNextCommentSteer(context.Background(), util.MustParseUUID(f.taskID)); err != nil {
- t.Fatalf("claim 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 steer: %v", err)
- }
- if err := testHandler.Queries.RecordCommentFollowUpDelivery(context.Background(), db.RecordCommentFollowUpDeliveryParams{
- CommentID: util.MustParseUUID(followUpID), AgentID: util.MustParseUUID(f.agentID),
- FailureReason: pgtype.Text{String: "turn_ended", Valid: true},
- }); err != nil {
- t.Fatalf("record follow-up receipt: %v", err)
- }
-
- entries, status := fetchTimeline(t, f.issueID)
- if status != http.StatusOK {
- t.Fatalf("timeline status = %d, want 200", status)
- }
- byID := make(map[string]TimelineEntry, len(entries))
- for _, entry := range entries {
- byID[entry.ID] = entry
- }
- delivered := byID[deliveredID].AgentDeliveries
- if len(delivered) != 1 || delivered[0].Status != "delivered" || delivered[0].TaskID == nil || *delivered[0].TaskID != f.taskID {
- t.Fatalf("delivered receipt = %+v, want task_id %s", delivered, f.taskID)
- }
- followUp := byID[followUpID].AgentDeliveries
- if len(followUp) != 1 || followUp[0].Status != "follow_up" || followUp[0].TaskID != nil {
- t.Fatalf("follow-up receipt = %+v, want nullable task_id", followUp)
- }
-
- var recordedAsDelivered bool
- dbfx.QueryRow(t, `SELECT $2::uuid = ANY(delivered_comment_ids) FROM agent_task_queue WHERE id=$1`, f.taskID, deliveredID).
- Scan(&recordedAsDelivered)
- if recordedAsDelivered {
- t.Fatal("read-side task linkage wrote the steer comment into delivered_comment_ids")
- }
-}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 52dbd1f927..8e657e1e10 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1374,12 +1374,9 @@ 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,
- protocol.DaemonCapabilityTaskSteerV1,
- },
+ RuntimeID: runtimeID,
+ Status: "ok",
+ ServerCapabilities: []string{protocol.DaemonCapabilityRPCV1},
}
probeUpdateCtx, cancelProbeUpdate := context.WithTimeout(ctx, heartbeatHasPendingTimeout)
@@ -4091,106 +4088,6 @@ 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 {
@@ -4399,7 +4296,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.publishCommentDeliveryUpdates(r, h.reconcileCommentsOnCompletion(r.Context(), task))
+ 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.
@@ -4461,23 +4358,6 @@ 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).
//
@@ -4518,14 +4398,10 @@ func (h *Handler) finalizeUndeliveredCommentSteers(ctx context.Context, taskID p
// 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) []pgtype.UUID {
+func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.AgentTaskQueue) {
if task == nil || !task.IssueID.Valid || !task.AgentID.Valid || !task.CreatedAt.Valid {
- return nil
+ return
}
- // 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)
@@ -4539,10 +4415,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 deliveryUpdates
+ return
}
if len(comments) == 0 {
- return deliveryUpdates
+ return
}
// The delivered set is the claim-time receipt, not the enqueue-time plan.
// Legacy tasks backfill only the primary trigger, deliberately replaying
@@ -4553,21 +4429,11 @@ 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 deliveryUpdates
+ return
}
agentID := uuidToString(task.AgentID)
scheduled := 0
@@ -4679,7 +4545,6 @@ 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
@@ -5127,9 +4992,6 @@ 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
@@ -5582,10 +5444,6 @@ 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 f3f7022285..3daa648679 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -54,7 +54,6 @@ 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 cbd9917f09..748b68c1dd 100644
--- a/server/internal/handler/workspace_test.go
+++ b/server/internal/handler/workspace_test.go
@@ -536,7 +536,6 @@ 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)
@@ -553,7 +552,6 @@ VALUES ($1, $2, 'owner')
workspaceID string
mediaKey string
issueID string
- commentID string
}
fixtures := []*tenantFixture{
{workspaceID: targetWorkspaceID, mediaKey: targetMediaKey},
@@ -565,15 +563,10 @@ 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.QueryRow(t, `
+ dbfx.Exec(t, `
INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
VALUES ($1, $2, 'member', $3, 'Workspace delete tenant isolation')
-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)
+`, fixture.issueID, fixture.workspaceID, testUserID)
dbfx.Exec(t, `
INSERT INTO inbox_item (
workspace_id, recipient_type, recipient_id, type, issue_id, title
@@ -622,20 +615,6 @@ 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/migrations/comment_agent_delivery_rollback_test.go b/server/internal/migrations/comment_agent_delivery_rollback_test.go
new file mode 100644
index 0000000000..a4040aef2f
--- /dev/null
+++ b/server/internal/migrations/comment_agent_delivery_rollback_test.go
@@ -0,0 +1,71 @@
+package migrations
+
+import (
+ "context"
+ "os"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+const commentAgentDeliveryRollbackTestSchema = "comment_agent_delivery_rollback_test"
+
+func TestCommentAgentDeliveryRollbackMigrationRemovesRevertedSchema(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire Postgres connection: %v", err)
+ }
+ defer conn.Release()
+
+ cleanup := func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+commentAgentDeliveryRollbackTestSchema+" CASCADE")
+ }
+ cleanup()
+ t.Cleanup(cleanup)
+ if _, err := conn.Exec(ctx, "CREATE SCHEMA "+commentAgentDeliveryRollbackTestSchema); err != nil {
+ t.Fatalf("create isolated migration schema: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, commentAgentDeliveryRollbackTestSchema); err != nil {
+ t.Fatalf("set isolated migration search path: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE comment_agent_delivery (comment_id UUID PRIMARY KEY);
+ INSERT INTO comment_agent_delivery (comment_id) VALUES (gen_random_uuid());
+ `); err != nil {
+ t.Fatalf("create reverted feature schema: %v", err)
+ }
+
+ applyMigrationFile(t, ctx, conn.Conn(), "534_drop_comment_agent_delivery.up.sql")
+ assertCommentAgentDeliveryTableMissing(t, ctx, conn)
+
+ // Both fresh installs and a retried migration see no table. The cleanup is
+ // deliberately idempotent and its down direction must not recreate data.
+ applyMigrationFile(t, ctx, conn.Conn(), "534_drop_comment_agent_delivery.up.sql")
+ applyMigrationFile(t, ctx, conn.Conn(), "534_drop_comment_agent_delivery.down.sql")
+ assertCommentAgentDeliveryTableMissing(t, ctx, conn)
+}
+
+func assertCommentAgentDeliveryTableMissing(t *testing.T, ctx context.Context, conn *pgxpool.Conn) {
+ t.Helper()
+ var exists bool
+ if err := conn.QueryRow(ctx, `
+ SELECT to_regclass($1) IS NOT NULL
+ `, commentAgentDeliveryRollbackTestSchema+".comment_agent_delivery").Scan(&exists); err != nil {
+ t.Fatalf("inspect comment_agent_delivery table: %v", err)
+ }
+ if exists {
+ t.Fatal("comment_agent_delivery table still exists after rollback migration")
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 370f79af45..f6c06263e5 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2704,33 +2704,6 @@ 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
deleted file mode 100644
index b5a0720927..0000000000
--- a/server/migrations/507_comment_agent_delivery.down.sql
+++ /dev/null
@@ -1 +0,0 @@
-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
deleted file mode 100644
index 6d289a13a9..0000000000
--- a/server/migrations/507_comment_agent_delivery.up.sql
+++ /dev/null
@@ -1,17 +0,0 @@
--- 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
deleted file mode 100644
index 66f16f6419..0000000000
--- a/server/migrations/508_comment_agent_delivery_pending_index.down.sql
+++ /dev/null
@@ -1 +0,0 @@
-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
deleted file mode 100644
index 96ad954c21..0000000000
--- a/server/migrations/508_comment_agent_delivery_pending_index.up.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-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/migrations/534_drop_comment_agent_delivery.down.sql b/server/migrations/534_drop_comment_agent_delivery.down.sql
new file mode 100644
index 0000000000..c0ce5562d5
--- /dev/null
+++ b/server/migrations/534_drop_comment_agent_delivery.down.sql
@@ -0,0 +1,2 @@
+-- Intentionally empty. Rolling back the feature cleanup must not recreate an
+-- unused receipt table or restore delivery rows that the cleanup removed.
diff --git a/server/migrations/534_drop_comment_agent_delivery.up.sql b/server/migrations/534_drop_comment_agent_delivery.up.sql
new file mode 100644
index 0000000000..ef96987671
--- /dev/null
+++ b/server/migrations/534_drop_comment_agent_delivery.up.sql
@@ -0,0 +1,4 @@
+-- Remove the durable delivery receipts for the reverted comment-steering
+-- feature. Fresh databases that never applied migrations 507/508 are unchanged;
+-- staging databases that exercised the feature converge back to the old schema.
+DROP TABLE IF EXISTS comment_agent_delivery;
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index b0fee08034..2658bb445b 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -147,11 +147,6 @@ 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 ac9b3439fd..f66bae1211 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -103,10 +103,8 @@ 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() { _ = input.Close() }) }
+ closeStdin := func() { closeStdinOnce.Do(func() { _ = stdin.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
@@ -149,7 +147,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
// timeout.
writeDone := make(chan error, 1)
go func() {
- err := writeClaudeInput(input, prompt)
+ err := writeClaudeInput(stdin, prompt)
if err != nil {
closeStdin()
}
@@ -246,13 +244,6 @@ 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
@@ -261,6 +252,7 @@ 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{
@@ -270,7 +262,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
})
}
case "control_request":
- b.handleControlRequest(msg, input)
+ b.handleControlRequest(msg, stdin)
}
}
scanErr := scanner.Err()
@@ -369,21 +361,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
}()
- 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
+ return &Session{Messages: msgCh, Result: resCh}, nil
}
func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage, seenUsage map[string]struct{}) assistantTurn {
@@ -820,36 +798,6 @@ 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 74b3d46c6a..cb794797a5 100644
--- a/server/pkg/agent/claude_test.go
+++ b/server/pkg/agent/claude_test.go
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"encoding/json"
- "io"
"log/slog"
"os"
"path/filepath"
@@ -596,29 +595,6 @@ func TestBuildClaudeInputEncodesUserMessage(t *testing.T) {
}
}
-func TestBuildClaudeInputPreservesSteerFraming(t *testing.T) {
- t.Parallel()
-
- instruction := "[STEER] preserve ORIGINAL and merge STEERED into one final response"
- data, err := buildClaudeInput(instruction)
- if err != nil {
- t.Fatalf("buildClaudeInput: %v", err)
- }
- var payload struct {
- Message struct {
- Content []struct {
- Text string `json:"text"`
- } `json:"content"`
- } `json:"message"`
- }
- if err := json.Unmarshal(bytes.TrimSpace(data), &payload); err != nil {
- t.Fatalf("unmarshal payload: %v", err)
- }
- if len(payload.Message.Content) != 1 || payload.Message.Content[0].Text != instruction {
- t.Fatalf("Claude steer payload = %+v, want exact framed instruction", payload.Message.Content)
- }
-}
-
func TestMergeEnvFiltersClaudeCodeVars(t *testing.T) {
t.Parallel()
@@ -1345,82 +1321,3 @@ 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 7d0e511f4b..05f29185f4 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -937,24 +937,8 @@ 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
@@ -967,9 +951,6 @@ 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
@@ -1047,7 +1028,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
}
}()
- return &Session{Steer: steer, Messages: msgCh, Result: resCh}, nil
+ return &Session{Messages: msgCh, Result: resCh}, nil
}
func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecOptions, attempt int) (*Session, error) {
@@ -1925,24 +1906,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
}
}()
- 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
+ return &Session{Messages: msgCh, Result: resCh}, nil
}
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 542c06f4a8..dd5f404a11 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -42,67 +42,6 @@ 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")
- instruction := "[STEER] preserve ORIGINAL and merge STEERED into one final response"
- done := make(chan error, 1)
- go func() { done <- steerCodexTurn(context.Background(), c, instruction) }()
-
- 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"] != instruction {
- 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)
- }
-}
-
-func TestSteerCodexTurnPropagatesProviderFailure(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, "framed instruction") }()
-
- deadline := time.Now().Add(time.Second)
- for len(stdin.Lines()) == 0 && time.Now().Before(deadline) {
- time.Sleep(time.Millisecond)
- }
- if len(stdin.Lines()) != 1 {
- t.Fatalf("steer requests = %d, want 1", len(stdin.Lines()))
- }
- c.handleLine(`{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"active turn is not steerable"}}`)
- if err := <-done; err == nil || !strings.Contains(err.Error(), "active turn is not steerable") {
- t.Fatalf("steer error = %v, want provider failure", 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 73fabfbc2f..72fa310a97 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -804,109 +804,6 @@ 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 a6eea38487..718b9eadaa 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -585,19 +585,6 @@ 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
deleted file mode 100644
index 31cd0b4837..0000000000
--- a/server/pkg/db/generated/steer.sql.go
+++ /dev/null
@@ -1,444 +0,0 @@
-// 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.task_id, 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"`
- TaskID pgtype.UUID `json:"task_id"`
- 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.TaskID,
- &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 1249ec4923..93b9492750 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -182,20 +182,9 @@ func (q *Queries) DeleteWorkspaceChatMessages(ctx context.Context, workspaceID p
}
const deleteWorkspaceComments = `-- name: DeleteWorkspaceComments :exec
-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)
+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.
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 a4f684420d..cf33083e6c 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -687,28 +687,6 @@ 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
deleted file mode 100644
index b258c13377..0000000000
--- a/server/pkg/db/queries/steer.sql
+++ /dev/null
@@ -1,140 +0,0 @@
--- 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.task_id, 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 9e8f5c3f73..c302c45535 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -530,18 +530,7 @@ deleted_channel_installations AS (
DELETE FROM lark_installation WHERE lark_installation.workspace_id = $1;
-- name: DeleteWorkspaceComments :exec
--- 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);
+DELETE FROM comment WHERE comment.workspace_id = $1;
-- name: DeleteWorkspaceIssueRoots :exec
WITH deleted_wakeup_receipts AS (
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index e19586e4ab..664400c8c2 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -61,10 +61,6 @@ 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:
@@ -155,7 +151,6 @@ 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