Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5750: fix(chat): keep idle sends out of follow-up queue (#6418)
Multica Eve73283556d7b4
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsxindex 36caa1de52..61e2696e24 100644--- a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx@@ -46,6 +46,7 @@ import type {ChatPendingTask,} from "@multica/core/types";import {+ enqueuePendingChatTask,hideQueuedChatMessages,removePendingChatTask,} from "@multica/core/chat/pending";@@ -279,14 +280,25 @@ export default function ChatTab() {task_id: null,created_at: sentAt,};+ const optimisticTaskId = `optimistic-${optimistic.id}`;qc.setQueryData<ChatMessage[]>(chatKeys.messages(sessionId), (old) =>old ? [...old, optimistic] : [optimistic],);- qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {- task_id: `optimistic-${optimistic.id}`,- status: "queued",- created_at: sentAt,- });+ qc.setQueryData<ChatPendingTask>(+ chatKeys.pendingTask(sessionId),+ (old) =>+ enqueuePendingChatTask(+ old,+ {+ task_id: optimisticTaskId,+ status: "queued",+ created_at: sentAt,+ message_id: optimistic.id,+ content,+ },+ Boolean(old?.task_id),+ ),+ );if (isNewSession) {promoteNewDraft(sessionId);setActiveSessionId(sessionId);@@ -296,11 +308,30 @@ export default function ChatTab() {const result = await api.sendChatMessage(sessionId, content, {attachmentIds: attachmentIds.length > 0 ? attachmentIds : undefined,});+ // Replace the local bubble before reconciling pending state. When the+ // server says this is a follow-up, its real message id lets the shared+ // queue filter hide it immediately instead of waiting for the refetch.+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(sessionId), (old) =>+ old?.map((message) =>+ message.id === optimistic.id+ ? {+ ...message,+ id: result.message_id,+ task_id: result.task_id,+ created_at: result.created_at,+ }+ : message,+ ),+ );seedAcceptedPendingTask(qc, {chat_session_id: sessionId,task_id: result.task_id,created_at: result.created_at,+ message_id: result.message_id,+ content,+ optimistic_task_id: optimisticTaskId,supports_queue: result.supports_queue,+ queued: result.queued,});qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });if (options.clearDraft !== false) {@@ -310,7 +341,10 @@ export default function ChatTab() {qc.setQueryData<ChatMessage[]>(chatKeys.messages(sessionId), (old) =>old ? old.filter((m) => m.id !== optimistic.id) : old,);- qc.setQueryData(chatKeys.pendingTask(sessionId), {});+ qc.setQueryData<ChatPendingTask>(+ chatKeys.pendingTask(sessionId),+ (old) => removePendingChatTask(old, optimisticTaskId),+ );throw err;}},diff --git a/apps/mobile/components/chat/status-pill.tsx b/apps/mobile/components/chat/status-pill.tsxindex 68d3297a43..8f41612540 100644--- a/apps/mobile/components/chat/status-pill.tsx+++ b/apps/mobile/components/chat/status-pill.tsx@@ -76,6 +76,9 @@ function pickStage(taskMessages: readonly TaskMessagePayload[],availability: AgentAvailability | undefined,): Stage {+ // Mirrors web: deferred is an older turn waiting for retry backoff, not+ // active model work, so it must not fall through to "Thinking".+ if (status === "deferred") return { label: "Retrying" };if ((status === "queued" || status === "dispatched") &&availability === "offline"@@ -142,8 +145,14 @@ export function StatusPill({if (!taskId) return null;+ // Deferred retries retain task messages from the earlier attempt, so the+ // newer server status must win over those stale running hints.const status =- taskMessages.length > 0 ? "running" : pendingTask?.status;+ pendingTask?.status === "deferred"+ ? "deferred"+ : taskMessages.length > 0+ ? "running"+ : pendingTask?.status;const elapsedSec = Math.max(0, Math.floor((Date.now() - anchorMs) / 1000));const stage = pickStage(status, taskMessages, availability);diff --git a/apps/mobile/data/chat-schema.test.ts b/apps/mobile/data/chat-schema.test.tsindex 201d48fcc5..659c34189d 100644--- a/apps/mobile/data/chat-schema.test.ts+++ b/apps/mobile/data/chat-schema.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { ChatPendingTaskSchema } from "./schemas";+import { ChatPendingTaskSchema, SendChatMessageResponseSchema } from "./schemas";describe("ChatPendingTaskSchema", () => {it("keeps the pending head and valid queue rows when one row is malformed", () => {@@ -26,3 +26,19 @@ describe("ChatPendingTaskSchema", () => {]);});});++describe("SendChatMessageResponseSchema", () => {+ const base = {+ message_id: "message-1",+ task_id: "task-1",+ created_at: "2026-08-05T00:00:00Z",+ };++ it("keeps queue position parity with web", () => {+ expect(SendChatMessageResponseSchema.parse({ ...base, queued: false }).queued).toBe(false);+ });++ it("ignores a malformed additive queue position", () => {+ expect(SendChatMessageResponseSchema.parse({ ...base, queued: "no" }).queued).toBeUndefined();+ });+});diff --git a/apps/mobile/data/realtime/chat-ws-updaters.test.ts b/apps/mobile/data/realtime/chat-ws-updaters.test.tsindex a2be9ea1b9..5d5f0840e5 100644--- a/apps/mobile/data/realtime/chat-ws-updaters.test.ts+++ b/apps/mobile/data/realtime/chat-ws-updaters.test.ts@@ -7,11 +7,6 @@ import type {ChatQuickActionsPayload,} from "@multica/core/types";-// chat-ws-updaters imports chatKeys from data/queries/chat, which transitively-// imports the native fetch client. Mock it so the Node test never loads RN-// modules — chatKeys itself is a pure key factory and needs nothing from api.-vi.mock("@/data/api", () => ({ api: {} }));-import {applyChatDoneToCache,applyChatQuickActionsToCache,@@ -21,6 +16,11 @@ import {} from "./chat-ws-updaters";import { chatKeys } from "@/data/queries/chat";+// chat-ws-updaters imports chatKeys from data/queries/chat, which transitively+// imports the native fetch client. Mock it so the Node test never loads RN+// modules — chatKeys itself is a pure key factory and needs nothing from api.+vi.mock("@/data/api", () => ({ api: {} }));+const SESSION = "session-1";function donePayload(over: Partial<ChatDonePayload> = {}): ChatDonePayload {@@ -106,6 +106,87 @@ describe("applyChatDoneToCache", () => {});describe("pending task queue events", () => {+ it("keeps an idle accepted send out of the follow-up queue", () => {+ const qc = new QueryClient();++ seedAcceptedPendingTask(qc, {+ chat_session_id: SESSION,+ task_id: "task-1",+ created_at: "2026-07-09T00:00:00Z",+ supports_queue: true,+ queued: false,+ });++ expect(qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION))).toMatchObject({+ task_id: "task-1",+ queued_tasks: [],+ });+ });++ it("retains a placeholder head when a queued response arrives before its predecessor", () => {+ const qc = new QueryClient();+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION), {+ task_id: "optimistic-message-1",+ status: "queued",+ created_at: "2026-07-09T00:00:01Z",+ });++ seedAcceptedPendingTask(qc, {+ chat_session_id: SESSION,+ task_id: "task-follow-up",+ created_at: "2026-07-09T00:00:01Z",+ message_id: "message-follow-up",+ content: "follow up",+ optimistic_task_id: "optimistic-message-1",+ supports_queue: true,+ queued: true,+ });++ expect(qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION))).toEqual({+ task_id: "optimistic-message-1",+ status: "queued",+ created_at: "2026-07-09T00:00:01Z",+ supports_queue: true,+ queued_tasks: [{+ task_id: "task-follow-up",+ status: "queued",+ created_at: "2026-07-09T00:00:01Z",+ message_id: "message-follow-up",+ content: "follow up",+ }],+ });+ });++ it("replaces an optimistic follow-up without disturbing the active head", () => {+ const qc = new QueryClient();+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION), {+ task_id: "task-active",+ status: "running",+ created_at: "2026-07-09T00:00:00Z",+ queued_tasks: [{+ task_id: "optimistic-message-1",+ status: "queued",+ created_at: "2026-07-09T00:00:01Z",+ }],+ });++ seedAcceptedPendingTask(qc, {+ chat_session_id: SESSION,+ task_id: "task-follow-up",+ created_at: "2026-07-09T00:00:01Z",+ optimistic_task_id: "optimistic-message-1",+ supports_queue: true,+ queued: true,+ });++ expect(qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION))).toMatchObject({+ task_id: "task-active",+ status: "running",+ supports_queue: true,+ queued_tasks: [{ task_id: "task-follow-up" }],+ });+ });+it("keeps dispatch state when the send response arrives later", () => {const qc = new QueryClient();qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION), {@@ -126,6 +207,7 @@ describe("pending task queue events", () => {chat_session_id: SESSION,task_id: "task-1",created_at: "2026-07-09T00:00:01Z",+ queued: false,});expect(qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION))).toMatchObject({diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.tsindex adfa31b76e..4986501766 100644--- a/apps/mobile/data/realtime/chat-ws-updaters.ts+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts@@ -20,7 +20,10 @@* - chatKeys.pendingTask(sessionId)→ ChatPendingTask (empty `{}` = no in-flight)*/import type { QueryClient } from "@tanstack/react-query";-import { enqueuePendingChatTask } from "@multica/core/chat/pending";+import {+ enqueuePendingChatTask,+ removePendingChatTask,+} from "@multica/core/chat/pending";import type {ChatDonePayload,ChatMessage,@@ -249,7 +252,11 @@ export function seedAcceptedPendingTask(chat_session_id: string;task_id: string;created_at: string;+ message_id?: string;+ content?: string;+ optimistic_task_id?: string;supports_queue?: boolean;+ queued?: boolean;},) {qc.setQueryData<ChatPendingTask>(@@ -259,16 +266,27 @@ export function seedAcceptedPendingTask(task_id: payload.task_id,status: "queued",created_at: payload.created_at,+ ...(payload.message_id ? { message_id: payload.message_id } : {}),+ ...(payload.content !== undefined ? { content: payload.content } : {}),};- const next =- old?.task_id?.startsWith("optimistic-")- ? {- ...old,- ...task,- status: old.status && old.status !== "queued" ? old.status : task.status,- created_at: old.created_at || task.created_at,- }- : enqueuePendingChatTask(old, task);+ let next: ChatPendingTask;+ if (+ payload.queued === true &&+ payload.optimistic_task_id &&+ old?.task_id === payload.optimistic_task_id+ ) {+ // The server knows an authoritative predecessor exists, but this+ // client has not loaded it yet. Retain the optimistic root as a+ // non-network placeholder until the invalidation fills that head;+ // dropping it here would briefly unlock the composer and remove the+ // status line while leaving only a queue row.+ next = enqueuePendingChatTask(old, task, true);+ } else {+ const reconciled = payload.optimistic_task_id+ ? removePendingChatTask(old, payload.optimistic_task_id)+ : old;+ next = enqueuePendingChatTask(reconciled, task, payload.queued);+ }if (payload.supports_queue === true || old?.supports_queue === true) {next.supports_queue = true;}diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.tsindex a522762132..a64a02c20b 100644--- a/apps/mobile/data/schemas.ts+++ b/apps/mobile/data/schemas.ts@@ -326,6 +326,7 @@ export const SendChatMessageResponseSchema: z.ZodType<SendChatMessageResponse> =message_id: z.string(),task_id: z.string(),supports_queue: z.boolean().optional(),+ queued: z.boolean().optional().catch(undefined),created_at: z.string().default(""),}).loose();diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 28d574db98..59b204ee36 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -35,6 +35,7 @@ import {RuntimeUsageByAgentListSchema,RuntimeUsageByHourListSchema,RuntimeUsageListSchema,+ SendChatMessageResponseSchema,SquadListSchema,SquadSchema,TimelineEntriesSchema,@@ -476,6 +477,22 @@ describe("ChatPendingTaskSchema", () => {});});+describe("SendChatMessageResponseSchema", () => {+ const base = {+ message_id: "message-1",+ task_id: "task-1",+ created_at: "2026-08-05T00:00:00Z",+ };++ it("parses the server-authoritative queue position", () => {+ expect(SendChatMessageResponseSchema.parse({ ...base, queued: false }).queued).toBe(false);+ });++ it("ignores a malformed additive queue position without losing the accepted send", () => {+ expect(SendChatMessageResponseSchema.parse({ ...base, queued: "no" }).queued).toBeUndefined();+ });+});+describe("PrioritizeQueuedChatTaskResponseSchema", () => {const ENDPOINT = {endpoint: "POST /api/chat/sessions/:id/queued-tasks/:taskId/prioritize",diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 3f07525a55..640a33e087 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1267,6 +1267,7 @@ export const SendChatMessageResponseSchema: z.ZodType<SendChatMessageResponse> =message_id: z.string().min(1),task_id: z.string().min(1),supports_queue: z.boolean().optional(),+ queued: z.boolean().optional().catch(undefined),created_at: z.string().min(1),attachment_ids: z.array(z.string()).nullish().transform((ids) => ids ?? undefined),}).loose();diff --git a/packages/core/chat/pending.test.ts b/packages/core/chat/pending.test.tsindex af87732965..f2e5362c3b 100644--- a/packages/core/chat/pending.test.ts+++ b/packages/core/chat/pending.test.ts@@ -24,17 +24,45 @@ describe("pending chat queue", () => {expect(result.queued_tasks?.map((item) => item.task_id)).toEqual(["next", "later"]);});- it("keeps the first queued prompt in the queue until it starts running", () => {+ it("treats the first accepted task as the current head before it starts running", () => {const queued = {...task("next", "2026-01-01T00:00:01Z"),message_id: "message-next",};const pending = enqueuePendingChatTask(undefined, queued);- expect(pending.queued_tasks).toEqual([queued]);+ expect(pending.queued_tasks).toEqual([]);expect(promotePendingChatTask(pending, "next", "running").queued_tasks).toEqual([]);});+ it("keeps an authoritative queued send hidden while its head is still loading", () => {+ const queued = {+ ...task("next", "2026-01-01T00:00:01Z"),+ message_id: "message-next",+ };++ expect(enqueuePendingChatTask(undefined, queued, true)).toEqual({+ queued_tasks: [queued],+ });+ });++ it("preserves a follow-up when its response arrives before the head response", () => {+ const followUp = {+ ...task("next", "2026-01-01T00:00:01Z"),+ message_id: "message-next",+ };+ const waitingForHead = enqueuePendingChatTask(undefined, followUp, true);+ const head = {+ ...task("head", "2026-01-01T00:00:00Z"),+ message_id: "message-head",+ };++ expect(enqueuePendingChatTask(waitingForHead, head, false)).toEqual({+ ...head,+ queued_tasks: [followUp],+ });+ });+it("keeps a send response preview when a sparse queued event arrives later", () => {const current = {...task("active", "2026-01-01T00:00:00Z"),@@ -174,7 +202,7 @@ describe("pending chat queue", () => {const result = removePendingChatTask(current, "active");expect(result.task_id).toBe("next");expect(result.supports_queue).toBe(true);- expect(result.queued_tasks?.map((item) => item.task_id)).toEqual(["next", "later"]);+ expect(result.queued_tasks?.map((item) => item.task_id)).toEqual(["later"]);});it("keeps queued prompts out of the settled transcript", () => {@@ -204,7 +232,7 @@ describe("pending chat queue", () => {expect(hideQueuedChatMessages(messages, pending)).toEqual([messages[0]]);const waiting = removePendingChatTask(pending, "active");- expect(hideQueuedChatMessages(messages, waiting)).toEqual([messages[0]]);+ expect(hideQueuedChatMessages(messages, waiting)).toEqual(messages);expect(hideQueuedChatMessages(messages, promotePendingChatTask(waiting, "next", "running")),).toEqual(@@ -260,6 +288,6 @@ describe("pending chat queue", () => {const result = removePendingChatTask(current, "active");expect(result.task_id).toBe("send-now");- expect(result.queued_tasks?.map((item) => item.task_id)).toEqual(["send-now", "next"]);+ expect(result.queued_tasks?.map((item) => item.task_id)).toEqual(["next"]);});});diff --git a/packages/core/chat/pending.ts b/packages/core/chat/pending.tsindex ec319b7487..caba45f5a1 100644--- a/packages/core/chat/pending.ts+++ b/packages/core/chat/pending.ts@@ -37,9 +37,26 @@ function asSummary(task: ChatPendingTask): ChatQueuedTask | undefined {export function enqueuePendingChatTask(current: ChatPendingTask | undefined,task: ChatQueuedTask,+ queued = Boolean(current?.task_id && current.task_id !== task.task_id),): ChatPendingTask {if (!current?.task_id) {- return { ...task, queued_tasks: [task] };+ // A queued send can arrive before this client has loaded the real head.+ // Keep it hidden as a queue-only row until the authoritative refetch+ // fills in the head; an idle send becomes the head immediately.+ const queueSupport = current?.supports_queue === undefined+ ? {}+ : { supports_queue: current.supports_queue };+ return queued+ ? { ...queueSupport, queued_tasks: [task] }+ : {+ ...task,+ ...queueSupport,+ queued_tasks: normalizeQueue(+ (current?.queued_tasks ?? []).filter((queuedTask) =>+ queuedTask.task_id !== task.task_id+ ),+ ),+ };}if (current.task_id === task.task_id) {const status = current.status && current.status !== "queued"@@ -53,9 +70,14 @@ export function enqueuePendingChatTask(...task,status,created_at: current.created_at || task.created_at,- queued_tasks: status === "queued"- ? normalizeQueue([...queuedTasks, task])- : queuedTasks,+ queued_tasks: queuedTasks,+ };+ }+ if (!queued) {+ return {+ ...task,+ supports_queue: current.supports_queue,+ queued_tasks: [],};}return {@@ -112,7 +134,10 @@ export function removePendingChatTask((current.queued_tasks ?? []).filter((task) => task.task_id !== taskID),);if (!next) return EMPTY_PENDING_TASK;- return { ...next, supports_queue: current.supports_queue, queued_tasks: [next, ...rest] };+ const queueSupport = current.supports_queue === undefined+ ? {}+ : { supports_queue: current.supports_queue };+ return { ...next, ...queueSupport, queued_tasks: rest };}export function prioritizePendingChatTask(diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.tsindex ef90935000..f8ac8b478f 100644--- a/packages/core/realtime/use-realtime-sync.test.ts+++ b/packages/core/realtime/use-realtime-sync.test.ts@@ -380,12 +380,6 @@ describe("applyChatCancelFinalizedToCache", () => {created_at: "2026-05-13T05:00:01Z",content: "next",queued_tasks: [- {- task_id: "task-next",- status: "queued",- created_at: "2026-05-13T05:00:01Z",- content: "next",- },{task_id: "task-later",status: "queued",diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.tsindex 2d72723ee6..eec2fb93d7 100644--- a/packages/core/types/chat.ts+++ b/packages/core/types/chat.ts@@ -172,6 +172,11 @@ export interface SendChatMessageResponse {task_id: string;/** True when the server supports queued follow-up sends. */supports_queue?: boolean;+ /**+ * True only when this task was accepted behind another in-flight task in+ * the same chat session. Optional for compatibility with older servers.+ */+ queued?: boolean;/*** Server-authoritative task creation time. Optimistic StatusPill seed* uses this as its anchor so the timer starts from the real `0s` —@@ -260,8 +265,8 @@ export interface ChatPendingTask {/** Explicit capability gate; absent on servers predating follow-up queues. */supports_queue?: boolean;/**- * Ordered prompts that are still queued. When no task is active, the legacy- * root fields mirror the first entry for backward compatibility.+ * Ordered follow-ups behind the root task. The root may itself still have+ * database status `queued` before claim, but is never duplicated here.*/queued_tasks?: ChatQueuedTask[];}diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsxindex 0a2ed18858..4cf57f56fe 100644--- a/packages/views/chat/chat-page.tsx+++ b/packages/views/chat/chat-page.tsx@@ -299,6 +299,7 @@ export function ChatPage() {<ChatQueuetasks={c.pendingTask?.queued_tasks ?? []}+ headStatus={c.pendingTask?.status}onSendNow={c.handleSendQueuedTaskNow}onEdit={c.handleEditQueuedTask}onRemove={c.handleRemoveQueuedTask}diff --git a/packages/views/chat/components/chat-column.test.tsx b/packages/views/chat/components/chat-column.test.tsxindex 0bec93f92b..1766c7a9f9 100644--- a/packages/views/chat/components/chat-column.test.tsx+++ b/packages/views/chat/components/chat-column.test.tsx@@ -71,6 +71,7 @@ describe("chat column geometry", () => {"follow-up queue",<ChatQueuekey="q"+ headStatus="running"tasks={[{task_id: "task-queued",diff --git a/packages/views/chat/components/chat-queue.test.tsx b/packages/views/chat/components/chat-queue.test.tsxindex 717742372a..e1301ed032 100644--- a/packages/views/chat/components/chat-queue.test.tsx+++ b/packages/views/chat/components/chat-queue.test.tsx@@ -6,7 +6,7 @@ import { ChatQueue } from "./chat-queue";const TEST_RESOURCES = { en: { chat: enChat } };-function renderQueue() {+function renderQueue(headStatus = "running") {const callbacks = {onSendNow: vi.fn<(taskId: string) => Promise<void>>().mockResolvedValue(),onEdit: vi.fn<(taskId: string) => Promise<void>>().mockResolvedValue(),@@ -16,6 +16,7 @@ function renderQueue() {const view = render(<I18nProvider locale="en" resources={TEST_RESOURCES}><ChatQueue+ headStatus={headStatus}tasks={[{task_id: "task-2",@@ -63,6 +64,17 @@ describe("ChatQueue", () => {await waitFor(() => expect(actions.onClear).toHaveBeenCalledTimes(1));});+ it("disables send-now until the current positional head is claimable", () => {+ const actions = renderQueue("queued");++ const buttons = screen.getAllByRole("button", {+ name: "Send now is available after the current reply starts",+ });+ expect(buttons).toHaveLength(2);+ for (const button of buttons) expect(button).toBeDisabled();+ expect(actions.onSendNow).not.toHaveBeenCalled();+ });+it("keeps long queues bounded and blocks duplicate actions while one is pending", async () => {let finishClear: (() => void) | undefined;const actions = renderQueue();diff --git a/packages/views/chat/components/chat-queue.tsx b/packages/views/chat/components/chat-queue.tsxindex cec805a4b3..8fbd4ba0de 100644--- a/packages/views/chat/components/chat-queue.tsx+++ b/packages/views/chat/components/chat-queue.tsx@@ -10,15 +10,27 @@ import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";interface ChatQueueProps {tasks: ChatQueuedTask[];+ headStatus: string | undefined;onSendNow: (taskId: string) => Promise<void> | void;onEdit: (taskId: string) => Promise<void> | void;onRemove: (taskId: string) => Promise<void> | void;onClear: () => Promise<void> | void;}-export function ChatQueue({ tasks, onSendNow, onEdit, onRemove, onClear }: ChatQueueProps) {+export function ChatQueue({+ tasks,+ headStatus,+ onSendNow,+ onEdit,+ onRemove,+ onClear,+}: ChatQueueProps) {const { t } = useT("chat");const [busyAction, setBusyAction] = useState<string | null>(null);+ const canSendNow =+ headStatus === "dispatched" ||+ headStatus === "running" ||+ headStatus === "waiting_local_directory";if (tasks.length === 0) return null;@@ -68,21 +80,31 @@ export function ChatQueue({ tasks, onSendNow, onEdit, onRemove, onClear }: ChatQ<span className="min-w-0 flex-1 truncate">{task.content?.trim() || t(($) => $.queue.fallback)}</span>- <Button- variant="ghost"- size="icon-xs"- className="shrink-0 text-muted-foreground"- disabled={busyAction !== null}- title={t(($) => $.queue.send_now)}- aria-label={t(($) => $.queue.send_now)}- onClick={() => void run(sendNowKey, () => onSendNow(task.task_id))}- >- {busyAction === sendNowKey ? (- <Loader2 className="animate-spin" aria-hidden="true" />- ) : (- <Send aria-hidden="true" />+ <span+ className="shrink-0"+ title={t(($) =>+ canSendNow ? $.queue.send_now : $.queue.send_now_unavailable)}- </Button>+ >+ <Button+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground"+ disabled={busyAction !== null || !canSendNow}+ aria-label={t(($) =>+ canSendNow+ ? $.queue.send_now+ : $.queue.send_now_unavailable+ )}+ onClick={() => void run(sendNowKey, () => onSendNow(task.task_id))}+ >+ {busyAction === sendNowKey ? (+ <Loader2 className="animate-spin" aria-hidden="true" />+ ) : (+ <Send aria-hidden="true" />+ )}+ </Button>+ </span><Buttonvariant="ghost"size="icon-xs"diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex f92d905f66..7770fe0659 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -534,6 +534,7 @@ export function ChatWindow() {message_id: result.message_id,content: finalContent,supports_queue: result.supports_queue,+ queued: result.queued,});// Cache primed → publish the new active session, but only if the user// hasn't navigated away mid-send. Compare the live store against the@@ -894,6 +895,7 @@ export function ChatWindow() {<ChatQueuetasks={pendingTask?.queued_tasks ?? []}+ headStatus={pendingTask?.status}onSendNow={handleSendQueuedTaskNow}onEdit={handleEditQueuedTask}onRemove={handleRemoveQueuedTask}diff --git a/packages/views/chat/components/task-status-pill.test.ts b/packages/views/chat/components/task-status-pill.test.tsindex 894019a3e1..2b15e9917f 100644--- a/packages/views/chat/components/task-status-pill.test.ts+++ b/packages/views/chat/components/task-status-pill.test.ts@@ -1,7 +1,25 @@import { describe, it, expect } from "vitest";-import { pickStageKeys } from "./task-status-pill";+import { effectiveTaskStatus, pickStageKeys } from "./task-status-pill";describe("pickStageKeys", () => {+ it("returns retrying while a deferred chat retry waits for backoff", () => {+ expect(pickStageKeys("deferred", [], "offline")).toEqual({ stageKey: "retrying" });+ });++ it("keeps deferred authoritative over task messages from the earlier attempt", () => {+ expect(+ effectiveTaskStatus("deferred", [+ {+ task_id: "task-1",+ issue_id: "",+ seq: 1,+ type: "thinking",+ created_at: "2026-07-01T00:00:00Z",+ },+ ]),+ ).toBe("deferred");+ });+it("returns queued when status is queued and agent is online", () => {expect(pickStageKeys("queued", [], "online")).toEqual({ stageKey: "queued" });});diff --git a/packages/views/chat/components/task-status-pill.tsx b/packages/views/chat/components/task-status-pill.tsxindex 2709f279bf..da74b5bd51 100644--- a/packages/views/chat/components/task-status-pill.tsx+++ b/packages/views/chat/components/task-status-pill.tsx@@ -25,6 +25,7 @@ interface Stage {type StageKey =| "offline"| "reconnecting"+ | "retrying"| "queued"| "waiting_local_directory"| "starting_up"@@ -62,6 +63,10 @@ export function pickStageKeys(taskMessages: readonly TaskMessagePayload[],availability: AgentAvailability | undefined,): { stageKey: StageKey; toolKey?: ToolKey; static?: boolean } {+ // A deferred chat task is an older turn waiting for its retry backoff, not+ // active model work. Keep this ahead of availability hints so the specific+ // retry state never degrades to a misleading queued/thinking label.+ if (status === "deferred") return { stageKey: "retrying" };if ((status === "queued" || status === "dispatched") &&availability === "offline"@@ -108,6 +113,16 @@ export function pickStageKeys(return { stageKey: "thinking" };}+export function effectiveTaskStatus(+ status: string | undefined,+ taskMessages: readonly TaskMessagePayload[],+): string | undefined {+ // A retry keeps the task's earlier stream history. Deferred is the newer,+ // server-authoritative state and must win over that stale running evidence.+ if (status === "deferred") return status;+ return taskMessages.length > 0 ? "running" : status;+}+function useResolveStage(): (status: string | undefined,taskMessages: readonly TaskMessagePayload[],@@ -155,10 +170,9 @@ export function TaskStatusPill({return () => clearInterval(timer);}, []);- // Effective status — defense-in-depth derive on top of the cache. If any- // task_message has streamed in, the daemon has by definition started- // running; we trust that observation over a stale cache.- const status = taskMessages.length > 0 ? "running" : pendingTask.status;+ // Effective status — streamed messages prove a task has started, except+ // when the server has since moved that same task into retry backoff.+ const status = effectiveTaskStatus(pendingTask.status, taskMessages);const elapsedSecs = Math.max(0, Math.floor((now - anchor) / 1000));const stage = resolveStage(status, taskMessages, availability);diff --git a/packages/views/chat/components/use-chat-controller.test.ts b/packages/views/chat/components/use-chat-controller.test.tsindex 5db09882ab..7ec97bafd9 100644--- a/packages/views/chat/components/use-chat-controller.test.ts+++ b/packages/views/chat/components/use-chat-controller.test.ts@@ -58,6 +58,49 @@ describe("hasInFlightPendingTask", () => {});describe("seedAcceptedPendingTask", () => {+ it("keeps an idle send as the current head instead of putting it in the queue", () => {+ const qc = new QueryClient();++ seedAcceptedPendingTask(qc, sid, {+ task_id: "task-1",+ created_at: "2026-07-08T00:00:00Z",+ message_id: "message-1",+ content: "accepted prompt",+ supports_queue: true,+ queued: false,+ });++ expect(qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(sid))).toMatchObject({+ task_id: "task-1",+ message_id: "message-1",+ queued_tasks: [],+ });+ });++ it("adds a server-confirmed follow-up behind the current head", () => {+ const qc = new QueryClient();+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sid), {+ task_id: "task-active",+ status: "running",+ created_at: "2026-07-08T00:00:00Z",+ queued_tasks: [],+ });++ seedAcceptedPendingTask(qc, sid, {+ task_id: "task-next",+ created_at: "2026-07-08T00:00:01Z",+ message_id: "message-next",+ content: "follow up",+ supports_queue: true,+ queued: true,+ });++ expect(qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(sid))).toMatchObject({+ task_id: "task-active",+ queued_tasks: [expect.objectContaining({ task_id: "task-next" })],+ });+ });+it("keeps a task dispatched before the send response and refetches authority", () => {const qc = new QueryClient();qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sid), {@@ -74,6 +117,7 @@ describe("seedAcceptedPendingTask", () => {message_id: "message-1",content: "accepted prompt",supports_queue: true,+ queued: false,});expect(qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(sid))).toEqual(diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex d221707b13..8a57ac1c68 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -164,6 +164,7 @@ export function seedAcceptedPendingTask(message_id: string;content: string;supports_queue?: boolean;+ queued?: boolean;},) {qc.setQueryData<ChatPendingTask>(@@ -175,7 +176,7 @@ export function seedAcceptedPendingTask(created_at: task.created_at,message_id: task.message_id,content: task.content,- });+ }, task.queued);if (task.supports_queue === true || old?.supports_queue === true) {next.supports_queue = true;}@@ -602,6 +603,7 @@ export function useChatController(opts?: { isActive?: boolean }) {message_id: result.message_id,content: finalContent,supports_queue: result.supports_queue,+ queued: result.queued,});// Cache primed → publish the new active session, but only if the user// hasn't navigated away mid-send. See isStillOnComposeTarget. commitInputdiff --git a/packages/views/chat/components/use-chat-task-actions.ts b/packages/views/chat/components/use-chat-task-actions.tsindex da861e66ee..dafbfbc8d5 100644--- a/packages/views/chat/components/use-chat-task-actions.ts+++ b/packages/views/chat/components/use-chat-task-actions.ts@@ -217,7 +217,11 @@ export function useChatTaskActions(sessionId: activeSessionId,err,});- toast.error(t(($) => $.queue.action_failed_toast));+ toast.error(+ err instanceof ApiError && err.status === 409+ ? t(($) => $.queue.send_now_unavailable_toast)+ : t(($) => $.queue.action_failed_toast),+ );} finally {qc.invalidateQueries({ queryKey: pendingKey });}diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex 3d61685455..c38edbb826 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -37,6 +37,8 @@"title_other": "{{count}} queued messages","clear": "Clear all","send_now": "Send now",+ "send_now_unavailable": "Send now is available after the current reply starts",+ "send_now_unavailable_toast": "Send now is unavailable. Refreshing the queue.","edit": "Edit queued message","remove": "Remove queued message","fallback": "Queued message",@@ -164,6 +166,7 @@"stages": {"offline": "Offline","reconnecting": "Reconnecting",+ "retrying": "Retrying","queued": "Queued","waiting_local_directory": "Waiting for local directory","starting_up": "Starting up",diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex 99e9296196..19e6f9e302 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -35,6 +35,8 @@"title_other": "キュー内のメッセージ {{count}} 件","clear": "すべて削除","send_now": "今すぐ送信",+ "send_now_unavailable": "現在の返信が開始されると今すぐ送信できます",+ "send_now_unavailable_toast": "今すぐ送信できません。キューを更新しています。","edit": "キュー内のメッセージを編集","remove": "キューから削除","fallback": "キュー内のメッセージ",@@ -160,6 +162,7 @@"stages": {"offline": "オフライン","reconnecting": "再接続中",+ "retrying": "再試行中","queued": "待機中","waiting_local_directory": "ローカルディレクトリを待機中","starting_up": "起動中",diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex 068ebee05f..b5aef857bb 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -35,6 +35,8 @@"title_other": "대기 중인 메시지 {{count}}개","clear": "모두 지우기","send_now": "지금 보내기",+ "send_now_unavailable": "현재 답변이 시작되면 지금 보낼 수 있습니다",+ "send_now_unavailable_toast": "지금 보낼 수 없습니다. 대기열을 새로 고치는 중입니다.","edit": "대기 중인 메시지 편집","remove": "대기열에서 삭제","fallback": "대기 중인 메시지",@@ -160,6 +162,7 @@"stages": {"offline": "오프라인","reconnecting": "다시 연결 중",+ "retrying": "재시도 중","queued": "대기 중","waiting_local_directory": "로컬 디렉터리 대기 중","starting_up": "시작 중",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex 3230252553..8e921bb08f 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -35,6 +35,8 @@"title_other": "{{count}} 条排队消息","clear": "全部清空","send_now": "立即发送",+ "send_now_unavailable": "当前回复开始后才能立即发送",+ "send_now_unavailable_toast": "暂时无法立即发送,正在刷新队列。","edit": "编辑排队消息","remove": "移除排队消息","fallback": "排队消息",@@ -160,6 +162,7 @@"stages": {"offline": "离线","reconnecting": "重连中",+ "retrying": "重试中","queued": "排队中","waiting_local_directory": "等待本地目录释放","starting_up": "启动中",diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex 95400e6afd..b9301487a6 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -688,6 +688,7 @@ type SendChatMessageResponse struct {MessageID string `json:"message_id"`TaskID string `json:"task_id"`SupportsQueue bool `json:"supports_queue"`+ Queued bool `json:"queued"`// AttachmentIDs are the attachment rows actually bound to this message by// the server. The client diffs these against the ids it requested so it// can warn the user when an attachment silently failed to bind — no extra@@ -869,6 +870,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {MessageID: uuidToString(msg.ID),TaskID: uuidToString(task.ID),SupportsQueue: true,+ Queued: sent.Queued,CreatedAt: timestampToString(task.CreatedAt),AttachmentIDs: boundAttachmentIDs,})@@ -1481,8 +1483,8 @@ func (h *Handler) GetPendingChatTask(w http.ResponseWriter, r *http.Request) {}head := tasks[0]- queued := make([]QueuedChatTaskResponse, 0, len(tasks))- for _, task := range tasks {+ queued := make([]QueuedChatTaskResponse, 0, len(tasks)-1)+ for _, task := range tasks[1:] {if task.Status != "queued" {continue}@@ -1543,6 +1545,21 @@ func (h *Handler) PrioritizeQueuedChatTask(w http.ResponseWriter, r *http.Requesdb.PrioritizeQueuedChatTaskParams{ID: taskID, ChatSessionID: session.ID},)if errors.Is(err, pgx.ErrNoRows) {+ // The compare-and-set rejects both a stale queue row and a still-valid+ // follow-up that has no claimed reply to replace. Distinguish them for+ // current clients while preserving the same 409 compatibility contract.+ queuedTask, loadErr := qtx.GetAgentTask(r.Context(), taskID)+ if loadErr != nil && !errors.Is(loadErr, pgx.ErrNoRows) {+ writeError(w, http.StatusInternalServerError, "failed to load queued task")+ return+ }+ if loadErr == nil &&+ queuedTask.Status == "queued" &&+ queuedTask.ChatSessionID.Valid &&+ uuidToString(queuedTask.ChatSessionID) == uuidToString(session.ID) {+ writeError(w, http.StatusConflict, "there is no active reply to replace")+ return+ }writeError(w, http.StatusConflict, "task is no longer queued")return}@@ -1568,7 +1585,7 @@ func (h *Handler) PrioritizeQueuedChatTask(w http.ResponseWriter, r *http.Reques}// ClearQueuedChatTasks cancels every queued follow-up without touching the-// task already running for the session.+// session's current positional head, even when that head is not claimed yet.func (h *Handler) ClearQueuedChatTasks(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {diff --git a/server/internal/handler/chat_pending_tasks_test.go b/server/internal/handler/chat_pending_tasks_test.goindex b8dc6708bb..f4c646d6ca 100644--- a/server/internal/handler/chat_pending_tasks_test.go+++ b/server/internal/handler/chat_pending_tasks_test.go@@ -317,14 +317,26 @@ func TestGetPendingChatTask_ReturnsActiveHeadAndFIFOQueue(t *testing.T) {}if resp.TaskID != laterID ||resp.Status != "queued" ||- len(resp.QueuedTasks) != 2 ||- resp.QueuedTasks[0].TaskID != laterID ||- resp.QueuedTasks[1].TaskID != nextID {- t.Fatalf("all queued prompts must remain in the dedicated queue: %+v", resp)+ len(resp.QueuedTasks) != 1 ||+ resp.QueuedTasks[0].TaskID != nextID {+ t.Fatalf("the first queued row must become the head, not a follow-up: %+v", resp)+ }++ transcript, err = testHandler.Queries.ListChatMessages(+ context.Background(),+ util.MustParseUUID(sessionID),+ )+ if err != nil {+ t.Fatalf("list transcript after head promotion: %v", err)+ }+ if len(transcript) != 2 ||+ transcript[0].Content != "active prompt" ||+ transcript[1].Content != "later prompt" {+ t.Fatalf("transcript must expose the queued-status head only: %+v", transcript)}}-func TestListChatMessagesPage_QueuedRowsDoNotConsumeLimit(t *testing.T) {+func TestListChatMessagesPage_QueuedFollowUpsDoNotConsumeLimit(t *testing.T) {if testHandler == nil {t.Skip("database not available")}@@ -365,27 +377,31 @@ func TestListChatMessagesPage_QueuedRowsDoNotConsumeLimit(t *testing.T) {}}- t.Log("PAGING FIXTURE: endpoint=GET /api/chat/sessions/{id}/messages/page settled=4 queued=3 limit=2")- t.Log("REQUEST page=1: limit=2 before=<none>")- page1 := fetchChatMessagesPageForTest(t, sessionID, url.Values{"limit": {"2"}})- if len(page1.Messages) != 2 || page1.Messages[0].Content != "settled 3" || page1.Messages[1].Content != "settled 4" || !page1.HasMore || page1.NextCursor == nil {+ t.Log("PAGING FIXTURE: endpoint=GET /api/chat/sessions/{id}/messages/page settled=4 head=1 follow_ups=2 limit=3")+ t.Log("REQUEST page=1: limit=3 before=<none>")+ page1 := fetchChatMessagesPageForTest(t, sessionID, url.Values{"limit": {"3"}})+ if len(page1.Messages) != 3 ||+ page1.Messages[0].Content != "settled 3" ||+ page1.Messages[1].Content != "settled 4" ||+ page1.Messages[2].Content != "queued prompt A" ||+ !page1.HasMore || page1.NextCursor == nil {t.Fatalf("unexpected first page: %+v", page1)}- t.Logf("RESPONSE page=1: messages=[%q, %q] has_more=%t", page1.Messages[0].Content, page1.Messages[1].Content, page1.HasMore)+ t.Logf("RESPONSE page=1: messages=[%q, %q, %q] has_more=%t", page1.Messages[0].Content, page1.Messages[1].Content, page1.Messages[2].Content, page1.HasMore)t.Logf("CURSOR page=1: created_at=%s id=%s", page1.NextCursor.CreatedAt, page1.NextCursor.ID)page2Params := url.Values{- "limit": {"2"},+ "limit": {"3"},"before_created_at": {page1.NextCursor.CreatedAt},"before_id": {page1.NextCursor.ID},}- t.Logf("REQUEST page=2: limit=2 before_created_at=%s before_id=%s", page1.NextCursor.CreatedAt, page1.NextCursor.ID)+ t.Logf("REQUEST page=2: limit=3 before_created_at=%s before_id=%s", page1.NextCursor.CreatedAt, page1.NextCursor.ID)page2 := fetchChatMessagesPageForTest(t, sessionID, page2Params)if len(page2.Messages) != 2 || page2.Messages[0].Content != "settled 1" || page2.Messages[1].Content != "settled 2" || page2.HasMore || page2.NextCursor != nil {t.Fatalf("unexpected second page: %+v", page2)}t.Logf("RESPONSE page=2: messages=[%q, %q] has_more=%t next_cursor=<nil>", page2.Messages[0].Content, page2.Messages[1].Content, page2.HasMore)- t.Log("ASSERTION: page_sizes=2,2 queued_visible=0 cursor_advanced=true duplicates=0")+ t.Log("ASSERTION: page_sizes=3,2 head_visible=1 follow_ups_visible=0 cursor_advanced=true duplicates=0")}func TestPendingQueueHeadMatchesClaimForEqualCreatedAt(t *testing.T) {@@ -463,6 +479,15 @@ func TestPrioritizeQueuedChatTask_StaleTargetPreservesExistingPriority(t *testinif w.Code != http.StatusConflict {t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())}+ var conflictBody struct {+ Error string `json:"error"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &conflictBody); err != nil {+ t.Fatalf("decode stale-task conflict: %v", err)+ }+ if conflictBody.Error != "task is no longer queued" {+ t.Fatalf("stale-task error = %q", conflictBody.Error)+ }var priority intif err := testPool.QueryRow(@@ -477,6 +502,58 @@ func TestPrioritizeQueuedChatTask_StaleTargetPreservesExistingPriority(t *testin}}+func TestPrioritizeQueuedChatTask_RejectsWhileVisibleHeadIsUnclaimed(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ agentID := createHandlerTestAgent(t, "UnclaimedPrioritizeQueueAgent", []byte("[]"))+ sessionID := createHandlerTestChatSession(t, agentID)+ headID := insertPendingChatTask(t, agentID, sessionID, "queued")+ targetID := insertPendingChatTask(t, agentID, sessionID, "queued")+ if _, err := testPool.Exec(ctx, `+ UPDATE agent_task_queue+ SET created_at = CASE id WHEN $1 THEN '2026-07-29T01:00:00Z'::timestamptz ELSE '2026-07-29T01:00:01Z'::timestamptz END+ WHERE id IN ($1, $2)+ `, headID, targetID); err != nil {+ t.Fatalf("order unclaimed queue: %v", err)+ }++ req := withURLParams(+ newRequestAs(+ testUserID,+ http.MethodPost,+ "/api/chat/sessions/"+sessionID+"/queued-tasks/"+targetID+"/prioritize",+ nil,+ ),+ "sessionId", sessionID,+ "taskId", targetID,+ )+ w := httptest.NewRecorder()+ testHandler.PrioritizeQueuedChatTask(w, chatPendingCtxAs(t, req, testUserID))+ if w.Code != http.StatusConflict {+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())+ }+ var conflictBody struct {+ Error string `json:"error"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &conflictBody); err != nil {+ t.Fatalf("decode unclaimed-head conflict: %v", err)+ }+ if conflictBody.Error != "there is no active reply to replace" {+ t.Fatalf("unclaimed-head error = %q", conflictBody.Error)+ }++ pending, err := testHandler.Queries.ListPendingChatTasksForSession(ctx, parseUUID(sessionID))+ if err != nil {+ t.Fatalf("list preserved queue: %v", err)+ }+ if len(pending) != 2 || uuidToString(pending[0].ID) != headID || uuidToString(pending[1].ID) != targetID {+ t.Fatalf("rejected prioritize changed queue order: %+v", pending)+ }+}+func TestPrioritizeQueuedChatTask_BroadcastsQueueInvalidation(t *testing.T) {if testHandler == nil {t.Skip("database not available")@@ -484,6 +561,7 @@ func TestPrioritizeQueuedChatTask_BroadcastsQueueInvalidation(t *testing.T) {agentID := createHandlerTestAgent(t, "PrioritizeQueueBroadcastAgent", []byte("[]"))sessionID := createHandlerTestChatSession(t, agentID)+ insertPendingChatTask(t, agentID, sessionID, "running")taskID := insertPendingChatTask(t, agentID, sessionID, "queued")got := make(chan events.Event, 1)testHandler.Bus.Subscribe(protocol.EventTaskQueued, func(event events.Event) {@@ -520,24 +598,32 @@ func TestPrioritizeQueuedChatTask_BroadcastsQueueInvalidation(t *testing.T) {}}-func TestClearQueuedChatTasks_CancelsWholeQueueAndDeletesInputs(t *testing.T) {+func TestClearQueuedChatTasks_PreservesUnclaimedHeadAndDeletesFollowUps(t *testing.T) {if testHandler == nil {t.Skip("database not available")}agentID := createHandlerTestAgent(t, "ClearPendingQueueAgent", []byte("[]"))sessionID := createHandlerTestChatSession(t, agentID)- var taskIDs, attachmentIDs []string+ var taskIDs, messageIDs, attachmentIDs []stringfor _, content := range []string{"queued prompt A", "queued prompt B"} {- taskID, _, attachmentID := insertQueuedChatInputWithAttachment(+ taskID, messageID, attachmentID := insertQueuedChatInputWithAttachment(t,agentID,sessionID,content,)taskIDs = append(taskIDs, taskID)+ messageIDs = append(messageIDs, messageID)attachmentIDs = append(attachmentIDs, attachmentID)}+ if _, err := testPool.Exec(context.Background(), `+ UPDATE agent_task_queue+ SET created_at = CASE id WHEN $1 THEN '2026-07-29T01:00:00Z'::timestamptz ELSE '2026-07-29T01:00:01Z'::timestamptz END+ WHERE id IN ($1, $2)+ `, taskIDs[0], taskIDs[1]); err != nil {+ t.Fatalf("order queued tasks: %v", err)+ }req := withURLParam(newRequestAs(@@ -555,28 +641,33 @@ func TestClearQueuedChatTasks_CancelsWholeQueueAndDeletesInputs(t *testing.T) {t.Fatalf("expected 204, got %d: %s", w.Code, w.Body.String())}- for _, taskID := range taskIDs {- if got := taskStatus(t, taskID); got != "cancelled" {- t.Fatalf("queued task %s status = %q, want cancelled", taskID, got)- }+ if got := taskStatus(t, taskIDs[0]); got != "queued" {+ t.Fatalf("unclaimed head status = %q, want queued", got)}- var inputCount int+ if got := taskStatus(t, taskIDs[1]); got != "cancelled" {+ t.Fatalf("queued follow-up status = %q, want cancelled", got)+ }+ var headInputExists, followUpInputExists boolif err := testPool.QueryRow(context.Background(), `- SELECT count(*) FROM chat_message WHERE task_id = $1 OR task_id = $2- `, taskIDs[0], taskIDs[1]).Scan(&inputCount); err != nil {- t.Fatalf("count queued inputs after clear: %v", err)+ SELECT+ EXISTS (SELECT 1 FROM chat_message WHERE id = $1),+ EXISTS (SELECT 1 FROM chat_message WHERE id = $2)+ `, messageIDs[0], messageIDs[1]).Scan(&headInputExists, &followUpInputExists); err != nil {+ t.Fatalf("read queued inputs after clear: %v", err)}- if inputCount != 0 {- t.Fatalf("clear left %d queued input messages", inputCount)+ if !headInputExists || followUpInputExists {+ t.Fatalf("queued inputs after clear: head=%t follow_up=%t, want true/false", headInputExists, followUpInputExists)}- var attachmentCount int+ var headAttachmentExists, followUpAttachmentExists boolif err := testPool.QueryRow(context.Background(), `- SELECT count(*) FROM attachment WHERE id = $1 OR id = $2- `, attachmentIDs[0], attachmentIDs[1]).Scan(&attachmentCount); err != nil {- t.Fatalf("count queued attachments after clear: %v", err)+ SELECT+ EXISTS (SELECT 1 FROM attachment WHERE id = $1),+ EXISTS (SELECT 1 FROM attachment WHERE id = $2)+ `, attachmentIDs[0], attachmentIDs[1]).Scan(&headAttachmentExists, &followUpAttachmentExists); err != nil {+ t.Fatalf("read queued attachments after clear: %v", err)}- if attachmentCount != 0 {- t.Fatalf("clear left %d discarded attachment rows", attachmentCount)+ if !headAttachmentExists || followUpAttachmentExists {+ t.Fatalf("queued attachments after clear: head=%t follow_up=%t, want true/false", headAttachmentExists, followUpAttachmentExists)}}@@ -633,6 +724,37 @@ func TestListPendingChatTasks_OwnerSeesPrivateAgentTask(t *testing.T) {}}+func TestPendingChatTaskAggregatesIncludeDeferredRetry(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ _, _, memberID := privateAgentTestFixture(t)+ publicAgentID := createHandlerTestAgent(t, "PendingDeferredAggregateAgent", []byte("[]"))+ sessionID := insertChatSessionAs(t, publicAgentID, memberID)+ taskID := insertPendingChatTask(t, publicAgentID, sessionID, "deferred")++ w := httptest.NewRecorder()+ testHandler.ListPendingChatTasks(w, chatPendingCtxAs(+ t,+ newRequestAs(memberID, "GET", "/api/chat/pending-tasks", nil),+ memberID,+ ))+ if resp := decodePendingTasks(t, w); !containsPendingTask(resp.Tasks, taskID) {+ t.Fatalf("deferred retry %s missing from pending aggregate: %+v", taskID, resp.Tasks)+ }++ w = httptest.NewRecorder()+ testHandler.HasPendingChatTasks(w, chatPendingCtxAs(+ t,+ newRequestAs(memberID, "GET", "/api/chat/pending-tasks/has-any", nil),+ memberID,+ ))+ if !decodeHasPending(t, w) {+ t.Fatal("has-any returned false for an accessible deferred retry")+ }+}+// TestHasPendingChatTasks_FalseWhenOnlyInaccessiblePrivateAgent verifies the P3// boolean endpoint preserves the same permission filtering as the list: a// member whose only in-flight task is on a private agent they can't accessdiff --git a/server/internal/handler/chat_test.go b/server/internal/handler/chat_test.goindex 877fc2e343..8342cb8f1b 100644--- a/server/internal/handler/chat_test.go+++ b/server/internal/handler/chat_test.go@@ -33,6 +33,104 @@ func withChatTestWorkspaceCtx(t *testing.T, req *http.Request) *http.Request {return req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, memberRow))}+func TestSendChatMessage_ReportsPositionInsteadOfQueuedStatus(t *testing.T) {+ agentID := createHandlerTestAgent(t, "ChatSendQueuePositionAgent", []byte("[]"))+ sessionID := createHandlerTestChatSession(t, agentID)++ send := func(content string) SendChatMessageResponse {+ t.Helper()+ req := newRequest("POST", "/api/chat-sessions/"+sessionID+"/messages", map[string]any{+ "content": content,+ })+ req = withURLParam(req, "sessionId", sessionID)+ req = withChatTestWorkspaceCtx(t, req)+ w := httptest.NewRecorder()+ testHandler.SendChatMessage(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("SendChatMessage: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var response SendChatMessageResponse+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {+ t.Fatalf("decode send response: %v", err)+ }+ return response+ }++ if first := send("first"); first.Queued {+ t.Fatal("idle session's first task must not be reported as a queued follow-up")+ }+ if second := send("second"); !second.Queued {+ t.Fatal("second task behind an in-flight head must be reported as queued")+ }+}++func TestSendChatMessage_DeferredPredecessorStaysHeadAcrossPromotion(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ agentID := createHandlerTestAgent(t, "ChatSendDeferredPositionAgent", []byte("[]"))+ sessionID := createHandlerTestChatSession(t, agentID)+ send := func(content string) SendChatMessageResponse {+ t.Helper()+ req := newRequest("POST", "/api/chat-sessions/"+sessionID+"/messages", map[string]any{+ "content": content,+ })+ req = withURLParam(req, "sessionId", sessionID)+ req = withChatTestWorkspaceCtx(t, req)+ w := httptest.NewRecorder()+ testHandler.SendChatMessage(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("SendChatMessage: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var response SendChatMessageResponse+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {+ t.Fatalf("decode send response: %v", err)+ }+ return response+ }++ predecessor := send("retrying prompt")+ if _, err := testPool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = 'deferred', priority = 3, fire_at = now() + interval '5 seconds'+ WHERE id = $1+ `, predecessor.TaskID); err != nil {+ t.Fatalf("defer predecessor: %v", err)+ }+ followUp := send("new prompt")+ if !followUp.Queued {+ t.Fatal("a send behind a deferred retry must be reported as queued")+ }++ assertStableHead := func(stage string) {+ t.Helper()+ pending, err := testHandler.Queries.ListPendingChatTasksForSession(ctx, parseUUID(sessionID))+ if err != nil {+ t.Fatalf("list pending tasks %s: %v", stage, err)+ }+ if len(pending) != 2 || uuidToString(pending[0].ID) != predecessor.TaskID || uuidToString(pending[1].ID) != followUp.TaskID {+ t.Fatalf("pending order %s = %+v, want deferred predecessor then follow-up", stage, pending)+ }+ messages, err := testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))+ if err != nil {+ t.Fatalf("list transcript %s: %v", stage, err)+ }+ if len(messages) != 1 || messages[0].Content != "retrying prompt" {+ t.Fatalf("transcript %s exposed queued follow-up: %+v", stage, messages)+ }+ }+ assertStableHead("while deferred")++ if _, err := testPool.Exec(ctx, `+ UPDATE agent_task_queue SET status = 'queued', fire_at = NULL WHERE id = $1+ `, predecessor.TaskID); err != nil {+ t.Fatalf("promote deferred predecessor: %v", err)+ }+ assertStableHead("after promotion")+}+// TestSendChatMessage_LinksAttachments verifies that attachments uploaded// against a chat_session (chat_message_id NULL) are back-filled with the// message_id when SendChatMessage receives the matching attachment_ids.diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 87ac8bdbc3..021c39d4a2 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1718,6 +1718,7 @@ type DirectChatSendResult struct {Task db.AgentTaskQueueMessage db.ChatMessageBoundAttachmentIDs []pgtype.UUID+ Queued bool}// SendDirectChatMessage atomically persists one web/mobile direct-chat turn:@@ -1779,6 +1780,18 @@ func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.Chatreturn ErrChatTaskAgentNoRuntime}+ // The database status of every newly-created task is "queued" until a+ // daemon claims it. Product queue semantics are positional instead: this+ // send is a follow-up only when another visible task in the same session+ // is already ahead of it. Deferred retries count because they resume an+ // older turn before this one. The session + agent locks serialize sibling+ // sends, retries, terminal writes, and claims around this read.+ queued, err := qtx.HasPendingChatTurnForSession(ctx, session.ID)+ if err != nil {+ return fmt.Errorf("check direct chat queue position: %w", err)+ }+ out.Queued = queued+task, err := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{AgentID: session.AgentID,RuntimeID: carrier.RuntimeID,diff --git a/server/migrations/255_agent_task_queue_chat_pending_deferred_v3.down.sql b/server/migrations/255_agent_task_queue_chat_pending_deferred_v3.down.sqlnew file mode 100644index 0000000000..71bdfbc7db--- /dev/null+++ b/server/migrations/255_agent_task_queue_chat_pending_deferred_v3.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_chat_pending_v3;diff --git a/server/migrations/255_agent_task_queue_chat_pending_deferred_v3.up.sql b/server/migrations/255_agent_task_queue_chat_pending_deferred_v3.up.sqlnew file mode 100644index 0000000000..42d95ad20c--- /dev/null+++ b/server/migrations/255_agent_task_queue_chat_pending_deferred_v3.up.sql@@ -0,0 +1,16 @@+-- Extend the pending-chat partial index to deferred retries (MUL-5750).+--+-- The session pending endpoint now treats a deferred retry as a visible head,+-- and the workspace FAB aggregate must use the same in-flight status set.+-- Migration 143's v2 predicate covers only the four immediately runnable or+-- claimed statuses, so PostgreSQL cannot use it for the five-status aggregate.+--+-- Build v3 before dropping v2 so old and new server versions both retain a+-- usable index throughout a rolling deploy. The old four-status queries are a+-- subset of this predicate and can use v3 safely. This file stays a single+-- statement because CREATE INDEX CONCURRENTLY cannot run in a transaction or+-- a multi-command string.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_chat_pending_v3+ ON agent_task_queue (chat_session_id, created_at DESC)+ WHERE chat_session_id IS NOT NULL+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred');diff --git a/server/migrations/256_drop_agent_task_queue_chat_pending_v2.down.sql b/server/migrations/256_drop_agent_task_queue_chat_pending_v2.down.sqlnew file mode 100644index 0000000000..6872c2e0b0--- /dev/null+++ b/server/migrations/256_drop_agent_task_queue_chat_pending_v2.down.sql@@ -0,0 +1,5 @@+-- Recreate v2 before migration 255's down step removes v3.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_chat_pending_v2+ ON agent_task_queue (chat_session_id, created_at DESC)+ WHERE chat_session_id IS NOT NULL+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory');diff --git a/server/migrations/256_drop_agent_task_queue_chat_pending_v2.up.sql b/server/migrations/256_drop_agent_task_queue_chat_pending_v2.up.sqlnew file mode 100644index 0000000000..42c9de927e--- /dev/null+++ b/server/migrations/256_drop_agent_task_queue_chat_pending_v2.up.sql@@ -0,0 +1,5 @@+-- Drop the superseded four-status partial index after v3 is available.+--+-- Kept separate from migration 254 so both files contain exactly one+-- concurrent index statement and no rollout window is left without coverage.+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_chat_pending_v2;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex ed70da7f89..178f2ebee1 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -983,13 +983,35 @@ func (q *Queries) CancelQueuedAgentTask(ctx context.Context, arg CancelQueuedAge}const cancelQueuedAgentTasksForSession = `-- name: CancelQueuedAgentTasksForSession :many-UPDATE agent_task_queue+WITH head AS MATERIALIZED (+ SELECT candidate.id+ FROM agent_task_queue AS candidate+ WHERE candidate.chat_session_id = $1+ AND candidate.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND candidate.regenerate_quick_actions_for IS NULL+ ORDER BY+ CASE+ WHEN candidate.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN candidate.status = 'deferred' THEN 1+ ELSE 2+ END,+ candidate.priority DESC,+ candidate.created_at ASC,+ candidate.id ASC+ LIMIT 1+)+UPDATE agent_task_queue AS queuedSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL-WHERE chat_session_id = $1- 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+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`+// Clear only positional follow-ups. The first visible task is current even+// when it has not been claimed yet, so an all-queued session must preserve its+// priority/FIFO head. Keep this selector in lockstep with the visible-head+// invariant documented above ListChatMessages in chat.sql.func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSessionID pgtype.UUID) ([]AgentTaskQueue, error) {rows, err := q.db.Query(ctx, cancelQueuedAgentTasksForSession, chatSessionID)if err != nil {diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex fa5f221919..68480f7d61 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -950,7 +950,7 @@ SELECT EXISTS (FROM agent_task_queue atqJOIN chat_session cs ON cs.id = atq.chat_session_idWHERE atq.chat_session_id IS NOT NULL- AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-- Background quick-actions regeneration passes own no visible turn and must-- never light the FAB "running" indicator (MUL-5149 refresh follow-up).AND atq.regenerate_quick_actions_for IS NULL@@ -982,6 +982,27 @@ func (q *Queries) HasPendingChatTasksByCreator(ctx context.Context, arg HasPendireturn has_pending, err}+const hasPendingChatTurnForSession = `-- name: HasPendingChatTurnForSession :one+SELECT EXISTS (+ SELECT 1 FROM agent_task_queue+ WHERE chat_session_id = $1+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND regenerate_quick_actions_for IS NULL+) AS has_pending+`++// Position-only check for a direct send. Unlike GetPendingChatTask this is an+// EXISTS query and includes deferred retries: a new user turn must remain a+// follow-up while an older retry waits for its backoff, otherwise promotion of+// that retry would make the new message disappear from the visible transcript.+// Background quick-action regeneration owns no visible turn and is excluded.+func (q *Queries) HasPendingChatTurnForSession(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {+ row := q.db.QueryRow(ctx, hasPendingChatTurnForSession, chatSessionID)+ var has_pending bool+ err := row.Scan(&has_pending)+ return has_pending, err+}+const linkChatMessageToTask = `-- name: LinkChatMessageToTask :execUPDATE chat_messageSET task_id = $2@@ -1332,11 +1353,39 @@ WHERE message.chat_session_id = $1WHERE task.chat_session_id = message.chat_session_idAND task.status = 'queued'AND task.id = message.task_id+ -- "Queued follow-up" is positional, not the row's transient status:+ -- the first pending task is the current turn even before claim.+ AND task.id <> (+ SELECT head.id+ FROM agent_task_queue AS head+ WHERE head.chat_session_id = $1+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND head.regenerate_quick_actions_for IS NULL+ ORDER BY+ CASE+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN head.status = 'deferred' THEN 1+ ELSE 2+ END,+ head.priority DESC,+ head.created_at ASC,+ head.id ASC+ LIMIT 1+ )))ORDER BY message.created_at ASC, message.id ASC`+// IMPORTANT: the visible-head selector below is also used by+// ListChatMessagesForLegacyTask, ListChatMessagesPage,+// ListPendingChatTasksForSession, and CancelQueuedAgentTasksForSession in+// agent.sql. Keep the eligible statuses and ordering identical: a claimed task+// is current, a deferred retry precedes still-queued work, and queued peers use+// claim priority/FIFO order. Background quick-action regeneration is invisible.+// This is a presentation/visibility order, not a scheduling guarantee:+// deferred rows are not claimable before promotion, so a queued row may be+// claimed during the backoff and then becomes the visible claimed head.func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUID) ([]ChatMessage, error) {rows, err := q.db.Query(ctx, listChatMessages, chatSessionID)if err != nil {@@ -1381,6 +1430,23 @@ WHERE message.chat_session_id = $1WHERE task.chat_session_id = message.chat_session_idAND task.status = 'queued'AND task.id = message.task_id+ AND task.id <> (+ SELECT head.id+ FROM agent_task_queue AS head+ WHERE head.chat_session_id = $1+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND head.regenerate_quick_actions_for IS NULL+ ORDER BY+ CASE+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN head.status = 'deferred' THEN 1+ ELSE 2+ END,+ head.priority DESC,+ head.created_at ASC,+ head.id ASC+ LIMIT 1+ )))ORDER BY message.created_at ASC, message.id ASC@@ -1432,6 +1498,23 @@ WHERE message.chat_session_id = $1WHERE task.chat_session_id = message.chat_session_idAND task.status = 'queued'AND task.id = message.task_id+ AND task.id <> (+ SELECT head.id+ FROM agent_task_queue AS head+ WHERE head.chat_session_id = $1+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND head.regenerate_quick_actions_for IS NULL+ ORDER BY+ CASE+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN head.status = 'deferred' THEN 1+ ELSE 2+ END,+ head.priority DESC,+ head.created_at ASC,+ head.id ASC+ LIMIT 1+ )))AND (@@ -1591,7 +1674,7 @@ SELECT atq.id AS task_id, atq.status, atq.chat_session_id, cs.agent_idFROM agent_task_queue atqJOIN chat_session cs ON cs.id = atq.chat_session_idWHERE atq.chat_session_id IS NOT NULL- AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-- Exclude background quick-actions regeneration passes: they own no assistant-- turn and must not surface as "running" chat work (MUL-5149 refresh follow-up).AND atq.regenerate_quick_actions_for IS NULL@@ -1622,7 +1705,7 @@ type ListPendingChatTasksByCreatorRow struct {//// atq.chat_session_id IS NOT NULL is redundant given the JOIN, but stated// explicitly so the planner can prove the query predicate is a subset of the-// idx_agent_task_queue_chat_pending_v2 partial-index predicate and use it.+// idx_agent_task_queue_chat_pending_v3 partial-index predicate and use it.func (q *Queries) ListPendingChatTasksByCreator(ctx context.Context, arg ListPendingChatTasksByCreatorParams) ([]ListPendingChatTasksByCreatorRow, error) {rows, err := q.db.Query(ctx, listPendingChatTasksByCreator, arg.WorkspaceID, arg.CreatorID)if err != nil {@@ -1665,10 +1748,14 @@ LEFT JOIN LATERAL (LIMIT 1) AS message ON TRUEWHERE task.chat_session_id = $1- AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')AND task.regenerate_quick_actions_for IS NULLORDER BY- CASE WHEN task.status = 'queued' THEN 1 ELSE 0 END,+ CASE+ WHEN task.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN task.status = 'deferred' THEN 1+ ELSE 2+ END,task.priority DESC,task.created_at ASC,task.id ASC@@ -1682,7 +1769,10 @@ type ListPendingChatTasksForSessionRow struct {Content string `json:"content"`}-// Returns the active task first, followed by prioritized then FIFO follow-ups.+// Returns a claimed task first, then a deferred retry, followed by prioritized+// then FIFO queued work. See the shared visible-head invariant above+// ListChatMessages; changing this order requires changing every selector named+// there in the same patch.// The message lateral join reads only the immutable input owned by each task;// it avoids loading the session's complete message history just to render a// one-line queue preview. GetPendingChatTask remains for legacy callers that@@ -1929,6 +2019,16 @@ WITH target AS MATERIALIZED (WHERE candidate.id = $2AND candidate.chat_session_id = $1AND candidate.status = 'queued'+ -- "Send now" is valid only while there is a visible claimed task for the+ -- client to cancel. If the visible head is still queued (or deferred), the+ -- selected row would otherwise replace it without any active_task_id.+ AND EXISTS (+ SELECT 1+ FROM agent_task_queue AS active+ WHERE active.chat_session_id = $1+ AND active.status IN ('dispatched', 'running', 'waiting_local_directory')+ AND active.regenerate_quick_actions_for IS NULL+ )FOR UPDATE), demoted AS (UPDATE agent_task_queue AS queued@@ -1952,6 +2052,7 @@ SELECTFROM agent_task_queue AS activeWHERE active.chat_session_id = $1AND active.status IN ('dispatched', 'running', 'waiting_local_directory')+ AND active.regenerate_quick_actions_for IS NULLORDER BY active.created_at ASC, active.id ASCLIMIT 1)::uuid AS active_task_iddiff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex f4e452d943..4456e088ca 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1073,11 +1073,33 @@ WHERE id = sqlc.arg('id')RETURNING *;-- name: CancelQueuedAgentTasksForSession :many-UPDATE agent_task_queue+-- Clear only positional follow-ups. The first visible task is current even+-- when it has not been claimed yet, so an all-queued session must preserve its+-- priority/FIFO head. Keep this selector in lockstep with the visible-head+-- invariant documented above ListChatMessages in chat.sql.+WITH head AS MATERIALIZED (+ SELECT candidate.id+ FROM agent_task_queue AS candidate+ WHERE candidate.chat_session_id = $1+ AND candidate.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND candidate.regenerate_quick_actions_for IS NULL+ ORDER BY+ CASE+ WHEN candidate.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN candidate.status = 'deferred' THEN 1+ ELSE 2+ END,+ candidate.priority DESC,+ candidate.created_at ASC,+ candidate.id ASC+ LIMIT 1+)+UPDATE agent_task_queue AS queuedSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL-WHERE chat_session_id = $1- AND status = 'queued'-RETURNING *;+WHERE queued.chat_session_id = $1+ AND queued.status = 'queued'+ AND queued.id IS DISTINCT FROM (SELECT id FROM head)+RETURNING queued.*;-- name: MarkChatFinalizeDeferred :one-- Arms the deferred chat-finalize marker for a cancelled chat task whosediff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex c4b59361be..b3e9086461 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -449,6 +449,15 @@ WHERE task_id = $1 AND role = 'user'RETURNING *;-- name: ListChatMessages :many+-- IMPORTANT: the visible-head selector below is also used by+-- ListChatMessagesForLegacyTask, ListChatMessagesPage,+-- ListPendingChatTasksForSession, and CancelQueuedAgentTasksForSession in+-- agent.sql. Keep the eligible statuses and ordering identical: a claimed task+-- is current, a deferred retry precedes still-queued work, and queued peers use+-- claim priority/FIFO order. Background quick-action regeneration is invisible.+-- This is a presentation/visibility order, not a scheduling guarantee:+-- deferred rows are not claimable before promotion, so a queued row may be+-- claimed during the backoff and then becomes the visible claimed head.SELECT message.* FROM chat_message AS messageWHERE message.chat_session_id = $1AND NOT (@@ -459,6 +468,25 @@ WHERE message.chat_session_id = $1WHERE task.chat_session_id = message.chat_session_idAND task.status = 'queued'AND task.id = message.task_id+ -- "Queued follow-up" is positional, not the row's transient status:+ -- the first pending task is the current turn even before claim.+ AND task.id <> (+ SELECT head.id+ FROM agent_task_queue AS head+ WHERE head.chat_session_id = $1+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND head.regenerate_quick_actions_for IS NULL+ ORDER BY+ CASE+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN head.status = 'deferred' THEN 1+ ELSE 2+ END,+ head.priority DESC,+ head.created_at ASC,+ head.id ASC+ LIMIT 1+ )))ORDER BY message.created_at ASC, message.id ASC;@@ -476,6 +504,23 @@ WHERE message.chat_session_id = $1WHERE task.chat_session_id = message.chat_session_idAND task.status = 'queued'AND task.id = message.task_id+ AND task.id <> (+ SELECT head.id+ FROM agent_task_queue AS head+ WHERE head.chat_session_id = $1+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND head.regenerate_quick_actions_for IS NULL+ ORDER BY+ CASE+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN head.status = 'deferred' THEN 1+ ELSE 2+ END,+ head.priority DESC,+ head.created_at ASC,+ head.id ASC+ LIMIT 1+ )))ORDER BY message.created_at ASC, message.id ASC;@@ -503,6 +548,23 @@ WHERE message.chat_session_id = $1WHERE task.chat_session_id = message.chat_session_idAND task.status = 'queued'AND task.id = message.task_id+ AND task.id <> (+ SELECT head.id+ FROM agent_task_queue AS head+ WHERE head.chat_session_id = $1+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND head.regenerate_quick_actions_for IS NULL+ ORDER BY+ CASE+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN head.status = 'deferred' THEN 1+ ELSE 2+ END,+ head.priority DESC,+ head.created_at ASC,+ head.id ASC+ LIMIT 1+ )))AND (@@ -665,6 +727,19 @@ SELECT EXISTS (AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')) AS has_active;+-- name: HasPendingChatTurnForSession :one+-- Position-only check for a direct send. Unlike GetPendingChatTask this is an+-- EXISTS query and includes deferred retries: a new user turn must remain a+-- follow-up while an older retry waits for its backoff, otherwise promotion of+-- that retry would make the new message disappear from the visible transcript.+-- Background quick-action regeneration owns no visible turn and is excluded.+SELECT EXISTS (+ SELECT 1 FROM agent_task_queue+ WHERE chat_session_id = $1+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND regenerate_quick_actions_for IS NULL+) AS has_pending;+-- name: GetPendingChatTask :one-- Returns the most recent in-flight task for a chat session, if any.-- Used by the frontend to recover pending state after refresh / reopen.@@ -681,7 +756,10 @@ ORDER BY created_at DESCLIMIT 1;-- name: ListPendingChatTasksForSession :many--- Returns the active task first, followed by prioritized then FIFO follow-ups.+-- Returns a claimed task first, then a deferred retry, followed by prioritized+-- then FIFO queued work. See the shared visible-head invariant above+-- ListChatMessages; changing this order requires changing every selector named+-- there in the same patch.-- The message lateral join reads only the immutable input owned by each task;-- it avoids loading the session's complete message history just to render a-- one-line queue preview. GetPendingChatTask remains for legacy callers that@@ -702,10 +780,14 @@ LEFT JOIN LATERAL (LIMIT 1) AS message ON TRUEWHERE task.chat_session_id = $1- AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')AND task.regenerate_quick_actions_for IS NULLORDER BY- CASE WHEN task.status = 'queued' THEN 1 ELSE 0 END,+ CASE+ WHEN task.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0+ WHEN task.status = 'deferred' THEN 1+ ELSE 2+ END,task.priority DESC,task.created_at ASC,task.id ASC;@@ -717,6 +799,16 @@ WITH target AS MATERIALIZED (WHERE candidate.id = sqlc.arg('id')AND candidate.chat_session_id = sqlc.arg('chat_session_id')AND candidate.status = 'queued'+ -- "Send now" is valid only while there is a visible claimed task for the+ -- client to cancel. If the visible head is still queued (or deferred), the+ -- selected row would otherwise replace it without any active_task_id.+ AND EXISTS (+ SELECT 1+ FROM agent_task_queue AS active+ WHERE active.chat_session_id = sqlc.arg('chat_session_id')+ AND active.status IN ('dispatched', 'running', 'waiting_local_directory')+ AND active.regenerate_quick_actions_for IS NULL+ )FOR UPDATE), demoted AS (UPDATE agent_task_queue AS queued@@ -740,6 +832,7 @@ SELECTFROM agent_task_queue AS activeWHERE active.chat_session_id = sqlc.arg('chat_session_id')AND active.status IN ('dispatched', 'running', 'waiting_local_directory')+ AND active.regenerate_quick_actions_for IS NULLORDER BY active.created_at ASC, active.id ASCLIMIT 1)::uuid AS active_task_id@@ -756,12 +849,12 @@ FROM prioritized;---- atq.chat_session_id IS NOT NULL is redundant given the JOIN, but stated-- explicitly so the planner can prove the query predicate is a subset of the--- idx_agent_task_queue_chat_pending_v2 partial-index predicate and use it.+-- idx_agent_task_queue_chat_pending_v3 partial-index predicate and use it.SELECT atq.id AS task_id, atq.status, atq.chat_session_id, cs.agent_idFROM agent_task_queue atqJOIN chat_session cs ON cs.id = atq.chat_session_idWHERE atq.chat_session_id IS NOT NULL- AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-- Exclude background quick-actions regeneration passes: they own no assistant-- turn and must not surface as "running" chat work (MUL-5149 refresh follow-up).AND atq.regenerate_quick_actions_for IS NULL@@ -784,7 +877,7 @@ SELECT EXISTS (FROM agent_task_queue atqJOIN chat_session cs ON cs.id = atq.chat_session_idWHERE atq.chat_session_id IS NOT NULL- AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-- Background quick-actions regeneration passes own no visible turn and must-- never light the FAB "running" indicator (MUL-5149 refresh follow-up).AND atq.regenerate_quick_actions_for IS NULL