Skip to content

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

Go

feat(issues): show agent execution inline in comment threads (#8131)

Jiayuan Zhang028f3b4437f9
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index d22714bc28..35155d816a 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -579,6 +579,11 @@ describe("TimelineEntriesSchema", () => {
});
describe("AgentTaskListSchema", () => {
+ 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);
+ expect(parsed[0]?.cancelled_by_comment_change).toBe(typeof value === "boolean" ? value : undefined);
+ });
const task = {
id: "task-1",
agent_id: "agent-1",
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 5d86396c91..909ac24a09 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1738,6 +1738,7 @@ const TaskUsageSchema = z.object({
}).loose();
export const AgentTaskSchema = z.object({
+ cancelled_by_comment_change: z.boolean().optional().catch(undefined),
id: z.string(),
agent_id: z.string().default(""),
runtime_id: z.string().default(""),
diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.ts
index b924dda149..a07c3d0764 100644
--- a/packages/core/chat/queries.ts
+++ b/packages/core/chat/queries.ts
@@ -1,4 +1,5 @@
-import { infiniteQueryOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
+import { infiniteQueryOptions, queryOptions, useQuery, type QueryClient } from "@tanstack/react-query";
+import { useEffect, useRef } from "react";
import { api } from "../api";
import type { TaskMessagePayload } from "../types/events";
import type {
@@ -213,6 +214,26 @@ export function taskMessagesOptions(taskId: string) {
});
}
+/** A visible run follows WS updates and backfills on mount and completion. */
+export function useTaskMessages(taskId: string, isLive: boolean, enabled = true) {
+ const query = useQuery({
+ ...taskMessagesOptions(taskId),
+ enabled: enabled && isTaskMessageTaskId(taskId),
+ refetchOnMount: "always",
+ refetchOnWindowFocus: "always",
+ });
+ const previous = useRef({ isLive, enabled });
+ const { refetch } = query;
+ useEffect(() => {
+ if (enabled && isTaskMessageTaskId(taskId)
+ && (!previous.current.enabled || (previous.current.isLive && !isLive))) {
+ void refetch({ cancelRefetch: false });
+ }
+ previous.current = { isLive, enabled };
+ }, [taskId, isLive, enabled, refetch]);
+ return query;
+}
+
/**
* Merge task-message batches into one seq-ordered, seq-deduplicated list for
* the shared `["task-messages", taskId]` cache. Existing entries win on
diff --git a/packages/core/chat/use-task-messages.test.tsx b/packages/core/chat/use-task-messages.test.tsx
new file mode 100644
index 0000000000..a8566b9bc8
--- /dev/null
+++ b/packages/core/chat/use-task-messages.test.tsx
@@ -0,0 +1,58 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { api } from "../api";
+import type { TaskMessagePayload } from "../types/events";
+import { chatKeys, taskMessagesOptions, useTaskMessages } from "./queries";
+
+vi.mock("../api", () => ({ api: { listTaskMessages: vi.fn() } }));
+afterEach(() => { cleanup(); vi.clearAllMocks(); });
+const id = "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc";
+const msg = (seq: number): TaskMessagePayload => ({ task_id: id, issue_id: "issue", type: "text", content: `part${seq}`, seq });
+
+describe("useTaskMessages", () => {
+ it("defers historical transcript requests and backfills cached data when opened", async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ client.setQueryData(chatKeys.taskMessages(id), [msg(1)]);
+ vi.mocked(api.listTaskMessages).mockResolvedValue([msg(1), msg(2)]);
+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+ const { result, rerender } = renderHook(({ enabled }) => useTaskMessages(id, false, enabled), {
+ wrapper, initialProps: { enabled: false },
+ });
+ expect(api.listTaskMessages).not.toHaveBeenCalled();
+ rerender({ enabled: true });
+ await waitFor(() => expect(result.current.data).toHaveLength(2));
+ expect(api.listTaskMessages).toHaveBeenCalledTimes(1);
+ rerender({ enabled: false });
+ await act(async () => { await client.invalidateQueries({ queryKey: chatKeys.taskMessagesAll() }); });
+ expect(api.listTaskMessages).toHaveBeenCalledTimes(1);
+ vi.mocked(api.listTaskMessages).mockResolvedValue([msg(1), msg(2), msg(3)]);
+ rerender({ enabled: true });
+ await waitFor(() => expect(result.current.data).toHaveLength(3));
+ expect(api.listTaskMessages).toHaveBeenCalledTimes(2);
+ client.clear();
+ });
+
+ it("backfills cached live data without dropping concurrent WS events and recovers the terminal tail", async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ client.setQueryDefaults(chatKeys.taskMessages(id), { structuralSharing: taskMessagesOptions(id).structuralSharing });
+ client.setQueryData(chatKeys.taskMessages(id), [msg(1)]);
+ let resolve!: (messages: TaskMessagePayload[]) => void;
+ vi.mocked(api.listTaskMessages).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+ const { result, rerender } = renderHook(({ live }) => { const query = useTaskMessages(id, live); return { data: query.data }; }, { wrapper, initialProps: { live: true } });
+ await waitFor(() => expect(api.listTaskMessages).toHaveBeenCalledTimes(1));
+ act(() => client.setQueryData(chatKeys.taskMessages(id), [msg(1), msg(3)]));
+ await act(async () => resolve([msg(1), msg(2)]));
+ await waitFor(() => expect(result.current.data?.map((row) => row.seq)).toEqual([1, 2, 3]));
+ vi.mocked(api.listTaskMessages).mockResolvedValue([msg(1), msg(2), msg(3), msg(4)]);
+ rerender({ live: false });
+ await waitFor(() => expect(result.current.data?.map((row) => row.seq)).toEqual([1, 2, 3, 4]));
+ vi.mocked(api.listTaskMessages).mockResolvedValue([msg(1), msg(2), msg(3), msg(4), msg(5)]);
+ await act(async () => { await client.invalidateQueries({ queryKey: chatKeys.taskMessagesAll() }); });
+ await waitFor(() => expect(result.current.data).toHaveLength(5));
+ client.clear();
+ });
+});
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 4b8365925e..22203d97ea 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -1137,3 +1137,19 @@ export function useUnsubscribeFromIssueSubtree(issueId: string) {
},
});
}
+
+export function useCancelIssueRun(issueId: string) {
+ const client = useQueryClient();
+ return useMutation({
+ mutationFn: (taskId: string) => api.cancelTask(issueId, taskId),
+ onSuccess: () => client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) }),
+ });
+}
+
+export function useRetryIssueRun(issueId: string) {
+ const client = useQueryClient();
+ return useMutation({
+ mutationFn: (taskId: string) => api.rerunIssue(issueId, taskId),
+ onSuccess: () => client.invalidateQueries({ queryKey: issueKeys.tasks(issueId) }),
+ });
+}
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index 0ecb9fd2f8..df4476f499 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -20,6 +20,16 @@ import type {
} from "../types";
import { ALL_STATUSES } from "./config";
+export function issueTasksOptions(issueId: string) {
+ return queryOptions({
+ queryKey: issueKeys.tasks(issueId),
+ queryFn: () => api.listTasksByIssue(issueId),
+ enabled: !!issueId,
+ staleTime: 30_000,
+ refetchOnWindowFocus: true,
+ });
+}
+
export interface IssueSortParam {
sort_by?: ListIssuesParams["sort_by"];
sort_direction?: ListIssuesParams["sort_direction"];
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 958ba6d312..40d2286dbe 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -312,6 +312,8 @@ export interface AgentTask {
// coarse values; `string & {}` admits the rest without collapsing the
// hints.
failure_reason?: TaskFailureReason | (string & {}) | "";
+ /** The input comment was edited or deleted, invalidating this run. */
+ cancelled_by_comment_change?: boolean;
created_at: string;
/** Non-empty when the task was spawned from a chat session. */
chat_session_id?: string;
diff --git a/packages/ui/components/common/quick-emoji-picker.tsx b/packages/ui/components/common/quick-emoji-picker.tsx
index 9e1d6cb15f..1fc654f18d 100644
--- a/packages/ui/components/common/quick-emoji-picker.tsx
+++ b/packages/ui/components/common/quick-emoji-picker.tsx
@@ -2,6 +2,7 @@
import { useState, lazy, Suspense } from "react";
import { SmilePlus } from "lucide-react";
+import { cn } from "@multica/ui/lib/utils";
import { Popover, PopoverTrigger, PopoverContent } from "@multica/ui/components/ui/popover";
const EmojiPicker = lazy(() =>
@@ -14,9 +15,10 @@ interface QuickEmojiPickerProps {
onSelect: (emoji: string) => void;
align?: "start" | "end";
className?: string;
+ ariaLabel?: string;
}
-function QuickEmojiPicker({ onSelect, align = "start", className }: QuickEmojiPickerProps) {
+function QuickEmojiPicker({ onSelect, align = "start", className, ariaLabel = "Add reaction" }: QuickEmojiPickerProps) {
const [open, setOpen] = useState(false);
const [showFull, setShowFull] = useState(false);
@@ -37,9 +39,11 @@ function QuickEmojiPicker({ onSelect, align = "start", className }: QuickEmojiPi
render={
<button
type="button"
- className={`inline-flex items-center justify-center h-6 w-6 rounded-full text-muted-foreground hover:bg-accent hover:text-foreground transition-colors ${className ?? ""}`}
+ aria-label={ariaLabel}
+ title={ariaLabel}
+ className={cn("inline-flex shrink-0 items-center justify-center h-6 w-6 rounded-full text-muted-foreground hover:bg-accent hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", className)}
>
- <SmilePlus className="h-3.5 w-3.5" />
+ <SmilePlus className="h-3.5 w-3.5" aria-hidden />
</button>
}
/>
diff --git a/packages/ui/components/common/reaction-bar.tsx b/packages/ui/components/common/reaction-bar.tsx
index f041a01600..dbe6755bfb 100644
--- a/packages/ui/components/common/reaction-bar.tsx
+++ b/packages/ui/components/common/reaction-bar.tsx
@@ -40,6 +40,7 @@ interface ReactionBarProps {
onToggle: (emoji: string) => void;
getActorName: (type: string, id: string) => string;
className?: string;
+ showPicker?: boolean;
}
function ReactionBar({
@@ -48,8 +49,10 @@ function ReactionBar({
onToggle,
getActorName,
className,
+ showPicker = true,
}: ReactionBarProps) {
const grouped = groupReactions(reactions, currentUserId);
+ if (!showPicker && grouped.length === 0) return null;
return (
<div className={`flex flex-wrap items-center gap-1.5 ${className ?? ""}`}>
@@ -76,7 +79,7 @@ function ReactionBar({
</TooltipContent>
</Tooltip>
))}
- <QuickEmojiPicker onSelect={onToggle} />
+ {showPicker && <QuickEmojiPicker onSelect={onToggle} />}
</div>
);
}
diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.css
index cdd7dfe8c4..80ecd3c33c 100644
--- a/packages/ui/styles/base.css
+++ b/packages/ui/styles/base.css
@@ -290,6 +290,21 @@ html[data-dnd-dragging="true"] * {
transition: none;
}
+/* Each block owns only its own author/body, excluding nested replies.
+ * Keep space reserved and keyboard access intact when mouse actions fade out.
+ * Portaled menus hold their trigger visible even after focus leaves the block. */
+[data-comment-actions] {
+ transition: opacity 120ms ease-out;
+}
+
+@media (hover: hover) and (pointer: fine) {
+ [data-comment-block]:not(:hover):not(:focus-within)
+ [data-comment-actions]:not(:has([aria-haspopup][aria-expanded="true"])) {
+ opacity: 0;
+ pointer-events: none;
+ }
+}
+
@media (prefers-reduced-motion: reduce) {
.animate-entrance-spin,
.animate-onboarding-enter,
@@ -302,11 +317,27 @@ html[data-dnd-dragging="true"] * {
animation: none;
}
+ .animate-chat-text-shimmer {
+ background-image: none;
+ color: var(--muted-foreground);
+ -webkit-text-fill-color: currentColor;
+ }
+
+ [data-comment-actions],
[data-right-sidebar-panel] {
transition: none;
}
}
+@media (forced-colors: active) {
+ .animate-chat-text-shimmer {
+ animation: none;
+ background-image: none;
+ color: CanvasText;
+ -webkit-text-fill-color: currentColor;
+ }
+}
+
/* Sonner toast: align icon to first line of text, not vertically centered */
[data-sonner-toast] {
align-items: flex-start !important;
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
index ffa972294e..d353bd951b 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
@@ -12,6 +12,11 @@ import { renderWithI18n } from "../../test/i18n";
import { AgentTranscriptDialog } from "./agent-transcript-dialog";
import type { TimelineItem } from "./build-timeline";
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace" }));
+vi.mock("./use-trace-issue-labels", () => ({
+ useTraceIssueLabels: () => (text: string) => text.replaceAll("01a07eca-8e82-775e-be06-e4a97ccfa299", "DEV-17"),
+}));
+
const copyTextMock = vi.hoisted(() => vi.fn().mockResolvedValue(true));
vi.mock("@multica/core/api", () => ({
@@ -431,26 +436,27 @@ describe("AgentTranscriptDialog", () => {
expect(screen.getByText("1 of 3 steps")).toBeInTheDocument();
});
- it("hides the timeline for a run too short for it to say anything", () => {
+ it("hides the timeline when steps have no timestamps", () => {
renderDialog();
expect(screen.queryByText("Model")).not.toBeInTheDocument();
expect(screen.queryByText("Tools")).not.toBeInTheDocument();
});
- it("shows model and tool lanes once a run is long enough to have spent time", () => {
+ it.each([{ count: 1, seconds: 20 }, { count: 8, seconds: 30 }, { count: 8, seconds: 320 }])("shows the timeline for $count steps over $seconds seconds", ({ count, seconds }) => {
const at = (seconds: number) =>
new Date(Date.parse("2026-06-08T08:00:00Z") + seconds * 1000).toISOString();
const longRun: TimelineItem[] = [];
- for (let i = 0; i < 8; i++) {
+ for (let i = 0; i < count; i++) {
+ const start = (seconds / count) * i;
longRun.push(
- { seq: i * 2 + 1, type: "tool_use", tool: "Bash", input: { command: `step ${i}` }, created_at: at(i * 40) },
- { seq: i * 2 + 2, type: "tool_result", tool: "Bash", output: "ok", created_at: at(i * 40 + 20) },
+ { seq: i * 2 + 1, type: "tool_use", tool: "Bash", input: { command: `step ${i}` }, created_at: at(start) },
+ { seq: i * 2 + 2, type: "tool_result", tool: "Bash", output: "ok", created_at: at(start + seconds / count / 2) },
);
}
renderDialog(longRun, {
- task: { ...baseTask, started_at: at(0), completed_at: at(320) },
+ task: { ...baseTask, started_at: at(0), completed_at: at(seconds) },
});
expect(screen.getByText("Model")).toBeInTheDocument();
@@ -901,3 +907,17 @@ describe("AgentTranscriptDialog — reason vs raw diagnostics", () => {
expect(screen.queryByText("Reason")).not.toBeInTheDocument();
});
});
+
+
+describe("readable issue references", () => {
+ it("searches both the displayed identifier and original UUID", async () => {
+ const issueId = "01a07eca-8e82-775e-be06-e4a97ccfa299";
+ renderDialog([{ seq: 1, type: "tool_use", tool: "exec_command", input: { command: `multica issue get ${issueId} --output json` } }]);
+ expect(screen.getByText("multica issue get DEV-17 --output json")).toBeInTheDocument();
+ const search = screen.getByRole("textbox");
+ fireEvent.change(search, { target: { value: "DEV-17" } });
+ expect(screen.getByText("multica issue get DEV-17 --output json")).toBeInTheDocument();
+ fireEvent.change(search, { target: { value: issueId } });
+ expect(screen.getByText("multica issue get DEV-17 --output json")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index 2cbc1771c7..905bc3e847 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -1,6 +1,8 @@
"use client";
import { useState, useRef, useCallback, useEffect, useLayoutEffect, useMemo, forwardRef } from "react";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useTraceIssueLabels } from "./use-trace-issue-labels";
import { Virtuoso, type VirtuosoHandle, type Components } from "react-virtuoso";
import {
Bot,
@@ -68,7 +70,6 @@ import {
isCallStep,
isGroupRow,
rowCalls,
- shouldShowTimeline,
toolKindTotals,
type TraceCallStep,
type TraceGroupRow,
@@ -116,6 +117,8 @@ interface AgentTranscriptDialogProps {
items: TimelineItem[];
agentName: string;
isLive?: boolean;
+ /** Loading/error content while the caller retrieves the transcript. */
+ contentState?: React.ReactNode;
/**
* Optional content rendered between the header chips and the event list.
* Used by autopilot run rows to surface the inbound webhook trigger
@@ -305,9 +308,11 @@ export function AgentTranscriptDialog({
agentName,
isLive = false,
headerSlot,
+ contentState,
}: AgentTranscriptDialogProps) {
const { t } = useT("agents");
const locale = useLocale();
+ const formatText = useTraceIssueLabels(useWorkspaceId(), task.issue_id, items, open);
const [selectedSeq, setSelectedSeq] = useState<number | null>(null);
const [expandedGroups, setExpandedGroups] = useState<Set<number>>(() => new Set());
const [query, setQuery] = useState("");
@@ -494,10 +499,13 @@ export function AgentTranscriptDialog({
if (activeFilterSet.size === 0 && trimmedQuery.length === 0) return steps;
return steps.filter((step) => {
if (activeFilterSet.size > 0 && !activeFilterSet.has(stepFilterKey(step))) return false;
- if (trimmedQuery.length > 0 && !stepHaystack(step).includes(trimmedQuery)) return false;
+ if (trimmedQuery.length > 0) {
+ const raw = stepHaystack(step);
+ if (!raw.includes(trimmedQuery) && !formatText(raw).toLowerCase().includes(trimmedQuery)) return false;
+ }
return true;
});
- }, [steps, activeFilterSet, trimmedQuery]);
+ }, [steps, activeFilterSet, trimmedQuery, formatText]);
// Grouping runs on what the reader is looking at: filtering breaks adjacency,
// and a group that spans a hidden step would be a lie about what ran.
@@ -523,9 +531,6 @@ export function AgentTranscriptDialog({
const runEnd = task.completed_at ?? lastStamp;
const lanes = useMemo(() => buildLanes(steps, runStart, runEnd), [steps, runStart, runEnd]);
- // A short run's timeline says less than the durations already on each row,
- // so it does not render at all.
- const showTimeline = shouldShowTimeline(steps, lanes);
const toolKinds = useMemo(() => toolKindTotals(steps), [steps]);
const outcome = useMemo(() => buildRunOutcome(steps), [steps]);
@@ -1070,7 +1075,7 @@ export function AgentTranscriptDialog({
<RunOutcomeRow outcome={outcome} branch={task.branch_name} />
{/* ── Where the time went ────────────────────────────────────── */}
- {showTimeline && lanes && (
+ {lanes && (
<RunTimeline
lanes={lanes}
toolKinds={toolKinds}
@@ -1197,7 +1202,7 @@ export function AgentTranscriptDialog({
{/* ── Steps, and the inspector when one is selected ───────────── */}
<div className="flex min-h-0 flex-1">
<div className="flex min-w-0 flex-1 flex-col">
- {displayRows.length === 0 ? (
+ {contentState ? <div className="flex h-full items-center justify-center p-4">{contentState}</div> : displayRows.length === 0 ? (
<div className="flex h-full items-center justify-center text-body text-muted-foreground">
{isAntigravityLiveEmpty ? (
<div className="flex max-w-md items-center gap-2 px-4 text-center">
@@ -1244,6 +1249,7 @@ export function AgentTranscriptDialog({
itemContent={(_, row) => (
<TranscriptRow
row={row}
+ formatText={formatText}
runStartMs={runStartMs}
isLive={isLive}
selectedSeq={selectedSeq}
@@ -1355,6 +1361,7 @@ function RunOutcomeRow({
// ─── Rows ───────────────────────────────────────────────────────────────────
interface TranscriptRowProps {
+ formatText: (text: string) => string;
row: TraceRow;
runStartMs?: number;
isLive: boolean;
@@ -1444,6 +1451,7 @@ function ProseRow({ row, runStartMs }: TranscriptRowProps & { row: TraceMessageS
* click away in the inspector. */
function StepRow({
row,
+ formatText,
runStartMs,
isLive,
selectedSeq,
@@ -1452,10 +1460,11 @@ function StepRow({
const { t } = useT("agents");
const summaryLabels = useMemo<TraceSummaryLabels>(
() => ({
+ formatText,
morePaths: (path, extraCount) =>
t(($) => $.transcript.patch_summary_more, { path, extra: extraCount }),
}),
- [t],
+ [t, formatText],
);
const call = isCallStep(row) ? row : null;
@@ -1522,6 +1531,7 @@ function StepRow({
/** Consecutive same-tool calls, folded to one line until asked. */
function GroupRow({
row,
+ formatText,
runStartMs,
selectedSeq,
expanded,
@@ -1531,10 +1541,11 @@ function GroupRow({
const { t } = useT("agents");
const summaryLabels = useMemo<TraceSummaryLabels>(
() => ({
+ formatText,
morePaths: (path, extraCount) =>
t(($) => $.transcript.patch_summary_more, { path, extra: extraCount }),
}),
- [t],
+ [t, formatText],
);
return (
@@ -1607,7 +1618,7 @@ function callSummary(step: TraceCallStep, labels: TraceSummaryLabels): string {
}
if (!step.result) return "";
if (readImageResult(step.result.output)) return "";
- return traceEventSummary({ type: "tool_result", output: step.result.output });
+ return traceEventSummary({ type: "tool_result", output: step.result.output }, labels);
}
function firstLineOf(value: string | undefined): string {
@@ -1731,7 +1742,7 @@ function InspectorSection({ label, children }: { label: string; children: React.
}
/** One payload, rendered as what it is. */
-function StepBody({ item }: { item: TimelineItem }) {
+export function StepBody({ item }: { item: TimelineItem }) {
const { t } = useT("agents");
const detail = useMemo(() => traceEventDetail(item), [item]);
const image = useMemo(() => readImageResult(item.output), [item.output]);
diff --git a/packages/views/common/task-transcript/build-steps.test.ts b/packages/views/common/task-transcript/build-steps.test.ts
index 6d479d4b8d..e586d2efd8 100644
--- a/packages/views/common/task-transcript/build-steps.test.ts
+++ b/packages/views/common/task-transcript/build-steps.test.ts
@@ -6,7 +6,6 @@ import {
groupSteps,
laneSegmentPosition,
rowCalls,
- shouldShowTimeline,
timelineTicks,
toolKindTotals,
type TraceCallStep,
@@ -304,33 +303,3 @@ describe("toolKindTotals", () => {
});
});
});
-
-describe("shouldShowTimeline", () => {
- function longRun(stepCount: number, seconds: number) {
- const items: TimelineItem[] = [];
- for (let i = 0; i < stepCount; i++) {
- const start = (seconds / stepCount) * i;
- items.push(call("Bash", start), result("Bash", start + 1));
- }
- return buildSteps(items);
- }
-
- it("shows for a long run with many steps", () => {
- const steps = longRun(10, 600);
- expect(shouldShowTimeline(steps, buildLanes(steps, at(0), at(600)))).toBe(true);
- });
-
- it("hides for a short run — a handful of bars says less than the row durations", () => {
- const steps = longRun(3, 600);
- expect(shouldShowTimeline(steps, buildLanes(steps, at(0), at(600)))).toBe(false);
- });
-
- it("hides for a fast run even with many steps", () => {
- const steps = longRun(10, 20);
- expect(shouldShowTimeline(steps, buildLanes(steps, at(0), at(20)))).toBe(false);
- });
-
- it("hides when lanes could not be built", () => {
- expect(shouldShowTimeline(longRun(10, 600), null)).toBe(false);
- });
-});
diff --git a/packages/views/common/task-transcript/build-steps.ts b/packages/views/common/task-transcript/build-steps.ts
index 040fbeab97..a59fe3a5ef 100644
--- a/packages/views/common/task-transcript/build-steps.ts
+++ b/packages/views/common/task-transcript/build-steps.ts
@@ -426,13 +426,3 @@ export function toolKindTotals(steps: TraceStep[]): ToolKindTotals {
}
return totals;
}
-
-/** Below these, a timeline is chrome: it would render a handful of bars that
- * say less than the durations already on each row. */
-export const TIMELINE_MIN_STEPS = 8;
-export const TIMELINE_MIN_MS = 60_000;
-
-export function shouldShowTimeline(steps: TraceStep[], lanes: TraceLanes | null): boolean {
- if (!lanes) return false;
- return steps.length >= TIMELINE_MIN_STEPS && lanes.totalMs >= TIMELINE_MIN_MS;
-}
diff --git a/packages/views/common/task-transcript/trace-event-presenter.ts b/packages/views/common/task-transcript/trace-event-presenter.ts
index 35194c7361..99b0a39dde 100644
--- a/packages/views/common/task-transcript/trace-event-presenter.ts
+++ b/packages/views/common/task-transcript/trace-event-presenter.ts
@@ -104,6 +104,8 @@ function clip(value: string, max: number): string {
* keeps the fallback safe rather than blank.
*/
export interface TraceSummaryLabels {
+ /** Resolve known entity IDs before a summary is clipped; evidence stays raw. */
+ formatText?: (text: string) => string;
/**
* Phrase a multi-file patch, e.g. `src/a.go +2 more`.
*
@@ -124,7 +126,7 @@ export function traceToolArgSummary(
labels?: TraceSummaryLabels,
): string {
if (!input) return "";
- const str = (v: unknown): string => (typeof v === "string" ? v : "");
+ const str = (v: unknown): string => (typeof v === "string" ? labels?.formatText?.(v) ?? v : "");
if (str(input.query)) return str(input.query);
// A multi-file patch has no single path field; without this the row's
// summary would fall through to the generic scan and come back empty.
@@ -134,11 +136,12 @@ export function traceToolArgSummary(
if (str(input.path)) return shortenTracePath(str(input.path));
if (str(input.pattern)) return str(input.pattern);
if (str(input.description)) return str(input.description);
- if (str(input.command)) return clip(stripShellWrapper(str(input.command)), 120);
+ const command = str(input.command) || str(input.cmd);
+ if (command) return clip(stripShellWrapper(command), 120);
if (str(input.prompt)) return clip(str(input.prompt), 120);
if (str(input.skill)) return str(input.skill);
for (const v of Object.values(input)) {
- if (typeof v === "string" && v.length > 0 && v.length < 120) return v;
+ if (typeof v === "string" && v.length > 0 && str(v).length < 120) return str(v);
}
return "";
}
@@ -166,7 +169,7 @@ export function traceEventSummary(event: TraceEvent, labels?: TraceSummaryLabels
case "tool_result":
// Unwrap first: the collapsed row is the one people read without
// clicking, so it must not show transport escaping.
- return clip(collapseWhitespace(unwrapToolOutput(event.output ?? "")), 200);
+ return clip(collapseWhitespace(labels?.formatText?.(unwrapToolOutput(event.output ?? "")) ?? unwrapToolOutput(event.output ?? "")), 200);
default:
return firstLine(event.content ?? event.output);
}
diff --git a/packages/views/common/task-transcript/trace-issue-labels.test.ts b/packages/views/common/task-transcript/trace-issue-labels.test.ts
new file mode 100644
index 0000000000..cdfb841f01
--- /dev/null
+++ b/packages/views/common/task-transcript/trace-issue-labels.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { collectTraceIssueIds, replaceTraceIssueIds } from "./trace-issue-labels";
+import { traceEventCopyText, traceEventDetail, traceToolArgSummary } from "./trace-event-presenter";
+
+const issue = "01a07eca-8e82-775e-be06-e4a97ccfa299";
+const other = "01a07cd3-f171-706d-9e76-b3428d0de333";
+const thread = "01a07cd9-610f-7b89-98e2-a194339b1372";
+const labels = new Map([[issue, "DEV-17"], [other, "DEV-14"]]);
+
+describe("trace issue labels", () => {
+ it("resolves only issue targets, deduplicating commands and preserving comment IDs", () => {
+ expect(collectTraceIssueIds(issue, [
+ { type: "tool_use", input: { command: `multica issue comment list '${issue}' --thread ${thread}` } },
+ { type: "tool_use", input: { cmd: `multica issue get ${other.toUpperCase()} --output json` } },
+ { type: "tool_use", input: { issue_id: other } },
+ { type: "tool_use", input: { command: `multica issue comment update ${thread}` } },
+ { type: "tool_result", output: `multica issue get ${thread}` },
+ { type: "text", content: `multica issue get ${thread}` },
+ ])).toEqual([issue, other]);
+ });
+
+ it("replaces exact known UUIDs case-insensitively and leaves unknown IDs intact", () => {
+ expect(replaceTraceIssueIds(`${issue.toUpperCase()} (${other}) --thread ${thread}`, labels))
+ .toBe(`DEV-17 (DEV-14) --thread ${thread}`);
+ expect(replaceTraceIssueIds(`prefix${issue} ${issue}-suffix ${issue}f`, labels))
+ .toBe(`prefix${issue} ${issue}-suffix ${issue}f`);
+ expect(replaceTraceIssueIds(issue, new Map())).toBe(issue);
+ });
+
+ it("formats before truncation without changing raw input, detail or copy text", () => {
+ const command = `multica issue update ${issue} --description '${other} ${issue} visible-tail'`;
+ const input = { command };
+ const event = { type: "tool_use", tool: "exec_command", input };
+ expect(traceToolArgSummary(input, { formatText: (text) => replaceTraceIssueIds(text, labels) }))
+ .toBe("multica issue update DEV-17 --description 'DEV-14 DEV-17 visible-tail'");
+ expect(traceToolArgSummary({ cmd: command }, { formatText: (text) => replaceTraceIssueIds(text, labels) }))
+ .toBe("multica issue update DEV-17 --description 'DEV-14 DEV-17 visible-tail'");
+ expect(input.command).toBe(command);
+ expect(traceEventDetail(event)).toEqual({ kind: "text", text: JSON.stringify(input, null, 2) });
+ expect(traceEventCopyText(event)).toContain(issue);
+ expect(traceEventCopyText(event)).not.toContain("DEV-17");
+ });
+});
diff --git a/packages/views/common/task-transcript/trace-issue-labels.ts b/packages/views/common/task-transcript/trace-issue-labels.ts
new file mode 100644
index 0000000000..36d22af751
--- /dev/null
+++ b/packages/views/common/task-transcript/trace-issue-labels.ts
@@ -0,0 +1,34 @@
+import type { TraceEvent } from "./trace-event-presenter";
+
+const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
+const UUID_VALUE = new RegExp(`^${UUID}$`, "i");
+// Only these positional arguments identify issues. In particular --thread and
+// --parent identify comments, and must never be sent to the issue resolver.
+const ISSUE_COMMAND = new RegExp(
+ `\\bmultica\\s+issue\\s+(?:get|update|comment\\s+(?:list|add))\\s+["']?(${UUID})(?![\\w-])`,
+ "gi",
+);
+
+export function collectTraceIssueIds(issueId: string, events: readonly TraceEvent[]): string[] {
+ const ids = new Set<string>();
+ const add = (id: unknown) => {
+ if (typeof id === "string" && UUID_VALUE.test(id)) ids.add(id.toLowerCase());
+ };
+ add(issueId);
+ for (const event of events) {
+ if (event.type !== "tool_use" || !event.input) continue;
+ add(event.input.issue_id);
+ for (const key of ["command", "cmd"]) {
+ const command = event.input[key];
+ if (typeof command !== "string") continue;
+ for (const match of command.matchAll(ISSUE_COMMAND)) add(match[1]);
+ }
+ }
+ return [...ids];
+}
+
+/** Display-only: never rewrite stored events, expanded evidence, or clipboard text. */
+export function replaceTraceIssueIds(text: string, labels: ReadonlyMap<string, string>): string {
+ return text.replace(new RegExp(`(?<![\\w-])${UUID}(?![\\w-])`, "gi"),
+ (id) => labels.get(id.toLowerCase()) ?? id);
+}
diff --git a/packages/views/common/task-transcript/use-trace-issue-labels.ts b/packages/views/common/task-transcript/use-trace-issue-labels.ts
new file mode 100644
index 0000000000..bf46d90e1b
--- /dev/null
+++ b/packages/views/common/task-transcript/use-trace-issue-labels.ts
@@ -0,0 +1,23 @@
+"use client";
+
+import { useCallback, useMemo } from "react";
+import { useQueries } from "@tanstack/react-query";
+import { issueDetailOptions } from "@multica/core/issues/queries";
+import type { TraceEvent } from "./trace-event-presenter";
+import { collectTraceIssueIds, replaceTraceIssueIds } from "./trace-issue-labels";
+
+export function useTraceIssueLabels(wsId: string, issueId: string, events: readonly TraceEvent[], enabled = true) {
+ const ids = useMemo(() => collectTraceIssueIds(issueId, events), [issueId, events]);
+ const issues = useQueries({
+ queries: ids.map((id) => ({
+ ...issueDetailOptions(wsId, id),
+ enabled: enabled && !!wsId,
+ staleTime: 60_000,
+ retry: false,
+ })),
+ combine: (results) => results.flatMap(({ data }) =>
+ data?.id && data.identifier ? [{ id: data.id, identifier: data.identifier }] : []),
+ });
+ const labels = useMemo(() => new Map(issues.map((issue) => [issue.id.toLowerCase(), issue.identifier])), [issues]);
+ return useCallback((text: string) => replaceTraceIssueIds(text, labels), [labels]);
+}
diff --git a/packages/views/issues/components/active-task-order.test.ts b/packages/views/issues/components/active-task-order.test.ts
new file mode 100644
index 0000000000..8c61954c88
--- /dev/null
+++ b/packages/views/issues/components/active-task-order.test.ts
@@ -0,0 +1,28 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { AgentTask } from "@multica/core/types";
+import { compareActiveIssueTasks } from "./active-task-order";
+
+const task = (id: string, status: AgentTask["status"], priority = 0, created_at = "2026-09-08T03:00:00Z") =>
+ ({ id, status, priority, created_at });
+const ids = (tasks: ReturnType<typeof task>[]) => tasks.toSorted(compareActiveIssueTasks).map((t) => t.id);
+
+describe("active issue task display order", () => {
+ it("keeps running and already claimed tasks ahead of pending work", () => {
+ expect(ids([task("queued", "queued", 10), task("parked", "waiting_local_directory"),
+ task("dispatched", "dispatched"), task("running", "running")]))
+ .toEqual(["running", "dispatched", "parked", "queued"]);
+ });
+
+ it("matches queue priority descending, enqueue time ascending, then task ID", () => {
+ expect(ids([task("new", "queued", 0, "2026-09-08T04:00:00Z"),
+ task("old-b", "queued"), task("urgent", "queued", 2, "2026-09-08T05:00:00Z"),
+ task("old-a", "queued")])).toEqual(["urgent", "old-a", "old-b", "new"]);
+ });
+
+ it("compares timestamp instants instead of timezone strings", () => {
+ expect(ids([task("later", "queued", 0, "2026-09-08T03:01:00Z"),
+ task("earlier", "queued", 0, "2026-09-08T11:00:00+08:00")])).toEqual(["earlier", "later"]);
+ expect(compareActiveIssueTasks(task("a", "queued", 0, "2026-09-08T11:00:00+08:00"), task("b", "queued"))).toBeLessThan(0);
+ });
+});
diff --git a/packages/views/issues/components/active-task-order.ts b/packages/views/issues/components/active-task-order.ts
new file mode 100644
index 0000000000..a73a58b351
--- /dev/null
+++ b/packages/views/issues/components/active-task-order.ts
@@ -0,0 +1,21 @@
+import type { AgentTask } from "@multica/core/types";
+
+type OrderedTask = Pick<AgentTask, "id" | "status" | "priority" | "created_at">;
+
+function phase(task: OrderedTask): number {
+ if (task.status === "running") return 0;
+ if (task.status === "dispatched" || task.status === "waiting_local_directory") return 1;
+ return 2;
+}
+
+/** Show current execution first, then queued work in ClaimAgentTask order. */
+export function compareActiveIssueTasks(a: OrderedTask, b: OrderedTask): number {
+ const phaseDiff = phase(a) - phase(b);
+ if (phaseDiff) return phaseDiff;
+ const priorityDiff = (b.priority ?? 0) - (a.priority ?? 0);
+ if (priorityDiff) return priorityDiff;
+ // Queue age belongs to the run, not its latest coalesced comment. Parse
+ // timestamps so equivalent instants with different offsets sort identically.
+ const ageDiff = Date.parse(a.created_at) - Date.parse(b.created_at);
+ return (Number.isFinite(ageDiff) ? ageDiff : 0) || a.id.localeCompare(b.id);
+}
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 17e724947e..b9dee1bf2b 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -1,10 +1,10 @@
"use client";
-import { memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";
+import { Fragment, memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { CheckCircle2, ChevronRight, ListChevronsDownUp, Copy, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Card } from "@multica/ui/components/ui/card";
-import { Button } from "@multica/ui/components/ui/button";
+import { Button, buttonVariants } from "@multica/ui/components/ui/button";
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -25,6 +25,7 @@ import {
} from "@multica/ui/components/ui/alert-dialog";
import { ActorAvatar } from "../../common/actor-avatar";
import { ReactionBar } from "@multica/ui/components/common/reaction-bar";
+import { QuickEmojiPicker } from "@multica/ui/components/common/quick-emoji-picker";
import { cn } from "@multica/ui/lib/utils";
import { copyText } from "@multica/ui/lib/clipboard";
import { useActorName } from "@multica/core/workspace/hooks";
@@ -44,6 +45,12 @@ 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 { useRunCommentMotion } from "./use-run-comment-motion";
+
+const commentActionClassName =
+ "text-muted-foreground aria-expanded:bg-transparent aria-expanded:hover:bg-muted dark:aria-expanded:hover:bg-muted/50";
const highlightedCommentBackgroundClass =
"bg-[color-mix(in_srgb,var(--card)_95%,var(--brand)_5%)]";
@@ -89,6 +96,9 @@ function StickyHeaderShell({
interface CommentCardProps {
issueId: string;
+ runs?: CommentRun[];
+ runViewState?: InlineCommentRunState;
+ enteringRunIds?: ReadonlySet<string>;
entry: TimelineEntry;
/**
* Flat list of every nested reply under this thread root, in render order.
@@ -586,6 +596,8 @@ function CommentRevisionConflict({
// ---------------------------------------------------------------------------
function CommentRow({
+ runHeader,
+ runMetadata,
issueId,
entry,
currentUserId,
@@ -598,6 +610,8 @@ function CommentRow({
onCreateSubIssue,
onResolveToggle,
}: {
+ runHeader?: ReactNode;
+ runMetadata?: ReactNode;
issueId: string;
entry: TimelineEntry;
currentUserId?: string;
@@ -627,7 +641,7 @@ function CommentRow({
const reactions = entry.reactions ?? [];
return (
- <div className="py-1.5">
+ <div data-comment-block className="pb-3">
{/* Header pins to the timeline's scroll parent within this reply's own
row box, so a LONG reply keeps its
author + actions visible while you scroll its body, then releases once
@@ -635,7 +649,7 @@ function CommentRow({
highlight state while it occludes the body scrolling underneath. */}
<StickyHeaderShell
highlighted={isHighlighted}
- className="flex items-center gap-2.5 px-4 max-md:px-3 pt-1 pb-1.5"
+ className="flex items-center gap-2.5 px-4 max-md:px-3 pt-3 pb-2"
>
<ActorAvatar
actorType={entry.actor_type}
@@ -663,20 +677,28 @@ function CommentRow({
</TooltipContent>
</Tooltip>
+ {runHeader}
+
{isResolution && (
<span className="text-caption font-medium text-success">
{t(($) => $.comment.resolve.resolution_badge)}
</span>
)}
- <div className="ml-auto flex items-center gap-0.5">
+ <div data-comment-actions className="ml-auto flex shrink-0 items-center gap-0.5">
+ {!edit.editing && <QuickEmojiPicker
+ onSelect={(emoji) => onToggleReaction(entry.id, emoji)}
+ ariaLabel={t(($) => $.comment.add_reaction)}
+ align="end"
+ className={buttonVariants({ variant: "ghost", size: "icon-sm", className: commentActionClassName })}
+ />}
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button
variant="ghost"
size="icon-sm"
- className="text-muted-foreground"
+ className={commentActionClassName}
aria-label={t(($) => $.comment.more_actions)}
>
<MoreHorizontal className="h-4 w-4" aria-hidden />
@@ -822,7 +844,7 @@ function CommentRow({
</div>
) : (
<>
- <div className="pl-12 pr-4 max-md:pl-3 max-md:pr-3 pt-1 text-body leading-relaxed text-foreground">
+ <div data-comment-content={entry.id} className="pl-12 pr-4 max-md:pl-3 max-md:pr-3 text-body leading-relaxed text-foreground">
<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" />
@@ -833,15 +855,49 @@ function CommentRow({
className="mt-2 pl-12 pr-4 max-md:pl-3 max-md:pr-3"
/>
)}
- <ReactionBar
- reactions={reactions}
- currentUserId={currentUserId}
- onToggle={(emoji) => onToggleReaction(entry.id, emoji)}
- getActorName={getActorName}
- 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">{runMetadata}</div>
+ {!edit.editing && <ReactionBar
+ reactions={reactions}
+ showPicker={false}
+ currentUserId={currentUserId}
+ onToggle={(emoji) => onToggleReaction(entry.id, emoji)}
+ getActorName={getActorName}
+ className="mt-1.5 pl-12 pr-4 max-md:pl-3 max-md:pr-3"
+ />}
+ </div>
+ );
+}
+
+/** A run without a persisted reply still belongs to the agent, never its trigger author. */
+export function AgentRunComment({ run, standalone = false, commentProps, entering = false }: {
+ run: CommentRun;
+ standalone?: boolean;
+ entering?: boolean;
+ commentProps?: CommentCardProps;
+}) {
+ const viewState = useInlineCommentRunState();
+ const reply = commentProps?.entry;
+ const motionRef = useRunCommentMotion(entering, reply?.id, run.task.status);
+ return (
+ <div ref={motionRef} data-run-slot-id={run.task.id}
+ data-run-comment-id={!reply ? run.task.id : undefined}
+ id={!standalone && reply ? `comment-${reply.id}` : undefined}
+ className={cn(standalone ? !reply && "rounded-xl border bg-card" : "border-t border-border/50", !reply && "py-1.5", reply && commentProps?.highlightedCommentId === reply.id && highlightedCommentBackgroundClass)}>
+ {commentProps ? standalone ? (
+ <CommentCard {...commentProps} runs={commentProps.runs ?? [run]} runViewState={viewState} />
+ ) : (
+ <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} />
+ ) : <div className="px-4 max-md:px-3">
+ <InlineCommentRun run={run} viewState={viewState} showIdentity />
+ </div>}
</div>
);
}
@@ -859,6 +915,9 @@ function CommentRow({
function CommentCardImpl({
issueId,
+ runs = EMPTY_COMMENT_RUNS,
+ runViewState,
+ enteringRunIds,
entry,
replies,
currentUserId,
@@ -895,6 +954,22 @@ function CommentCardImpl({
const [confirmDelete, setConfirmDelete] = useState(false);
const allNestedReplies = replies;
+ const slottedReplyIds = new Set(runs.filter((run) => run.hasReply && run.anchorCommentId && run.commentId !== entry.id)
+ .map((run) => run.commentId));
+ 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} />);
+
+ const renderAnchoredRuns = (commentId: string) => runs.filter((run) => run.anchorCommentId === commentId
+ && !(replyFolded && run.hasReply))
+ .map((run) => {
+ const reply = run.hasReply ? allNestedReplies.find((entry) => entry.id === run.commentId) : undefined;
+ return <Fragment key={run.task.id}><AgentRunComment run={run} entering={enteringRunIds?.has(run.task.id)} commentProps={reply ? {
+ issueId, entry: reply, replies: [], currentUserId, canModerate, onReply, onEdit, onDelete,
+ onToggleReaction, onCreateSubIssue, onResolveToggle, highlightedCommentId, enteringRunIds,
+ } : undefined} />{reply && reply.id !== commentId && renderAnchoredRuns(reply.id)}</Fragment>;
+ });
const replyCount = allNestedReplies.length;
const contentPreview = (entry.content ?? "").replace(/\n/g, " ").slice(0, 80);
@@ -952,23 +1027,14 @@ function CommentCardImpl({
That is what keeps exactly one header pinned at a time: without this
wrapper the header's containing block is the whole thread and it
stays stuck behind every reply. */}
- <div className={cn("transition-colors duration-700", isHighlighted && highlightedCommentBackgroundClass)}>
- {/* Header — always visible, acts as toggle */}
+ <div data-comment-block className={cn("transition-colors duration-700", isHighlighted && highlightedCommentBackgroundClass)}>
+ {/* Keep the author aligned with replies; thread controls sit on the right. */}
<StickyHeaderShell
sticky={stickyHeader}
highlighted={isHighlighted}
- className="px-4 max-md:px-3 py-3"
+ className={cn("px-4 max-md:px-3", open ? "pt-3 pb-2" : "py-3")}
>
<div className="flex items-center gap-2.5">
- <button
- type="button"
- aria-expanded={open}
- aria-controls={`comment-body-${entry.id}`}
- onClick={handleToggle}
- className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- >
- <ChevronRight className={cn("h-3.5 w-3.5 transition-transform", open && "rotate-90")} />
- </button>
<ActorAvatar
actorType={entry.actor_type}
actorId={entry.actor_id}
@@ -995,6 +1061,8 @@ function CommentCardImpl({
</TooltipContent>
</Tooltip>
+ {renderRuns(entry.id, "header")}
+
{!open && contentPreview && (
<span className="min-w-0 flex-1 truncate text-caption text-muted-foreground">
{contentPreview}
@@ -1006,15 +1074,34 @@ function CommentCardImpl({
</span>
)}
- {open && (
- <div className="ml-auto flex items-center gap-0.5">
+ <div data-comment-actions className="ml-auto flex shrink-0 items-center gap-0.5">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={open ? t(($) => $.comment.collapse_thread) : t(($) => $.comment.expand_thread)}
+ title={open ? t(($) => $.comment.collapse_thread) : t(($) => $.comment.expand_thread)}
+ aria-expanded={open}
+ aria-controls={open ? `comment-body-${entry.id}` : undefined}
+ onClick={handleToggle}
+ className={commentActionClassName}
+ >
+ <ChevronRight aria-hidden className={cn("h-3.5 w-3.5 transition-transform motion-reduce:transition-none", open && "rotate-90")} />
+ </Button>
+ {open && <>
+ {!edit.editing && <QuickEmojiPicker
+ onSelect={(emoji) => onToggleReaction(entry.id, emoji)}
+ ariaLabel={t(($) => $.comment.add_reaction)}
+ align="end"
+ className={buttonVariants({ variant: "ghost", size: "icon-sm", className: commentActionClassName })}
+ />}
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button
variant="ghost"
size="icon-sm"
- className="text-muted-foreground"
+ className={commentActionClassName}
aria-label={t(($) => $.comment.more_actions)}
>
<MoreHorizontal className="h-4 w-4" aria-hidden />
@@ -1080,8 +1167,8 @@ function CommentCardImpl({
onConfirm={() => onDelete(entry.id)}
hasReplies
/>
- </div>
- )}
+ </>}
+ </div>
</div>
</StickyHeaderShell>
@@ -1089,11 +1176,11 @@ function CommentCardImpl({
probes computed styles to detect animations, forcing a style
recalculation across long issue-detail documents. */}
{open && (
- <div id={`comment-body-${entry.id}`} className="px-4 max-md:px-3 pt-1 pb-3">
+ <div id={`comment-body-${entry.id}`} className="px-4 max-md:px-3 pb-3">
{edit.editing ? (
<div
{...edit.dropZoneProps}
- className="relative pl-10 max-md:pl-0"
+ className="relative pl-8 max-md:pl-0"
onKeyDown={(e) => { if (e.key === "Escape") edit.cancelEdit(); }}
>
<div className="text-body leading-relaxed">
@@ -1170,26 +1257,28 @@ function CommentCardImpl({
</div>
) : (
<>
- <div className="pl-10 max-md:pl-0 text-body leading-relaxed text-foreground">
+ <div data-comment-content={entry.id} className="pl-8 max-md:pl-0 text-body leading-relaxed text-foreground">
<ReadonlyContent content={entry.content ?? ""} attachments={entry.attachments} />
</div>
- <AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-10 max-md:pl-0" />
+ <AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-8 max-md:pl-0" />
{retryableAgentFailureComment(entry) && (
<TaskCommentRetryButton
issueId={issueId}
taskId={entry.source_task_id}
- className="mt-2 pl-10 max-md:pl-0"
+ className="mt-2 pl-8 max-md:pl-0"
/>
)}
- <ReactionBar
- reactions={reactions}
- currentUserId={currentUserId}
- onToggle={(emoji) => onToggleReaction(entry.id, emoji)}
- getActorName={getActorName}
- className="mt-1.5 pl-10 max-md:pl-0"
- />
</>
)}
+ <div className="pl-8 max-md:pl-0">{renderRuns(entry.id)}</div>
+ {!edit.editing && <ReactionBar
+ reactions={reactions}
+ showPicker={false}
+ currentUserId={currentUserId}
+ onToggle={(emoji) => onToggleReaction(entry.id, emoji)}
+ getActorName={getActorName}
+ className="mt-1.5 pl-8 max-md:pl-0"
+ />}
</div>
)}
</div>
@@ -1199,6 +1288,7 @@ function CommentCardImpl({
to mirror the body Panel's collapse visibility. */}
{open && (
<>
+ {renderAnchoredRuns(entry.id)}
{replyFolded ? (
<>
{/* reply-mode folded: other replies behind a bar, resolution pinned below */}
@@ -1211,27 +1301,32 @@ function CommentCardImpl({
</div>
)}
{resolutionReply && (
- <div
- id={`comment-${resolutionReply.id}`}
- className={cn(
- "border-t border-border/50 transition-colors duration-700",
- highlightedCommentId === resolutionReply.id && highlightedCommentBackgroundClass,
- )}
- >
- <CommentRow
- issueId={issueId}
- entry={resolutionReply}
- currentUserId={currentUserId}
- canModerate={canModerate}
- isResolution
- isHighlighted={highlightedCommentId === resolutionReply.id}
- onEdit={onEdit}
- onDelete={onDelete}
- onToggleReaction={onToggleReaction}
- onCreateSubIssue={onCreateSubIssue}
- onResolveToggle={onResolveToggle}
- />
- </div>
+ <>
+ <div
+ id={`comment-${resolutionReply.id}`}
+ className={cn(
+ "border-t border-border/50 transition-colors duration-700",
+ highlightedCommentId === resolutionReply.id && highlightedCommentBackgroundClass,
+ )}
+ >
+ <CommentRow
+ issueId={issueId}
+ entry={resolutionReply}
+ runHeader={renderRuns(resolutionReply.id, "header")}
+ runMetadata={renderRuns(resolutionReply.id)}
+ currentUserId={currentUserId}
+ canModerate={canModerate}
+ isResolution
+ isHighlighted={highlightedCommentId === resolutionReply.id}
+ onEdit={onEdit}
+ onDelete={onDelete}
+ onToggleReaction={onToggleReaction}
+ onCreateSubIssue={onCreateSubIssue}
+ onResolveToggle={onResolveToggle}
+ />
+ </div>
+ {renderAnchoredRuns(resolutionReply.id)}
+ </>
)}
</>
) : (
@@ -1249,29 +1344,33 @@ function CommentCardImpl({
</button>
)}
{/* Replies — chronological; the resolution keeps its place with a badge */}
- {allNestedReplies.map((reply) => (
- <div
- key={reply.id}
- id={`comment-${reply.id}`}
- className={cn(
- "border-t border-border/50 transition-colors duration-700",
- highlightedCommentId === reply.id && highlightedCommentBackgroundClass,
- )}
- >
- <CommentRow
- issueId={issueId}
- entry={reply}
- currentUserId={currentUserId}
- canModerate={canModerate}
- isResolution={reply.id === replyResolutionId}
- isHighlighted={highlightedCommentId === reply.id}
- onEdit={onEdit}
- onDelete={onDelete}
- onToggleReaction={onToggleReaction}
- onCreateSubIssue={onCreateSubIssue}
- onResolveToggle={onResolveToggle}
- />
- </div>
+ {allNestedReplies.filter((reply) => !slottedReplyIds.has(reply.id)).map((reply) => (
+ <Fragment key={reply.id}>
+ <div
+ id={`comment-${reply.id}`}
+ className={cn(
+ "border-t border-border/50 transition-colors duration-700",
+ highlightedCommentId === reply.id && highlightedCommentBackgroundClass,
+ )}
+ >
+ <CommentRow
+ issueId={issueId}
+ entry={reply}
+ runHeader={renderRuns(reply.id, "header")}
+ runMetadata={renderRuns(reply.id)}
+ currentUserId={currentUserId}
+ canModerate={canModerate}
+ isResolution={reply.id === replyResolutionId}
+ isHighlighted={highlightedCommentId === reply.id}
+ onEdit={onEdit}
+ onDelete={onDelete}
+ onToggleReaction={onToggleReaction}
+ onCreateSubIssue={onCreateSubIssue}
+ onResolveToggle={onResolveToggle}
+ />
+ </div>
+ {renderAnchoredRuns(reply.id)}
+ </Fragment>
))}
{/* Reply input */}
diff --git a/packages/views/issues/components/comment-runs.test.ts b/packages/views/issues/components/comment-runs.test.ts
new file mode 100644
index 0000000000..81f5f13a7e
--- /dev/null
+++ b/packages/views/issues/components/comment-runs.test.ts
@@ -0,0 +1,213 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { AgentTask, TimelineEntry } from "@multica/core/types";
+import { commentRunOutput, buildCommentRunView } from "./comment-runs";
+
+const groupCommentRuns = (...args: Parameters<typeof buildCommentRunView>) => buildCommentRunView(...args).runs;
+
+function task(id: string, overrides: Partial<AgentTask> = {}): AgentTask {
+ return { id, agent_id: "agent", runtime_id: "runtime", issue_id: "issue", status: "running", priority: 0,
+ created_at: "2026-09-07T00:00:00Z", started_at: null, dispatched_at: null, completed_at: null, result: null, error: null, ...overrides };
+}
+function comment(id: string, overrides: Partial<TimelineEntry> = {}): TimelineEntry {
+ return { id, type: "comment", actor_type: "member", actor_id: "user", created_at: "2026-09-07T00:00:00Z", ...overrides };
+}
+
+describe("groupCommentRuns", () => {
+ it.each(["queued", "dispatched", "running", "completed"] as const)("waits for a missing trigger before placing a %s run and its reply", (status) => {
+ const run = task("run", { status, trigger_comment_id: "trigger",
+ delivered_comment_ids: status === "queued" || status === "dispatched" ? [] : ["trigger"] });
+ const root = comment("root");
+ const trigger = comment("trigger", { parent_id: root.id });
+ const before = buildCommentRunView([run], [root]);
+ expect(before.standaloneRuns).toEqual([]);
+ expect(before.runs.size).toBe(0);
+ const reply = comment("answer", { actor_type: "agent", source_task_id: run.id });
+ const earlyReply = buildCommentRunView([run], [root, reply]);
+ expect(earlyReply.standaloneRuns).toEqual([]);
+ expect(earlyReply.timeline.find((entry) => entry.id === reply.id)?.parent_id).toBe(trigger.id);
+ const after = buildCommentRunView([run], [root, trigger, reply]);
+ expect(after.standaloneRuns).toEqual([]);
+ expect(after.runs.get(root.id)).toEqual([{ task: run, anchorCommentId: trigger.id, commentId: reply.id, hasReply: true }]);
+ });
+
+ it("waits for the intended merged trigger and preserves retry ancestry", () => {
+ const original = task("original", { status: "queued", trigger_comment_id: "new", coalesced_comment_ids: ["old"], delivered_comment_ids: [] });
+ const retry = task("retry", { status: "queued", parent_task_id: original.id, delivered_comment_ids: [] });
+ const old = comment("old");
+ const next = comment("new", { parent_id: old.id });
+ const before = buildCommentRunView([original, retry], [old]);
+ expect(before.standaloneRuns).toEqual([]);
+ expect(before.runs.size).toBe(0);
+ const after = buildCommentRunView([original, retry], [old, next]);
+ expect(after.runs.get(old.id)?.map((run) => run.anchorCommentId)).toEqual([old.id, old.id]);
+ expect(after.standaloneRuns).toEqual([]);
+ });
+
+ it("keeps a queued run in place as its thread receives more instructions and its answer", () => {
+ const root = comment("root");
+ const first = comment("first", { parent_id: root.id });
+ const other = comment("other-thread");
+ const second = comment("second", { parent_id: root.id, created_at: "2026-09-07T00:01:00Z" });
+ const run = task("run", { status: "queued", trigger_comment_id: first.id });
+ const before = buildCommentRunView([run], [root, first, other]);
+ const merged = { ...run, trigger_comment_id: second.id, coalesced_comment_ids: [first.id] };
+ const awaitingComment = buildCommentRunView([merged], [root, first, other], before.runs);
+ expect(awaitingComment.runs.get(root.id)?.[0]?.anchorCommentId).toBe(first.id);
+ const after = buildCommentRunView([merged], [root, first, other, second], before.runs);
+ expect(after.runs.get(root.id)?.[0]?.anchorCommentId).toBe(first.id);
+ expect(after.runs.has(other.id)).toBe(false);
+ const answer = comment("answer", { actor_type: "agent", source_task_id: run.id });
+ const complete = buildCommentRunView([{ ...merged, status: "completed", delivered_comment_ids: [first.id, second.id] }], [root, first, other, second, answer]);
+ expect(complete.runs.get(root.id)?.[0]).toMatchObject({ anchorCommentId: first.id, commentId: answer.id, hasReply: true });
+ });
+
+ it("projects chained answers and assignment subtrees before finding run roots", () => {
+ const first = task("first", { trigger_comment_id: "root" });
+ const second = task("second", { trigger_comment_id: "answer-a" });
+ const assigned = task("assigned");
+ const followup = task("followup", { trigger_comment_id: "nested" });
+ const timeline = [comment("root"),
+ comment("answer-a", { actor_type: "agent", source_task_id: first.id }),
+ comment("answer-b", { actor_type: "agent", source_task_id: second.id }),
+ comment("assigned-answer", { parent_id: "root", actor_type: "agent", source_task_id: assigned.id }),
+ comment("nested", { parent_id: "assigned-answer" })];
+ const view = buildCommentRunView([followup, second, assigned, first], timeline);
+ expect(view.runs.get("root")?.map((run) => run.task.id)).toEqual(["first", "second"]);
+ expect(view.runs.get("assigned-answer")?.map((run) => run.task.id)).toEqual(["assigned", "followup"]);
+ expect(view.timeline.find((entry) => entry.id === "answer-a")?.parent_id).toBe("root");
+ expect(view.timeline.find((entry) => entry.id === "answer-b")?.parent_id).toBe("answer-a");
+ expect(view.timeline.find((entry) => entry.id === "assigned-answer")?.parent_id).toBeUndefined();
+ expect(timeline.find((entry) => entry.id === "assigned-answer")?.parent_id).toBe("root");
+ });
+
+ it("does not project reply relationships that would create a comment cycle", () => {
+ const first = task("first", { trigger_comment_id: "b" });
+ const second = task("second", { trigger_comment_id: "a" });
+ const timeline = [comment("a", { actor_type: "agent", source_task_id: first.id }),
+ comment("b", { actor_type: "agent", source_task_id: second.id })];
+ expect(buildCommentRunView([first, second], timeline).timeline).toEqual(timeline);
+ });
+ it("replaces invalidated queued runs without adding cancelled comment blocks", () => {
+ const old = task("old", { status: "cancelled", trigger_comment_id: "root", cancelled_by_comment_change: true });
+ const next = task("new", { status: "queued", trigger_comment_id: "root" });
+ const later = task("later", { status: "queued", trigger_comment_id: "followup" });
+ const tasks = [old, { ...old, id: "second-edit" }, next, later];
+ const timeline = [comment("root"), comment("followup", { parent_id: "root" })];
+ const grouped = groupCommentRuns(tasks, timeline);
+ expect(grouped.get("root")?.map((run) => run.task.id)).toEqual(["later", "new"]);
+ expect(buildCommentRunView(tasks, timeline).standaloneRuns).toEqual([]);
+ expect(tasks).toHaveLength(4); // Full execution history remains intact.
+ const reply = comment("answer", { actor_type: "agent", source_task_id: next.id });
+ expect(groupCommentRuns(tasks, [...timeline, reply]).get("root")?.find((run) => run.task.id === next.id))
+ .toMatchObject({ anchorCommentId: "root", commentId: "answer", hasReply: true });
+ });
+
+ it.each([
+ { cancelled_by_comment_change: undefined },
+ { cancelled_by_comment_change: false },
+ { dispatched_at: "2026-09-07T00:00:01Z" },
+ { started_at: "2026-09-07T00:00:01Z" },
+ { delivered_comment_ids: ["root"] },
+ { status: "failed" as const },
+ ])("retains manual cancellation and actual execution: %j", (overrides) => {
+ const run = task("old", { status: "cancelled", trigger_comment_id: "root", cancelled_by_comment_change: true, ...overrides });
+ expect(groupCommentRuns([run], [comment("root")]).get("root")?.[0]?.task.id).toBe(run.id);
+ });
+
+ it("keeps actual replies even when cancellation metadata says the input changed", () => {
+ const run = task("old", { status: "cancelled", cancelled_by_comment_change: true });
+ const reply = comment("answer", { actor_type: "agent", source_task_id: run.id });
+ expect(buildCommentRunView([run], [reply]).standaloneRuns).toHaveLength(1);
+ expect(buildCommentRunView([run], []).standaloneRuns).toEqual([]);
+ });
+ it("keeps merged runs at their earliest input, including nested replies", () => {
+ const timeline = [comment("root"), comment("reply", { parent_id: "root" }), comment("nested", { parent_id: "reply" })];
+ const run = task("run", { trigger_comment_id: "nested", coalesced_comment_ids: ["root", "reply"], delivered_comment_ids: ["root", "reply", "nested"] });
+ expect([...groupCommentRuns([run], timeline)]).toEqual([["root", [{ task: run, commentId: "root", anchorCommentId: "root", hasReply: false }]]]);
+ });
+
+ it.each([{ receipt: [] }, { receipt: ["old"] }])("uses planned comment coverage while queued, even with a delivery receipt of $receipt", ({ receipt }) => {
+ const run = task("queued", {
+ status: "queued", trigger_comment_id: "new", coalesced_comment_ids: ["old"],
+ delivered_comment_ids: receipt,
+ });
+ const timeline = [comment("old"), comment("new")];
+ expect(groupCommentRuns([run], timeline).get("new")).toEqual([
+ { task: run, commentId: "new", anchorCommentId: "new", hasReply: false },
+ ]);
+ });
+
+ it("keeps the trigger position while binding the latest persisted reply", () => {
+ const run = task("run", { status: "completed", trigger_comment_id: "root" });
+ const timeline = [comment("root"),
+ comment("progress", { parent_id: "root", actor_type: "agent", source_task_id: run.id }),
+ comment("final", { parent_id: "root", actor_type: "agent", source_task_id: run.id, created_at: "2026-09-07T00:01:00Z" }),
+ comment("unrelated", { actor_type: "agent", source_task_id: "other" })];
+ const map = groupCommentRuns([run], timeline);
+ expect(map.get("root")).toEqual([{ task: run, commentId: "final", anchorCommentId: "root", hasReply: true }]);
+ expect(map.size).toBe(1);
+ });
+
+ it.each(["cancelled", "failed"] as const)("preserves the planned anchor after a queued run is %s before dispatch", (status) => {
+ const run = task("stopped", {
+ status, trigger_comment_id: "new", coalesced_comment_ids: ["old"],
+ delivered_comment_ids: [], completed_at: "2026-09-07T00:01:00Z",
+ });
+ const retry = task("retry", { status: "queued", parent_task_id: run.id, delivered_comment_ids: [] });
+ expect(groupCommentRuns([run, retry], [comment("old"), comment("new")]).get("new")?.map((row) => row.task.id))
+ .toEqual(["retry", "stopped"]);
+ expect(groupCommentRuns([{ ...run, dispatched_at: "2026-09-07T00:00:30Z" }], [comment("new")]).size).toBe(0);
+ });
+
+ it("uses authoritative delivered comments when the newest trigger was not delivered", () => {
+ const run = task("run", { trigger_comment_id: "new", coalesced_comment_ids: ["old"], delivered_comment_ids: ["old"] });
+ expect(groupCommentRuns([run], [comment("old"), comment("new")]).get("old")?.[0]?.commentId).toBe("old");
+ expect(groupCommentRuns([{ ...run, delivered_comment_ids: [] }], [comment("old"), comment("new")]).size).toBe(0);
+ });
+
+ it("keeps retries on their original trigger and ignores missing or cyclic ancestry", () => {
+ const original = task("original", { trigger_comment_id: "root" });
+ const retry = task("retry", { parent_task_id: original.id });
+ expect(groupCommentRuns([retry, original], [comment("root")]).get("root")?.map((row) => row.task.id)).toEqual(["original", "retry"]);
+ expect(groupCommentRuns([task("a", { parent_task_id: "b" }), task("b", { parent_task_id: "a" })], []).size).toBe(0);
+ expect(groupCommentRuns([task("deleted", { trigger_comment_id: "missing" })], []).size).toBe(0);
+ });
+
+ it("associates assignment runs with their own replies and preserves unrelated thread references", () => {
+ const run = task("assigned");
+ const timeline = [comment("delivery", { actor_type: "agent", source_task_id: run.id })];
+ const before = groupCommentRuns([run], timeline);
+ const after = groupCommentRuns([run, task("other", { trigger_comment_id: "other" })], [...timeline, comment("other")], before);
+ expect(after.get("delivery")).toBe(before.get("delivery"));
+ });
+});
+
+describe("commentRunOutput", () => {
+ it("only exposes the completed daemon deliverable and tolerates response drift", () => {
+ expect(commentRunOutput(task("r", { status: "completed", result: { comment: "Done" } }))).toBe("Done");
+ for (const result of [null, "Done", {}, { comment: 1 }, { comment: " " }]) {
+ expect(commentRunOutput(task("r", { status: "completed", result }))).toBeNull();
+ }
+ expect(commentRunOutput(task("r", { result: { comment: "Still working" } }))).toBeNull();
+ });
+});
+
+describe("standaloneCommentRuns", () => {
+ it.each(["queued", "dispatched", "running", "failed", "cancelled", "completed"] as const)("keeps an unanchored %s run visible", (status) => {
+ const run = task("assignment", { status, delivered_comment_ids: [] });
+ expect(buildCommentRunView([run], []).standaloneRuns)
+ .toEqual([{ task: run, hasReply: false }]);
+ });
+
+ it("keeps assignment slots after replies arrive and excludes comment-triggered slots", () => {
+ const assigned = task("assignment");
+ const triggered = task("comment-run", { trigger_comment_id: "trigger" });
+ const tasks = [assigned, triggered];
+ const timeline = [comment("trigger")];
+ expect(buildCommentRunView(tasks, timeline).standaloneRuns.map((run) => run.task.id)).toEqual([assigned.id]);
+ const reply = comment("answer", { actor_type: "agent", source_task_id: assigned.id });
+ expect(buildCommentRunView(tasks, [...timeline, reply]).standaloneRuns)
+ .toEqual([{ task: assigned, commentId: reply.id, anchorCommentId: undefined, hasReply: true }]);
+ });
+});
diff --git a/packages/views/issues/components/comment-runs.ts b/packages/views/issues/components/comment-runs.ts
new file mode 100644
index 0000000000..e3863d6aed
--- /dev/null
+++ b/packages/views/issues/components/comment-runs.ts
@@ -0,0 +1,159 @@
+import type { AgentTask, TimelineEntry } from "@multica/core/types";
+
+export interface CommentRun {
+ task: AgentTask;
+ commentId?: string;
+ /** Stable trigger location; absent for issue-level runs such as assignment. */
+ anchorCommentId?: string;
+ /** The comment already contains this run's reply; only append its activity. */
+ hasReply: boolean;
+}
+
+export const EMPTY_COMMENT_RUNS: CommentRun[] = [];
+
+/** Use the daemon's deliverable, never guess a final answer from progress text. */
+export function commentRunOutput(task: AgentTask): string | null {
+ if (task.status !== "completed" || !task.result || typeof task.result !== "object") return null;
+ return "comment" in task.result && typeof task.result.comment === "string" && task.result.comment.trim()
+ ? task.result.comment : null;
+}
+
+export function isActiveCommentRun(task: AgentTask): boolean {
+ return ["queued", "dispatched", "waiting_local_directory", "running"].includes(task.status);
+}
+
+/** Published replies own their log entry even while the agent finishes its run. */
+export function showCommentRunInHeader(run: CommentRun): boolean {
+ return run.hasReply && (isActiveCommentRun(run.task) || run.task.status === "completed");
+}
+
+/** Invalidated queued input is history, not an agent response to the new text. */
+function isObsoleteCommentRun(task: AgentTask): boolean {
+ return task.status === "cancelled" && task.cancelled_by_comment_change === true
+ && !task.dispatched_at && !task.started_at && !task.delivered_comment_ids?.length;
+}
+
+/** Keep each run at its trigger; associate replies by task identity, never arrival order. */
+export function buildCommentRunView(
+ tasks: readonly AgentTask[],
+ timeline: readonly TimelineEntry[],
+ previous = new Map<string, CommentRun[]>(),
+): { timeline: readonly TimelineEntry[]; runs: Map<string, CommentRun[]>; standaloneRuns: CommentRun[] } {
+ const comments = new Map(timeline.filter((entry) => entry.type === "comment").map((entry) => [entry.id, entry]));
+ const threadRoot = (id: string): string | undefined => {
+ const seen = new Set<string>();
+ let entry = comments.get(id);
+ while (entry?.parent_id) {
+ if (seen.has(entry.id)) return undefined;
+ seen.add(entry.id);
+ entry = comments.get(entry.parent_id);
+ }
+ return entry?.id;
+ };
+ const replies = new Map<string, TimelineEntry>();
+ for (const entry of comments.values()) {
+ if (!entry.source_task_id || entry.actor_type !== "agent") continue;
+ const prior = replies.get(entry.source_task_id);
+ if (!prior || entry.created_at > prior.created_at || (entry.created_at === prior.created_at && entry.id > prior.id)) {
+ replies.set(entry.source_task_id, entry);
+ }
+ }
+ const byTask = new Map(tasks.map((task) => [task.id, task]));
+ const priorAnchors = new Map([...previous.values()].flatMap((runs) => runs.map((run) => [run.task.id, run.anchorCommentId] as const)));
+ const placements: CommentRun[] = [];
+ for (const task of [...tasks].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id))) {
+ const reply = replies.get(task.id);
+ if (isObsoleteCommentRun(task) && !reply) continue;
+ let anchorId: string | undefined;
+ let source: AgentTask | undefined = task;
+ const visited = new Set<string>();
+ while (!anchorId && source && !visited.has(source.id)) {
+ visited.add(source.id);
+ // Before claim, the receipt is empty (or belongs to a previous claim).
+ // Dispatch can precede receipt persistence; retain the planned anchor
+ // until delivery is known, or if the run terminates before dispatch.
+ const usesPlannedCoverage = source.status === "queued"
+ || (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
+ ? source.delivered_comment_ids
+ : [source.trigger_comment_id, ...(source.coalesced_comment_ids ?? [])];
+ const candidates = ids.flatMap((id) => id && comments.has(id) ? [comments.get(id)!] : []);
+ // Task events can arrive before their comments. Preserve the intended
+ // anchor even when it cannot be rendered yet; it is not an assignment.
+ anchorId = source.trigger_comment_id && ids.includes(source.trigger_comment_id)
+ ? source.trigger_comment_id
+ : candidates.sort((a, b) => b.created_at.localeCompare(a.created_at))[0]?.id
+ ?? ids.find((id) => !!id);
+ // Same-thread batches retain their first input's slot as newer replies
+ // coalesce. Wait for missing comments instead of guessing their thread;
+ // historical batches spanning several threads retain their trigger.
+ const root = candidates[0] && threadRoot(candidates[0].id);
+ if (root && candidates.length === ids.filter(Boolean).length
+ && candidates.every((entry) => threadRoot(entry.id) === root)) {
+ anchorId = candidates.sort((a, b) => a.created_at.localeCompare(b.created_at)
+ || timeline.indexOf(a) - timeline.indexOf(b))[0]?.id;
+ }
+ const priorAnchor = priorAnchors.get(source.id);
+ if (priorAnchor && ids.includes(priorAnchor) && candidates.length < ids.filter(Boolean).length) {
+ anchorId = priorAnchor;
+ }
+ source = source.parent_task_id ? byTask.get(source.parent_task_id) : undefined;
+ }
+ placements.push({ task, commentId: reply?.id ?? anchorId, anchorCommentId: anchorId, hasReply: !!reply });
+ }
+ // Project every task-owned answer first, then use that same tree for run
+ // grouping, replies, resolution, and navigation. Assignment answers become
+ // roots even if the agent originally posted them inside an existing thread.
+ const parents = new Map<string, string | undefined>();
+ for (const run of placements) {
+ if (run.hasReply && run.commentId && run.commentId !== run.anchorCommentId) {
+ parents.set(run.commentId, run.anchorCommentId);
+ }
+ }
+ const cyclic = new Set<string>();
+ for (const id of parents.keys()) {
+ const seen = new Set([id]);
+ let parent = parents.get(id);
+ while (parent) {
+ if (seen.has(parent)) { cyclic.add(id); break; }
+ seen.add(parent);
+ parent = parents.has(parent) ? parents.get(parent) : comments.get(parent)?.parent_id ?? undefined;
+ }
+ }
+ for (const id of cyclic) parents.delete(id);
+ const projected = timeline.map((entry) => {
+ const parent = parents.get(entry.id);
+ return parents.has(entry.id) && (entry.parent_id ?? undefined) !== parent
+ ? { ...entry, parent_id: parent } : entry;
+ });
+ const projectedComments = new Map(projected.filter((entry) => entry.type === "comment").map((entry) => [entry.id, entry]));
+ const grouped = new Map<string, CommentRun[]>();
+ for (const run of placements) {
+ let root = projectedComments.get(run.anchorCommentId ?? run.commentId ?? "");
+ if (!root) continue;
+ const ancestors = new Set([root.id]);
+ while (root.parent_id && projectedComments.has(root.parent_id) && !ancestors.has(root.parent_id)) {
+ root = projectedComments.get(root.parent_id)!;
+ ancestors.add(root.id);
+ }
+ const rows = grouped.get(root.id) ?? [];
+ rows.push(run);
+ grouped.set(root.id, rows);
+ }
+ // Preserve memoized comment cards when a different thread receives an event.
+ for (const [root, rows] of grouped) {
+ const prior = previous.get(root);
+ if (prior?.length === rows.length && rows.every((row, i) =>
+ row.task === prior[i]!.task && row.commentId === prior[i]!.commentId && row.anchorCommentId === prior[i]!.anchorCommentId && row.hasReply === prior[i]!.hasReply)) {
+ grouped.set(root, prior);
+ }
+ }
+ // Missing comment data must not turn a thread-owned run into a root block.
+ return {
+ timeline: projected,
+ runs: grouped,
+ standaloneRuns: placements.filter((run) => !run.anchorCommentId),
+ };
+}
diff --git a/packages/views/issues/components/execution-log-section.test.tsx b/packages/views/issues/components/execution-log-section.test.tsx
index 539f2c6e40..0bd00508e8 100644
--- a/packages/views/issues/components/execution-log-section.test.tsx
+++ b/packages/views/issues/components/execution-log-section.test.tsx
@@ -318,6 +318,16 @@ describe("execution log header geometry", () => {
);
}
+ it("shows the running task before pending tasks in queue order", () => {
+ renderSection([
+ makeTask({ id: "new", status: "queued", trigger_summary: "Order: second", created_at: "2026-09-08T03:02:00Z" }),
+ makeTask({ id: "old", status: "queued", trigger_summary: "Order: first", created_at: "2026-09-08T03:01:00Z" }),
+ makeTask({ id: "running", status: "running", trigger_summary: "Order: running", created_at: "2026-09-08T03:00:00Z" }),
+ ]);
+ expect(screen.getAllByText(/^Order:/).map((el) => el.textContent))
+ .toEqual(["Order: running", "Order: first", "Order: second"]);
+ });
+
function headerOf(): HTMLElement {
const label = screen.getByText("Execution log");
const header = label.closest("div");
diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsx
index 9a957937fa..a02657638a 100644
--- a/packages/views/issues/components/execution-log-section.tsx
+++ b/packages/views/issues/components/execution-log-section.tsx
@@ -5,7 +5,7 @@ import { useQuery } from "@tanstack/react-query";
import { ChevronRight, Loader2, RotateCcw, Square } from "lucide-react";
import { toast } from "sonner";
import { api, dispatchReasonCode } from "@multica/core/api";
-import { issueKeys } from "@multica/core/issues/queries";
+import { issueTasksOptions } from "@multica/core/issues/queries";
import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";
import type { AgentTask } from "@multica/core/types";
import { useTimeAgo } from "../../i18n";
@@ -19,6 +19,7 @@ import { formatDuration } from "../../agents/components/agent-activity-hover-con
import { TranscriptButton } from "../../common/task-transcript";
import { cancelReasonLabel, failureReasonLabel } from "../../agents/components/tabs/task-failure";
import { useT } from "../../i18n";
+import { compareActiveIssueTasks } from "./active-task-order";
import {
formatTokens,
formatUsd,
@@ -80,12 +81,7 @@ export function ExecutionLogSection({ issueId, identifier }: ExecutionLogSection
// a `["issues", "tasks"]` prefix-match — no local WS subscriptions
// needed, and the cache stays fresh even when this component isn't
// mounted (e.g. user cancels from agent-side, then navigates here).
- const { data: tasks = [] } = useQuery({
- queryKey: issueKeys.tasks(issueId),
- queryFn: () => api.listTasksByIssue(issueId),
- staleTime: 30_000,
- refetchOnWindowFocus: true,
- });
+ const { data: tasks = [] } = useQuery(issueTasksOptions(issueId));
const activeTasks = useMemo(
() =>
@@ -98,7 +94,7 @@ export function ExecutionLogSection({ issueId, identifier }: ExecutionLogSection
// what tells the user the agent is alive and will resume.
t.status === "waiting_local_directory" ||
t.status === "running",
- ),
+ ).toSorted(compareActiveIssueTasks),
[tasks],
);
diff --git a/packages/views/issues/components/inline-comment-run.test.tsx b/packages/views/issues/components/inline-comment-run.test.tsx
new file mode 100644
index 0000000000..557ce1ce43
--- /dev/null
+++ b/packages/views/issues/components/inline-comment-run.test.tsx
@@ -0,0 +1,213 @@
+import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import 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 type { TaskMessagePayload } from "@multica/core/types/events";
+import { renderWithI18n } from "../../test/i18n";
+import { InlineCommentRun } from "./inline-comment-run";
+
+vi.mock("@multica/core/api", () => ({ api: {
+ getIssue: vi.fn(), listTaskMessages: vi.fn(), cancelTask: vi.fn(), rerunIssue: vi.fn(),
+}, dispatchReasonCode: () => undefined }));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace" }));
+vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Reviewer" }) }));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => <span /> }));
+vi.mock("../../editor", () => ({ ReadonlyContent: ({ content }: { content: string }) => <div>{content}</div> }));
+vi.mock("../../common/task-transcript/agent-transcript-dialog", () => ({
+ AgentTranscriptDialog: ({ contentState, isLive }: { contentState?: ReactNode; isLive?: boolean }) => <div role="dialog" data-live={isLive}>{contentState ?? "Full transcript"}</div>,
+ StepBody: ({ item }: { item: { output?: string } }) => <div>{item.output}</div>,
+}));
+
+const id = "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc";
+function task(overrides: Partial<AgentTask> = {}): AgentTask {
+ return { id, agent_id: "agent", runtime_id: "runtime", issue_id: "issue", status: "running", priority: 0,
+ created_at: "2026-09-07T00:00:00Z", started_at: "2026-09-07T00:00:00Z", dispatched_at: null,
+ completed_at: null, result: null, error: null, ...overrides };
+}
+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(); });
+
+function setup(initialTask: AgentTask, hasReply = false, presentation: "inline" | "header" = "inline") {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
+ const view = (current: AgentTask, reply = hasReply) => <QueryClientProvider client={client}>
+ <InlineCommentRun run={{ task: current, commentId: "comment", hasReply: reply }} presentation={presentation} />
+ </QueryClientProvider>;
+ const rendered = renderWithI18n(view(initialTask));
+ return { client, rerender: (current: AgentTask, reply = hasReply) => rendered.rerender(view(current, reply)) };
+}
+
+describe("InlineCommentRun", () => {
+ it("opens completed reply logs from a compact header button and loads only on demand", async () => {
+ let resolve!: (value: TaskMessagePayload[]) => void;
+ vi.mocked(api.listTaskMessages).mockImplementation(() => new Promise((done) => { resolve = done; }));
+ setup(task({ status: "completed", completed_at: "2026-09-07T00:01:23Z" }), true, "header");
+ expect(screen.queryByText("Completed")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
+ expect(api.listTaskMessages).not.toHaveBeenCalled();
+ const trigger = screen.getByRole("button", { name: "Open full log" });
+ expect(trigger).toHaveAttribute("aria-haspopup", "dialog");
+ fireEvent.click(trigger);
+ expect(screen.getByRole("dialog")).toHaveTextContent("Loading activity");
+ await act(async () => resolve(messages));
+ await screen.findByText("Full transcript");
+ expect(api.listTaskMessages).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps published replies visually settled while their full log remains live", async () => {
+ vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
+ const current = task();
+ const { rerender } = setup(current, true, "header");
+ expect(screen.queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
+ const trigger = screen.getByRole("button", { name: "Open full log" });
+ const icon = trigger.querySelector("svg");
+ expect(icon).not.toHaveClass("animate-spin");
+ fireEvent.click(trigger);
+ await screen.findByText("Full transcript");
+ expect(screen.getByRole("dialog")).toHaveAttribute("data-live", "true");
+ rerender({ ...current, status: "completed", completed_at: "2026-09-07T00:01:23Z" });
+ expect(screen.getByRole("button", { name: "Open full log" })).toBe(trigger);
+ expect(screen.getByRole("dialog")).toHaveTextContent("Full transcript");
+ expect(screen.getByRole("dialog")).toHaveAttribute("data-live", "false");
+ expect(trigger.querySelector("svg")).toBe(icon);
+ expect(screen.queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
+ });
+
+ it("lets a completed header log recover when its initial fetch fails", async () => {
+ vi.mocked(api.listTaskMessages).mockRejectedValueOnce(new Error("offline"));
+ setup(task({ status: "completed" }), true, "header");
+ fireEvent.click(screen.getByRole("button", { name: "Open full log" }));
+ await screen.findByRole("alert");
+ vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ await screen.findByText("Full transcript");
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ });
+
+ it("uses a readable issue identifier in live progress and expanded activity", async () => {
+ const issueId = "01a07eca-8e82-775e-be06-e4a97ccfa299";
+ vi.mocked(api.getIssue).mockResolvedValue({ id: issueId, identifier: "DEV-17" } as Awaited<ReturnType<typeof api.getIssue>>);
+ vi.mocked(api.listTaskMessages).mockResolvedValue([
+ { task_id: id, issue_id: issueId, seq: 1, type: "tool_use", tool: "exec_command", input: { command: `multica issue get ${issueId} --output json` } },
+ ]);
+ setup(task({ issue_id: issueId }));
+ await screen.findByText("multica issue get DEV-17 --output json");
+ fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
+ expect(screen.getAllByText("multica issue get DEV-17 --output json")).toHaveLength(2);
+ expect(api.getIssue).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(["completed", "queued"] as const)("keeps the same focused disclosure button for a %s run", async (status) => {
+ vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
+ setup(task({ status }));
+ const before = screen.getByRole("button", { name: /View activity/ });
+ before.focus();
+ fireEvent.click(before, { detail: 0 });
+ const expanded = screen.getByRole("button", { name: /View activity/ });
+ expect(expanded).toBe(before);
+ expect(expanded).toHaveFocus();
+ expect(expanded).toHaveAttribute("aria-expanded", "true");
+ await screen.findByRole("button", { name: "Open full log" });
+ fireEvent.click(expanded, { detail: 0 });
+ expect(screen.getByRole("button", { name: /View activity/ })).toHaveFocus();
+ expect(screen.getByRole("button", { name: /View activity/ })).toHaveAttribute("aria-expanded", "false");
+ });
+ it("shows real activity, expands in place, follows WS data and retains the open transcript at completion", async () => {
+ vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
+ const current = task();
+ const { client, rerender } = setup(current);
+ await screen.findByText("pnpm test");
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ const toggle = screen.getByRole("button", { name: /View activity/ });
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ fireEvent.click(toggle);
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+ const tail: TaskMessagePayload = { task_id: id, issue_id: "issue", seq: 3, type: "tool_result", tool: "exec_command", output: "12 passed" };
+ act(() => client.setQueryData(chatKeys.taskMessages(id), [...messages, tail]));
+ expect(screen.queryByText("Waiting for the agent to respond.")).not.toBeInTheDocument();
+ vi.mocked(api.listTaskMessages).mockResolvedValue([...messages, tail]);
+ rerender({ ...current, status: "completed", completed_at: "2026-09-07T00:01:23Z" }, true);
+ await screen.findByText("Completed");
+ expect(screen.getByRole("button", { name: /View activity/ })).toHaveAttribute("aria-expanded", "true");
+ expect(screen.queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Open full log" }));
+ expect(screen.getByRole("dialog")).toHaveTextContent("Full transcript");
+ });
+
+ it("retains the last meaningful activity between tool results and the next agent message", async () => {
+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);
+ const { client } = setup(task());
+ await screen.findByText("Waiting for the agent to respond.");
+ await waitFor(() => expect(client.isFetching()).toBe(0));
+ const events: TaskMessagePayload[] = [];
+ async function receive(event: Omit<TaskMessagePayload, "task_id" | "issue_id" | "seq">) {
+ events.push({ task_id: id, issue_id: "issue", seq: events.length + 1, ...event });
+ await act(async () => {
+ client.setQueryData(chatKeys.taskMessages(id), [...events]);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ }
+ await receive({ type: "text", content: "Checking navigation." });
+ await screen.findByText("Checking navigation.");
+ await receive({ type: "tool_use", tool: "exec_command", input: { command: "pnpm test" } });
+ await screen.findByText("pnpm test");
+ await receive({ type: "tool_result", tool: "exec_command", output: "12 passed" });
+ expect(screen.getByText("pnpm test")).toBeInTheDocument();
+ expect(screen.queryByText("Waiting for the agent to respond.")).not.toBeInTheDocument();
+ await receive({ type: "text", content: " " });
+ expect(screen.getByText("pnpm test")).toBeInTheDocument();
+ await receive({ type: "text", content: "Tests passed. Reviewing the changes." });
+ await screen.findByText("Tests passed. Reviewing the changes.");
+ expect(screen.queryByText("pnpm test")).not.toBeInTheDocument();
+ });
+
+ it("keeps completed replies readable without fetching or duplicating their deliverable", () => {
+ setup(task({ status: "completed", result: { comment: "Already posted" } }), true);
+ expect(api.listTaskMessages).not.toHaveBeenCalled();
+ expect(screen.queryByText("Already posted")).not.toBeInTheDocument();
+ expect(screen.getByText("Completed")).toBeInTheDocument();
+ });
+
+ it("shows a completed deliverable if the corresponding comment is missing", () => {
+ setup(task({ status: "completed", result: { comment: "Review complete." } }));
+ expect(screen.getByText("Review complete.")).toBeInTheDocument();
+ expect(screen.getByText("Review complete.").closest('[data-slot="card"]')).toBeNull();
+ expect(screen.getByText("Completed").closest('[data-slot="card"]')).toBeNull();
+ expect(api.listTaskMessages).not.toHaveBeenCalled();
+ });
+
+ it.each(["queued", "running"] as const)("confirms stopping the specific %s run before its reply", async (state) => {
+ vi.mocked(api.cancelTask).mockResolvedValue(task({ status: "cancelled" }));
+ setup(task({ status: state }));
+ if (state === "queued") {
+ expect(screen.getByText("Waiting for an available agent.")).toBeInTheDocument();
+ expect(api.listTaskMessages).not.toHaveBeenCalled();
+ vi.mocked(api.listTaskMessages).mockResolvedValue([]);
+ fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
+ await screen.findByText("No activity recorded yet.");
+ expect(screen.queryByText("Waiting for the agent to respond.")).not.toBeInTheDocument();
+ }
+ fireEvent.click(screen.getByRole("button", { name: "Stop" }));
+ expect(api.cancelTask).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Stop run" }));
+ await waitFor(() => expect(api.cancelTask).toHaveBeenCalledWith("issue", id));
+ });
+
+ it("keeps a failed transcript fetch recoverable inside the comment", async () => {
+ vi.mocked(api.listTaskMessages).mockRejectedValueOnce(new Error("offline"));
+ setup(task({ status: "failed" }));
+ fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
+ await screen.findByRole("alert");
+ vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
+ });
+});
diff --git a/packages/views/issues/components/inline-comment-run.tsx b/packages/views/issues/components/inline-comment-run.tsx
new file mode 100644
index 0000000000..d22788df51
--- /dev/null
+++ b/packages/views/issues/components/inline-comment-run.tsx
@@ -0,0 +1,229 @@
+"use client";
+
+import { useEffect, useId, useMemo, useState } from "react";
+import { AlertCircle, Brain, ChevronRight, ExternalLink, Loader2, MessageSquare, RotateCcw, ScrollText, 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 { dispatchReasonCode } from "@multica/core/api";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { Button } from "@multica/ui/components/ui/button";
+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";
+import { buildTimeline } from "../../common/task-transcript/build-timeline";
+import { buildSteps, groupSteps, isCallStep, isGroupRow, type TraceRow } from "../../common/task-transcript/build-steps";
+import { traceEventSummary, traceToolArgSummary } from "../../common/task-transcript/trace-event-presenter";
+import { redactSecrets } from "../../common/task-transcript/redact";
+import { ReadonlyContent } from "../../editor";
+import { useT } from "../../i18n";
+import { formatDuration } from "../../agents/components/agent-activity-hover-content";
+import { cancelReasonLabel, failureReasonLabel } from "../../agents/components/tabs/task-failure";
+import { TerminateTaskConfirmDialog } from "./terminate-task-confirm-dialog";
+import { TaskStatusIcon } from "./task-status-icon";
+import { useStatusLabel } from "./task-run-labels";
+import { commentRunOutput, isActiveCommentRun, showCommentRunInHeader, type CommentRun } from "./comment-runs";
+
+import { useRunDisclosureMotion } from "./use-run-comment-motion";
+
+export function useInlineCommentRunState() {
+ const [expanded, setExpanded] = useState(false);
+ const [fullLogOpen, setFullLogOpen] = useState(false);
+ const disclosure = useRunDisclosureMotion(expanded);
+ return { expanded, setExpanded, fullLogOpen, setFullLogOpen, disclosure };
+}
+
+export type InlineCommentRunState = ReturnType<typeof useInlineCommentRunState>;
+
+export function InlineCommentRun({ run, className, viewState, showIdentity = false, presentation = "inline" }: {
+ run: CommentRun;
+ className?: string;
+ viewState?: InlineCommentRunState;
+ showIdentity?: boolean;
+ presentation?: "inline" | "header";
+}) {
+ const { task, hasReply } = run;
+ const { t } = useT("issues");
+ const { t: tAgents } = useT("agents");
+ const { getActorName } = useActorName();
+ const name = getActorName("agent", task.agent_id);
+ const status = useStatusLabel(task.status);
+ const active = isActiveCommentRun(task);
+ const localViewState = useInlineCommentRunState();
+ const state = viewState ?? localViewState;
+ const { expanded, setExpanded, fullLogOpen, setFullLogOpen } = state;
+ const [confirmStop, setConfirmStop] = useState(false);
+ const [now, setNow] = useState(Date.now);
+ const [visibleCount, setVisibleCount] = useState(12);
+ const cancel = useCancelIssueRun(task.issue_id);
+ const retry = useRetryIssueRun(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.
+ const loadTranscript = task.status === "running" || (presentation === "inline" && expanded) || fullLogOpen;
+ const { data, isPending, isError, refetch } = useTaskMessages(task.id, active, loadTranscript);
+ const items = useMemo(() => buildTimeline(data ?? []), [data]);
+ const formatText = useTraceIssueLabels(useWorkspaceId(), task.issue_id, items, loadTranscript);
+ const steps = useMemo(() => buildSteps(items), [items]);
+ const rows = useMemo(() => groupSteps(steps), [steps]);
+ useEffect(() => {
+ if (!active) return;
+ const timer = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(timer);
+ }, [active]);
+ const start = task.started_at ?? task.dispatched_at ?? task.created_at;
+ const end = active ? now : task.completed_at ? Date.parse(task.completed_at) : undefined;
+ const elapsed = end !== undefined && Number.isFinite(Date.parse(start)) && Number.isFinite(end)
+ ? formatDuration(start, end) : "";
+ const failure = task.status === "failed"
+ ? failureReasonLabel(task.failure_reason, tAgents)
+ : cancelReasonLabel(task, tAgents);
+ const output = !hasReply ? commentRunOutput(task) : null;
+ const latest = steps.findLast((step) => step.kind !== "text" || step.item.content?.trim());
+ const pendingCall = steps.findLast((step) => isCallStep(step) && !step.result);
+ const current = pendingCall ?? latest;
+ // Keep the last activity visible after a tool returns, until new progress arrives.
+ const activitySummary = current && isCallStep(current)
+ ? redactSecrets(traceToolArgSummary(current.call?.input, { formatText }) || current.tool)
+ : current?.kind === "text" ? redactSecrets(formatText(current.item.content ?? ""))
+ : current?.kind === "thinking" ? t(($) => $.inline_run.thinking)
+ : current?.kind === "error" ? t(($) => $.inline_run.error)
+ : t(($) => $.inline_run.waiting_response);
+ const summary = task.status === "queued" ? t(($) => $.inline_run.queued)
+ : task.status === "dispatched" ? t(($) => $.inline_run.starting)
+ : task.status === "waiting_local_directory" ? t(($) => $.inline_run.waiting_directory)
+ : activitySummary;
+ const showProgress = active && !hasReply;
+ const 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 transcript = fullLogOpen && <AgentTranscriptDialog open onOpenChange={setFullLogOpen}
+ task={task} items={items} agentName={name} isLive={active}
+ contentState={isPending ? <p role="status" className="text-body text-muted-foreground">{t(($) => $.inline_run.loading)}</p>
+ : isError ? <div role="alert" className="text-body text-destructive">{t(($) => $.inline_run.load_failed)}
+ <button className="ml-2 underline" type="button" onClick={() => void refetch()}>{t(($) => $.inline_run.try_again)}</button>
+ </div> : undefined} />;
+ const stopButton = active && <Button size="icon-sm" variant="ghost" className="text-muted-foreground"
+ aria-label={stopLabel} title={stopLabel} disabled={cancel.isPending || cancel.isSuccess}
+ onClick={() => setConfirmStop(true)}>
+ {cancel.isPending || cancel.isSuccess ? <Loader2 className="size-3.5 animate-spin motion-reduce:animate-none" /> : <Square className="size-3.5" />}
+ </Button>;
+ const stopDialog = <TerminateTaskConfirmDialog open={confirmStop} onOpenChange={setConfirmStop}
+ showRunningNote={task.status !== "queued"}
+ onConfirm={() => cancel.mutate(task.id, { onError: () => toast.error(t(($) => $.execution_log.cancel_failed)) })} />;
+ if (presentation === "header" && showCommentRunInHeader(run)) {
+ return <span className="inline-flex shrink-0" data-comment-actions data-run-id={task.id}>
+ <Tooltip>
+ <TooltipTrigger render={<Button type="button" size="icon-sm" variant="ghost"
+ className="text-muted-foreground aria-expanded:bg-transparent aria-expanded:hover:bg-muted dark:aria-expanded:hover:bg-muted/50"
+ aria-label={t(($) => $.inline_run.full_log)} aria-haspopup="dialog" aria-expanded={fullLogOpen}
+ onClick={() => setFullLogOpen(true)}>
+ <ScrollText aria-hidden className="size-3.5" />
+ </Button>} />
+ <TooltipContent>{t(($) => $.inline_run.full_log)}</TooltipContent>
+ </Tooltip>
+ {transcript}
+ </span>;
+ }
+ return (
+ <section aria-label={t(($) => $.inline_run.label, { name })}
+ className={cn("@container/run min-w-0 py-2", className)} data-run-id={task.id}>
+ <div className="flex min-h-7 min-w-0 items-center gap-2" data-run-summary-row>
+ {showIdentity && <>
+ <ActorAvatar actorType="agent" actorId={task.agent_id} size="md" enableHoverCard />
+ <span className="max-w-[30%] shrink-0 truncate text-body font-medium" title={name}>{name}</span>
+ </>}
+ <span className={cn("flex shrink-0 items-center gap-1.5 whitespace-nowrap text-caption text-muted-foreground", showProgress && "sr-only")}
+ role="status" data-run-status>
+ <TaskStatusIcon status={task.status} />{status}
+ </span>
+ <button type="button"
+ className={cn("flex min-w-0 items-center gap-1.5 rounded py-1 text-left text-caption text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ showProgress ? "flex-1 text-body" : "order-last ml-auto shrink-0",
+ showIdentity && !showProgress && "@max-[32rem]/run:min-w-7 @max-[32rem]/run:justify-center")}
+ aria-label={stepLabel ? `${activityLabel} · ${stepLabel}` : activityLabel}
+ aria-expanded={expanded} aria-controls={expanded ? regionId : undefined}
+ onClick={(event) => { state.disclosure.onTrigger(event); setExpanded(!expanded); }}>
+ {showProgress
+ ? <span data-run-summary className="min-w-0 flex-1 truncate" title={summary}>
+ <span className={cn("inline-block max-w-full truncate align-bottom",
+ (task.status === "running" || task.status === "dispatched") && "animate-chat-text-shimmer")}>{summary}</span>
+ </span>
+ : <span className={cn(showIdentity && "@max-[32rem]/run:sr-only")}>{activityLabel}</span>}
+ {!showProgress && stepLabel && <span className="text-faint-foreground @max-[32rem]/run:hidden">· {stepLabel}</span>}
+ <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>
+ {stopButton}
+ {!hasReply && (task.status === "failed" || task.status === "cancelled") && <Button
+ size="sm" variant="ghost" className={cn("text-muted-foreground", showIdentity && "@max-[32rem]/run:size-7 @max-[32rem]/run:p-0")} disabled={retry.isPending || retry.isSuccess}
+ onClick={() => retry.mutate(task.id, { onError: (error) => toast.error(
+ dispatchReasonCode(error) === "invocation_not_allowed" ? t(($) => $.execution_log.retry_blocked) : t(($) => $.execution_log.retry_failed),
+ ) })}>
+ <RotateCcw className="size-3.5" /><span className={cn(showIdentity && "@max-[32rem]/run:sr-only")}>{t(($) => $.execution_log.retry_task_tooltip)}</span>
+ </Button>}
+ </div>
+ <div className={cn(showIdentity && "pl-8")}>
+ {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 ref={state.disclosure.contentRef} id={regionId} className="mt-2 min-w-0 space-y-1">
+ {isPending && <p className="text-caption text-muted-foreground">{t(($) => $.inline_run.loading)}</p>}
+ {isError && <div role="alert" className="text-caption text-destructive">{t(($) => $.inline_run.load_failed)}
+ <button className="ml-2 underline" type="button" onClick={() => void refetch()}>{t(($) => $.inline_run.try_again)}</button></div>}
+ {!isPending && !isError && rows.length === 0 && <p className="text-caption text-muted-foreground">{t(($) => $.inline_run.empty)}</p>}
+ {rows.length > visibleCount && <button type="button" className="py-1 text-caption text-muted-foreground hover:text-foreground"
+ onClick={() => setVisibleCount((count) => count + 12)}>{t(($) => $.inline_run.show_earlier, { count: rows.length - visibleCount })}</button>}
+ {rows.slice(-visibleCount).map((row) => <InlineStep key={row.seq} row={row} live={active} formatText={formatText} />)}
+ <button type="button" className="flex items-center gap-1.5 rounded py-2 text-caption text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => setFullLogOpen(true)}>{t(($) => $.inline_run.full_log)}<ExternalLink className="size-3" /></button>
+ </div>}
+ </div>
+ {transcript}
+ {stopDialog}
+ </section>
+ );
+}
+
+function InlineStep({ row, live, formatText }: { row: TraceRow; live: boolean; formatText: (text: string) => string }) {
+ const { t } = useT("issues");
+ const [open, setOpen] = useState(false);
+ const disclosure = useRunDisclosureMotion(open);
+ const [limit, setLimit] = useState(12);
+ const onToggle = (event: React.SyntheticEvent<HTMLDetailsElement>) => setOpen(event.currentTarget.open);
+ const grouped = isGroupRow(row);
+ const call = isCallStep(row);
+ const pending = call && live && !row.result;
+ const error = !grouped && !call && row.kind === "error";
+ const Icon = grouped || call ? Terminal : row.kind === "text" ? MessageSquare : row.kind === "thinking" ? Brain : AlertCircle;
+ const summary = call
+ ? redactSecrets(traceToolArgSummary(row.call?.input, { formatText }) || (row.result ? traceEventSummary(row.result, { formatText }) : "")) || row.tool
+ : grouped ? row.tool
+ : row.kind === "text" ? t(($) => $.inline_run.message)
+ : row.kind === "thinking" ? t(($) => $.inline_run.thinking)
+ : t(($) => $.inline_run.error);
+ return <details className="min-w-0 text-caption" onToggle={onToggle}>
+ <summary onClick={disclosure.onTrigger} className="flex cursor-pointer list-none items-center gap-2 rounded py-1.5 hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden">
+ {pending ? <Loader2 aria-hidden className="size-3.5 shrink-0 animate-spin text-info motion-reduce:animate-none" />
+ : <Icon aria-hidden className={cn("size-3.5 shrink-0", error ? "text-destructive" : "text-muted-foreground")} />}
+ <span className={cn("min-w-0 flex-1 truncate", error && "text-destructive")} title={summary}>{summary}</span>
+ {(grouped || call) && <span className="shrink-0 text-micro text-muted-foreground">
+ {grouped ? t(($) => $.inline_run.steps, { count: row.steps.length }) : row.tool}
+ </span>}
+ <ChevronRight ref={disclosure.chevronRef} aria-hidden className={cn("size-3 shrink-0 text-muted-foreground", open && "rotate-90")} />
+ </summary>
+ {open && <div ref={disclosure.contentRef} className="min-w-0 space-y-2 overflow-hidden pl-5.5">
+ {grouped ? <>
+ {row.steps.length > limit && <button type="button" className="py-1 text-muted-foreground" onClick={() => setLimit((value) => value + 12)}>
+ {t(($) => $.inline_run.show_earlier, { count: row.steps.length - limit })}</button>}
+ {row.steps.slice(-limit).map((step) => <InlineStep key={step.seq} row={step} live={live} formatText={formatText} />)}
+ </> : call ? <>
+ {row.call && <StepBody item={row.call} />}
+ {row.result && <StepBody item={row.result} />}
+ {pending && <p className="text-muted-foreground">{t(($) => $.inline_run.waiting_result)}</p>}
+ </> : <StepBody item={row.item} />}
+ </div>}
+ </details>;
+}
diff --git a/packages/views/issues/components/issue-agent-header-chip.test.tsx b/packages/views/issues/components/issue-agent-header-chip.test.tsx
index 3bc9a63b10..97cb57f7ca 100644
--- a/packages/views/issues/components/issue-agent-header-chip.test.tsx
+++ b/packages/views/issues/components/issue-agent-header-chip.test.tsx
@@ -189,6 +189,18 @@ beforeEach(() => {
});
describe("IssueAgentHeaderChip", () => {
+ it("lists pending threads oldest first after the running task, even after coalescing", () => {
+ // ListTasksByIssue returns newest first, as in DEV-24.
+ mockState.tasks = [
+ makeTask({ id: "dlc", status: "queued", created_at: "2026-09-08T11:44:52+08:00" }),
+ makeTask({ id: "beginner", status: "queued", created_at: "2026-09-08T11:44:34+08:00", trigger_comment_id: "new-supplement", coalesced_comment_ids: ["original"] }),
+ makeTask({ id: "running", created_at: "2026-09-08T11:44:26+08:00" }),
+ ];
+ renderWithI18n(<IssueAgentHeaderChip issueId="issue-1" />);
+ expect(screen.getAllByTestId("active-task-row").map((row) => row.querySelector("span")?.textContent))
+ .toEqual(["running", "beginner", "dlc"]);
+ });
+
it("shows the active agent name without event count or elapsed time", () => {
mockState.tasks = [makeTask({})];
diff --git a/packages/views/issues/components/issue-agent-header-chip.tsx b/packages/views/issues/components/issue-agent-header-chip.tsx
index d48a92052c..115d210713 100644
--- a/packages/views/issues/components/issue-agent-header-chip.tsx
+++ b/packages/views/issues/components/issue-agent-header-chip.tsx
@@ -16,6 +16,7 @@ import { TranscriptButton } from "../../common/task-transcript";
import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";
import { ActiveTaskRow } from "./execution-log-section";
import { useT } from "../../i18n";
+import { compareActiveIssueTasks } from "./active-task-order";
// Per-issue "is an agent working on this right now?" chip for the issue
// detail header. Lives in the header (not the scrollable body) so the live
@@ -59,9 +60,9 @@ export const IssueAgentHeaderChip = memo(function IssueAgentHeaderChip({
const { running, queued } = useMemo(() => {
const running: AgentTask[] = [];
const queued: AgentTask[] = [];
- // The list is already issue-scoped by the endpoint, so only the status
- // split matters here.
- for (const task of tasks) {
+ // The endpoint returns history newest first. Active work instead uses
+ // execution/queue order, shared with the right-panel log.
+ for (const task of tasks.toSorted(compareActiveIssueTasks)) {
if (task.status === "running") running.push(task);
else if (
task.status === "queued" ||
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 588693694d..443cfa3921 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -2,7 +2,8 @@ import { forwardRef, useEffect, useRef, useState, useImperativeHandle } from "re
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { Issue, IssueStatusEntry, Label, TimelineEntry } from "@multica/core/types";
+import type { AgentTask, Issue, IssueStatusEntry, Label, TimelineEntry } from "@multica/core/types";
+import { issueKeys } from "@multica/core/issues/queries";
import { issueStatusKeys } from "@multica/core/issue-statuses";
import { I18nProvider } from "@multica/core/i18n/react";
import { toast } from "sonner";
@@ -319,6 +320,8 @@ const mockApiObj = vi.hoisted(() => ({
removeCommentReaction: vi.fn(),
listMembers: vi.fn().mockResolvedValue([{ user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" }]),
listAgents: vi.fn().mockResolvedValue([]),
+ getAgent: vi.fn().mockResolvedValue(null),
+ listRuntimes: vi.fn().mockResolvedValue([]),
getProject: vi.fn(),
listProjects: vi.fn().mockResolvedValue({ projects: [] }),
}));
@@ -704,6 +707,7 @@ describe("IssueDetail (shared)", () => {
mockApiObj.listIssues.mockResolvedValue({ issues: [], total: 0 });
mockApiObj.getActiveTasksForIssue.mockResolvedValue({ tasks: [] });
mockApiObj.listTasksByIssue.mockResolvedValue([]);
+ mockApiObj.listTaskMessages.mockResolvedValue([]);
mockApiObj.rerunIssue.mockResolvedValue({ id: "task-rerun" });
mockApiObj.listMembers.mockResolvedValue([
{ user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" },
@@ -1199,6 +1203,222 @@ describe("IssueDetail (shared)", () => {
expect(screen.queryByRole("button", { name: /^Metadata\b/ })).not.toBeInTheDocument();
});
+ // Mapping edge cases live in comment-runs.test.ts; this verifies the shipped
+ // IssueDetail -> CommentCard -> metadata card wiring as server caches change.
+ it("keeps execution in an agent block before and after its persisted reply arrives", async () => {
+ const taskId = "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc";
+ const task: AgentTask = {
+ id: taskId, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
+ status: "queued", priority: 0, created_at: "2026-01-16T00:00:00Z",
+ started_at: null, dispatched_at: null, completed_at: null, result: null, error: null,
+ trigger_comment_id: "comment-1", delivered_comment_ids: [],
+ };
+ const root = mockTimeline[0]!;
+ mockApiObj.listTimeline.mockResolvedValue([]);
+ mockApiObj.listTasksByIssue.mockResolvedValue([task]);
+ mockApiObj.listTaskMessages.mockResolvedValue([
+ { task_id: taskId, issue_id: "issue-1", seq: 1, type: "tool_use", tool: "exec_command", input: { command: "pnpm test" } },
+ ]);
+ const client = createTestQueryClient();
+ const { container } = render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={client}>
+ <IssueDetail issueId="issue-1" defaultSidebarOpen={false} />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+ await waitFor(() => expect(client.getQueryData(issueKeys.tasks("issue-1"))).toEqual([task]));
+ await waitFor(() => expect(client.getQueryData(issueKeys.timeline("issue-1"))).toEqual([]));
+ expect(container.querySelector(`[data-run-id="${taskId}"]`)).toBeNull();
+ mockApiObj.listTimeline.mockResolvedValue([root]);
+ act(() => client.setQueryData(issueKeys.timeline("issue-1"), [root]));
+ await screen.findByText("Waiting for an available agent.");
+ const userBlock = container.querySelector(`#comment-body-${root.id}`)!.parentElement!;
+ const agentBlock = container.querySelector(`[data-run-comment-id="${taskId}"]`)!;
+ expect(agentBlock).not.toBeNull();
+ expect(userBlock.contains(agentBlock)).toBe(false);
+ expect(agentBlock.parentElement).toBe(userBlock.parentElement);
+ expect(agentBlock.querySelector(`[data-run-id="${taskId}"]`)).not.toBeNull();
+ const running: AgentTask = { ...task, status: "running", started_at: task.created_at, delivered_comment_ids: [root.id] };
+ act(() => client.setQueryData(issueKeys.tasks("issue-1"), [running]));
+ await screen.findByText("pnpm test");
+ expect(container.querySelector(`[data-run-comment-id="${taskId}"]`)).toBe(agentBlock);
+ expect(userBlock.querySelector("[data-run-id]")).toBeNull();
+
+ fireEvent.click(within(agentBlock as HTMLElement).getByRole("button", { name: /View activity/ }));
+ await within(agentBlock as HTMLElement).findByRole("button", { name: "Open full log" });
+
+ const reply: TimelineEntry = {
+ ...mockTimeline[1]!, id: "run-reply", parent_id: root.id, source_task_id: taskId,
+ content: "Review complete. The navigation is ready.",
+ };
+ const completed: AgentTask = { ...running, status: "completed", completed_at: "2026-01-16T00:01:00Z" };
+ mockApiObj.listTasksByIssue.mockResolvedValue([running]);
+ mockApiObj.listTimeline.mockResolvedValue([root, reply]);
+ act(() => {
+ client.setQueryData(issueKeys.timeline("issue-1"), [root, reply]);
+ });
+ const body = await screen.findByText(reply.content!);
+ const replyRow = container.querySelector("#comment-run-reply")!;
+ await waitFor(() => expect(within(replyRow as HTMLElement).getByRole("button", { name: "Open full log" })).toBeInTheDocument());
+ expect(within(replyRow as HTMLElement).queryByText("Completed")).not.toBeInTheDocument();
+ const run = replyRow.querySelector(`[data-run-id="${taskId}"]`)!;
+ expect(run.querySelector('[data-slot="card"]')).toBeNull();
+ expect(container.querySelectorAll(`[data-run-id="${taskId}"]`)).toHaveLength(1);
+ expect(run.contains(body)).toBe(false);
+ expect(replyRow.contains(body)).toBe(true);
+ expect(container.querySelector(`[data-run-comment-id="${taskId}"]`)).toBeNull();
+ expect(userBlock.querySelector("[data-run-id]")).toBeNull();
+ expect(within(replyRow as HTMLElement).queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
+ expect(within(run as HTMLElement).queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
+ const logButton = within(run as HTMLElement).getByRole("button", { name: "Open full log" });
+ expect(logButton.closest("[data-comment-block]")?.querySelector("[data-run-summary-row]")).toBeNull();
+ mockApiObj.listTasksByIssue.mockResolvedValue([completed]);
+ act(() => client.setQueryData(issueKeys.tasks("issue-1"), [completed]));
+ await waitFor(() => expect(within(run as HTMLElement).queryByRole("button", { name: "Stop" })).not.toBeInTheDocument());
+ expect(within(run as HTMLElement).getByRole("button", { name: "Open full log" })).toBe(logButton);
+ fireEvent.click(within(run as HTMLElement).getByRole("button", { name: "Open full log" }));
+ await screen.findByRole("dialog");
+ expect(mockApiObj.listTaskMessages).toHaveBeenCalledWith(taskId);
+ });
+
+ it.each([null, "comment-1"])("shows an assignment reply once in its run slot when posted under %s", async (parentId) => {
+ const task: AgentTask = {
+ id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
+ status: "queued", priority: 0, created_at: "2026-01-16T00:00:00Z",
+ started_at: null, dispatched_at: null, completed_at: null, result: null, error: null,
+ delivered_comment_ids: [],
+ };
+ const existing = { ...mockTimeline[0]!, id: "comment-1" };
+ mockApiObj.listTimeline.mockResolvedValue([existing]);
+ mockApiObj.listTasksByIssue.mockResolvedValue([task]);
+ mockApiObj.listTaskMessages.mockResolvedValue([
+ { task_id: task.id, issue_id: "issue-1", seq: 1, type: "tool_use", tool: "exec_command", input: { command: "pnpm test" } },
+ ]);
+ const queryClient = createTestQueryClient();
+ const { container } = render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={queryClient}>
+ <IssueDetail issueId="issue-1" defaultSidebarOpen={false} />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+ await screen.findByText("Waiting for an available agent.");
+ expect(container.querySelector(`[data-run-comment-id="${task.id}"]`)).not.toBeNull();
+ const assignmentSlot = container.querySelector(`[data-run-slot-id="${task.id}"]`);
+ const running: AgentTask = { ...task, status: "running", started_at: task.created_at };
+ act(() => queryClient.setQueryData(issueKeys.tasks("issue-1"), [running]));
+ await screen.findByText("pnpm test");
+ expect(container.querySelectorAll(`[data-run-id="${task.id}"]`)).toHaveLength(1);
+ const reply: TimelineEntry = {
+ ...mockTimeline[1]!, id: "assignment-reply", parent_id: parentId, source_task_id: task.id,
+ content: "Assignment complete.", created_at: "2026-01-16T00:01:00Z",
+ };
+ const completed: AgentTask = { ...running, status: "completed", completed_at: reply.created_at };
+ mockApiObj.listTasksByIssue.mockResolvedValue([running]);
+ mockApiObj.listTimeline.mockResolvedValue([existing, reply]);
+ act(() => {
+ queryClient.setQueryData(issueKeys.timeline("issue-1"), [existing, reply]);
+ });
+ await waitFor(() => expect(screen.getAllByText(reply.content!)).toHaveLength(1));
+ await waitFor(() => expect(container.querySelector(`[data-run-comment-id="${task.id}"]`)).toBeNull());
+ expect(container.querySelector(`[data-run-slot-id="${task.id}"]`)).toBe(assignmentSlot);
+ const replyBlock = container.querySelector("#comment-assignment-reply")!;
+ expect(replyBlock.querySelector(`[data-run-id="${task.id}"]`)).not.toBeNull();
+ expect(container.querySelectorAll(`[data-run-id="${task.id}"]`)).toHaveLength(1);
+ const headerLog = within(replyBlock as HTMLElement).getByRole("button", { name: "Open full log" });
+ expect(replyBlock.querySelector("[data-run-summary-row]")).toBeNull();
+ expect(within(replyBlock as HTMLElement).queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
+ mockApiObj.listTasksByIssue.mockResolvedValue([completed]);
+ act(() => queryClient.setQueryData(issueKeys.tasks("issue-1"), [completed]));
+ await waitFor(() => expect(within(replyBlock as HTMLElement).queryByRole("button", { name: "Stop" })).not.toBeInTheDocument());
+ expect(within(replyBlock as HTMLElement).getByRole("button", { name: "Open full log" })).toBe(headerLog);
+ });
+
+ it("replaces each queued run in place without moving replies behind later requests", async () => {
+ const root = mockTimeline[0]!;
+ const second = { ...root, id: "request-two", parent_id: root.id, content: "Second request", created_at: "2026-01-16T00:00:02Z" };
+ const third = { ...root, id: "request-three", parent_id: root.id, content: "Third request", created_at: "2026-01-16T00:00:04Z" };
+ const tasks: AgentTask[] = [root, second, third].map((trigger, index) => ({
+ id: `ba2e8d1c-7f9b-4e2a-9c1d-123456789ab${index}`, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
+ status: "queued", priority: 0, created_at: trigger.created_at,
+ started_at: null, dispatched_at: null, completed_at: null, result: null, error: null,
+ trigger_comment_id: trigger.id, delivered_comment_ids: [],
+ }));
+ let timeline = [root, second, third];
+ mockApiObj.listTimeline.mockResolvedValue(timeline);
+ mockApiObj.listTasksByIssue.mockResolvedValue(tasks);
+ const client = createTestQueryClient();
+ const { container } = render(<I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={client}><IssueDetail issueId="issue-1" defaultSidebarOpen={false} /></QueryClientProvider>
+ </I18nProvider>);
+ await waitFor(() => expect(container.querySelectorAll('[data-run-slot-id]')).toHaveLength(3));
+ const slots = tasks.map((task) => container.querySelector(`[data-run-slot-id="${task.id}"]`)!);
+ fireEvent.click(within(slots[0] as HTMLElement).getByRole("button", { name: /View activity/ }));
+ await within(slots[0] as HTMLElement).findByText("No activity recorded yet.");
+ for (const index of [0, 1]) {
+ const reply: TimelineEntry = { ...mockTimeline[1]!, id: `answer-${index}`, parent_id: index === 0 ? null : root.id,
+ source_task_id: tasks[index]!.id, content: `Answer ${index}`, created_at: `2026-01-16T00:01:0${index}Z` };
+ tasks[index] = { ...tasks[index]!, status: "completed", completed_at: reply.created_at,
+ delivered_comment_ids: [tasks[index]!.trigger_comment_id!] };
+ timeline = [...timeline, reply];
+ mockApiObj.listTasksByIssue.mockResolvedValue([...tasks]);
+ mockApiObj.listTimeline.mockResolvedValue(timeline);
+ act(() => {
+ client.setQueryData(issueKeys.tasks("issue-1"), [...tasks]);
+ client.setQueryData(issueKeys.timeline("issue-1"), timeline);
+ });
+ await screen.findByText(reply.content!);
+ expect(container.querySelector(`[data-run-slot-id="${tasks[index]!.id}"]`)).toBe(slots[index]);
+ expect(slots[index]!.textContent).toContain(reply.content);
+ expect(container.querySelectorAll(`[data-run-id="${tasks[index]!.id}"]`)).toHaveLength(1);
+ }
+ expect(within(slots[0] as HTMLElement).getByRole("button", { name: "Open full log" })).toBeInTheDocument();
+ expect(within(slots[0] as HTMLElement).queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
+ expect(slots[0]!.nextElementSibling?.id).toBe("comment-request-two");
+ expect(slots[1]!.nextElementSibling?.id).toBe("comment-request-three");
+ expect(container.querySelector(`[data-run-slot-id="${tasks[2]!.id}"]`)).toBe(slots[2]);
+ expect(within(slots[2] as HTMLElement).getByText("Waiting for an available agent.")).toBeInTheDocument();
+ });
+
+ it("keeps a downstream run in the thread after its triggering agent reply is projected there", async () => {
+ const root = mockTimeline[0]!;
+ const first: AgentTask = { id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789ab0", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
+ status: "completed", priority: 0, created_at: root.created_at, started_at: root.created_at, dispatched_at: null,
+ completed_at: "2026-01-16T00:01:00Z", result: null, error: null, trigger_comment_id: root.id };
+ const answer = { ...mockTimeline[1]!, id: "answer-a", parent_id: null, source_task_id: first.id, content: "Agent A response" };
+ const second: AgentTask = { ...first, id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789ab1", agent_id: "agent-2", status: "queued",
+ started_at: null, completed_at: null, trigger_comment_id: answer.id };
+ mockApiObj.listTimeline.mockResolvedValue([root, answer]);
+ mockApiObj.listTasksByIssue.mockResolvedValue([first, second]);
+ const { container } = renderIssueDetail();
+ await screen.findByText(answer.content);
+ await waitFor(() => expect(container.querySelectorAll(`[data-run-id="${second.id}"]`)).toHaveLength(1));
+ expect(container.querySelector(`#comment-${root.id}`)?.querySelector(`[data-run-id="${second.id}"]`)).not.toBeNull();
+ });
+
+ it.each(["failed", "cancelled"] as const)("keeps a %s run outside the user reply that triggered it", async (status) => {
+ const root = mockTimeline[0]!;
+ const trigger = { ...root, id: "user-reply", parent_id: root.id, content: "Please try this task" };
+ const task: AgentTask = {
+ id: "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
+ status, priority: 0, created_at: "2026-01-16T00:00:00Z",
+ started_at: null, dispatched_at: null, completed_at: "2026-01-16T00:01:00Z", result: null, error: null,
+ trigger_comment_id: trigger.id, delivered_comment_ids: [],
+ };
+ mockApiObj.listTimeline.mockResolvedValue([root, trigger]);
+ mockApiObj.listTasksByIssue.mockResolvedValue([task]);
+ const { container } = renderIssueDetail();
+ await screen.findByText(trigger.content);
+ await waitFor(() => expect(container.querySelector(`[data-run-comment-id="${task.id}"]`)).not.toBeNull());
+ const userReply = container.querySelector("#comment-user-reply")!;
+ const agentBlock = container.querySelector(`[data-run-comment-id="${task.id}"]`)!;
+ expect(userReply.contains(agentBlock)).toBe(false);
+ expect(userReply.nextElementSibling).toBe(agentBlock);
+ expect(within(agentBlock as HTMLElement).getByRole("button", { name: "Retry run" })).toBeInTheDocument();
+ expect(container.querySelectorAll(`[data-run-id="${task.id}"]`)).toHaveLength(1);
+ });
+
// Details is creator + immutable timestamps, so it ranks below the
// execution log, which is what people actually open the sidebar for.
it("orders the Details section after the execution log", async () => {
@@ -1690,6 +1910,20 @@ describe("IssueDetail (shared)", () => {
});
describe("highlightCommentId scroll-to-comment", () => {
+ it.each(["root", "reply"])("unfolds an assignment run with a resolved %s when a notification targets a hidden reply", async (resolved) => {
+ const run: AgentTask = { id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
+ status: "completed", priority: 0, created_at: "2026-01-16T00:00:00Z", started_at: null, dispatched_at: null,
+ completed_at: "2026-01-16T00:01:00Z", result: null, error: null, delivered_comment_ids: [] };
+ const root = { ...mockTimeline[1]!, id: "assigned-answer", parent_id: null, source_task_id: run.id,
+ content: "Assignment answer", resolved_at: resolved === "root" ? "2026-01-17T00:00:00Z" : null };
+ const target = { ...mockTimeline[0]!, id: "hidden-target", parent_id: root.id, content: "Hidden notification target" };
+ const resolution = { ...target, id: "resolution", content: "Resolved reply", resolved_at: "2026-01-17T00:00:00Z" };
+ mockApiObj.listTimeline.mockResolvedValue([root, target, ...(resolved === "reply" ? [resolution] : [])]);
+ mockApiObj.listTasksByIssue.mockResolvedValue([run]);
+ renderIssueDetailWithHighlight(target.id);
+ await waitFor(() => expect(document.getElementById(`comment-${target.id}`)).not.toBeNull());
+ await waitFor(() => expect(document.getElementById(`comment-${target.id}`)).toHaveClass(highlightedCommentBackgroundClass));
+ });
it("scrolls to the highlighted comment after both issue and timeline finish loading", async () => {
renderIssueDetailWithHighlight("comment-2");
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 6d96ebe2f2..bee2fed722 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -78,7 +78,10 @@ import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
import { SubIssuesAgentWorkingChip } from "./sub-issues-agent-working-chip";
import { ProjectPicker } from "../../projects/components/project-picker";
import { LocalDirectoryHint } from "../../projects/components/local-directory-hint";
-import { CommentCard } from "./comment-card";
+import { useNewRunIds } from "./use-run-comment-motion";
+import { AgentRunComment, CommentCard } from "./comment-card";
+import { EMPTY_COMMENT_RUNS, buildCommentRunView, type CommentRun } from "./comment-runs";
+import { issueTasksOptions } from "@multica/core/issues/queries";
import { SourceContextBadge } from "./source-context-viewer";
import { RevisionConflictCompare } from "./revision-conflict-compare";
import { CommentInput } from "./comment-input";
@@ -454,6 +457,7 @@ function shallowEqualEntries(a: TimelineEntry[], b: TimelineEntry[]): boolean {
// into one activity-group row) but project it into a discriminated union
// the itemContent dispatcher can switch on.
type TimelineItem =
+ | { kind: "run"; id: string; run: CommentRun; entry?: TimelineEntry }
| { kind: "comment"; id: string; entry: TimelineEntry }
| { kind: "resolved-bar"; id: string; entry: TimelineEntry }
| { kind: "activity-group"; id: string; entries: TimelineEntry[] };
@@ -461,7 +465,7 @@ type TimelineItem =
type RawTimelineGroup = {
type: "comment" | "activities";
entries: TimelineEntry[];
-};
+} | { type: "run"; run: CommentRun; entry?: TimelineEntry };
function flattenGroups(
groups: ReadonlyArray<RawTimelineGroup>,
@@ -469,7 +473,9 @@ function flattenGroups(
): TimelineItem[] {
const out: TimelineItem[] = [];
for (const group of groups) {
- if (group.type === "comment") {
+ if (group.type === "run") {
+ out.push({ kind: "run", id: group.entry?.id ?? group.run.task.id, run: group.run, entry: group.entry });
+ } else if (group.type === "comment") {
const entry = group.entries[0]!;
const isResolved = !!entry.resolved_at;
const isExpanded = expandedResolved.has(entry.id);
@@ -1424,6 +1430,15 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
editComment, deleteComment, toggleResolveComment, toggleReaction: handleToggleReaction,
} = useIssueTimeline(id, user?.id);
+ const { data: commentTasks } = useQuery(issueTasksOptions(id));
+ const enteringRunIds = useNewRunIds(id, commentTasks);
+ const previousCommentRuns = useRef(new Map<string, CommentRun[]>());
+ const { runs: commentRuns, timeline: displayTimeline, standaloneRuns } = useMemo(() => {
+ const next = buildCommentRunView(commentTasks ?? [], timeline, previousCommentRuns.current);
+ previousCommentRuns.current = next.runs;
+ return next;
+ }, [commentTasks, timeline]);
+
// Resolve / unresolve must always clear the per-session expand entry so
// re-resolving an already-expanded thread folds it back to the bar (the
// expand Set is keyed only on commentId, not on resolution state). Without
@@ -1434,13 +1449,13 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// Fold the thread back on any resolve change: clear the thread ROOT's
// expand entry (expand state is keyed on root id, but a resolve target
// can be a reply). Walk parent_id up to the root.
- const byId = new Map(timeline.map((e) => [e.id, e]));
+ const byId = new Map(displayTimeline.map((e) => [e.id, e]));
let cur = byId.get(commentId);
while (cur?.parent_id && byId.get(cur.parent_id)) cur = byId.get(cur.parent_id)!;
clearResolvedExpand(cur?.id ?? commentId);
toggleResolveComment(commentId, resolved);
},
- [timeline, clearResolvedExpand, toggleResolveComment],
+ [displayTimeline, clearResolvedExpand, toggleResolveComment],
);
// Memoized timeline grouping. Each render rebuilds the per-parent map from
@@ -1458,11 +1473,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// bucketed under their parent's id and rendered nested inside CommentCard.
// No orphan rescue needed: the timeline is fetched in full, so every
// reply's parent is always in the same array.
- const topLevel = timeline.filter(
+ const topLevel = displayTimeline.filter(
(e) => e.type === "activity" || !e.parent_id,
);
const repliesByParent = new Map<string, TimelineEntry[]>();
- for (const e of timeline) {
+ for (const e of displayTimeline) {
if (e.type === "comment" && e.parent_id) {
const list = repliesByParent.get(e.parent_id) ?? [];
list.push(e);
@@ -1493,13 +1508,24 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const COALESCE_MS = 2 * 60 * 1000;
const NO_TIME_LIMIT_ACTIONS = new Set(["task_completed", "task_failed"]);
const NEVER_COALESCE_ACTIONS = new Set(["squad_leader_evaluated"]);
- const coalesced: TimelineEntry[] = [];
- for (const entry of topLevel) {
+ // Unanchored runs separate activity groups at their actual start position.
+ const standaloneReplyIds = new Set(standaloneRuns.filter((run) => run.hasReply).map((run) => run.commentId));
+ const chronological = [...topLevel.filter((entry) => !standaloneReplyIds.has(entry.id)), ...standaloneRuns].sort((a, b) => {
+ const left = "task" in a ? a.task : a;
+ const right = "task" in b ? b.task : b;
+ return Date.parse(left.created_at) - Date.parse(right.created_at);
+ });
+ const coalesced: (TimelineEntry | CommentRun)[] = [];
+ for (const entry of chronological) {
+ if ("task" in entry) {
+ coalesced.push(entry);
+ continue;
+ }
if (entry.type === "activity") {
const prev = coalesced[coalesced.length - 1];
if (
!NEVER_COALESCE_ACTIONS.has(entry.action!) &&
- prev?.type === "activity" &&
+ prev && !("task" in prev) && prev.type === "activity" &&
prev.action === entry.action &&
prev.actor_type === entry.actor_type &&
prev.actor_id === entry.actor_id &&
@@ -1514,9 +1540,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
}
// Group consecutive activities together so the connector line works
- const groups: { type: "activities" | "comment"; entries: TimelineEntry[] }[] = [];
+ const groups: RawTimelineGroup[] = [];
for (const entry of coalesced) {
- if (entry.type === "activity") {
+ if ("task" in entry) {
+ groups.push({ type: "run", run: entry, entry: entry.hasReply ? displayTimeline.find((comment) => comment.id === entry.commentId) : undefined });
+ } else if (entry.type === "activity") {
const last = groups[groups.length - 1];
if (last?.type === "activities") {
last.entries.push(entry);
@@ -1529,7 +1557,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
}
return { threadReplies, groups };
- }, [timeline]);
+ }, [displayTimeline, standaloneRuns]);
// Flat array consumed by <Virtuoso>. Recomputed when timelineView.groups
// changes (timeline events) or expandedResolved flips (user toggles a
@@ -1601,7 +1629,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const minimapThreads = useMemo<ThreadMinimapThread[]>(
() =>
items.flatMap((it) => {
- if (it.kind !== "comment" && it.kind !== "resolved-bar") return [];
+ if (it.kind === "activity-group" || !it.entry) return [];
const replies = timelineView.threadReplies.get(it.id) ?? EMPTY_REPLIES;
return [
{
@@ -1872,14 +1900,14 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const rootId = replyToRoot.get(highlightCommentId);
if (rootId && rootId !== highlightCommentId) {
// Root resolved → the whole thread is a folded bar.
- if (items[targetIdx]?.kind === "resolved-bar") {
+ const rootItem = items[targetIdx];
+ if (rootItem?.kind === "resolved-bar" || (rootItem?.kind === "run" && rootItem.entry?.resolved_at && !expandedResolved.has(rootId))) {
toggleResolvedExpand(rootId, true);
return;
}
// A reply is the resolution → the other replies fold behind the
// "N comments" bar; expand if the target is one of those folded replies.
- const rootItem = items[targetIdx];
- if (rootItem?.kind === "comment" && !expandedResolved.has(rootId)) {
+ if ((rootItem?.kind === "comment" || rootItem?.kind === "run") && rootItem.entry && !expandedResolved.has(rootId)) {
const resolution = deriveThreadResolution(
rootItem.entry,
timelineView.threadReplies.get(rootId) ?? EMPTY_REPLIES,
@@ -2005,7 +2033,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
{ content: issue?.description, attachments: descEditorAttachments },
];
for (const item of items) {
- if (item.kind === "activity-group") continue;
+ if (item.kind === "activity-group" || !item.entry) continue;
blocks.push({
content: item.entry.content,
attachments: item.entry.attachments,
@@ -2587,6 +2615,25 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// The wrapper `id="comment-..."` is the deep-link target — equivalent to
// a native `<a href="#comment-...">` anchor.
const renderItem = (_i: number, item: TimelineItem): React.ReactElement => {
+ if (item.kind === "run") {
+ const reply = item.entry;
+ return <div className="pb-3" id={reply ? `comment-${reply.id}` : undefined}>
+ {reply?.resolved_at && !expandedResolved.has(reply.id) ? <ResolvedThreadBar
+ entry={reply} replies={timelineView.threadReplies.get(reply.id) ?? EMPTY_REPLIES}
+ onExpand={() => toggleResolvedExpand(reply.id, true)} /> : <AgentRunComment run={item.run} entering={enteringRunIds.has(item.run.task.id)} standalone
+ commentProps={reply ? {
+ issueId: id, entry: reply, replies: timelineView.threadReplies.get(reply.id) ?? EMPTY_REPLIES,
+ currentUserId: user?.id, canModerate: canModerateComments, onReply: submitReply,
+ onReplyAccepted: scrollToTimelineBottom, onEdit: editComment, onDelete: deleteComment,
+ onToggleReaction: handleToggleReaction, onCreateSubIssue: openCommentSubIssue,
+ onResolveToggle: handleResolveToggle,
+ onCollapseResolved: reply.resolved_at ? () => toggleResolvedExpand(reply.id, false) : undefined,
+ expandedResolvedIds: expandedResolved, onResolvedExpandChange: toggleResolvedExpand,
+ highlightedCommentId: highlightedId,
+ runs: commentRuns.get(reply.id) ?? EMPTY_COMMENT_RUNS, enteringRunIds,
+ } : undefined} />}
+ </div>;
+ }
if (item.kind === "resolved-bar") {
return (
<div className="pb-3" id={`comment-${item.id}`}>
@@ -2604,6 +2651,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
<div className="pb-3" id={`comment-${item.id}`}>
<CommentCard
issueId={id}
+ runs={commentRuns.get(item.id) ?? EMPTY_COMMENT_RUNS}
+ enteringRunIds={enteringRunIds}
entry={item.entry}
replies={timelineView.threadReplies.get(item.id) ?? EMPTY_REPLIES}
currentUserId={user?.id}
@@ -3331,7 +3380,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
data={items}
initialScrollTop={restoredScrollTop}
increaseViewportBy={{ top: 800, bottom: 800 }}
- computeItemKey={(_i, item) => `${item.kind}:${item.id}`}
+ computeItemKey={(_i, item) => `${item.kind}:${item.kind === "run" ? item.run.task.id : item.id}`}
skipAnimationFrameInResizeObserver
// followOutput intentionally NOT set. Virtuoso treats
// it as a sticky "is at bottom" flag and resets
@@ -3344,7 +3393,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
) : (
<div className="mt-4">
{items.map((item, i) => (
- <Fragment key={`${item.kind}:${item.id}`}>
+ <Fragment key={`${item.kind}:${item.kind === "run" ? item.run.task.id : item.id}`}>
{renderItem(i, item)}
</Fragment>
))}
diff --git a/packages/views/issues/components/use-run-comment-motion.test.tsx b/packages/views/issues/components/use-run-comment-motion.test.tsx
new file mode 100644
index 0000000000..9c202be219
--- /dev/null
+++ b/packages/views/issues/components/use-run-comment-motion.test.tsx
@@ -0,0 +1,138 @@
+import { useState } from "react";
+import { cleanup, fireEvent, render, renderHook, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { AgentTask } from "@multica/core/types";
+import { useNewRunIds, useRunCommentMotion, useRunDisclosureMotion } from "./use-run-comment-motion";
+
+const animate = vi.fn((_frames: Keyframe[], _options: KeyframeAnimationOptions) => ({ cancel: vi.fn() }));
+const originalAnimate = Object.getOwnPropertyDescriptor(Element.prototype, "animate");
+let reduced = false;
+beforeEach(() => {
+ reduced = false;
+ animate.mockClear();
+ Object.defineProperty(Element.prototype, "animate", { configurable: true, value: animate });
+ vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: reduced })));
+});
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ if (originalAnimate) Object.defineProperty(Element.prototype, "animate", originalAnimate);
+ else Reflect.deleteProperty(Element.prototype, "animate");
+ vi.unstubAllGlobals();
+});
+
+function task(id: string): AgentTask {
+ return { id, issue_id: "issue", agent_id: "agent", runtime_id: "runtime", status: "queued", priority: 0,
+ created_at: "2026-09-07T00:00:00Z", started_at: null, dispatched_at: null, completed_at: null, result: null, error: null };
+}
+
+function Slot({ entering = false, replyId, status = "queued" }: { entering?: boolean; replyId?: string; status?: string }) {
+ const ref = useRunCommentMotion(entering, replyId, status);
+ return <div ref={ref}><span data-run-status>{status}</span><div data-comment-content={replyId}>Reply</div></div>;
+}
+function Disclosure() {
+ const [open, setOpen] = useState(false);
+ const motion = useRunDisclosureMotion(open);
+ return <>
+ <button key={String(open)} onClick={(event) => { motion.onTrigger(event); setOpen(!open); }}>
+ <svg ref={motion.chevronRef} style={{ rotate: open ? "90deg" : "0deg" }} />Toggle
+ </button>
+ {open && <div ref={motion.contentRef}>Activity</div>}
+ </>;
+}
+
+describe("run comment motion", () => {
+ it("marks only runs added after the initial snapshot and resets across issues", async () => {
+ const old = task("old");
+ const added = task("new");
+ const { result, rerender } = renderHook(({ issueId, tasks }: { issueId: string; tasks?: AgentTask[] }) => useNewRunIds(issueId, tasks),
+ { initialProps: { issueId: "first", tasks: undefined } as { issueId: string; tasks?: AgentTask[] } });
+ rerender({ issueId: "first", tasks: [old] });
+ expect(result.current.size).toBe(0);
+ rerender({ issueId: "first", tasks: [old, added] });
+ await waitFor(() => expect([...result.current]).toEqual(["new"]));
+ const marked = result.current;
+ rerender({ issueId: "first", tasks: [old, { ...added, status: "running" }] });
+ expect(result.current).toBe(marked);
+ rerender({ issueId: "second", tasks: [task("other")] });
+ expect(result.current.size).toBe(0);
+ });
+
+ it("animates live arrival once and never replays on a virtualized remount", () => {
+ const view = render(<Slot />);
+ expect(animate).not.toHaveBeenCalled();
+ view.rerender(<Slot entering />);
+ expect(animate).toHaveBeenCalledWith(
+ [{ opacity: 0, transform: "translateY(4px)" }, { opacity: 1, transform: "translateY(0)" }],
+ expect.objectContaining({ duration: 160 }),
+ );
+ view.rerender(<Slot entering />);
+ expect(animate).toHaveBeenCalledTimes(1);
+ const animation = animate.mock.results[0]!.value;
+ view.unmount();
+ expect(animation.cancel).toHaveBeenCalled();
+ animate.mockClear();
+ render(<Slot entering />);
+ expect(animate).not.toHaveBeenCalled();
+ });
+
+ it("fades only the arriving reply and changed status, not routine rerenders", () => {
+ const view = render(<Slot status="running" />);
+ view.rerender(<Slot status="completed" replyId="reply" />);
+ expect(animate.mock.instances).toEqual([screen.getByText("Reply"), screen.getByText("completed")]);
+ expect(animate.mock.calls.map((call) => call[1].duration)).toEqual([160, 100]);
+ view.rerender(<Slot status="completed" replyId="reply" />);
+ expect(animate).toHaveBeenCalledTimes(2);
+ view.unmount();
+ animate.mockClear();
+ render(<Slot status="completed" replyId="reply" />);
+ expect(animate).not.toHaveBeenCalled();
+ });
+
+ it("keeps reduced motion to a short fade without displacement", () => {
+ reduced = true;
+ const view = render(<Slot />);
+ view.rerender(<Slot entering />);
+ expect(animate).toHaveBeenCalledWith([{ opacity: 0 }, { opacity: 1 }], expect.objectContaining({ duration: 60 }));
+ });
+
+ it("fades pointer disclosure once and keeps keyboard disclosure immediate", () => {
+ render(<Disclosure />);
+ const toggle = () => screen.getByRole("button", { name: "Toggle" });
+ fireEvent.click(toggle(), { detail: 1 });
+ expect(screen.getByText("Activity")).toBeInTheDocument();
+ expect(animate).toHaveBeenCalledWith(
+ [{ opacity: 0, transform: "translateY(-4px)" }, { opacity: 1, transform: "translateY(0)" }],
+ expect.objectContaining({ duration: 180 }),
+ );
+ expect(animate).toHaveBeenCalledWith([{ rotate: "0deg" }, { rotate: "90deg" }], expect.objectContaining({ duration: 180 }));
+ fireEvent.click(toggle(), { detail: 1 });
+ expect(animate).toHaveBeenCalledWith([{ rotate: "90deg" }, { rotate: "0deg" }], expect.objectContaining({ duration: 120 }));
+ animate.mockClear();
+ fireEvent.click(toggle(), { detail: 0 });
+ expect(screen.getByText("Activity")).toBeInTheDocument();
+ expect(animate).not.toHaveBeenCalled();
+ });
+
+ it("uses only a short content fade for reduced-motion disclosure", () => {
+ reduced = true;
+ render(<Disclosure />);
+ fireEvent.click(screen.getByRole("button", { name: "Toggle" }), { detail: 1 });
+ expect(animate).toHaveBeenCalledTimes(1);
+ expect(animate).toHaveBeenCalledWith([{ opacity: 0 }, { opacity: 1 }], expect.objectContaining({ duration: 60 }));
+ });
+
+ it("reverses a rapid toggle from the visible arrow angle and cancels stale motion", () => {
+ render(<Disclosure />);
+ fireEvent.click(screen.getByRole("button", { name: "Toggle" }), { detail: 1 });
+ const firstAnimations = animate.mock.results.map((result) => result.value);
+ const toggle = screen.getByRole("button", { name: "Toggle" });
+ const computed = getComputedStyle(toggle.querySelector("svg")!);
+ computed.rotate = "42deg";
+ const style = vi.spyOn(window, "getComputedStyle").mockReturnValue(computed);
+ fireEvent.click(toggle, { detail: 1 });
+ expect(animate).toHaveBeenLastCalledWith([{ rotate: "42deg" }, { rotate: "0deg" }], expect.objectContaining({ duration: 120 }));
+ for (const animation of firstAnimations) expect(animation.cancel).toHaveBeenCalled();
+ style.mockRestore();
+ });
+});
diff --git a/packages/views/issues/components/use-run-comment-motion.ts b/packages/views/issues/components/use-run-comment-motion.ts
new file mode 100644
index 0000000000..ab744ea1f7
--- /dev/null
+++ b/packages/views/issues/components/use-run-comment-motion.ts
@@ -0,0 +1,97 @@
+import { useEffect, useLayoutEffect, useRef, useState, type MouseEvent } from "react";
+import type { AgentTask } from "@multica/core/types";
+
+const EMPTY_IDS: ReadonlySet<string> = new Set();
+const EASING = "cubic-bezier(0.22, 1, 0.36, 1)";
+
+function reveal(element: HTMLElement | null, duration: number, translate = 0) {
+ if (!element?.animate) return;
+ const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
+ return element.animate(
+ translate && !reduced
+ ? [{ opacity: 0, transform: `translateY(${translate}px)` }, { opacity: 1, transform: "translateY(0)" }]
+ : [{ opacity: 0 }, { opacity: 1 }],
+ { duration: reduced ? 60 : duration, easing: EASING },
+ );
+}
+
+/** Mark additions after the initial query, not existing history or route restoration. */
+export function useNewRunIds(issueId: string, tasks: readonly AgentTask[] | undefined) {
+ const known = useRef<{ issueId: string; ids: Set<string> } | null>(null);
+ const [arrivals, setArrivals] = useState<{ issueId: string; ids: ReadonlySet<string> }>({ issueId, ids: EMPTY_IDS });
+ useEffect(() => {
+ if (!tasks) return;
+ if (!known.current || known.current.issueId !== issueId) {
+ known.current = { issueId, ids: new Set(tasks.map((task) => task.id)) };
+ setArrivals((previous) => previous.issueId === issueId && previous.ids === EMPTY_IDS
+ ? previous : { issueId, ids: EMPTY_IDS });
+ return;
+ }
+ const added = tasks.filter((task) => !known.current!.ids.has(task.id));
+ if (added.length === 0) return;
+ for (const task of added) known.current.ids.add(task.id);
+ setArrivals((previous) => ({ issueId, ids: new Set([
+ ...(previous.issueId === issueId ? previous.ids : EMPTY_IDS), ...added.map((task) => task.id),
+ ]) }));
+ }, [issueId, tasks]);
+ return arrivals.issueId === issueId ? arrivals.ids : EMPTY_IDS;
+}
+
+/** Animate observed changes only. A virtualized row's first mount is always still. */
+export function useRunCommentMotion(entering: boolean, replyId: string | undefined, status: string) {
+ const ref = useRef<HTMLDivElement>(null);
+ const previous = useRef({ entering, replyId, status });
+ useLayoutEffect(() => {
+ const before = previous.current;
+ previous.current = { entering, replyId, status };
+ const animations: (Animation | undefined)[] = [];
+ if (entering && !before.entering) animations.push(reveal(ref.current, 160, 4));
+ if (replyId && replyId !== before.replyId) {
+ const body = Array.from(ref.current?.querySelectorAll<HTMLElement>("[data-comment-content]") ?? [])
+ .find((element) => element.dataset.commentContent === replyId);
+ animations.push(reveal(body ?? null, 160));
+ }
+ if (status !== before.status) animations.push(reveal(ref.current?.querySelector("[data-run-status]") ?? null, 100));
+ return () => { for (const animation of animations) animation?.cancel(); };
+ }, [entering, replyId, status]);
+ return ref;
+}
+
+/** Animate the toggle itself, including when historical runs mount a new trigger. */
+export function useRunDisclosureMotion(open: boolean) {
+ const contentRef = useRef<HTMLDivElement>(null);
+ const chevronRef = useRef<SVGSVGElement>(null);
+ const pending = useRef(false);
+ const focusedTrigger = useRef<HTMLElement | null>(null);
+ const fromRotation = useRef("0deg");
+ useLayoutEffect(() => {
+ const requested = pending.current;
+ pending.current = false;
+ const previousTrigger = focusedTrigger.current;
+ focusedTrigger.current = null;
+ if (previousTrigger && !previousTrigger.isConnected && document.activeElement === document.body) {
+ chevronRef.current?.closest<HTMLElement>("button, summary")?.focus({ preventScroll: true });
+ }
+ if (!requested) return;
+ const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
+ const duration = open ? 180 : 120;
+ const arrow = !reduced ? chevronRef.current?.animate?.(
+ [{ rotate: fromRotation.current }, { rotate: open ? "90deg" : "0deg" }],
+ { duration, easing: EASING },
+ ) : undefined;
+ const content = open ? reveal(contentRef.current, duration, -4) : undefined;
+ return () => { arrow?.cancel(); content?.cancel(); };
+ }, [open]);
+ return {
+ contentRef,
+ chevronRef,
+ onTrigger(event: MouseEvent<HTMLElement>) {
+ pending.current = event.detail > 0;
+ focusedTrigger.current = event.detail === 0 && document.activeElement === event.currentTarget ? event.currentTarget : null;
+ // Sample before React cancels the previous animation or replaces the
+ // trigger, so rapid reversals start at the currently visible angle.
+ const rotation = chevronRef.current ? getComputedStyle(chevronRef.current).rotate : undefined;
+ fromRotation.current = rotation && rotation !== "none" ? rotation : open ? "90deg" : "0deg";
+ },
+ };
+}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 822a7f8900..a7c08c098c 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -1,4 +1,26 @@
{
+ "inline_run": {
+ "label": "{{name}} run",
+ "stop": "Stop",
+ "stopping": "Stopping...",
+ "queued": "Waiting for an available agent.",
+ "starting": "Preparing the agent session.",
+ "waiting_directory": "Waiting for another run to release the working directory.",
+ "thinking": "Thinking",
+ "waiting_response": "Waiting for the agent to respond.",
+ "view_activity": "View activity",
+ "steps_one": "{{count}} step",
+ "steps_other": "{{count}} steps",
+ "loading": "Loading activity...",
+ "load_failed": "Could not load activity.",
+ "try_again": "Try again",
+ "empty": "No activity recorded yet.",
+ "show_earlier": "Show {{count}} earlier steps",
+ "full_log": "Open full log",
+ "message": "Agent message",
+ "error": "Error",
+ "waiting_result": "Waiting for the tool result..."
+ },
"status_catalog_error": {
"title": "Couldn't load the status list",
"hint": "Issues are hidden until it loads, because a status filter can't be applied without it.",
@@ -459,6 +481,9 @@
"show_more_activities_other": "Show {{count}} more activities"
},
"comment": {
+ "add_reaction": "Add reaction",
+ "collapse_thread": "Collapse thread",
+ "expand_thread": "Expand thread",
"delete_title": "Delete comment",
"delete_desc": "This comment will be permanently deleted. This cannot be undone.",
"delete_desc_with_replies": "This comment and all its replies will be permanently deleted. This cannot be undone.",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 2ba63d11e7..2fabbef122 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -1,4 +1,25 @@
{
+ "inline_run": {
+ "label": "{{name}} の実行",
+ "stop": "停止",
+ "stopping": "停止中...",
+ "queued": "利用可能なエージェントを待っています。",
+ "starting": "エージェントのセッションを準備しています。",
+ "waiting_directory": "別の実行が作業ディレクトリを解放するのを待っています。",
+ "thinking": "思考中",
+ "waiting_response": "エージェントの応答を待っています。",
+ "view_activity": "実行過程を表示",
+ "steps_other": "{{count}} ステップ",
+ "loading": "実行過程を読み込み中...",
+ "load_failed": "実行過程を読み込めませんでした。",
+ "try_again": "再試行",
+ "empty": "実行記録はまだありません。",
+ "show_earlier": "前の {{count}} ステップを表示",
+ "full_log": "完全なログを開く",
+ "message": "エージェントのメッセージ",
+ "error": "エラー",
+ "waiting_result": "ツールの結果を待っています..."
+ },
"status_catalog_error": {
"title": "ステータス一覧を読み込めませんでした",
"hint": "これがないとステータスの絞り込みを適用できないため、タスクは表示されません。",
@@ -451,6 +472,9 @@
"show_more_activities_other": "アクティビティをさらに {{count}} 件表示"
},
"comment": {
+ "add_reaction": "リアクションを追加",
+ "collapse_thread": "スレッドを折りたたむ",
+ "expand_thread": "スレッドを展開",
"delete_title": "コメントを削除",
"delete_desc": "このコメントは完全に削除されます。この操作は元に戻せません。",
"delete_desc_with_replies": "このコメントとすべての返信が完全に削除されます。この操作は元に戻せません。",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 94788b57a9..a11286b582 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -1,4 +1,25 @@
{
+ "inline_run": {
+ "label": "{{name}} 실행",
+ "stop": "중지",
+ "stopping": "중지 중...",
+ "queued": "사용 가능한 에이전트를 기다리고 있습니다.",
+ "starting": "에이전트 세션을 준비하고 있습니다.",
+ "waiting_directory": "다른 실행이 작업 디렉터리를 해제할 때까지 기다리고 있습니다.",
+ "thinking": "생각 중",
+ "waiting_response": "에이전트의 응답을 기다리고 있습니다.",
+ "view_activity": "실행 과정 보기",
+ "steps_other": "{{count}}단계",
+ "loading": "실행 과정 불러오는 중...",
+ "load_failed": "실행 과정을 불러올 수 없습니다.",
+ "try_again": "다시 시도",
+ "empty": "아직 실행 기록이 없습니다.",
+ "show_earlier": "이전 {{count}}단계 보기",
+ "full_log": "전체 로그 열기",
+ "message": "에이전트 메시지",
+ "error": "오류",
+ "waiting_result": "도구 결과를 기다리고 있습니다..."
+ },
"status_catalog_error": {
"title": "상태 목록을 불러오지 못했습니다",
"hint": "이것 없이는 상태 필터를 적용할 수 없어 태스크를 표시하지 않습니다.",
@@ -451,6 +472,9 @@
"show_more_activities_other": "활동 {{count}}개 더 보기"
},
"comment": {
+ "add_reaction": "반응 추가",
+ "collapse_thread": "스레드 접기",
+ "expand_thread": "스레드 펼치기",
"delete_title": "댓글 삭제",
"delete_desc": "이 댓글이 영구 삭제됩니다. 이 작업은 되돌릴 수 없습니다.",
"delete_desc_with_replies": "이 댓글과 모든 답글이 영구 삭제됩니다. 이 작업은 되돌릴 수 없습니다.",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index fcd1438bf6..4c308301ba 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -1,4 +1,25 @@
{
+ "inline_run": {
+ "label": "{{name}} 的运行",
+ "stop": "停止",
+ "stopping": "正在停止...",
+ "queued": "等待可用的智能体。",
+ "starting": "正在准备智能体会话。",
+ "waiting_directory": "等待其他运行释放工作目录。",
+ "thinking": "思考中",
+ "waiting_response": "等待智能体响应。",
+ "view_activity": "查看执行过程",
+ "steps_other": "{{count}} 个步骤",
+ "loading": "正在加载执行过程...",
+ "load_failed": "无法加载执行过程。",
+ "try_again": "重试",
+ "empty": "暂无执行记录。",
+ "show_earlier": "显示前面的 {{count}} 个步骤",
+ "full_log": "打开完整日志",
+ "message": "智能体消息",
+ "error": "错误",
+ "waiting_result": "等待工具返回结果..."
+ },
"status_catalog_error": {
"title": "状态列表加载失败",
"hint": "没有它就无法应用状态筛选,因此暂时不显示任务。",
@@ -451,6 +472,9 @@
"show_more_activities_other": "展开更早 {{count}} 条动态"
},
"comment": {
+ "add_reaction": "添加表情回应",
+ "collapse_thread": "收起讨论",
+ "expand_thread": "展开讨论",
"delete_title": "删除评论",
"delete_desc": "这条评论会被永久删除,无法撤销。",
"delete_desc_with_replies": "这条评论及其全部回复会被永久删除,无法撤销。",
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index d6cb2d4821..a4a7dc7d4c 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -298,6 +298,7 @@ var concurrentIndexCleanups = map[string]string{
"443_issue_project_status_index": "idx_issue_project_status",
"445_comment_delegated_failure_unsettled_index": "idx_comment_delegated_failure_unsettled",
"446_issue_properties_bigm_index": "idx_issue_properties_bigm",
+ "452_agent_task_pending_thread_unique": "idx_one_pending_task_per_issue_agent_thread",
}
// concurrentDownIndexCleanups covers every migration whose down direction
@@ -322,6 +323,7 @@ var concurrentDownIndexCleanups = map[string]string{
"391_drop_agent_task_queue_dispatched_prepare_index": "idx_agent_task_queue_dispatched_prepare",
"437_drop_agent_runtime_last_seen_at_index": "idx_agent_runtime_last_seen_at",
"450_drop_comment_delegated_failure_pending_index": "idx_comment_delegated_failure_pending",
+ "453_drop_pending_issue_agent_unique": "idx_one_pending_task_per_issue_agent_v2",
}
var preMigrationHooks = func() map[string]preMigrationHook {
diff --git a/server/cmd/server/comment_at_least_once_test.go b/server/cmd/server/comment_at_least_once_test.go
index bc3460369c..340dccdff2 100644
--- a/server/cmd/server/comment_at_least_once_test.go
+++ b/server/cmd/server/comment_at_least_once_test.go
@@ -2,6 +2,7 @@ package main
import (
"context"
+ "fmt"
"testing"
"time"
@@ -65,12 +66,13 @@ func TestConsecutiveCommentsMergeNotDropped(t *testing.T) {
resp.Body.Close()
})
- // Three deliberate comments in a row, before any run starts.
- cidA := postComment(t, issueID, "First instruction", nil)
- cidB := postComment(t, issueID, "Second, correcting the first", nil)
- cidC := postComment(t, issueID, "Third, one more detail", nil)
+ // Three explicit instructions in the same thread, before any run starts.
+ mention := fmt.Sprintf("[@Agent](mention://agent/%s) ", agentID)
+ cidA := postComment(t, issueID, mention+"First instruction", nil)
+ cidB := postComment(t, issueID, mention+"Second, correcting the first", &cidA)
+ cidC := postComment(t, issueID, mention+"Third, one more detail", &cidA)
- // Still exactly one task: we bound concurrency to one run per (issue,agent).
+ // Still exactly one pending task for this (issue, agent, thread).
if n := countPendingTasksForAgent(t, issueID, agentID); n != 1 {
t.Fatalf("expected exactly 1 pending task after 3 comments, got %d", n)
}
@@ -147,14 +149,18 @@ func TestGetLatestMemberCommentForIssueSince(t *testing.T) {
// insertCommentAt inserts a comment with an explicit created_at and author, and
// returns its id. Used to construct precise before/after-anchor scenarios.
-func insertCommentAt(t *testing.T, issueID, authorType, authorID, content string, at time.Time) string {
+func insertCommentAt(t *testing.T, issueID, authorType, authorID, content string, at time.Time, parentIDs ...string) string {
t.Helper()
var id string
+ var parentID *string
+ if len(parentIDs) > 0 {
+ parentID = &parentIDs[0]
+ }
err := testPool.QueryRow(context.Background(), `
- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at, updated_at)
- VALUES ($1, $2, $3, $4, $5, 'comment', $6, $6)
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at, updated_at, parent_id)
+ VALUES ($1, $2, $3, $4, $5, 'comment', $6, $6, $7)
RETURNING id::text
- `, issueID, testWorkspaceID, authorType, authorID, content, at).Scan(&id)
+ `, issueID, testWorkspaceID, authorType, authorID, content, at, parentID).Scan(&id)
if err != nil {
t.Fatalf("insertCommentAt: %v", err)
}
@@ -211,7 +217,7 @@ func TestMergeCommentIntoPendingTask_RecomputesOriginatorAndSkipsDispatched(t *t
now := time.Now()
cidA := insertCommentAt(t, issueID, "member", testUserID, "first, from originator A", now.Add(-2*time.Minute))
- cidB := insertCommentAt(t, issueID, "member", testUserID, "second, folds in", now.Add(-1*time.Minute))
+ cidB := insertCommentAt(t, issueID, "member", testUserID, "second, folds in", now.Add(-1*time.Minute), cidA)
// A second member to act as a DIFFERENT originator.
otherUserID := createWorkspaceMember(t, "merge-recompute-other")
@@ -259,7 +265,7 @@ func TestMergeCommentIntoPendingTask_RecomputesOriginatorAndSkipsDispatched(t *t
if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE issue_id = $1`, issueID); err != nil {
t.Fatalf("flip task to dispatched: %v", err)
}
- cidC := insertCommentAt(t, issueID, "member", testUserID, "third, arrives after dispatch", now)
+ cidC := insertCommentAt(t, issueID, "member", testUserID, "third, arrives after dispatch", now, cidA)
if _, err := queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
IssueID: pgIssue,
AgentID: pgAgent,
@@ -339,8 +345,8 @@ func TestMergeCommentIntoPendingTask_TargetsQueuedNotDeferred(t *testing.T) {
now := time.Now()
cidQueued := insertCommentAt(t, issueID, "member", testUserID, "queued task trigger", now.Add(-3*time.Minute))
- cidDeferred := insertCommentAt(t, issueID, "member", testUserID, "deferred fallback trigger", now.Add(-2*time.Minute))
- cidNew := insertCommentAt(t, issueID, "member", testUserID, "new comment, must fold into queued", now.Add(-1*time.Minute))
+ cidDeferred := insertCommentAt(t, issueID, "member", testUserID, "deferred fallback trigger", now.Add(-2*time.Minute), cidQueued)
+ cidNew := insertCommentAt(t, issueID, "member", testUserID, "new comment, must fold into queued", now.Add(-1*time.Minute), cidQueued)
var runtimeID string
if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {
diff --git a/server/cmd/server/comment_trigger_integration_test.go b/server/cmd/server/comment_trigger_integration_test.go
index 0a8210c6fd..9cf4955527 100644
--- a/server/cmd/server/comment_trigger_integration_test.go
+++ b/server/cmd/server/comment_trigger_integration_test.go
@@ -671,9 +671,9 @@ func TestDeleteCommentCancelsTriggeredTasks(t *testing.T) {
})
}
-// TestCommentTriggerCoalescing verifies that rapid-fire comments don't create
-// duplicate tasks (coalescing dedup).
-func TestCommentTriggerCoalescing(t *testing.T) {
+// TestCommentThreadsQueueSeparatelyFromAssignment verifies that each root
+// comment queues independently of other threads and the assignment task.
+func TestCommentThreadsQueueSeparatelyFromAssignment(t *testing.T) {
agentID := getAgentID(t)
issueID := createIssueAssignedToAgent(t, "Coalescing test", agentID)
t.Cleanup(func() {
@@ -682,12 +682,21 @@ func TestCommentTriggerCoalescing(t *testing.T) {
resp.Body.Close()
})
- // Post two comments rapidly — only 1 task should be created (coalescing).
- postComment(t, issueID, "First comment", nil)
- postComment(t, issueID, "Second comment", nil)
+ // Distinct root comments must not merge with each other or the assignment.
+ first := postComment(t, issueID, "First comment", nil)
+ second := postComment(t, issueID, "Second comment", nil)
- if n := countPendingTasks(t, issueID); n != 1 {
- t.Errorf("expected 1 pending task (coalescing), got %d", n)
+ if n := countPendingTasks(t, issueID); n != 3 {
+ t.Fatalf("expected assignment plus two independent thread tasks, got %d", n)
+ }
+ for _, id := range []string{first, second} {
+ var count int
+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent_task_queue WHERE issue_id=$1 AND agent_id=$2 AND trigger_comment_id=$3 AND cardinality(coalesced_comment_ids)=0`, issueID, agentID, id).Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count != 1 {
+ t.Errorf("comment %s should own exactly one unmerged task, got %d", id, count)
+ }
}
}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 56c275691b..e91717ef13 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -346,6 +346,8 @@ type TaskIssueStatusData struct {
}
type AgentTaskResponse struct {
+ CancelledByCommentChange bool `json:"cancelled_by_comment_change,omitempty"`
+
ID string `json:"id"`
AgentID string `json:"agent_id"`
RuntimeID string `json:"runtime_id"`
@@ -752,6 +754,10 @@ type TaskAgentData struct {
// derivation; pass "" only on daemon-facing paths that genuinely don't have
// it, in which case RelativeWorkDir falls back to the existing WorkDir.
func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {
+ var cancellation struct {
+ TaskID string `json:"comment_change_cancelled_task_id"`
+ }
+ _ = json.Unmarshal(t.Context, &cancellation)
var result any
if t.Result != nil {
json.Unmarshal(t.Result, &result)
@@ -777,6 +783,9 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {
handoffNote = t.HandoffNote.String
}
return AgentTaskResponse{
+ // Task-scoped provenance must not transfer through copied retry context.
+ CancelledByCommentChange: t.Status == "cancelled" && cancellation.TaskID != "" && cancellation.TaskID == uuidToString(t.ID),
+
ID: uuidToString(t.ID),
AgentID: uuidToString(t.AgentID),
RuntimeID: uuidToString(t.RuntimeID),
diff --git a/server/internal/handler/attribution_response_test.go b/server/internal/handler/attribution_response_test.go
index b302a3a387..abe4c7dc9b 100644
--- a/server/internal/handler/attribution_response_test.go
+++ b/server/internal/handler/attribution_response_test.go
@@ -11,6 +11,26 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
+func TestTaskCommentChangeCancellation(t *testing.T) {
+ id := "11111111-1111-1111-1111-111111111111"
+ for _, tc := range []struct {
+ name, taskID, status, context string
+ want bool
+ }{
+ {"edited input", id, "cancelled", `{"comment_change_cancelled_task_id":"` + id + `"}`, true},
+ {"manual stop", id, "cancelled", `{}`, false},
+ {"retry inherits context", "22222222-2222-2222-2222-222222222222", "cancelled", `{"comment_change_cancelled_task_id":"` + id + `"}`, false},
+ {"not cancelled", id, "running", `{"comment_change_cancelled_task_id":"` + id + `"}`, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got := taskToResponse(db.AgentTaskQueue{ID: parseUUID(tc.taskID), Status: tc.status, Context: []byte(tc.context)}, "")
+ if got.CancelledByCommentChange != tc.want {
+ t.Fatalf("cancelled_by_comment_change = %v, want %v", got.CancelledByCommentChange, tc.want)
+ }
+ })
+ }
+}
+
// TestTaskAttributionBase covers the pure row→attribution mapping (MUL-4302 §9):
// source label + precise flag, initiator/originator raw refs, evidence, lineage —
// no DB, no name hydration.
diff --git a/server/internal/handler/autopilot_mention_authority_test.go b/server/internal/handler/autopilot_mention_authority_test.go
index 8528c86982..c59bd39b41 100644
--- a/server/internal/handler/autopilot_mention_authority_test.go
+++ b/server/internal/handler/autopilot_mention_authority_test.go
@@ -378,6 +378,8 @@ func TestReconcileCommentsOnCompletion_AutopilotDelegationRestoresAuthority(t *t
fx := newAutopilotDelegationFixture(t, workerID, creatorUserID, "autopilot")
issueID := uuidToString(fx.Issue.ID)
workerTaskID := seedCompletedTaskOnIssueBefore(t, workerID, issueID, fx.RuntimeID)
+ // Simulate a claim race that registered an undelivered thread input.
+ dbfx.Exec(t, `UPDATE agent_task_queue SET coalesced_comment_ids=ARRAY[$2::uuid] WHERE id=$1`, workerTaskID, fx.Comment.ID)
workerTask, err := testHandler.Queries.GetAgentTask(ctx, util.MustParseUUID(workerTaskID))
if err != nil {
t.Fatalf("load worker task: %v", err)
@@ -651,6 +653,8 @@ func TestUpdateComment_AdminEditOfAgentCommentClearsStaleLineage(t *testing.T) {
// lineage cleared it must NOT resurrect the creator authority or enqueue a
// follow-up. (Without the fix this reconcile would enqueue exactly one.)
workerTaskID := seedCompletedTaskOnIssueBefore(t, workerID, issueID, fx.RuntimeID)
+ // Simulate a claim race that registered an undelivered thread input.
+ dbfx.Exec(t, `UPDATE agent_task_queue SET coalesced_comment_ids=ARRAY[$2::uuid] WHERE id=$1`, workerTaskID, fx.Comment.ID)
workerTask, err := testHandler.Queries.GetAgentTask(ctx, util.MustParseUUID(workerTaskID))
if err != nil {
t.Fatalf("load worker task: %v", err)
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index c96517806b..0990309ba6 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1535,6 +1535,7 @@ type commentAgentTrigger struct {
}
type commentTriggerComputeOptions struct {
+ ThreadCommentID pgtype.UUID
ExcludeTriggerCommentID pgtype.UUID
// OriginatorUserID is the top-of-chain human user id for this trigger
// (MUL-3963). Only consulted for AGENT actors — canInvokeAgent judges A2A
@@ -2138,7 +2139,7 @@ func (h *Handler) resolveCommentTriggerEnqueue(ctx context.Context, issue db.Iss
// it is newer than the task and completion reconcile covers it by
// timestamp; MUL-4195 leaves the claimed task untouched. Defer to
// the active task, or enqueue fresh if it has since finished.
- active, activeErr := h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, trigger.Agent.ID)
+ active, activeErr := h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, trigger.Agent.ID, triggerCommentID)
if status, reason, enqueueFresh := decidePostMergeMiss(active, activeErr); !enqueueFresh {
return status, reason
}
@@ -2270,10 +2271,11 @@ func commentEnqueueFailureReason(err error) DispatchReasonCode {
// duplicate) AND must not report a success — "cannot confirm whether a run is
// active" is never the same as "a run is active". See decidePostMergeMiss /
// decideSuppressedLeaderOutcome for the two decisions.
-func (h *Handler) hasActiveTaskForIssueAndAgent(ctx context.Context, issueID, agentID pgtype.UUID) (bool, error) {
- active, err := h.Queries.HasActiveTaskForIssueAndAgent(ctx, db.HasActiveTaskForIssueAndAgentParams{
- IssueID: issueID,
- AgentID: agentID,
+func (h *Handler) hasActiveTaskForIssueAndAgent(ctx context.Context, issueID, agentID, threadCommentID pgtype.UUID) (bool, error) {
+ active, err := h.Queries.HasActiveTaskForIssueAndAgentInThread(ctx, db.HasActiveTaskForIssueAndAgentInThreadParams{
+ ThreadCommentID: threadCommentID,
+ IssueID: issueID,
+ AgentID: agentID,
})
if err != nil {
slog.Warn("has active task for issue+agent check failed",
@@ -2625,6 +2627,13 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu
// — the implicit routing fallbacks (assignee, thread parent, conversation) were
// never named by the user, so a no-route there is not a silent no-op.
func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, actorType, actorID string, opts commentTriggerComputeOptions) ([]commentAgentTrigger, []commentMentionTarget) {
+ // A persisted comment determines its thread; previews use the parent.
+ // A new top-level preview has no thread yet and cannot merge with a queue.
+ opts.ThreadCommentID = opts.ExcludeTriggerCommentID
+ if !opts.ThreadCommentID.Valid && parentComment != nil {
+ opts.ThreadCommentID = parentComment.ID
+ }
+
if isNoteComment(content) {
return nil, nil
}
@@ -2989,21 +2998,26 @@ func (h *Handler) routeAssignedSquadLeaderFallback(ctx context.Context, issue db
}
func (h *Handler) hasPendingTaskForIssueAndAgent(ctx context.Context, issueID, agentID pgtype.UUID, opts commentTriggerComputeOptions) (bool, error) {
+ if !opts.ThreadCommentID.Valid {
+ return false, nil
+ }
// Key dedup on the reviewed head so re-pushing to the PR mid-review
// invalidates dedup and a fresh run enqueues against the new HEAD (TEN-356).
headSha := h.TaskService.ResolveIssueReviewSHAParam(ctx, issueID)
if opts.ExcludeTriggerCommentID.Valid {
- return h.Queries.HasPendingTaskForIssueAndAgentExcludingTriggerComment(ctx, db.HasPendingTaskForIssueAndAgentExcludingTriggerCommentParams{
+ return h.Queries.HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread(ctx, db.HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThreadParams{
+ ThreadCommentID: opts.ThreadCommentID,
IssueID: issueID,
AgentID: agentID,
ExcludeTriggerCommentID: opts.ExcludeTriggerCommentID,
HeadSha: headSha,
})
}
- return h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
- IssueID: issueID,
- AgentID: agentID,
- HeadSha: headSha,
+ return h.Queries.HasPendingTaskForIssueAndAgentInThread(ctx, db.HasPendingTaskForIssueAndAgentInThreadParams{
+ ThreadCommentID: opts.ThreadCommentID,
+ IssueID: issueID,
+ AgentID: agentID,
+ HeadSha: headSha,
})
}
@@ -3139,7 +3153,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
// deferred; otherwise nothing runs → self_trigger_suppressed.
if authorType == "agent" && authorID == uuidToString(leaderID) &&
h.shouldSuppressSquadLeaderSelfTrigger(ctx, issue.ID, leaderID, squad.ID) {
- active, activeErr := h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, leaderID)
+ active, activeErr := h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, leaderID, opts.ThreadCommentID)
status, reason := decideSuppressedLeaderOutcome(active, activeErr)
addTarget(commentMentionTarget{TargetType: "squad", TargetID: m.ID, Status: status, ReasonCode: reason})
continue
diff --git a/server/internal/handler/comment_duplicate_enqueue_race_test.go b/server/internal/handler/comment_duplicate_enqueue_race_test.go
index 8ce25715da..ea467a486e 100644
--- a/server/internal/handler/comment_duplicate_enqueue_race_test.go
+++ b/server/internal/handler/comment_duplicate_enqueue_race_test.go
@@ -9,6 +9,7 @@ import (
"testing"
"github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/testutil"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -43,14 +44,11 @@ func dupRaceFixture(t *testing.T, agentName string, issueNumber int) (agentID, i
func insertDupRaceComment(t *testing.T, issueID, content, age string) string {
t.Helper()
- var id string
- if err := testPool.QueryRow(context.Background(), `
- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)
- VALUES ($1, $2, 'member', $3, $4, 'comment', now() - $5::interval)
- RETURNING id
- `, issueID, testWorkspaceID, testUserID, content, age).Scan(&id); err != nil {
- t.Fatalf("insert comment %q: %v", content, err)
- }
+ // These race cases compete for the same thread slot.
+ var parentID *string
+ dbfx.QueryRow(t, `SELECT (SELECT id::text FROM comment WHERE issue_id=$1 AND parent_id IS NULL ORDER BY created_at, id LIMIT 1)`, issueID).Scan(&parentID)
+ id := dbfx.Comment(t, issueID, content, testutil.Cols{"parent_id": parentID})
+ dbfx.Exec(t, `UPDATE comment SET created_at=now()-$2::interval WHERE id=$1`, id, age)
return id
}
@@ -396,7 +394,7 @@ func TestCommentEnqueueRaceQueuedWinnerReattributesOriginator(t *testing.T) {
if _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agentUUID, util.MustParseUUID(winnerCommentID)); err != nil {
t.Fatalf("enqueue winning task: %v", err)
}
- // Losing comment authored by M2.
+ // Losing comment authored by M2 in the same thread.
var loserCommentID string
if err := testPool.QueryRow(ctx, `
INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)
@@ -406,6 +404,8 @@ func TestCommentEnqueueRaceQueuedWinnerReattributesOriginator(t *testing.T) {
t.Fatalf("insert M2 loser comment: %v", err)
}
+ dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE id=$1`, loserCommentID, winnerCommentID)
+
trigger := commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent}
results := testHandler.enqueueCommentAgentTriggers(ctx, issue, util.MustParseUUID(loserCommentID), []commentAgentTrigger{trigger})
if res := results[agentID]; res.status != DispatchCoalesced {
diff --git a/server/internal/handler/comment_merge_failclosed_test.go b/server/internal/handler/comment_merge_failclosed_test.go
index acc9780546..da8d86661c 100644
--- a/server/internal/handler/comment_merge_failclosed_test.go
+++ b/server/internal/handler/comment_merge_failclosed_test.go
@@ -50,6 +50,7 @@ func TestMergeCommentIntoPendingTask_FailClosedKeepsOriginalSnapshot(t *testing.
t.Fatalf("seed comment B: %v", err)
}
+ dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE id=$1`, cidB, cidA)
// A QUEUED task with a fully precise snapshot triggered by cidA.
if _, err := testPool.Exec(ctx, `
INSERT INTO agent_task_queue
diff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.go
index 676759ce47..bbdc910cde 100644
--- a/server/internal/handler/comment_reconcile_test.go
+++ b/server/internal/handler/comment_reconcile_test.go
@@ -94,6 +94,8 @@ func TestCompleteTask_ReconcilesMemberCommentPostedDuringRun(t *testing.T) {
VALUES ($1, $2, 'member', $3, 'wait, also handle this', 'comment', now() - interval '1 minute')
`, issueID, testWorkspaceID, testUserID)
+ dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE issue_id=$1 AND id<>$2`, issueID, triggerCommentID)
+
if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {
t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
}
@@ -287,6 +289,7 @@ func TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent(t *testing.
VALUES ($1, $2, 'agent', $3, $4, 'comment')
RETURNING id
`, issueID, testWorkspaceID, agentA, mention).Scan(&mentionCommentID)
+ dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE id=$1`, mentionCommentID, triggerCommentID)
mentionComment, err := testHandler.Queries.GetComment(ctx, util.MustParseUUID(mentionCommentID))
if err != nil {
t.Fatalf("setup: load mention comment: %v", err)
@@ -500,6 +503,8 @@ func TestConsecutiveCommentsDifferentOriginatorsFullEnqueuePath(t *testing.T) {
// B's comment (different originator) before start → must fold in, NOT drop.
cB := insertMemberComment(userB, "second, from B — different user")
+ dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE id=$1`, cB.ID, cA.ID)
+ cB.ParentID = cA.ID
testHandler.triggerTasksForComment(ctx, issue, cB, nil, "member", userB, userB, nil)
// Still exactly one task (bounded concurrency, no unique-index collision).
@@ -564,6 +569,8 @@ func TestCompleteTask_ReconcilesDispatchedWindowComment(t *testing.T) {
VALUES ($1, $2, 'member', $3, 'squeezed in before start', 'comment', now() - interval '3 minutes')
`, issueID, testWorkspaceID, testUserID)
+ dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE issue_id=$1 AND id<>$2`, issueID, triggerCommentID)
+
if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {
t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
}
@@ -655,6 +662,8 @@ func TestCompleteTask_ReconcilesPreDispatchMergeRaceComment(t *testing.T) {
`, agentID, runtimeID, issueID, triggerCommentID, deliveredCoalescedID).Scan(&taskID)
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })
+ dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE issue_id=$1 AND id<>$2`, issueID, triggerCommentID)
+
if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {
t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
}
@@ -713,8 +722,9 @@ func TestCompleteTask_ReconcilesPlannedButUndeliveredComments(t *testing.T) {
return id
}
old1 := insertComment("planned old one", "10 minutes")
- old2 := insertComment("planned old two", "9 minutes")
+ old2 := insertComment("[@Agent](mention://agent/"+agentID+") planned old two", "9 minutes")
trigger := insertComment("planned trigger", "8 minutes")
+ dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE issue_id=$1 AND id<>$2`, issueID, old1)
delivered := []string{trigger}
if tc.deliveredOldCount > 0 {
delivered = append([]string{old1}, delivered...)
diff --git a/server/internal/handler/comment_thread_queue_test.go b/server/internal/handler/comment_thread_queue_test.go
new file mode 100644
index 0000000000..c6215a6bcc
--- /dev/null
+++ b/server/internal/handler/comment_thread_queue_test.go
@@ -0,0 +1,144 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "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"
+)
+
+func TestCommentThreadQueuesMergeAndExecuteIndependently(t *testing.T) {
+ ctx := context.Background()
+ runtimeID := dbfx.Runtime(t, "thread queue runtime")
+ agentID := dbfx.Agent(t, "thread queue agent", runtimeID)
+ issueID := dbfx.Issue(t, "thread queue issue", testutil.Cols{"assignee_type": "agent", "assignee_id": agentID})
+ rootA := dbfx.Comment(t, issueID, "thread A")
+ rootB := dbfx.Comment(t, issueID, "thread B")
+ replyA := dbfx.Comment(t, issueID, "A supplement", testutil.Cols{"parent_id": rootA})
+ nestedA := dbfx.Comment(t, issueID, "A nested supplement", testutil.Cols{"parent_id": replyA})
+ t.Cleanup(func() { dbfx.Exec(t, "DELETE FROM agent_task_queue WHERE issue_id = $1", issueID) })
+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ agent, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ enqueue := func(commentID string, pending bool, want DispatchStatus) {
+ t.Helper()
+ result := testHandler.enqueueCommentAgentTriggers(ctx, issue, parseUUID(commentID),
+ []commentAgentTrigger{{Agent: agent, Source: commentTriggerSourceMentionAgent, AlreadyPending: pending}})
+ if result[agentID].status != want {
+ t.Fatalf("enqueue %s: got %+v, want %s", commentID, result[agentID], want)
+ }
+ }
+ enqueue(rootA, false, DispatchQueued)
+ // Even a stale pending hint from another thread must not merge or defer B.
+ enqueue(rootB, true, DispatchQueued)
+ enqueue(replyA, true, DispatchCoalesced)
+ enqueue(nestedA, true, DispatchCoalesced)
+ tasks, err := testHandler.Queries.ListTasksByIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(tasks) != 2 {
+ t.Fatalf("got %d runs, want one per thread", len(tasks))
+ }
+ var a, b db.AgentTaskQueue
+ for _, task := range tasks {
+ switch uuidToString(task.CommentThreadID) {
+ case rootA:
+ a = task
+ case rootB:
+ b = task
+ default:
+ t.Fatalf("wrong thread scope: %s", uuidToString(task.CommentThreadID))
+ }
+ }
+ if uuidToString(a.TriggerCommentID) != nestedA || len(a.CoalescedCommentIds) != 2 || len(b.CoalescedCommentIds) != 0 {
+ t.Fatalf("wrong input batches: A=%+v B=%+v", a.TriggerCommentID, b.CoalescedCommentIds)
+ }
+ claim := db.ClaimAgentTaskParams{AgentID: parseUUID(agentID), RuntimeID: parseUUID(runtimeID), PrepareLeaseSecs: 60, RuntimeStaleSecs: 120}
+ claimed, err := testHandler.Queries.ClaimAgentTask(ctx, claim)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if claimed.ID != a.ID {
+ t.Fatal("oldest thread should execute first")
+ }
+ if _, err := testHandler.Queries.ClaimAgentTask(ctx, claim); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("another thread ran concurrently on the same issue: %v", err)
+ }
+ // A new instruction after execution starts belongs to a successor run.
+ dbfx.Exec(t, "UPDATE agent_task_queue SET status='running', started_at=now(), delivered_comment_ids=ARRAY[$2::uuid,$3::uuid,$4::uuid] WHERE id=$1", uuidToString(a.ID), rootA, replyA, nestedA)
+ followupA := dbfx.Comment(t, issueID, "A follow-up", testutil.Cols{"parent_id": rootA})
+ enqueue(followupA, false, DispatchQueued)
+ dbfx.Exec(t, "UPDATE agent_task_queue SET status='completed', completed_at=now() WHERE id=$1", uuidToString(a.ID))
+ completed, err := testHandler.Queries.GetAgentTask(ctx, a.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ testHandler.reconcileCommentsOnCompletion(ctx, &completed)
+ tasks, err = testHandler.Queries.ListTasksByIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(tasks) != 3 {
+ t.Fatalf("completion duplicated another thread: got %d tasks", len(tasks))
+ }
+ // A row-specific rerun replaces only A's pending successor.
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, issue.ID, a.ID, pgtype.UUID{}, parseUUID(testUserID), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ other, err := testHandler.Queries.GetAgentTask(ctx, b.ID)
+ if err != nil || other.Status != "queued" {
+ t.Fatalf("rerun disturbed thread B: %s / %v", other.Status, err)
+ }
+ if rerun.CommentThreadID != a.CommentThreadID {
+ t.Fatal("rerun lost thread scope")
+ }
+ if _, err := testHandler.TaskService.CancelTask(ctx, rerun.ID); err != nil {
+ t.Fatal(err)
+ }
+ other, err = testHandler.Queries.GetAgentTask(ctx, b.ID)
+ if err != nil || other.Status != "queued" {
+ t.Fatalf("stop disturbed thread B: %s / %v", other.Status, err)
+ }
+}
+
+func TestDeferredCommentThreadsPromoteIndependently(t *testing.T) {
+ ctx := context.Background()
+ runtimeID := dbfx.Runtime(t, "thread promotion runtime")
+ agentID := dbfx.Agent(t, "thread promotion agent", runtimeID)
+ issueID := dbfx.Issue(t, "thread promotion issue")
+ rootA := dbfx.Comment(t, issueID, "A")
+ rootB := dbfx.Comment(t, issueID, "B")
+ create := func(root string) string {
+ return dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": issueID, "trigger_comment_id": root, "status": "deferred", "fire_at": testutil.Raw("now()-interval '1 minute'")})
+ }
+ a, b := create(rootA), create(rootB)
+ anotherA := create(rootA)
+ promoted, err := testHandler.Queries.PromoteDueDeferredTasksForRuntime(ctx, db.PromoteDueDeferredTasksForRuntimeParams{RuntimeID: parseUUID(runtimeID), RuntimeStaleSecs: 120})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(promoted) != 2 {
+ t.Fatalf("promoted %d runs, want one per thread", len(promoted))
+ }
+ for _, id := range []string{a, b} {
+ row, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(id))
+ if err != nil || row.Status != "queued" {
+ t.Fatalf("thread did not promote: %s / %v", row.Status, err)
+ }
+ }
+ row, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(anotherA))
+ if err != nil || row.Status != "deferred" {
+ t.Fatalf("second run in A must stay deferred: %s / %v", row.Status, err)
+ }
+}
diff --git a/server/internal/handler/comment_trigger_preview_test.go b/server/internal/handler/comment_trigger_preview_test.go
index b007088873..b1c9bfb941 100644
--- a/server/internal/handler/comment_trigger_preview_test.go
+++ b/server/internal/handler/comment_trigger_preview_test.go
@@ -466,7 +466,7 @@ func TestPreviewCommentTriggers_ExplicitMentionSuppressesAssigneeFallback(t *tes
}
}
-func TestCreateComment_ExplicitMentionKeepsPendingRouteWithoutDuplicateTask(t *testing.T) {
+func TestCreateComment_ExplicitMentionQueuesDifferentThreadsIndependently(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
@@ -487,8 +487,8 @@ func TestCreateComment_ExplicitMentionKeepsPendingRouteWithoutDuplicateTask(t *t
}
postCommentForTriggerPreviewTest(t, issueID, map[string]any{"content": content + " again"})
- if got := countQueuedCommentTriggerTasks(t, issueID, mentionedID); got != 1 {
- t.Fatalf("duplicate pending mention queued tasks = %d, want 1", got)
+ if got := countQueuedCommentTriggerTasks(t, issueID, mentionedID); got != 2 {
+ t.Fatalf("separate thread queued tasks = %d, want 2", got)
}
}
@@ -1277,7 +1277,7 @@ func TestPreviewCommentTriggers_MalformedMentionIDDoesNotPanic(t *testing.T) {
}
}
-func TestPreviewCommentTriggers_AllSuppressesAssigneeAndPendingDedupes(t *testing.T) {
+func TestPreviewCommentTriggers_AllSuppressesAssigneeAndNewThreadQueuesSeparately(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
@@ -1311,8 +1311,8 @@ func TestPreviewCommentTriggers_AllSuppressesAssigneeAndPendingDedupes(t *testin
postCommentForTriggerPreviewTest(t, issueID, map[string]any{
"content": "can you continue here?",
})
- if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 1 {
- t.Fatalf("pending assignee create queued tasks = %d, want 1", got)
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 2 {
+ t.Fatalf("assignment and new comment thread queued tasks = %d, want 2", got)
}
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 541dc430dc..c7004e81be 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2602,7 +2602,9 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
resp.TriggerCommentContent = comment.Content
resp.TriggerThreadID = uuidToString(comment.ID)
if comment.ParentID.Valid {
- resp.TriggerThreadID = uuidToString(comment.ParentID)
+ if root, err := h.Queries.GetCommentThreadRootID(r.Context(), comment.ID); err == nil {
+ resp.TriggerThreadID = uuidToString(root)
+ }
}
resp.TriggerAuthorType = comment.AuthorType
// The triggering comment's author is the task initiator — the
@@ -4091,6 +4093,7 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
plannedCommentIDs = append(plannedCommentIDs, task.TriggerCommentID)
}
comments, err := h.Queries.ListReconcilableCommentsForIssueSince(ctx, db.ListReconcilableCommentsForIssueSinceParams{
+ CommentThreadID: task.CommentThreadID,
IssueID: task.IssueID,
Since: task.CreatedAt,
PlannedCommentIds: plannedCommentIDs,
@@ -4298,7 +4301,11 @@ func (h *Handler) buildCoalescedCommentData(ctx context.Context, workspaceID pgt
CreatedAt: timestampToString(comment.CreatedAt),
}
if comment.ParentID.Valid {
- data.ThreadID = uuidToString(comment.ParentID)
+ root, err := h.Queries.GetCommentThreadRootID(ctx, comment.ID)
+ if err != nil {
+ continue
+ }
+ data.ThreadID = uuidToString(root)
}
if comment.AuthorID.Valid {
switch comment.AuthorType {
diff --git a/server/internal/handler/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
index c2e537a2ba..e351a6fcd2 100644
--- a/server/internal/handler/daemon_comment_delivery_test.go
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -15,6 +15,7 @@ import (
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/testutil"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -233,6 +234,16 @@ func createCommentDeliveryFixture(t *testing.T, label string) commentDeliveryFix
}
}
+func makeCommentDeliverySingleThread(t *testing.T, fixture commentDeliveryFixture) {
+ t.Helper()
+ root := dbfx.Comment(t, fixture.issueID, "thread root", testutil.Cols{"author_type": "agent", "author_id": fixture.agentID})
+ dbfx.Exec(t, `UPDATE comment SET created_at=now()-interval '10 minutes' WHERE id=$1`, root)
+ for _, id := range fixture.commentID {
+ dbfx.Exec(t, `UPDATE comment SET parent_id=$2 WHERE id=$1`, id, root)
+ }
+ dbfx.Exec(t, `UPDATE agent_task_queue SET trigger_comment_id=trigger_comment_id WHERE id=$1`, fixture.taskID)
+}
+
func claimCommentDeliveryFixture(t *testing.T, fixture commentDeliveryFixture, capabilities string) AgentTaskResponse {
t.Helper()
w := httptest.NewRecorder()
@@ -353,6 +364,7 @@ func TestClaimTaskByRuntime_CoalescedOnlyStaleTaskDoesNotReuseDeletedTriggerCapa
t.Skip("database not available")
}
fixture := createCommentDeliveryFixture(t, "Deleted trigger stale claim")
+ makeCommentDeliverySingleThread(t, fixture)
if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
t.Fatalf("assign stale-claim issue: %v", err)
}
@@ -386,6 +398,7 @@ func TestUpdateComment_RequeuesSurvivingCoalescedBatch(t *testing.T) {
t.Skip("database not available")
}
fixture := createCommentDeliveryFixture(t, "Edited trigger batch repair")
+ makeCommentDeliverySingleThread(t, fixture)
if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
t.Fatalf("assign edited-trigger issue: %v", err)
}
@@ -408,6 +421,7 @@ func TestDeleteComment_RequeuesSurvivingCoalescedBatch(t *testing.T) {
t.Skip("database not available")
}
fixture := createCommentDeliveryFixture(t, "Deleted trigger batch repair")
+ makeCommentDeliverySingleThread(t, fixture)
if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
t.Fatalf("assign deleted-trigger issue: %v", err)
}
@@ -435,6 +449,7 @@ func TestUpdateComment_CancelsAndRequeuesWhenEditedInputIsCoalesced(t *testing.T
t.Skip("database not available")
}
fixture := createCommentDeliveryFixture(t, "Edited coalesced input repair")
+ makeCommentDeliverySingleThread(t, fixture)
if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
t.Fatalf("assign edited-coalesced issue: %v", err)
}
@@ -450,6 +465,13 @@ func TestUpdateComment_CancelsAndRequeuesWhenEditedInputIsCoalesced(t *testing.T
}
assertRepairedCommentBatch(t, fixture, fixture.commentID[0], fixture.commentID[1:])
+ original, err := testHandler.Queries.GetAgentTask(context.Background(), parseUUID(fixture.taskID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !taskToResponse(original, testWorkspaceID).CancelledByCommentChange {
+ t.Fatal("edited input must identify the cancelled run as invalidated by a comment change")
+ }
}
func TestDeleteComment_CancelsAndRequeuesWhenDeletedInputIsCoalesced(t *testing.T) {
@@ -457,6 +479,7 @@ func TestDeleteComment_CancelsAndRequeuesWhenDeletedInputIsCoalesced(t *testing.
t.Skip("database not available")
}
fixture := createCommentDeliveryFixture(t, "Deleted coalesced input repair")
+ makeCommentDeliverySingleThread(t, fixture)
if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
t.Fatalf("assign deleted-coalesced issue: %v", err)
}
@@ -477,6 +500,7 @@ func TestDeleteComment_FailureRestoresCancelledCompleteBatch(t *testing.T) {
t.Skip("database not available")
}
fixture := createCommentDeliveryFixture(t, "Failed deletion batch repair")
+ makeCommentDeliverySingleThread(t, fixture)
if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
t.Fatalf("assign failed-delete issue: %v", err)
}
@@ -506,6 +530,7 @@ func TestDeleteComment_ConcurrentNoOpIsReportedAndRestoresCancelledBatch(t *test
t.Skip("database not available")
}
fixture := createCommentDeliveryFixture(t, "Concurrent deletion batch repair")
+ makeCommentDeliverySingleThread(t, fixture)
if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
t.Fatalf("assign concurrent-delete issue: %v", err)
}
@@ -587,6 +612,7 @@ func TestClaimTaskByRuntime_PayloadOverflowReceiptsOnlyEmbeddedPrefix(t *testing
t.Skip("database not available")
}
fixture := createCommentDeliveryFixture(t, "Comment payload overflow")
+ makeCommentDeliverySingleThread(t, fixture)
oversized := strings.Repeat("x", maxClaimCommentPayloadBytes+1024)
if _, err := testPool.Exec(context.Background(), `UPDATE comment SET content = $2 WHERE id = $1`, fixture.commentID[0], oversized); err != nil {
t.Fatalf("make first coalesced comment oversized: %v", err)
diff --git a/server/internal/handler/delegated_failure_recovery_test.go b/server/internal/handler/delegated_failure_recovery_test.go
index 516d372a81..0cc555b4a1 100644
--- a/server/internal/handler/delegated_failure_recovery_test.go
+++ b/server/internal/handler/delegated_failure_recovery_test.go
@@ -118,7 +118,8 @@ func TestUpdateComment_RequeuesDelegatedFailureRecoverySurvivor(t *testing.T) {
Scan(&activeTasks, &recoveryCovered); err != nil {
t.Fatalf("read rebuilt coordinator task: %v", err)
}
- if activeTasks != 1 || !recoveryCovered {
- t.Fatalf("rebuilt active tasks/recovery coverage = %d/%v, want 1/true", activeTasks, recoveryCovered)
+ // Rebuilding an old cross-thread batch preserves both independent runs.
+ if activeTasks != 2 || !recoveryCovered {
+ t.Fatalf("rebuilt active tasks/recovery coverage = %d/%v, want 2/true", activeTasks, recoveryCovered)
}
}
diff --git a/server/internal/handler/issue_revision_test.go b/server/internal/handler/issue_revision_test.go
index fa96a820d0..7dfe9876ac 100644
--- a/server/internal/handler/issue_revision_test.go
+++ b/server/internal/handler/issue_revision_test.go
@@ -436,6 +436,7 @@ func TestConcurrentCommentRevisionConflictCancelsTaskBatchOnce(t *testing.T) {
}
ctx := context.Background()
fixture := createCommentDeliveryFixture(t, "revision task side effects")
+ makeCommentDeliverySingleThread(t, fixture)
if _, err := testPool.Exec(ctx, `
UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1
`, fixture.issueID, fixture.agentID); err != nil {
diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.go
index b48d8c13be..8ac03ad612 100644
--- a/server/internal/handler/issue_trigger.go
+++ b/server/internal/handler/issue_trigger.go
@@ -72,7 +72,7 @@ func (h *Handler) shouldSuppressActiveSelfAssignment(ctx context.Context, actorT
if actorType != "agent" || actorID == "" || actorID != uuidToString(targetAgentID) {
return false
}
- active, err := h.hasActiveTaskForIssueAndAgent(ctx, issueID, targetAgentID)
+ active, err := h.Queries.HasActiveTaskForIssueAndAgent(ctx, db.HasActiveTaskForIssueAndAgentParams{IssueID: issueID, AgentID: targetAgentID})
return active || err != nil
}
diff --git a/server/internal/handler/mention_self_trigger_test.go b/server/internal/handler/mention_self_trigger_test.go
index 93c475f91c..47bb8ccd93 100644
--- a/server/internal/handler/mention_self_trigger_test.go
+++ b/server/internal/handler/mention_self_trigger_test.go
@@ -230,9 +230,9 @@ func TestEnqueueMentionedAgentTasks_SelfMentionDedupesAgainstPendingTask(t *test
t.Fatalf("reset tasks: %v", err)
}
if _, err := testPool.Exec(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status)
- VALUES ($1, $2, $3, $4)
- `, fx.JID, fx.RuntimeID, fx.IssueAID, tc.status); err != nil {
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, trigger_comment_id)
+ VALUES ($1, $2, $3, $4, $5)
+ `, fx.JID, fx.RuntimeID, fx.IssueAID, tc.status, fx.CommentA.ID); err != nil {
t.Fatalf("seed %s task: %v", tc.status, err)
}
diff --git a/server/internal/handler/squad_worker_comment_wakes_leader_test.go b/server/internal/handler/squad_worker_comment_wakes_leader_test.go
index 07531f098a..eb61765c7b 100644
--- a/server/internal/handler/squad_worker_comment_wakes_leader_test.go
+++ b/server/internal/handler/squad_worker_comment_wakes_leader_test.go
@@ -99,14 +99,14 @@ func TestCreateComment_WorkerAgentCommentWakesSquadLeader_MUL4015(t *testing.T)
}
}
-// TestCreateComment_WorkerAgentCommentDoesNotWakeLeader_WhenLeaderTaskPending
+// TestCreateComment_WorkerAgentCommentQueuesSeparatelyFromLeaderAssignment
// pins the dedup behavior: when the squad leader ALREADY has a queued or
// dispatched task on the issue, a worker's completion comment does not double-
// enqueue a second leader task. This is the desired "coalescing" behavior in
// production — the leader is going to run once and will observe the worker's
// comment in that run. Regression coverage so nobody drops the dedup and
// starts stacking duplicate leader runs.
-func TestCreateComment_WorkerAgentCommentDoesNotWakeLeader_WhenLeaderTaskPending(t *testing.T) {
+func TestCreateComment_WorkerAgentCommentQueuesSeparatelyFromLeaderAssignment(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
@@ -159,8 +159,7 @@ func TestCreateComment_WorkerAgentCommentDoesNotWakeLeader_WhenLeaderTaskPending
t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
}
- // Expected: still exactly 1 queued leader task (the pre-seeded one) —
- // no double enqueue.
+ // The new comment thread queues independently of the assignment run.
var leaderTasks int
if err := testPool.QueryRow(ctx, `
SELECT count(*) FROM agent_task_queue
@@ -168,8 +167,8 @@ func TestCreateComment_WorkerAgentCommentDoesNotWakeLeader_WhenLeaderTaskPending
`, issueID, fx.LeaderID).Scan(&leaderTasks); err != nil {
t.Fatalf("count leader tasks: %v", err)
}
- if leaderTasks != 1 {
- t.Fatalf("expected 1 queued leader task (dedup), got %d", leaderTasks)
+ if leaderTasks != 2 {
+ t.Fatalf("expected separate assignment and comment tasks, got %d", leaderTasks)
}
}
diff --git a/server/internal/service/attribution_stamp_test.go b/server/internal/service/attribution_stamp_test.go
index 2a456071b4..d40c2a9643 100644
--- a/server/internal/service/attribution_stamp_test.go
+++ b/server/internal/service/attribution_stamp_test.go
@@ -217,6 +217,10 @@ func TestMergeCommentIntoPendingTask_KeepsAccountableEqualsOriginator(t *testing
t.Fatalf("seed comment: %v", err)
}
+ // Bind this task's input to the thread whose attribution is being refreshed.
+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET trigger_comment_id=$2 WHERE id=$1`, taskID, commentID); err != nil {
+ t.Fatal(err)
+ }
// Re-stamp the FULL snapshot for B's member comment (direct_human + comment
// evidence), as the caller does.
if _, err := q.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
diff --git a/server/internal/service/builtin_skills/multica-platform/references/mentions.md b/server/internal/service/builtin_skills/multica-platform/references/mentions.md
index ca15af2362..e22b006551 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/mentions.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/mentions.md
@@ -117,9 +117,9 @@ None of these start a fresh run, and none produce an error response — but they
are three different things, and the response tells you which. A mention that
never parsed is a truly silent no-op. One that parsed and was refused comes back
in `trigger_outcomes` as `status: "blocked"` with a `reason_code`. One whose
-target is already busy comes back `coalesced` or `deferred`: no second run, but
-your comment IS folded into the task that is already running, so it still gets
-read. Read that array after posting — it is the only place any of this shows up.
+target has a queued task in the same comment thread can come back `coalesced`.
+A claim race can return `deferred`: the input is recorded for a follow-up run,
+not injected into an already running prompt. Different threads queue independently. Read that array after posting — it is the only place any of this shows up.
- **A name where a UUID belongs.** `mention://member/Alice` is dead. The id
group accepts only hex+dashes or `all`; the non-hex letters in a typical name
@@ -138,10 +138,15 @@ read. Read that array after posting — it is the only place any of this shows u
with `target_unavailable` instead — a non-UUID names no entity anywhere, so
it conceals nothing. Neither case is ever an error response.
- **An already-pending task.** Even a correct `@agent`/`@squad` starts no second
- run when the target already has a pending task on this issue. This is a fold,
- not a drop: the comment merges into that task and the outcome is `coalesced`
- (same reviewed head) or `deferred` (different head) — do NOT re-post it as
- "the mention didn't work". Edit preview is the only exception:
+ run when the same target has a mergeable queued task in the **same thread**
+ (the root comment and all descendants), with the same reviewed head. The
+ outcome is `coalesced`; all covered instructions are delivered together.
+ Different root threads and assignment-triggered runs have separate queue
+ slots. Inputs received after execution starts belong to a successor run;
+ `deferred` means a claim race durably recorded the follow-up obligation.
+ Agent concurrency limits still apply, and runs for the same issue and agent
+ execute serially. Stopping or retrying one thread does not cancel another
+ thread's queue. Do not re-post a successfully queued/coalesced/deferred input. Edit preview is the only exception:
`editing_comment_id` ignores pending tasks from the same comment being edited,
because save cancels those old tasks before it re-computes triggers. It is
still comment-scoped, not an agent-wide bypass.
@@ -187,6 +192,12 @@ result comment on the autopilot issue can still wake the leader), and it survive
a busy target: if the mentioned agent is already running, the delegation is
replayed at that run's completion under the same authority, so it is never lost.
+Editing or deleting input cancels active runs that contain that comment and
+re-evaluates surviving inputs. These cancelled runs expose
+`cancelled_by_comment_change: true` in task responses. Unstarted runs without
+replies remain in execution history but do not create cancelled comment blocks;
+manual cancellations and runs that already executed remain visible.
+
An edit is treated as a fresh action — it re-derives the comment's lineage from
the editing action. Only the agent author editing its OWN comment re-stamps the
lineage to the editing task; any other editor — including a workspace owner/admin
diff --git a/server/internal/service/delegated_failure_recovery_settled_test.go b/server/internal/service/delegated_failure_recovery_settled_test.go
index 7a6dea0564..fc43d0485e 100644
--- a/server/internal/service/delegated_failure_recovery_settled_test.go
+++ b/server/internal/service/delegated_failure_recovery_settled_test.go
@@ -227,7 +227,7 @@ func TestManualRerunSettlesDeliveredRecovery(t *testing.T) {
if err != nil {
t.Fatalf("parse actor id: %v", err)
}
- if _, err := svc.RerunIssue(ctx, issueID, pgtype.UUID{}, pgtype.UUID{}, actorID, func(db.Agent) bool { return true }); err != nil {
+ if _, err := svc.RerunIssue(ctx, issueID, recoveryTaskID, pgtype.UUID{}, actorID, func(db.Agent) bool { return true }); err != nil {
t.Fatalf("RerunIssue: %v", err)
}
diff --git a/server/internal/service/delegated_failure_recovery_test.go b/server/internal/service/delegated_failure_recovery_test.go
index 9642f839b1..ee20443565 100644
--- a/server/internal/service/delegated_failure_recovery_test.go
+++ b/server/internal/service/delegated_failure_recovery_test.go
@@ -680,10 +680,10 @@ func TestFinalDelegatedFailureMergesIntoPendingCoordinatorTask(t *testing.T) {
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority,
originator_user_id, accountable_user_id, originator_source,
- trigger_evidence_kind, trigger_evidence_ref_id
+ trigger_evidence_kind, trigger_evidence_ref_id, trigger_comment_id
)
- VALUES ($1, $2, $3, 'queued', 0, $4, $4, 'direct_human', 'issue_assignment', $3)
- RETURNING id`, f.coordinator, f.runtimeID, f.issueID, f.userID).Scan(&pendingID); err != nil {
+ VALUES ($1, $2, $3, 'queued', 0, $4, $4, 'direct_human', 'issue_assignment', $3, $5)
+ RETURNING id`, f.coordinator, f.runtimeID, f.issueID, f.userID, f.sourceTrigger).Scan(&pendingID); err != nil {
t.Fatalf("seed pending coordinator task: %v", err)
}
@@ -741,10 +741,10 @@ func TestDelegatedFailurePlannedBehindDispatchedCoordinatorGetsFollowUp(t *testi
if err := f.pool.QueryRow(ctx, `
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, dispatched_at,
- originator_user_id, accountable_user_id, originator_source
+ originator_user_id, accountable_user_id, originator_source, trigger_comment_id
)
- VALUES ($1, $2, $3, 'dispatched', 0, now(), $4, $4, 'direct_human')
- RETURNING id`, f.coordinator, f.runtimeID, f.issueID, f.userID).Scan(&activeID); err != nil {
+ VALUES ($1, $2, $3, 'dispatched', 0, now(), $4, $4, 'direct_human', $5)
+ RETURNING id`, f.coordinator, f.runtimeID, f.issueID, f.userID, f.sourceTrigger).Scan(&activeID); err != nil {
t.Fatalf("seed active coordinator task: %v", err)
}
diff --git a/server/internal/service/issue_channel_media_test.go b/server/internal/service/issue_channel_media_test.go
index 62da445e04..69b7346fed 100644
--- a/server/internal/service/issue_channel_media_test.go
+++ b/server/internal/service/issue_channel_media_test.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"reflect"
"testing"
@@ -226,8 +227,8 @@ func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(t
NewOriginatorSource: pgtype.Text{String: "direct_human", Valid: true},
NewTriggerEvidenceKind: pgtype.Text{String: "comment", Valid: true},
NewTriggerEvidenceRefID: mergedCommentID,
- }); err != nil {
- callbackErr = fmt.Errorf("merge immediate comment into deferred task: %w", err)
+ }); !errors.Is(err, pgx.ErrNoRows) {
+ callbackErr = fmt.Errorf("new comment thread must not merge into the assignment: %v", err)
}
})
@@ -272,8 +273,8 @@ func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(t
Scan(&taskID, &triggerCommentID, &runtimeID, &taskCount); err != nil {
t.Fatalf("load final pending task: %v", err)
}
- if taskCount != 1 || taskID != result.AssignedTaskID || triggerCommentID != mergedCommentID {
- t.Fatalf("pending task = count %d id %v trigger %v, want one task %v with trigger %v", taskCount, taskID, triggerCommentID, result.AssignedTaskID, mergedCommentID)
+ if taskCount != 1 || taskID != result.AssignedTaskID || triggerCommentID.Valid {
+ t.Fatalf("pending task = count %d id %v trigger %v, want one assignment task %v without a comment trigger", taskCount, taskID, triggerCommentID, result.AssignedTaskID)
}
if wakeup.calls[0].runtimeID != util.UUIDToString(runtimeID) {
t.Fatalf("schedule wakeup runtime = %q, want %q", wakeup.calls[0].runtimeID, util.UUIDToString(runtimeID))
@@ -308,6 +309,9 @@ func TestHydrateDeferredChannelIssueTaskOverlayDoesNotOverwriteMergedCommentPlan
RETURNING id`, task.IssueID, workspaceID, userID).Scan(&commentID); err != nil {
t.Fatalf("seed merged comment: %v", err)
}
+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET trigger_comment_id=$2 WHERE id=$1`, task.ID, commentID); err != nil {
+ t.Fatal(err)
+ }
mergedOverlay := json.RawMessage(`{"mcpServers":{"merged":{"url":"https://merged.example"}}}`)
if _, err := q.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
IssueID: task.IssueID,
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index a11ebf8781..f37bd4c63f 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -716,7 +716,7 @@ func isDuplicatePendingTaskErr(err error) bool {
return false
}
switch pgErr.ConstraintName {
- case "idx_one_pending_task_per_issue_agent", "idx_one_pending_task_per_issue_agent_v2":
+ case "idx_one_pending_task_per_issue_agent", "idx_one_pending_task_per_issue_agent_v2", "idx_one_pending_task_per_issue_agent_thread":
return true
default:
return false
@@ -5295,9 +5295,10 @@ func hasRunnableSuccessor(ctx context.Context, q *db.Queries, task db.AgentTaskQ
if !task.IssueID.Valid {
return false, nil
}
- return q.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{
- IssueID: task.IssueID,
- AgentID: task.AgentID,
+ return q.HasPendingTaskForIssueAndAgentInThread(ctx, db.HasPendingTaskForIssueAndAgentInThreadParams{
+ ThreadCommentID: task.TriggerCommentID,
+ IssueID: task.IssueID,
+ AgentID: task.AgentID,
})
}
@@ -5621,9 +5622,10 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
// that failed after this committed.
cerr := s.runInTx(ctx, func(qtx *db.Queries) error {
var err error
- cancelled, err = qtx.CancelPendingTasksByIssueAndAgent(ctx, db.CancelPendingTasksByIssueAndAgentParams{
- IssueID: issueID,
- AgentID: agentID,
+ cancelled, err = qtx.CancelPendingTasksByIssueAndAgentInThread(ctx, db.CancelPendingTasksByIssueAndAgentInThreadParams{
+ ThreadCommentID: triggerCommentID,
+ IssueID: issueID,
+ AgentID: agentID,
})
if err != nil {
return err
diff --git a/server/internal/service/task_channel_media_race_test.go b/server/internal/service/task_channel_media_race_test.go
index 234fd169d0..60c1138fe2 100644
--- a/server/internal/service/task_channel_media_race_test.go
+++ b/server/internal/service/task_channel_media_race_test.go
@@ -535,6 +535,9 @@ func TestDeferredChannelIssueTaskPromotesAfterMediaSettlement(t *testing.T) {
VALUES ($1, $2, 'member', $3, 'More context') RETURNING id`, issueID, workspaceID, userID).Scan(&commentID); err != nil {
t.Fatalf("seed comment: %v", err)
}
+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET trigger_comment_id=$2 WHERE id=$1`, task.ID, commentID); err != nil {
+ t.Fatal(err)
+ }
merged, err := q.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
IssueID: issueID,
AgentID: util.MustParseUUID(agentID),
@@ -579,7 +582,7 @@ func TestDeferredChannelIssueTaskConflictsWithQueuedSiblingAtDatabase(t *testing
ctx := context.Background()
var indexDefinition string
- if err := pool.QueryRow(ctx, `SELECT pg_get_indexdef('idx_one_pending_task_per_issue_agent_v2'::regclass)`).Scan(&indexDefinition); err != nil {
+ if err := pool.QueryRow(ctx, `SELECT pg_get_indexdef('idx_one_pending_task_per_issue_agent_thread'::regclass)`).Scan(&indexDefinition); err != nil {
t.Fatalf("load pending-task index: %v", err)
}
if !strings.Contains(indexDefinition, "channel_issue_media_pending") {
@@ -614,7 +617,7 @@ func TestDeferredChannelIssueTaskConflictsWithQueuedSiblingAtDatabase(t *testing
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)
VALUES ($1, $2, $3, 'queued', 0)`, task.AgentID, task.RuntimeID, issueID)
var pgErr *pgconn.PgError
- if !errors.As(err, &pgErr) || pgErr.Code != "23505" || pgErr.ConstraintName != "idx_one_pending_task_per_issue_agent_v2" {
+ if !errors.As(err, &pgErr) || pgErr.Code != "23505" || pgErr.ConstraintName != "idx_one_pending_task_per_issue_agent_thread" {
t.Fatalf("queued sibling insert error = %v, want unique violation on pending-task index", err)
}
}
diff --git a/server/migrations/451_agent_task_comment_thread.down.sql b/server/migrations/451_agent_task_comment_thread.down.sql
new file mode 100644
index 0000000000..5ff54b8163
--- /dev/null
+++ b/server/migrations/451_agent_task_comment_thread.down.sql
@@ -0,0 +1,4 @@
+DROP TRIGGER agent_task_comment_thread ON agent_task_queue;
+DROP FUNCTION set_agent_task_comment_thread();
+ALTER TABLE agent_task_queue DROP COLUMN comment_thread_id;
+DROP FUNCTION comment_thread_root_id(uuid);
diff --git a/server/migrations/451_agent_task_comment_thread.up.sql b/server/migrations/451_agent_task_comment_thread.up.sql
new file mode 100644
index 0000000000..dcac33165a
--- /dev/null
+++ b/server/migrations/451_agent_task_comment_thread.up.sql
@@ -0,0 +1,35 @@
+-- Persist the queue's thread scope so uniqueness remains atomic for every
+-- writer, including retries and older clients. This is derived data, not a FK.
+ALTER TABLE agent_task_queue ADD COLUMN comment_thread_id uuid;
+
+CREATE FUNCTION comment_thread_root_id(comment_id uuid) RETURNS uuid
+LANGUAGE sql STABLE STRICT AS $$
+ WITH RECURSIVE ancestors AS (
+ SELECT c.id, c.parent_id, c.issue_id, ARRAY[c.id] AS path
+ FROM comment c WHERE c.id = comment_id
+ UNION ALL
+ SELECT p.id, p.parent_id, p.issue_id, a.path || p.id
+ FROM ancestors a JOIN comment p ON p.id = a.parent_id AND p.issue_id = a.issue_id
+ WHERE NOT p.id = ANY(a.path)
+ )
+ SELECT COALESCE(
+ (SELECT id FROM ancestors ORDER BY cardinality(path) DESC LIMIT 1),
+ comment_id
+ )
+$$;
+
+CREATE FUNCTION set_agent_task_comment_thread() RETURNS trigger
+LANGUAGE plpgsql AS $$
+BEGIN
+ NEW.comment_thread_id := comment_thread_root_id(NEW.trigger_comment_id);
+ RETURN NEW;
+END
+$$;
+
+CREATE TRIGGER agent_task_comment_thread
+BEFORE INSERT OR UPDATE OF trigger_comment_id ON agent_task_queue
+FOR EACH ROW EXECUTE FUNCTION set_agent_task_comment_thread();
+
+UPDATE agent_task_queue
+SET comment_thread_id = comment_thread_root_id(trigger_comment_id)
+WHERE trigger_comment_id IS NOT NULL;
diff --git a/server/migrations/452_agent_task_pending_thread_unique.down.sql b/server/migrations/452_agent_task_pending_thread_unique.down.sql
new file mode 100644
index 0000000000..f7b783e1f9
--- /dev/null
+++ b/server/migrations/452_agent_task_pending_thread_unique.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_one_pending_task_per_issue_agent_thread;
diff --git a/server/migrations/452_agent_task_pending_thread_unique.up.sql b/server/migrations/452_agent_task_pending_thread_unique.up.sql
new file mode 100644
index 0000000000..a8111c9b8a
--- /dev/null
+++ b/server/migrations/452_agent_task_pending_thread_unique.up.sql
@@ -0,0 +1,5 @@
+-- Build the new guard before retiring the issue-wide guard.
+CREATE UNIQUE INDEX CONCURRENTLY idx_one_pending_task_per_issue_agent_thread
+ ON agent_task_queue (issue_id, agent_id, COALESCE(comment_thread_id, '00000000-0000-0000-0000-000000000000'::uuid))
+ WHERE status IN ('queued', 'dispatched')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true');
diff --git a/server/migrations/453_drop_pending_issue_agent_unique.down.sql b/server/migrations/453_drop_pending_issue_agent_unique.down.sql
new file mode 100644
index 0000000000..17f07ada50
--- /dev/null
+++ b/server/migrations/453_drop_pending_issue_agent_unique.down.sql
@@ -0,0 +1,6 @@
+-- Drain per-thread pending queues before downgrading; never discard requests
+-- merely to recreate the older, narrower uniqueness constraint.
+CREATE UNIQUE INDEX CONCURRENTLY idx_one_pending_task_per_issue_agent_v2
+ ON agent_task_queue (issue_id, agent_id)
+ WHERE status IN ('queued', 'dispatched')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true');
diff --git a/server/migrations/453_drop_pending_issue_agent_unique.up.sql b/server/migrations/453_drop_pending_issue_agent_unique.up.sql
new file mode 100644
index 0000000000..50b2c8ce1e
--- /dev/null
+++ b/server/migrations/453_drop_pending_issue_agent_unique.up.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_one_pending_task_per_issue_agent_v2;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 9b5aedb0a8..b2ff477a13 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -32,7 +32,7 @@ WHERE acknowledged.id = (
WHERE attempt_count.trigger_evidence_kind = 'delegated_failure'
AND attempt_count.trigger_evidence_ref_id = $2
) >= $3::int
-RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir, acknowledged.channel_context_revision
+RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir, acknowledged.channel_context_revision, acknowledged.comment_thread_id
`
type AcknowledgeExhaustedDelegatedFailureRecoveryParams struct {
@@ -103,6 +103,7 @@ func (q *Queries) AcknowledgeExhaustedDelegatedFailureRecovery(ctx context.Conte
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -303,7 +304,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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
+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
`
// Automatic cancellation without an explicit persisted failure reason. Unlike
@@ -366,6 +367,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -424,7 +426,7 @@ SET status = 'cancelled',
END
WHERE task.id = $1
AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id
`
// An explicit user cancellation is a terminal acknowledgement for any
@@ -489,6 +491,7 @@ func (q *Queries) CancelAgentTaskByUser(ctx context.Context, id pgtype.UUID) (Ag
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -501,7 +504,7 @@ SET status = 'cancelled',
failure_reason = $2,
prepare_lease_expires_at = NULL
WHERE id = $3 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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
+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
`
type CancelAgentTaskWithReasonParams struct {
@@ -575,6 +578,7 @@ func (q *Queries) CancelAgentTaskWithReason(ctx context.Context, arg CancelAgent
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -583,7 +587,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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
+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
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -655,6 +659,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -670,7 +675,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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
+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
`
// Cancels active tasks belonging to a chat session. Called from
@@ -742,6 +747,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -757,7 +763,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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
+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
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -829,6 +835,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -842,10 +849,11 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerComment :many
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
+ context = COALESCE(context, '{}'::jsonb) || jsonb_build_object('comment_change_cancelled_task_id', id::text)
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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
+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
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -916,6 +924,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -936,9 +945,9 @@ WITH cancelled AS (
AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
AND primary_task.issue_id = $1
AND primary_task.agent_id = $2
- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for, fallback.branch_name, fallback.durable_work_dir, fallback.channel_context_revision
+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for, fallback.branch_name, fallback.durable_work_dir, fallback.channel_context_revision, fallback.comment_thread_id
)
-SELECT 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 FROM cancelled
+SELECT 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 FROM cancelled
`
type CancelDeferredEscalationsForIssueAgentParams struct {
@@ -1001,6 +1010,7 @@ type CancelDeferredEscalationsForIssueAgentRow struct {
BranchName pgtype.Text `json:"branch_name"`
DurableWorkDir pgtype.Text `json:"durable_work_dir"`
ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
+ CommentThreadID pgtype.UUID `json:"comment_thread_id"`
}
func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
@@ -1067,6 +1077,7 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -1083,7 +1094,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE escalation_for_task_id = $1
AND status IN ('deferred', 'queued', '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
+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
`
func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -1150,6 +1161,7 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -1166,7 +1178,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2
AND status IN ('queued', 'dispatched', 'deferred')
-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
+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
`
type CancelPendingTasksByIssueAndAgentParams struct {
@@ -1254,6 +1266,100 @@ func (q *Queries) CancelPendingTasksByIssueAndAgent(ctx context.Context, arg Can
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const cancelPendingTasksByIssueAndAgentInThread = `-- name: CancelPendingTasksByIssueAndAgentInThread :many
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+WHERE issue_id = $1 AND agent_id = $2
+ AND status IN ('queued', 'dispatched', 'deferred')
+ AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($3::uuid)
+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
+`
+
+type CancelPendingTasksByIssueAndAgentInThreadParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ ThreadCommentID pgtype.UUID `json:"thread_comment_id"`
+}
+
+// Cancel only the not-yet-started plan in the selected thread. Other threads
+// retain their queues; running tasks are stopped explicitly through CancelTask.
+func (q *Queries) CancelPendingTasksByIssueAndAgentInThread(ctx context.Context, arg CancelPendingTasksByIssueAndAgentInThreadParams) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelPendingTasksByIssueAndAgentInThread, arg.IssueID, arg.AgentID, arg.ThreadCommentID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -1271,7 +1377,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1
AND chat_session_id = $2
AND status = 'queued'
-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
+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
`
type CancelQueuedAgentTaskParams struct {
@@ -1339,6 +1445,7 @@ func (q *Queries) CancelQueuedAgentTask(ctx context.Context, arg CancelQueuedAge
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -1366,7 +1473,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE queued.chat_session_id = $1
AND queued.status = 'queued'
AND queued.id IS DISTINCT FROM (SELECT id FROM head)
-RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir, queued.channel_context_revision
+RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir, queued.channel_context_revision, queued.comment_thread_id
`
// Clear only positional follow-ups. The first visible task is current even
@@ -1437,6 +1544,7 @@ func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSess
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -1461,10 +1569,11 @@ WHERE r.runtime_id = ANY($1::uuid[])
SELECT 1 FROM agent_task_queue successor
WHERE successor.issue_id = r.issue_id
AND successor.agent_id = r.agent_id
+ AND successor.comment_thread_id IS NOT DISTINCT FROM r.comment_thread_id
AND successor.id <> r.id
AND successor.status IN ('queued', 'dispatched', 'running', '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
+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
`
// Cancels deferred auto-retry rows that a newer active task has already
@@ -1555,6 +1664,7 @@ func (q *Queries) CancelSupersededDeferredRetriesForRuntimes(ctx context.Context
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -1624,7 +1734,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-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
+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
`
type ClaimAgentTaskParams struct {
@@ -1707,6 +1817,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -1715,7 +1826,7 @@ const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = NULL
WHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL
-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
+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
`
// Atomically claims the deferred marker so the daemon ack and the sweeper
@@ -1778,6 +1889,7 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -1976,7 +2088,7 @@ SET status = 'completed', completed_at = now(), result = $2,
retired_session_id = COALESCE($8, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
-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
+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
`
type CompleteAgentTaskParams struct {
@@ -2068,6 +2180,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -2311,7 +2424,7 @@ SELECT
$22,
COALESCE($23::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
-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
+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
`
type CreateAgentTaskParams struct {
@@ -2440,6 +2553,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -2468,7 +2582,7 @@ SELECT
$19,
COALESCE($20::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
-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
+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
`
type CreateDeferredAgentTaskParams struct {
@@ -2584,6 +2698,7 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -2622,7 +2737,7 @@ SELECT
$23,
COALESCE($24::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
-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
+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
`
type CreateDeferredChannelIssueTaskParams struct {
@@ -2742,6 +2857,7 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Create
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -2767,7 +2883,7 @@ WHERE p.id = $5
AND p.chat_session_id IS NULL
AND p.autopilot_run_id IS NULL
AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)
-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
+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
`
type CreateManualQuickCreateRetryTaskParams struct {
@@ -2851,6 +2967,7 @@ func (q *Queries) CreateManualQuickCreateRetryTask(ctx context.Context, arg Crea
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -2873,7 +2990,7 @@ SELECT
$11,
COALESCE($12::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
-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
+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
`
type CreateQuickCreateTaskParams struct {
@@ -2972,6 +3089,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -3012,10 +3130,10 @@ SELECT
FROM agent_task_queue p
WHERE p.id = $1
AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)
-ON CONFLICT (issue_id, agent_id) WHERE status IN ('queued', 'dispatched')
+ON CONFLICT (issue_id, agent_id, (COALESCE(comment_thread_id, '00000000-0000-0000-0000-000000000000'::uuid))) WHERE status IN ('queued', 'dispatched')
OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
DO NOTHING
-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
+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
`
type CreateRetryTaskParams struct {
@@ -3165,6 +3283,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -3345,7 +3464,7 @@ WHERE t.id = v.id
WHERE retry_parent.id = t.parent_task_id
AND retry_parent.failure_reason = 'runtime_offline'
)
-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
+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
`
type ExpireStaleQueuedTasksParams struct {
@@ -3479,6 +3598,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -3497,7 +3617,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-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
+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
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -3568,6 +3688,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -3586,7 +3707,7 @@ SET status = 'failed',
retired_session_id = COALESCE($9, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', '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
+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
`
type FailAgentTaskParams struct {
@@ -3684,6 +3805,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -3730,7 +3852,7 @@ WHERE retry.id = victims.id
AND COALESCE(runtime.last_seen_at, runtime.updated_at) >=
now() - make_interval(secs => $2::double precision)
)
-RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir, retry.channel_context_revision
+RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir, retry.channel_context_revision, retry.comment_thread_id
`
type FailExpiredRuntimeReconnectRetriesParams struct {
@@ -3810,6 +3932,7 @@ func (q *Queries) FailExpiredRuntimeReconnectRetries(ctx context.Context, arg Fa
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -3864,7 +3987,7 @@ WHERE (
)
)
)
-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
+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
`
type FailStaleTasksParams struct {
@@ -3975,6 +4098,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -4216,7 +4340,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE id = $1
`
@@ -4278,12 +4402,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
const getAgentTaskForDelegatedFailureUpdate = `-- name: GetAgentTaskForDelegatedFailureUpdate :one
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE id = $1
FOR UPDATE
`
@@ -4349,12 +4474,13 @@ func (q *Queries) GetAgentTaskForDelegatedFailureUpdate(ctx context.Context, id
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -4429,10 +4555,22 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
+const getCommentThreadRootID = `-- name: GetCommentThreadRootID :one
+SELECT comment_thread_root_id($1::uuid)::uuid AS id
+`
+
+func (q *Queries) GetCommentThreadRootID(ctx context.Context, commentID pgtype.UUID) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, getCommentThreadRootID, commentID)
+ var id pgtype.UUID
+ err := row.Scan(&id)
+ return id, err
+}
+
const getLastTaskSession = `-- name: GetLastTaskSession :one
WITH retired_sessions AS (
SELECT DISTINCT r.retired_session_id AS session_id
@@ -4872,6 +5010,30 @@ func (q *Queries) HasActiveTaskForIssueAndAgent(ctx context.Context, arg HasActi
return has_active, err
}
+const hasActiveTaskForIssueAndAgentInThread = `-- name: HasActiveTaskForIssueAndAgentInThread :one
+SELECT count(*) > 0 AS has_active FROM agent_task_queue
+WHERE issue_id = $1 AND agent_id = $2
+ AND (
+ status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
+ )
+ AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($3::uuid)
+`
+
+type HasActiveTaskForIssueAndAgentInThreadParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ ThreadCommentID pgtype.UUID `json:"thread_comment_id"`
+}
+
+// Active execution and pending work in this comment thread only.
+func (q *Queries) HasActiveTaskForIssueAndAgentInThread(ctx context.Context, arg HasActiveTaskForIssueAndAgentInThreadParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasActiveTaskForIssueAndAgentInThread, arg.IssueID, arg.AgentID, arg.ThreadCommentID)
+ var has_active bool
+ err := row.Scan(&has_active)
+ return has_active, err
+}
+
const hasPendingTaskForIssue = `-- name: HasPendingTaskForIssue :one
SELECT count(*) > 0 AS has_pending FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched')
@@ -4963,6 +5125,79 @@ func (q *Queries) HasPendingTaskForIssueAndAgentExcludingTriggerComment(ctx cont
return has_pending, err
}
+const hasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread = `-- name: HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread :one
+SELECT count(*) > 0 AS has_pending FROM agent_task_queue
+WHERE issue_id = $1
+ AND agent_id = $2
+ AND (
+ status IN ('queued', 'dispatched')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
+ )
+ AND trigger_comment_id IS DISTINCT FROM $3::uuid
+ AND (
+ COALESCE($4::text, '') = ''
+ OR context->>'head_sha' = $4::text
+ )
+ AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($5::uuid)
+`
+
+type HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThreadParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ ExcludeTriggerCommentID pgtype.UUID `json:"exclude_trigger_comment_id"`
+ HeadSha pgtype.Text `json:"head_sha"`
+ ThreadCommentID pgtype.UUID `json:"thread_comment_id"`
+}
+
+// Thread-scoped edit preview: ignore the comment whose old run save replaces.
+func (q *Queries) HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread(ctx context.Context, arg HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThreadParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread,
+ arg.IssueID,
+ arg.AgentID,
+ arg.ExcludeTriggerCommentID,
+ arg.HeadSha,
+ arg.ThreadCommentID,
+ )
+ var has_pending bool
+ err := row.Scan(&has_pending)
+ return has_pending, err
+}
+
+const hasPendingTaskForIssueAndAgentInThread = `-- name: HasPendingTaskForIssueAndAgentInThread :one
+SELECT count(*) > 0 AS has_pending FROM agent_task_queue
+WHERE issue_id = $1 AND agent_id = $2
+ AND (
+ status IN ('queued', 'dispatched')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
+ )
+ AND (
+ COALESCE($3::text, '') = ''
+ OR context->>'head_sha' = $3::text
+ )
+ AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($4::uuid)
+`
+
+type HasPendingTaskForIssueAndAgentInThreadParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ HeadSha pgtype.Text `json:"head_sha"`
+ ThreadCommentID pgtype.UUID `json:"thread_comment_id"`
+}
+
+// Same pending/head rules as HasPendingTaskForIssueAndAgent, scoped to one
+// root comment and all descendants. NULL selects assignment-level work.
+func (q *Queries) HasPendingTaskForIssueAndAgentInThread(ctx context.Context, arg HasPendingTaskForIssueAndAgentInThreadParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasPendingTaskForIssueAndAgentInThread,
+ arg.IssueID,
+ arg.AgentID,
+ arg.HeadSha,
+ arg.ThreadCommentID,
+ )
+ var has_pending bool
+ err := row.Scan(&has_pending)
+ return has_pending, err
+}
+
const hasRetryTaskForParent = `-- name: HasRetryTaskForParent :one
SELECT count(*) > 0
FROM agent_task_queue
@@ -5175,7 +5410,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -5249,6 +5484,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -5363,7 +5599,7 @@ func (q *Queries) ListActiveTasksByIssueFamily(ctx context.Context, arg ListActi
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -5432,6 +5668,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -5622,7 +5859,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U
}
const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE chat_finalize_deferred_at IS NOT NULL
AND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)
ORDER BY chat_finalize_deferred_at
@@ -5701,6 +5938,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -5825,7 +6063,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -5894,6 +6132,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -5906,7 +6145,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id FROM agent_task_queue atq
WHERE atq.runtime_id = $1
AND atq.status = 'queued'
AND EXISTS (
@@ -6003,6 +6242,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -6015,7 +6255,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id FROM agent_task_queue atq
WHERE atq.runtime_id = ANY($1::uuid[])
AND atq.status = 'queued'
AND EXISTS (
@@ -6114,6 +6354,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -6126,7 +6367,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -6195,6 +6436,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -6269,16 +6511,16 @@ func (q *Queries) ListUserAgentsByRuntimeForUpdate(ctx context.Context, runtimeI
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir, latest.channel_context_revision FROM agent a
+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir, latest.channel_context_revision, latest.comment_thread_id FROM agent a
JOIN LATERAL (
- SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision
+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id
FROM agent_task_queue atq
WHERE atq.agent_id = a.id
AND atq.status IN ('completed', 'failed')
@@ -6377,6 +6619,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -6627,7 +6870,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
WHERE id = $1 AND status = 'dispatched'
-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
+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
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -6703,6 +6946,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -6711,7 +6955,7 @@ const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = now()
WHERE id = $1
-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
+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
`
// Arms the deferred chat-finalize marker for a cancelled chat task whose
@@ -6774,6 +7018,7 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -6807,12 +7052,13 @@ WHERE id = (
SELECT t.id FROM agent_task_queue t
WHERE t.issue_id = $12
AND t.agent_id = $13
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($1::uuid)
AND (
t.status = 'queued'
OR (t.status = 'deferred' AND t.context->>'channel_issue_media_pending' = 'true')
)
-- Head-scoped (TEN-356, #5914): never fold across HEADs. The physical
- -- unique index is only (issue_id, agent_id), so an insert-race loser can
+ -- unique index is per (issue_id, agent_id, thread), so an insert-race loser can
-- collide with a pending task stamped for a DIFFERENT head_sha; merging
-- into it would give a new-HEAD comment old-HEAD review coverage. Empty/
-- absent head_sha (no linked PR) matches any task, preserving coalescing.
@@ -6925,6 +7171,7 @@ WHERE id = (
SELECT t.id FROM agent_task_queue t
WHERE t.issue_id = $3
AND t.agent_id = $4
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($1::uuid)
AND (
t.status = 'queued'
OR (t.status = 'deferred' AND t.context->>'channel_issue_media_pending' = 'true')
@@ -6934,7 +7181,7 @@ WHERE id = (
ORDER BY t.created_at DESC
LIMIT 1
)
-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
+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
`
type MergeDelegatedFailureCommentIntoPendingTaskParams struct {
@@ -7013,6 +7260,7 @@ func (q *Queries) MergeDelegatedFailureCommentIntoPendingTask(ctx context.Contex
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -7035,6 +7283,7 @@ WHERE t.runtime_id = ANY($1::uuid[])
SELECT 1 FROM agent_task_queue occupant
WHERE occupant.issue_id = t.issue_id
AND occupant.agent_id = t.agent_id
+ AND occupant.comment_thread_id IS NOT DISTINCT FROM t.comment_thread_id
AND occupant.id <> t.id
AND (
occupant.status IN ('queued', 'dispatched')
@@ -7068,7 +7317,7 @@ const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTas
UPDATE agent_task_queue
SET status = 'queued', fire_at = NULL
WHERE id = $1 AND issue_id IS NOT NULL AND status = 'deferred'
-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
+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
`
// Early promotion is idempotent at the service layer: a task already promoted
@@ -7131,6 +7380,7 @@ func (q *Queries) PromoteDeferredChannelIssueTask(ctx context.Context, id pgtype
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -7140,7 +7390,7 @@ WITH due AS (
SELECT t.id,
t.issue_id,
row_number() OVER (
- PARTITION BY t.issue_id, t.agent_id
+ PARTITION BY t.issue_id, t.agent_id, t.comment_thread_id
ORDER BY t.priority DESC, t.created_at ASC, t.id
) AS rn
FROM agent_task_queue t
@@ -7158,6 +7408,7 @@ WITH due AS (
SELECT 1 FROM agent_task_queue occupant
WHERE occupant.issue_id = t.issue_id
AND occupant.agent_id = t.agent_id
+ AND occupant.comment_thread_id IS NOT DISTINCT FROM t.comment_thread_id
AND occupant.id <> t.id
AND (
occupant.status IN ('queued', 'dispatched')
@@ -7168,7 +7419,7 @@ WITH due AS (
UPDATE agent_task_queue
SET status = 'queued'
WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
-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
+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
`
type PromoteDueDeferredTasksForRuntimeParams struct {
@@ -7177,7 +7428,7 @@ type PromoteDueDeferredTasksForRuntimeParams struct {
}
// Promotion is fenced against the single queued/dispatched slot
-// idx_one_pending_task_per_issue_agent_v2 allows per (issue, agent). A deferred
+// idx_one_pending_task_per_issue_agent_thread allows per (issue, agent, thread). A deferred
// row is NOT covered by that index, so it can legitimately coexist with a queued
// one — a manual rerun enqueued behind a running task, plus the deferred retry
// that task's failure armed (runtime_offline, provider_network's final attempt).
@@ -7185,8 +7436,8 @@ type PromoteDueDeferredTasksForRuntimeParams struct {
// the claim loop promotes before it claims, that error blocked every claim on the
// runtime — including the rerun the operator was waiting for.
//
-// Two fences: skip a row whose (issue, agent) slot is already occupied, and
-// promote at most ONE row per (issue, agent) so a single statement cannot collide
+// Two fences: skip a row whose (issue, agent, thread) slot is already occupied, and
+// promote at most ONE row per (issue, agent, thread) so a single statement cannot collide
// with itself. A skipped row stays deferred with fire_at in the past and is
// promoted by a later tick once the slot frees, so nothing is lost — the human's
// rerun simply goes first. Chat / quick-create rows (issue_id NULL) are outside
@@ -7255,6 +7506,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, arg Pro
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -7271,7 +7523,7 @@ WITH due AS (
SELECT t.id,
t.issue_id,
row_number() OVER (
- PARTITION BY t.issue_id, t.agent_id
+ PARTITION BY t.issue_id, t.agent_id, t.comment_thread_id
ORDER BY t.priority DESC, t.created_at ASC, t.id
) AS rn
FROM agent_task_queue t
@@ -7289,6 +7541,7 @@ WITH due AS (
SELECT 1 FROM agent_task_queue occupant
WHERE occupant.issue_id = t.issue_id
AND occupant.agent_id = t.agent_id
+ AND occupant.comment_thread_id IS NOT DISTINCT FROM t.comment_thread_id
AND occupant.id <> t.id
AND (
occupant.status IN ('queued', 'dispatched')
@@ -7299,7 +7552,7 @@ WITH due AS (
UPDATE agent_task_queue
SET status = 'queued'
WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
-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
+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
`
type PromoteDueDeferredTasksForRuntimesParams struct {
@@ -7374,6 +7627,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, arg Pr
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -7497,7 +7751,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-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
+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
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -7575,6 +7829,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -7616,7 +7871,7 @@ WHERE id IN (
LIMIT $5::int
FOR UPDATE SKIP LOCKED
)
-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
+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
`
type ReclaimStaleDispatchedTasksForRuntimesParams struct {
@@ -7704,6 +7959,7 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -7724,7 +7980,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', '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
+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
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -7797,6 +8053,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -7876,6 +8133,7 @@ WHERE id = (
SELECT t.id FROM agent_task_queue t
WHERE t.issue_id = $2
AND t.agent_id = $3
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($1::uuid)
AND t.status IN ('dispatched', 'running', 'waiting_local_directory')
AND (
COALESCE($4::text, '') = ''
@@ -7945,7 +8203,7 @@ WHERE id = $1
AND status = 'dispatched'
AND started_at IS NULL
AND dispatched_at = $3
-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
+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
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -8017,6 +8275,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -8290,7 +8549,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE id = $1 AND 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
+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
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -8357,6 +8616,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 96879930df..7503bed8fe 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -300,7 +300,7 @@ SELECT
$11,
COALESCE($12::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
-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
+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
`
type CreateAutopilotTaskParams struct {
@@ -408,6 +408,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -933,7 +934,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD
}
const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :one
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE autopilot_run_id = $1
ORDER BY created_at
LIMIT 1
@@ -999,6 +1000,7 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 165895e012..956debd065 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -387,7 +387,7 @@ SELECT
$15::bigint,
COALESCE($16::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
-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
+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
`
type CreateChatTaskParams struct {
@@ -491,6 +491,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -570,7 +571,7 @@ FROM (
WHERE task.id = $1
AND pending.max_until IS NOT NULL
AND (task.fire_at IS NULL OR task.fire_at < pending.max_until)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id
`
// Closes the enqueue-vs-append race: under READ COMMITTED a media message can
@@ -637,6 +638,7 @@ func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
@@ -2880,7 +2882,7 @@ WHERE task.chat_session_id = $1
AND message.role = 'user'
AND message.channel_media_pending_until > now()
)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id
`
// Media completion may race with the 3s run batcher. Promote every original
@@ -2953,6 +2955,7 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -3383,7 +3386,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :one
UPDATE agent_task_queue
SET chat_input_task_id = id
WHERE id = $1
-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
+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
`
// Stamps a freshly-created direct-chat task as the owner of its own input batch
@@ -3451,6 +3454,7 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
)
return i, err
}
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index fa14ce8dcf..f4b3c3a411 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -1289,16 +1289,18 @@ 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 FROM comment
WHERE issue_id = $1
+ AND (id = ANY($2::uuid[])
+ OR comment_thread_root_id(id) = $3::uuid)
AND (
(
author_type IN ('member', 'agent')
- AND (created_at > $2 OR id = ANY($3::uuid[]))
+ AND (created_at > $4 OR id = ANY($2::uuid[]))
)
OR (
author_type = 'system'
AND type = 'progress_update'
AND source_task_id IS NOT NULL
- AND id = ANY($3::uuid[])
+ AND id = ANY($2::uuid[])
)
)
ORDER BY created_at ASC, id ASC
@@ -1306,8 +1308,9 @@ ORDER BY created_at ASC, id ASC
type ListReconcilableCommentsForIssueSinceParams struct {
IssueID pgtype.UUID `json:"issue_id"`
- Since pgtype.Timestamptz `json:"since"`
PlannedCommentIds []pgtype.UUID `json:"planned_comment_ids"`
+ CommentThreadID pgtype.UUID `json:"comment_thread_id"`
+ Since pgtype.Timestamptz `json:"since"`
}
// MUL-4195 / MUL-4304 completion reconciliation: every MEMBER- or AGENT-authored
@@ -1343,7 +1346,12 @@ type ListReconcilableCommentsForIssueSinceParams struct {
// replaying in order lets later comments coalesce onto the follow-up created by
// the first.
func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg ListReconcilableCommentsForIssueSinceParams) ([]Comment, error) {
- rows, err := q.db.Query(ctx, listReconcilableCommentsForIssueSince, arg.IssueID, arg.Since, arg.PlannedCommentIds)
+ rows, err := q.db.Query(ctx, listReconcilableCommentsForIssueSince,
+ arg.IssueID,
+ arg.PlannedCommentIds,
+ arg.CommentThreadID,
+ arg.Since,
+ )
if err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 0474f390ca..9ac8f01a1d 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -172,6 +172,7 @@ type AgentTaskQueue struct {
BranchName pgtype.Text `json:"branch_name"`
DurableWorkDir pgtype.Text `json:"durable_work_dir"`
ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
+ CommentThreadID pgtype.UUID `json:"comment_thread_id"`
}
type AgentToLabel struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index bb53cd9d75..2621e3e376 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-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
+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
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -110,6 +110,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
@@ -212,7 +213,7 @@ SET status = 'failed', completed_at = now(), error = 'runtime went offline',
FROM victims
WHERE task.id = victims.id
AND task.status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id
`
type FailTasksForOfflineRuntimesParams struct {
@@ -292,6 +293,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context, arg FailTasks
&i.BranchName,
&i.DurableWorkDir,
&i.ChannelContextRevision,
+ &i.CommentThreadID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index a13cedb95a..10ab9740da 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -586,7 +586,7 @@ SELECT
FROM agent_task_queue p
WHERE p.id = $1
AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)
-ON CONFLICT (issue_id, agent_id) WHERE status IN ('queued', 'dispatched')
+ON CONFLICT (issue_id, agent_id, (COALESCE(comment_thread_id, '00000000-0000-0000-0000-000000000000'::uuid))) WHERE status IN ('queued', 'dispatched')
OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
DO NOTHING
RETURNING *;
@@ -670,6 +670,16 @@ WHERE issue_id = $1 AND agent_id = $2
AND status IN ('queued', 'dispatched', 'deferred')
RETURNING *;
+-- name: CancelPendingTasksByIssueAndAgentInThread :many
+-- Cancel only the not-yet-started plan in the selected thread. Other threads
+-- retain their queues; running tasks are stopped explicitly through CancelTask.
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+WHERE issue_id = $1 AND agent_id = $2
+ AND status IN ('queued', 'dispatched', 'deferred')
+ AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(sqlc.narg('thread_comment_id')::uuid)
+RETURNING *;
+
-- name: CancelAgentTasksByAgent :many
-- Bulk-cancel every active (queued/dispatched/running) task for an agent.
-- Returns the affected rows so callers can broadcast task:cancelled events.
@@ -687,7 +697,8 @@ RETURNING *;
-- coalesced input; cancellation prevents an agent from acting on a stale or
-- deleted version. Must run before deletion clears trigger_comment_id.
UPDATE agent_task_queue
-SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
+ context = COALESCE(context, '{}'::jsonb) || jsonb_build_object('comment_change_cancelled_task_id', id::text)
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
@@ -1767,6 +1778,21 @@ WHERE issue_id = $1 AND agent_id = $2
OR context->>'head_sha' = sqlc.narg('head_sha')::text
);
+-- name: HasPendingTaskForIssueAndAgentInThread :one
+-- Same pending/head rules as HasPendingTaskForIssueAndAgent, scoped to one
+-- root comment and all descendants. NULL selects assignment-level work.
+SELECT count(*) > 0 AS has_pending FROM agent_task_queue
+WHERE issue_id = $1 AND agent_id = $2
+ AND (
+ status IN ('queued', 'dispatched')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
+ )
+ AND (
+ COALESCE(sqlc.narg('head_sha')::text, '') = ''
+ OR context->>'head_sha' = sqlc.narg('head_sha')::text
+ )
+ AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(sqlc.narg('thread_comment_id')::uuid);
+
-- name: HasPendingTaskForIssueAndAgentExcludingTriggerComment :one
-- Same as HasPendingTaskForIssueAndAgent, but ignores tasks triggered by the
-- current comment being edited. Edit preview needs this because save cancels
@@ -1785,6 +1811,22 @@ WHERE issue_id = @issue_id
OR context->>'head_sha' = sqlc.narg('head_sha')::text
);
+-- name: HasPendingTaskForIssueAndAgentExcludingTriggerCommentInThread :one
+-- Thread-scoped edit preview: ignore the comment whose old run save replaces.
+SELECT count(*) > 0 AS has_pending FROM agent_task_queue
+WHERE issue_id = @issue_id
+ AND agent_id = @agent_id
+ AND (
+ status IN ('queued', 'dispatched')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
+ )
+ AND trigger_comment_id IS DISTINCT FROM @exclude_trigger_comment_id::uuid
+ AND (
+ COALESCE(sqlc.narg('head_sha')::text, '') = ''
+ OR context->>'head_sha' = sqlc.narg('head_sha')::text
+ )
+ AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(sqlc.narg('thread_comment_id')::uuid);
+
-- name: MergeCommentIntoPendingTask :one
-- MUL-4195: fold a newly-arrived comment into an existing task for (issue,
-- agent) that has NOT yet been claimed, instead of letting the
@@ -1856,12 +1898,13 @@ WHERE id = (
SELECT t.id FROM agent_task_queue t
WHERE t.issue_id = @issue_id
AND t.agent_id = @agent_id
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(@new_trigger_comment_id::uuid)
AND (
t.status = 'queued'
OR (t.status = 'deferred' AND t.context->>'channel_issue_media_pending' = 'true')
)
-- Head-scoped (TEN-356, #5914): never fold across HEADs. The physical
- -- unique index is only (issue_id, agent_id), so an insert-race loser can
+ -- unique index is per (issue_id, agent_id, thread), so an insert-race loser can
-- collide with a pending task stamped for a DIFFERENT head_sha; merging
-- into it would give a new-HEAD comment old-HEAD review coverage. Empty/
-- absent head_sha (no linked PR) matches any task, preserving coalescing.
@@ -1908,6 +1951,7 @@ WHERE id = (
SELECT t.id FROM agent_task_queue t
WHERE t.issue_id = @issue_id
AND t.agent_id = @agent_id
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(@comment_id::uuid)
AND t.status IN ('dispatched', 'running', 'waiting_local_directory')
AND (
COALESCE(sqlc.narg('head_sha')::text, '') = ''
@@ -1937,6 +1981,7 @@ WHERE id = (
SELECT t.id FROM agent_task_queue t
WHERE t.issue_id = @issue_id
AND t.agent_id = @agent_id
+ AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(@comment_id::uuid)
AND (
t.status = 'queued'
OR (t.status = 'deferred' AND t.context->>'channel_issue_media_pending' = 'true')
@@ -2143,6 +2188,16 @@ WHERE issue_id = $1 AND agent_id = $2
OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
);
+-- name: HasActiveTaskForIssueAndAgentInThread :one
+-- Active execution and pending work in this comment thread only.
+SELECT count(*) > 0 AS has_active FROM agent_task_queue
+WHERE issue_id = $1 AND agent_id = $2
+ AND (
+ status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
+ )
+ AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(sqlc.narg('thread_comment_id')::uuid);
+
-- name: GetLatestTaskRoleForIssueAndAgent :one
-- Returns the role markers from the agent's most recent task on this issue.
-- Used by the squad-leader self-trigger guard to tell apart leader tasks,
@@ -2228,6 +2283,7 @@ WHERE r.runtime_id = ANY(@runtime_ids::uuid[])
SELECT 1 FROM agent_task_queue successor
WHERE successor.issue_id = r.issue_id
AND successor.agent_id = r.agent_id
+ AND successor.comment_thread_id IS NOT DISTINCT FROM r.comment_thread_id
AND successor.id <> r.id
AND successor.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
)
@@ -2235,7 +2291,7 @@ RETURNING *;
-- name: PromoteDueDeferredTasksForRuntime :many
-- Promotion is fenced against the single queued/dispatched slot
--- idx_one_pending_task_per_issue_agent_v2 allows per (issue, agent). A deferred
+-- idx_one_pending_task_per_issue_agent_thread allows per (issue, agent, thread). A deferred
-- row is NOT covered by that index, so it can legitimately coexist with a queued
-- one — a manual rerun enqueued behind a running task, plus the deferred retry
-- that task's failure armed (runtime_offline, provider_network's final attempt).
@@ -2243,8 +2299,8 @@ RETURNING *;
-- the claim loop promotes before it claims, that error blocked every claim on the
-- runtime — including the rerun the operator was waiting for.
--
--- Two fences: skip a row whose (issue, agent) slot is already occupied, and
--- promote at most ONE row per (issue, agent) so a single statement cannot collide
+-- Two fences: skip a row whose (issue, agent, thread) slot is already occupied, and
+-- promote at most ONE row per (issue, agent, thread) so a single statement cannot collide
-- with itself. A skipped row stays deferred with fire_at in the past and is
-- promoted by a later tick once the slot frees, so nothing is lost — the human's
-- rerun simply goes first. Chat / quick-create rows (issue_id NULL) are outside
@@ -2253,7 +2309,7 @@ WITH due AS (
SELECT t.id,
t.issue_id,
row_number() OVER (
- PARTITION BY t.issue_id, t.agent_id
+ PARTITION BY t.issue_id, t.agent_id, t.comment_thread_id
ORDER BY t.priority DESC, t.created_at ASC, t.id
) AS rn
FROM agent_task_queue t
@@ -2271,6 +2327,7 @@ WITH due AS (
SELECT 1 FROM agent_task_queue occupant
WHERE occupant.issue_id = t.issue_id
AND occupant.agent_id = t.agent_id
+ AND occupant.comment_thread_id IS NOT DISTINCT FROM t.comment_thread_id
AND occupant.id <> t.id
AND (
occupant.status IN ('queued', 'dispatched')
@@ -2344,6 +2401,7 @@ WHERE t.runtime_id = ANY(@runtime_ids::uuid[])
SELECT 1 FROM agent_task_queue occupant
WHERE occupant.issue_id = t.issue_id
AND occupant.agent_id = t.agent_id
+ AND occupant.comment_thread_id IS NOT DISTINCT FROM t.comment_thread_id
AND occupant.id <> t.id
AND (
occupant.status IN ('queued', 'dispatched')
@@ -2360,7 +2418,7 @@ WITH due AS (
SELECT t.id,
t.issue_id,
row_number() OVER (
- PARTITION BY t.issue_id, t.agent_id
+ PARTITION BY t.issue_id, t.agent_id, t.comment_thread_id
ORDER BY t.priority DESC, t.created_at ASC, t.id
) AS rn
FROM agent_task_queue t
@@ -2378,6 +2436,7 @@ WITH due AS (
SELECT 1 FROM agent_task_queue occupant
WHERE occupant.issue_id = t.issue_id
AND occupant.agent_id = t.agent_id
+ AND occupant.comment_thread_id IS NOT DISTINCT FROM t.comment_thread_id
AND occupant.id <> t.id
AND (
occupant.status IN ('queued', 'dispatched')
@@ -2746,3 +2805,6 @@ INSERT INTO agent (
@owner_id, '', '{}'::jsonb, '[]'::jsonb, 'user', @system_key
)
RETURNING *;
+
+-- name: GetCommentThreadRootID :one
+SELECT comment_thread_root_id(@comment_id::uuid)::uuid AS id;
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index 766a61d1c6..45d56560b1 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -381,6 +381,8 @@ LIMIT 1;
-- 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)
AND (
(
author_type IN ('member', 'agent')