Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: add messages to active Claude Code and Codex runs (MUL-7565) (#8682)
Multica Eve93ae552ba951
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 5c77648956..74c6553891 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2692,6 +2692,24 @@ export class ApiClient {});}+ async createTaskSupplement(issueId: string, taskId: string, content: string, clientRequestId: string): Promise<Comment> {+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/tasks/${taskId}/supplements`, {+ method: "POST",+ body: JSON.stringify({ content, client_request_id: clientRequestId }),+ });+ const comment = parseWithFallback<Comment>(raw, CommentSchema, EMPTY_COMMENT, {+ endpoint: "POST /api/issues/:id/tasks/:taskId/supplements",+ });+ if (!comment.id) throw new Error("Invalid additional-message response");+ return comment;+ }++ async retryTaskSupplement(issueId: string, taskId: string, commentId: string): Promise<void> {+ await this.fetch(`/api/issues/${issueId}/tasks/${taskId}/supplements/${commentId}/retry`, {+ method: "POST",+ });+ }+async getIssueUsage(issueId: string): Promise<IssueUsageSummary> {return this.fetch(`/api/issues/${issueId}/usage`);}diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 23f4122407..5de48b3d65 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -541,6 +541,25 @@ describe("IssueTriggerPreviewSchema", () => {});describe("TimelineEntriesSchema", () => {+ it("preserves run-bound supplement delivery receipts", () => {+ const parsed = TimelineEntriesSchema.parse([{+ type: "comment",+ id: "supplement-1",+ actor_type: "member",+ actor_id: "user-1",+ created_at: "2026-01-01T00:00:00Z",+ content: "also cover rollback",+ supplement_task_id: "task-1",+ supplement_status: "delivered",+ supplement_delivered_at: "2026-01-01T00:00:01Z",+ }]);+ expect(parsed[0]).toMatchObject({+ supplement_task_id: "task-1",+ supplement_status: "delivered",+ supplement_delivered_at: "2026-01-01T00:00:01Z",+ });+ });+it("preserves source_task_id for agent failure comments", () => {const parsed = TimelineEntriesSchema.parse([{@@ -613,6 +632,20 @@ describe("TimelineEntriesSchema", () => {});describe("AgentTaskListSchema", () => {+ it("preserves negotiated supplement capability, ordered coverage and permission", () => {+ const parsed = AgentTaskListSchema.parse([{+ id: "run",+ supplement_capability: "task-supplement-v1",+ supplement_comment_ids: ["comment-1", "comment-2"],+ can_supplement: true,+ }]);+ expect(parsed[0]).toMatchObject({+ supplement_capability: "task-supplement-v1",+ supplement_comment_ids: ["comment-1", "comment-2"],+ can_supplement: true,+ });+ });+it.each([true, false, undefined, null, "true", 1])("safely parses comment cancellation metadata: %s", (value) => {const parsed = AgentTaskListSchema.parse([{ id: "run", cancelled_by_comment_change: value }]);expect(parsed).toHaveLength(1);diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 0298966f8a..003ad9a264 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -918,6 +918,10 @@ const TimelineEntrySchema = z.object({reactions: z.array(ReactionSchema).optional(),attachments: z.array(AttachmentSchema).optional(),source_task_id: z.string().nullable().optional(),+ supplement_task_id: z.string().optional().catch(undefined),+ supplement_status: z.enum(["pending", "delivering", "delivered", "failed"]).optional().catch(undefined),+ supplement_failure_reason: z.string().optional().catch(undefined),+ supplement_delivered_at: z.string().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),@@ -1063,6 +1067,10 @@ export const CommentSchema = z.object({updated_at: z.string(),revision: z.number().int().positive().optional(),source_task_id: z.string().nullable().optional(),+ supplement_task_id: z.string().optional().catch(undefined),+ supplement_status: z.enum(["pending", "delivering", "delivered", "failed"]).optional().catch(undefined),+ supplement_failure_reason: z.string().optional().catch(undefined),+ supplement_delivered_at: z.string().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),@@ -1835,6 +1843,9 @@ export const AgentTaskSchema = z.object({// entire execution log, so degrade that field to "absent" independently.coalesced_comment_ids: OptionalStringArraySchema,delivered_comment_ids: OptionalStringArraySchema,+ supplement_capability: z.string().optional().catch(undefined),+ supplement_comment_ids: OptionalStringArraySchema,+ can_supplement: z.boolean().optional().catch(undefined),trigger_summary: z.string().optional(),kind: z.string().optional(),work_dir: z.string().optional().catch(undefined),diff --git a/packages/core/drafts/register-all-drafts.ts b/packages/core/drafts/register-all-drafts.tsindex 41a0f4be33..5996800153 100644--- a/packages/core/drafts/register-all-drafts.ts+++ b/packages/core/drafts/register-all-drafts.ts@@ -17,6 +17,7 @@import "../issues/stores/draft-store";import "../issues/stores/quick-create-store";import "../issues/stores/comment-draft-store";+import "../issues/stores/task-supplement-draft-store";import "../projects/draft-store";import "../feedback/draft-store";import "../agents/manual-draft-store";diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex 7cb90e04f9..a2cdaf0ac4 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -37,7 +37,7 @@ import {} from "./delete-cache";import { useWorkspaceId } from "../hooks";import { useRecentContextStore } from "../chat/recent-context-store";-import { useRecentIssuesStore } from "./stores";+import { useRecentIssuesStore, useTaskSupplementDraftStore } from "./stores";import type { InboxItem, Issue, IssueReaction } from "../types";import type {CreateCommentSubIssueManualRequest,@@ -1208,6 +1208,60 @@ export function useCancelIssueRun(issueId: string) {});}+export function useCreateTaskSupplement(issueId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: ({ taskId, content, clientRequestId }: {+ taskId: string;+ content: string;+ clientRequestId: string;+ }) => api.createTaskSupplement(issueId, taskId, content, clientRequestId),+ onSuccess: (comment, { taskId, clientRequestId }) => {+ // Re-anchoring the run can unmount its composer before this response.+ // Clear the submitted draft here, without discarding any newer edits.+ const drafts = useTaskSupplementDraftStore.getState();+ if (drafts.drafts[taskId]?.clientRequestId === clientRequestId) {+ drafts.clear(taskId);+ }+ const entry: TimelineEntry = {+ type: "comment",+ id: comment.id,+ actor_type: comment.author_type,+ actor_id: comment.author_id,+ content: comment.content,+ parent_id: comment.parent_id,+ comment_type: comment.type,+ reactions: comment.reactions ?? [],+ attachments: comment.attachments ?? [],+ created_at: comment.created_at,+ updated_at: comment.updated_at,+ supplement_task_id: comment.supplement_task_id,+ supplement_status: comment.supplement_status,+ supplement_failure_reason: comment.supplement_failure_reason,+ supplement_delivered_at: comment.supplement_delivered_at,+ };+ client.setQueryData<TimelineCache>(issueKeys.timeline(issueId), (old) => {+ if (!old) return [entry];+ if (old.some((item) => item.id === entry.id)) return old;+ return sortTimelineEntriesAsc([...old, entry]);+ });+ client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) });+ },+ });+}++export function useRetryTaskSupplement(issueId: string) {+ const client = useQueryClient();+ return useMutation({+ mutationFn: ({ taskId, commentId }: { taskId: string; commentId: string }) =>+ api.retryTaskSupplement(issueId, taskId, commentId),+ onSettled: () => {+ client.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });+ client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) });+ },+ });+}+export function useRetryIssueRun(issueId: string) {const client = useQueryClient();return useMutation({diff --git a/packages/core/issues/stores/index.ts b/packages/core/issues/stores/index.tsindex 20fa75e673..d721815240 100644--- a/packages/core/issues/stores/index.ts+++ b/packages/core/issues/stores/index.ts@@ -28,6 +28,7 @@ export {} from "./resolved-expand-store";export { useCommentComposerStore } from "./comment-composer-store";export { useCommentDraftStore, type CommentDraftKey } from "./comment-draft-store";+export { useTaskSupplementDraftStore, type TaskSupplementDraft } from "./task-supplement-draft-store";export {myIssuesViewStore,type MyIssuesViewState,diff --git a/packages/core/issues/stores/task-supplement-draft-store.test.ts b/packages/core/issues/stores/task-supplement-draft-store.test.tsnew file mode 100644index 0000000000..5fc88848f2--- /dev/null+++ b/packages/core/issues/stores/task-supplement-draft-store.test.ts@@ -0,0 +1,43 @@+// @vitest-environment jsdom+import { beforeEach, describe, expect, it } from "vitest";+import { useTaskSupplementDraftStore } from "./task-supplement-draft-store";++describe("task supplement draft store", () => {+ beforeEach(() => useTaskSupplementDraftStore.setState({ drafts: {} }));++ it.each(["", " \n "])("clears an empty terminal draft (%j)", (content) => {+ const store = useTaskSupplementDraftStore.getState();+ store.setContent("task-1", "issue-1", content);+ store.markEnded("task-1");+ expect(useTaskSupplementDraftStore.getState().drafts["task-1"]).toBeUndefined();+ });++ it("clears a previously ended draft after its text is erased", () => {+ const store = useTaskSupplementDraftStore.getState();+ store.setContent("task-1", "issue-1", "retained");+ store.markEnded("task-1");+ store.setContent("task-1", "issue-1", "");+ store.markEnded("task-1");+ expect(useTaskSupplementDraftStore.getState().drafts["task-1"]).toBeUndefined();+ });++ it("does not let another task consume or clear the draft", () => {+ const store = useTaskSupplementDraftStore.getState();+ store.setContent("task-1", "issue-1", "first");+ store.setContent("task-2", "issue-1", "second");+ store.clear("task-2");+ expect(useTaskSupplementDraftStore.getState().drafts["task-1"]?.content).toBe("first");+ });++ it("changes request identity only when the user changes text", () => {+ const store = useTaskSupplementDraftStore.getState();+ store.setContent("task-1", "issue-1", "same text");+ store.setRequestId("task-1", "request-1");+ store.markEnded("task-1");+ expect(useTaskSupplementDraftStore.getState().drafts["task-1"]).toMatchObject({+ content: "same text", clientRequestId: "request-1", ended: true,+ });+ store.setContent("task-1", "issue-1", "edited text");+ expect(useTaskSupplementDraftStore.getState().drafts["task-1"]?.clientRequestId).toBeUndefined();+ });+});diff --git a/packages/core/issues/stores/task-supplement-draft-store.ts b/packages/core/issues/stores/task-supplement-draft-store.tsnew file mode 100644index 0000000000..85f893fd24--- /dev/null+++ b/packages/core/issues/stores/task-supplement-draft-store.ts@@ -0,0 +1,106 @@+import { create } from "zustand";+import { createJSONStorage, persist } from "zustand/middleware";+import { registerDraftCleanup } from "../../drafts/cleanup-registry";+import { defaultStorage } from "../../platform/storage";+import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";++export interface TaskSupplementDraft {+ issueId: string;+ content: string;+ open: boolean;+ ended: boolean;+ clientRequestId?: string;+ updatedAt: number;+}++interface TaskSupplementDraftStore {+ drafts: Record<string, TaskSupplementDraft>;+ open: (taskId: string, issueId: string) => void;+ setContent: (taskId: string, issueId: string, content: string) => void;+ setRequestId: (taskId: string, clientRequestId: string) => void;+ markEnded: (taskId: string) => void;+ clear: (taskId: string) => void;+}++const TTL_MS = 30 * 24 * 60 * 60 * 1000;++function prune(drafts: Record<string, TaskSupplementDraft>): Record<string, TaskSupplementDraft> {+ const cutoff = Date.now() - TTL_MS;+ return Object.fromEntries(Object.entries(drafts).filter(([, draft]) =>+ draft.updatedAt >= cutoff && (!!draft.content.trim() || draft.open),+ ));+}++export const useTaskSupplementDraftStore = create<TaskSupplementDraftStore>()(+ persist(+ (set) => ({+ drafts: {},+ open: (taskId, issueId) => set((state) => ({+ drafts: {+ ...state.drafts,+ [taskId]: {+ issueId,+ content: state.drafts[taskId]?.content ?? "",+ clientRequestId: state.drafts[taskId]?.clientRequestId,+ ended: state.drafts[taskId]?.ended ?? false,+ open: true,+ updatedAt: Date.now(),+ },+ },+ })),+ setContent: (taskId, issueId, content) => set((state) => ({+ drafts: {+ ...state.drafts,+ [taskId]: {+ issueId,+ content,+ open: true,+ ended: state.drafts[taskId]?.ended ?? false,+ // Editing creates a new logical request; retries of unchanged text+ // keep the prior id through setRequestId instead.+ clientRequestId: undefined,+ updatedAt: Date.now(),+ },+ },+ })),+ setRequestId: (taskId, clientRequestId) => set((state) => {+ const draft = state.drafts[taskId];+ if (!draft) return state;+ return { drafts: { ...state.drafts, [taskId]: { ...draft, clientRequestId, updatedAt: Date.now() } } };+ }),+ markEnded: (taskId) => set((state) => {+ const draft = state.drafts[taskId];+ if (!draft) return state;+ if (!draft.content.trim()) {+ const drafts = { ...state.drafts };+ delete drafts[taskId];+ return { drafts };+ }+ if (draft.ended) return state;+ return { drafts: { ...state.drafts, [taskId]: { ...draft, open: true, ended: true, updatedAt: Date.now() } } };+ }),+ clear: (taskId) => set((state) => {+ if (!(taskId in state.drafts)) return state;+ const drafts = { ...state.drafts };+ delete drafts[taskId];+ return { drafts };+ }),+ }),+ {+ name: "multica_task_supplement_drafts",+ storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),+ merge: (persisted, current) => ({+ ...current,+ drafts: prune((persisted as { drafts?: Record<string, TaskSupplementDraft> } | undefined)?.drafts ?? {}),+ }),+ },+ ),+);++registerForWorkspaceRehydration(() => useTaskSupplementDraftStore.persist.rehydrate());++registerDraftCleanup({+ storageKey: "multica_task_supplement_drafts",+ workspaceScoped: true,+ resetInMemory: () => useTaskSupplementDraftStore.setState({ drafts: {} }),+});diff --git a/packages/core/types/activity.ts b/packages/core/types/activity.tsindex 7a469e4b01..b17bc0f857 100644--- a/packages/core/types/activity.ts+++ b/packages/core/types/activity.ts@@ -33,6 +33,11 @@ export interface TimelineEntry {resolved_by_type?: CommentAuthorType | null;resolved_by_id?: string | null;source_task_id?: string | null;+ /** Delivery receipt for a member message explicitly bound to one live run. */+ supplement_task_id?: string;+ supplement_status?: "pending" | "delivering" | "delivered" | "failed";+ supplement_failure_reason?: string;+ supplement_delivered_at?: string;/*** 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 throughdiff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 2d08f2be6f..78c5a3f30b 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -366,6 +366,12 @@ export interface AgentTask {* trigger/coalesced union; an explicitly empty array is still authoritative.*/delivered_comment_ids?: string[];+ /** Exact run-scoped live-input capability negotiated at this task's start. */+ supplement_capability?: string;+ /** Ordinary historical comments explicitly bound to this run, in send order. */+ supplement_comment_ids?: string[];+ /** Server-side invocation verdict for the current member and this agent. */+ can_supplement?: boolean;/*** Canonical short description of what triggered this task — snapshot* taken at creation time. For comment-triggered tasks it's thediff --git a/packages/core/types/comment.ts b/packages/core/types/comment.tsindex b0bcf5a8f6..aaca94eeb8 100644--- a/packages/core/types/comment.ts+++ b/packages/core/types/comment.ts@@ -47,6 +47,10 @@ 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[];+ supplement_task_id?: string;+ supplement_status?: "pending" | "delivering" | "delivered" | "failed";+ supplement_failure_reason?: string;+ supplement_delivered_at?: string;}// The domain result of one explicitly-mentioned trigger target. Success-shapeddiff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex 04e6450088..0559db6c59 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -1,6 +1,7 @@"use client";import { Fragment, memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";+import { useQuery } from "@tanstack/react-query";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";@@ -40,6 +41,8 @@ import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";import type { TimelineEntry, Attachment } from "@multica/core/types";import { contentReferencesAttachment } from "@multica/core/types";import { isDeletedComment } from "@multica/core/issues/comment-deletion";+import { useRetryTaskSupplement } from "@multica/core/issues/mutations";+import { issueTasksOptions } from "@multica/core/issues/queries";import { useConfigStore } from "@multica/core/config";import { selectStandaloneAttachments } from "@multica/core/attachments/image-sequence";import { useCommentCollapseStore, useCommentDraftStore } from "@multica/core/issues/stores";@@ -47,8 +50,8 @@ import { useT } from "../../i18n";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, showCommentRunInHeader, type CommentRun } from "./comment-runs";+import { InlineCommentRun, PlacedInlineCommentRun, useInlineCommentRunState, type InlineCommentRunState } from "./inline-comment-run";+import { EMPTY_COMMENT_RUNS, type CommentRun } from "./comment-runs";import { useCommentAnnotations } from "./use-comment-annotations";import { useRunCommentMotion } from "./use-run-comment-motion";@@ -605,6 +608,55 @@ function CommentRevisionConflict({// Single comment row (used for both parent and replies within the same Card)// ---------------------------------------------------------------------------+export function SupplementReceipt({ issueId, entry }: {+ issueId: string;+ entry: TimelineEntry;+}) {+ if (!entry.supplement_task_id || !entry.supplement_status || entry.supplement_status === "delivered") return null;+ return <ActiveSupplementReceipt issueId={issueId} entry={entry} />;+}++function ActiveSupplementReceipt({ issueId, entry }: { issueId: string; entry: TimelineEntry }) {+ const { t } = useT("issues");+ const retry = useRetryTaskSupplement(issueId);+ // Run placement belongs to one card, but every bound supplement must observe+ // the task's terminal state, including earlier top-level comments.+ const { data: taskStatus } = useQuery({+ ...issueTasksOptions(issueId),+ enabled: !!issueId && !!entry.supplement_task_id && !!entry.supplement_status,+ select: (tasks) => tasks.find((task) => task.id === entry.supplement_task_id)?.status,+ });+ if (!entry.supplement_task_id || !entry.supplement_status || entry.supplement_status === "delivered") return null;+ const terminal = taskStatus === "completed" || taskStatus === "failed" || taskStatus === "cancelled";+ const endedBeforeDelivery = terminal+ && (entry.supplement_status === "pending" || entry.supplement_status === "delivering");+ if (!endedBeforeDelivery && (entry.supplement_status === "pending" || entry.supplement_status === "delivering")) {+ return <p role="status" className="mt-1.5 text-caption text-muted-foreground">+ {t(($) => $.inline_run.supplement_waiting_delivery)}+ </p>;+ }+ const reasonCode = endedBeforeDelivery ? "turn_ended" : entry.supplement_failure_reason;+ const reason = reasonCode === "turn_ended"+ ? t(($) => $.inline_run.supplement_failure_turn_ended)+ : reasonCode === "turn_not_started"+ ? t(($) => $.inline_run.supplement_failure_turn_not_started)+ : reasonCode === "provider_rejected"+ ? t(($) => $.inline_run.supplement_failure_provider_rejected)+ : reasonCode === "timeout"+ ? t(($) => $.inline_run.supplement_failure_timeout)+ : t(($) => $.inline_run.supplement_failure_unknown);+ return <div role="alert" className="mt-1.5 flex items-center gap-2 text-caption text-destructive">+ <span>{t(($) => $.inline_run.supplement_not_delivered, { reason })}</span>+ {!terminal && reasonCode !== "turn_ended" && <Button type="button" size="xs" variant="outline" disabled={retry.isPending}+ onClick={() => retry.mutate({ taskId: entry.supplement_task_id!, commentId: entry.id }, {+ onError: () => toast.error(t(($) => $.inline_run.supplement_retry_failed)),+ })}>+ {retry.isPending && <Loader2 className="size-3 animate-spin motion-reduce:animate-none" />}+ {t(($) => $.inline_run.supplement_retry)}+ </Button>}+ </div>;+}+function CommentRow({runHeader,runMetadata,@@ -649,8 +701,9 @@ function CommentRow({const edit = useEditAttachmentState(issueId, entry, onEdit);const isOwn = entry.actor_type === "member" && entry.actor_id === currentUserId;- const canEditEntry = isOwn || (canModerate && entry.actor_type === "member");- const canDeleteEntry = isOwn || canModerate;+ const canEditEntry = !entry.supplement_task_id && (isOwn || (canModerate && entry.actor_type === "member"));+ const supplementInFlight = entry.supplement_task_id && (entry.supplement_status === "pending" || entry.supplement_status === "delivering");+ const canDeleteEntry = !supplementInFlight && (isOwn || canModerate);const [confirmDelete, setConfirmDelete] = useState(false);const reactions = entry.reactions ?? [];@@ -880,6 +933,9 @@ 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" />+ <div className="pl-12 pr-4 max-md:pl-3 max-md:pr-3">+ <SupplementReceipt issueId={issueId} entry={entry} />+ </div>{retryableAgentFailureComment(entry) && (<TaskCommentRetryButtonissueId={issueId}@@ -929,10 +985,8 @@ export function AgentRunComment({ run, standalone = false, commentProps, enterin<CommentRow {...commentProps}isHighlighted={commentProps.highlightedCommentId === reply?.id}isResolution={!!reply?.resolved_at}- runHeader={showCommentRunInHeader(run)- ? <InlineCommentRun run={run} viewState={viewState} presentation="header" /> : undefined}- runMetadata={!showCommentRunInHeader(run)- ? <InlineCommentRun run={run} viewState={viewState} /> : undefined} />+ runHeader={<PlacedInlineCommentRun run={run} viewState={viewState} presentation="header" />}+ runMetadata={<PlacedInlineCommentRun run={run} viewState={viewState} />} />) : <div className="px-4 max-md:px-3"><InlineCommentRun run={run} viewState={viewState} showIdentity /></div>}@@ -1000,8 +1054,9 @@ function CommentCardImpl({const edit = useEditAttachmentState(issueId, entry, onEdit);const isOwn = entry.actor_type === "member" && entry.actor_id === currentUserId;- const canEditEntry = isOwn || (canModerate && entry.actor_type === "member");- const canDeleteEntry = isOwn || canModerate;+ const canEditEntry = !entry.supplement_task_id && (isOwn || (canModerate && entry.actor_type === "member"));+ const supplementInFlight = entry.supplement_status === "pending" || entry.supplement_status === "delivering";+ const canDeleteEntry = !supplementInFlight && (isOwn || canModerate);const [confirmDelete, setConfirmDelete] = useState(false);const allNestedReplies = replies;@@ -1020,9 +1075,8 @@ function CommentCardImpl({const slottedReplyIds = new Set(slottedRuns.flatMap((run) =>[run.commentId, ...(runOutputs.get(run.task.id) ?? []).map((reply) => reply.id)]));const renderRuns = (commentId: string, presentation: "inline" | "header" = "inline") => runs.filter((run) => run.commentId === commentId && run.hasReply- && showCommentRunInHeader(run) === (presentation === "header")&& (!run.anchorCommentId || run.anchorCommentId === commentId || replyFolded))- .map((run) => <InlineCommentRun key={run.task.id} run={run} presentation={presentation} viewState={run.commentId === entry.id ? runViewState : undefined} />);+ .map((run) => <PlacedInlineCommentRun key={run.task.id} run={run} presentation={presentation} viewState={run.commentId === entry.id ? runViewState : undefined} />);const renderAnchoredRuns = (commentId: string) => runs.filter((run) => run.anchorCommentId === commentId&& !(replyFolded && run.hasReply))@@ -1382,6 +1436,9 @@ 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" />+ <div className="pl-8 max-md:pl-0">+ <SupplementReceipt issueId={issueId} entry={entry} />+ </div>{retryableAgentFailureComment(entry) && (<TaskCommentRetryButtonissueId={issueId}diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsxindex c551e7bc3d..d74bb2d90e 100644--- a/packages/views/issues/components/comment-composers.test.tsx+++ b/packages/views/issues/components/comment-composers.test.tsx@@ -1,4 +1,4 @@-import { forwardRef, useEffect, useImperativeHandle, useRef, type ReactNode, type Ref } from "react";+import { forwardRef, useEffect, useImperativeHandle, useRef, useState, type ReactNode, type Ref } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { describe, it, expect, vi, beforeEach } from "vitest";import { act, fireEvent, screen, waitFor } from "@testing-library/react";@@ -102,6 +102,7 @@ vi.mock("../../editor", async () => ({ContentEditor: forwardRef(function MockContentEditor({defaultValue,+ value,onUpdate,placeholder,onUploadFile,@@ -111,6 +112,7 @@ vi.mock("../../editor", async () => ({quickActionMenu,}: {defaultValue?: string;+ value?: string;onUpdate?: (markdown: string) => void;placeholder?: string;onUploadFile?: (file: File, uploadId: string) => Promise<UploadResult | null>;@@ -124,7 +126,9 @@ vi.mock("../../editor", async () => ({editorDefaultValues.values.push(defaultValue);editorQuickActionMenu.last = quickActionMenu;editorUploadSignal.notify = onUploadingChange;- const valueRef = useRef(defaultValue ?? "");+ const initialValue = value ?? defaultValue ?? "";+ const valueRef = useRef(initialValue);+ const [editorValue, setEditorValue] = useState(initialValue);// Mirrors the real editor's `uploading` node attrs: the placeholder exists// from before the await until the upload settles, `hasActiveUploads` reads// it synchronously, and the host is told through onUploadingChange.@@ -141,11 +145,17 @@ vi.mock("../../editor", async () => ({};// eslint-disable-next-line react-hooks/exhaustive-deps}, []);+ useEffect(() => {+ if (value === undefined || value === valueRef.current) return;+ valueRef.current = value;+ setEditorValue(value);+ }, [value]);useImperativeHandle(ref, () => ({getMarkdown: () => valueRef.current,clearContent: () => {valueRef.current = "";+ setEditorValue("");},focus: () => { focusCalls.focused += 1; },focusAtCoords: () => {},@@ -157,6 +167,7 @@ vi.mock("../../editor", async () => ({const result = await onUploadFile?.(file, `mock-upload-${++mockUploadIdSeq}`);if (!result || destroyedRef.current) return;valueRef.current = `${valueRef.current}\n${result.url}`.trim();+ setEditorValue(valueRef.current);onUpdate?.(valueRef.current);} finally {inFlightRef.current -= 1;@@ -176,6 +187,7 @@ vi.mock("../../editor", async () => ({insertMarkdownSpy(md);if (destroyedRef.current || !insertMarkdownBehavior.succeed) return false;valueRef.current = `${valueRef.current}\n\n${md}`.trim();+ setEditorValue(valueRef.current);onUpdate?.(valueRef.current);return true;},@@ -184,10 +196,11 @@ vi.mock("../../editor", async () => ({return (<textareadata-testid="editor"- defaultValue={defaultValue}+ value={editorValue}placeholder={placeholder}onChange={(event) => {valueRef.current = event.target.value;+ setEditorValue(event.target.value);onUpdate?.(event.target.value);}}onKeyDown={(event) => {diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsxindex a5dff3c6a8..ed8a1a6e13 100644--- a/packages/views/issues/components/comment-input.tsx+++ b/packages/views/issues/components/comment-input.tsx@@ -36,10 +36,8 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme// Sending mid-upload would strip the pending image's blob URL out of the// markdown and bind no attachment id — the comment posts without the file.const uploadGate = useUploadGate(editorRef);- // Read the persisted draft once on mount. ContentEditor only honors- // `defaultValue` at mount time, so this snapshot drives both the editor's- // initial content and the submit-button enable state — without this the- // button would be disabled even though the editor visibly contains text.+ // Subscribe to the persisted draft so an explicit recovery action from a+ // completed run can move text here even while this composer is mounted.// Quick actions in the `/` menu: picking one inserts the server-rendered// body so the user can edit before sending, instead of firing immediately.const quickActionMenu = useQuickActionMenu(issueId);@@ -47,6 +45,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Commeconst [initialDraft] = useState(() =>useCommentDraftStore.getState().getDraft(draftKey),);+ const persistedDraft = useCommentDraftStore((store) => store.getDraft(draftKey));const [content, setContent] = useState(initialDraft ?? "");const [isEmpty, setIsEmpty] = useState(() => !initialDraft?.trim());const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());@@ -88,6 +87,17 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme// Flush on every onUpdate (debounced upstream) + visibilitychange/pagehide// so tab close / mobile background doesn't lose work. Cleared on submit.const setDraft = useCommentDraftStore((s) => s.setDraft);+ useEffect(() => {+ // Only an actual stored value is an external update. An absent entry is+ // not a command to erase the editor: it is normal during the synchronous+ // keystroke -> store handoff and after explicit submit cleanup.+ if (persistedDraft === undefined) return;+ const next = persistedDraft;+ if (next === content) return;+ setContent(next);+ setIsEmpty(!next.trim());+ if (next.trim()) lazy.activate();+ }, [content, lazy, persistedDraft]);useEffect(() => {const flush = () => {const md = editorRef.current?.getMarkdown();@@ -232,7 +242,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation }: Comme><ContentEditorref={editorRef}- defaultValue={initialDraft}+ value={persistedDraft ?? content}onReady={lazy.onReady}placeholder={t(($) => $.comment.leave_comment_placeholder)}onUpdate={(md) => {diff --git a/packages/views/issues/components/comment-runs.test.ts b/packages/views/issues/components/comment-runs.test.tsindex d314fe28ea..47a7e4b65a 100644--- a/packages/views/issues/components/comment-runs.test.ts+++ b/packages/views/issues/components/comment-runs.test.ts@@ -14,6 +14,29 @@ function comment(id: string, overrides: Partial<TimelineEntry> = {}): TimelineEn}describe("groupCommentRuns", () => {+ it("moves one run after each accepted supplement and keeps the final answer in that block", () => {+ const root = comment("root");+ const supplement = comment("supplement", {+ parent_id: root.id,+ created_at: "2026-09-07T00:01:00Z",+ supplement_task_id: "run",+ supplement_status: "delivered",+ });+ const answer = comment("answer", {+ actor_type: "agent",+ source_task_id: "run",+ created_at: "2026-09-07T00:02:00Z",+ });+ const run = task("run", { trigger_comment_id: root.id, delivered_comment_ids: [root.id] });+ const view = buildCommentRunView([run], [root, supplement, answer]);+ expect(view.runs.get(root.id)?.[0]).toMatchObject({+ anchorCommentId: supplement.id,+ commentId: answer.id,+ hasReply: true,+ });+ expect(view.timeline.find((entry) => entry.id === answer.id)?.parent_id).toBe(supplement.id);+ });+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",delivered_comment_ids: status === "queued" || status === "dispatched" ? [] : ["trigger"] });diff --git a/packages/views/issues/components/comment-runs.ts b/packages/views/issues/components/comment-runs.tsindex b73a4b034c..840dfe599c 100644--- a/packages/views/issues/components/comment-runs.ts+++ b/packages/views/issues/components/comment-runs.ts@@ -44,6 +44,13 @@ export function buildCommentRunView(// in Execution history, but it must not become an unanchored Activity block.const inlineTasks = tasks.filter((task) => task.kind !== "quick_create");const comments = new Map(timeline.filter((entry) => entry.type === "comment").map((entry) => [entry.id, entry]));+ const supplementalByTask = new Map<string, string[]>();+ for (const entry of comments.values()) {+ if (!entry.supplement_task_id) continue;+ const ids = supplementalByTask.get(entry.supplement_task_id) ?? [];+ ids.push(entry.id);+ supplementalByTask.set(entry.supplement_task_id, ids);+ }const timelineOrder = new Map(timeline.map((entry, index) => [entry.id, index]));const threadRoot = (id: string): string | undefined => {const seen = new Set<string>();@@ -88,9 +95,14 @@ export function buildCommentRunView(|| (source.status === "dispatched" && !source.delivered_comment_ids?.length)|| ((source.status === "cancelled" || source.status === "failed")&& !source.dispatched_at && !source.started_at);- const ids = !usesPlannedCoverage && source.delivered_comment_ids !== undefined+ const baseIds = !usesPlannedCoverage && source.delivered_comment_ids !== undefined? source.delivered_comment_ids: [source.trigger_comment_id, ...(source.coalesced_comment_ids ?? [])];+ const ids = [...new Set([+ ...baseIds,+ ...(source.supplement_comment_ids ?? []),+ ...(supplementalByTask.get(source.id) ?? []),+ ])];const candidates = ids.flatMap((id) => id && comments.has(id) ? [comments.get(id)!] : []);const latestCandidateId = () => [...candidates].sort((a, b) => b.created_at.localeCompare(a.created_at)|| (timelineOrder.get(b.id) ?? -1) - (timelineOrder.get(a.id) ?? -1))[0]?.id;diff --git a/packages/views/issues/components/inline-comment-run.test.tsx b/packages/views/issues/components/inline-comment-run.test.tsxindex 471d6337b9..ef698dc12f 100644--- a/packages/views/issues/components/inline-comment-run.test.tsx+++ b/packages/views/issues/components/inline-comment-run.test.tsx@@ -4,14 +4,20 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { ReactNode } from "react";import { api } from "@multica/core/api";import { chatKeys } from "@multica/core/chat/queries";-import type { AgentTask } from "@multica/core/types";+import { issueKeys } from "@multica/core/issues/queries";+import { useCommentDraftStore, useTaskSupplementDraftStore } from "@multica/core/issues/stores";+import type { AgentTask, TimelineEntry } from "@multica/core/types";import type { TaskMessagePayload } from "@multica/core/types/events";import { renderWithI18n } from "../../test/i18n";-import { InlineCommentRun } from "./inline-comment-run";+import { InlineCommentRun, PlacedInlineCommentRun } from "./inline-comment-run";+import { SupplementReceipt } from "./comment-card";++const dispatchReasonCodeMock = vi.hoisted(() => vi.fn());vi.mock("@multica/core/api", () => ({ api: {getIssue: vi.fn(), listTaskMessages: vi.fn(), cancelTask: vi.fn(), rerunIssue: vi.fn(),-}, dispatchReasonCode: () => undefined }));+ createTaskSupplement: vi.fn(), retryTaskSupplement: vi.fn(), listTasksByIssue: vi.fn(),+}, dispatchReasonCode: dispatchReasonCodeMock }));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace" }));vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Reviewer" }) }));vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => <span /> }));@@ -31,7 +37,12 @@ const messages: TaskMessagePayload[] = [{ task_id: id, issue_id: "issue", seq: 1, type: "text", content: "Checking navigation." },{ task_id: id, issue_id: "issue", seq: 2, type: "tool_use", tool: "exec_command", input: { command: "pnpm test" } },];-afterEach(() => { cleanup(); vi.clearAllMocks(); });+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ useTaskSupplementDraftStore.setState({ drafts: {} });+ useCommentDraftStore.setState({ drafts: {} });+});function setup(initialTask: AgentTask, hasReply = false, presentation: "inline" | "header" = "inline") {const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });@@ -43,6 +54,204 @@ function setup(initialTask: AgentTask, hasReply = false, presentation: "inline"}describe("InlineCommentRun", () => {+ it("creates no receipt observers for ordinary or delivered comments", () => {+ const client = new QueryClient();+ const entry = { id: "comment", type: "comment" } as TimelineEntry;+ renderWithI18n(<QueryClientProvider client={client}>+ <SupplementReceipt issueId="issue" entry={entry} />+ <SupplementReceipt issueId="issue" entry={{ ...entry, supplement_task_id: id, supplement_status: "delivered" }} />+ </QueryClientProvider>);+ expect(client.getQueryCache().getAll()).toHaveLength(0);+ });++ it.each(["toggle", "cancel", "escape"])("closes and clears a running draft with %s", (action) => {+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);+ setup(task({ supplement_capability: "task-supplement-v1", can_supplement: true }));+ fireEvent.click(screen.getByRole("button", { name: "Add message" }));+ const input = screen.getByPlaceholderText("Add guidance for this running turn");+ fireEvent.change(input, { target: { value: "Discard this draft." } });+ if (action === "escape") fireEvent.keyDown(input, { key: "Escape" });+ else fireEvent.click(screen.getByRole("button", { name: action === "toggle" ? "Add message" : "Cancel" }));+ expect(screen.queryByPlaceholderText("Add guidance for this running turn")).not.toBeInTheDocument();+ expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();+ expect(api.createTaskSupplement).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Add message" }));+ expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("");+ });++ it.each(["completed", "cancelled", "failed"] as const)("removes an empty panel when the run becomes %s", (status) => {+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);+ const current = task({ supplement_capability: "task-supplement-v1", can_supplement: true });+ const { rerender } = setup(current);+ fireEvent.click(screen.getByRole("button", { name: "Add message" }));+ rerender({ ...current, status });+ expect(screen.queryByPlaceholderText("Add guidance for this running turn")).not.toBeInTheDocument();+ expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();+ });++ it.each(["Move to new message", "Discard"])("lets a terminal draft %s and restores the reply header", (action) => {+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);+ const current = task({ supplement_capability: "task-supplement-v1", can_supplement: true });+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const view = (status: AgentTask["status"], hasReply: boolean) => <QueryClientProvider client={client}>+ <PlacedInlineCommentRun run={{ task: { ...current, status }, commentId: "reply", hasReply }} presentation="header" />+ <PlacedInlineCommentRun run={{ task: { ...current, status }, commentId: "reply", hasReply }} />+ </QueryClientProvider>;+ const rendered = renderWithI18n(view("running", false));+ fireEvent.click(screen.getByRole("button", { name: "Add message" }));+ fireEvent.change(screen.getByPlaceholderText("Add guidance for this running turn"), { target: { value: "Preserve this only on move." } });+ rendered.rerender(view("completed", true));+ expect(screen.getByRole("button", { name: "Move to new message" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Discard" })).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: action }));+ expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();+ expect(useCommentDraftStore.getState().getDraft("new:issue")).toBe(action === "Discard" ? undefined : "Preserve this only on move.");+ expect(screen.queryByPlaceholderText("Add guidance for this running turn")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Open full log" })).toBeInTheDocument();+ expect(api.createTaskSupplement).not.toHaveBeenCalled();+ });++ it("disables additional messages without negotiated support", () => {+ const { client } = setup(task());+ expect(screen.getByRole("button", { name: "Add message" })).toBeDisabled();+ client.clear();+ });+ it("preserves additional-message text when delivery submission fails", async () => {+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);+ vi.mocked(api.createTaskSupplement).mockRejectedValue(new Error("run ended"));+ setup(task({ supplement_capability: "task-supplement-v1", can_supplement: true }));+ fireEvent.click(screen.getByRole("button", { name: "Add message" }));+ const input = screen.getByPlaceholderText("Add guidance for this running turn");+ fireEvent.change(input, { target: { value: "preserve this draft" } });+ fireEvent.click(screen.getByRole("button", { name: "Send" }));+ await waitFor(() => expect(api.createTaskSupplement).toHaveBeenCalled());+ expect(input).toHaveValue("preserve this draft");+ });++ it.each([false, true])("settles a sent draft after the run remounts (edited: %s)", async (edited) => {+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);+ const comment = {+ id: "supplement-comment", issue_id: "issue", author_type: "member" as const, author_id: "user",+ content: "Create a rollback note.", type: "comment" as const, parent_id: null, reactions: [], attachments: [],+ created_at: "2026-09-07T00:00:10Z", updated_at: "2026-09-07T00:00:10Z",+ resolved_at: null, resolved_by_type: null, resolved_by_id: null,+ supplement_task_id: id, supplement_status: "pending" as const,+ };+ let resolveRequest!: (value: typeof comment) => void;+ const request = new Promise<typeof comment>((resolve) => { resolveRequest = resolve; });+ vi.mocked(api.createTaskSupplement).mockReturnValue(request);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ const current = task({ supplement_capability: "task-supplement-v1", can_supplement: true });+ const view = (commentId: string) => <QueryClientProvider client={client}>+ <PlacedInlineCommentRun key={commentId} run={{ task: current, commentId, hasReply: false }} />+ </QueryClientProvider>;+ const rendered = renderWithI18n(view("comment"));+ fireEvent.click(screen.getByRole("button", { name: "Add message" }));+ const input = screen.getByPlaceholderText("Add guidance for this running turn");+ fireEvent.change(input, { target: { value: comment.content } });+ fireEvent.click(screen.getByRole("button", { name: "Send" }));+ await waitFor(() => expect(api.createTaskSupplement).toHaveBeenCalledWith(+ "issue", id, comment.content, expect.any(String),+ ));++ // A realtime comment can re-anchor the run before the send response arrives.+ rendered.rerender(view(comment.id));+ const remountedInput = screen.getByPlaceholderText("Add guidance for this running turn");+ expect(remountedInput).not.toBe(input);+ expect(remountedInput).toHaveValue(comment.content);+ if (edited) fireEvent.change(remountedInput, { target: { value: "A newer unsent draft." } });++ await act(async () => resolveRequest(comment));+ await waitFor(() => expect(client.getMutationCache().getAll()[0]?.state.status).toBe("success"));+ if (edited) {+ expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("A newer unsent draft.");+ } else {+ expect(screen.queryByPlaceholderText("Add guidance for this running turn")).not.toBeInTheDocument();+ expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();+ fireEvent.click(screen.getByRole("button", { name: "Add message" }));+ expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("");+ }+ client.clear();+ });++ it("keeps the task draft through reply placement changes and a full remount", () => {+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ const view = (hasReply: boolean) => <QueryClientProvider client={client}>+ <PlacedInlineCommentRun run={{ task: task({ supplement_capability: "task-supplement-v1", can_supplement: true }), commentId: "reply", hasReply }} presentation="header" />+ <PlacedInlineCommentRun run={{ task: task({ supplement_capability: "task-supplement-v1", can_supplement: true }), commentId: "reply", hasReply }} />+ </QueryClientProvider>;+ const rendered = renderWithI18n(view(false));+ fireEvent.click(screen.getByRole("button", { name: "Add message" }));+ fireEvent.change(screen.getByPlaceholderText("Add guidance for this running turn"), {+ target: { value: "Create remount-proof evidence." },+ });++ rendered.rerender(view(true));+ expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("Create remount-proof evidence.");+ rendered.unmount();++ renderWithI18n(view(true));+ expect(screen.getByPlaceholderText("Add guidance for this running turn")).toHaveValue("Create remount-proof evidence.");+ expect(screen.queryByRole("button", { name: "Open full log" })).not.toBeInTheDocument();+ });++ it("keeps a 409 draft and moves it explicitly to the new-message composer", async () => {+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);+ dispatchReasonCodeMock.mockReturnValue("task_supplement_turn_ended");+ vi.mocked(api.createTaskSupplement).mockRejectedValue(new Error("ended"));+ setup(task({ supplement_capability: "task-supplement-v1", can_supplement: true }));+ fireEvent.click(screen.getByRole("button", { name: "Add message" }));+ const input = screen.getByPlaceholderText("Add guidance for this running turn");+ fireEvent.change(input, { target: { value: "Create retained.txt." } });+ fireEvent.click(screen.getByRole("button", { name: "Send" }));+ const move = await screen.findByRole("button", { name: "Move to new message" });+ expect(input).toHaveValue("Create retained.txt.");+ fireEvent.click(move);+ expect(useCommentDraftStore.getState().getDraft("new:issue")).toBe("Create retained.txt.");+ expect(useTaskSupplementDraftStore.getState().drafts[id]).toBeUndefined();+ });++ it.each(["completed", "cancelled", "failed"] as const)("settles a pending receipt immediately when the run becomes %s", async (status) => {+ const entry = {+ id: "supplement-comment", issue_id: "issue", actor_type: "member", actor_id: "user",+ content: "Create receipt evidence.", type: "comment", created_at: "2026-09-07T00:00:10Z",+ supplement_task_id: id, supplement_status: "pending",+ } as TimelineEntry;+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ client.setQueryData(issueKeys.tasks("issue"), [task()]);+ renderWithI18n(<QueryClientProvider client={client}>+ <SupplementReceipt issueId="issue" entry={entry} />+ </QueryClientProvider>);+ expect(screen.getByRole("status")).toHaveTextContent("Waiting for delivery");+ act(() => client.setQueryData(issueKeys.tasks("issue"), [task({ status })]));+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Not delivered · the run ended before delivery"));+ expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument();+ });++ it("localizes a stable injection failure and retries the same bound comment", async () => {+ vi.mocked(api.retryTaskSupplement).mockResolvedValue();+ vi.mocked(api.listTasksByIssue).mockResolvedValue([task()]);+ const entry = {+ id: "supplement-comment", issue_id: "issue", actor_type: "member", actor_id: "user",+ content: "Create receipt evidence.", type: "comment", created_at: "2026-09-07T00:00:10Z",+ supplement_task_id: id, supplement_status: "failed", supplement_failure_reason: "provider_rejected",+ } as TimelineEntry;+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ client.setQueryData(issueKeys.tasks("issue"), [task()]);+ renderWithI18n(<QueryClientProvider client={client}>+ <SupplementReceipt issueId="issue" entry={entry} />+ </QueryClientProvider>);++ expect(screen.getByRole("alert")).toHaveTextContent("Not delivered · the agent rejected the message");+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ await waitFor(() => expect(api.retryTaskSupplement).toHaveBeenCalledWith("issue", id, "supplement-comment"));+ await waitFor(() => expect(screen.getByRole("button", { name: "Retry" })).not.toBeDisabled());+ act(() => client.setQueryData(issueKeys.tasks("issue"), [task({ status: "completed" })]));+ await waitFor(() => expect(screen.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument());+ expect(screen.getByRole("alert")).toHaveTextContent("Not delivered · the agent rejected the message");+ });+it("previews streamed agent messages in collapsed steps and expands the full body", async () => {const message: TaskMessagePayload = {task_id: id, issue_id: "issue", seq: 1, type: "text", content: "Checking the PR",diff --git a/packages/views/issues/components/inline-comment-run.tsx b/packages/views/issues/components/inline-comment-run.tsxindex c0c28e3baf..53180df016 100644--- a/packages/views/issues/components/inline-comment-run.tsx+++ b/packages/views/issues/components/inline-comment-run.tsx@@ -1,17 +1,19 @@"use client";import { useEffect, useId, useMemo, useState } from "react";-import { AlertCircle, Brain, ChevronRight, CirclePause, Clock3, ExternalLink, Loader2, MessageSquare, RotateCcw, ScrollText, Square, Terminal } from "lucide-react";+import { AlertCircle, Brain, ChevronRight, CirclePause, Clock3, ExternalLink, Loader2, MessageSquare, MessageSquarePlus, RotateCcw, ScrollText, Send, Square, Terminal } from "lucide-react";import { toast } from "sonner";import { useWorkspaceId } from "@multica/core/hooks";import { useTraceIssueLabels } from "../../common/task-transcript/use-trace-issue-labels";import { useActorName } from "@multica/core/workspace/hooks";import { useTaskMessages } from "@multica/core/chat/queries";-import { useCancelIssueRun, useRetryIssueRun } from "@multica/core/issues/mutations";+import { useCancelIssueRun, useCreateTaskSupplement, useRetryIssueRun } from "@multica/core/issues/mutations";+import { useCommentDraftStore, useTaskSupplementDraftStore } from "@multica/core/issues/stores";import { dispatchReasonCode } from "@multica/core/api";import type { AgentTask } from "@multica/core/types";import { ActorAvatar } from "../../common/actor-avatar";import { Button } from "@multica/ui/components/ui/button";+import { Textarea } from "@multica/ui/components/ui/textarea";import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";import { cn } from "@multica/ui/lib/utils";import { AgentTranscriptDialog, StepBody } from "../../common/task-transcript/agent-transcript-dialog";@@ -52,6 +54,16 @@ export function useInlineCommentRunState() {export type InlineCommentRunState = ReturnType<typeof useInlineCommentRunState>;+export function PlacedInlineCommentRun({ presentation = "inline", ...props }: Parameters<typeof InlineCommentRun>[0]) {+ const draft = useTaskSupplementDraftStore((store) => store.drafts[props.run.task.id]);+ // A live reply normally compacts its run into the comment header. Once the+ // user opens a task draft, keep the full run mounted at its timeline slot so+ // reply arrival and supplement-driven re-anchoring cannot discard the text.+ const inHeader = showCommentRunInHeader(props.run) && !draft?.open;+ if ((presentation === "header") !== inHeader) return null;+ return <InlineCommentRun {...props} presentation={presentation} />;+}+export function InlineCommentRun({ run, className, viewState, showIdentity = false, presentation = "inline" }: {run: CommentRun;className?: string;@@ -73,9 +85,11 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = falconst [confirmStop, setConfirmStop] = useState(false);const [now, setNow] = useState(Date.now);const [visibleCount, setVisibleCount] = useState(12);+ const supplementDraft = useTaskSupplementDraftStore((store) => store.drafts[task.id]);const animationVisibility = useRunAnimationVisibility<HTMLDivElement>();const cancel = useCancelIssueRun(task.issue_id);const retry = useRetryIssueRun(task.issue_id);+ const supplement = useCreateTaskSupplement(task.issue_id);const regionId = useId();// Keep one disclosure button mounted across queued, live, and historical states.// Historical, collapsed runs still don't fetch transcripts.@@ -116,6 +130,46 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = falconst activityLabel = t(($) => $.inline_run.view_activity);const stepLabel = steps.length > 0 ? t(($) => $.inline_run.steps, { count: steps.length }) : "";const stopLabel = cancel.isPending || cancel.isSuccess ? t(($) => $.inline_run.stopping) : t(($) => $.inline_run.stop);+ const canSupplement = task.status === "running"+ && task.supplement_capability === "task-supplement-v1"+ && task.can_supplement === true+ && !supplementDraft?.ended;+ const supplementDisabledReason = supplementDraft?.ended+ ? t(($) => $.inline_run.supplement_ended)+ : task.status !== "running"+ ? t(($) => $.inline_run.supplement_waiting_start)+ : task.supplement_capability !== "task-supplement-v1"+ ? t(($) => $.inline_run.supplement_unsupported)+ : !task.can_supplement ? t(($) => $.inline_run.supplement_forbidden) : "";+ useEffect(() => {+ if (supplementDraft && task.status !== "running" && !active) {+ useTaskSupplementDraftStore.getState().markEnded(task.id);+ }+ }, [active, supplementDraft, task.id, task.status]);+ const closeSupplement = () => {+ if (!supplement.isPending) useTaskSupplementDraftStore.getState().clear(task.id);+ };+ const submitSupplement = () => {+ const content = supplementDraft?.content.trim() ?? "";+ if (!content || !canSupplement || supplement.isPending) return;+ const clientRequestId = supplementDraft?.clientRequestId ?? crypto.randomUUID();+ useTaskSupplementDraftStore.getState().setRequestId(task.id, clientRequestId);+ supplement.mutate({ taskId: task.id, content, clientRequestId }, {+ onError: (error) => {+ const code = dispatchReasonCode(error);+ if (code === "task_supplement_turn_ended") {+ useTaskSupplementDraftStore.getState().markEnded(task.id);+ }+ toast.error(code === "task_supplement_turn_ended"+ ? t(($) => $.inline_run.supplement_ended)+ : code === "task_supplement_unsupported"+ ? t(($) => $.inline_run.supplement_unsupported)+ : code === "invocation_not_allowed"+ ? t(($) => $.inline_run.supplement_forbidden)+ : t(($) => $.inline_run.supplement_failed));+ },+ });+ };const transcript = fullLogOpen && <AgentTranscriptDialog open onOpenChange={setFullLogOpen}task={task} items={items} agentName={name} isLive={active} finalFocus={logFromKeyboard}contentState={isPending ? <p role="status" className="text-body text-muted-foreground">{t(($) => $.inline_run.loading)}</p>@@ -127,6 +181,19 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = falonClick={() => setConfirmStop(true)}>{cancel.isPending || cancel.isSuccess ? <Loader2 className="size-3.5 animate-spin motion-reduce:animate-none" /> : <Square className="size-3.5" />}</Button>;+ const supplementButton = active && <Tooltip>+ <TooltipTrigger render={<span className="inline-flex">+ <Button type="button" size="sm" variant="ghost" className="text-muted-foreground"+ aria-label={t(($) => $.inline_run.supplement_action)}+ aria-expanded={!!supplementDraft?.open}+ disabled={supplement.isPending || (!supplementDraft?.open && !canSupplement)}+ onClick={() => supplementDraft?.open ? closeSupplement() : useTaskSupplementDraftStore.getState().open(task.id, task.issue_id)}>+ <MessageSquarePlus className="size-3.5" />+ <span className="@max-[32rem]/run:sr-only">{t(($) => $.inline_run.supplement_action)}</span>+ </Button>+ </span>} />+ <TooltipContent>{canSupplement ? t(($) => $.inline_run.supplement_action) : supplementDisabledReason}</TooltipContent>+ </Tooltip>;const stopDialog = <TerminateTaskConfirmDialog open={confirmStop} onOpenChange={setConfirmStop}showRunningNote={task.status !== "queued"}onConfirm={() => cancel.mutate(task.id, { onError: () => toast.error(t(($) => $.execution_log.cancel_failed)) })} />;@@ -171,6 +238,7 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = fal<ChevronRight ref={state.disclosure.chevronRef} aria-hidden className={cn("size-3.5 shrink-0", expanded && "rotate-90")} /></button><span className={cn("shrink-0 whitespace-nowrap text-caption tabular-nums text-muted-foreground", showIdentity && !active && "@max-[32rem]/run:hidden")}>{elapsed}</span>+ {supplementButton}{stopButton}{!hasReply && (task.status === "failed" || task.status === "cancelled") && <Buttonsize="sm" variant="ghost" className={cn("text-muted-foreground", showIdentity && "@max-[32rem]/run:size-7 @max-[32rem]/run:p-0")} disabled={retry.isPending || retry.isSuccess}@@ -181,6 +249,51 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = fal</Button>}</div><div className={cn(showIdentity && "pl-8")}>+ {supplementDraft?.open && <div className="mt-2 space-y-2 rounded-md border bg-muted/20 p-2"+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ closeSupplement();+ }+ }}>+ <Textarea value={supplementDraft.content} autoFocus rows={3}+ placeholder={t(($) => $.inline_run.supplement_placeholder)}+ disabled={supplement.isPending}+ onChange={(event) => {+ useTaskSupplementDraftStore.getState().setContent(task.id, task.issue_id, event.target.value);+ }}+ onKeyDown={(event) => {+ if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {+ event.preventDefault();+ submitSupplement();+ }+ }} />+ <div className="flex items-center justify-between gap-2">+ <p className="text-micro text-muted-foreground">{canSupplement+ ? t(($) => $.inline_run.supplement_notice)+ : supplementDraft.ended || task.status !== "running" ? t(($) => $.inline_run.supplement_ended) : supplementDisabledReason}</p>+ <div className="flex shrink-0 items-center gap-2">+ <Button type="button" size="sm" variant="outline" disabled={supplement.isPending} onClick={closeSupplement}>+ {supplementDraft.ended ? t(($) => $.inline_run.supplement_discard) : t(($) => $.comment.cancel_action)}+ </Button>+ {supplementDraft.ended && supplementDraft.content.trim() && <Button type="button" size="sm" variant="outline"+ disabled={supplement.isPending}+ onClick={() => {+ useCommentDraftStore.getState().appendToDraftContent(`new:${task.issue_id}`, supplementDraft.content);+ useTaskSupplementDraftStore.getState().clear(task.id);+ toast.success(t(($) => $.inline_run.supplement_moved));+ }}>+ {t(($) => $.inline_run.supplement_move_to_new)}+ </Button>}+ {!supplementDraft.ended && <Button type="button" size="sm" disabled={!supplementDraft.content.trim() || supplement.isPending || !canSupplement}+ onClick={submitSupplement}>+ {supplement.isPending ? <Loader2 className="size-3.5 animate-spin motion-reduce:animate-none" /> : <Send className="size-3.5" />}+ {t(($) => $.inline_run.supplement_send)}+ </Button>}+ </div>+ </div>+ </div>}{output && <div className="mt-2 text-body"><ReadonlyContent content={redactSecrets(output)} /></div>}{failure && <p className="mt-1 text-caption text-destructive">{failure}</p>}{expanded && <div id={regionId} className="mt-2 min-w-0 space-y-1">diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex a29559e515..95ad33cfad 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -422,6 +422,10 @@ vi.mock("@multica/core/issues/stores", async () => ({}),},),+ useTaskSupplementDraftStore: (await import("zustand")).create(() => ({+ drafts: {}, open: vi.fn(), setContent: vi.fn(), setRequestId: vi.fn(),+ markEnded: vi.fn(), clear: vi.fn(),+ })),useCommentComposerStore: Object.assign((selector?: any) => {const state = { sticky: true, toggleSticky: () => {} };diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.tsindex cee70faf44..0fbef1ab23 100644--- a/packages/views/issues/hooks/use-issue-timeline.ts+++ b/packages/views/issues/hooks/use-issue-timeline.ts@@ -65,6 +65,10 @@ 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,+ supplement_task_id: c.supplement_task_id,+ supplement_status: c.supplement_status,+ supplement_failure_reason: c.supplement_failure_reason,+ supplement_delivered_at: c.supplement_delivered_at,deleted_at: c.deleted_at,};}diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 4392410e09..612aa1ea38 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -19,7 +19,28 @@"full_log": "Open full log","message": "Agent message","error": "Error",- "waiting_result": "Waiting for the tool result..."+ "waiting_result": "Waiting for the tool result...",+ "supplement_action": "Add message",+ "supplement_placeholder": "Add guidance for this running turn",+ "supplement_send": "Send",+ "supplement_notice": "The agent keeps working on the original goal.",+ "supplement_waiting_start": "Available after this run starts.",+ "supplement_unsupported": "This run did not negotiate support for additional messages.",+ "supplement_forbidden": "You do not have permission to run this agent.",+ "supplement_ended": "This run has ended. Your text is preserved; start another run explicitly to send it.",+ "supplement_failed": "Could not send the message. Your text is preserved.",+ "supplement_waiting_delivery": "Waiting for delivery",+ "supplement_not_delivered": "Not delivered · {{reason}}",+ "supplement_failure_turn_ended": "the run ended before delivery",+ "supplement_failure_turn_not_started": "the agent was not ready",+ "supplement_failure_provider_rejected": "the agent rejected the message",+ "supplement_failure_timeout": "delivery timed out",+ "supplement_failure_unknown": "unknown reason",+ "supplement_move_to_new": "Move to new message",+ "supplement_discard": "Discard",+ "supplement_moved": "Moved to the new message box.",+ "supplement_retry": "Retry",+ "supplement_retry_failed": "Could not retry delivery."},"status_catalog_error": {"title": "Couldn't load the status list",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 163b7c1bb9..034569db25 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -19,7 +19,28 @@"full_log": "Ouvrir le journal complet","message": "Message de l'agent","error": "Erreur",- "waiting_result": "En attente du résultat de l'outil..."+ "waiting_result": "En attente du résultat de l'outil...",+ "supplement_action": "Ajouter un message",+ "supplement_placeholder": "Ajouter une consigne à cette exécution",+ "supplement_send": "Envoyer",+ "supplement_notice": "L'agent poursuit l'objectif initial.",+ "supplement_waiting_start": "Disponible après le démarrage de l'exécution.",+ "supplement_unsupported": "Cette exécution ne prend pas en charge les messages supplémentaires.",+ "supplement_forbidden": "Vous n'êtes pas autorisé à exécuter cet agent.",+ "supplement_ended": "Cette exécution est terminée. Votre texte est conservé ; lancez explicitement une autre exécution pour l'envoyer.",+ "supplement_failed": "Impossible d'envoyer le message. Votre texte est conservé.",+ "supplement_waiting_delivery": "En attente de livraison",+ "supplement_not_delivered": "Non livré · {{reason}}",+ "supplement_failure_turn_ended": "l'exécution s'est terminée avant la livraison",+ "supplement_failure_turn_not_started": "l’agent n’était pas prêt",+ "supplement_failure_provider_rejected": "l’agent a refusé le message",+ "supplement_failure_timeout": "la livraison a expiré",+ "supplement_failure_unknown": "raison inconnue",+ "supplement_move_to_new": "Déplacer vers un nouveau message",+ "supplement_discard": "Abandonner",+ "supplement_moved": "Déplacé vers la zone de nouveau message.",+ "supplement_retry": "Réessayer",+ "supplement_retry_failed": "Impossible de réessayer la livraison."},"status_catalog_error": {"title": "Impossible de charger la liste des états",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 3db3cf97fe..b45bb53c65 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -18,7 +18,28 @@"full_log": "完全なログを開く","message": "エージェントのメッセージ","error": "エラー",- "waiting_result": "ツールの結果を待っています..."+ "waiting_result": "ツールの結果を待っています...",+ "supplement_action": "メッセージを追加",+ "supplement_placeholder": "この実行に追加の指示を入力",+ "supplement_send": "送信",+ "supplement_notice": "エージェントは元の目標を継続します。",+ "supplement_waiting_start": "実行開始後に利用できます。",+ "supplement_unsupported": "この実行は追加メッセージに対応していません。",+ "supplement_forbidden": "このエージェントを実行する権限がありません。",+ "supplement_ended": "この実行は終了しました。入力は保持されています。送信するには明示的に別の実行を開始してください。",+ "supplement_failed": "メッセージを送信できませんでした。入力は保持されています。",+ "supplement_waiting_delivery": "配信待ち",+ "supplement_not_delivered": "未配信 · {{reason}}",+ "supplement_failure_turn_ended": "配信前に実行が終了しました",+ "supplement_failure_turn_not_started": "エージェントの準備ができていませんでした",+ "supplement_failure_provider_rejected": "エージェントがメッセージを拒否しました",+ "supplement_failure_timeout": "配信がタイムアウトしました",+ "supplement_failure_unknown": "原因不明",+ "supplement_move_to_new": "新しいメッセージへ移動",+ "supplement_discard": "破棄",+ "supplement_moved": "新しいメッセージ入力欄へ移動しました。",+ "supplement_retry": "再試行",+ "supplement_retry_failed": "配信を再試行できませんでした。"},"status_catalog_error": {"title": "ステータス一覧を読み込めませんでした",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex edd651a614..a5a806ec67 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -18,7 +18,28 @@"full_log": "전체 로그 열기","message": "에이전트 메시지","error": "오류",- "waiting_result": "도구 결과를 기다리고 있습니다..."+ "waiting_result": "도구 결과를 기다리고 있습니다...",+ "supplement_action": "메시지 추가",+ "supplement_placeholder": "이 실행에 추가 지침 입력",+ "supplement_send": "보내기",+ "supplement_notice": "에이전트는 원래 목표를 계속 처리합니다.",+ "supplement_waiting_start": "실행이 시작된 후 사용할 수 있습니다.",+ "supplement_unsupported": "이 실행은 추가 메시지를 지원하도록 협상되지 않았습니다.",+ "supplement_forbidden": "이 에이전트를 실행할 권한이 없습니다.",+ "supplement_ended": "이 실행은 종료되었습니다. 입력은 보존되며, 보내려면 새 실행을 명시적으로 시작하세요.",+ "supplement_failed": "메시지를 보내지 못했습니다. 입력은 보존됩니다.",+ "supplement_waiting_delivery": "전달 대기 중",+ "supplement_not_delivered": "전달되지 않음 · {{reason}}",+ "supplement_failure_turn_ended": "전달 전에 실행이 종료됨",+ "supplement_failure_turn_not_started": "에이전트가 준비되지 않음",+ "supplement_failure_provider_rejected": "에이전트가 메시지를 거부함",+ "supplement_failure_timeout": "전달 시간 초과",+ "supplement_failure_unknown": "알 수 없는 이유",+ "supplement_move_to_new": "새 메시지로 이동",+ "supplement_discard": "버리기",+ "supplement_moved": "새 메시지 입력란으로 이동했습니다.",+ "supplement_retry": "다시 시도",+ "supplement_retry_failed": "전달을 다시 시도하지 못했습니다."},"status_catalog_error": {"title": "상태 목록을 불러오지 못했습니다",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 5aeb9e2d99..93e42a8a7f 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -18,7 +18,28 @@"full_log": "打开完整日志","message": "智能体消息","error": "错误",- "waiting_result": "等待工具返回结果..."+ "waiting_result": "等待工具返回结果...",+ "supplement_action": "补充消息",+ "supplement_placeholder": "为本次运行补充纯文字要求",+ "supplement_send": "发送",+ "supplement_notice": "智能体会继续处理原目标。",+ "supplement_waiting_start": "运行开始后才可补充消息。",+ "supplement_unsupported": "本次运行未协商支持补充消息。",+ "supplement_forbidden": "你无权运行这个智能体。",+ "supplement_ended": "本次运行已结束。输入已保留;如需发送,请显式另起一轮。",+ "supplement_failed": "消息发送失败,输入已保留。",+ "supplement_waiting_delivery": "等待送达",+ "supplement_not_delivered": "未送达 · {{reason}}",+ "supplement_failure_turn_ended": "送达前运行已结束",+ "supplement_failure_turn_not_started": "智能体尚未就绪",+ "supplement_failure_provider_rejected": "智能体拒绝了该消息",+ "supplement_failure_timeout": "送达超时",+ "supplement_failure_unknown": "原因未知",+ "supplement_move_to_new": "移到新消息",+ "supplement_discard": "丢弃",+ "supplement_moved": "已移到新消息输入框。",+ "supplement_retry": "重试",+ "supplement_retry_failed": "无法重试送达。"},"status_catalog_error": {"title": "状态列表加载失败",diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex f35caa6078..cc3c03b906 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -141,6 +141,9 @@ var pgBigmOperatorClass = extensionOperatorClass{// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{"535_github_pr_address_index": "idx_github_pull_request_pr_owner_repo",+ "539_task_supplement_request_index": "task_supplement_task_request_uidx",+ "540_task_supplement_capability_index": "task_supplement_capability_task_uidx",+ "541_task_supplement_comment_index": "task_supplement_comment_uidx","510_wakeup_id": "issue_wakeup_id_idx","511_wakeup_issue": "issue_wakeup_issue_idx","512_wakeup_due": "issue_wakeup_due_idx",diff --git a/server/cmd/migrate/migrate_task_supplement_test.go b/server/cmd/migrate/migrate_task_supplement_test.gonew file mode 100644index 0000000000..16d8f7142f--- /dev/null+++ b/server/cmd/migrate/migrate_task_supplement_test.go@@ -0,0 +1,85 @@+package main++import (+ "context"+ "math/rand/v2"+ "slices"+ "testing"+ "time"+)++func TestTaskSupplementMigrationsUpDownUpInIsolatedSchema(t *testing.T) {+ base := openTestPool(t)+ ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)+ defer cancel()+ schema := createScratchSchema(t, ctx, base, "task_supplement_")+ pool := openTestPoolWithSearchPath(t, schema)+ if _, err := pool.Exec(ctx, `CREATE TABLE agent_task_queue (id UUID PRIMARY KEY, status TEXT NOT NULL)`); err != nil {+ t.Fatal(err)+ }++ for _, direction := range []string{"up", "down", "up"} {+ versions := []string{+ "538_task_supplement",+ "539_task_supplement_request_index",+ "540_task_supplement_capability_index",+ "541_task_supplement_comment_index",+ "542_task_supplement_primary_key",+ "543_task_supplement_teardown_guard",+ }+ if direction == "down" {+ slices.Reverse(versions)+ }+ if err := runMigrations(ctx, pool, runOptions{+ Direction: direction,+ Files: realMigrationFiles(t, versions, direction),+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: hooksForDirection(direction),+ Conditions: conditionsForDirection(direction),+ }); err != nil {+ t.Fatalf("migrate %s: %v", direction, err)+ }+ for _, table := range []string{"task_supplement", "task_supplement_capability"} {+ var exists bool+ if err := pool.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, schema+"."+table).Scan(&exists); err != nil || exists != (direction == "up") {+ t.Fatalf("after %s, table %s exists=%v: %v", direction, table, exists, err)+ }+ }+ if direction == "up" {+ var indexes int+ err := pool.QueryRow(ctx, `+ SELECT count(*) FROM pg_index i+ JOIN pg_class c ON c.oid = i.indexrelid+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = $1 AND i.indisvalid AND c.relname = ANY($2::text[])+ `, schema, []string{"task_supplement_task_request_uidx", "task_supplement_capability_task_uidx", "task_supplement_pkey"}).Scan(&indexes)+ if err != nil || indexes != 3 {+ t.Fatalf("valid supplement indexes = %d, want 3: %v", indexes, err)+ }+ var primary bool+ if err := pool.QueryRow(ctx, `SELECT indisprimary FROM pg_index WHERE indexrelid = 'task_supplement_pkey'::regclass`).Scan(&primary); err != nil || !primary {+ t.Fatalf("receipt primary key missing: %v", err)+ }+ // Teardown owns dependent deletion and must not run receipt settlement.+ tx, err := pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ _, err = tx.Exec(ctx, `+ INSERT INTO agent_task_queue VALUES ('00000000-0000-0000-0000-000000000001', 'running');+ INSERT INTO task_supplement (task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status)+ VALUES ('00000000-0000-0000-0000-000000000001', gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'pending');+ SET LOCAL multica.workspace_teardown = 'on';+ UPDATE agent_task_queue SET status='cancelled';`)+ var status string+ if err == nil {+ err = tx.QueryRow(ctx, `SELECT status FROM task_supplement`).Scan(&status)+ }+ _ = tx.Rollback(ctx)+ if err != nil || status != "pending" {+ t.Fatalf("teardown ran receipt settlement: %s, %v", status, err)+ }+ }+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex aa41b023f1..0342e10d8a 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -491,6 +491,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busif notifier, ok := opts.DaemonWakeup.(handler.DaemonPendingWorkNotifier); ok {h.DaemonPendingWork = notifier}+ if notifier, ok := opts.DaemonWakeup.(handler.DaemonTaskSupplementNotifier); ok {+ h.DaemonTaskSupplement = notifier+ }if notifier, ok := opts.DaemonWakeup.(handler.RuntimeGoneNotifier); ok {h.DaemonRuntimeGone = notifier}@@ -1556,6 +1559,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/tasks/{taskId}/status", h.GetTaskStatus)r.Post("/tasks/{taskId}/start", h.StartTask)+ r.Post("/tasks/{taskId}/supplements/claim", h.ClaimTaskSupplement)+ r.Post("/tasks/{taskId}/supplements/{commentId}/ack", h.AckTaskSupplement)r.Post("/tasks/{taskId}/wait-local-directory", h.MarkTaskWaitingLocalDirectory)r.Post("/tasks/{taskId}/progress", h.ReportTaskProgress)r.Post("/tasks/{taskId}/complete", h.CompleteTask)@@ -1995,6 +2000,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Patch("/wakeups/{wakeupID}/instruction", h.EditIssueWakeupInstruction)r.Get("/active-task", h.GetActiveTaskForIssue)r.Post("/tasks/{taskId}/cancel", h.CancelTask)+ r.With(handler.RequireHumanActor).Post("/tasks/{taskId}/supplements", h.CreateTaskSupplement)+ r.With(handler.RequireHumanActor).Post("/tasks/{taskId}/supplements/{commentId}/retry", h.RetryTaskSupplement)r.Post("/rerun", h.RerunIssue)r.Post("/quick-actions/{quickActionId}/run", h.RunQuickAction)r.Post("/quick-actions/{quickActionId}/render", h.RenderQuickAction)diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex c339edb5d6..cd9a5957e0 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -31,6 +31,8 @@ func (e *requestError) Error() string {return fmt.Sprintf("%s %s returned %d: %s", e.Method, e.Path, e.StatusCode, e.Body)}+var errInvalidResponseBody = errors.New("invalid response body")+// isWorkspaceNotFoundError returns true if the error is a 404 with "workspace not found" body.func isWorkspaceNotFoundError(err error) bool {var reqErr *requestError@@ -434,6 +436,30 @@ func (c *Client) ExtendTaskPrepareLease(ctx context.Context, runtimeID, taskID sreturn c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/tasks/%s/prepare-lease", runtimeID, taskID), map[string]any{}, nil)}+type TaskSupplement struct {+ CommentID string `json:"comment_id"`+ AuthorName string `json:"author_name"`+ Content string `json:"content"`+}++func (c *Client) ClaimTaskSupplement(ctx context.Context, taskID string) (*TaskSupplement, error) {+ var supplement TaskSupplement+ if err := c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/supplements/claim", taskID), map[string]any{}, &supplement); err != nil {+ return nil, err+ }+ if supplement.CommentID == "" {+ return nil, nil+ }+ return &supplement, nil+}++func (c *Client) AckTaskSupplement(ctx context.Context, taskID, commentID string, delivered bool, errText string) error {+ return c.postJSONWithRetry(ctx,+ fmt.Sprintf("/api/daemon/tasks/%s/supplements/%s/ack", taskID, commentID),+ map[string]any{"delivered": delivered, "error": errText}, nil,+ []time.Duration{0, 100 * time.Millisecond, 300 * time.Millisecond})+}+// startTaskRetrySchedule allows two short reconnects without the terminal// callbacks' 124s backoff. The whole start has a 30s budget (not 3 x the HTTP// client's 30s timeout). Preparation keeps renewing its 45s lease every 15s@@ -442,30 +468,58 @@ func (c *Client) ExtendTaskPrepareLease(ctx context.Context, runtimeID, taskID s// fresh claims, and cannot reuse this acknowledgement.var startTaskRetrySchedule = []time.Duration{500 * time.Millisecond, 2 * time.Second}-const startTaskTimeout = 30 * time.Second+const (+ startTaskTimeout = 30 * time.Second+ // Start responses can include an issue snapshot alongside the capability.+ maxStartTaskResponseBytes = 1 << 20+)var errStartClaimRejected = errors.New("task start claim rejected")-func (c *Client) StartTask(ctx context.Context, task Task) error {+func (c *Client) StartTask(ctx context.Context, task Task, capabilities ...string) (bool, error) {+ var negotiated bool+ var decodeResponse responseDecoder = func(r io.Reader) error {+ data, err := io.ReadAll(io.LimitReader(r, maxStartTaskResponseBytes+1))+ if err != nil {+ return err+ }+ if len(data) > maxStartTaskResponseBytes {+ return fmt.Errorf("%w: task start exceeds %d bytes", errInvalidResponseBody, maxStartTaskResponseBytes)+ }+ var response struct {+ SupplementCapability string `json:"supplement_capability"`+ }+ // Empty acknowledgements start the task without negotiating supplements.+ // Invalid JSON fails without retrying; transport read failures can retry.+ if len(data) != 0 {+ if err := json.Unmarshal(data, &response); err != nil {+ return fmt.Errorf("%w: task start: %w", errInvalidResponseBody, err)+ }+ }+ negotiated = response.SupplementCapability == protocol.DaemonCapabilityTaskSupplementV1+ return nil+ }path := fmt.Sprintf("/api/daemon/tasks/%s/start", task.ID)if !task.StartClaimSupported {// Old servers have no safe replay contract. Preserve one attempt.- return c.postJSON(ctx, path, map[string]any{}, nil)+ err := c.postJSON(ctx, path, map[string]any{"capabilities": capabilities}, decodeResponse)+ return err == nil && negotiated, err}if task.RuntimeID == "" || task.DispatchedAt == "" {- return fmt.Errorf("start task: claim is missing runtime_id or dispatched_at")+ return false, fmt.Errorf("start task: claim is missing runtime_id or dispatched_at")}ctx, cancel := context.WithTimeout(ctx, startTaskTimeout)defer cancel()err := c.postJSONWithRetry(ctx, path, map[string]any{"runtime_id": task.RuntimeID,+ "capabilities": capabilities,"dispatched_at": task.DispatchedAt,- }, nil, startTaskRetrySchedule)+ }, decodeResponse, startTaskRetrySchedule)var reqErr *requestErrorif errors.As(err, &reqErr) && reqErr.StatusCode == http.StatusConflict {- return fmt.Errorf("%w: %w", errStartClaimRejected, err)+ return false, fmt.Errorf("%w: %w", errStartClaimRejected, err)}- return err+ return err == nil && negotiated, err}// MarkTaskWaitingLocalDirectory parks a freshly-dispatched task in the@@ -1128,15 +1182,15 @@ var retrySleep = func(ctx context.Context, d time.Duration) error {// resolve on retry: connection / TLS / I/O errors at the transport layer// (including client timeouts surfacing as context.DeadlineExceeded inside// http.Client.Do), 5xx server responses, and 408/429 rate-limit-style 4xx-// codes. Other 4xx codes are treated as permanent — retrying a 400 (bad-// body) or 404 (task not found) only burns time.+// codes. Response validation errors marked with errInvalidResponseBody and+// other 4xx codes are permanent.//// The caller is responsible for separately bailing on parent-context// cancellation; this predicate cannot distinguish "the daemon is shutting// down" from "the HTTP client timed out a single attempt" because both// reach here as context errors wrapped by net/http.func isTransientError(err error) bool {- if err == nil {+ if err == nil || errors.Is(err, errInvalidResponseBody) {return false}var reqErr *requestError@@ -1204,9 +1258,14 @@ func (c *Client) postJSON(ctx context.Context, path string, reqBody any, respBodreturn c.postJSONVia(ctx, c.client, path, reqBody, respBody)}+// responseDecoder customizes successful-response decoding inside each attempt.+type responseDecoder func(io.Reader) error+// postJSONVia is postJSON over an explicit http.Client. Callers pick the client// to control the timeout regime: c.client (fixed 30s) for control-plane calls,// c.bundleClient (deadline from ctx) for large skill-bundle downloads.+// respBody can be a JSON destination or a responseDecoder that decodes a+// successful response inside each attempt, before retry decisions are made.func (c *Client) postJSONVia(ctx context.Context, httpClient *http.Client, path string, reqBody any, respBody any) error {return c.postJSONViaObserved(ctx, httpClient, path, reqBody, respBody, nil)}@@ -1250,6 +1309,9 @@ func (c *Client) postJSONViaObserved(ctx context.Context, httpClient *http.Clienio.Copy(io.Discard, respReader)return nil}+ if decode, ok := respBody.(responseDecoder); ok {+ return decode(respReader)+ }return json.NewDecoder(respReader).Decode(respBody)}diff --git a/server/internal/daemon/client_start_test.go b/server/internal/daemon/client_start_test.goindex 66e147220c..af00c9ed0f 100644--- a/server/internal/daemon/client_start_test.go+++ b/server/internal/daemon/client_start_test.go@@ -18,6 +18,22 @@ type startTaskTransport func(*http.Request) (*http.Response, error)func (f startTaskTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }+func TestStartTaskBoundsResponseRead(t *testing.T) {+ const responseSize = 2 << 20+ body := strings.NewReader(strings.Repeat(" ", responseSize))+ client := NewClient("https://daemon.test")+ client.client.Transport = startTaskTransport(func(*http.Request) (*http.Response, error) {+ return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(body)}, nil+ })+ _, err := client.StartTask(context.Background(), Task{ID: "task-1"})+ if !errors.Is(err, errInvalidResponseBody) || !strings.Contains(err.Error(), "exceeds") {+ t.Fatalf("StartTask error = %v, want response size error", err)+ }+ if read := responseSize - body.Len(); read > (1<<20)+1 {+ t.Fatalf("read %d bytes before rejecting oversized response", read)+ }+}+func TestStartTaskRetries(t *testing.T) {defer noSleepRetry(t)()for _, tc := range []struct {@@ -58,7 +74,7 @@ func TestStartTaskRetries(t *testing.T) {}return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader("{}")), Header: make(http.Header)}, nil})- err := client.StartTask(context.Background(), startTestClaim())+ _, err := client.StartTask(context.Background(), startTestClaim())if tc.status == http.StatusConflict && !errors.Is(err, errStartClaimRejected) {t.Fatalf("lost claim rejection: %v", err)}@@ -84,7 +100,7 @@ func TestStartTaskCancellationStopsRetry(t *testing.T) {calls++return nil, io.ErrUnexpectedEOF})- err := client.StartTask(ctx, startTestClaim())+ _, err := client.StartTask(ctx, startTestClaim())if err == nil || !errors.Is(ctx.Err(), context.Canceled) || calls != 1 {t.Fatalf("error = %v, context = %v, calls = %d; want cancelled backoff and one attempt", err, ctx.Err(), calls)}@@ -126,14 +142,14 @@ func TestStartTaskLegacyServerDoesNotRetry(t *testing.T) {client.client.Transport = startTaskTransport(func(r *http.Request) (*http.Response, error) {calls++body, _ := io.ReadAll(r.Body)- if string(body) != "{}" {+ if string(body) != `{"capabilities":null}` {t.Fatalf("legacy body: %s", body)}return nil, io.ErrUnexpectedEOF})claim := startTestClaim()claim.StartClaimSupported = false- if err := client.StartTask(context.Background(), claim); err == nil || calls != 1 {+ if _, err := client.StartTask(context.Background(), claim); err == nil || calls != 1 {t.Fatalf("legacy start: err=%v calls=%d", err, calls)}}@@ -152,12 +168,12 @@ func TestStartTaskBudgetAndMissingClaim(t *testing.T) {})claim := startTestClaim()claim.DispatchedAt = ""- if err := client.StartTask(context.Background(), claim); err == nil || calls != 0 {+ if _, err := client.StartTask(context.Background(), claim); err == nil || calls != 0 {t.Fatalf("missing claim: %v, calls=%d", err, calls)}ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)defer cancel()- if err := client.StartTask(ctx, startTestClaim()); err == nil || calls != 1 {+ if _, err := client.StartTask(ctx, startTestClaim()); err == nil || calls != 1 {t.Fatalf("deadline: %v, calls=%d", err, calls)}}diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.goindex d6058fcdfc..bab777aafb 100644--- a/server/internal/daemon/client_test.go+++ b/server/internal/daemon/client_test.go@@ -100,6 +100,72 @@ func TestClient_IdentityHeaders_GetJSON(t *testing.T) {}}+func TestStartTaskCapabilityNegotiationMixedVersions(t *testing.T) {+ defer noSleepRetry(t)()+ const prefix = `{"supplement_capability":"task-supplement-v1","issue":{"description":"`+ const suffix = `"}}`+ responseAtLimit := prefix + strings.Repeat("x", (1<<20)-len(prefix)-len(suffix)) + suffix+ for _, tc := range []struct {+ name string+ response string+ contentLength string+ negotiated bool+ wantError bool+ retry bool+ }{+ {name: "empty response", response: ""},+ {name: "truncated HTTP body", contentLength: "8", wantError: true, retry: true},+ {name: "truncated response", response: `{"supplement_capability":`, wantError: true},+ {name: "trailing garbage", response: `{"supplement_capability":"task-supplement-v1"}garbage`, wantError: true},+ {name: "HTML response", response: `<html>Proxy error</html>`, wantError: true},+ {name: "response at size limit", response: responseAtLimit, negotiated: true},+ {name: "response exceeds size limit", response: responseAtLimit + " ", wantError: true},+ {name: "old server task response", response: `{"id":"task-1","status":"running"}`, negotiated: false},+ {name: "new server explicit capability", response: `{"supplement_capability":"task-supplement-v1"}`, negotiated: true},+ } {+ for _, mode := range []string{"legacy", "claim-fenced"} {+ t.Run(tc.name+"/"+mode, func(t *testing.T) {+ var calls atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls.Add(1)+ var body struct {+ Capabilities []string `json:"capabilities"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("decode start request: %v", err)+ }+ if len(body.Capabilities) != 1 || body.Capabilities[0] != protocol.DaemonCapabilityTaskSupplementV1 {+ t.Errorf("capabilities = %#v", body.Capabilities)+ }+ w.Header().Set("Content-Type", "application/json")+ if tc.contentLength != "" {+ w.Header().Set("Content-Length", tc.contentLength)+ }+ _, _ = w.Write([]byte(tc.response))+ }))+ defer srv.Close()++ task := startTestClaim()+ task.StartClaimSupported = mode == "claim-fenced"+ got, err := NewClient(srv.URL).StartTask(context.Background(), task, protocol.DaemonCapabilityTaskSupplementV1)+ if (err != nil) != tc.wantError {+ t.Errorf("StartTask: %v", err)+ }+ if got != tc.negotiated {+ t.Errorf("negotiated = %v, want %v", got, tc.negotiated)+ }+ wantCalls := 1+ if tc.retry && task.StartClaimSupported {+ wantCalls += len(startTaskRetrySchedule)+ }+ if got := int(calls.Load()); got != wantCalls {+ t.Errorf("requests = %d, want %d", got, wantCalls)+ }+ })+ }+ }+}+func TestClient_ResolveRemoteMCPCredentialUsesExplicitDaemonToken(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if got := r.Header.Get("Authorization"); got != "Bearer mdt_task_broker" {diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex afc31651e8..00785e21e7 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -32,6 +32,7 @@ import ("github.com/multica-ai/multica/server/internal/daemon/repocache""github.com/multica-ai/multica/server/internal/selfexec""github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/protocol""github.com/multica-ai/multica/server/pkg/redact""github.com/multica-ai/multica/server/pkg/skillbundle""github.com/multica-ai/multica/server/pkg/taskfailure"@@ -666,6 +667,12 @@ type Daemon struct {// taskSlotWait is the brief semaphore wait before the capacity backoff.// New sets the production default; tests shorten it to reach that branch.taskSlotWait time.Duration+ // taskSupplementSignals carries content-free server hints to the exact+ // negotiated task. The two intervals are production defaults in New and+ // independently overridable by focused tests.+ taskSupplementSignals taskSupplementSignals+ taskSupplementPollInterval time.Duration+ taskSupplementReadyInterval time.Duration// envRootBusyWait is how long a task that is entitled to a prior env root// waits for the previous run to let go of it before giving up and preparing// a fresh one. New() sets it; the zero value means "do not wait", which is@@ -703,42 +710,44 @@ func New(cfg Config, logger *slog.Logger) *Daemon {// server can split logs/metrics by client version (parallel to the CLI).client.SetVersion(cfg.CLIVersion)d := &Daemon{- cfg: cfg,- client: client,- repoCache: repocache.New(cacheRoot, logger),- skillCache: NewSkillBundleCache(skillCacheRoot),- logger: logger,- terminalReports: newTerminalReportStore(cfg),- terminalReportWakeup: make(chan struct{}, 1),- terminalReportNow: time.Now,- terminalReportFlight: make(map[string]struct{}),- workspaces: make(map[string]*workspaceState),- runtimeIndex: make(map[string]Runtime),- profileLaunchSpecs: make(map[string]profileLaunchSpec),- runtimeSet: newRuntimeSetWatcher(),- agentDiscoveryKick: make(chan struct{}, 1),- agentVersions: make(map[string]string),- skippedAgents: make(map[string]string),- resolvedPaths: make(map[string]healedAgent),- wsHBLastAck: make(map[string]time.Time),- activeEnvRoots: make(map[string]int),- deletingEnvRoots: make(map[string]bool),- activeStores: make(map[string]int),- deletingStores: make(map[string]bool),- localPathLocks: NewLocalPathLocker(),- runtimeGoneInflight: make(map[string]struct{}),- pendingWorkInflight: make(map[string]struct{}),- pendingWorkLastRun: make(map[string]time.Time),- reregisterNextAttempt: make(map[string]time.Time),- reregisterLastCompletedAt: make(map[string]time.Time),- cancelPollInterval: 5 * time.Second,- taskSlotWait: taskSlotWaitTimeout,- envRootBusyWait: 15 * time.Second,- taskPrepareTimeout: defaultTaskPrepareTimeout,- prepareLeaseRefresh: taskPrepareLeaseRefresh,- reconcile: newReconcileBroadcaster(),- workspaceChanges: newWorkspaceChangeSignal(),- wsRPC: newWSRPCClient(wsRPCResponseGrace),+ cfg: cfg,+ client: client,+ repoCache: repocache.New(cacheRoot, logger),+ skillCache: NewSkillBundleCache(skillCacheRoot),+ logger: logger,+ terminalReports: newTerminalReportStore(cfg),+ terminalReportWakeup: make(chan struct{}, 1),+ terminalReportNow: time.Now,+ terminalReportFlight: make(map[string]struct{}),+ workspaces: make(map[string]*workspaceState),+ runtimeIndex: make(map[string]Runtime),+ profileLaunchSpecs: make(map[string]profileLaunchSpec),+ runtimeSet: newRuntimeSetWatcher(),+ agentDiscoveryKick: make(chan struct{}, 1),+ agentVersions: make(map[string]string),+ skippedAgents: make(map[string]string),+ resolvedPaths: make(map[string]healedAgent),+ wsHBLastAck: make(map[string]time.Time),+ activeEnvRoots: make(map[string]int),+ deletingEnvRoots: make(map[string]bool),+ activeStores: make(map[string]int),+ deletingStores: make(map[string]bool),+ localPathLocks: NewLocalPathLocker(),+ runtimeGoneInflight: make(map[string]struct{}),+ pendingWorkInflight: make(map[string]struct{}),+ pendingWorkLastRun: make(map[string]time.Time),+ reregisterNextAttempt: make(map[string]time.Time),+ reregisterLastCompletedAt: make(map[string]time.Time),+ cancelPollInterval: 5 * time.Second,+ taskSlotWait: taskSlotWaitTimeout,+ taskSupplementPollInterval: defaultTaskSupplementPollInterval,+ taskSupplementReadyInterval: defaultTaskSupplementReadyInterval,+ envRootBusyWait: 15 * time.Second,+ taskPrepareTimeout: defaultTaskPrepareTimeout,+ prepareLeaseRefresh: taskPrepareLeaseRefresh,+ reconcile: newReconcileBroadcaster(),+ workspaceChanges: newWorkspaceChangeSignal(),+ wsRPC: newWSRPCClient(wsRPCResponseGrace),}d.activeEnvRootsCond = sync.NewCond(&d.activeEnvRootsMu)d.activeStoresCond = sync.NewCond(&d.activeStoresMu)@@ -8376,10 +8385,23 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// other errors use its existing FailTask + taskfailure.Classify path with the same// "start task failed: <…>" string and the same failure_reason// taxonomy as before — see MUL-2946 for the classifier contract.- if err := d.client.StartTask(prepareCtx, task); err != nil {+ var taskCapabilities []string+ if agent.SupportsTaskSupplement(provider, resolvedVersion) && task.IssueID != "" {+ taskCapabilities = append(taskCapabilities, protocol.DaemonCapabilityTaskSupplementV1)+ }+ taskSupplementNegotiated, err := d.client.StartTask(prepareCtx, task, taskCapabilities...)+ if err != nil {stopPrepareLease()return TaskResult{}, fmt.Errorf("start task failed: %w", err)}+ if taskSupplementNegotiated {+ // Register before provider launch so a hint cannot arrive in the gap+ // between the committed server transition and turn/started. The row is+ // durable, so a coalesced hint is sufficient; the five-second fallback+ // covers a notification sent before this start response arrived.+ _, unsubscribeSupplements := d.taskSupplementSignals.subscribe(task.ID)+ defer unsubscribeSupplements()+ }stopPrepareLease()prepareComplete = truecancelPrepare()@@ -8637,6 +8659,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iidleWatchdogTimeout = d.cfg.OpenCodeIdleWatchdog}execOpts := agent.ExecOptions{+ EnableTaskSupplement: taskSupplementNegotiated,Cwd: env.WorkDir,Model: model,ThreadName: deriveTaskThreadName(task),@@ -9279,6 +9302,23 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, prophaseRecorder.Mark(taskPhaseRuntimeStarted)taskLog.Debug("backend started, draining messages")+ // Only negotiated sessions may claim additions. Stop and join delivery+ // before the caller reports the task's terminal state to the server.+ if opts.EnableTaskSupplement && session.Supplement != nil && session.SupplementReady != nil {+ supplementCtx, cancelSupplements := context.WithCancel(agentCtx)+ supplementsDone := make(chan struct{})+ wakeup, unsubscribe := d.taskSupplementSignals.subscribe(taskID)+ go func() {+ defer unsubscribe()+ defer close(supplementsDone)+ d.runTaskSupplementLoop(supplementCtx, session, taskID, wakeup, taskLog)+ }()+ defer func() {+ cancelSupplements()+ <-supplementsDone+ }()+ }+// 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 scannerdiff --git a/server/internal/daemon/leader_workdir_reuse_test.go b/server/internal/daemon/leader_workdir_reuse_test.goindex 7c9fa7b70a..85137fe26e 100644--- a/server/internal/daemon/leader_workdir_reuse_test.go+++ b/server/internal/daemon/leader_workdir_reuse_test.go@@ -368,7 +368,7 @@ printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_idwriteTestExecutable(t, fakeBin, []byte(script))srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))logger := slog.New(slog.NewTextHandler(io.Discard, nil))diff --git a/server/internal/daemon/pi_busy_retry_unix_test.go b/server/internal/daemon/pi_busy_retry_unix_test.goindex 7a9634ed54..f663455732 100644--- a/server/internal/daemon/pi_busy_retry_unix_test.go+++ b/server/internal/daemon/pi_busy_retry_unix_test.go@@ -51,7 +51,7 @@ printf '%s\n' '{"type":"turn_end","message":{"role":"assistant","model":"test","}srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))defer srv.Close()diff --git a/server/internal/daemon/task_supplement.go b/server/internal/daemon/task_supplement.gonew file mode 100644index 0000000000..47d96b1445--- /dev/null+++ b/server/internal/daemon/task_supplement.go@@ -0,0 +1,183 @@+package daemon++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "strconv"+ "strings"+ "sync"+ "time"++ "github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++const (+ defaultTaskSupplementPollInterval = 5 * time.Second+ defaultTaskSupplementReadyInterval = 50 * time.Millisecond+ taskSupplementAckTimeout = 5 * time.Second+)++// taskSupplementSignals routes best-effort WebSocket hints to one exact+// in-flight task. A one-slot channel coalesces duplicate hints. Creating the+// slot before provider launch preserves a hint sent after the server marks the+// task running but before the provider confirms an active turn.+type taskSupplementSignals struct {+ mu sync.Mutex+ byTask map[string]chan struct{}+}++func (s *taskSupplementSignals) subscribe(taskID string) (<-chan struct{}, func()) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.byTask == nil {+ s.byTask = make(map[string]chan struct{})+ }+ ch := s.byTask[taskID]+ if ch == nil {+ ch = make(chan struct{}, 1)+ s.byTask[taskID] = ch+ }+ return ch, func() {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.byTask[taskID] == ch {+ delete(s.byTask, taskID)+ }+ }+}++func (s *taskSupplementSignals) notify(taskID string) {+ s.mu.Lock()+ defer s.mu.Unlock()+ // A nil channel ignores stale or unnegotiated hints without allocating state.+ select {+ case s.byTask[taskID] <- struct{}{}:+ default:+ }+}++func (d *Daemon) effectiveTaskSupplementPollInterval() time.Duration {+ if d.taskSupplementPollInterval > 0 {+ return d.taskSupplementPollInterval+ }+ return defaultTaskSupplementPollInterval+}++func (d *Daemon) effectiveTaskSupplementReadyInterval() time.Duration {+ if d.taskSupplementReadyInterval > 0 {+ return d.taskSupplementReadyInterval+ }+ return defaultTaskSupplementReadyInterval+}++func waitTaskSupplement(ctx context.Context, wakeup <-chan struct{}, delay time.Duration) bool {+ timer := time.NewTimer(delay)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ return false+ case <-wakeup:+ return true+ case <-timer.C:+ return true+ }+}++func formatTaskSupplementInstruction(authorName, content string) string {+ authorName = strings.Join(strings.Fields(authorName), " ")+ if authorName == "" {+ authorName = "a user"+ }+ return fmt.Sprintf(`[ADDITIONAL GUIDANCE] Human %s added guidance while you were working.++Treat this as additional guidance for the same active task, not as a replacement:+- Preserve and complete the original objective.+- Incorporate this guidance 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 message:+%s`, strconv.Quote(authorName), content)+}++func taskSupplementEndpointUnsupported(err error) bool {+ var reqErr *requestError+ return errors.As(err, &reqErr) && (reqErr.StatusCode == http.StatusNotFound || reqErr.StatusCode == http.StatusPreconditionFailed)+}++func taskSupplementFailureReason(ctx context.Context, err error) string {+ if err == nil {+ return ""+ }+ if errors.Is(err, context.DeadlineExceeded) {+ return protocol.TaskSupplementFailureTimeout+ }+ if ctx.Err() != nil || errors.Is(err, context.Canceled) {+ return protocol.TaskSupplementFailureTurnEnded+ }+ if strings.Contains(strings.ToLower(err.Error()), "turn") && strings.Contains(strings.ToLower(err.Error()), "not started") {+ return protocol.TaskSupplementFailureTurnNotStarted+ }+ return protocol.TaskSupplementFailureProviderRejected+}++// runTaskSupplementLoop serially claims and acknowledges durable additions for+// one negotiated run. It performs no HTTP request until the provider confirms a live+// turn, wakes immediately on a content-free WebSocket hint, and otherwise uses+// the same five-second cadence as task cancellation polling.+func (d *Daemon) runTaskSupplementLoop(ctx context.Context, session *agent.Session, taskID string, wakeup <-chan struct{}, taskLog *slog.Logger) {+ if session == nil || session.Supplement == nil || session.SupplementReady == nil {+ return+ }+ for {+ if ctx.Err() != nil {+ return+ }+ if !session.SupplementReady() {+ if !waitTaskSupplement(ctx, wakeup, d.effectiveTaskSupplementReadyInterval()) {+ return+ }+ continue+ }++ claimCtx, cancelClaim := context.WithTimeout(ctx, 3*time.Second)+ supplement, claimErr := d.client.ClaimTaskSupplement(claimCtx, taskID)+ cancelClaim()+ if claimErr != nil || supplement == nil {+ if taskSupplementEndpointUnsupported(claimErr) {+ return+ }+ if claimErr != nil {+ taskLog.Debug("additional message claim failed", "error", claimErr)+ }+ if !waitTaskSupplement(ctx, wakeup, d.effectiveTaskSupplementPollInterval()) {+ return+ }+ continue+ }++ // The adapter owns transport deadlines. Hook-based providers wait for a+ // safe boundary, which can follow a long-running tool; run cancellation+ // still aborts that wait and prevents late delivery.+ injectErr := session.Supplement(ctx, formatTaskSupplementInstruction(supplement.AuthorName, supplement.Content))+ reason := taskSupplementFailureReason(ctx, injectErr)+ if injectErr != nil {+ // Raw provider/Go diagnostics remain local. Workspace-visible state is+ // restricted to the stable reason code sent below.+ taskLog.Warn("additional message injection failed", "comment_id", supplement.CommentID, "reason", reason, "error", injectErr)+ }++ ackCtx, cancelAck := context.WithTimeout(context.WithoutCancel(ctx), taskSupplementAckTimeout)+ ackErr := d.client.AckTaskSupplement(ackCtx, taskID, supplement.CommentID, injectErr == nil, reason)+ cancelAck()+ if ackErr != nil {+ taskLog.Warn("additional message acknowledgement failed", "comment_id", supplement.CommentID, "error", ackErr)+ }+ // Do not sleep after a claim: drain already-ordered pending rows one at a+ // time. When empty, the branch above returns to the bounded wait.+ }+}diff --git a/server/internal/daemon/task_supplement_test.go b/server/internal/daemon/task_supplement_test.gonew file mode 100644index 0000000000..d4278e7002--- /dev/null+++ b/server/internal/daemon/task_supplement_test.go@@ -0,0 +1,175 @@+package daemon++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func taskSupplementTestDaemon(t *testing.T, handler http.HandlerFunc) *Daemon {+ t.Helper()+ server := httptest.NewServer(handler)+ t.Cleanup(server.Close)+ return &Daemon{+ client: NewClient(server.URL),+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ taskSupplementPollInterval: 10 * time.Millisecond,+ taskSupplementReadyInterval: 5 * time.Millisecond,+ }+}++func TestTaskSupplementLoopWaitsForTurnReadyBeforeClaim(t *testing.T) {+ var claims atomic.Int32+ d := taskSupplementTestDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ claims.Add(1)+ w.WriteHeader(http.StatusNotFound)+ })+ var ready atomic.Bool+ session := &agent.Session{+ SupplementReady: ready.Load,+ Supplement: func(context.Context, string) error { return nil },+ }+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)+ defer cancel()+ wakeup, unsubscribe := d.taskSupplementSignals.subscribe("task-ready")+ defer unsubscribe()+ done := make(chan struct{})+ go func() {+ defer close(done)+ d.runTaskSupplementLoop(ctx, session, "task-ready", wakeup, d.logger)+ }()+ time.Sleep(30 * time.Millisecond)+ if got := claims.Load(); got != 0 {+ t.Fatalf("claims before turn ready = %d, want 0", got)+ }+ ready.Store(true)+ d.taskSupplementSignals.notify("task-ready")+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("loop did not stop after old-server 404")+ }+ if got := claims.Load(); got != 1 {+ t.Fatalf("claims after turn ready = %d, want 1", got)+ }+}++func TestTaskSupplementLoopAcknowledgesBeforeTurnEnds(t *testing.T) {+ for _, tc := range []struct {+ name string+ err error+ reason string+ }{+ {name: "delivered"},+ {name: "provider timeout", err: context.DeadlineExceeded, reason: protocol.TaskSupplementFailureTimeout},+ } {+ t.Run(tc.name, func(t *testing.T) {+ var claims atomic.Int32+ ackSeen := make(chan struct{}, 1)+ d := taskSupplementTestDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/supplements/claim"):+ if claims.Add(1) == 1 {+ _ = json.NewEncoder(w).Encode(map[string]string{+ "comment_id": "comment-1", "author_name": "Ada", "content": "Create evidence.txt",+ })+ return+ }+ w.WriteHeader(http.StatusPreconditionFailed)+ case strings.HasSuffix(r.URL.Path, "/supplements/comment-1/ack"):+ var body struct {+ Delivered bool `json:"delivered"`+ Error string `json:"error"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Error(err)+ }+ if body.Delivered != (tc.err == nil) || body.Error != tc.reason {+ t.Errorf("ack = %#v, want delivered=%v reason=%q", body, tc.err == nil, tc.reason)+ }+ ackSeen <- struct{}{}+ default:+ t.Errorf("unexpected request %s", r.URL.Path)+ }+ })+ injections := 0+ session := &agent.Session{+ SupplementReady: func() bool { return true },+ Supplement: func(_ context.Context, instruction string) error {+ injections+++ if !strings.Contains(instruction, "Preserve and complete the original objective") || !strings.Contains(instruction, "Create evidence.txt") {+ t.Errorf("injected instruction lost framing or content: %q", instruction)+ }+ return tc.err+ },+ }+ wakeup, unsubscribe := d.taskSupplementSignals.subscribe("task-ack")+ defer unsubscribe()+ d.runTaskSupplementLoop(t.Context(), session, "task-ack", wakeup, d.logger)+ if injections != 1 {+ t.Fatalf("injections = %d, want 1", injections)+ }+ select {+ case <-ackSeen:+ default:+ t.Fatal("loop returned before delivery acknowledgement")+ }+ })+ }+}++type supplementGateBackend struct {+ supplementCalls atomic.Int32+ enabled bool+}++func (b *supplementGateBackend) Execute(_ context.Context, _ string, opts agent.ExecOptions) (*agent.Session, error) {+ b.enabled = opts.EnableTaskSupplement+ messages := make(chan agent.Message)+ close(messages)+ results := make(chan agent.Result, 1)+ results <- agent.Result{Status: "completed", Output: "done"}+ return &agent.Session{+ Messages: messages,+ Result: results,+ SupplementReady: func() bool { return true },+ Supplement: func(context.Context, string) error {+ b.supplementCalls.Add(1)+ return nil+ },+ }, nil+}++func TestExecuteAndDrainSupplementNegotiation(t *testing.T) {+ for _, negotiated := range []bool{false, true} {+ t.Run(fmt.Sprintf("negotiated=%v", negotiated), func(t *testing.T) {+ var requests atomic.Int32+ d := taskSupplementTestDaemon(t, func(w http.ResponseWriter, _ *http.Request) {+ requests.Add(1)+ w.WriteHeader(http.StatusNotFound)+ })+ backend := &supplementGateBackend{}+ opts := agent.ExecOptions{EnableTaskSupplement: negotiated}+ if _, _, err := d.executeAndDrain(t.Context(), backend, "original", opts, d.logger, "task", "", new(atomic.Int32)); err != nil {+ t.Fatal(err)+ }+ if backend.enabled != negotiated {+ t.Fatalf("provider hooks enabled=%v, want %v", backend.enabled, negotiated)+ }+ if !negotiated && (requests.Load() != 0 || backend.supplementCalls.Load() != 0) {+ t.Fatalf("unnegotiated run made HTTP requests=%d supplement calls=%d", requests.Load(), backend.supplementCalls.Load())+ }+ })+ }+}diff --git a/server/internal/daemon/task_usage_test.go b/server/internal/daemon/task_usage_test.goindex 29439249c1..8b3ecfb3c6 100644--- a/server/internal/daemon/task_usage_test.go+++ b/server/internal/daemon/task_usage_test.go@@ -54,7 +54,7 @@ func TestRunTaskPreservesProviderCostWithoutTokens(t *testing.T) {script := strings.NewReplacer("FIXTURE_INPUT", fmt.Sprint(tc.input), "FIXTURE_COST", fmt.Sprint(tc.cost)).Replace(taskUsageGrokFixture)writeTestExecutable(t, fake, []byte(script))srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))defer srv.Close()d := &Daemon{diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.goindex cfe15dddce..fffb88614e 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -407,6 +407,17 @@ func (d *Daemon) readTaskWakeupMessagesForConnection(conn *websocket.Conn, taskWd.logger.Debug("task wakeup received", "runtime_id", payload.RuntimeID, "task_id", payload.TaskID)}signalTaskWakeup(taskWakeups, payload.RuntimeID)+ case protocol.EventDaemonTaskSupplementAvailable:+ var payload protocol.TaskAvailablePayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {+ d.logger.Debug("task supplement websocket invalid payload", "error", err)+ continue+ }+ if payload.TaskID == "" {+ d.logger.Debug("task supplement websocket missing task_id")+ continue+ }+ d.taskSupplementSignals.notify(payload.TaskID)case protocol.EventDaemonRuntimeProfilesChanged:var payload protocol.RuntimeProfilesChangedPayloadif err := json.Unmarshal(msg.Payload, &payload); err != nil {diff --git a/server/internal/daemon/wakeup_test.go b/server/internal/daemon/wakeup_test.goindex 3dde55ff22..afad87faa7 100644--- a/server/internal/daemon/wakeup_test.go+++ b/server/internal/daemon/wakeup_test.go@@ -124,6 +124,48 @@ func TestRunTaskWakeupConnectionSignalsDisconnect(t *testing.T) {}}+func TestRunTaskWakeupConnectionRoutesTaskSupplementHint(t *testing.T) {+ upgrader := websocket.Upgrader{}+ sendHint := make(chan struct{})+ serverDone := make(chan struct{})+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ conn, err := upgrader.Upgrade(w, r, nil)+ if err != nil {+ return+ }+ defer conn.Close()+ <-sendHint+ payload, _ := json.Marshal(protocol.TaskAvailablePayload{RuntimeID: "runtime-1", TaskID: "task-1"})+ _ = conn.WriteJSON(protocol.Message{Type: protocol.EventDaemonTaskSupplementAvailable, Payload: payload})+ <-serverDone+ }))+ defer srv.Close()++ d := New(Config{ServerBaseURL: srv.URL, HeartbeatInterval: time.Hour}, slog.Default())+ supplementWakeup, unsubscribe := d.taskSupplementSignals.subscribe("task-1")+ defer unsubscribe()+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ errCh := make(chan error, 1)+ go func() {+ _, err := d.runTaskWakeupConnection(ctx, []string{"runtime-1"}, make(chan taskWakeup, 2), make(chan struct{}))+ errCh <- err+ }()+ close(sendHint)+ select {+ case <-supplementWakeup:+ case <-time.After(time.Second):+ t.Fatal("task supplement hint did not wake its exact task")+ }+ close(serverDone)+ cancel()+ select {+ case <-errCh:+ case <-time.After(time.Second):+ t.Fatal("websocket reader did not release after cancellation")+ }+}+// TestWSHeartbeatFreshnessSuppressesHTTP pins the WS-vs-HTTP coordination:// once a runtime acked over WS within the freshness window the HTTP// heartbeat loop must skip it to avoid duplicate DB writes.diff --git a/server/internal/daemon/workdir_race_test.go b/server/internal/daemon/workdir_race_test.goindex a9c3914686..2d44f85803 100644--- a/server/internal/daemon/workdir_race_test.go+++ b/server/internal/daemon/workdir_race_test.go@@ -44,7 +44,7 @@ func TestHandleTask_DoesNotCallStartTaskItself(t *testing.T) {case strings.HasSuffix(r.URL.Path, "/start"):startCalls.Add(1)}- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))t.Cleanup(srv.Close)@@ -113,7 +113,7 @@ func TestRunTask_StartTaskCalledAfterWorkdirOnDisk(t *testing.T) {envRootOnDisk.Store(true)}}- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))t.Cleanup(srv.Close)@@ -189,7 +189,7 @@ printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id}srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))t.Cleanup(srv.Close)@@ -423,7 +423,7 @@ printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_idwriteTestExecutable(t, fakeBin, []byte(script))srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))t.Cleanup(srv.Close)@@ -521,7 +521,7 @@ printf 'ran\n' > "$CAPTURE_FILE"writeTestExecutable(t, fakeBin, []byte(script))srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))t.Cleanup(srv.Close)@@ -589,7 +589,7 @@ func TestRunTask_ExtendsPrepareLeaseDuringStartTask(t *testing.T) {leaseDuringStart.Store(true)closeLeaseOnce.Do(func() { close(leaseSeenDuringStart) })}- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))case strings.HasSuffix(r.URL.Path, "/start"):attempt := startAttempts.Add(1)startEntered.Store(true)@@ -601,9 +601,9 @@ func TestRunTask_ExtendsPrepareLeaseDuringStartTask(t *testing.T) {w.WriteHeader(http.StatusServiceUnavailable)return}- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))default:- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}}))t.Cleanup(srv.Close)@@ -711,7 +711,7 @@ func prepareTimeoutStopsLeaseDuringBlockedStart(t *testing.T, budget time.Duratiif strings.HasSuffix(r.URL.Path, "/start") {<-releaseStart}- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))defer srv.Close()// LIFO: unblock /start before Close waits for its handler.@@ -838,7 +838,7 @@ func TestHandleTask_KeepsEnvRootActiveAcrossCompletion(t *testing.T) {activeAtComplete.Store(true)}}- w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{}`))}))t.Cleanup(srv.Close)d.client = NewClient(srv.URL)diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.goindex b395378fc5..ce0f332f21 100644--- a/server/internal/daemonws/hub.go+++ b/server/internal/daemonws/hub.go@@ -444,7 +444,14 @@ func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request, identity C// NotifyTaskAvailable sends a best-effort wakeup to daemons watching runtimeID.func (h *Hub) NotifyTaskAvailable(runtimeID, taskID string) {- h.notifyTaskAvailable(runtimeID, taskID, "")+ h.notifyTask(protocol.EventDaemonTaskAvailable, runtimeID, taskID, "")+}++// NotifyTaskSupplementAvailable wakes only the daemon that owns runtimeID;+// the task ID lets that daemon wake the matching in-flight run without polling+// or disturbing the machine-level new-task claim loop.+func (h *Hub) NotifyTaskSupplementAvailable(runtimeID, taskID string) {+ h.notifyTask(protocol.EventDaemonTaskSupplementAvailable, runtimeID, taskID, "")}// NotifyRuntimeProfilesChanged asks connected daemons in workspaceID to pull@@ -475,11 +482,11 @@ func (h *Hub) NotifyRuntimeGone(runtimeID string) {h.notifyRuntimeGone(runtimeID, "")}-func (h *Hub) notifyTaskAvailable(runtimeID, taskID, eventID string) {- if h == nil || runtimeID == "" {+func (h *Hub) notifyTask(eventType, runtimeID, taskID, eventID string) {+ if h == nil || runtimeID == "" || (eventType == protocol.EventDaemonTaskSupplementAvailable && taskID == "") {return}- data, err := taskAvailableFrame(runtimeID, taskID)+ data, err := taskWakeupFrame(eventType, runtimeID, taskID)if err != nil {return}@@ -608,10 +615,10 @@ func (h *Hub) DeliverDaemonRuntime(scopeID string, frame []byte, eventID string)M.WakeupReceivedTotal.Add(1)}switch msg.Type {- case protocol.EventDaemonTaskAvailable:+ case protocol.EventDaemonTaskAvailable, protocol.EventDaemonTaskSupplementAvailable:var payload protocol.TaskAvailablePayload- if err := json.Unmarshal(msg.Payload, &payload); err != nil || payload.RuntimeID == "" {- slog.Debug("daemon websocket relay: invalid task_available payload", "error", err, "scope_id", scopeID, "event_id", eventID)+ if err := json.Unmarshal(msg.Payload, &payload); err != nil || payload.RuntimeID == "" || (msg.Type == protocol.EventDaemonTaskSupplementAvailable && payload.TaskID == "") {+ slog.Debug("daemon websocket relay: invalid task wakeup payload", "type", msg.Type, "error", err, "scope_id", scopeID, "event_id", eventID)M.WakeupDeliveredMiss.Add(1)return}@@ -757,9 +764,9 @@ func (h *Hub) notifyUserFrame(userID string, data []byte, eventID string) (delivreturn delivered, deduped}-func taskAvailableFrame(runtimeID, taskID string) ([]byte, error) {+func taskWakeupFrame(eventType, runtimeID, taskID string) ([]byte, error) {return json.Marshal(protocol.Message{- Type: protocol.EventDaemonTaskAvailable,+ Type: eventType,Payload: mustMarshalRaw(protocol.TaskAvailablePayload{RuntimeID: runtimeID,TaskID: taskID,diff --git a/server/internal/daemonws/hub_test.go b/server/internal/daemonws/hub_test.goindex 00349a8d91..207650b6c7 100644--- a/server/internal/daemonws/hub_test.go+++ b/server/internal/daemonws/hub_test.go@@ -16,54 +16,61 @@ import ()func TestNotifyTaskAvailable(t *testing.T) {- M.Reset()- defer M.Reset()-- hub := NewHub()- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- hub.HandleWebSocket(w, r, ClientIdentity{RuntimeIDs: []string{"runtime-1"}})- }))- defer server.Close()-- wsURL := "ws" + strings.TrimPrefix(server.URL, "http")- conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)- if err != nil {- t.Fatalf("Dial: %v", err)- }- defer conn.Close()-- deadline := time.Now().Add(time.Second)- for hub.RuntimeConnectionCount("runtime-1") == 0 {- if time.Now().After(deadline) {- t.Fatal("runtime connection was not registered")- }- time.Sleep(10 * time.Millisecond)- }-- hub.NotifyTaskAvailable("runtime-1", "task-1")-- if err := conn.SetReadDeadline(time.Now().Add(time.Second)); err != nil {- t.Fatalf("SetReadDeadline: %v", err)- }- _, raw, err := conn.ReadMessage()- if err != nil {- t.Fatalf("ReadMessage: %v", err)- }-- var msg protocol.Message- if err := json.Unmarshal(raw, &msg); err != nil {- t.Fatalf("unmarshal message: %v", err)- }- if msg.Type != protocol.EventDaemonTaskAvailable {- t.Fatalf("message type = %q, want %q", msg.Type, protocol.EventDaemonTaskAvailable)- }-- var payload protocol.TaskAvailablePayload- if err := json.Unmarshal(msg.Payload, &payload); err != nil {- t.Fatalf("unmarshal payload: %v", err)- }- if payload.RuntimeID != "runtime-1" || payload.TaskID != "task-1" {- t.Fatalf("payload = %+v, want runtime/task IDs", payload)+ for eventType, notify := range map[string]func(*Hub, string, string){+ protocol.EventDaemonTaskAvailable: (*Hub).NotifyTaskAvailable,+ protocol.EventDaemonTaskSupplementAvailable: (*Hub).NotifyTaskSupplementAvailable,+ } {+ t.Run(eventType, func(t *testing.T) {+ M.Reset()+ defer M.Reset()++ hub := NewHub()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ hub.HandleWebSocket(w, r, ClientIdentity{RuntimeIDs: []string{"runtime-1"}})+ }))+ defer server.Close()++ wsURL := "ws" + strings.TrimPrefix(server.URL, "http")+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)+ if err != nil {+ t.Fatalf("Dial: %v", err)+ }+ defer conn.Close()++ deadline := time.Now().Add(time.Second)+ for hub.RuntimeConnectionCount("runtime-1") == 0 {+ if time.Now().After(deadline) {+ t.Fatal("runtime connection was not registered")+ }+ time.Sleep(10 * time.Millisecond)+ }++ notify(hub, "runtime-1", "task-1")++ if err := conn.SetReadDeadline(time.Now().Add(time.Second)); err != nil {+ t.Fatalf("SetReadDeadline: %v", err)+ }+ _, raw, err := conn.ReadMessage()+ if err != nil {+ t.Fatalf("ReadMessage: %v", err)+ }++ var msg protocol.Message+ if err := json.Unmarshal(raw, &msg); err != nil {+ t.Fatalf("unmarshal message: %v", err)+ }+ if msg.Type != eventType {+ t.Fatalf("message type = %q, want %q", msg.Type, eventType)+ }++ var payload protocol.TaskAvailablePayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {+ t.Fatalf("unmarshal payload: %v", err)+ }+ if payload.RuntimeID != "runtime-1" || payload.TaskID != "task-1" {+ t.Fatalf("payload = %+v, want runtime/task IDs", payload)+ }+ })}}@@ -229,40 +236,47 @@ func TestNotifyRuntimeProfilesChangedIndexesAllAuthorizedWorkspaces(t *testing.T}func TestRelayNotifierPublishesDaemonRuntimeScope(t *testing.T) {- M.Reset()- defer M.Reset()-- relay := &recordingRelayPublisher{}- notifier := NewRelayNotifier(nil, relay)-- notifier.NotifyTaskAvailable("runtime-1", "task-1")-- if relay.scopeType != realtime.ScopeDaemonRuntime {- t.Fatalf("scopeType = %q, want %q", relay.scopeType, realtime.ScopeDaemonRuntime)- }- if relay.scopeID != "task-1" {- t.Fatalf("scopeID = %q, want task_id shard key", relay.scopeID)- }- if relay.eventID == "" {- t.Fatal("expected event id")- }- if M.WakeupPublishedTotal.Load() != 1 {- t.Fatalf("published metric = %d, want 1", M.WakeupPublishedTotal.Load())- }-- var msg protocol.Message- if err := json.Unmarshal(relay.frame, &msg); err != nil {- t.Fatalf("unmarshal frame: %v", err)- }- if msg.Type != protocol.EventDaemonTaskAvailable {- t.Fatalf("message type = %q, want %q", msg.Type, protocol.EventDaemonTaskAvailable)- }- var payload protocol.TaskAvailablePayload- if err := json.Unmarshal(msg.Payload, &payload); err != nil {- t.Fatalf("unmarshal payload: %v", err)- }- if payload.RuntimeID != "runtime-1" || payload.TaskID != "task-1" {- t.Fatalf("payload = %+v, want runtime/task IDs", payload)+ for eventType, notify := range map[string]func(*RelayNotifier, string, string){+ protocol.EventDaemonTaskAvailable: (*RelayNotifier).NotifyTaskAvailable,+ protocol.EventDaemonTaskSupplementAvailable: (*RelayNotifier).NotifyTaskSupplementAvailable,+ } {+ t.Run(eventType, func(t *testing.T) {+ M.Reset()+ defer M.Reset()++ relay := &recordingRelayPublisher{}+ notifier := NewRelayNotifier(nil, relay)++ notify(notifier, "runtime-1", "task-1")++ if relay.scopeType != realtime.ScopeDaemonRuntime {+ t.Fatalf("scopeType = %q, want %q", relay.scopeType, realtime.ScopeDaemonRuntime)+ }+ if relay.scopeID != "task-1" {+ t.Fatalf("scopeID = %q, want task_id shard key", relay.scopeID)+ }+ if relay.eventID == "" {+ t.Fatal("expected event id")+ }+ if M.WakeupPublishedTotal.Load() != 1 {+ t.Fatalf("published metric = %d, want 1", M.WakeupPublishedTotal.Load())+ }++ var msg protocol.Message+ if err := json.Unmarshal(relay.frame, &msg); err != nil {+ t.Fatalf("unmarshal frame: %v", err)+ }+ if msg.Type != eventType {+ t.Fatalf("message type = %q, want %q", msg.Type, eventType)+ }+ var payload protocol.TaskAvailablePayload+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {+ t.Fatalf("unmarshal payload: %v", err)+ }+ if payload.RuntimeID != "runtime-1" || payload.TaskID != "task-1" {+ t.Fatalf("payload = %+v, want runtime/task IDs", payload)+ }+ })}}@@ -332,38 +346,45 @@ func TestRelayNotifierPublishesWorkspacesChanged(t *testing.T) {}func TestRelayNotifierDedupsLocalRedisLoopback(t *testing.T) {- M.Reset()- defer M.Reset()-- hub := NewHub()- client := attachDaemonTestClient(hub, "runtime-1")- relay := &localFirstDaemonRelayPublisher{t: t, client: client}- notifier := NewRelayNotifier(hub, relay)-- notifier.NotifyTaskAvailable("runtime-1", "task-1")-- if !relay.called {- t.Fatal("expected relay publish to be invoked")- }- if relay.eventID == "" {- t.Fatal("expected event id")- }- if M.WakeupDeliveredHit.Load() != 1 {- t.Fatalf("delivered hit metric = %d, want 1", M.WakeupDeliveredHit.Load())- }-- hub.DeliverDaemonRuntime(relay.scopeID, relay.frame, relay.eventID)-- select {- case duplicate := <-client.send:- t.Fatalf("expected redis loopback to be deduped, got duplicate %s", duplicate)- case <-time.After(20 * time.Millisecond):- }- if M.WakeupDeliveredHit.Load() != 1 {- t.Fatalf("delivered hit metric after loopback = %d, want 1", M.WakeupDeliveredHit.Load())- }- if M.WakeupDeliveredMiss.Load() != 0 {- t.Fatalf("delivered miss metric after dedup = %d, want 0", M.WakeupDeliveredMiss.Load())+ for eventType, notify := range map[string]func(*RelayNotifier, string, string){+ protocol.EventDaemonTaskAvailable: (*RelayNotifier).NotifyTaskAvailable,+ protocol.EventDaemonTaskSupplementAvailable: (*RelayNotifier).NotifyTaskSupplementAvailable,+ } {+ t.Run(eventType, func(t *testing.T) {+ M.Reset()+ defer M.Reset()++ hub := NewHub()+ client := attachDaemonTestClient(hub, "runtime-1")+ relay := &localFirstDaemonRelayPublisher{t: t, client: client}+ notifier := NewRelayNotifier(hub, relay)++ notify(notifier, "runtime-1", "task-1")++ if !relay.called {+ t.Fatal("expected relay publish to be invoked")+ }+ if relay.eventID == "" {+ t.Fatal("expected event id")+ }+ if M.WakeupDeliveredHit.Load() != 1 {+ t.Fatalf("delivered hit metric = %d, want 1", M.WakeupDeliveredHit.Load())+ }++ hub.DeliverDaemonRuntime(relay.scopeID, relay.frame, relay.eventID)++ select {+ case duplicate := <-client.send:+ t.Fatalf("expected redis loopback to be deduped, got duplicate %s", duplicate)+ case <-time.After(20 * time.Millisecond):+ }+ if M.WakeupDeliveredHit.Load() != 1 {+ t.Fatalf("delivered hit metric after loopback = %d, want 1", M.WakeupDeliveredHit.Load())+ }+ if M.WakeupDeliveredMiss.Load() != 0 {+ t.Fatalf("delivered miss metric after dedup = %d, want 0", M.WakeupDeliveredMiss.Load())+ }+ })}}diff --git a/server/internal/daemonws/notifier.go b/server/internal/daemonws/notifier.goindex b8055195f4..5ac22332d4 100644--- a/server/internal/daemonws/notifier.go+++ b/server/internal/daemonws/notifier.go@@ -6,6 +6,7 @@ import ("github.com/oklog/ulid/v2""github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/pkg/protocol")// RelayNotifier sends daemon wakeup hints to the local daemon hub and, when@@ -21,17 +22,25 @@ func NewRelayNotifier(local *Hub, relay realtime.RelayPublisher) *RelayNotifier}func (n *RelayNotifier) NotifyTaskAvailable(runtimeID, taskID string) {- if runtimeID == "" {+ n.notifyTask(protocol.EventDaemonTaskAvailable, runtimeID, taskID)+}++func (n *RelayNotifier) NotifyTaskSupplementAvailable(runtimeID, taskID string) {+ n.notifyTask(protocol.EventDaemonTaskSupplementAvailable, runtimeID, taskID)+}++func (n *RelayNotifier) notifyTask(eventType, runtimeID, taskID string) {+ if runtimeID == "" || (eventType == protocol.EventDaemonTaskSupplementAvailable && taskID == "") {return}eventID := ulid.Make().String()if n.local != nil {- n.local.notifyTaskAvailable(runtimeID, taskID, eventID)+ n.local.notifyTask(eventType, runtimeID, taskID, eventID)}if n.relay == nil {return}- frame, err := taskAvailableFrame(runtimeID, taskID)+ frame, err := taskWakeupFrame(eventType, runtimeID, taskID)if err != nil {M.WakeupPublishErrors.Add(1)return@@ -42,7 +51,7 @@ func (n *RelayNotifier) NotifyTaskAvailable(runtimeID, taskID string) {}if err := n.relay.PublishWithID(realtime.ScopeDaemonRuntime, shardKey, "", frame, eventID); err != nil {M.WakeupPublishErrors.Add(1)- slog.Warn("daemon websocket wakeup publish failed", "error", err, "runtime_id", runtimeID, "task_id", taskID)+ slog.Warn("daemon websocket wakeup publish failed", "type", eventType, "error", err, "runtime_id", runtimeID, "task_id", taskID)return}M.WakeupPublishedTotal.Add(1)diff --git a/server/internal/handler/activity.go b/server/internal/handler/activity.goindex 06bffb593b..f1591de932 100644--- a/server/internal/handler/activity.go+++ b/server/internal/handler/activity.go@@ -47,7 +47,11 @@ type TimelineEntry struct {ResolvedByID *string `json:"resolved_by_id,omitempty"`SourceTaskID *string `json:"source_task_id,omitempty"`// Set only on a tombstone: a comment deleted while it still had replies.- DeletedAt *string `json:"deleted_at,omitempty"`+ DeletedAt *string `json:"deleted_at,omitempty"`+ SupplementTaskID string `json:"supplement_task_id,omitempty"`+ SupplementStatus string `json:"supplement_status,omitempty"`+ SupplementFailureReason *string `json:"supplement_failure_reason,omitempty"`+ SupplementDeliveredAt *string `json:"supplement_delivered_at,omitempty"`}// timelineHardCap bounds the per-issue timeline payload. Sized as a defensive@@ -283,6 +287,14 @@ func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []Ti}reactions := h.groupReactions(r, ids)attachments := h.groupAttachments(r, ids)+ supplements := make(map[string]db.TaskSupplement)+ if rows, err := h.Queries.ListTaskSupplementsByCommentIDs(r.Context(), db.ListTaskSupplementsByCommentIDsParams{+ WorkspaceID: comments[0].WorkspaceID, CommentIds: ids,+ }); err == nil {+ for _, row := range rows {+ supplements[uuidToString(row.CommentID)] = row+ }+ }out := make([]TimelineEntry, len(comments))for i, c := range comments {@@ -310,6 +322,12 @@ func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []TiSourceTaskID: uuidToPtr(c.SourceTaskID),DeletedAt: timestampToPtr(c.DeletedAt),}+ if supplement, ok := supplements[cid]; ok {+ out[i].SupplementTaskID = uuidToString(supplement.TaskID)+ out[i].SupplementStatus = supplement.Status+ out[i].SupplementFailureReason = textToPtr(supplement.FailureReason)+ out[i].SupplementDeliveredAt = timestampToPtr(supplement.DeliveredAt)+ }}return out}diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 5bce765cda..df23bdd1b6 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -454,10 +454,13 @@ type AgentTaskResponse struct {// Populated on both terminal paths — a failed run can still have committed// partial work, and that is when the pointer matters most.BranchName string `json:"branch_name,omitempty"`- TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task- CoalescedCommentIDs []string `json:"coalesced_comment_ids,omitempty"` // MUL-4195: earlier comments folded into this run when it had not yet started, so a single run still covers every deliberate comment; trigger_comment_id is the newest. Surfaced so the UI can show which comments a run covered. omitempty so old clients ignore it- CoalescedComments []CoalescedCommentData `json:"coalesced_comments,omitempty"` // MUL-4195: full detail (thread_id/author/created_at/content) of the folded comments, so the daemon prompt can address each without assuming they share the triggering thread. omitempty so old clients ignore it- DeliveredCommentIDs []string `json:"delivered_comment_ids"` // always present: [] is an authoritative empty receipt, while field absence identifies responses from legacy servers+ TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task+ CoalescedCommentIDs []string `json:"coalesced_comment_ids,omitempty"` // MUL-4195: earlier comments folded into this run when it had not yet started, so a single run still covers every deliberate comment; trigger_comment_id is the newest. Surfaced so the UI can show which comments a run covered. omitempty so old clients ignore it+ CoalescedComments []CoalescedCommentData `json:"coalesced_comments,omitempty"` // MUL-4195: full detail (thread_id/author/created_at/content) of the folded comments, so the daemon prompt can address each without assuming they share the triggering thread. omitempty so old clients ignore it+ DeliveredCommentIDs []string `json:"delivered_comment_ids"` // always present: [] is an authoritative empty receipt, while field absence identifies responses from legacy servers+ SupplementCapability string `json:"supplement_capability,omitempty"`+ SupplementCommentIDs []string `json:"supplement_comment_ids,omitempty"`+ CanSupplement bool `json:"can_supplement,omitempty"`TriggerThreadID string `json:"trigger_thread_id,omitempty"` // root comment ID for the triggering threadTriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering commentTriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes@@ -2714,6 +2717,7 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {taskIDs[i] = t.ID}}+ h.hydrateTaskSupplementMetadata(r.Context(), r, agent.WorkspaceID, tasks, resp)h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))if includeUsage {if err := h.hydrateAgentTaskUsage(r.Context(), agent.ID, taskIDs, resp); err != nil {diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex a0b5ea77e9..b0a17d666a 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -82,7 +82,11 @@ type CommentResponse struct {// was blocked (no invoke permission, target unavailable, runtime offline) now// reports that here instead of silently dropping the trigger, so the client// can show "comment posted, but N targets were not triggered".- TriggerOutcomes []CommentTriggerOutcome `json:"trigger_outcomes,omitempty"`+ TriggerOutcomes []CommentTriggerOutcome `json:"trigger_outcomes,omitempty"`+ SupplementTaskID string `json:"supplement_task_id,omitempty"`+ SupplementStatus string `json:"supplement_status,omitempty"`+ SupplementFailureReason *string `json:"supplement_failure_reason,omitempty"`+ SupplementDeliveredAt *string `json:"supplement_delivered_at,omitempty"`}// CommentTriggerOutcome is the per-target result of an explicit @agent / @squad@@ -126,6 +130,9 @@ func commentToResponse(c db.Comment, reactions []ReactionResponse, attachments [}}+// Shared bound for plugin comments and input sent to a running agent.+const maxCommentContentBytes = 64 * 1024+// summaryContentRunes bounds comment content under summary=true. 200 runes is// enough to tell what a comment is about (its opening) while cutting the bulk// of a long body out of an agent's context budget. Counted in runes, not bytes,@@ -3346,6 +3353,15 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "comment not found")return}+ if _, err := h.Queries.GetTaskSupplementByComment(r.Context(), db.GetTaskSupplementByCommentParams{+ CommentID: existing.ID, WorkspaceID: wsUUID,+ }); err == nil {+ writeError(w, http.StatusConflict, "additional messages cannot be edited")+ return+ } else if !errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusInternalServerError, "failed to verify additional message")+ return+ }member, ok := h.workspaceMember(w, r, workspaceID)if !ok {@@ -3665,7 +3681,9 @@ func (h *Handler) DeleteComment(w http.ResponseWriter, r *http.Request) {if hasIssue {h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, pgtype.UUID{})}- if errors.Is(err, pgx.ErrNoRows) {+ if errors.Is(err, errTaskSupplementInFlight) {+ writeError(w, http.StatusConflict, "additional message is still being delivered")+ } else if errors.Is(err, pgx.ErrNoRows) {writeError(w, http.StatusNotFound, "comment not found")} else {writeError(w, http.StatusInternalServerError, "failed to delete comment")@@ -3773,6 +3791,8 @@ func (h *Handler) withLiveCommentLock(ctx context.Context, commentID, workspaceI// matching the depth bound of the ancestor path queries.const commentTombstonePruneDepth = 256+var errTaskSupplementInFlight = errors.New("additional message is still being delivered")+// deleteComment deletes exactly one comment (#8296). A comment that still has// replies becomes a tombstone — content, attachments, reactions and resolution// cleared, row kept — so each reply stays attached to its direct parent. A@@ -3796,6 +3816,23 @@ func (h *Handler) deleteComment(ctx context.Context, commentID, workspaceID pgtyif err != nil {return out, err}+ // Keep receipt admission locked through deletion so a concurrent retry+ // cannot resurrect or deliver the content being removed.+ receipt, receiptErr := qtx.LockTaskSupplementByComment(ctx, db.LockTaskSupplementByCommentParams{+ CommentID: commentID, WorkspaceID: workspaceID,+ })+ if receiptErr == nil {+ if receipt.Status == "pending" || receipt.Status == "delivering" {+ return out, errTaskSupplementInFlight+ }+ if err := qtx.DeleteTaskSupplementByComment(ctx, db.DeleteTaskSupplementByCommentParams{+ CommentID: commentID, WorkspaceID: workspaceID,+ }); err != nil {+ return out, err+ }+ } else if !errors.Is(receiptErr, pgx.ErrNoRows) {+ return out, receiptErr+ }// Separate statement on purpose: its snapshot postdates the locks above,// so it sees every committed reply, and none can be added while they are// held.diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 1126a0e491..f82e379fa5 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -4037,7 +4037,6 @@ func (h *Handler) ListPendingTasksByRuntime(w http.ResponseWriter, r *http.Requefor i, t := range tasks {resp[i] = taskToResponse(t, workspaceID)}-writeJSON(w, http.StatusOK, resp)}@@ -4085,8 +4084,9 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {}var req struct {- RuntimeID string `json:"runtime_id"`- DispatchedAt string `json:"dispatched_at"`+ Capabilities []string `json:"capabilities"`+ RuntimeID string `json:"runtime_id"`+ DispatchedAt string `json:"dispatched_at"`}if r.ContentLength != 0 {if err := json.NewDecoder(r.Body).Decode(&req); err != nil {@@ -4094,13 +4094,14 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {return}}+ enableTaskSupplement := slices.Contains(req.Capabilities, protocol.DaemonCapabilityTaskSupplementV1)var task *db.AgentTaskQueuevar err errorlegacy := req.RuntimeID == "" && req.DispatchedAt == ""if legacy {// Older daemons send {}. Keep their single-winner behavior; in// particular, they cannot acknowledge an already-running task.- task, err = h.TaskService.StartTask(r.Context(), parseUUID(taskID))+ task, err = h.TaskService.StartTask(r.Context(), parseUUID(taskID), enableTaskSupplement)} else {runtimeID, ok := parseUUIDOrBadRequest(w, req.RuntimeID, "runtime_id")if !ok {@@ -4114,7 +4115,7 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {task, err = h.TaskService.StartTaskForClaim(r.Context(), db.LockAgentTaskStartClaimParams{ID: parseUUID(taskID), RuntimeID: runtimeID,DispatchedAt: pgtype.Timestamptz{Time: generation, Valid: true},- })+ }, enableTaskSupplement)}if err != nil {slog.Warn("start task failed", "task_id", taskID, "error", err)@@ -4131,7 +4132,19 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {}slog.Info("task started", "task_id", taskID, "agent_id", uuidToString(task.AgentID))- writeJSON(w, http.StatusOK, taskToResponse(*task, workspaceID))+ resp := taskToResponse(*task, workspaceID)+ // Echo the capability the server actually committed for this exact run.+ // A daemon must use this response rather than its own offer: an old server+ // ignores the offer and omits the field, which keeps daemon-first rollouts+ // fail closed without requiring synchronized deployment.+ if task.IssueID.Valid {+ if capability, capabilityErr := h.Queries.GetTaskSupplementCapability(r.Context(), task.ID); capabilityErr == nil {+ resp.SupplementCapability = capability.Capability+ } else if !errors.Is(capabilityErr, pgx.ErrNoRows) {+ slog.Warn("start task: failed to load negotiated supplement capability", "task_id", taskID, "error", capabilityErr)+ }+ }+ writeJSON(w, http.StatusOK, resp)}// TaskWaitLocalDirectoryRequest is the body the daemon POSTs when it parks@@ -5657,6 +5670,7 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {for i, t := range tasks {resp[i] = taskToResponse(t, workspaceID)}+ h.hydrateTaskSupplementMetadata(r.Context(), r, issue.WorkspaceID, tasks, resp)// Execution-log rows render the "on behalf of <member>" badge, so this// issue-facing surface must resolve initiator/originator names (departed-safe,// one batch) — otherwise the badge falls back to "someone" on issue detail.diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 0f0cb63ce9..e37694b22a 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -2013,7 +2013,9 @@ func TestStartTask_AutopilotRunOnlyTask_ResolvesWorkspace(t *testing.T) {// Same-workspace daemon token must succeed — this is the bug in #1224.w = httptest.NewRecorder()- req = newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/start", nil,+ req = newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/start", map[string]any{+ "capabilities": []string{protocol.DaemonCapabilityTaskSupplementV1},+ },testWorkspaceID, "legit-daemon")req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))@@ -2027,6 +2029,11 @@ func TestStartTask_AutopilotRunOnlyTask_ResolvesWorkspace(t *testing.T) {if status != "running" {t.Fatalf("expected task status 'running' after StartTask, got %q", status)}+ var capabilityRows int+ dbfx.QueryRow(t, `SELECT count(*) FROM task_supplement_capability WHERE task_id = $1`, taskID).Scan(&capabilityRows)+ if capabilityRows != 0 {+ t.Fatalf("run-only autopilot persisted %d supplement capabilities, want 0", capabilityRows)+ }}// ClaimTaskByRuntime must surface the issue's project github_repo resourcesdiff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 9e23de71ff..4634b6acbe 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -174,6 +174,12 @@ type DaemonPendingWorkNotifier interface {NotifyPendingWork(runtimeID, kind string)}+// DaemonTaskSupplementNotifier sends a content-free wakeup for one exact run.+// The daemon still pulls and authenticates the durable supplement over HTTP.+type DaemonTaskSupplementNotifier interface {+ NotifyTaskSupplementAvailable(runtimeID, taskID string)+}+// RuntimeGoneNotifier invalidates a runtime that was deleted while its daemon// still has an authenticated WebSocket connection.type RuntimeGoneNotifier interface {@@ -232,7 +238,8 @@ type Handler struct {// heartbeat-carried requests (MUL-5444). Optional: when nil,// requestDaemonPendingWork falls back to the local DaemonHub, which is the// correct delivery scope for a single-node deployment.- DaemonPendingWork DaemonPendingWorkNotifier+ DaemonPendingWork DaemonPendingWorkNotifier+ DaemonTaskSupplement DaemonTaskSupplementNotifier// ModelCatalogCache serves the last known good model list for a runtime so// the picker can render without waiting for a daemon round trip// (stale-while-revalidate, MUL-5444). Nil-safe: every call site treats a nildiff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.goindex f529fe7ef7..6e55bf0ec0 100644--- a/server/internal/handler/plugin_action.go+++ b/server/internal/handler/plugin_action.go@@ -551,7 +551,7 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {publicapiv1.WriteProblem(w, r, http.StatusBadRequest, "invalid_request", "content is required")return}- if len(content) > maxPluginCommentBytes {+ if len(content) > maxCommentContentBytes {publicapiv1.WriteProblem(w, r, http.StatusBadRequest, "invalid_request", "content is too long")return}@@ -621,9 +621,6 @@ func (h *Handler) CreatePluginComment(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusCreated, publicPluginComment(comment))}-// maxPluginCommentBytes keeps a surface from using comments as bulk storage.-const maxPluginCommentBytes = 64 * 1024-// maxPluginCommentsPerRead bounds one read. The query returns the NEWEST N in// chronological order, so a surface on a long thread sees the recent end rather// than a truncated beginning.diff --git a/server/internal/handler/task_supplement.go b/server/internal/handler/task_supplement.gonew file mode 100644index 0000000000..2a64df7dfa--- /dev/null+++ b/server/internal/handler/task_supplement.go@@ -0,0 +1,366 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func (h *Handler) hydrateTaskSupplementMetadata(ctx context.Context, r *http.Request, workspaceID pgtype.UUID, tasks []db.AgentTaskQueue, resp []AgentTaskResponse) {+ if len(tasks) == 0 || len(tasks) != len(resp) {+ return+ }+ taskIDs := make([]pgtype.UUID, 0, len(tasks))+ for i := range tasks {+ if tasks[i].IssueID.Valid {+ taskIDs = append(taskIDs, tasks[i].ID)+ }+ }+ if len(taskIDs) == 0 {+ return+ }+ rows, err := h.Queries.ListTaskSupplementMetadata(ctx, db.ListTaskSupplementMetadataParams{+ WorkspaceID: workspaceID,+ TaskIds: taskIDs,+ })+ if err != nil {+ return // metadata is optional and must fail closed+ }+ byTask := make(map[string]db.ListTaskSupplementMetadataRow, len(rows))+ for _, row := range rows {+ byTask[uuidToString(row.TaskID)] = row+ }++ userID := requestUserID(r)+ permission := make(map[string]bool)+ for i, task := range tasks {+ row, ok := byTask[uuidToString(task.ID)]+ if !ok {+ continue+ }+ resp[i].SupplementCapability = row.Capability+ resp[i].SupplementCommentIDs = uuidsToStrings(row.CommentIds)+ if task.Status != "running" || row.Capability != protocol.DaemonCapabilityTaskSupplementV1 || userID == "" {+ continue+ }+ agentID := uuidToString(task.AgentID)+ allowed, checked := permission[agentID]+ if !checked {+ agent, loadErr := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{+ ID: task.AgentID, WorkspaceID: workspaceID,+ })+ allowed = loadErr == nil && h.canInvokeAgent(ctx, agent, "member", userID, userID, uuidToString(workspaceID))+ permission[agentID] = allowed+ }+ resp[i].CanSupplement = allowed+ }+}++type taskSupplementReceiptResponse struct {+ TaskID string `json:"supplement_task_id"`+ Status string `json:"supplement_status"`+ FailureReason *string `json:"supplement_failure_reason,omitempty"`+ DeliveredAt *string `json:"supplement_delivered_at,omitempty"`+}++func supplementReceipt(s db.TaskSupplement) taskSupplementReceiptResponse {+ return taskSupplementReceiptResponse{+ TaskID: uuidToString(s.TaskID),+ Status: s.Status,+ FailureReason: textToPtr(s.FailureReason),+ DeliveredAt: timestampToPtr(s.DeliveredAt),+ }+}++func applySupplementReceipt(resp *CommentResponse, s db.TaskSupplement) {+ receipt := supplementReceipt(s)+ resp.SupplementTaskID = receipt.TaskID+ resp.SupplementStatus = receipt.Status+ resp.SupplementFailureReason = receipt.FailureReason+ resp.SupplementDeliveredAt = receipt.DeliveredAt+}++func (h *Handler) loadTaskSupplementTarget(w http.ResponseWriter, r *http.Request) (db.Issue, db.AgentTaskQueue, pgtype.UUID, bool) {+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return db.Issue{}, db.AgentTaskQueue{}, pgtype.UUID{}, false+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return db.Issue{}, db.AgentTaskQueue{}, pgtype.UUID{}, false+ }+ authorID, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return db.Issue{}, db.AgentTaskQueue{}, pgtype.UUID{}, false+ }+ taskID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "taskId"), "task id")+ if !ok {+ return db.Issue{}, db.AgentTaskQueue{}, pgtype.UUID{}, false+ }+ task, err := h.Queries.GetAgentTask(r.Context(), taskID)+ if err != nil || uuidToString(task.IssueID) != uuidToString(issue.ID) {+ writeError(w, http.StatusNotFound, "task not found")+ return db.Issue{}, db.AgentTaskQueue{}, pgtype.UUID{}, false+ }+ agent, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{+ ID: task.AgentID, WorkspaceID: issue.WorkspaceID,+ })+ if err != nil || !h.canInvokeAgent(r.Context(), agent, "member", userID, userID, uuidToString(issue.WorkspaceID)) {+ writeErrorCode(w, http.StatusForbidden, "invocation_not_allowed", "you cannot run this agent")+ return db.Issue{}, db.AgentTaskQueue{}, pgtype.UUID{}, false+ }+ return issue, task, authorID, true+}++type createTaskSupplementRequest struct {+ Content string `json:"content"`+ ClientRequestID string `json:"client_request_id"`+}++// CreateTaskSupplement adds one ordinary historical comment to one exact run.+// The SQL statement owns the terminal race: when completion wins, no comment,+// binding, or coverage marker is created.+func (h *Handler) CreateTaskSupplement(w http.ResponseWriter, r *http.Request) {+ issue, task, authorID, ok := h.loadTaskSupplementTarget(w, r)+ if !ok {+ return+ }+ var req createTaskSupplementRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8*maxCommentContentBytes)).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ req.Content = sanitizeNullBytes(req.Content)+ if len(req.Content) > maxCommentContentBytes {+ writeError(w, http.StatusBadRequest, "content is too long")+ return+ }+ if strings.TrimSpace(req.Content) == "" {+ writeError(w, http.StatusBadRequest, "content is required")+ return+ }+ requestID, ok := parseUUIDOrBadRequest(w, req.ClientRequestID, "client_request_id")+ if !ok {+ return+ }+ lookup := db.GetTaskSupplementByRequestParams{+ TaskID: task.ID, WorkspaceID: issue.WorkspaceID, AuthorID: authorID, ClientRequestID: requestID,+ }+ if existing, err := h.Queries.GetTaskSupplementByRequest(r.Context(), lookup); err == nil {+ h.notifyTaskSupplementAvailable(task)+ h.writeExistingTaskSupplement(w, r, existing)+ return+ } else if !errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusInternalServerError, "failed to check additional message")+ return+ }+ if task.Status != "running" {+ writeErrorCode(w, http.StatusConflict, "task_supplement_turn_ended", "this run has ended")+ return+ }+ capability, err := h.Queries.GetTaskSupplementCapability(r.Context(), task.ID)+ if errors.Is(err, pgx.ErrNoRows) || capability.Capability != protocol.DaemonCapabilityTaskSupplementV1 {+ writeErrorCode(w, http.StatusPreconditionFailed, "task_supplement_unsupported", "this run does not support additional messages")+ return+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to check additional-message support")+ return+ }++ created, err := h.Queries.CreateTaskSupplement(r.Context(), db.CreateTaskSupplementParams{+ TaskID: task.ID, IssueID: issue.ID, WorkspaceID: issue.WorkspaceID,+ AuthorID: authorID, Content: req.Content, ClientRequestID: requestID,+ })+ if isUniqueViolation(err) {+ if existing, loadErr := h.Queries.GetTaskSupplementByRequest(r.Context(), lookup); loadErr == nil {+ h.notifyTaskSupplementAvailable(task)+ h.writeExistingTaskSupplement(w, r, existing)+ return+ } else if !errors.Is(loadErr, pgx.ErrNoRows) {+ writeError(w, http.StatusInternalServerError, "failed to check additional message")+ return+ }+ writeError(w, http.StatusConflict, "client_request_id is already in use")+ return+ }+ if errors.Is(err, pgx.ErrNoRows) {+ writeErrorCode(w, http.StatusConflict, "task_supplement_turn_ended", "this run has ended")+ return+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create additional message")+ return+ }+ comment := db.Comment{+ ID: created.ID, IssueID: created.IssueID, AuthorType: created.AuthorType,+ AuthorID: created.AuthorID, Content: created.Content, Type: created.Type,+ CreatedAt: created.CreatedAt, UpdatedAt: created.UpdatedAt, ParentID: created.ParentID,+ WorkspaceID: created.WorkspaceID, ResolvedAt: created.ResolvedAt,+ ResolvedByType: created.ResolvedByType, ResolvedByID: created.ResolvedByID,+ SourceTaskID: created.SourceTaskID, QuickActionID: created.QuickActionID,+ ViaPluginID: created.ViaPluginID, Revision: created.Revision,+ RecoverySettledAt: created.RecoverySettledAt, DeletedAt: created.DeletedAt,+ }+ resp := commentToResponse(comment, nil, nil)+ resp.IssueRevision = created.IssueRevision+ resp.SupplementTaskID = uuidToString(created.SupplementTaskID)+ resp.SupplementStatus = created.SupplementStatus+ resp.SupplementFailureReason = textToPtr(created.SupplementFailureReason)+ resp.SupplementDeliveredAt = timestampToPtr(created.SupplementDeliveredAt)+ h.publish(protocol.EventCommentCreated, uuidToString(issue.WorkspaceID), "member", uuidToString(authorID), map[string]any{+ "comment": resp, "issue_title": issue.Title, "issue_revision": created.IssueRevision,+ })+ h.notifyTaskSupplementAvailable(task)+ writeJSON(w, http.StatusCreated, resp)+}++func (h *Handler) notifyTaskSupplementAvailable(task db.AgentTaskQueue) {+ if h.DaemonTaskSupplement == nil || task.Status != "running" || !task.RuntimeID.Valid {+ return+ }+ h.DaemonTaskSupplement.NotifyTaskSupplementAvailable(uuidToString(task.RuntimeID), uuidToString(task.ID))+}++func (h *Handler) writeExistingTaskSupplement(w http.ResponseWriter, r *http.Request, existing db.TaskSupplement) {+ comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{+ ID: existing.CommentID, WorkspaceID: existing.WorkspaceID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load additional message")+ return+ }+ resp := commentToResponse(comment, nil, nil)+ applySupplementReceipt(&resp, existing)+ writeJSON(w, http.StatusOK, resp)+}++func (h *Handler) RetryTaskSupplement(w http.ResponseWriter, r *http.Request) {+ issue, task, _, ok := h.loadTaskSupplementTarget(w, r)+ if !ok {+ return+ }+ commentID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "commentId"), "comment id")+ if !ok {+ return+ }+ row, err := h.Queries.RetryTaskSupplement(r.Context(), db.RetryTaskSupplementParams{+ CommentID: commentID, WorkspaceID: issue.WorkspaceID, TaskID: task.ID, IssueID: issue.ID,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ existing, loadErr := h.Queries.GetTaskSupplementByComment(r.Context(), db.GetTaskSupplementByCommentParams{+ CommentID: commentID, WorkspaceID: issue.WorkspaceID,+ })+ if loadErr == nil && existing.TaskID == task.ID && existing.Status == "pending" {+ row = existing // duplicate retry is an idempotent success+ err = nil+ }+ }+ if errors.Is(err, pgx.ErrNoRows) {+ writeErrorCode(w, http.StatusConflict, "task_supplement_not_retryable", "this message cannot be retried")+ return+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to retry additional message")+ return+ }+ h.publishTaskSupplementUpdate(r, row)+ h.notifyTaskSupplementAvailable(task)+ writeJSON(w, http.StatusOK, supplementReceipt(row))+}++type ackTaskSupplementRequest struct {+ Delivered bool `json:"delivered"`+ Error string `json:"error,omitempty"`+}++func (h *Handler) ClaimTaskSupplement(w http.ResponseWriter, r *http.Request) {+ taskID := chi.URLParam(r, "taskId")+ if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {+ return+ }+ row, err := h.Queries.ClaimNextTaskSupplement(r.Context(), parseUUID(taskID))+ if errors.Is(err, pgx.ErrNoRows) {+ writeJSON(w, http.StatusOK, map[string]any{})+ return+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to claim additional message")+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "comment_id": uuidToString(row.CommentID), "author_name": row.AuthorName, "content": row.Content,+ })+}++func (h *Handler) AckTaskSupplement(w http.ResponseWriter, r *http.Request) {+ 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 ackTaskSupplementRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ var row db.TaskSupplement+ var err error+ if req.Delivered {+ row, err = h.Queries.AckTaskSupplementDelivered(r.Context(), db.AckTaskSupplementDeliveredParams{+ TaskID: parseUUID(taskID), CommentID: commentID,+ })+ } else {+ reason := stableTaskSupplementFailureReason(req.Error)+ row, err = h.Queries.AckTaskSupplementFailed(r.Context(), db.AckTaskSupplementFailedParams{+ TaskID: parseUUID(taskID), CommentID: commentID,+ FailureReason: pgtype.Text{String: reason, Valid: true},+ })+ }+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusConflict, "additional message is no longer deliverable")+ return+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to acknowledge additional message")+ return+ }+ h.publishTaskSupplementUpdate(r, row)+ writeJSON(w, http.StatusOK, supplementReceipt(row))+}++func stableTaskSupplementFailureReason(reason string) string {+ reason = strings.TrimSpace(sanitizeNullBytes(reason))+ switch reason {+ case protocol.TaskSupplementFailureTurnNotStarted, protocol.TaskSupplementFailureTimeout,+ protocol.TaskSupplementFailureTurnEnded, protocol.TaskSupplementFailureProviderRejected:+ return reason+ default:+ // Provider and Go errors are private daemon diagnostics. Never persist or+ // rebroadcast them to workspace members, and never byte-truncate UTF-8.+ return protocol.TaskSupplementFailureProviderRejected+ }+}++func (h *Handler) publishTaskSupplementUpdate(r *http.Request, row db.TaskSupplement) {+ comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{+ ID: row.CommentID, WorkspaceID: row.WorkspaceID,+ })+ if err != nil {+ return+ }+ resp := commentToResponse(comment, nil, nil)+ applySupplementReceipt(&resp, row)+ h.publish(protocol.EventCommentUpdated, uuidToString(row.WorkspaceID), "system", "", map[string]any{"comment": resp})+}diff --git a/server/internal/handler/task_supplement_test.go b/server/internal/handler/task_supplement_test.gonew file mode 100644index 0000000000..8c96c3ec2b--- /dev/null+++ b/server/internal/handler/task_supplement_test.go@@ -0,0 +1,545 @@+package handler++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "slices"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type supplementFixture struct {+ runtimeID string+ agentID string+ issueID string+ taskID string+ triggerID string+}++func TestStableTaskSupplementFailureReason(t *testing.T) {+ for _, reason := range []string{+ protocol.TaskSupplementFailureTurnNotStarted,+ protocol.TaskSupplementFailureProviderRejected,+ protocol.TaskSupplementFailureTimeout,+ protocol.TaskSupplementFailureTurnEnded,+ } {+ if got := stableTaskSupplementFailureReason(reason); got != reason {+ t.Fatalf("stableTaskSupplementFailureReason(%q) = %q", reason, got)+ }+ }+ for _, raw := range []string{"", "供应商错误:无法发送", strings.Repeat("界", 600)} {+ if got := stableTaskSupplementFailureReason(raw); got != protocol.TaskSupplementFailureProviderRejected {+ t.Fatalf("raw reason %q escaped as %q", raw, got)+ }+ }+}++func TestTaskSupplementClaimStartReplay(t *testing.T) {+ f := newSupplementFixture(t, "codex", "dispatched", false)+ dbfx.Cleanup(t, `DELETE FROM task_supplement_capability WHERE task_id=$1`, f.taskID)+ generation := time.Date(2026, 9, 23, 0, 0, 0, 0, time.UTC)+ dbfx.Exec(t, `UPDATE agent_task_queue SET dispatched_at=$2 WHERE id=$1`, f.taskID, generation)+ for range 2 {+ req := withURLParam(newDaemonTokenRequest(http.MethodPost, "/start", map[string]any{+ "runtime_id": f.runtimeID, "dispatched_at": generation.Format(time.RFC3339Nano),+ "capabilities": []string{protocol.DaemonCapabilityTaskSupplementV1},+ }, testWorkspaceID, "start-claim-test"), "taskId", f.taskID)+ var started AgentTaskResponse+ testutil.Call(t, testHandler.StartTask, req).Want(http.StatusOK).JSON(&started)+ if started.SupplementCapability != protocol.DaemonCapabilityTaskSupplementV1 {+ t.Fatalf("lost negotiated capability on start replay: %+v", started)+ }+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM task_supplement_capability WHERE task_id=$1`, f.taskID); n != 1 {+ t.Fatalf("start replay wrote %d capabilities", n)+ }+}++func TestTaskSupplementLateDeliveryAndDeletion(t *testing.T) {+ f := newSupplementFixture(t, "claude", "running", true)+ var sent, pending CommentResponse+ supplementRequest(t, f, "0199a4e8-22ce-7b01-bba5-111111111111", "already injected").Want(http.StatusCreated).JSON(&sent)+ if _, err := testHandler.Queries.ClaimNextTaskSupplement(t.Context(), parseUUID(f.taskID)); err != nil {+ t.Fatal(err)+ }+ supplementRequest(t, f, "0199a4e8-22ce-7b01-bba5-222222222222", "never injected").Want(http.StatusCreated).JSON(&pending)+ deleteRequest := func() *http.Request {+ return withURLParam(newRequest(http.MethodDelete, "/comments/"+sent.ID, nil), "commentId", sent.ID)+ }+ testutil.Call(t, testHandler.DeleteComment, deleteRequest()).Want(http.StatusConflict)+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='completed' WHERE id=$1`, f.taskID)+ for _, c := range []CommentResponse{sent, pending} {+ req := withURLParams(newDaemonTokenRequest(http.MethodPost, "/ack", map[string]any{"delivered": true}, testWorkspaceID, "legit-daemon"), "taskId", f.taskID, "commentId", c.ID)+ want := http.StatusOK+ if c.ID == pending.ID {+ want = http.StatusConflict+ }+ testutil.Call(t, testHandler.AckTaskSupplement, req).Want(want)+ }+ testutil.Call(t, testHandler.DeleteComment, deleteRequest()).Want(http.StatusNoContent)+ if n := dbfx.Count(t, `SELECT count(*) FROM task_supplement WHERE comment_id=$1`, sent.ID); n != 0 {+ t.Fatal("deleted comment retained its receipt")+ }+}++func TestTaskSupplementSubmissionBoundsAndConflicts(t *testing.T) {+ f := newSupplementFixture(t, "codex", "running", true)+ const requestID = "0199a4e8-22ce-7b01-bba5-111111111111"+ supplementRequest(t, f, requestID, strings.Repeat("x", maxCommentContentBytes+1)).Want(http.StatusBadRequest)+ if n := dbfx.Count(t, `SELECT count(*) FROM task_supplement WHERE task_id=$1`, f.taskID); n != 0 {+ t.Fatal("oversized input was persisted")+ }+ supplementRequest(t, f, requestID, "original").Want(http.StatusCreated)+ // Another author's request key is unique within the task but invisible to+ // the current author's idempotency lookup. This is a conflict, not a 500.+ dbfx.Exec(t, `UPDATE task_supplement SET author_id=$2 WHERE task_id=$1`, f.taskID, "0199a4e8-22ce-7b01-bba5-333333333333")+ supplementRequest(t, f, requestID, "collision").Want(http.StatusConflict)+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id=$1 AND content='collision'`, f.issueID); n != 0 {+ t.Fatal("conflict left an orphan comment")+ }+}++func newSupplementFixture(t *testing.T, provider, status string, negotiated bool) supplementFixture {+ t.Helper()+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := dbfx.Runtime(t, "supplement-"+provider, testutil.Cols{"provider": provider})+ agentID := dbfx.Agent(t, "Supplement "+provider, runtimeID)+ issueID := dbfx.Issue(t, "supplement "+provider)+ triggerID := dbfx.Comment(t, issueID, "original objective")+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "trigger_comment_id": triggerID,+ "status": status,+ "started_at": testutil.Raw("CASE WHEN '" + status + "' = 'running' THEN now() ELSE NULL END"),+ })+ if negotiated {+ dbfx.Exec(t, `+ INSERT INTO task_supplement_capability (task_id, workspace_id, issue_id, capability)+ VALUES ($1, $2, $3, $4)+ `, taskID, testWorkspaceID, issueID, protocol.DaemonCapabilityTaskSupplementV1)+ dbfx.Cleanup(t, `DELETE FROM task_supplement_capability WHERE task_id = $1`, taskID)+ }+ dbfx.Cleanup(t, `DELETE FROM task_supplement WHERE task_id = $1`, taskID)+ return supplementFixture{runtimeID: runtimeID, agentID: agentID, issueID: issueID, taskID: taskID, triggerID: triggerID}+}++func supplementRequest(t *testing.T, fixture supplementFixture, requestID, content string) *testutil.Response {+ t.Helper()+ req := newRequest(http.MethodPost, "/api/issues/"+fixture.issueID+"/tasks/"+fixture.taskID+"/supplements", map[string]any{+ "client_request_id": requestID,+ "content": content,+ })+ return testutil.Call(t, testHandler.CreateTaskSupplement,+ withURLParams(req, "id", fixture.issueID, "taskId", fixture.taskID),+ )+}++func TestTaskSupplementNegotiationFailsClosed(t *testing.T) {++ for _, tc := range []struct {+ name string+ provider string+ daemonAdvertises bool+ wantCapabilityRow bool+ }{+ {name: "codex negotiated", provider: "codex", daemonAdvertises: true, wantCapabilityRow: true},+ {name: "claude negotiated", provider: "claude", daemonAdvertises: true, wantCapabilityRow: true},+ {name: "claude old daemon", provider: "claude", daemonAdvertises: false, wantCapabilityRow: false},+ {name: "old daemon", provider: "codex", daemonAdvertises: false, wantCapabilityRow: false},+ {name: "unsupported runtime", provider: "kimi", daemonAdvertises: true, wantCapabilityRow: false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ fixture := newSupplementFixture(t, tc.provider, "dispatched", false)+ var capabilities []string+ if tc.daemonAdvertises {+ capabilities = []string{protocol.DaemonCapabilityTaskSupplementV1}+ }+ req := withURLParam(newRequest(http.MethodPost, "/start", map[string]any{"capabilities": capabilities}), "taskId", fixture.taskID)+ var started AgentTaskResponse+ testutil.Call(t, testHandler.StartTask, req).Want(http.StatusOK).JSON(&started)+ if started.Status != "running" || started.StartedAt == nil {+ t.Fatalf("StartTask returned stale row: %#v", started)+ }+ if got := started.SupplementCapability == protocol.DaemonCapabilityTaskSupplementV1; got != tc.wantCapabilityRow {+ t.Fatalf("negotiated capability = %v, want %v", got, tc.wantCapabilityRow)+ }+ if !tc.wantCapabilityRow {+ supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-111111111111", "extra").Want(http.StatusPreconditionFailed)+ } else {+ supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-111111111111", "extra").Want(http.StatusCreated)+ }+ })+ }+}++func TestTaskSupplementCapabilityDoesNotBreakNonIssueStarts(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ for _, provider := range []string{"codex", "claude"} {+ t.Run(provider, func(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "supplement-no-issue", testutil.Cols{"provider": provider})+ agentID := dbfx.Agent(t, "Supplement no issue", runtimeID)+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": nil, "status": "dispatched"})+ started, err := testHandler.TaskService.StartTask(t.Context(), parseUUID(taskID), true)+ if err != nil || started.Status != "running" {+ t.Fatalf("non-issue start = %#v: %v", started, err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM task_supplement_capability WHERE task_id = $1`, taskID); n != 0 {+ t.Fatalf("capability rows = %d, want 0", n)+ }+ })+ }+}++func TestTaskSupplementCompletionDoesNotReplayBoundComments(t *testing.T) {+ for _, provider := range []string{"codex", "claude"} {+ for _, status := range []string{"pending", "delivering", "delivered", "failed"} {+ for _, ordinary := range []string{"none", "unhandled", "queued"} {+ t.Run(provider+"/"+status+"/"+ordinary, func(t *testing.T) {+ fixture := newSupplementFixture(t, provider, "running", true)+ // A plain reply routes back to the agent owning the original thread.+ dbfx.Exec(t, `UPDATE comment SET content = $2 WHERE id = $1`, fixture.triggerID,+ fmt.Sprintf("[@Supplement](mention://agent/%s) original objective", fixture.agentID))+ dbfx.Exec(t, `UPDATE agent_task_queue SET delivered_comment_ids = ARRAY[trigger_comment_id] WHERE id = $1`, fixture.taskID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, fixture.issueID)++ var ordinaryID, queuedID string+ if ordinary != "none" {+ ordinaryID = dbfx.Comment(t, fixture.issueID, "Handle this ordinary reply next.", testutil.Cols{+ "parent_id": fixture.triggerID,+ })+ }+ if ordinary == "queued" {+ queuedID = dbfx.Task(t, fixture.agentID, testutil.Cols{+ "issue_id": fixture.issueID, "runtime_id": fixture.runtimeID,+ "trigger_comment_id": ordinaryID,+ })+ }++ var supplement CommentResponse+ supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-999999999999", "Add this only to the current run.").+ Want(http.StatusCreated).JSON(&supplement)+ // Receipt transitions are covered by the retry test; vary only the+ // persisted state consumed by completion reconciliation here.+ dbfx.Exec(t, `UPDATE task_supplement SET status = $2 WHERE comment_id = $1`, supplement.ID, status)++ // Drive the real completion handler: a direct SQL status update skips+ // the reconciliation that previously replayed the supplement.+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/"+fixture.taskID+"/complete",+ map[string]any{"output": "done"}, testWorkspaceID, "legit-daemon")+ testutil.Call(t, testHandler.CompleteTask, withURLParam(req, "taskId", fixture.taskID)).Want(http.StatusOK)+ if status == "pending" || status == "delivering" {+ receipt, err := testHandler.Queries.GetTaskSupplementByComment(t.Context(), db.GetTaskSupplementByCommentParams{+ CommentID: parseUUID(supplement.ID), WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil || receipt.Status != "failed" || receipt.FailureReason.String != protocol.TaskSupplementFailureTurnEnded {+ t.Fatalf("completion did not settle pending delivery: %#v: %v", receipt, err)+ }+ }++ wantTasks := 1+ if ordinary != "none" {+ wantTasks+++ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, fixture.issueID); n != wantTasks {+ t.Fatalf("completion left %d runs, want %d; supplement must never create a follow-up", n, wantTasks)+ }+ if ordinary != "none" {+ var followupID, triggerID string+ var coalesced []string+ dbfx.QueryRow(t, `SELECT id, trigger_comment_id, coalesced_comment_ids::text[]+ FROM agent_task_queue WHERE issue_id = $1 AND id <> $2 AND status = 'queued'`,+ fixture.issueID, fixture.taskID).Scan(&followupID, &triggerID, &coalesced)+ if queuedID != "" && followupID != queuedID {+ t.Fatalf("replaced existing queued run %s with %s", queuedID, followupID)+ }+ if triggerID != ordinaryID || slices.Contains(coalesced, supplement.ID) {+ t.Fatalf("follow-up input = trigger %s, coalesced %v; want ordinary comment %s without supplement %s",+ triggerID, coalesced, ordinaryID, supplement.ID)+ }+ }+ })+ }+ }+ }+}++func TestTaskSupplementConcurrentClaimsKeepUniqueReceipts(t *testing.T) {+ fixture := newSupplementFixture(t, "codex", "running", true)++ const additions = 20+ for i := 0; i < additions; i++ {+ supplementRequest(t, fixture, fmt.Sprintf("0199a4e8-22ce-7b01-bba5-%012x", i+1),+ fmt.Sprintf("addition %02d", i)).Want(http.StatusCreated)+ }+ var wg sync.WaitGroup++ type claimResult struct {+ row db.ClaimNextTaskSupplementRow+ err error+ }+ claims := make(chan claimResult, additions)+ for i := 0; i < additions; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ row, err := testHandler.Queries.ClaimNextTaskSupplement(context.Background(), parseUUID(fixture.taskID))+ claims <- claimResult{row, err}+ }()+ }+ wg.Wait()+ close(claims)+ seen := make(map[string]bool, additions)+ for result := range claims {+ claimed := result.row+ id := uuidToString(claimed.CommentID)+ if result.err != nil || seen[id] || claimed.AttemptCount != 1 {+ t.Fatalf("claim %q duplicated=%v attempts=%d: %v", id, seen[id], claimed.AttemptCount, result.err)+ }+ seen[id] = true+ if _, err := testHandler.Queries.AckTaskSupplementDelivered(context.Background(), db.AckTaskSupplementDeliveredParams{+ TaskID: parseUUID(fixture.taskID), CommentID: claimed.CommentID,+ }); err != nil {+ t.Fatalf("ack %s: %v", id, err)+ }+ }+ if len(seen) != additions {+ t.Fatalf("claimed %d unique comments, want %d", len(seen), additions)+ }+ if _, err := testHandler.Queries.ClaimNextTaskSupplement(context.Background(), parseUUID(fixture.taskID)); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("extra claim = %v, want no rows", err)+ }+ if delivered := dbfx.Count(t, `SELECT count(*) FROM task_supplement WHERE task_id = $1 AND status = 'delivered'`, fixture.taskID); delivered != additions {+ t.Fatalf("delivered receipts = %d, want %d", delivered, additions)+ }++ var taskCount int+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, fixture.issueID).Scan(&taskCount)+ if taskCount != 1 {+ t.Fatalf("concurrent additions created %d runs, want one", taskCount)+ }+}++func TestTaskSupplementConcurrentDuplicateSubmissionsAndRetries(t *testing.T) {+ fixture := newSupplementFixture(t, "codex", "running", true)+ const attempts = 10+ responses := make(chan *testutil.Response, attempts)+ var wg sync.WaitGroup+ for i := 0; i < attempts; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ responses <- supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-888888888888", "duplicate addition")+ }()+ }+ wg.Wait()+ close(responses)+ var commentID string+ for response := range responses {+ var comment CommentResponse+ response.WantOneOf(http.StatusOK, http.StatusCreated).JSON(&comment)+ if comment.SupplementTaskID != fixture.taskID || comment.SupplementStatus != "pending" {+ t.Fatalf("submission receipt = %#v", comment)+ }+ if commentID != "" && commentID != comment.ID {+ t.Fatalf("duplicate submission created %s, want %s", comment.ID, commentID)+ }+ commentID = comment.ID+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM task_supplement WHERE task_id = $1`, fixture.taskID); n != 1 {+ t.Fatalf("duplicate submissions created %d receipts", n)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1 AND content = 'duplicate addition'`, fixture.issueID); n != 1 {+ t.Fatalf("duplicate submissions left %d comments", n)+ }+ claim, err := testHandler.Queries.ClaimNextTaskSupplement(context.Background(), parseUUID(fixture.taskID))+ if err != nil {+ t.Fatal(err)+ }+ if _, err := testHandler.Queries.AckTaskSupplementFailed(context.Background(), db.AckTaskSupplementFailedParams{+ TaskID: parseUUID(fixture.taskID), CommentID: claim.CommentID,+ FailureReason: pgtype.Text{String: protocol.TaskSupplementFailureProviderRejected, Valid: true},+ }); err != nil {+ t.Fatal(err)+ }+ responses = make(chan *testutil.Response, attempts)+ for i := 0; i < attempts; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ req := withURLParams(newRequest(http.MethodPost, "/retry", nil),+ "id", fixture.issueID, "taskId", fixture.taskID, "commentId", commentID)+ responses <- testutil.Call(t, testHandler.RetryTaskSupplement, req)+ }()+ }+ wg.Wait()+ close(responses)+ for response := range responses {+ response.Want(http.StatusOK)+ }+ retried, err := testHandler.Queries.ClaimNextTaskSupplement(context.Background(), parseUUID(fixture.taskID))+ if err != nil || retried.CommentID != claim.CommentID || retried.AttemptCount != 2 {+ t.Fatalf("retry claim = %#v: %v", retried, err)+ }+ if _, err := testHandler.Queries.ClaimNextTaskSupplement(context.Background(), parseUUID(fixture.taskID)); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("duplicate retry left another claim: %v", err)+ }+ ack := db.AckTaskSupplementDeliveredParams{TaskID: parseUUID(fixture.taskID), CommentID: claim.CommentID}+ firstAck, err := testHandler.Queries.AckTaskSupplementDelivered(context.Background(), ack)+ if err != nil || firstAck.Status != "delivered" || !firstAck.DeliveredAt.Valid {+ t.Fatalf("delivery receipt = %#v: %v", firstAck, err)+ }+ secondAck, err := testHandler.Queries.AckTaskSupplementDelivered(context.Background(), ack)+ if err != nil || !secondAck.DeliveredAt.Valid || secondAck.DeliveredAt != firstAck.DeliveredAt {+ t.Fatalf("duplicate acknowledgement changed receipt: %#v: %v", secondAck, err)+ }+}++func TestTaskSupplementTimestampOrderAndCommentIDTieBreak(t *testing.T) {+ for _, sameTime := range []bool{false, true} {+ t.Run(fmt.Sprintf("same timestamp=%v", sameTime), func(t *testing.T) {+ fixture := newSupplementFixture(t, "codex", "running", true)+ var first, second CommentResponse+ supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-666666666666", "first").Want(http.StatusCreated).JSON(&first)+ supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-777777777777", "second").Want(http.StatusCreated).JSON(&second)+ firstTime := time.Date(2026, 9, 22, 1, 0, 0, 0, time.UTC)+ secondTime := firstTime.Add(time.Second)+ want := []string{first.ID, second.ID}+ if sameTime {+ secondTime = firstTime+ slices.Sort(want)+ } else {+ // Deliberately invert creation order: timestamps, not a hidden+ // allocation sequence, must drive both metadata and claims.+ firstTime, secondTime = secondTime, firstTime+ want = []string{second.ID, first.ID}+ }+ dbfx.Exec(t, `UPDATE task_supplement SET created_at = $2 WHERE comment_id = $1`, first.ID, firstTime)+ dbfx.Exec(t, `UPDATE task_supplement SET created_at = $2 WHERE comment_id = $1`, second.ID, secondTime)+ rows, err := testHandler.Queries.ListTaskSupplementMetadata(context.Background(), db.ListTaskSupplementMetadataParams{+ WorkspaceID: parseUUID(testWorkspaceID), TaskIds: []pgtype.UUID{parseUUID(fixture.taskID)},+ })+ if err != nil || len(rows) != 1 {+ t.Fatalf("metadata rows=%v: %v", rows, err)+ }+ if got := uuidsToStrings(rows[0].CommentIds); !slices.Equal(got, want) {+ t.Fatalf("metadata order=%v, want %v", got, want)+ }+ for _, id := range want {+ claim, err := testHandler.Queries.ClaimNextTaskSupplement(context.Background(), parseUUID(fixture.taskID))+ if err != nil || uuidToString(claim.CommentID) != id {+ t.Fatalf("claim=%s, want %s: %v", uuidToString(claim.CommentID), id, err)+ }+ }+ })+ }+}++func TestTaskSupplementTerminalRaceCreatesNothing(t *testing.T) {+ for _, status := range []string{"completed", "cancelled"} {+ t.Run(status, func(t *testing.T) {+ assertTaskSupplementTerminalRaceCreatesNothing(t, status)+ })+ }+}++func assertTaskSupplementTerminalRaceCreatesNothing(t *testing.T, terminalStatus string) {+ t.Helper()+ fixture := newSupplementFixture(t, "codex", "running", true)+ tx, err := testPool.Begin(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(context.Background())+ if _, err := tx.Exec(context.Background(), `SELECT id FROM agent_task_queue WHERE id = $1 FOR UPDATE`, fixture.taskID); err != nil {+ t.Fatal(err)+ }+ result := make(chan error, 1)+ go func() {+ _, createErr := testHandler.Queries.CreateTaskSupplement(context.Background(), db.CreateTaskSupplementParams{+ TaskID: parseUUID(fixture.taskID), IssueID: parseUUID(fixture.issueID), WorkspaceID: parseUUID(testWorkspaceID),+ AuthorID: parseUUID(testUserID), Content: "must not orphan",+ ClientRequestID: parseUUID("0199a4e8-22ce-7b01-bba5-444444444444"),+ })+ result <- createErr+ }()+ if _, err := tx.Exec(context.Background(), `UPDATE agent_task_queue SET status = $2, completed_at = now() WHERE id = $1`, fixture.taskID, terminalStatus); err != nil {+ t.Fatal(err)+ }+ if err := tx.Commit(context.Background()); err != nil {+ t.Fatal(err)+ }+ select {+ case err := <-result:+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("race create error = %v, want no rows", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("race create remained blocked")+ }+ var comments, supplements int+ dbfx.QueryRow(t, `SELECT count(*) FROM comment WHERE issue_id = $1 AND content = 'must not orphan'`, fixture.issueID).Scan(&comments)+ dbfx.QueryRow(t, `SELECT count(*) FROM task_supplement WHERE task_id = $1`, fixture.taskID).Scan(&supplements)+ if comments != 0 || supplements != 0 {+ t.Fatalf("terminal race left comments=%d supplements=%d", comments, supplements)+ }+}++func TestTaskSupplementStopRemainsIndependent(t *testing.T) {+ fixture := newSupplementFixture(t, "codex", "running", true)+ var comment CommentResponse+ supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-777777777777", "pending when stopped").+ Want(http.StatusCreated).JSON(&comment)+ cancelReq := withURLParams(newRequest(http.MethodPost, "/cancel", nil),+ "id", fixture.issueID, "taskId", fixture.taskID)+ testutil.Call(t, testHandler.CancelTask, cancelReq).Want(http.StatusOK)+ receipt, err := testHandler.Queries.GetTaskSupplementByComment(context.Background(), db.GetTaskSupplementByCommentParams{+ CommentID: parseUUID(comment.ID), WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil || receipt.Status != "failed" || receipt.FailureReason.String != "turn_ended" {+ t.Fatalf("stop receipt = %#v, err %v", receipt, err)+ }+ var taskCount int+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, fixture.issueID).Scan(&taskCount)+ if taskCount != 1 {+ t.Fatalf("stop or supplement created %d runs, want one", taskCount)+ }+}++func TestTaskSupplementPermissionAndTenantIsolation(t *testing.T) {+ fixture := newSupplementFixture(t, "codex", "running", true)+ otherUser := dbfx.Insert(t, "user", testutil.Cols{"name": "No Invoke", "email": "[email protected]"})+ dbfx.Member(t, testWorkspaceID, otherUser, "member")+ req := newRequestAs(otherUser, http.MethodPost, "/supplements", map[string]any{+ "client_request_id": "0199a4e8-22ce-7b01-bba5-555555555555", "content": "not allowed",+ })+ testutil.Call(t, testHandler.CreateTaskSupplement,+ withURLParams(req, "id", fixture.issueID, "taskId", fixture.taskID)).Want(http.StatusForbidden)++ foreignIssueID, foreignTaskID := setupForeignWorkspaceFixture(t)+ crossTenant := newRequest(http.MethodPost, "/api/issues/"+foreignIssueID+"/tasks/"+foreignTaskID+"/supplements", map[string]any{+ "client_request_id": "0199a4e8-22ce-7b01-bba5-666666666666", "content": "cross tenant",+ })+ testutil.Call(t, testHandler.CreateTaskSupplement,+ withURLParams(crossTenant, "id", foreignIssueID, "taskId", foreignTaskID)).Want(http.StatusNotFound)++ var count int+ dbfx.QueryRow(t, `SELECT count(*) FROM task_supplement WHERE task_id = $1`, fixture.taskID).Scan(&count)+ if count != 0 {+ t.Fatalf("denied requests created %d supplements", count)+ }+}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 3daa648679..f5cdce9c9d 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -121,6 +121,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"squad_member": workspaceDelete,"sys_cron_executions": workspaceDeleteKeep,"task_message": workspaceDelete,+ "task_supplement": workspaceDelete,+ "task_supplement_capability": workspaceDelete,"task_token": workspaceDelete,"task_usage": workspaceDelete,"task_usage_hourly": workspaceDelete,diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex bc22b6458e..f1a8a03190 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -4165,8 +4165,12 @@ func (s *TaskService) maybeLogClaimSlow(agentID pgtype.UUID, outcome string, sta// StartTask transitions a dispatched task to running.// Issue status is NOT changed here — the agent manages it via the CLI.-func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.AgentTaskQueue, error) {- task, err := s.Queries.StartAgentTask(ctx, taskID)+func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID, supplementSupport ...bool) (*db.AgentTaskQueue, error) {+ enableTaskSupplement := len(supplementSupport) > 0 && supplementSupport[0]+ task, err := s.Queries.StartAgentTaskWithSupplement(ctx, db.StartAgentTaskWithSupplementParams{+ TaskID: taskID,+ EnableTaskSupplement: enableTaskSupplement,+ })if err != nil {return nil, fmt.Errorf("start task: %w", err)}@@ -4177,7 +4181,7 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag// StartTaskForClaim serializes the ownership check and transition with reclaim,// cancellation and other start requests. A replay linearizes at the locked read;// a cancellation that commits later can still cancel the acknowledged task.-func (s *TaskService) StartTaskForClaim(ctx context.Context, claim db.LockAgentTaskStartClaimParams) (*db.AgentTaskQueue, error) {+func (s *TaskService) StartTaskForClaim(ctx context.Context, claim db.LockAgentTaskStartClaimParams, supplementSupport ...bool) (*db.AgentTaskQueue, error) {if !claim.ID.Valid || !claim.RuntimeID.Valid || !claim.DispatchedAt.Valid {return nil, fmt.Errorf("start task: incomplete claim")}@@ -4193,7 +4197,10 @@ func (s *TaskService) StartTaskForClaim(ctx context.Context, claim db.LockAgentT}replay := task.Status == "running"if !replay {- task, err = qtx.StartAgentTask(ctx, task.ID)+ task, err = qtx.StartAgentTaskWithSupplement(ctx, db.StartAgentTaskWithSupplementParams{+ TaskID: task.ID,+ EnableTaskSupplement: len(supplementSupport) > 0 && supplementSupport[0],+ })if err != nil {return nil, fmt.Errorf("start claimed task: %w", err)}diff --git a/server/migrations/538_task_supplement.down.sql b/server/migrations/538_task_supplement.down.sqlnew file mode 100644index 0000000000..c0272290a1--- /dev/null+++ b/server/migrations/538_task_supplement.down.sql@@ -0,0 +1,4 @@+DROP TRIGGER IF EXISTS trg_settle_terminal_task_supplements ON agent_task_queue;+DROP FUNCTION IF EXISTS settle_terminal_task_supplements();+DROP TABLE IF EXISTS task_supplement;+DROP TABLE IF EXISTS task_supplement_capability;diff --git a/server/migrations/538_task_supplement.up.sql b/server/migrations/538_task_supplement.up.sqlnew file mode 100644index 0000000000..bd0abe6697--- /dev/null+++ b/server/migrations/538_task_supplement.up.sql@@ -0,0 +1,52 @@+-- Keep negotiated capability outside agent_task_queue. Older application+-- builds use SELECT * for that hot table, so adding columns would make a+-- server rollback fail while scanning otherwise-valid task rows.+CREATE TABLE task_supplement_capability (+ task_id UUID NOT NULL,+ workspace_id UUID NOT NULL,+ issue_id UUID NOT NULL,+ capability TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++-- Durable delivery receipts for explicit, human-authored additions to one+-- exact run. Relationships intentionally have no database foreign keys: task,+-- issue, comment and workspace teardown remain application-owned and never+-- acquire a new cascade/lock tree.+CREATE TABLE task_supplement (+ task_id UUID NOT NULL,+ workspace_id UUID NOT NULL,+ issue_id UUID NOT NULL,+ comment_id UUID NOT NULL,+ author_id UUID NOT NULL,+ client_request_id UUID NOT NULL,+ status TEXT NOT NULL CHECK (status IN ('pending', 'delivering', 'delivered', 'failed')),+ failure_reason TEXT,+ attempt_count INTEGER NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ delivered_at TIMESTAMPTZ+);++-- Terminal transition and receipt settlement share the task row update's+-- transaction and lock. This prevents a run from ending between two+-- application statements and leaving a pending receipt that can never move.+CREATE FUNCTION settle_terminal_task_supplements() RETURNS trigger+LANGUAGE plpgsql AS $$+BEGIN+ IF OLD.status IN ('queued', 'deferred', 'dispatched', 'waiting_local_directory', 'running')+ AND NEW.status IN ('completed', 'failed', 'cancelled') THEN+ UPDATE task_supplement+ SET status = 'failed',+ failure_reason = 'turn_ended',+ updated_at = now()+ WHERE task_id = NEW.id+ AND status IN ('pending', 'delivering');+ END IF;+ RETURN NEW;+END;+$$;++CREATE TRIGGER trg_settle_terminal_task_supplements+AFTER UPDATE OF status ON agent_task_queue+FOR EACH ROW EXECUTE FUNCTION settle_terminal_task_supplements();diff --git a/server/migrations/539_task_supplement_request_index.down.sql b/server/migrations/539_task_supplement_request_index.down.sqlnew file mode 100644index 0000000000..6f5fb2a4c8--- /dev/null+++ b/server/migrations/539_task_supplement_request_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS task_supplement_task_request_uidx;diff --git a/server/migrations/539_task_supplement_request_index.up.sql b/server/migrations/539_task_supplement_request_index.up.sqlnew file mode 100644index 0000000000..45201a6c09--- /dev/null+++ b/server/migrations/539_task_supplement_request_index.up.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS task_supplement_task_request_uidx+ ON task_supplement (task_id, client_request_id);diff --git a/server/migrations/540_task_supplement_capability_index.down.sql b/server/migrations/540_task_supplement_capability_index.down.sqlnew file mode 100644index 0000000000..1430f35ad2--- /dev/null+++ b/server/migrations/540_task_supplement_capability_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS task_supplement_capability_task_uidx;diff --git a/server/migrations/540_task_supplement_capability_index.up.sql b/server/migrations/540_task_supplement_capability_index.up.sqlnew file mode 100644index 0000000000..e89be0f086--- /dev/null+++ b/server/migrations/540_task_supplement_capability_index.up.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS task_supplement_capability_task_uidx+ ON task_supplement_capability (task_id);diff --git a/server/migrations/541_task_supplement_comment_index.down.sql b/server/migrations/541_task_supplement_comment_index.down.sqlnew file mode 100644index 0000000000..24a97466bc--- /dev/null+++ b/server/migrations/541_task_supplement_comment_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS task_supplement_comment_uidx;diff --git a/server/migrations/541_task_supplement_comment_index.up.sql b/server/migrations/541_task_supplement_comment_index.up.sqlnew file mode 100644index 0000000000..d97a4eb66b--- /dev/null+++ b/server/migrations/541_task_supplement_comment_index.up.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS task_supplement_comment_uidx+ ON task_supplement (comment_id);diff --git a/server/migrations/542_task_supplement_primary_key.down.sql b/server/migrations/542_task_supplement_primary_key.down.sqlnew file mode 100644index 0000000000..1b6d8b0d6d--- /dev/null+++ b/server/migrations/542_task_supplement_primary_key.down.sql@@ -0,0 +1,3 @@+-- Roll back the supplement migration batch together (538-543). PostgreSQL+-- drops the attached index with the constraint; 541 recreates it on upgrade.+ALTER TABLE task_supplement DROP CONSTRAINT IF EXISTS task_supplement_pkey;diff --git a/server/migrations/542_task_supplement_primary_key.up.sql b/server/migrations/542_task_supplement_primary_key.up.sqlnew file mode 100644index 0000000000..dfd18aa281--- /dev/null+++ b/server/migrations/542_task_supplement_primary_key.up.sql@@ -0,0 +1,4 @@+-- Reuse the concurrently built unique index; do not build another index while+-- holding the table lock. Deploy only after the complete migration batch.+ALTER TABLE task_supplement+ ADD CONSTRAINT task_supplement_pkey PRIMARY KEY USING INDEX task_supplement_comment_uidx;diff --git a/server/migrations/543_task_supplement_teardown_guard.down.sql b/server/migrations/543_task_supplement_teardown_guard.down.sqlnew file mode 100644index 0000000000..7d06c56a9e--- /dev/null+++ b/server/migrations/543_task_supplement_teardown_guard.down.sql@@ -0,0 +1,4 @@+DROP TRIGGER IF EXISTS trg_settle_terminal_task_supplements ON agent_task_queue;+CREATE TRIGGER trg_settle_terminal_task_supplements+AFTER UPDATE OF status ON agent_task_queue+FOR EACH ROW EXECUTE FUNCTION settle_terminal_task_supplements();diff --git a/server/migrations/543_task_supplement_teardown_guard.up.sql b/server/migrations/543_task_supplement_teardown_guard.up.sqlnew file mode 100644index 0000000000..db8bba7448--- /dev/null+++ b/server/migrations/543_task_supplement_teardown_guard.up.sql@@ -0,0 +1,8 @@+-- Receipt state follows the terminal transition atomically. This does not+-- delete dependents: issue/workspace/comment deletion remains application-owned.+DROP TRIGGER IF EXISTS trg_settle_terminal_task_supplements ON agent_task_queue;+CREATE TRIGGER trg_settle_terminal_task_supplements+AFTER UPDATE OF status ON agent_task_queue+FOR EACH ROW+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')+EXECUTE FUNCTION settle_terminal_task_supplements();diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 2658bb445b..5545440c3e 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -24,8 +24,11 @@ type Backend interface {// ExecOptions configures a single execution.type ExecOptions struct {- Cwd string- Model string+ // EnableTaskSupplement installs provider hooks only for runs whose daemon/server+ // capability handshake enabled additional messages.+ EnableTaskSupplement bool+ Cwd string+ Model string// SystemPrompt carries the Multica runtime brief for the few providers// that cannot pick it up from disk. The daemon leaves it empty for every// other provider (see daemon.providerNeedsInlineSystemPrompt), because the@@ -56,7 +59,7 @@ type ExecOptions struct {// tool continues to use the separate tool watchdog budget.IdleWatchdogTimeout time.Duration// HandshakeTimeout bounds startup RPCs for providers with a long-lived- // protocol transport. It is currently consumed by Codex app-server;+ // protocol transport, including Codex app-server and Claude SDK hooks;// zero uses the provider default rather than disabling the bound.HandshakeTimeout time.Duration// TurnInterruptTimeout bounds how long the Codex backend waits for the@@ -147,6 +150,17 @@ func runContext(ctx context.Context, timeout time.Duration) (context.Context, co// Session represents a running agent execution.type Session struct {+ // Supplement delivers an additional human instruction to the currently+ // active provider turn. Nil means the backend cannot safely do so.+ // Adapters bound their own transport calls; a hook-based adapter may wait+ // for the next provider boundary until ctx or the execution is cancelled.+ Supplement func(context.Context, string) error+ // SupplementReady reports whether Supplement currently targets a live,+ // provider-confirmed turn. The daemon must not claim durable input before+ // this becomes true: claiming during provider initialization would convert+ // a transient startup window into a user-visible delivery failure. Nil is+ // fail-closed and means no run-scoped input may be claimed.+ SupplementReady func() bool// 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 adiff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex f66bae1211..59be6a9259 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -103,8 +103,18 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptcancel()return nil, fmt.Errorf("claude stdin pipe: %w", err)}+ inputWriter := &claudeInputWriter{w: stdin}+ var supplements *claudeSupplementSession+ if opts.EnableTaskSupplement {+ supplements = newClaudeSupplementSession(runCtx)+ }var closeStdinOnce sync.Once- closeStdin := func() { closeStdinOnce.Do(func() { _ = stdin.Close() }) }+ closeStdin := func() {+ closeStdinOnce.Do(func() { _ = stdin.Close() })+ if supplements != nil {+ supplements.end()+ }+ }// Capture stderr into both the daemon log (as before) and a bounded tail// buffer so we can include the last few KB in Result.Error when claude// exits unexpectedly. Without the tail, an exit-code-only failure looks@@ -147,9 +157,18 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// timeout.writeDone := make(chan error, 1)go func() {- err := writeClaudeInput(stdin, prompt)+ if supplements != nil {+ if initErr := supplements.initialize(inputWriter, claudeSupplementHandshakeTimeout); initErr != nil {+ b.cfg.Logger.Warn("Claude additional messages unavailable; continuing normally", "error", initErr)+ supplements.end()+ }+ }+ err := writeClaudeInput(inputWriter, prompt)if err != nil {closeStdin()+ if supplements != nil {+ cancel()+ }}writeDone <- err}()@@ -177,6 +196,8 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptassistantEventCount := 0toolUseCount := 0unreadableAssistantCount := 0+ controlErrors := make(chan error, 1)+ var controlWrites sync.WaitGroup// On cancellation / timeout, terminate claude (and every MCP server and// tool subprocess it spawned) BEFORE unblocking the scanner. EOF stdin@@ -262,7 +283,29 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt})}case "control_request":- b.handleControlRequest(msg, stdin)+ var reply func(io.Writer) error+ if supplements != nil {+ reply, _ = supplements.prepareHook(msg)+ }+ controlWrites.Add(1)+ go func(msg claudeSDKMessage, reply func(io.Writer) error) {+ defer controlWrites.Done()+ if reply == nil {+ b.handleControlRequest(msg, inputWriter)+ return+ }+ if err := reply(inputWriter); err != nil {+ select {+ case controlErrors <- err:+ default:+ }+ cancel()+ }+ }(msg, reply)+ case "control_response":+ if supplements != nil {+ supplements.handleResponse(msg.Response)+ }}}scanErr := scanner.Err()@@ -287,6 +330,18 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// time cmd has exited, the prompt write has either succeeded, hit a// broken pipe, or been unblocked by the kill that ended cmd.writeErr := <-writeDone+ controlWrites.Wait()+ if writeErr == nil {+ select {+ case writeErr = <-controlErrors:+ default:+ }+ }+ // Internal protocol failures cancel the process to unblock its pipes.+ // Preserve the actual failure instead of reporting a user cancellation.+ if supplements != nil && writeErr != nil && ctx.Err() == nil && terminalReasonError == "" && !errors.Is(runCtx.Err(), context.DeadlineExceeded) {+ terminalReasonError = fmt.Sprintf("claude input/control protocol failed: %v", writeErr)+ }completionGuardError := ""if sawAsyncLaunch {@@ -361,7 +416,12 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}}()- return &Session{Messages: msgCh, Result: resCh}, nil+ session := &Session{Messages: msgCh, Result: resCh}+ if supplements != nil {+ session.Supplement = supplements.supplement+ session.SupplementReady = supplements.ready+ }+ return session, nil}func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage, seenUsage map[string]struct{}) assistantTurn {@@ -574,6 +634,7 @@ type claudeSDKMessage struct {// control request fieldsRequestID string `json:"request_id,omitempty"`Request json.RawMessage `json:"request,omitempty"`+ Response json.RawMessage `json:"response,omitempty"`}type claudeLogEntry struct {diff --git a/server/pkg/agent/claude_deadlock_test.go b/server/pkg/agent/claude_deadlock_test.goindex b99535c8dd..0e19cebc33 100644--- a/server/pkg/agent/claude_deadlock_test.go+++ b/server/pkg/agent/claude_deadlock_test.go@@ -59,6 +59,9 @@ func TestMain(m *testing.M) {case "usage_fixture":runFakeClaudeUsageFixture()os.Exit(0)+ case "supplement":+ runFakeClaudeSupplement()+ os.Exit(0)case "startup_stdout_burst":runFakeClaudeStartupStdoutBurst()os.Exit(0)diff --git a/server/pkg/agent/claude_supplement.go b/server/pkg/agent/claude_supplement.gonew file mode 100644index 0000000000..0a7dcba4ca--- /dev/null+++ b/server/pkg/agent/claude_supplement.go@@ -0,0 +1,239 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "slices"+ "strings"+ "sync"+ "time"+)++const (+ claudeSupplementInitializeID = "multica-supplement-initialize"+ claudeSupplementHandshakeTimeout = 3 * time.Second+)++// All four context events support additionalContext; Stop uses decision/reason.+// https://code.claude.com/docs/en/hooks#add-context-for-claude+var claudeSupplementEvents = []string{"UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Stop"}++// Claude has no conditional, current-turn-only user input request. SDK hooks+// instead insert context while the provider is waiting at a turn boundary.+// A Stop hook with pending input continues the same loop; an empty Stop closes+// admission before releasing Claude. No supplement is ever a new user prompt.+// Wire contract: anthropics/claude-agent-sdk-python, _internal/query.py.+type claudeSupplementSession struct {+ ctx context.Context+ mu sync.Mutex+ active bool+ started bool+ ended bool+ pending []*claudeSupplementInput+ initialized chan error+}++type claudeSupplementInput struct {+ ctx context.Context+ text string+ done chan error+ writing bool+}++func newClaudeSupplementSession(ctx context.Context) *claudeSupplementSession {+ return &claudeSupplementSession{ctx: ctx, initialized: make(chan error, 1)}+}++func (s *claudeSupplementSession) initialize(w io.Writer, timeout time.Duration) error {+ if timeout <= 0 {+ timeout = 60 * time.Second+ }+ ctx, cancel := context.WithTimeout(s.ctx, timeout)+ defer cancel()+ hooks := make(map[string]any, len(claudeSupplementEvents))+ for _, event := range claudeSupplementEvents {+ hooks[event] = []any{map[string]any{"hookCallbackIds": []string{"multica-supplement-" + event}}}+ }+ if err := writeClaudeFrame(w, map[string]any{+ "type": "control_request", "request_id": claudeSupplementInitializeID,+ "request": map[string]any{"subtype": "initialize", "hooks": hooks},+ }); err != nil {+ return err+ }+ select {+ case err := <-s.initialized:+ return err+ case <-ctx.Done():+ return fmt.Errorf("claude supplement initialization: %w", ctx.Err())+ }+}++func (s *claudeSupplementSession) handleResponse(raw json.RawMessage) {+ var response struct {+ RequestID string `json:"request_id"`+ Subtype string `json:"subtype"`+ Error string `json:"error"`+ }+ if json.Unmarshal(raw, &response) != nil || response.RequestID != claudeSupplementInitializeID {+ return+ }+ var err error+ if response.Subtype != "success" {+ err = fmt.Errorf("claude supplement initialization rejected: %s", response.Error)+ }+ select {+ case s.initialized <- err:+ default:+ }+}++func (s *claudeSupplementSession) ready() bool {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.active && !s.ended && s.ctx.Err() == nil+}++func (s *claudeSupplementSession) supplement(ctx context.Context, text string) error {+ input := &claudeSupplementInput{ctx: ctx, text: text, done: make(chan error, 1)}+ s.mu.Lock()+ if err := ctx.Err(); err != nil {+ s.mu.Unlock()+ return err+ }+ if s.ended || s.ctx.Err() != nil {+ s.mu.Unlock()+ return context.Canceled+ }+ if !s.active {+ started := s.started+ s.mu.Unlock()+ if started {+ return context.Canceled+ }+ return errors.New("claude turn has not started")+ }+ s.pending = append(s.pending, input)+ s.mu.Unlock()+ select {+ case err := <-input.done:+ return err+ case <-ctx.Done():+ case <-s.ctx.Done():+ }+ // Serialize cancellation with hook delivery. If delivery won, preserve its+ // outcome; otherwise remove the message so a later hook cannot replay it.+ s.mu.Lock()+ if input.writing {+ // Once a hook owns the frame, its write decides delivery. Cancellation+ // closes the process pipe; it must not report failure before that write.+ s.mu.Unlock()+ return <-input.done+ }+ defer s.mu.Unlock()+ select {+ case err := <-input.done:+ return err+ default:+ }+ for i, pending := range s.pending {+ if pending == input {+ s.pending = append(s.pending[:i], s.pending[i+1:]...)+ break+ }+ }+ if err := ctx.Err(); err != nil {+ return err+ }+ return s.ctx.Err()+}++func (s *claudeSupplementSession) end() {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.ended, s.active = true, false+ for _, input := range s.pending {+ input.done <- context.Canceled+ }+ s.pending = nil+ select {+ case s.initialized <- context.Canceled:+ default:+ }+}++// prepareHook claims pending input synchronously, but leaves pipe I/O to the+// caller's writer goroutine so stdout can keep draining under backpressure.+func (s *claudeSupplementSession) prepareHook(msg claudeSDKMessage) (func(io.Writer) error, bool) {+ var req struct {+ Subtype string `json:"subtype"`+ CallbackID string `json:"callback_id"`+ Input struct {+ Event string `json:"hook_event_name"`+ AgentID string `json:"agent_id"`+ } `json:"input"`+ }+ if json.Unmarshal(msg.Request, &req) != nil || req.Subtype != "hook_callback" {+ return nil, false+ }+ output := map[string]any{}+ s.mu.Lock()+ // Hook registrations are inherited by subagents. Only the main loop may+ // consume instructions addressed to this Multica task.+ owned := slices.Contains(claudeSupplementEvents, req.Input.Event) && req.CallbackID == "multica-supplement-"+req.Input.Event+ var delivered []*claudeSupplementInput+ if owned && req.Input.AgentID == "" && msg.ParentToolUseID == "" && !s.ended && s.ctx.Err() == nil {+ s.started = true+ var texts []string+ for _, input := range s.pending {+ if err := input.ctx.Err(); err != nil {+ input.done <- err+ continue+ }+ delivered = append(delivered, input)+ input.writing = true+ texts = append(texts, input.text)+ }+ s.pending = nil+ s.active = req.Input.Event != "Stop" || len(delivered) > 0+ if len(delivered) > 0 {+ text := strings.Join(texts, "\n\n")+ if req.Input.Event == "Stop" {+ output = map[string]any{"decision": "block", "reason": text}+ } else {+ output["hookSpecificOutput"] = map[string]any{"hookEventName": req.Input.Event, "additionalContext": text}+ }+ }+ }+ frame := map[string]any{+ "type": "control_response",+ "response": map[string]any{"subtype": "success", "request_id": msg.RequestID, "response": output},+ }+ s.mu.Unlock()+ return func(w io.Writer) error {+ err := writeClaudeFrame(w, frame)+ for _, input := range delivered {+ input.done <- err+ }+ return err+ }, true+}++func writeClaudeFrame(w io.Writer, frame any) error {+ return json.NewEncoder(w).Encode(frame)+}++// The initial prompt and SDK control replies share stdin. Serialize entire+// frames, including prompts larger than a pipe's atomic-write limit.+type claudeInputWriter struct {+ mu sync.Mutex+ w io.Writer+}++func (w *claudeInputWriter) Write(data []byte) (int, error) {+ w.mu.Lock()+ defer w.mu.Unlock()+ return w.w.Write(data)+}diff --git a/server/pkg/agent/claude_supplement_test.go b/server/pkg/agent/claude_supplement_test.gonew file mode 100644index 0000000000..d6de275ba0--- /dev/null+++ b/server/pkg/agent/claude_supplement_test.go@@ -0,0 +1,395 @@+package agent++import (+ "bufio"+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os"+ "strings"+ "testing"+ "time"+)++func (s *claudeSupplementSession) handleHook(msg claudeSDKMessage, w io.Writer) (bool, error) {+ reply, handled := s.prepareHook(msg)+ if !handled {+ return false, nil+ }+ return true, reply(w)+}++func claudeSupplementHook(event, agentID string) claudeSDKMessage {+ request, _ := json.Marshal(map[string]any{+ "subtype": "hook_callback", "callback_id": "multica-supplement-" + event,+ "input": map[string]any{"hook_event_name": event, "agent_id": agentID},+ })+ return claudeSDKMessage{Type: "control_request", RequestID: "hook-request", Request: request}+}++func activeClaudeSupplementSession(t *testing.T) *claudeSupplementSession {+ t.Helper()+ s := newClaudeSupplementSession(t.Context())+ if s.ready() {+ t.Fatal("supplements ready before provider hook")+ }+ if _, err := s.handleHook(claudeSupplementHook("UserPromptSubmit", ""), io.Discard); err != nil {+ t.Fatal(err)+ }+ if !s.ready() {+ t.Fatal("provider hook did not enable supplements")+ }+ t.Cleanup(s.end)+ return s+}++func queueClaudeSupplement(t *testing.T, s *claudeSupplementSession, ctx context.Context, text string, count int) <-chan error {+ t.Helper()+ done := make(chan error, 1)+ go func() { done <- s.supplement(ctx, text) }()+ deadline := time.After(3 * time.Second)+ for {+ s.mu.Lock()+ queued := len(s.pending)+ s.mu.Unlock()+ if queued == count {+ return done+ }+ select {+ case err := <-done:+ t.Fatalf("supplement returned before provider accepted it: %v", err)+ case <-deadline:+ t.Fatal("supplement was not queued")+ case <-time.After(time.Millisecond):+ }+ }+}++func TestClaudeSupplementDeliveredAtProviderBoundary(t *testing.T) {+ for _, event := range claudeSupplementEvents {+ t.Run(event, func(t *testing.T) {+ s := activeClaudeSupplementSession(t)+ first := queueClaudeSupplement(t, s, t.Context(), "Keep the original goal; add A.", 1)+ second := queueClaudeSupplement(t, s, t.Context(), "Also add B.", 2)+ select {+ case <-first:+ t.Fatal("local queueing must not acknowledge delivery")+ default:+ }+ var wire bytes.Buffer+ if handled, err := s.handleHook(claudeSupplementHook(event, ""), &wire); !handled || err != nil {+ t.Fatalf("hook: handled=%v err=%v", handled, err)+ }+ for _, done := range []<-chan error{first, second} {+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ }+ var frame struct {+ Type string `json:"type"`+ Response struct {+ RequestID string `json:"request_id"`+ Response struct {+ Decision string `json:"decision"`+ Reason string `json:"reason"`+ Hook struct {+ Context string `json:"additionalContext"`+ } `json:"hookSpecificOutput"`+ } `json:"response"`+ } `json:"response"`+ }+ if err := json.Unmarshal(wire.Bytes(), &frame); err != nil {+ t.Fatal(err)+ }+ if frame.Type != "control_response" || frame.Response.RequestID != "hook-request" {+ t.Fatalf("must reply to the provider hook, not send a new prompt: %s", wire.Bytes())+ }+ text := frame.Response.Response.Hook.Context+ if event == "Stop" {+ if frame.Response.Response.Decision != "block" {+ t.Fatal("pending input must keep the current loop running")+ }+ text = frame.Response.Response.Reason+ }+ if text != "Keep the original goal; add A.\n\nAlso add B." {+ t.Fatalf("delivered instructions = %q", text)+ }+ if !s.ready() {+ t.Fatal("delivery must allow subsequent supplements")+ }+ })+ }+}++func TestClaudeSupplementRejectsAfterStopAndEnd(t *testing.T) {+ s := activeClaudeSupplementSession(t)+ _, _ = s.handleHook(claudeSupplementHook("Stop", ""), io.Discard)+ if s.ready() {+ t.Fatal("empty Stop must close admission before result arrives")+ }+ if err := s.supplement(t.Context(), "too late"); err == nil {+ t.Fatal("supplement accepted after Stop")+ }+ s.end()+ _, _ = s.handleHook(claudeSupplementHook("PreToolUse", ""), io.Discard)+ if s.ready() {+ t.Fatal("late events reopened a completed run")+ }+}++func TestClaudeSupplementRacingStopNeverStartsAnotherTurn(t *testing.T) {+ for i := 0; i < 100; i++ {+ s := activeClaudeSupplementSession(t)+ start := make(chan struct{})+ done := make(chan error, 1)+ go func() {+ <-start+ done <- s.supplement(t.Context(), "racing input")+ }()+ var wire bytes.Buffer+ close(start)+ _, err := s.handleHook(claudeSupplementHook("Stop", ""), &wire)+ if err != nil {+ t.Fatal(err)+ }+ select {+ case err := <-done:+ if strings.Contains(wire.String(), "racing input") {+ if err != nil || !strings.Contains(wire.String(), `"decision":"block"`) {+ t.Fatalf("accepted input must continue this loop: err=%v response=%s", err, wire.Bytes())+ }+ } else if !errors.Is(err, context.Canceled) {+ t.Fatalf("Stop won but input was not rejected: %v", err)+ }+ case <-time.After(time.Second):+ t.Fatal("Stop left supplement waiting")+ }+ s.end()+ }+}++func TestClaudeSupplementDoesNotReachSubagent(t *testing.T) {+ s := activeClaudeSupplementSession(t)+ done := queueClaudeSupplement(t, s, t.Context(), "main task only", 1)+ for _, event := range []string{"PreToolUse", "Stop"} {+ var wire bytes.Buffer+ _, _ = s.handleHook(claudeSupplementHook(event, "child-agent"), &wire)+ if strings.Contains(wire.String(), "main task only") {+ t.Fatal("subagent consumed main task supplement")+ }+ }+ select {+ case <-done:+ t.Fatal("subagent acknowledged main task supplement")+ default:+ }+ if !s.ready() {+ t.Fatal("subagent Stop closed the main run")+ }+ _, _ = s.handleHook(claudeSupplementHook("Stop", ""), io.Discard)+ if err := <-done; err != nil {+ t.Fatal(err)+ }+}++func TestClaudeSupplementCancellationCannotDeliverLater(t *testing.T) {+ s := activeClaudeSupplementSession(t)+ ctx, cancel := context.WithCancel(t.Context())+ done := queueClaudeSupplement(t, s, ctx, "cancelled input", 1)+ cancel()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("cancellation: %v", err)+ }+ var wire bytes.Buffer+ _, _ = s.handleHook(claudeSupplementHook("Stop", ""), &wire)+ if strings.Contains(wire.String(), "cancelled input") || strings.Contains(wire.String(), "block") {+ t.Fatalf("cancelled input was delivered: %s", wire.Bytes())+ }+}++func TestClaudeSupplementRunEndReleasesPending(t *testing.T) {+ s := activeClaudeSupplementSession(t)+ done := queueClaudeSupplement(t, s, t.Context(), "pending input", 1)+ s.end()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("run end: %v", err)+ }+}++type failedClaudeInput struct{}++func (failedClaudeInput) Write([]byte) (int, error) { return 0, io.ErrClosedPipe }++func TestClaudeSupplementWriteFailureIsNotDelivery(t *testing.T) {+ s := activeClaudeSupplementSession(t)+ done := queueClaudeSupplement(t, s, t.Context(), "input", 1)+ _, err := s.handleHook(claudeSupplementHook("PostToolUse", ""), failedClaudeInput{})+ if !errors.Is(err, io.ErrClosedPipe) {+ t.Fatalf("write: %v", err)+ }+ if err := <-done; !errors.Is(err, io.ErrClosedPipe) {+ t.Fatalf("delivery: %v", err)+ }+}++// This fake CLI implements the official SDK initialize/hook_callback exchange.+// It accepts exactly one user prompt; every later input must reply to a hook.+func runFakeClaudeSupplement() {+ reader := bufio.NewReader(os.Stdin)+ read := func() map[string]any {+ line, err := reader.ReadBytes('\n')+ if err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(10)+ }+ var frame map[string]any+ if json.Unmarshal(line, &frame) != nil {+ os.Exit(11)+ }+ return frame+ }+ init := read()+ if init["type"] != "control_request" {+ os.Exit(12)+ }+ request := init["request"].(map[string]any)+ hooks := request["hooks"].(map[string]any)+ for _, event := range []string{"UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Stop"} {+ if hooks[event] == nil {+ os.Exit(13)+ }+ }+ if failure := os.Getenv("CLAUDE_SUPPLEMENT_INIT_FAILURE"); failure != "" {+ if failure == "reject" {+ _ = writeClaudeFrame(os.Stdout, map[string]any{"type": "control_response", "response": map[string]any{+ "subtype": "error", "request_id": init["request_id"], "error": "hooks unsupported",+ }})+ }+ // Unsupported hooks disable supplements, but the original goal still runs.+ if prompt := read(); prompt["type"] != "user" {+ os.Exit(19)+ }+ fmt.Println(`{"type":"result","subtype":"success","result":"original goal completed"}`)+ if _, err := reader.ReadBytes('\n'); err != io.EOF {+ os.Exit(19)+ }+ return+ }+ _ = writeClaudeFrame(os.Stdout, map[string]any{"type": "control_response", "response": map[string]any{"subtype": "success", "request_id": init["request_id"], "response": map[string]any{}}})+ prompt := read()+ if prompt["type"] != "user" {+ os.Exit(14)+ }+ hook := func(event string) map[string]any {+ _ = json.NewEncoder(os.Stdout).Encode(claudeSupplementHook(event, ""))+ if event == "PostToolUse" {+ // Fill stdout before reading a hook reply larger than stdin's pipe+ // buffer. A synchronous reply on the stdout reader deadlocks here.+ for range 8 {+ _ = writeClaudeFrame(os.Stdout, map[string]any{"type": "system", "subtype": "backpressure", "padding": strings.Repeat("x", 32*1024)})+ }+ }+ frame := read()+ if frame["type"] != "control_response" {+ os.Exit(15)+ }+ return frame["response"].(map[string]any)["response"].(map[string]any)+ }+ hook("UserPromptSubmit")+ fmt.Println(`{"type":"system","subtype":"init","session_id":"claude-supplement"}`)+ for {+ out := hook("PostToolUse")+ if specific, ok := out["hookSpecificOutput"].(map[string]any); ok {+ if specific["additionalContext"] != strings.Repeat("context ", 8192) {+ os.Exit(16)+ }+ break+ }+ time.Sleep(5 * time.Millisecond)+ }+ if out := hook("Stop"); len(out) != 0 {+ os.Exit(17)+ }+ fmt.Println(`{"type":"result","subtype":"success","session_id":"claude-supplement","result":"original goal and tests completed"}`)+ if _, err := reader.ReadBytes('\n'); err != io.EOF {+ os.Exit(18)+ }+}++func TestClaudeSupplementExecuteUsesSamePromptUnderBackpressure(t *testing.T) {+ self, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ b := &claudeBackend{cfg: Config{ExecutablePath: self, Logger: slog.Default(), Env: map[string]string{"CLAUDE_FAKE_MODE": "supplement", "IS_SANDBOX": "1"}}}+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+ defer cancel()+ session, err := b.Execute(ctx, "original goal", ExecOptions{EnableTaskSupplement: true})+ if err != nil {+ t.Fatal(err)+ }+ if session.Supplement == nil || session.SupplementReady == nil {+ t.Fatal("Claude supplement interface missing")+ }+ for !session.SupplementReady() {+ select {+ case result := <-session.Result:+ t.Fatalf("ended before ready: %+v", result)+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ case <-time.After(time.Millisecond):+ }+ }+ if err := session.Supplement(ctx, strings.Repeat("context ", 8192)); err != nil {+ t.Fatal(err)+ }+ select {+ case result := <-session.Result:+ if result.Status != "completed" || result.Output != "original goal and tests completed" {+ t.Fatalf("result: %+v", result)+ }+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+ if session.SupplementReady() {+ t.Fatal("completed process still accepts supplements")+ }+ if err := session.Supplement(ctx, "late input"); err == nil {+ t.Fatal("late input accepted")+ }+}++func TestClaudeSupplementInitializeFailure(t *testing.T) {+ for _, failure := range []string{"reject", "timeout"} {+ t.Run(failure, func(t *testing.T) {+ self, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ b := &claudeBackend{cfg: Config{ExecutablePath: self, Logger: slog.Default(), Env: map[string]string{+ "CLAUDE_FAKE_MODE": "supplement", "CLAUDE_SUPPLEMENT_INIT_FAILURE": failure, "IS_SANDBOX": "1",+ }}}+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+ defer cancel()+ session, err := b.Execute(ctx, "original goal", ExecOptions{EnableTaskSupplement: true, HandshakeTimeout: time.Hour})+ if err != nil {+ t.Fatal(err)+ }+ select {+ case result := <-session.Result:+ if result.Status != "completed" || result.Output != "original goal completed" {+ t.Fatalf("handshake failure must preserve ordinary execution: %+v", result)+ }+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+ if session.SupplementReady() {+ t.Fatal("failed handshake enabled supplements")+ }+ })+ }+}diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex 05f29185f4..13a8f9b3cb 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -320,15 +320,17 @@ type codexFirstItemWaitObservation struct {mu sync.MutexstartedAt time.TimefinishedAt time.Time+ turnID stringoutcome stringstderr codexStderrClassification}-func (o *codexFirstItemWaitObservation) start(now time.Time) {+func (o *codexFirstItemWaitObservation) start(now time.Time, turnID string) {o.mu.Lock()defer o.mu.Unlock()if o.startedAt.IsZero() {o.startedAt = now+ o.turnID = turnID}}@@ -343,13 +345,13 @@ func (o *codexFirstItemWaitObservation) finish(now time.Time, outcome string, sto.stderr = stderr}-func (o *codexFirstItemWaitObservation) snapshot() (time.Duration, string, codexStderrClassification, bool) {+func (o *codexFirstItemWaitObservation) snapshot() (time.Duration, string, string, codexStderrClassification, bool) {o.mu.Lock()defer o.mu.Unlock()if o.startedAt.IsZero() || o.finishedAt.IsZero() || o.outcome == "" {- return 0, "", codexStderrClassification{}, false+ return 0, "", "", codexStderrClassification{}, false}- return o.finishedAt.Sub(o.startedAt), o.outcome, o.stderr, true+ return o.finishedAt.Sub(o.startedAt), o.turnID, o.outcome, o.stderr, true}// codexBackend implements Backend by spawning `codex app-server --listen stdio://`@@ -937,8 +939,30 @@ 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+ supplement := func(supplementCtx context.Context, instruction string) error {+ sessionMu.RLock()+ session := currentSession+ sessionMu.RUnlock()+ if session == nil || session.Supplement == nil {+ return errors.New("codex turn does not accept additional messages")+ }+ return session.Supplement(supplementCtx, instruction)+ }+ supplementReady := func() bool {+ sessionMu.RLock()+ session := currentSession+ sessionMu.RUnlock()+ return session != nil && session.SupplementReady != nil && session.SupplementReady()+ }go func() {+ defer func() {+ sessionMu.Lock()+ currentSession = nil+ sessionMu.Unlock()+ }()defer close(msgCh)defer close(resCh)session := firstSession@@ -951,6 +975,9 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptiresCh <- Result{Status: "failed", Error: err.Error()}return}+ sessionMu.Lock()+ currentSession = session+ sessionMu.Unlock()}// Hold back the leading session-pin status messages until this// attempt proves it made real progress. A retry never continues the@@ -1028,7 +1055,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti}}()- return &Session{Messages: msgCh, Result: resCh}, nil+ return &Session{Supplement: supplement, SupplementReady: supplementReady, Messages: msgCh, Result: resCh}, nil}func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecOptions, attempt int) (*Session, error) {@@ -1209,11 +1236,12 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec// race between the lifecycle goroutine writing and the reader reading.turnDone := make(chan bool, 1) // true = aborted+ var c *codexClientobserveMessage := func(msg Message) {logCodexAgentMessage(b.cfg.Logger, msg)activity := describeCodexSemanticActivity(msg)if activity == "status:running" {- firstItemWait.start(time.Now())+ firstItemWait.start(time.Now(), c.activeTurnID())}trySendString(semanticActivityCh, activity)if activity != "" {@@ -1221,7 +1249,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec}}- c := &codexClient{+ c = &codexClient{cfg: b.cfg,stdin: stdin,pending: make(map[int]*pendingRPC),@@ -1698,7 +1726,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecresetTimer(semanticTimer, semanticInactivityTimeout)if activity == "status:running" && !firstTurnStarted {firstTurnStarted = true- firstItemWait.start(time.Now())+ firstItemWait.start(time.Now(), c.activeTurnID())firstTurnNoProgressTimer = time.NewTimer(firstTurnNoProgressTimeout)firstTurnNoProgressTimerC = firstTurnNoProgressTimer.C} else if firstTurnStarted && !firstTurnProgressObserved && isCodexFirstTurnProgressActivity(activity) {@@ -1815,7 +1843,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec)}- if waitLatency, outcome, classification, ok := firstItemWait.snapshot(); ok {+ if waitLatency, firstTurnID, outcome, classification, ok := firstItemWait.snapshot(); ok {if waitLatency < 0 {waitLatency = 0}@@ -1836,7 +1864,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec"active_launches", activeLaunches,"method", "turn/start","thread_id", threadID,- "turn_id", c.activeTurnID(),+ "turn_id", firstTurnID,"outcome", outcome,"latency", waitLatency.Round(time.Millisecond).String(),"latency_ms", waitLatency.Milliseconds(),@@ -1906,7 +1934,29 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec}}()- return &Session{Messages: msgCh, Result: resCh}, nil+ supplement := func(supplementCtx context.Context, instruction string) error {+ return supplementCodexTurn(supplementCtx, c, instruction)+ }+ supplementReady := func() bool {+ return c.getThreadID() != "" && c.activeTurnID() != ""+ }+ return &Session{Supplement: supplement, SupplementReady: supplementReady, Messages: msgCh, Result: resCh}, nil+}++func supplementCodexTurn(ctx context.Context, c *codexClient, instruction string) error {+ ctx, cancel := context.WithTimeout(ctx, 8*time.Second)+ defer cancel()+ threadID := c.getThreadID()+ turnID := c.activeTurnID()+ if threadID == "" || turnID == "" {+ return errors.New("codex turn has not started")+ }+ _, err := c.request(ctx, "turn/steer", map[string]any{+ "threadId": threadID,+ "expectedTurnId": turnID,+ "input": []map[string]any{{"type": "text", "text": instruction}},+ })+ return err}func resolveCodexHandshakeTimeouts(opts ExecOptions) (time.Duration, time.Duration) {@@ -2340,6 +2390,7 @@ type codexClient struct {threadIDMu sync.RWMutexthreadID stringturnIDMu sync.RWMutex+ lastTurnID stringturnID stringonMessage func(Message)// onAgentMessageChunk reports whether a text chunk was handed to the@@ -2494,14 +2545,21 @@ func (c *codexClient) getThreadID() string {}func (c *codexClient) setActiveTurnID(turnID string) {- if turnID == "" {- return- }c.turnIDMu.Lock()+ if turnID != "" {+ c.lastTurnID = turnID+ }c.turnID = turnIDc.turnIDMu.Unlock()}+// usageTurnID retains attribution after the turn closes its steering window.+func (c *codexClient) usageTurnID() string {+ c.turnIDMu.RLock()+ defer c.turnIDMu.RUnlock()+ return c.lastTurnID+}+func (c *codexClient) activeTurnID() string {c.turnIDMu.RLock()defer c.turnIDMu.RUnlock()@@ -3442,6 +3500,7 @@ func (c *codexClient) handleRawNotification(method string, params map[string]anyreturn}c.turnCompleted = true+ c.setActiveTurnID("")aborted := status == "cancelled" || status == "canceled" ||status == "aborted" || status == "interrupted"@@ -3753,13 +3812,14 @@ func (c *codexClient) handleItemNotification(method string, params map[string]an// updateThreadTokenUsage consumes the v2 app-server's real usage notification.// Resume can replay a historical snapshot after thread/resume returns, so only-// notifications attributed to the active turn are eligible. The first current-+// notifications attributed to this run's active or just-completed turn are eligible.+// A late final snapshot must survive closing supplement admission. The first current-// turn snapshot contributes `last`; later snapshots contribute the monotonic// delta from `total`. This retains multi-response tool loops without charging// replayed history or duplicate snapshots twice.func (c *codexClient) updateThreadTokenUsage(params map[string]any) {turnID, _ := params["turnId"].(string)- if turnID == "" || turnID != c.activeTurnID() {+ if turnID == "" || turnID != c.usageTurnID() {return}diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex dd5f404a11..887ca3f9d8 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -42,6 +42,56 @@ func newTestCodexClient(t *testing.T) (*codexClient, *fakeStdin, []Message) {return c, fs, messages}+func TestSupplementCodexTurnTargetsExactActiveTurn(t *testing.T) {+ c, _, _ := newTestCodexClient(t)+ c.threadID = "thread-current"+ c.setActiveTurnID("turn-current")+ stdin := &fakeStdinWithHook{}+ stdin.afterWrite = func() {+ c.handleLine(`{"jsonrpc":"2.0","id":1,"result":{}}`)+ }+ c.stdin = stdin++ if err := supplementCodexTurn(context.Background(), c, "keep the original goal and add this"); err != nil {+ t.Fatalf("supplementCodexTurn: %v", err)+ }+ lines := stdin.Lines()+ if len(lines) != 1 {+ t.Fatalf("request lines = %d, want 1", len(lines))+ }+ var request struct {+ Method string `json:"method"`+ Params struct {+ ThreadID string `json:"threadId"`+ ExpectedTurnID string `json:"expectedTurnId"`+ Input []struct {+ Type string `json:"type"`+ Text string `json:"text"`+ } `json:"input"`+ } `json:"params"`+ }+ if err := json.Unmarshal([]byte(lines[0]), &request); err != nil {+ t.Fatal(err)+ }+ if request.Method != "turn/steer" || request.Params.ThreadID != "thread-current" || request.Params.ExpectedTurnID != "turn-current" {+ t.Fatalf("steer target = %#v", request)+ }+ if len(request.Params.Input) != 1 || request.Params.Input[0].Type != "text" || request.Params.Input[0].Text != "keep the original goal and add this" {+ t.Fatalf("steer input = %#v", request.Params.Input)+ }+}++func TestSupplementCodexTurnFailsClosedWithoutActiveTurn(t *testing.T) {+ c, stdin, _ := newTestCodexClient(t)+ c.threadID = "thread-current"+ if err := supplementCodexTurn(context.Background(), c, "extra"); err == nil {+ t.Fatal("supplementCodexTurn succeeded without an active turn")+ }+ if len(stdin.Lines()) != 0 {+ t.Fatalf("wrote a steer request without an active turn: %v", stdin.Lines())+ }+}+type fakeStdin struct {mu sync.Mutexdata []byte@@ -1885,14 +1935,17 @@ func TestCodexTurnNotificationGateIgnoresSubagentTurnStarted(t *testing.T) {c.handleLine(`{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr_main","turn":{"id":"turn-main"}}}`)c.handleLine(`{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr_subagent","turn":{"id":"turn-sub"}}}`)+ if turnID := c.activeTurnID(); turnID != "turn-main" {+ t.Fatalf("subagent turn/started replaced client turnID: got %q", turnID)+ }c.handleLine(`{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr_main","turnId":"turn-main","item":{"type":"agentMessage","id":"msg-main","text":"Main answer"}}}`)c.handleLine(`{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr_main","turn":{"id":"turn-main","status":"completed"}}}`)if gate.turnID != "turn-main" {t.Fatalf("subagent turn/started replaced gate turnID: got %q", gate.turnID)}- if turnID := c.activeTurnID(); turnID != "turn-main" {- t.Fatalf("subagent turn/started replaced client turnID: got %q", turnID)+ if turnID := c.activeTurnID(); turnID != "" {+ t.Fatalf("completed main turn remained supplement-ready: active turn ID %q", turnID)}if gotText != "Main answer" {t.Fatalf("main turn text was lost after subagent start: got %q", gotText)@@ -3730,6 +3783,27 @@ func TestCodexThreadTokenUsageUpdatedDeduplicatesSnapshot(t *testing.T) {}}+func TestCodexTokenUsageArrivingAfterTurnCompleted(t *testing.T) {+ c, _, _ := newTestCodexClient(t)+ c.threadID = "thread-1"+ c.setActiveTurnID("turn-current")+ c.handleRawNotification("turn/completed", map[string]any{+ "threadId": "thread-1", "turn": map[string]any{"id": "turn-current", "status": "completed"},+ })+ if c.activeTurnID() != "" {+ t.Fatal("completed turn still accepts supplements")+ }+ for _, turn := range []string{"turn-old", "turn-current", "turn-current"} {+ c.handleRawNotification("thread/tokenUsage/updated", codexThreadTokenUsageParams(+ "thread-1", turn, map[string]any{"inputTokens": float64(110)},+ map[string]any{"inputTokens": float64(100), "cachedInputTokens": float64(30), "outputTokens": float64(10)},+ ))+ }+ if want := (TokenUsage{InputTokens: 70, CacheReadTokens: 30, OutputTokens: 10}); c.usage != want {+ t.Fatalf("late usage = %+v, want %+v", c.usage, want)+ }+}+func TestCodexThreadTokenUsageUpdatedAccumulatesCurrentTurnResponses(t *testing.T) {c := &codexClient{}c.setActiveTurnID("turn-current")diff --git a/server/pkg/agent/version.go b/server/pkg/agent/version.goindex 601e7d0f69..6cd6a91fc2 100644--- a/server/pkg/agent/version.go+++ b/server/pkg/agent/version.go@@ -125,6 +125,26 @@ type semver struct {Major, Minor, Patch int}+// SupportsTaskSupplement gates the resolved executable, including custom+// commands. Unknown versions must not advertise a capability they may lack.+func SupportsTaskSupplement(provider, version string) bool {+ var minimum string+ switch provider {+ case "codex":+ // v0.100.0 exposes turn/steer with the expectedTurnId precondition.+ minimum = "0.100.0"+ case "claude":+ // 2.1.110 fixes PreToolUse additionalContext being lost on tool failure.+ // https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md+ minimum = "2.1.110"+ default:+ return false+ }+ detected, err := parseSemver(version)+ floor, _ := parseSemver(minimum)+ return err == nil && !detected.lessThan(floor)+}+// versionRe matches version strings like "2.1.100", "v2.0.0", or// "2.1.100 (Claude Code)" — it extracts the first three numeric components.var versionRe = regexp.MustCompile(`v?(\d+)\.(\d+)\.(\d+)`)diff --git a/server/pkg/agent/version_test.go b/server/pkg/agent/version_test.goindex aca6288b0e..f136fb4594 100644--- a/server/pkg/agent/version_test.go+++ b/server/pkg/agent/version_test.go@@ -5,6 +5,21 @@ import ("testing")+func TestTaskSupplementVersionGate(t *testing.T) {+ for _, tc := range []struct {+ provider, version string+ want bool+ }{+ {"codex", "codex-cli 0.100.0", true}, {"codex", "0.99.0", false},+ {"claude", "2.1.110 (Claude Code)", true}, {"claude", "2.1.109", false},+ {"codex", "", false}, {"claude", "dev", false}, {"kimi", "9.0.0", false},+ } {+ if got := SupportsTaskSupplement(tc.provider, tc.version); got != tc.want {+ t.Errorf("%s %q: supported=%v, want %v", tc.provider, tc.version, got, tc.want)+ }+ }+}+func TestParseSemver(t *testing.T) {tests := []struct {input stringdiff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 0bfc2bdf6b..f920a9d111 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -8594,7 +8594,7 @@ SET status = 'running',started_at = now(),wait_reason = NULL,prepare_lease_expires_at = NULL-WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')+WHERE agent_task_queue.id = $1 AND agent_task_queue.status IN ('dispatched', 'waiting_local_directory')RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot`diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex f11c556dd5..754ba567b0 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -1332,25 +1332,31 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List}const listReconcilableCommentsForIssueSince = `-- name: ListReconcilableCommentsForIssueSince :many-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at FROM comment-WHERE issue_id = $1- AND (id = ANY($2::uuid[])- OR comment_thread_root_id(id) = $3::uuid)+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at FROM comment c+WHERE c.issue_id = $1+ AND (c.id = ANY($2::uuid[])+ OR comment_thread_root_id(c.id) = $3::uuid)-- A deleted comment is no longer input, even when replies keep its row.- AND deleted_at IS NULL+ AND c.deleted_at IS NULL+ -- Explicit supplements belong only to their bound run, regardless of+ -- delivery status. Failed delivery must not become an automatic new run.+ AND NOT EXISTS (+ SELECT 1 FROM task_supplement s+ WHERE s.comment_id = c.id AND s.workspace_id = c.workspace_id+ )AND ((- author_type IN ('member', 'agent')- AND (created_at > $4 OR id = ANY($2::uuid[]))+ c.author_type IN ('member', 'agent')+ AND (c.created_at > $4 OR c.id = ANY($2::uuid[])))OR (- author_type = 'system'- AND type = 'progress_update'- AND source_task_id IS NOT NULL- AND id = ANY($2::uuid[])+ c.author_type = 'system'+ AND c.type = 'progress_update'+ AND c.source_task_id IS NOT NULL+ AND c.id = ANY($2::uuid[])))-ORDER BY created_at ASC, id ASC+ORDER BY c.created_at ASC, c.id ASC`type ListReconcilableCommentsForIssueSinceParams struct {diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 437b4fd709..e885650774 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -487,6 +487,12 @@ cleared_wakeup_receipts AS (cleared_wakeups AS (DELETE FROM issue_wakeup WHERE issue_id IN (SELECT target.id FROM target)),+cleared_task_supplements AS (+ DELETE FROM task_supplement WHERE issue_id IN (SELECT target.id FROM target)+),+cleared_task_supplement_capabilities AS (+ DELETE FROM task_supplement_capability WHERE issue_id IN (SELECT target.id FROM target)+),cleared_vcs_pr_links AS (DELETE FROM issue_vcs_pull_request WHERE issue_id IN (SELECT target.id FROM target))diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 4f1fa2a481..64247266b2 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1429,6 +1429,29 @@ type TaskMessage struct {CallID pgtype.Text `json:"call_id"`}+type TaskSupplement struct {+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ CommentID pgtype.UUID `json:"comment_id"`+ AuthorID pgtype.UUID `json:"author_id"`+ ClientRequestID pgtype.UUID `json:"client_request_id"`+ Status string `json:"status"`+ FailureReason pgtype.Text `json:"failure_reason"`+ AttemptCount int32 `json:"attempt_count"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`+}++type TaskSupplementCapability struct {+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ Capability string `json:"capability"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type TaskToken struct {ID pgtype.UUID `json:"id"`TokenHash string `json:"token_hash"`diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.gonew file mode 100644index 0000000000..63c3ee7085--- /dev/null+++ b/server/pkg/db/generated/supplement.sql.go@@ -0,0 +1,659 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: supplement.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const ackTaskSupplementDelivered = `-- name: AckTaskSupplementDelivered :one+WITH task AS MATERIALIZED (+ SELECT id FROM agent_task_queue WHERE id = $2 FOR UPDATE+)+UPDATE task_supplement s+SET status = 'delivered',+ delivered_at = COALESCE(delivered_at, now()),+ failure_reason = NULL,+ updated_at = now()+FROM task t+WHERE s.task_id = t.id+ AND s.comment_id = $1+ AND (s.status IN ('delivering', 'delivered')+ OR (s.status = 'failed' AND s.failure_reason = 'turn_ended' AND s.attempt_count > 0))+RETURNING s.task_id, s.workspace_id, s.issue_id, s.comment_id, s.author_id, s.client_request_id, s.status, s.failure_reason, s.attempt_count, s.created_at, s.updated_at, s.delivered_at+`++type AckTaskSupplementDeliveredParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ TaskID pgtype.UUID `json:"task_id"`+}++// The provider can accept input before completion while its HTTP acknowledgement+// arrives afterward. Serialize with settlement and preserve that successful write.+func (q *Queries) AckTaskSupplementDelivered(ctx context.Context, arg AckTaskSupplementDeliveredParams) (TaskSupplement, error) {+ row := q.db.QueryRow(ctx, ackTaskSupplementDelivered, arg.CommentID, arg.TaskID)+ var i TaskSupplement+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ )+ return i, err+}++const ackTaskSupplementFailed = `-- name: AckTaskSupplementFailed :one+UPDATE task_supplement+SET status = 'failed',+ failure_reason = $1,+ updated_at = now()+WHERE task_id = $2+ AND comment_id = $3+ AND status = 'delivering'+RETURNING task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at+`++type AckTaskSupplementFailedParams struct {+ FailureReason pgtype.Text `json:"failure_reason"`+ TaskID pgtype.UUID `json:"task_id"`+ CommentID pgtype.UUID `json:"comment_id"`+}++func (q *Queries) AckTaskSupplementFailed(ctx context.Context, arg AckTaskSupplementFailedParams) (TaskSupplement, error) {+ row := q.db.QueryRow(ctx, ackTaskSupplementFailed, arg.FailureReason, arg.TaskID, arg.CommentID)+ var i TaskSupplement+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ )+ return i, err+}++const claimNextTaskSupplement = `-- name: ClaimNextTaskSupplement :one+WITH next AS MATERIALIZED (+ SELECT s.comment_id+ FROM task_supplement s+ JOIN agent_task_queue t ON t.id = s.task_id+ JOIN task_supplement_capability cap ON cap.task_id = t.id+ WHERE s.task_id = $1+ AND s.status = 'pending'+ AND t.status = 'running'+ AND cap.capability = 'task-supplement-v1'+ ORDER BY s.created_at, s.comment_id+ FOR UPDATE OF s SKIP LOCKED+ LIMIT 1+), claimed AS (+ UPDATE task_supplement s+ SET status = 'delivering',+ attempt_count = attempt_count + 1,+ failure_reason = NULL,+ updated_at = now()+ FROM next+ WHERE s.comment_id = next.comment_id+ RETURNING s.task_id, s.workspace_id, s.issue_id, s.comment_id, s.author_id, s.client_request_id, s.status, s.failure_reason, s.attempt_count, s.created_at, s.updated_at, s.delivered_at+)+SELECT claimed.comment_id, claimed.attempt_count, c.content,+ 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 = claimed.author_id+`++type ClaimNextTaskSupplementRow struct {+ CommentID pgtype.UUID `json:"comment_id"`+ AttemptCount int32 `json:"attempt_count"`+ Content string `json:"content"`+ AuthorName string `json:"author_name"`+}++func (q *Queries) ClaimNextTaskSupplement(ctx context.Context, taskID pgtype.UUID) (ClaimNextTaskSupplementRow, error) {+ row := q.db.QueryRow(ctx, claimNextTaskSupplement, taskID)+ var i ClaimNextTaskSupplementRow+ err := row.Scan(+ &i.CommentID,+ &i.AttemptCount,+ &i.Content,+ &i.AuthorName,+ )+ return i, err+}++const createTaskSupplement = `-- name: CreateTaskSupplement :one+WITH locked_task AS MATERIALIZED (+ SELECT t.id, t.issue_id, t.agent_id, t.trigger_comment_id+ FROM agent_task_queue t+ JOIN agent_runtime r ON r.id = t.runtime_id+ JOIN task_supplement_capability cap ON cap.task_id = t.id+ WHERE t.id = $1+ AND t.issue_id = $2+ AND r.workspace_id = $3+ AND t.status = 'running'+ AND cap.capability = 'task-supplement-v1'+ AND r.provider IN ('codex', 'claude')+ FOR UPDATE OF t+), touched_issue AS (+ UPDATE issue i SET+ updated_at = now(),+ revision = revision + 1,+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())+ FROM locked_task t+ WHERE i.id = t.issue_id AND i.workspace_id = $3+ RETURNING i.id, i.workspace_id, i.revision+), inserted_comment AS (+ INSERT INTO comment (+ issue_id, workspace_id, author_type, author_id, content, type, parent_id+ )+ SELECT i.id, i.workspace_id, 'member', $4, $5, 'comment', t.trigger_comment_id+ FROM touched_issue i+ JOIN locked_task t ON t.issue_id = i.id+ RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at, deleted_at+), inserted_supplement AS (+ INSERT INTO task_supplement (+ task_id, workspace_id, issue_id, comment_id, author_id,+ client_request_id, status+ )+ SELECT t.id, i.workspace_id, i.id, c.id, $4,+ $6,+ 'pending'+ FROM locked_task t+ JOIN touched_issue i ON i.id = t.issue_id+ JOIN inserted_comment c ON c.issue_id = i.id+ RETURNING task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at+)+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, c.deleted_at, i.revision AS issue_revision,+ s.task_id AS supplement_task_id, s.status AS supplement_status,+ s.failure_reason AS supplement_failure_reason,+ s.delivered_at AS supplement_delivered_at+FROM inserted_comment c+JOIN touched_issue i ON i.id = c.issue_id+JOIN inserted_supplement s ON s.comment_id = c.id+`++type CreateTaskSupplementParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ ClientRequestID pgtype.UUID `json:"client_request_id"`+}++type CreateTaskSupplementRow struct {+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ParentID pgtype.UUID `json:"parent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`+ ResolvedByType pgtype.Text `json:"resolved_by_type"`+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+ QuickActionID pgtype.UUID `json:"quick_action_id"`+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`+ Revision int64 `json:"revision"`+ RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`+ IssueRevision int64 `json:"issue_revision"`+ SupplementTaskID pgtype.UUID `json:"supplement_task_id"`+ SupplementStatus string `json:"supplement_status"`+ SupplementFailureReason pgtype.Text `json:"supplement_failure_reason"`+ SupplementDeliveredAt pgtype.Timestamptz `json:"supplement_delivered_at"`+}++// Locking the exact task serializes against terminal transitions.+// Comment creation, explicit task binding and run coverage then+// commit as one statement: a terminal-race loser creates nothing.+func (q *Queries) CreateTaskSupplement(ctx context.Context, arg CreateTaskSupplementParams) (CreateTaskSupplementRow, error) {+ row := q.db.QueryRow(ctx, createTaskSupplement,+ arg.TaskID,+ arg.IssueID,+ arg.WorkspaceID,+ arg.AuthorID,+ arg.Content,+ arg.ClientRequestID,+ )+ var i CreateTaskSupplementRow+ err := row.Scan(+ &i.ID,+ &i.IssueID,+ &i.AuthorType,+ &i.AuthorID,+ &i.Content,+ &i.Type,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ParentID,+ &i.WorkspaceID,+ &i.ResolvedAt,+ &i.ResolvedByType,+ &i.ResolvedByID,+ &i.SourceTaskID,+ &i.QuickActionID,+ &i.ViaPluginID,+ &i.Revision,+ &i.RecoverySettledAt,+ &i.DeletedAt,+ &i.IssueRevision,+ &i.SupplementTaskID,+ &i.SupplementStatus,+ &i.SupplementFailureReason,+ &i.SupplementDeliveredAt,+ )+ return i, err+}++const deleteTaskSupplementByComment = `-- name: DeleteTaskSupplementByComment :exec+DELETE FROM task_supplement+WHERE comment_id = $1 AND workspace_id = $2+`++type DeleteTaskSupplementByCommentParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) DeleteTaskSupplementByComment(ctx context.Context, arg DeleteTaskSupplementByCommentParams) error {+ _, err := q.db.Exec(ctx, deleteTaskSupplementByComment, arg.CommentID, arg.WorkspaceID)+ return err+}++const getTaskSupplementByComment = `-- name: GetTaskSupplementByComment :one+SELECT task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at FROM task_supplement+WHERE comment_id = $1 AND workspace_id = $2+`++type GetTaskSupplementByCommentParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetTaskSupplementByComment(ctx context.Context, arg GetTaskSupplementByCommentParams) (TaskSupplement, error) {+ row := q.db.QueryRow(ctx, getTaskSupplementByComment, arg.CommentID, arg.WorkspaceID)+ var i TaskSupplement+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ )+ return i, err+}++const getTaskSupplementByRequest = `-- name: GetTaskSupplementByRequest :one+SELECT s.task_id, s.workspace_id, s.issue_id, s.comment_id, s.author_id, s.client_request_id, s.status, s.failure_reason, s.attempt_count, s.created_at, s.updated_at, s.delivered_at+FROM task_supplement s+WHERE s.task_id = $1+ AND s.workspace_id = $2+ AND s.author_id = $3+ AND s.client_request_id = $4+`++type GetTaskSupplementByRequestParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AuthorID pgtype.UUID `json:"author_id"`+ ClientRequestID pgtype.UUID `json:"client_request_id"`+}++func (q *Queries) GetTaskSupplementByRequest(ctx context.Context, arg GetTaskSupplementByRequestParams) (TaskSupplement, error) {+ row := q.db.QueryRow(ctx, getTaskSupplementByRequest,+ arg.TaskID,+ arg.WorkspaceID,+ arg.AuthorID,+ arg.ClientRequestID,+ )+ var i TaskSupplement+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ )+ return i, err+}++const getTaskSupplementCapability = `-- name: GetTaskSupplementCapability :one+SELECT task_id, workspace_id, issue_id, capability, created_at FROM task_supplement_capability WHERE task_id = $1+`++func (q *Queries) GetTaskSupplementCapability(ctx context.Context, taskID pgtype.UUID) (TaskSupplementCapability, error) {+ row := q.db.QueryRow(ctx, getTaskSupplementCapability, taskID)+ var i TaskSupplementCapability+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.Capability,+ &i.CreatedAt,+ )+ return i, err+}++const listTaskSupplementMetadata = `-- name: ListTaskSupplementMetadata :many+SELECT cap.task_id, cap.capability,+ COALESCE(array_agg(s.comment_id ORDER BY s.created_at, s.comment_id)+ FILTER (WHERE s.comment_id IS NOT NULL), '{}'::uuid[])::uuid[] AS comment_ids+FROM task_supplement_capability cap+LEFT JOIN task_supplement s ON s.task_id = cap.task_id+WHERE cap.workspace_id = $1+ AND cap.task_id = ANY($2::uuid[])+GROUP BY cap.task_id, cap.capability+`++type ListTaskSupplementMetadataParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ TaskIds []pgtype.UUID `json:"task_ids"`+}++type ListTaskSupplementMetadataRow struct {+ TaskID pgtype.UUID `json:"task_id"`+ Capability string `json:"capability"`+ CommentIds []pgtype.UUID `json:"comment_ids"`+}++func (q *Queries) ListTaskSupplementMetadata(ctx context.Context, arg ListTaskSupplementMetadataParams) ([]ListTaskSupplementMetadataRow, error) {+ rows, err := q.db.Query(ctx, listTaskSupplementMetadata, arg.WorkspaceID, arg.TaskIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListTaskSupplementMetadataRow{}+ for rows.Next() {+ var i ListTaskSupplementMetadataRow+ if err := rows.Scan(&i.TaskID, &i.Capability, &i.CommentIds); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listTaskSupplementsByCommentIDs = `-- name: ListTaskSupplementsByCommentIDs :many+SELECT task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at FROM task_supplement+WHERE workspace_id = $1+ AND comment_id = ANY($2::uuid[])+`++type ListTaskSupplementsByCommentIDsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ CommentIds []pgtype.UUID `json:"comment_ids"`+}++func (q *Queries) ListTaskSupplementsByCommentIDs(ctx context.Context, arg ListTaskSupplementsByCommentIDsParams) ([]TaskSupplement, error) {+ rows, err := q.db.Query(ctx, listTaskSupplementsByCommentIDs, arg.WorkspaceID, arg.CommentIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []TaskSupplement{}+ for rows.Next() {+ var i TaskSupplement+ if err := rows.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const lockTaskSupplementByComment = `-- name: LockTaskSupplementByComment :one+SELECT task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at FROM task_supplement+WHERE comment_id = $1 AND workspace_id = $2+FOR UPDATE+`++type LockTaskSupplementByCommentParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) LockTaskSupplementByComment(ctx context.Context, arg LockTaskSupplementByCommentParams) (TaskSupplement, error) {+ row := q.db.QueryRow(ctx, lockTaskSupplementByComment, arg.CommentID, arg.WorkspaceID)+ var i TaskSupplement+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ )+ return i, err+}++const retryTaskSupplement = `-- name: RetryTaskSupplement :one+WITH comment AS MATERIALIZED (+ SELECT id FROM comment+ WHERE id = $1 AND workspace_id = $2 AND deleted_at IS NULL+ FOR UPDATE+), active_task AS MATERIALIZED (+ SELECT agent_task_queue.id FROM agent_task_queue+ WHERE agent_task_queue.id = $3+ AND agent_task_queue.issue_id = $4+ AND agent_task_queue.status = 'running'+ AND EXISTS (SELECT 1 FROM comment)+ AND EXISTS (+ SELECT 1 FROM task_supplement_capability cap+ WHERE cap.task_id = agent_task_queue.id+ AND cap.capability = 'task-supplement-v1'+ )+ FOR UPDATE OF agent_task_queue+)+UPDATE task_supplement s+SET status = 'pending',+ failure_reason = NULL,+ updated_at = now()+FROM active_task t+WHERE s.task_id = t.id+ AND s.comment_id = $1+ AND s.workspace_id = $2+ AND s.status = 'failed'+RETURNING s.task_id, s.workspace_id, s.issue_id, s.comment_id, s.author_id, s.client_request_id, s.status, s.failure_reason, s.attempt_count, s.created_at, s.updated_at, s.delivered_at+`++type RetryTaskSupplementParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ TaskID pgtype.UUID `json:"task_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++func (q *Queries) RetryTaskSupplement(ctx context.Context, arg RetryTaskSupplementParams) (TaskSupplement, error) {+ row := q.db.QueryRow(ctx, retryTaskSupplement,+ arg.CommentID,+ arg.WorkspaceID,+ arg.TaskID,+ arg.IssueID,+ )+ var i TaskSupplement+ err := row.Scan(+ &i.TaskID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.CommentID,+ &i.AuthorID,+ &i.ClientRequestID,+ &i.Status,+ &i.FailureReason,+ &i.AttemptCount,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.DeliveredAt,+ )+ return i, err+}++const startAgentTaskWithSupplement = `-- name: StartAgentTaskWithSupplement :one+WITH candidate AS MATERIALIZED (+ SELECT t.id, t.issue_id, r.workspace_id, r.provider+ FROM agent_task_queue t+ JOIN agent_runtime r ON r.id = t.runtime_id+ WHERE t.id = $1+ AND t.status IN ('dispatched', 'waiting_local_directory')+ FOR UPDATE OF t+), capability AS (+ INSERT INTO task_supplement_capability (task_id, workspace_id, issue_id, capability)+ SELECT id, workspace_id, issue_id, 'task-supplement-v1'+ FROM candidate+ WHERE $2::boolean+ AND provider IN ('codex', 'claude')+ AND issue_id IS NOT NULL+ ON CONFLICT DO NOTHING+ RETURNING task_id+)+UPDATE agent_task_queue t+SET status = 'running',+ started_at = now(),+ wait_reason = NULL,+ prepare_lease_expires_at = NULL+FROM candidate+WHERE t.id = candidate.id+ -- Reference the data-modifying CTE explicitly: capability persistence and+ -- the returned running row are one indivisible statement.+ AND (SELECT count(*) FROM capability) >= 0+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+`++type StartAgentTaskWithSupplementParams struct {+ TaskID pgtype.UUID `json:"task_id"`+ EnableTaskSupplement bool `json:"enable_task_supplement"`+}++// Starting the task and recording the exact daemon/server capability handshake+// are one state transition. A missing row is the fail-closed value for old+// daemons, old servers, unsupported providers and application rollback.+func (q *Queries) StartAgentTaskWithSupplement(ctx context.Context, arg StartAgentTaskWithSupplementParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, startAgentTaskWithSupplement, arg.TaskID, arg.EnableTaskSupplement)+ var i AgentTaskQueue+ err := row.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,+ )+ return i, err+}diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 93b9492750..561adc9ca5 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -25,6 +25,12 @@ deleted_task_messages AS (deleted_task_tokens AS (DELETE FROM task_token WHERE task_id IN (SELECT id FROM batch)),+deleted_task_supplements AS (+ DELETE FROM task_supplement WHERE task_id IN (SELECT id FROM batch)+),+deleted_task_supplement_capabilities AS (+ DELETE FROM task_supplement_capability WHERE task_id IN (SELECT id FROM batch)+),deleted_channel_outbound_cards AS (DELETE FROM channel_outbound_card_message WHERE task_id IN (SELECT id FROM batch)),@@ -298,6 +304,12 @@ deleted_task_tokens AS (DELETE FROM task_tokenWHERE workspace_id = $1),+deleted_orphan_task_supplements AS (+ DELETE FROM task_supplement WHERE workspace_id = $1+),+deleted_orphan_task_supplement_capabilities AS (+ DELETE FROM task_supplement_capability WHERE workspace_id = $1+),deleted_hourly_dirty AS (DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1),diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 97a33d5f5f..74fc1b03a3 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -980,7 +980,7 @@ SET status = 'running',started_at = now(),wait_reason = NULL,prepare_lease_expires_at = NULL-WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')+WHERE agent_task_queue.id = $1 AND agent_task_queue.status IN ('dispatched', 'waiting_local_directory')RETURNING *;-- name: LockAgentTaskStartClaim :onediff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex 8d5131b531..f12db9a127 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -375,25 +375,31 @@ LIMIT 1;-- recorded in this run's planned inputs. Timestamp-only implicit agent replies-- remain excluded. Replays are scoped to the completing agent, never a fan-out.-- Ordered ASC so later comments coalesce onto the follow-up created by the first.-SELECT * FROM comment-WHERE issue_id = @issue_id- AND (id = ANY(@planned_comment_ids::uuid[])- OR comment_thread_root_id(id) = sqlc.narg('comment_thread_id')::uuid)+SELECT c.* FROM comment c+WHERE c.issue_id = @issue_id+ AND (c.id = ANY(@planned_comment_ids::uuid[])+ OR comment_thread_root_id(c.id) = sqlc.narg('comment_thread_id')::uuid)-- A deleted comment is no longer input, even when replies keep its row.- AND deleted_at IS NULL+ AND c.deleted_at IS NULL+ -- Explicit supplements belong only to their bound run, regardless of+ -- delivery status. Failed delivery must not become an automatic new run.+ AND NOT EXISTS (+ SELECT 1 FROM task_supplement s+ WHERE s.comment_id = c.id AND s.workspace_id = c.workspace_id+ )AND ((- author_type IN ('member', 'agent')- AND (created_at > @since OR id = ANY(@planned_comment_ids::uuid[]))+ c.author_type IN ('member', 'agent')+ AND (c.created_at > @since OR c.id = ANY(@planned_comment_ids::uuid[])))OR (- author_type = 'system'- AND type = 'progress_update'- AND source_task_id IS NOT NULL- AND id = ANY(@planned_comment_ids::uuid[])+ c.author_type = 'system'+ AND c.type = 'progress_update'+ AND c.source_task_id IS NOT NULL+ AND c.id = ANY(@planned_comment_ids::uuid[])))-ORDER BY created_at ASC, id ASC;+ORDER BY c.created_at ASC, c.id ASC;-- name: GetComment :oneSELECT * FROM commentdiff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex a44f2a26c3..06cd8fb03b 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -472,6 +472,12 @@ cleared_wakeup_receipts AS (cleared_wakeups AS (DELETE FROM issue_wakeup WHERE issue_id IN (SELECT target.id FROM target)),+cleared_task_supplements AS (+ DELETE FROM task_supplement WHERE issue_id IN (SELECT target.id FROM target)+),+cleared_task_supplement_capabilities AS (+ DELETE FROM task_supplement_capability WHERE issue_id IN (SELECT target.id FROM target)+),cleared_vcs_pr_links AS (DELETE FROM issue_vcs_pull_request WHERE issue_id IN (SELECT target.id FROM target))diff --git a/server/pkg/db/queries/supplement.sql b/server/pkg/db/queries/supplement.sqlnew file mode 100644index 0000000000..236ccdc4c5--- /dev/null+++ b/server/pkg/db/queries/supplement.sql@@ -0,0 +1,210 @@+-- name: StartAgentTaskWithSupplement :one+-- Starting the task and recording the exact daemon/server capability handshake+-- are one state transition. A missing row is the fail-closed value for old+-- daemons, old servers, unsupported providers and application rollback.+WITH candidate AS MATERIALIZED (+ SELECT t.id, t.issue_id, r.workspace_id, r.provider+ FROM agent_task_queue t+ JOIN agent_runtime r ON r.id = t.runtime_id+ WHERE t.id = @task_id+ AND t.status IN ('dispatched', 'waiting_local_directory')+ FOR UPDATE OF t+), capability AS (+ INSERT INTO task_supplement_capability (task_id, workspace_id, issue_id, capability)+ SELECT id, workspace_id, issue_id, 'task-supplement-v1'+ FROM candidate+ WHERE @enable_task_supplement::boolean+ AND provider IN ('codex', 'claude')+ AND issue_id IS NOT NULL+ ON CONFLICT DO NOTHING+ RETURNING task_id+)+UPDATE agent_task_queue t+SET status = 'running',+ started_at = now(),+ wait_reason = NULL,+ prepare_lease_expires_at = NULL+FROM candidate+WHERE t.id = candidate.id+ -- Reference the data-modifying CTE explicitly: capability persistence and+ -- the returned running row are one indivisible statement.+ AND (SELECT count(*) FROM capability) >= 0+RETURNING t.*;++-- name: CreateTaskSupplement :one+-- Locking the exact task serializes against terminal transitions.+-- Comment creation, explicit task binding and run coverage then+-- commit as one statement: a terminal-race loser creates nothing.+WITH locked_task AS MATERIALIZED (+ SELECT t.id, t.issue_id, t.agent_id, t.trigger_comment_id+ FROM agent_task_queue t+ JOIN agent_runtime r ON r.id = t.runtime_id+ JOIN task_supplement_capability cap ON cap.task_id = t.id+ WHERE t.id = @task_id+ AND t.issue_id = @issue_id+ AND r.workspace_id = @workspace_id+ AND t.status = 'running'+ AND cap.capability = 'task-supplement-v1'+ AND r.provider IN ('codex', 'claude')+ FOR UPDATE OF t+), touched_issue AS (+ UPDATE issue i SET+ updated_at = now(),+ revision = revision + 1,+ last_activity_at = GREATEST(COALESCE(last_activity_at, updated_at), now())+ FROM locked_task t+ WHERE i.id = t.issue_id AND i.workspace_id = @workspace_id+ RETURNING i.id, i.workspace_id, i.revision+), inserted_comment AS (+ INSERT INTO comment (+ issue_id, workspace_id, author_type, author_id, content, type, parent_id+ )+ SELECT i.id, i.workspace_id, 'member', @author_id, @content, 'comment', t.trigger_comment_id+ FROM touched_issue i+ JOIN locked_task t ON t.issue_id = i.id+ RETURNING *+), inserted_supplement AS (+ INSERT INTO task_supplement (+ task_id, workspace_id, issue_id, comment_id, author_id,+ client_request_id, status+ )+ SELECT t.id, i.workspace_id, i.id, c.id, @author_id,+ @client_request_id,+ 'pending'+ FROM locked_task t+ JOIN touched_issue i ON i.id = t.issue_id+ JOIN inserted_comment c ON c.issue_id = i.id+ RETURNING *+)+SELECT c.*, i.revision AS issue_revision,+ s.task_id AS supplement_task_id, s.status AS supplement_status,+ s.failure_reason AS supplement_failure_reason,+ s.delivered_at AS supplement_delivered_at+FROM inserted_comment c+JOIN touched_issue i ON i.id = c.issue_id+JOIN inserted_supplement s ON s.comment_id = c.id;++-- name: GetTaskSupplementByRequest :one+SELECT s.*+FROM task_supplement s+WHERE s.task_id = @task_id+ AND s.workspace_id = @workspace_id+ AND s.author_id = @author_id+ AND s.client_request_id = @client_request_id;++-- name: GetTaskSupplementByComment :one+SELECT * FROM task_supplement+WHERE comment_id = @comment_id AND workspace_id = @workspace_id;++-- name: GetTaskSupplementCapability :one+SELECT * FROM task_supplement_capability WHERE task_id = @task_id;++-- name: ListTaskSupplementsByCommentIDs :many+SELECT * FROM task_supplement+WHERE workspace_id = @workspace_id+ AND comment_id = ANY(@comment_ids::uuid[]);++-- name: ListTaskSupplementMetadata :many+SELECT cap.task_id, cap.capability,+ COALESCE(array_agg(s.comment_id ORDER BY s.created_at, s.comment_id)+ FILTER (WHERE s.comment_id IS NOT NULL), '{}'::uuid[])::uuid[] AS comment_ids+FROM task_supplement_capability cap+LEFT JOIN task_supplement s ON s.task_id = cap.task_id+WHERE cap.workspace_id = @workspace_id+ AND cap.task_id = ANY(@task_ids::uuid[])+GROUP BY cap.task_id, cap.capability;++-- name: ClaimNextTaskSupplement :one+WITH next AS MATERIALIZED (+ SELECT s.comment_id+ FROM task_supplement s+ JOIN agent_task_queue t ON t.id = s.task_id+ JOIN task_supplement_capability cap ON cap.task_id = t.id+ WHERE s.task_id = @task_id+ AND s.status = 'pending'+ AND t.status = 'running'+ AND cap.capability = 'task-supplement-v1'+ ORDER BY s.created_at, s.comment_id+ FOR UPDATE OF s SKIP LOCKED+ LIMIT 1+), claimed AS (+ UPDATE task_supplement s+ SET status = 'delivering',+ attempt_count = attempt_count + 1,+ failure_reason = NULL,+ updated_at = now()+ FROM next+ WHERE s.comment_id = next.comment_id+ RETURNING s.*+)+SELECT claimed.comment_id, claimed.attempt_count, 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 = claimed.author_id;++-- name: AckTaskSupplementDelivered :one+-- The provider can accept input before completion while its HTTP acknowledgement+-- arrives afterward. Serialize with settlement and preserve that successful write.+WITH task AS MATERIALIZED (+ SELECT id FROM agent_task_queue WHERE id = @task_id FOR UPDATE+)+UPDATE task_supplement s+SET status = 'delivered',+ delivered_at = COALESCE(delivered_at, now()),+ failure_reason = NULL,+ updated_at = now()+FROM task t+WHERE s.task_id = t.id+ AND s.comment_id = @comment_id+ AND (s.status IN ('delivering', 'delivered')+ OR (s.status = 'failed' AND s.failure_reason = 'turn_ended' AND s.attempt_count > 0))+RETURNING s.*;++-- name: AckTaskSupplementFailed :one+UPDATE task_supplement+SET status = 'failed',+ failure_reason = @failure_reason,+ updated_at = now()+WHERE task_id = @task_id+ AND comment_id = @comment_id+ AND status = 'delivering'+RETURNING *;++-- name: RetryTaskSupplement :one+WITH comment AS MATERIALIZED (+ SELECT id FROM comment+ WHERE id = @comment_id AND workspace_id = @workspace_id AND deleted_at IS NULL+ FOR UPDATE+), active_task AS MATERIALIZED (+ SELECT agent_task_queue.id FROM agent_task_queue+ WHERE agent_task_queue.id = @task_id+ AND agent_task_queue.issue_id = @issue_id+ AND agent_task_queue.status = 'running'+ AND EXISTS (SELECT 1 FROM comment)+ AND EXISTS (+ SELECT 1 FROM task_supplement_capability cap+ WHERE cap.task_id = agent_task_queue.id+ AND cap.capability = 'task-supplement-v1'+ )+ FOR UPDATE OF agent_task_queue+)+UPDATE task_supplement s+SET status = 'pending',+ failure_reason = NULL,+ updated_at = now()+FROM active_task t+WHERE s.task_id = t.id+ AND s.comment_id = @comment_id+ AND s.workspace_id = @workspace_id+ AND s.status = 'failed'+RETURNING s.*;++-- name: LockTaskSupplementByComment :one+SELECT * FROM task_supplement+WHERE comment_id = @comment_id AND workspace_id = @workspace_id+FOR UPDATE;++-- name: DeleteTaskSupplementByComment :exec+DELETE FROM task_supplement+WHERE comment_id = @comment_id AND workspace_id = @workspace_id;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex c302c45535..3160bfc86d 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -212,6 +212,12 @@ deleted_task_messages AS (deleted_task_tokens AS (DELETE FROM task_token WHERE task_id IN (SELECT id FROM batch)),+deleted_task_supplements AS (+ DELETE FROM task_supplement WHERE task_id IN (SELECT id FROM batch)+),+deleted_task_supplement_capabilities AS (+ DELETE FROM task_supplement_capability WHERE task_id IN (SELECT id FROM batch)+),deleted_channel_outbound_cards AS (DELETE FROM channel_outbound_card_message WHERE task_id IN (SELECT id FROM batch)),@@ -311,6 +317,12 @@ deleted_task_tokens AS (DELETE FROM task_tokenWHERE workspace_id = $1),+deleted_orphan_task_supplements AS (+ DELETE FROM task_supplement WHERE workspace_id = $1+),+deleted_orphan_task_supplement_capabilities AS (+ DELETE FROM task_supplement_capability WHERE workspace_id = $1+),deleted_hourly_dirty AS (DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1),diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 11f4a6849a..ca215896c0 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -143,12 +143,13 @@ const (EventSquadDeleted = "squad:deleted"// Daemon events- EventDaemonHeartbeat = "daemon:heartbeat"- EventDaemonHeartbeatAck = "daemon:heartbeat_ack"- EventDaemonRegister = "daemon:register"- EventDaemonTaskAvailable = "daemon:task_available"- EventDaemonRuntimeProfilesChanged = "daemon:runtime_profiles_changed"- EventDaemonWorkspacesChanged = "daemon:workspaces_changed"+ EventDaemonHeartbeat = "daemon:heartbeat"+ EventDaemonHeartbeatAck = "daemon:heartbeat_ack"+ EventDaemonRegister = "daemon:register"+ EventDaemonTaskAvailable = "daemon:task_available"+ EventDaemonTaskSupplementAvailable = "daemon:task_supplement_available"+ EventDaemonRuntimeProfilesChanged = "daemon:runtime_profiles_changed"+ EventDaemonWorkspacesChanged = "daemon:workspaces_changed"// EventDaemonPendingWork is a runtime-scoped hint that a heartbeat-carried// request (model discovery, capability discovery, or local-skill import) is// queued for that runtime. Without it the daemon only learns about thediff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex 664400c8c2..d1acdb2dfb 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -61,6 +61,16 @@ const (// work, so such a daemon keeps getting a fresh directory and the parent's// stays untouched on disk.DaemonCapabilityCheckoutKeepsWorkV1 = "checkout-keeps-work-v1"+ // DaemonCapabilityTaskSupplementV1 advertises that this provider run can accept+ // an additional text instruction without cancelling or starting a task.+ // It is persisted when this exact task enters running; absence always means+ // unsupported so mixed server/daemon versions fail closed.+ DaemonCapabilityTaskSupplementV1 = "task-supplement-v1"++ TaskSupplementFailureTurnNotStarted = "turn_not_started"+ TaskSupplementFailureProviderRejected = "provider_rejected"+ TaskSupplementFailureTimeout = "timeout"+ TaskSupplementFailureTurnEnded = "turn_ended"// AppCapabilityChatDraftRestoreV1 is advertised (X-Client-Capabilities) by// app clients that understand the durable draft-restore recovery path:@@ -122,8 +132,9 @@ type TaskDispatchPayload struct {Description string `json:"description"`}-// TaskAvailablePayload is sent from server to daemon as a wakeup hint. The-// daemon still claims work through the existing HTTP claim endpoint.+// TaskAvailablePayload carries content-free task and supplement wakeup hints.+// Supplement hints require an exact task ID; the daemon claims durable input+// through the corresponding HTTP endpoint.type TaskAvailablePayload struct {RuntimeID string `json:"runtime_id"`TaskID string `json:"task_id,omitempty"`