Skip to content

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

Go

MUL-5570 / MUL-5493: feat(chat): add a managed follow-up queue (#6211)

TeAmoa4dc54f2eda8
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
index 474c3424bf..36caa1de52 100644
--- a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
@@ -45,6 +45,10 @@ import type {
ChatMessage,
ChatPendingTask,
} from "@multica/core/types";
+import {
+ hideQueuedChatMessages,
+ removePendingChatTask,
+} from "@multica/core/chat/pending";
import { api } from "@/data/api";
import { useAuthStore } from "@/data/auth-store";
import { useWorkspaceStore } from "@/data/workspace-store";
@@ -68,6 +72,10 @@ import {
} from "@/data/stores/chat-drafts-store";
import { useChatSessionPickerStore } from "@/data/stores/chat-session-picker-store";
import { useChatSessionRealtime } from "@/data/realtime/use-chat-session-realtime";
+import {
+ invalidatePendingTask,
+ seedAcceptedPendingTask,
+} from "@/data/realtime/chat-ws-updaters";
import { canAssignAgent } from "@/lib/can-assign-agent";
import { useWorkspaceAgentAvailability } from "@/lib/workspace-agent-availability";
import { useAgentPresence } from "@/lib/use-agent-presence";
@@ -133,6 +141,7 @@ export default function ChatTab() {
const { data: pendingTask } = useQuery(
pendingChatTaskOptions(activeSessionId),
);
+ const visibleMessages = hideQueuedChatMessages(messages, pendingTask);
// Live execution trace for the in-flight task. `task:message` WS events
// append rows to this same cache key via `appendTaskMessage`, so the
// list/pill stay in sync without a polling fetch. `enabled` is gated by
@@ -287,10 +296,11 @@ export default function ChatTab() {
const result = await api.sendChatMessage(sessionId, content, {
attachmentIds: attachmentIds.length > 0 ? attachmentIds : undefined,
});
- qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {
+ seedAcceptedPendingTask(qc, {
+ chat_session_id: sessionId,
task_id: result.task_id,
- status: "queued",
created_at: result.created_at,
+ supports_queue: result.supports_queue,
});
qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
if (options.clearDraft !== false) {
@@ -318,11 +328,18 @@ export default function ChatTab() {
// ── Cancel in-flight ───────────────────────────────────────────────────
const handleStop = useCallback(() => {
if (!pendingTask?.task_id || !activeSessionId) return;
- qc.setQueryData(chatKeys.pendingTask(activeSessionId), {});
- void api.cancelTaskById(pendingTask.task_id).catch(() => {
- // Silent — task may have already terminated server-side.
- });
- }, [pendingTask?.task_id, activeSessionId, qc]);
+ if (pendingTask.status === "queued") return;
+ const taskId = pendingTask.task_id;
+ const sessionId = activeSessionId;
+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), (old) =>
+ removePendingChatTask(old, taskId),
+ );
+ void api.cancelTaskById(taskId)
+ .catch(() => {
+ // Silent — task may have already terminated server-side.
+ })
+ .finally(() => invalidatePendingTask(qc, sessionId));
+ }, [pendingTask?.task_id, pendingTask?.status, activeSessionId, qc]);
// ── Header / sheet actions ─────────────────────────────────────────────
const handleNewChat = useCallback(() => {
@@ -415,7 +432,7 @@ export default function ChatTab() {
className="flex-1"
>
<ChatMessageList
- messages={messages}
+ messages={visibleMessages}
loading={messagesLoading}
hasSessions={sessions.length > 0}
agentName={currentAgent?.name}
@@ -442,6 +459,7 @@ export default function ChatTab() {
onSend={handleSend}
onStop={handleStop}
sending={sending}
+ allowStop={pendingTask?.status !== "queued"}
disabled={disabled}
disabledReason={disabledReason}
/>
diff --git a/apps/mobile/components/chat/chat-composer.tsx b/apps/mobile/components/chat/chat-composer.tsx
index c4e154108c..994e4ce386 100644
--- a/apps/mobile/components/chat/chat-composer.tsx
+++ b/apps/mobile/components/chat/chat-composer.tsx
@@ -50,6 +50,8 @@ interface Props {
/** True while an agent task is running for the active session. The
* composer swaps Send for Stop. */
sending: boolean;
+ /** Queued tasks remain busy, but do not expose Stop without draft restore. */
+ allowStop?: boolean;
/** Hard-disable typing + send. Used when there's no usable agent in the
* workspace or the session is archived (legacy). */
disabled?: boolean;
@@ -65,6 +67,7 @@ export function ChatComposer({
onSend,
onStop,
sending,
+ allowStop = true,
disabled = false,
disabledReason,
}: Props) {
@@ -113,7 +116,7 @@ export function ChatComposer({
disabled={disabled}
disabledReason={disabledReason}
isSending={sending}
- renderStop={() => <StopButton onPress={handleStop} />}
+ renderStop={allowStop ? () => <StopButton onPress={handleStop} /> : undefined}
manageKeyboard={false}
/>
);
diff --git a/apps/mobile/data/chat-schema.test.ts b/apps/mobile/data/chat-schema.test.ts
new file mode 100644
index 0000000000..201d48fcc5
--- /dev/null
+++ b/apps/mobile/data/chat-schema.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import { ChatPendingTaskSchema } from "./schemas";
+
+describe("ChatPendingTaskSchema", () => {
+ it("keeps the pending head and valid queue rows when one row is malformed", () => {
+ const parsed = ChatPendingTaskSchema.parse({
+ task_id: "task-active",
+ status: "running",
+ queued_tasks: [
+ {
+ task_id: "task-next",
+ status: "queued",
+ created_at: "2026-08-03T00:00:00Z",
+ },
+ { status: "queued" },
+ ],
+ });
+
+ expect(parsed.task_id).toBe("task-active");
+ expect(parsed.queued_tasks).toEqual([
+ {
+ task_id: "task-next",
+ status: "queued",
+ created_at: "2026-08-03T00:00:00Z",
+ },
+ ]);
+ });
+});
diff --git a/apps/mobile/data/queries/chat.ts b/apps/mobile/data/queries/chat.ts
index 6b8e2e1b4f..a1b8f07432 100644
--- a/apps/mobile/data/queries/chat.ts
+++ b/apps/mobile/data/queries/chat.ts
@@ -5,7 +5,7 @@
* - sessions(wsId) → ChatSession[] for the workspace dropdown / sheet
* - messages(sessionId) → ChatMessage[] for the active session
* - pendingTask(sessionId)→ ChatPendingTask, populated when an agent task is
- * in flight; cleared on chat:done / task:cancelled
+ * in flight; refreshed on terminal task events
*
* Same shape as web's `chatKeys` in packages/core/chat/queries.ts (mobile
* owns its own copy per the "mirror, don't import" rule in apps/mobile/CLAUDE.md).
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.test.ts b/apps/mobile/data/realtime/chat-ws-updaters.test.ts
index 480a270591..a2be9ea1b9 100644
--- a/apps/mobile/data/realtime/chat-ws-updaters.test.ts
+++ b/apps/mobile/data/realtime/chat-ws-updaters.test.ts
@@ -3,6 +3,7 @@ import { QueryClient, QueryObserver } from "@tanstack/react-query";
import type {
ChatDonePayload,
ChatMessage,
+ ChatPendingTask,
ChatQuickActionsPayload,
} from "@multica/core/types";
@@ -14,6 +15,9 @@ vi.mock("@/data/api", () => ({ api: {} }));
import {
applyChatDoneToCache,
applyChatQuickActionsToCache,
+ promotePendingTaskToRunning,
+ seedAcceptedPendingTask,
+ seedPendingTaskFromQueued,
} from "./chat-ws-updaters";
import { chatKeys } from "@/data/queries/chat";
@@ -50,8 +54,9 @@ describe("applyChatDoneToCache", () => {
expect(invalidate).toHaveBeenCalledWith({
queryKey: chatKeys.messages(SESSION),
});
- // pendingTask cleared so the status pill unmounts.
- expect(qc.getQueryData(chatKeys.pendingTask(SESSION))).toEqual({});
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.pendingTask(SESSION),
+ });
});
it("invalidates even when the payload lacks an inline message (legacy shape)", () => {
@@ -100,6 +105,90 @@ describe("applyChatDoneToCache", () => {
});
});
+describe("pending task queue events", () => {
+ it("keeps dispatch state when the send response arrives later", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION), {
+ task_id: "task-1",
+ status: "queued",
+ created_at: "2026-07-09T00:00:00Z",
+ });
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ promotePendingTaskToRunning(qc, {
+ task_id: "task-1",
+ agent_id: "agent-1",
+ issue_id: "",
+ runtime_id: "runtime-1",
+ chat_session_id: SESSION,
+ });
+ seedAcceptedPendingTask(qc, {
+ chat_session_id: SESSION,
+ task_id: "task-1",
+ created_at: "2026-07-09T00:00:01Z",
+ });
+
+ expect(qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION))).toMatchObject({
+ task_id: "task-1",
+ status: "running",
+ });
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.pendingTask(SESSION),
+ });
+ });
+
+ it("does not replace an active head with a sparse follow-up queued event", () => {
+ const qc = new QueryClient();
+ const active: ChatPendingTask = {
+ task_id: "task-active",
+ status: "running",
+ created_at: "2026-07-09T00:00:00Z",
+ };
+ qc.setQueryData(chatKeys.pendingTask(SESSION), active);
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ seedPendingTaskFromQueued(qc, {
+ task_id: "task-follow-up",
+ agent_id: "agent-1",
+ issue_id: "",
+ chat_session_id: SESSION,
+ status: "queued",
+ });
+
+ expect(qc.getQueryData(chatKeys.pendingTask(SESSION))).toEqual(active);
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.pendingTask(SESSION),
+ });
+ });
+
+ it("refetches pending state and messages when a task is dispatched", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(SESSION), {
+ task_id: "task-active",
+ status: "running",
+ });
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ promotePendingTaskToRunning(qc, {
+ task_id: "task-follow-up",
+ agent_id: "agent-1",
+ issue_id: "",
+ runtime_id: "runtime-1",
+ chat_session_id: SESSION,
+ });
+
+ expect(qc.getQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(SESSION),
+ )?.task_id).toBe("task-active");
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.pendingTask(SESSION),
+ });
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.messages(SESSION),
+ });
+ });
+});
+
function assistantMsg(over: Partial<ChatMessage> = {}): ChatMessage {
return {
id: "msg-1",
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.ts
index e76561a5c4..adfa31b76e 100644
--- a/apps/mobile/data/realtime/chat-ws-updaters.ts
+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts
@@ -20,6 +20,7 @@
* - chatKeys.pendingTask(sessionId)→ ChatPendingTask (empty `{}` = no in-flight)
*/
import type { QueryClient } from "@tanstack/react-query";
+import { enqueuePendingChatTask } from "@multica/core/chat/pending";
import type {
ChatDonePayload,
ChatMessage,
@@ -150,9 +151,9 @@ export function applyChatDoneToCache(
qc.invalidateQueries({
queryKey: chatKeys.messages(payload.chat_session_id),
});
- // Clear in-flight pointer in the same tick so StatusPill unmounts and
- // the AssistantMessage owns the rendering.
- qc.setQueryData(chatKeys.pendingTask(payload.chat_session_id), {});
+ // A queued successor may already exist. Refetch the server-authoritative
+ // head instead of clearing it and briefly presenting the session as idle.
+ invalidatePendingTask(qc, payload.chat_session_id);
}
/**
@@ -210,14 +211,9 @@ export function seedPendingTaskFromQueued(
payload: TaskQueuedPayload,
) {
if (!payload.chat_session_id) return;
- qc.setQueryData<ChatPendingTask>(
- chatKeys.pendingTask(payload.chat_session_id),
- (old) => ({
- ...(old ?? {}),
- task_id: payload.task_id,
- status: "queued",
- }),
- );
+ // A follow-up can be queued while another task is active. The event does
+ // not carry enough queue state to replace that active head safely.
+ invalidatePendingTask(qc, payload.chat_session_id);
}
export function promotePendingTaskToRunning(
@@ -234,13 +230,52 @@ export function promotePendingTaskToRunning(
return { ...old, status: "running" };
},
);
+ invalidatePendingTask(qc, payload.chat_session_id);
+ qc.invalidateQueries({
+ queryKey: chatKeys.messages(payload.chat_session_id),
+ });
}
-export function clearPendingTask(
+export function invalidatePendingTask(
qc: QueryClient,
sessionId: string,
) {
- qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
+}
+
+export function seedAcceptedPendingTask(
+ qc: QueryClient,
+ payload: {
+ chat_session_id: string;
+ task_id: string;
+ created_at: string;
+ supports_queue?: boolean;
+ },
+) {
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(payload.chat_session_id),
+ (old) => {
+ const task = {
+ task_id: payload.task_id,
+ status: "queued",
+ created_at: payload.created_at,
+ };
+ 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);
+ if (payload.supports_queue === true || old?.supports_queue === true) {
+ next.supports_queue = true;
+ }
+ return next;
+ },
+ );
+ invalidatePendingTask(qc, payload.chat_session_id);
}
// =====================================================
diff --git a/apps/mobile/data/realtime/use-chat-session-realtime.ts b/apps/mobile/data/realtime/use-chat-session-realtime.ts
index 60f539701d..2c36228588 100644
--- a/apps/mobile/data/realtime/use-chat-session-realtime.ts
+++ b/apps/mobile/data/realtime/use-chat-session-realtime.ts
@@ -8,15 +8,15 @@
*
* Events handled:
* - chat:message → invalidate messages + pendingTask
- * - chat:done → patch messages inline + clear pendingTask
+ * - chat:done → patch messages inline + refresh pendingTask
* - chat:quick_actions → patch the async quick-actions supplement
* onto the assistant message
* - task:queued / dispatch → seed / promote pendingTask
- * - task:cancelled → clear pendingTask
+ * - task:cancelled → refresh pendingTask + messages
* - task:completed → no-op for messages (chat:done already
* wrote the assistant message); just
- * defensive clear of pendingTask
- * - task:failed → clear pendingTask + invalidate messages
+ * refresh pendingTask
+ * - task:failed → refresh pendingTask + invalidate messages
* (FailTask persists a failure assistant
* message that must show up)
* - chat:session_deleted → fire onSessionDeleted() so the screen
@@ -31,7 +31,7 @@ import {
appendTaskMessage,
applyChatDoneToCache,
applyChatQuickActionsToCache,
- clearPendingTask,
+ invalidatePendingTask,
promotePendingTaskToRunning,
seedPendingTaskFromQueued,
} from "./chat-ws-updaters";
@@ -84,20 +84,18 @@ export function useChatSessionRealtime(
}),
ws.on("task:cancelled", (payload) => {
if (!isMine(payload)) return;
- clearPendingTask(qc, sessionId);
+ invalidatePendingTask(qc, sessionId);
+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
}),
ws.on("task:completed", (payload) => {
if (!isMine(payload)) return;
- // `chat:done` already wrote the assistant message and cleared
- // pendingTask. Defensive clear in case the two events arrive
- // out of order on a flaky network.
- clearPendingTask(qc, sessionId);
+ invalidatePendingTask(qc, sessionId);
}),
ws.on("task:failed", (payload) => {
if (!isMine(payload)) return;
// FailTask persists a destructive assistant message — surface it
- // by refetching messages and clearing the pending pill.
- clearPendingTask(qc, sessionId);
+ // and recover any queued successor from the authoritative endpoint.
+ invalidatePendingTask(qc, sessionId);
qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
}),
ws.on("chat:session_deleted", (payload) => {
diff --git a/apps/mobile/data/realtime/use-chat-sessions-realtime.ts b/apps/mobile/data/realtime/use-chat-sessions-realtime.ts
index 9b8a85b244..b338ee4030 100644
--- a/apps/mobile/data/realtime/use-chat-sessions-realtime.ts
+++ b/apps/mobile/data/realtime/use-chat-sessions-realtime.ts
@@ -30,6 +30,9 @@ export function useChatSessionsRealtime() {
// chat:done flips `has_unread` server-side; refetch so the dot shows
// even when the user isn't in the chat screen.
ws.on("chat:done", invalidateSessions),
+ // Cancellation may delete a queued prompt or append "Stopped.", both
+ // of which change the session preview.
+ ws.on("task:cancelled", invalidateSessions),
// chat:session_read clears the unread flag (could be triggered from
// web/desktop on the same account).
ws.on("chat:session_read", invalidateSessions),
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index 6f35d5cfae..a522762132 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -294,11 +294,30 @@ export const ChatMessageListSchema = z.array(ChatMessageSchema).default([]);
export const EMPTY_CHAT_MESSAGE_LIST: ChatMessage[] = [];
-// All fields optional — server returns an empty object when no in-flight task.
+const ChatQueuedTaskSchema = z.object({
+ task_id: z.string(),
+ status: z.string().default("queued"),
+ created_at: z.string().default(""),
+ message_id: z.string().optional(),
+ content: z.string().optional(),
+}).loose();
+
+const ChatQueuedTasksSchema = z.array(z.unknown()).transform((tasks) =>
+ tasks.flatMap((task) => {
+ const parsed = ChatQueuedTaskSchema.safeParse(task);
+ return parsed.success ? [parsed.data] : [];
+ }),
+);
+
+// All root fields are optional — server returns an empty object when no
+// task is in flight. Ignore malformed queue rows without discarding a valid
+// head, matching packages/core/api/schemas.ts.
export const ChatPendingTaskSchema: z.ZodType<ChatPendingTask> = z.object({
task_id: z.string().optional(),
status: z.string().optional(),
created_at: z.string().optional(),
+ supports_queue: z.boolean().optional(),
+ queued_tasks: ChatQueuedTasksSchema.optional(),
}).loose();
export const EMPTY_CHAT_PENDING_TASK: ChatPendingTask = {};
@@ -306,6 +325,7 @@ export const EMPTY_CHAT_PENDING_TASK: ChatPendingTask = {};
export const SendChatMessageResponseSchema: z.ZodType<SendChatMessageResponse> = z.object({
message_id: z.string(),
task_id: z.string(),
+ supports_queue: z.boolean().optional(),
created_at: z.string().default(""),
}).loose();
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index d79a1d165a..a3ef58c9e9 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -1399,6 +1399,26 @@ describe("ApiClient", () => {
expect(init.headers["X-Client-Capabilities"]).toBe(CHAT_DRAFT_RESTORE_CAPABILITY);
});
+ it("scopes queued edit cancellation to the expected chat session", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(taskResponse), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await new ApiClient("https://api.example.test").cancelTaskById("task-1", {
+ queuedAction: "edit",
+ sessionId: "session-1",
+ });
+
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(
+ "https://api.example.test/api/tasks/task-1/cancel" +
+ "?expected_status=queued&chat_session_id=session-1&queue_action=edit",
+ );
+ });
+
it("treats a null cancelled chat message as absent", async () => {
vi.stubGlobal(
"fetch",
@@ -1454,6 +1474,18 @@ describe("ApiClient", () => {
});
});
+ it("clears a chat queue with one session-scoped request", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await new ApiClient("https://api.example.test").clearQueuedChatTasks("session-1");
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://api.example.test/api/chat/sessions/session-1/queued-tasks",
+ expect.objectContaining({ method: "DELETE" }),
+ );
+ });
+
describe("chat attachment wiring", () => {
it("uploadFile includes chat_session_id in the FormData body", async () => {
const fetchMock = vi.fn().mockResolvedValue(
@@ -1520,7 +1552,7 @@ describe("ApiClient", () => {
it("sendChatMessage serialises attachment_ids onto the JSON body when present", async () => {
const fetchMock = vi.fn().mockResolvedValue(
- new Response(JSON.stringify({ message_id: "m1", task_id: "t1", created_at: "" }), {
+ new Response(JSON.stringify({ message_id: "m1", task_id: "t1", created_at: "2026-08-01T00:00:00Z" }), {
status: 201,
headers: { "Content-Type": "application/json" },
}),
@@ -1540,7 +1572,7 @@ describe("ApiClient", () => {
it("sendChatMessage omits attachment_ids when the list is empty or undefined", async () => {
const fetchMock = vi.fn().mockImplementation(() =>
Promise.resolve(
- new Response(JSON.stringify({ message_id: "m1", task_id: "t1", created_at: "" }), {
+ new Response(JSON.stringify({ message_id: "m1", task_id: "t1", created_at: "2026-08-01T00:00:00Z" }), {
status: 201,
headers: { "Content-Type": "application/json" },
}),
@@ -1555,6 +1587,43 @@ describe("ApiClient", () => {
expect(JSON.parse(fetchMock.mock.calls[0]![1]?.body as string)).toEqual({ content: "hello" });
expect(JSON.parse(fetchMock.mock.calls[1]![1]?.body as string)).toEqual({ content: "again" });
});
+
+ it("sendChatMessage accepts the server's null attachment_ids for text-only sends", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({
+ message_id: "m1",
+ task_id: "t1",
+ created_at: "2026-08-01T00:00:00Z",
+ attachment_ids: null,
+ }), {
+ status: 201,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+
+ await expect(
+ new ApiClient("https://api.example.test").sendChatMessage("session-1", "hello"),
+ ).resolves.toMatchObject({ attachment_ids: undefined });
+ });
+
+ it("sendChatMessage rejects a malformed response", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ message_id: "m1", task_id: 42 }), {
+ status: 201,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+
+ await expect(
+ new ApiClient("https://api.example.test").sendChatMessage("session-1", "hello"),
+ ).rejects.toThrow();
+ });
});
});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 44c418ecb2..e0b5f7b021 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -90,6 +90,7 @@ import type {
ChatMessagesPage,
ChatDraftRestoresResponse,
ChatPendingTask,
+ PrioritizeQueuedChatTaskResponse,
PendingChatTasksResponse,
HasPendingChatTasksResponse,
SendChatMessageResponse,
@@ -191,6 +192,9 @@ import {
ChatDraftRestoresResponseSchema,
ChatMessageListSchema,
ChatMessagesPageSchema,
+ ChatPendingTaskSchema,
+ PrioritizeQueuedChatTaskResponseSchema,
+ SendChatMessageResponseSchema,
ChildIssuesResponseSchema,
CommentsListSchema,
CommentTriggerPreviewSchema,
@@ -214,6 +218,8 @@ import {
EMPTY_APP_CONFIG,
EMPTY_ATTACHMENT,
EMPTY_CHAT_MESSAGE_LIST,
+ EMPTY_CHAT_PENDING_TASK,
+ EMPTY_PRIORITIZE_QUEUED_CHAT_TASK_RESPONSE,
EMPTY_CLOUD_RUNTIME_NODE,
EMPTY_CLOUD_RUNTIME_NODE_LIST,
EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE,
@@ -2418,14 +2424,47 @@ export class ApiClient {
if (attachmentIds && attachmentIds.length > 0) {
body.attachment_ids = attachmentIds;
}
- return this.fetch(`/api/chat/sessions/${sessionId}/messages`, {
+ const raw = await this.fetch<unknown>(`/api/chat/sessions/${sessionId}/messages`, {
method: "POST",
body: JSON.stringify(body),
});
+ const response = parseWithFallback<SendChatMessageResponse | null>(
+ raw,
+ SendChatMessageResponseSchema,
+ null,
+ { endpoint: "POST /api/chat/sessions/:id/messages" },
+ );
+ if (!response) throw new Error("invalid send chat message response");
+ return response;
}
async getPendingChatTask(sessionId: string): Promise<ChatPendingTask> {
- return this.fetch(`/api/chat/sessions/${sessionId}/pending-task`);
+ const raw = await this.fetch<unknown>(`/api/chat/sessions/${sessionId}/pending-task`);
+ return parseWithFallback(raw, ChatPendingTaskSchema, EMPTY_CHAT_PENDING_TASK, {
+ endpoint: "GET /api/chat/sessions/:id/pending-task",
+ });
+ }
+
+ async prioritizeQueuedChatTask(
+ sessionId: string,
+ taskId: string,
+ ): Promise<PrioritizeQueuedChatTaskResponse> {
+ const raw = await this.fetch<unknown>(
+ `/api/chat/sessions/${sessionId}/queued-tasks/${taskId}/prioritize`,
+ { method: "POST" },
+ );
+ return parseWithFallback(
+ raw,
+ PrioritizeQueuedChatTaskResponseSchema,
+ EMPTY_PRIORITIZE_QUEUED_CHAT_TASK_RESPONSE,
+ { endpoint: "POST /api/chat/sessions/:id/queued-tasks/:taskId/prioritize" },
+ );
+ }
+
+ async clearQueuedChatTasks(sessionId: string): Promise<void> {
+ await this.fetch(`/api/chat/sessions/${sessionId}/queued-tasks`, {
+ method: "DELETE",
+ });
}
/**
@@ -2471,8 +2510,19 @@ export class ApiClient {
// defers the empty-transcript judgment — and therefore only withholds the
// synchronous restore from the response — for clients that send this; without
// it we would be treated as a pre-#5219 client and get the legacy behaviour.
- async cancelTaskById(taskId: string): Promise<CancelTaskResponse> {
- const raw = await this.fetch<unknown>(`/api/tasks/${taskId}/cancel`, {
+ async cancelTaskById(
+ taskId: string,
+ options?: { queuedAction?: "edit" | "remove"; sessionId?: string },
+ ): Promise<CancelTaskResponse> {
+ const params = new URLSearchParams();
+ if (options?.queuedAction) {
+ if (!options.sessionId) throw new Error("sessionId is required for queued-only cancellation");
+ params.set("expected_status", "queued");
+ params.set("chat_session_id", options.sessionId);
+ params.set("queue_action", options.queuedAction);
+ }
+ const query = params.size > 0 ? `?${params}` : "";
+ const raw = await this.fetch<unknown>(`/api/tasks/${taskId}/cancel${query}`, {
method: "POST",
headers: { "X-Client-Capabilities": CHAT_DRAFT_RESTORE_CAPABILITY },
});
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 7225e1d16c..28d574db98 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -11,9 +11,13 @@ import {
DashboardUsageByAgentListSchema,
DashboardUsageDailyListSchema,
ChatDraftRestoresResponseSchema,
+ ChatPendingTaskSchema,
+ PrioritizeQueuedChatTaskResponseSchema,
CreateFeedbackResponseSchema,
DuplicateIssueErrorBodySchema,
EMPTY_CHAT_DRAFT_RESTORES,
+ EMPTY_CHAT_PENDING_TASK,
+ EMPTY_PRIORITIZE_QUEUED_CHAT_TASK_RESPONSE,
EMPTY_CREATE_FEEDBACK_RESPONSE,
EMPTY_INBOX_ITEMS,
EMPTY_INBOX_UNREAD_SUMMARY,
@@ -410,6 +414,97 @@ describe("ChatDraftRestoresResponseSchema", () => {
});
});
+describe("ChatPendingTaskSchema", () => {
+ const ENDPOINT = { endpoint: "GET /api/chat/sessions/:id/pending-task" };
+
+ it("keeps legacy responses compatible when queued_tasks is absent", () => {
+ const parsed = parseWithFallback(
+ {
+ task_id: "task-active",
+ status: "running",
+ created_at: "2026-07-01T00:00:00Z",
+ },
+ ChatPendingTaskSchema,
+ EMPTY_CHAT_PENDING_TASK,
+ ENDPOINT,
+ );
+
+ expect(parsed).toMatchObject({
+ task_id: "task-active",
+ status: "running",
+ });
+ expect(parsed.queued_tasks).toBeUndefined();
+ });
+
+ it("parses queued task summaries", () => {
+ const parsed = ChatPendingTaskSchema.parse({
+ task_id: "task-active",
+ status: "running",
+ queued_tasks: [
+ {
+ task_id: "task-queued",
+ status: "queued",
+ content: "Follow up after the current task",
+ created_at: "2026-07-01T00:01:00Z",
+ },
+ ],
+ });
+
+ expect(parsed.queued_tasks).toEqual([
+ expect.objectContaining({
+ task_id: "task-queued",
+ content: "Follow up after the current task",
+ }),
+ ]);
+ });
+
+ it("keeps a valid head and ignores only malformed queued rows", () => {
+ const parsed = parseWithFallback(
+ {
+ task_id: "task-active",
+ queued_tasks: [{ task_id: 42, status: "queued" }],
+ },
+ ChatPendingTaskSchema,
+ EMPTY_CHAT_PENDING_TASK,
+ ENDPOINT,
+ );
+
+ expect(parsed).toEqual({
+ task_id: "task-active",
+ queued_tasks: [],
+ });
+ });
+});
+
+describe("PrioritizeQueuedChatTaskResponseSchema", () => {
+ const ENDPOINT = {
+ endpoint: "POST /api/chat/sessions/:id/queued-tasks/:taskId/prioritize",
+ };
+
+ it("parses the prioritized task id", () => {
+ expect(
+ PrioritizeQueuedChatTaskResponseSchema.parse({
+ task_id: "task-queued",
+ active_task_id: "task-active",
+ }),
+ ).toEqual({
+ task_id: "task-queued",
+ active_task_id: "task-active",
+ });
+ });
+
+ it("falls back when task_id is malformed", () => {
+ expect(
+ parseWithFallback(
+ { task_id: 42 },
+ PrioritizeQueuedChatTaskResponseSchema,
+ EMPTY_PRIORITIZE_QUEUED_CHAT_TASK_RESPONSE,
+ ENDPOINT,
+ ),
+ ).toBe(EMPTY_PRIORITIZE_QUEUED_CHAT_TASK_RESPONSE);
+ });
+});
+
describe("CreateFeedbackResponseSchema", () => {
const ENDPOINT = { endpoint: "POST /api/feedback" };
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 9231d4396a..3f07525a55 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -17,6 +17,9 @@ import type {
CancelTaskResponse,
ChatMessage,
ChatDraftRestoresResponse,
+ ChatPendingTask,
+ PrioritizeQueuedChatTaskResponse,
+ SendChatMessageResponse,
Comment,
CreateAgentFromTemplateResponse,
CreateBillingCheckoutSessionResponse,
@@ -1232,6 +1235,51 @@ export const ChatDraftRestoresResponseSchema = z.object({
restores: z.array(ChatDraftRestoreSchema).default([]),
}).loose();
+const ChatQueuedTaskSchema = z.object({
+ task_id: z.string(),
+ status: z.string().default("queued"),
+ created_at: z.string().default(""),
+ message_id: z.string().optional(),
+ content: z.string().optional(),
+}).loose();
+
+const ChatQueuedTasksSchema = z.array(z.unknown()).transform((tasks) =>
+ tasks.flatMap((task) => {
+ const parsed = ChatQueuedTaskSchema.safeParse(task);
+ return parsed.success ? [parsed.data] : [];
+ }),
+);
+
+// Root fields retain the legacy single-task response shape. Keep additive
+// fields optional so callers can distinguish an older server from an empty
+// queue. A malformed queue row is ignored without discarding a valid head.
+export const ChatPendingTaskSchema: z.ZodType<ChatPendingTask> = z.object({
+ task_id: z.string().optional(),
+ status: z.string().optional(),
+ created_at: z.string().optional(),
+ supports_queue: z.boolean().optional(),
+ queued_tasks: ChatQueuedTasksSchema.optional(),
+}).loose();
+
+export const EMPTY_CHAT_PENDING_TASK: ChatPendingTask = {};
+
+export const SendChatMessageResponseSchema: z.ZodType<SendChatMessageResponse> = z.object({
+ message_id: z.string().min(1),
+ task_id: z.string().min(1),
+ supports_queue: z.boolean().optional(),
+ created_at: z.string().min(1),
+ attachment_ids: z.array(z.string()).nullish().transform((ids) => ids ?? undefined),
+}).loose();
+
+export const PrioritizeQueuedChatTaskResponseSchema:
+ z.ZodType<PrioritizeQueuedChatTaskResponse> = z.object({
+ task_id: z.string(),
+ active_task_id: z.string().optional(),
+ }).loose();
+
+export const EMPTY_PRIORITIZE_QUEUED_CHAT_TASK_RESPONSE:
+ PrioritizeQueuedChatTaskResponse = { task_id: "" };
+
export const EMPTY_CHAT_DRAFT_RESTORES: ChatDraftRestoresResponse = {
restores: [],
};
diff --git a/packages/core/api/ws-client.test.ts b/packages/core/api/ws-client.test.ts
index 25e2e82bf0..91dbac0f46 100644
--- a/packages/core/api/ws-client.test.ts
+++ b/packages/core/api/ws-client.test.ts
@@ -387,6 +387,20 @@ describe("WSClient", () => {
expect(lastTimerDelay()).toBe(1000);
});
+ it("notifies reconnect when the initial connection succeeds only after a retry", () => {
+ const ws = new WSClient("ws://example.test/ws");
+ ws.setAuth("tok", "acme");
+ const onReconnect = vi.fn();
+ ws.onReconnect(onReconnect);
+ ws.connect();
+
+ simulateDisconnect();
+ vi.runOnlyPendingTimers();
+ simulateAuthAck();
+
+ expect(onReconnect).toHaveBeenCalledTimes(1);
+ });
+
it("keeps retrying indefinitely with capped delay", () => {
vi.stubGlobal(
"Math",
diff --git a/packages/core/api/ws-client.ts b/packages/core/api/ws-client.ts
index f4fb086c5b..6d47b957b2 100644
--- a/packages/core/api/ws-client.ts
+++ b/packages/core/api/ws-client.ts
@@ -181,8 +181,9 @@ export class WSClient {
private onAuthenticated() {
this.logger.info("connected");
+ const recoveredConnection = this.hasConnectedBefore || this.reconnectAttempt > 0;
this.reconnectAttempt = 0;
- if (this.hasConnectedBefore) {
+ if (recoveredConnection) {
for (const cb of this.onReconnectCallbacks) {
try {
cb();
diff --git a/packages/core/chat/pending.test.ts b/packages/core/chat/pending.test.ts
new file mode 100644
index 0000000000..af87732965
--- /dev/null
+++ b/packages/core/chat/pending.test.ts
@@ -0,0 +1,265 @@
+import { describe, expect, it } from "vitest";
+import {
+ enqueuePendingChatTask,
+ hideQueuedChatMessages,
+ prioritizePendingChatTask,
+ promotePendingChatTask,
+ removePendingChatTask,
+} from "./pending";
+
+const task = (task_id: string, created_at: string) => ({
+ task_id,
+ status: "queued",
+ created_at,
+ content: `message ${task_id}`,
+});
+
+describe("pending chat queue", () => {
+ it("keeps the active task at the head and follow-ups in FIFO order", () => {
+ const active = { ...task("active", "2026-01-01T00:00:00Z"), status: "running" };
+ const withLater = enqueuePendingChatTask(active, task("later", "2026-01-01T00:00:02Z"));
+ const result = enqueuePendingChatTask(withLater, task("next", "2026-01-01T00:00:01Z"));
+
+ expect(result.task_id).toBe("active");
+ 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", () => {
+ 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(promotePendingChatTask(pending, "next", "running").queued_tasks).toEqual([]);
+ });
+
+ it("keeps a send response preview when a sparse queued event arrives later", () => {
+ const current = {
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ queued_tasks: [
+ {
+ ...task("next", "2026-01-01T00:00:01Z"),
+ message_id: "message-next",
+ content: "Keep this visible preview",
+ },
+ ],
+ };
+
+ const result = enqueuePendingChatTask(current, {
+ task_id: "next",
+ status: "queued",
+ created_at: "2026-01-01T00:00:03Z",
+ });
+
+ expect(result.queued_tasks).toEqual([
+ expect.objectContaining({
+ task_id: "next",
+ created_at: "2026-01-01T00:00:01Z",
+ message_id: "message-next",
+ content: "Keep this visible preview",
+ }),
+ ]);
+ });
+
+ it("enriches a sparse queued event when the send response arrives later", () => {
+ const current = {
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ queued_tasks: [{
+ task_id: "next",
+ status: "queued",
+ created_at: "2026-01-01T00:00:01Z",
+ }],
+ };
+
+ const result = enqueuePendingChatTask(current, {
+ ...task("next", "2026-01-01T00:00:01Z"),
+ message_id: "message-next",
+ content: "Visible accepted prompt",
+ });
+
+ expect(result.queued_tasks).toEqual([
+ expect.objectContaining({
+ task_id: "next",
+ message_id: "message-next",
+ content: "Visible accepted prompt",
+ }),
+ ]);
+ });
+
+ it("does not downgrade a dispatched task when its send response arrives later", () => {
+ const current = {
+ ...task("first", "2026-01-01T00:00:00Z"),
+ status: "dispatched",
+ queued_tasks: [],
+ };
+
+ const result = enqueuePendingChatTask(current, {
+ ...task("first", "2026-01-01T00:00:00Z"),
+ message_id: "message-first",
+ content: "Keep the accepted prompt",
+ });
+
+ expect(result).toEqual(expect.objectContaining({
+ task_id: "first",
+ status: "dispatched",
+ message_id: "message-first",
+ content: "Keep the accepted prompt",
+ queued_tasks: [],
+ }));
+ });
+
+ it("promotes a queued task without losing later work", () => {
+ const current = {
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ supports_queue: true,
+ queued_tasks: [
+ task("next", "2026-01-01T00:00:01Z"),
+ task("later", "2026-01-01T00:00:02Z"),
+ ],
+ };
+
+ const result = promotePendingChatTask(current, "next", "running");
+ expect(result.task_id).toBe("next");
+ expect(result.status).toBe("running");
+ expect(result.supports_queue).toBe(true);
+ expect(result.queued_tasks?.map((item) => item.task_id)).toEqual(["later"]);
+ });
+
+ it("ignores a stale dispatch for an unknown task while another task is active", () => {
+ const current = {
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ queued_tasks: [task("next", "2026-01-01T00:00:01Z")],
+ };
+
+ expect(promotePendingChatTask(current, "stale", "running")).toBe(current);
+ });
+
+ it("does not resurrect an unknown task after the pending query cleared", () => {
+ expect(promotePendingChatTask(undefined, "stale", "running")).toEqual({});
+ expect(promotePendingChatTask({ supports_queue: true }, "stale", "running")).toEqual({
+ supports_queue: true,
+ });
+ });
+
+ it("removes only the selected queued task", () => {
+ const current = {
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ queued_tasks: [task("next", "2026-01-01T00:00:01Z")],
+ };
+
+ expect(removePendingChatTask(current, "next")).toEqual({
+ ...current,
+ queued_tasks: [],
+ });
+ });
+
+ it("promotes the first queued task when the active task finishes", () => {
+ const current = {
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ supports_queue: true,
+ queued_tasks: [
+ task("next", "2026-01-01T00:00:01Z"),
+ task("later", "2026-01-01T00:00:02Z"),
+ ],
+ };
+
+ 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"]);
+ });
+
+ it("keeps queued prompts out of the settled transcript", () => {
+ const messages = [
+ {
+ id: "message-active",
+ chat_session_id: "session",
+ role: "user" as const,
+ content: "active",
+ task_id: "active",
+ created_at: "2026-01-01T00:00:00Z",
+ },
+ {
+ id: "message-next",
+ chat_session_id: "session",
+ role: "user" as const,
+ content: "next",
+ task_id: "next",
+ created_at: "2026-01-01T00:00:01Z",
+ },
+ ];
+ const pending = {
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ queued_tasks: [{ ...task("next", "2026-01-01T00:00:01Z"), message_id: "message-next" }],
+ };
+
+ expect(hideQueuedChatMessages(messages, pending)).toEqual([messages[0]]);
+ const waiting = removePendingChatTask(pending, "active");
+ expect(hideQueuedChatMessages(messages, waiting)).toEqual([messages[0]]);
+ expect(
+ hideQueuedChatMessages(messages, promotePendingChatTask(waiting, "next", "running")),
+ ).toEqual(
+ messages,
+ );
+ });
+
+ it("keeps a queued retry's historical root prompt in the transcript", () => {
+ const root = {
+ id: "message-root",
+ chat_session_id: "session",
+ role: "user" as const,
+ content: "retry this",
+ task_id: "task-root",
+ created_at: "2026-01-01T00:00:00Z",
+ };
+ const pending = {
+ ...task("task-retry", "2026-01-01T00:00:01Z"),
+ queued_tasks: [{
+ ...task("task-retry", "2026-01-01T00:00:01Z"),
+ message_id: root.id,
+ }],
+ };
+
+ expect(hideQueuedChatMessages([root], pending)).toEqual([root]);
+ });
+
+ it("moves a send-now task to the front without disturbing the remaining queue", () => {
+ const current = {
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ queued_tasks: [
+ task("next", "2026-01-01T00:00:01Z"),
+ task("send-now", "2026-01-01T00:00:02Z"),
+ task("later", "2026-01-01T00:00:03Z"),
+ ],
+ };
+
+ expect(
+ prioritizePendingChatTask(current, "send-now").queued_tasks?.map((item) => item.task_id),
+ ).toEqual(["send-now", "next", "later"]);
+ });
+
+ it("preserves send-now order when the active task is removed", () => {
+ const current = prioritizePendingChatTask({
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ queued_tasks: [
+ task("next", "2026-01-01T00:00:01Z"),
+ task("send-now", "2026-01-01T00:00:02Z"),
+ ],
+ }, "send-now");
+
+ 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"]);
+ });
+});
diff --git a/packages/core/chat/pending.ts b/packages/core/chat/pending.ts
new file mode 100644
index 0000000000..ec319b7487
--- /dev/null
+++ b/packages/core/chat/pending.ts
@@ -0,0 +1,143 @@
+import type { ChatMessage, ChatPendingTask, ChatQueuedTask } from "../types/chat";
+
+const EMPTY_PENDING_TASK: ChatPendingTask = {};
+
+function compareQueuedTasks(left: ChatQueuedTask, right: ChatQueuedTask): number {
+ const leftTime = Date.parse(left.created_at);
+ const rightTime = Date.parse(right.created_at);
+ if (Number.isFinite(leftTime) && Number.isFinite(rightTime) && leftTime !== rightTime) {
+ return leftTime - rightTime;
+ }
+ return left.task_id.localeCompare(right.task_id);
+}
+
+function uniqueQueue(tasks: ChatQueuedTask[]): ChatQueuedTask[] {
+ const byID = new Map<string, ChatQueuedTask>();
+ // The send response carries the message preview while task:queued is sparse.
+ // Keep whichever observation is rich regardless of network arrival order.
+ for (const task of tasks) {
+ if (!byID.has(task.task_id) || task.message_id) byID.set(task.task_id, task);
+ }
+ return [...byID.values()];
+}
+
+function normalizeQueue(tasks: ChatQueuedTask[]): ChatQueuedTask[] {
+ return uniqueQueue(tasks).sort(compareQueuedTasks);
+}
+
+function asSummary(task: ChatPendingTask): ChatQueuedTask | undefined {
+ if (!task.task_id) return undefined;
+ return {
+ task_id: task.task_id,
+ status: task.status ?? "queued",
+ created_at: task.created_at ?? "",
+ };
+}
+
+export function enqueuePendingChatTask(
+ current: ChatPendingTask | undefined,
+ task: ChatQueuedTask,
+): ChatPendingTask {
+ if (!current?.task_id) {
+ return { ...task, queued_tasks: [task] };
+ }
+ if (current.task_id === task.task_id) {
+ const status = current.status && current.status !== "queued"
+ ? current.status
+ : task.status;
+ const queuedTasks = (current.queued_tasks ?? []).filter(
+ (queued) => queued.task_id !== task.task_id,
+ );
+ return {
+ ...current,
+ ...task,
+ status,
+ created_at: current.created_at || task.created_at,
+ queued_tasks: status === "queued"
+ ? normalizeQueue([...queuedTasks, task])
+ : queuedTasks,
+ };
+ }
+ return {
+ ...current,
+ queued_tasks: normalizeQueue([...(current.queued_tasks ?? []), task]),
+ };
+}
+
+export function promotePendingChatTask(
+ current: ChatPendingTask | undefined,
+ taskID: string,
+ status: string,
+ createdAt?: string,
+): ChatPendingTask {
+ const queue = current?.queued_tasks ?? [];
+ if (current?.task_id === taskID) {
+ return {
+ ...current,
+ status,
+ queued_tasks: queue.filter((task) => task.task_id !== taskID),
+ };
+ }
+
+ const promoted = queue.find((task) => task.task_id === taskID);
+ // Lifecycle events are only hints. A late event for an unknown task must
+ // not synthesize a new head after the authoritative pending query cleared.
+ if (!current?.task_id || !promoted) return current ?? EMPTY_PENDING_TASK;
+ const previousHead = asSummary(current ?? {});
+ return {
+ ...promoted,
+ supports_queue: current.supports_queue,
+ status,
+ created_at: promoted.created_at || createdAt || "",
+ queued_tasks: uniqueQueue([
+ ...(previousHead?.status === "queued" ? [previousHead] : []),
+ ...queue.filter((task) => task.task_id !== taskID),
+ ]),
+ };
+}
+
+export function removePendingChatTask(
+ current: ChatPendingTask | undefined,
+ taskID: string,
+): ChatPendingTask {
+ if (!current?.task_id) return EMPTY_PENDING_TASK;
+ if (current.task_id !== taskID) {
+ return {
+ ...current,
+ queued_tasks: (current.queued_tasks ?? []).filter((task) => task.task_id !== taskID),
+ };
+ }
+
+ const [next, ...rest] = uniqueQueue(
+ (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] };
+}
+
+export function prioritizePendingChatTask(
+ current: ChatPendingTask | undefined,
+ taskID: string,
+): ChatPendingTask {
+ if (!current?.task_id) return EMPTY_PENDING_TASK;
+ const queue = current.queued_tasks ?? [];
+ const selected = queue.find((task) => task.task_id === taskID);
+ if (!selected) return current;
+ return {
+ ...current,
+ queued_tasks: [selected, ...queue.filter((task) => task.task_id !== taskID)],
+ };
+}
+
+export function hideQueuedChatMessages(
+ messages: ChatMessage[],
+ pending: ChatPendingTask | undefined,
+): ChatMessage[] {
+ const queuedMessageTasks = new Map(
+ (pending?.queued_tasks ?? []).flatMap((task) =>
+ task.message_id ? [[task.message_id, task.task_id] as const] : []
+ ),
+ );
+ if (queuedMessageTasks.size === 0) return messages;
+ return messages.filter((message) => queuedMessageTasks.get(message.id) !== message.task_id);
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index d3ecfb987a..feb3280b27 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -53,6 +53,7 @@
"./chat": "./chat/index.ts",
"./chat/queries": "./chat/queries.ts",
"./chat/mutations": "./chat/mutations.ts",
+ "./chat/pending": "./chat/pending.ts",
"./chat/use-quick-actions-pending-timeout": "./chat/use-quick-actions-pending-timeout.ts",
"./chat/unread": "./chat/unread.ts",
"./runtimes": "./runtimes/index.ts",
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 4735730a1a..cbd8daf31c 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -8,6 +8,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import type { WSClient } from "../api/ws-client";
import { defaultStorage } from "../platform/storage";
import { issueKeys } from "../issues/queries";
+import { chatKeys } from "../chat/queries";
import { workspaceWorkingAgentsKeys } from "../agents/queries";
import { workspaceKeys } from "../workspace/queries";
import {
@@ -200,6 +201,51 @@ describe("useRealtimeSync — ws instance change", () => {
expect(calls).toContainEqual(["chat", "pending-task"]);
expect(calls).toContainEqual(["task-messages"]);
});
+
+ it("invalidates per-chat-session caches after an established ws reconnects", () => {
+ const ws = createMockWs();
+ renderHook(() => useRealtimeSync(ws, stores), {
+ wrapper: createWrapper(qc),
+ });
+ const reconnect = vi.mocked(ws.onReconnect).mock.calls[0]?.[0];
+ expect(reconnect).toBeDefined();
+
+ invalidateSpy.mockClear();
+ reconnect!();
+
+ const calls = invalidateSpy.mock.calls.map((call: [{ queryKey?: unknown }, ...unknown[]]) => call[0].queryKey);
+ expect(calls).toContainEqual(chatKeys.messagesAll());
+ expect(calls).toContainEqual(chatKeys.messagesPageAll());
+ expect(calls).toContainEqual(chatKeys.pendingTaskAll());
+ });
+});
+
+describe("useRealtimeSync — queued chat promotion", () => {
+ it("refetches the transcript when a queued prompt starts running", () => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const ws = createMockWs();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+ renderHook(() => useRealtimeSync(ws, createStores()), {
+ wrapper: createWrapper(qc),
+ });
+ const dispatch = vi
+ .mocked(ws.on)
+ .mock.calls.find(([event]) => event === "task:dispatch")?.[1];
+ expect(dispatch).toBeDefined();
+
+ invalidate.mockClear();
+ (dispatch as (payload: unknown) => void)({
+ task_id: "task-follow-up",
+ chat_session_id: "session-1",
+ });
+
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.messages("session-1"),
+ });
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.messagesPage("session-1"),
+ });
+ });
});
describe("useRealtimeSync — Table server membership invalidation", () => {
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.ts
index c571ac34a2..ef90935000 100644
--- a/packages/core/realtime/use-realtime-sync.test.ts
+++ b/packages/core/realtime/use-realtime-sync.test.ts
@@ -345,6 +345,85 @@ describe("applyChatCancelFinalizedToCache", () => {
expect(qc.getQueryData<ChatPendingTask>(pendingKey)).toEqual({});
});
+ it("promotes the next queued task when the restored task was the head", () => {
+ const qc = createQueryClient();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+ qc.setQueryData<ChatPendingTask>(pendingKey, {
+ task_id: taskId,
+ status: "running",
+ queued_tasks: [
+ {
+ task_id: "task-next",
+ status: "queued",
+ created_at: "2026-05-13T05:00:01Z",
+ content: "next",
+ },
+ {
+ task_id: "task-later",
+ status: "queued",
+ created_at: "2026-05-13T05:00:02Z",
+ content: "later",
+ },
+ ],
+ });
+
+ applyChatCancelFinalizedToCache(qc, {
+ outcome: "restored",
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-cancelled-user",
+ });
+
+ expect(qc.getQueryData<ChatPendingTask>(pendingKey)).toEqual({
+ task_id: "task-next",
+ status: "queued",
+ 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",
+ created_at: "2026-05-13T05:00:02Z",
+ content: "later",
+ },
+ ],
+ });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: pendingKey });
+ });
+
+ it("keeps a promoted successor when the restored event arrives late", () => {
+ const qc = createQueryClient();
+ const successor: ChatPendingTask = {
+ task_id: "task-next",
+ status: "running",
+ created_at: "2026-05-13T05:00:01Z",
+ queued_tasks: [
+ {
+ task_id: "task-later",
+ status: "queued",
+ created_at: "2026-05-13T05:00:02Z",
+ content: "later",
+ },
+ ],
+ };
+ qc.setQueryData<ChatPendingTask>(pendingKey, successor);
+
+ applyChatCancelFinalizedToCache(qc, {
+ outcome: "restored",
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-cancelled-user",
+ });
+
+ expect(qc.getQueryData<ChatPendingTask>(pendingKey)).toEqual(successor);
+ });
+
it("invalidates the draft-restores query for the initiator", () => {
const qc = createQueryClient();
const invalidate = vi.spyOn(qc, "invalidateQueries");
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 6474776e19..044b116ebd 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -55,6 +55,10 @@ import {
QUICK_ACTIONS_PENDING_TIMEOUT_MS,
} from "../chat/queries";
import { useChatStore } from "../chat";
+import {
+ promotePendingChatTask,
+ removePendingChatTask,
+} from "../chat/pending";
import { resolvePostAuthDestination, useHasOnboarded } from "../paths";
import type {
MemberAddedPayload,
@@ -174,8 +178,12 @@ export function applyChatDoneToCache(
(old) => patchLatestChatMessagePage(old, assistant),
);
}
- // Replacement is in the messages list now; safe to drop pending.
- qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ // Replacement is in the messages list now; remove only this task. If a
+ // follow-up is queued, it becomes the next head in the same render tick.
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(sessionId),
+ (old) => removePendingChatTask(old, taskId),
+ );
// Raise/clear the quick-actions placeholder marker. Kept OUTSIDE the
// message caches deliberately: the authoritative refetch below replaces
// those, and a flag stored on the message would vanish with it. Explicit
@@ -412,8 +420,14 @@ export function applyChatCancelFinalizedToCache(
if (payload.message_id) {
removeChatMessageFromCaches(qc, sessionId, payload.message_id);
}
- qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ // Deferred finalization can arrive after a queued successor was promoted.
+ // Remove only the cancelled task so a late restore cannot hide newer work.
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(sessionId),
+ (old) => removePendingChatTask(old, payload.task_id),
+ );
invalidateChatMessageQueries(qc, sessionId);
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
const isInitiator =
!!payload.initiator_user_id &&
!!currentUserId &&
@@ -1305,27 +1319,13 @@ export function useRealtimeSync(
}
});
- // Chat task lifecycle writethrough: keep `chatKeys.pendingTask(sessionId)`
- // synchronized with the server state machine via setQueryData rather than
- // invalidate-refetch. Same pattern as task:message — the WS payload
- // carries everything we need, and an HTTP roundtrip just to read what we
- // already know would add latency to every stage transition.
- //
- // task:queued is emitted by EnqueueChatTask. The optimistic seed in
- // chat-window.tsx may have already populated the cache with a temporary
- // id; this handler upgrades it to the real task_id (and reaffirms status
- // when reconnect replays the event for an already-running task).
+ // Lifecycle events are invalidation hints. They intentionally omit queue
+ // previews and message ids, so only the pending-task endpoint can author
+ // the complete queue shape.
const unsubTaskQueued = ws.on("task:queued", (p) => {
const payload = p as TaskQueuedPayload;
if (!payload.chat_session_id) return;
- qc.setQueryData<ChatPendingTask>(
- chatKeys.pendingTask(payload.chat_session_id),
- (old) => ({
- ...(old ?? {}),
- task_id: payload.task_id,
- status: "queued",
- }),
- );
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
invalidatePendingAggregate();
});
@@ -1340,11 +1340,10 @@ export function useRealtimeSync(
if (!payload.chat_session_id) return;
qc.setQueryData<ChatPendingTask>(
chatKeys.pendingTask(payload.chat_session_id),
- (old) => {
- if (!old || old.task_id !== payload.task_id) return old;
- return { ...old, status: "running" };
- },
+ (old) => promotePendingChatTask(old, payload.task_id, "running"),
);
+ invalidateChatMessageQueries(qc, payload.chat_session_id);
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
invalidatePendingAggregate();
});
@@ -1358,11 +1357,10 @@ export function useRealtimeSync(
if (!payload.chat_session_id) return;
qc.setQueryData<ChatPendingTask>(
chatKeys.pendingTask(payload.chat_session_id),
- (old) => {
- if (!old || old.task_id !== payload.task_id) return old;
- return { ...old, status: "running" };
- },
+ (old) => promotePendingChatTask(old, payload.task_id, "running"),
);
+ invalidateChatMessageQueries(qc, payload.chat_session_id);
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
invalidatePendingAggregate();
});
@@ -1378,11 +1376,15 @@ export function useRealtimeSync(
if (!payload.chat_session_id) return;
qc.setQueryData<ChatPendingTask>(
chatKeys.pendingTask(payload.chat_session_id),
- (old) => {
- if (!old || old.task_id !== payload.task_id) return old;
- return { ...old, status: "waiting_local_directory" };
- },
+ (old) =>
+ promotePendingChatTask(
+ old,
+ payload.task_id,
+ "waiting_local_directory",
+ ),
);
+ invalidateChatMessageQueries(qc, payload.chat_session_id);
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
invalidatePendingAggregate();
},
);
@@ -1402,9 +1404,14 @@ export function useRealtimeSync(
task_id: payload.task_id,
chat_session_id: payload.chat_session_id,
});
- qc.setQueryData(chatKeys.pendingTask(payload.chat_session_id), {});
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(payload.chat_session_id),
+ (old) => removePendingChatTask(old, payload.task_id),
+ );
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
invalidateChatMessageQueries(qc, payload.chat_session_id);
invalidatePendingAggregate();
+ invalidateSessionLists();
});
const unsubTaskCompleted = ws.on("task:completed", (p) => {
@@ -1414,12 +1421,11 @@ export function useRealtimeSync(
task_id: payload.task_id,
chat_session_id: payload.chat_session_id,
});
- // `chat:done` (broadcast immediately before this event in CompleteTask)
- // already wrote the assistant message into the messages cache and
- // cleared `chatKeys.pendingTask`. This event is now only responsible
- // for refreshing the per-user cross-session aggregate that drives the
- // FAB indicator — `chat:done` is per-session and doesn't carry that
- // information.
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(payload.chat_session_id),
+ (old) => removePendingChatTask(old, payload.task_id),
+ );
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
invalidatePendingAggregate();
});
@@ -1436,7 +1442,10 @@ export function useRealtimeSync(
// failure bubble shows up without requiring a page refresh. Pre-#1823
// this branch only flipped pending — the comment "No new message"
// was true then, but FailTask now persists a row.
- qc.setQueryData(chatKeys.pendingTask(payload.chat_session_id), {});
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(payload.chat_session_id),
+ (old) => removePendingChatTask(old, payload.task_id),
+ );
invalidateChatMessageQueries(qc, payload.chat_session_id);
qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
invalidatePendingAggregate();
diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.ts
index 5d66e92456..2d72723ee6 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -170,6 +170,8 @@ export interface ChatMessagesPage {
export interface SendChatMessageResponse {
message_id: string;
task_id: string;
+ /** True when the server supports queued follow-up sends. */
+ supports_queue?: boolean;
/**
* Server-authoritative task creation time. Optimistic StatusPill seed
* uses this as its anchor so the timer starts from the real `0s` —
@@ -237,8 +239,29 @@ export interface ChatDraftRestoresResponse {
* task_id/status only, then this query catches up with the real created_at
* so the timer survives refresh / reopen without "resetting to 0s".
*/
+export interface ChatQueuedTask {
+ task_id: string;
+ status: string;
+ created_at: string;
+ message_id?: string;
+ content?: string;
+}
+
+export interface PrioritizeQueuedChatTaskResponse {
+ task_id: string;
+ /** Server-authoritative task to stop after the selected task is prioritized. */
+ active_task_id?: string;
+}
+
export interface ChatPendingTask {
task_id?: string;
status?: string;
created_at?: string;
+ /** 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.
+ */
+ queued_tasks?: ChatQueuedTask[];
}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 241367788e..ff838e2b8c 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -120,6 +120,8 @@ export type {
ChatQuickActionsFailureState,
ChatMessagesPage,
ChatPendingTask,
+ ChatQueuedTask,
+ PrioritizeQueuedChatTaskResponse,
PendingChatTaskItem,
PendingChatTasksResponse,
HasPendingChatTasksResponse,
diff --git a/packages/ui/components/common/submit-button.tsx b/packages/ui/components/common/submit-button.tsx
index 08fde2faba..44471de97e 100644
--- a/packages/ui/components/common/submit-button.tsx
+++ b/packages/ui/components/common/submit-button.tsx
@@ -24,6 +24,8 @@ interface SubmitButtonProps {
busy?: boolean;
running?: boolean;
onStop?: () => void;
+ /** Keep a send control beside Stop so callers can enqueue follow-up work. */
+ allowSubmitWhileRunning?: boolean;
/**
* Tooltip shown over the send button when idle. Pass a string or a node
* (e.g. `Send · ⌘↵`). Omit to render no tooltip.
@@ -46,11 +48,13 @@ function SubmitButton({
busy,
running,
onStop,
+ allowSubmitWhileRunning,
tooltip,
ariaLabel,
stopTooltip,
stopAriaLabel,
}: SubmitButtonProps) {
+ let stopControl: ReactNode = null;
if (running) {
const stopButton = (
<Button
@@ -62,13 +66,13 @@ function SubmitButton({
<Square className="fill-current" aria-hidden="true" />
</Button>
);
- if (!stopTooltip) return stopButton;
- return (
+ stopControl = stopTooltip ? (
<Tooltip>
<TooltipTrigger render={stopButton} />
<TooltipContent side="top">{stopTooltip}</TooltipContent>
</Tooltip>
- );
+ ) : stopButton;
+ if (!allowSubmitWhileRunning) return stopControl;
}
const submitButton = (
@@ -77,7 +81,7 @@ function SubmitButton({
className="rounded-full"
disabled={disabled || loading || busy}
aria-disabled={busy || undefined}
- aria-busy={busy || undefined}
+ aria-busy={loading || busy || undefined}
onClick={onClick}
aria-label={ariaLabel}
>
@@ -93,12 +97,20 @@ function SubmitButton({
)}
</Button>
);
- if (!tooltip) return submitButton;
+ const submitControl = !tooltip
+ ? submitButton
+ : (
+ <Tooltip>
+ <TooltipTrigger render={submitButton} />
+ <TooltipContent side="top">{tooltip}</TooltipContent>
+ </Tooltip>
+ );
+ if (!stopControl) return submitControl;
return (
- <Tooltip>
- <TooltipTrigger render={submitButton} />
- <TooltipContent side="top">{tooltip}</TooltipContent>
- </Tooltip>
+ <>
+ {stopControl}
+ {submitControl}
+ </>
);
}
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index 6e5534ad84..0a2ed18858 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -24,6 +24,7 @@ import { useNavigation } from "../navigation";
import { useT } from "../i18n";
import { ChatMessageList, ChatMessageSkeleton } from "./components/chat-message-list";
import { ChatInput } from "./components/chat-input";
+import { ChatQueue } from "./components/chat-queue";
import { ChatThreadList } from "./components/chat-thread-list";
import { ChatSessionHeader } from "./components/chat-session-header";
import { EmptyState } from "./components/chat-empty-state";
@@ -296,6 +297,14 @@ export function ChatPage() {
<OfflineBanner agentName={c.activeAgent?.name} availability={c.availability} />
)}
+ <ChatQueue
+ tasks={c.pendingTask?.queued_tasks ?? []}
+ onSendNow={c.handleSendQueuedTaskNow}
+ onEdit={c.handleEditQueuedTask}
+ onRemove={c.handleRemoveQueuedTask}
+ onClear={c.handleClearQueuedTasks}
+ />
+
<ChatInput
onSend={c.handleSend}
restoreDraftRequest={c.restoreDraftRequest}
@@ -303,6 +312,7 @@ export function ChatPage() {
uploadEnabled={c.uploadEnabled}
onStop={c.handleStop}
isRunning={!!c.pendingTaskId}
+ allowSubmitWhileRunning={c.pendingTask?.supports_queue === true}
disabled={
c.isSessionArchived || c.isAgentArchived || !c.isAgentRuntimeBound
}
diff --git a/packages/views/chat/components/chat-column.test.tsx b/packages/views/chat/components/chat-column.test.tsx
index af7f1481a9..0bec93f92b 100644
--- a/packages/views/chat/components/chat-column.test.tsx
+++ b/packages/views/chat/components/chat-column.test.tsx
@@ -7,6 +7,7 @@ import { ChatMessageSkeleton } from "./chat-message-list";
import { NoAgentBanner } from "./no-agent-banner";
import { ArchivedAgentBanner } from "./archived-agent-banner";
import { OfflineBanner } from "./offline-banner";
+import { ChatQueue } from "./chat-queue";
// Every layer of the chat body has to land on the same left/right edges: the
// message column, the status banner above the composer, and the composer card.
@@ -66,6 +67,24 @@ describe("chat column geometry", () => {
["offline banner", <OfflineBanner key="o" agentName="Lambda" availability="offline" />],
["unstable banner", <OfflineBanner key="u" agentName="Lambda" availability="unstable" />],
["message skeleton", <ChatMessageSkeleton key="s" />],
+ [
+ "follow-up queue",
+ <ChatQueue
+ key="q"
+ tasks={[
+ {
+ task_id: "task-queued",
+ status: "queued",
+ content: "Follow up",
+ created_at: "2026-07-30T00:00:00Z",
+ },
+ ]}
+ onSendNow={() => {}}
+ onEdit={() => {}}
+ onRemove={() => {}}
+ onClear={() => {}}
+ />,
+ ],
])("aligns the %s on the shared gutter + column", (_label, ui) => {
const { container } = renderChat(ui);
const outer = root(container);
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index 788de9d838..a1a7617cbd 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -593,6 +593,30 @@ describe("ChatInput project context", () => {
expect(onProjectChange).toHaveBeenCalledWith(null);
});
+ it("keeps Stop and Queue Send available while the agent is running", async () => {
+ const onSend = vi.fn<ChatInputOnSend>(async () => true);
+ const onStop = vi.fn();
+ renderInput({ isRunning: true, allowSubmitWhileRunning: true, onSend, onStop });
+
+ fireEvent.change(screen.getByTestId("editor"), {
+ target: { value: "follow-up" },
+ });
+
+ expect(screen.getByRole("button", { name: "Stop" })).toBeInTheDocument();
+ const queueButton = screen.getByRole("button", { name: "Queue message" });
+ expect(queueButton).not.toBeDisabled();
+ fireEvent.click(queueButton);
+
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ });
+
+ it("shows only Stop while an older server is running", () => {
+ renderInput({ isRunning: true, onStop: vi.fn() });
+
+ expect(screen.getByRole("button", { name: "Stop" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Queue message" })).not.toBeInTheDocument();
+ });
+
it("locks the project control while a send is in flight so a mid-send switch cannot retarget the session", async () => {
// A brand-new chat creates its session row lazily during send, bound to
// the project selected at click time. If the user could switch project
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index b45a46e217..f8090f224b 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -87,6 +87,8 @@ interface ChatInputProps {
uploadEnabled?: boolean;
onStop?: () => void;
isRunning?: boolean;
+ /** Enabled only after the server explicitly advertises follow-up queues. */
+ allowSubmitWhileRunning?: boolean;
disabled?: boolean;
/** True when the user has no agent available — disables the editor and
* surfaces a distinct placeholder. Kept separate from `disabled` so
@@ -134,6 +136,7 @@ export function ChatInput({
uploadEnabled: uploadAllowed,
onStop,
isRunning,
+ allowSubmitWhileRunning,
disabled,
noAgent,
agentArchived,
@@ -431,8 +434,12 @@ export function ChatInput({
editorScrubbedRef.current = false;
// These states disable the SubmitButton, but Mod+Enter bypasses it — so a
// read-only or busy composer must still refuse the keyboard path.
- if (isRunning || disabled || noAgent) {
- logger.debug("input.send skipped", { isRunning, disabled, noAgent });
+ if (disabled || noAgent || (isRunning && !allowSubmitWhileRunning)) {
+ logger.debug("input.send skipped", {
+ disabled,
+ noAgent,
+ runningWithoutQueueSupport: !!isRunning && !allowSubmitWhileRunning,
+ });
return false;
}
// The editor is still holding a DIFFERENT draft's document than the one
@@ -677,13 +684,18 @@ export function ChatInput({
busy={gate.uploading}
running={isRunning}
onStop={onStop}
+ allowSubmitWhileRunning={allowSubmitWhileRunning}
tooltip={gate.uploading
? tEditor(($) => $.upload.in_progress)
- : sendShortcut
- ? `${t(($) => $.input.send_tooltip)} · ${formatShortcut(sendShortcut)}`
- : t(($) => $.input.send_tooltip)}
+ : isRunning
+ ? t(($) => $.input.queue_send_tooltip)
+ : sendShortcut
+ ? `${t(($) => $.input.send_tooltip)} · ${formatShortcut(sendShortcut)}`
+ : t(($) => $.input.send_tooltip)}
ariaLabel={gate.uploading
? tEditor(($) => $.upload.in_progress)
+ : isRunning
+ ? t(($) => $.input.queue_send_tooltip)
: t(($) => $.input.send_tooltip)}
stopTooltip={t(($) => $.input.stop_tooltip)}
stopAriaLabel={t(($) => $.input.stop_tooltip)}
diff --git a/packages/views/chat/components/chat-queue.test.tsx b/packages/views/chat/components/chat-queue.test.tsx
new file mode 100644
index 0000000000..717742372a
--- /dev/null
+++ b/packages/views/chat/components/chat-queue.test.tsx
@@ -0,0 +1,91 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { describe, expect, it, vi } from "vitest";
+import enChat from "../../locales/en/chat.json";
+import { ChatQueue } from "./chat-queue";
+
+const TEST_RESOURCES = { en: { chat: enChat } };
+
+function renderQueue() {
+ const callbacks = {
+ onSendNow: vi.fn<(taskId: string) => Promise<void>>().mockResolvedValue(),
+ onEdit: vi.fn<(taskId: string) => Promise<void>>().mockResolvedValue(),
+ onRemove: vi.fn<(taskId: string) => Promise<void>>().mockResolvedValue(),
+ onClear: vi.fn<() => Promise<void>>().mockResolvedValue(),
+ };
+ const view = render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <ChatQueue
+ tasks={[
+ {
+ task_id: "task-2",
+ status: "queued",
+ content: "First follow-up",
+ created_at: "2026-07-01T00:01:00Z",
+ },
+ {
+ task_id: "task-3",
+ status: "queued",
+ content: "",
+ created_at: "2026-07-01T00:02:00Z",
+ },
+ ]}
+ {...callbacks}
+ />
+ </I18nProvider>,
+ );
+ return { ...callbacks, container: view.container };
+}
+
+describe("ChatQueue", () => {
+ it("renders queued messages in order and falls back for empty content", () => {
+ renderQueue();
+
+ expect(screen.getByText("2 queued messages")).toBeInTheDocument();
+ expect(screen.getByText("First follow-up")).toBeInTheDocument();
+ expect(screen.getByText("Queued message")).toBeInTheDocument();
+ expect(screen.getAllByLabelText("Send now")).toHaveLength(2);
+ expect(screen.getAllByLabelText("Edit queued message")).toHaveLength(2);
+ expect(screen.getAllByLabelText("Remove queued message")).toHaveLength(2);
+ expect(screen.getByRole("button", { name: "Clear all" })).toBeInTheDocument();
+ });
+
+ it("runs send-now, edit, remove, and clear against the selected queue state", async () => {
+ const actions = renderQueue();
+
+ fireEvent.click(screen.getAllByLabelText("Send now")[1]!);
+ await waitFor(() => expect(actions.onSendNow).toHaveBeenCalledWith("task-3"));
+ fireEvent.click(screen.getAllByLabelText("Edit queued message")[0]!);
+ await waitFor(() => expect(actions.onEdit).toHaveBeenCalledWith("task-2"));
+ fireEvent.click(screen.getAllByLabelText("Remove queued message")[1]!);
+ await waitFor(() => expect(actions.onRemove).toHaveBeenCalledWith("task-3"));
+ fireEvent.click(screen.getByRole("button", { name: "Clear all" }));
+ await waitFor(() => expect(actions.onClear).toHaveBeenCalledTimes(1));
+ });
+
+ it("keeps long queues bounded and blocks duplicate actions while one is pending", async () => {
+ let finishClear: (() => void) | undefined;
+ const actions = renderQueue();
+ actions.onClear.mockReturnValue(new Promise<void>((resolve) => {
+ finishClear = resolve;
+ }));
+
+ const scroller = actions.container.querySelector(".overflow-y-auto");
+ expect(scroller).toHaveClass("max-h-40");
+
+ fireEvent.click(screen.getByRole("button", { name: "Clear all" }));
+ await waitFor(() => {
+ for (const button of screen.getAllByRole("button")) {
+ expect(button).toBeDisabled();
+ }
+ });
+
+ finishClear?.();
+ await waitFor(() => {
+ for (const button of screen.getAllByRole("button")) {
+ expect(button).toBeEnabled();
+ }
+ });
+ expect(actions.onClear).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/views/chat/components/chat-queue.tsx b/packages/views/chat/components/chat-queue.tsx
new file mode 100644
index 0000000000..cec805a4b3
--- /dev/null
+++ b/packages/views/chat/components/chat-queue.tsx
@@ -0,0 +1,123 @@
+"use client";
+
+import { useState } from "react";
+import { Loader2, Pencil, Send, X } from "lucide-react";
+import type { ChatQueuedTask } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../i18n";
+import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";
+
+interface ChatQueueProps {
+ tasks: ChatQueuedTask[];
+ 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) {
+ const { t } = useT("chat");
+ const [busyAction, setBusyAction] = useState<string | null>(null);
+
+ if (tasks.length === 0) return null;
+
+ const run = async (key: string, action: () => Promise<void> | void) => {
+ setBusyAction(key);
+ try {
+ await action();
+ } finally {
+ setBusyAction((current) => current === key ? null : current);
+ }
+ };
+
+ return (
+ <div
+ className={cn(CHAT_GUTTER, "mb-2")}
+ aria-live="polite"
+ aria-busy={busyAction !== null}
+ >
+ <div className={cn(CHAT_COLUMN, "rounded-lg border bg-muted/30 p-2")}>
+ <div className="mb-1 flex items-center justify-between gap-2 px-1">
+ <span className="text-caption font-medium text-muted-foreground">
+ {t(($) => $.queue.title, { count: tasks.length })}
+ </span>
+ <Button
+ variant="ghost"
+ size="xs"
+ disabled={busyAction !== null}
+ onClick={() => void run("clear", onClear)}
+ >
+ {busyAction === "clear" && <Loader2 className="animate-spin" aria-hidden="true" />}
+ {t(($) => $.queue.clear)}
+ </Button>
+ </div>
+ <div className="max-h-40 space-y-0.5 overflow-y-auto">
+ {tasks.map((task, index) => {
+ const sendNowKey = `send-now:${task.task_id}`;
+ const editKey = `edit:${task.task_id}`;
+ const removeKey = `remove:${task.task_id}`;
+ return (
+ <div
+ key={task.task_id}
+ className="flex min-w-0 items-center gap-2 rounded-md px-1.5 py-1 text-body"
+ >
+ <span className="w-4 shrink-0 text-center text-caption tabular-nums text-muted-foreground">
+ {index + 1}
+ </span>
+ <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" />
+ )}
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className="shrink-0 text-muted-foreground"
+ disabled={busyAction !== null}
+ title={t(($) => $.queue.edit)}
+ aria-label={t(($) => $.queue.edit)}
+ onClick={() => void run(editKey, () => onEdit(task.task_id))}
+ >
+ {busyAction === editKey ? (
+ <Loader2 className="animate-spin" aria-hidden="true" />
+ ) : (
+ <Pencil aria-hidden="true" />
+ )}
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className="shrink-0 text-muted-foreground"
+ disabled={busyAction !== null}
+ title={t(($) => $.queue.remove)}
+ aria-label={t(($) => $.queue.remove)}
+ onClick={() => void run(removeKey, () => onRemove(task.task_id))}
+ >
+ {busyAction === removeKey ? (
+ <Loader2 className="animate-spin" aria-hidden="true" />
+ ) : (
+ <X aria-hidden="true" />
+ )}
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 5ba0fa5f88..f92d905f66 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -57,11 +57,14 @@ import { useChatStore } from "@multica/core/chat";
import { chatQuickActionsPendingOptions } from "@multica/core/chat/queries";
import { useQuickActionsPendingTimeout } from "@multica/core/chat/use-quick-actions-pending-timeout";
import { useQuickActionsFailureToast } from "./use-quick-actions-failure-toast";
+import { hideQueuedChatMessages } from "@multica/core/chat/pending";
import { removeChatMessageFromCaches } from "@multica/core/realtime";
import { useChatDraftRestore } from "./use-chat-draft-restore";
+import { useChatTaskActions } from "./use-chat-task-actions";
import { useChatInputFocus } from "./use-chat-input-focus";
import { ChatMessageList, ChatMessageSkeleton } from "./chat-message-list";
import { ChatInput } from "./chat-input";
+import { ChatQueue } from "./chat-queue";
import { ChatResizeHandles } from "./chat-resize-handles";
import { useChatContextItems } from "./use-chat-context-items";
import { useChatResize } from "./use-chat-resize";
@@ -69,10 +72,11 @@ import {
hasInFlightPendingTask,
isStillOnComposeTarget,
planProjectContextChange,
+ seedAcceptedPendingTask,
} from "./use-chat-controller";
import { useChatProjectContextSupport } from "./use-chat-project-context-support";
import { createLogger } from "@multica/core/logger";
-import type { Agent, Attachment, ChatMessage, ChatMessagesPage, ChatPendingTask, ChatSession, PendingChatTasksResponse } from "@multica/core/types";
+import type { Agent, Attachment, ChatMessage, ChatMessagesPage, ChatSession, PendingChatTasksResponse } from "@multica/core/types";
import { useT } from "../../i18n";
const uiLogger = createLogger("chat.ui");
@@ -156,24 +160,28 @@ export function ChatWindow() {
// it starts from a large stable base and only subtracts the count of loaded
// prepended rows, so concurrent server inserts cannot drift the scroll anchor.
const messagePages = activeSessionId ? rawMessagePages?.pages ?? [] : [];
- const messages = [...messagePages].reverse().flatMap((page) => page.messages);
- const olderMessageCount = messagePages.slice(1).reduce((sum, page) => sum + page.messages.length, 0);
- const firstItemIndex = messages.length > 0
- ? CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX - olderMessageCount
- : 0;
+ const allMessages = [...messagePages].reverse().flatMap((page) => page.messages);
// Skeleton only shows for an un-cached session fetch. Cached switches
// return data synchronously — no flash. `enabled: false` (new chat)
// keeps isLoading false so the starter prompts aren't hidden.
- const showSkeleton = !!activeSessionId && messagesLoading;
-
// Server-authoritative pending task. Survives refresh / reopen / session
// switch because it's keyed on sessionId in the Query cache; WS events
// (chat:message / chat:done / task:*) keep it invalidated in real time.
//
// This is the SOLE source for pendingTaskId — no mirror in the store.
- const { data: pendingTask } = useQuery(
+ const { data: pendingTask, isLoading: pendingTaskLoading } = useQuery(
pendingChatTaskOptions(activeSessionId ?? ""),
);
+ const showSkeleton =
+ !!activeSessionId && (messagesLoading || pendingTaskLoading);
+ const messages = hideQueuedChatMessages(allMessages, pendingTask);
+ const olderMessageCount = messagePages.slice(1).reduce(
+ (sum, page) => sum + page.messages.length,
+ 0,
+ );
+ const firstItemIndex = messages.length > 0
+ ? CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX - olderMessageCount
+ : 0;
const pendingTaskId = pendingTask?.task_id ?? null;
const stopRequestedBeforeTaskRef = useRef(false);
// Durable deferred-cancellation draft restores (#5219). Same hook as the chat
@@ -190,6 +198,13 @@ export function ChatWindow() {
const appForeground = useAppForeground();
const { restoreDraftRequest, enqueueLocalRestore, handleRestoreDraftApplied } =
useChatDraftRestore(activeSessionId, isOpen && appForeground);
+ const {
+ cancelChatTask,
+ handleEditQueuedTask,
+ handleRemoveQueuedTask,
+ handleClearQueuedTasks,
+ handleSendQueuedTaskNow,
+ } = useChatTaskActions(activeSessionId, enqueueLocalRestore);
// Nonce handed to ChatInput to pull focus into the compose box: when a new
// chat starts (⊕ or switching agent), and whenever the window itself opens.
const { focusRequest, requestInputFocus } = useChatInputFocus(isOpen);
@@ -398,55 +413,6 @@ export function ChatWindow() {
// remain workspace-scoped drafts — sending is still the point where a
// session is created (if needed) and attachment_ids bind to the message.
- const cancelChatTask = useCallback(
- async (
- taskId: string,
- sessionId: string,
- options: { restoreDraftToInput: boolean; source: string },
- ) => {
- apiLogger.info("cancelTask.start", {
- taskId,
- sessionId,
- source: options.source,
- });
- qc.setQueryData(chatKeys.pendingTask(sessionId), {});
-
- try {
- const result = await api.cancelTaskById(taskId);
- const restored = result.cancelled_chat_message;
- if (restored?.restore_to_input) {
- removeChatMessageFromCaches(qc, restored.chat_session_id, restored.message_id);
- if (options.restoreDraftToInput && restored.chat_session_id === sessionId) {
- enqueueLocalRestore({
- id: restored.message_id,
- content: restored.content,
- attachments: restored.attachments,
- sessionId: restored.chat_session_id,
- });
- }
- }
- qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
- qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
- apiLogger.info("cancelTask.success", {
- taskId,
- sessionId,
- restoredToInput: !!restored?.restore_to_input && options.restoreDraftToInput,
- });
- return result;
- } catch (err) {
- apiLogger.warn("cancelTask.error (task may have already finished)", {
- taskId,
- sessionId,
- err,
- });
- qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
- qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
- return null;
- }
- },
- [qc, enqueueLocalRestore],
- );
-
const handleSend = useCallback(
async (
content: string,
@@ -468,6 +434,12 @@ export function ChatWindow() {
});
return false;
}
+ if (pendingTaskId && pendingTask?.supports_queue !== true) {
+ apiLogger.warn("sendChatMessage skipped: server does not support follow-up queues", {
+ sessionId: activeSessionId,
+ });
+ return false;
+ }
if (!activeAgentRuntimeBound) {
toast.error(t(($) => $.input.runtime_required_toast));
return false;
@@ -556,10 +528,12 @@ export function ChatWindow() {
chatKeys.messages(sessionId),
(old) => (old ? [...old, sent] : [sent]),
);
- qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {
+ seedAcceptedPendingTask(qc, sessionId, {
task_id: result.task_id,
- status: "queued",
created_at: result.created_at,
+ message_id: result.message_id,
+ content: finalContent,
+ supports_queue: result.supports_queue,
});
// Cache primed → publish the new active session, but only if the user
// hasn't navigated away mid-send. Compare the live store against the
@@ -607,6 +581,8 @@ export function ChatWindow() {
activeAgent,
activeAgentRuntimeBound,
isAgentArchived,
+ pendingTask,
+ pendingTaskId,
ensureSession,
cancelChatTask,
qc,
@@ -916,6 +892,14 @@ export function ChatWindow() {
<OfflineBanner agentName={activeAgent?.name} availability={availability} />
)}
+ <ChatQueue
+ tasks={pendingTask?.queued_tasks ?? []}
+ onSendNow={handleSendQueuedTaskNow}
+ onEdit={handleEditQueuedTask}
+ onRemove={handleRemoveQueuedTask}
+ onClear={handleClearQueuedTasks}
+ />
+
{/* Input — disabled for legacy archived sessions and for sessions whose
* agent has been archived (read-only); locked out entirely when there's
* no agent (the EmptyState above carries the CTA). */}
@@ -926,6 +910,7 @@ export function ChatWindow() {
uploadEnabled={!!activeAgent}
onStop={handleStop}
isRunning={!!pendingTaskId}
+ allowSubmitWhileRunning={pendingTask?.supports_queue === true}
disabled={
isSessionArchived || isAgentArchived || !activeAgentRuntimeBound
}
diff --git a/packages/views/chat/components/use-chat-controller.test.ts b/packages/views/chat/components/use-chat-controller.test.ts
index 4dafb8d42d..5db09882ab 100644
--- a/packages/views/chat/components/use-chat-controller.test.ts
+++ b/packages/views/chat/components/use-chat-controller.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import { QueryClient, type InfiniteData } from "@tanstack/react-query";
import { chatKeys } from "@multica/core/chat/queries";
import type { ChatMessage, ChatMessagesPage, ChatPendingTask } from "@multica/core/types";
@@ -6,6 +6,7 @@ import {
hasInFlightPendingTask,
isStillOnComposeTarget,
planProjectContextChange,
+ seedAcceptedPendingTask,
} from "./use-chat-controller";
// hasInFlightPendingTask is the discriminator the stale-session self-heal uses
@@ -56,6 +57,38 @@ describe("hasInFlightPendingTask", () => {
});
});
+describe("seedAcceptedPendingTask", () => {
+ it("keeps a task dispatched before the send response and refetches authority", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sid), {
+ task_id: "task-1",
+ status: "dispatched",
+ created_at: "2026-07-08T00:00:00Z",
+ queued_tasks: [],
+ });
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ seedAcceptedPendingTask(qc, sid, {
+ task_id: "task-1",
+ created_at: "2026-07-08T00:00:00Z",
+ message_id: "message-1",
+ content: "accepted prompt",
+ supports_queue: true,
+ });
+
+ expect(qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(sid))).toEqual(
+ expect.objectContaining({
+ task_id: "task-1",
+ status: "dispatched",
+ message_id: "message-1",
+ content: "accepted prompt",
+ queued_tasks: [],
+ }),
+ );
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: chatKeys.pendingTask(sid) });
+ });
+});
+
// The post-send "scrub the composer?" rule, shared by BOTH send chains (the
// chat tab's controller and the floating ChatWindow) so they cannot drift.
// MUL-4864: the new-chat composer is one box per workspace, so the selected
diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsx
index 16e5bb8d9c..8cc9e3dc15 100644
--- a/packages/views/chat/components/use-chat-controller.test.tsx
+++ b/packages/views/chat/components/use-chat-controller.test.tsx
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { act, renderHook } from "@testing-library/react";
-import type { Agent, ChatSession, Project } from "@multica/core/types";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import type { Agent, ChatPendingTask, ChatSession, Project } from "@multica/core/types";
interface QueuedRestore {
id: string;
@@ -53,8 +53,15 @@ const h = vi.hoisted(() => {
store.pendingSendRestores = next;
}),
};
+ const queryClient = {
+ getQueryData: vi.fn(),
+ setQueryData: vi.fn(),
+ invalidateQueries: vi.fn(),
+ cancelQueries: vi.fn(),
+ };
return {
store,
+ queryClient,
archivedMutate: vi.fn(),
markReadMutate: vi.fn(),
// Stable across renders so tests can assert on it; lazy-creates the session
@@ -69,6 +76,7 @@ const h = vi.hoisted(() => {
sessions: [] as ChatSession[],
agents: [] as Agent[],
projects: [] as Project[],
+ pendingTask: null as ChatPendingTask | null,
draftRestores: null as
| { restores: { id: string; chat_session_id: string; content: string }[] }
| null,
@@ -89,7 +97,20 @@ vi.mock("@multica/core/projects/queries", () => ({
}));
vi.mock("@multica/views/issues/components", () => ({ canAssignAgent: () => true }));
vi.mock("@multica/core/api", () => ({
- api: { sendChatMessage: vi.fn(), cancelTaskById: vi.fn() },
+ ApiError: class ApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ }
+ },
+ api: {
+ sendChatMessage: vi.fn(),
+ cancelTaskById: vi.fn(),
+ clearQueuedChatTasks: vi.fn(),
+ prioritizeQueuedChatTask: vi.fn(),
+ },
// Names the 403 that a revoked invoke permission raises (MUL-4525); plain
// failures have no reason code.
dispatchReasonCode: () => undefined,
@@ -144,6 +165,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => {
if (key.includes("runtimes")) return { data: [] };
if (key.includes("sessions")) return { data: h.sessions, isSuccess: true };
if (key.includes("projects")) return { data: h.projects, isSuccess: true };
+ if (key.includes("pending-task")) return { data: h.pendingTask };
if (key.includes("draft-restores")) return { data: h.draftRestores };
return { data: null };
},
@@ -154,16 +176,12 @@ vi.mock("@tanstack/react-query", async (importOriginal) => {
hasNextPage: false,
isFetchingNextPage: false,
}),
- useQueryClient: () => ({
- getQueryData: vi.fn(),
- setQueryData: vi.fn(),
- invalidateQueries: vi.fn(),
- }),
+ useQueryClient: () => h.queryClient,
};
});
import { useChatController } from "./use-chat-controller";
-import { api } from "@multica/core/api";
+import { api, ApiError } from "@multica/core/api";
// --- Fixtures ---------------------------------------------------------------
function makeSession(
@@ -202,13 +220,19 @@ const sA = makeSession({ id: "sA", agent_id: "agent-a", updated_at: "2026-07-08T
const sB = makeSession({ id: "sB", agent_id: "agent-b", updated_at: "2026-07-08T02:00:00Z" });
const sC = makeSession({ id: "sC", agent_id: "agent-a", updated_at: "2026-07-08T01:00:00Z" });
-function setup(activeSessionId: string | null, sessions: ChatSession[], agents: Agent[]) {
+function setup(
+ activeSessionId: string | null,
+ sessions: ChatSession[],
+ agents: Agent[],
+ pendingTask: ChatPendingTask | null = null,
+) {
h.store.activeSessionId = activeSessionId;
h.store.selectedAgentId = null;
h.store.selectedProjectId = null;
h.sessions = sessions;
h.agents = agents;
h.projects = [];
+ h.pendingTask = pendingTask;
const { result } = renderHook(() => useChatController());
// Ignore any render-time store writes (self-heal etc.); we assert only the
// effect of the call under test.
@@ -494,6 +518,315 @@ describe("useChatController.archiveSession", () => {
});
});
+describe("useChatController queued task actions", () => {
+ beforeEach(() => {
+ vi.mocked(api.cancelTaskById).mockReset();
+ vi.mocked(api.clearQueuedChatTasks).mockReset();
+ vi.mocked(api.prioritizeQueuedChatTask).mockReset();
+ h.removeFromCaches.mockClear();
+ h.store.enqueuePendingSendRestore.mockClear();
+ h.store.pendingSendRestores = {};
+ h.queryClient.getQueryData.mockReset();
+ h.queryClient.setQueryData.mockReset();
+ h.queryClient.invalidateQueries.mockReset();
+ h.queryClient.cancelQueries.mockReset();
+ });
+
+ it("recovers an edited queued prompt through durable draft restore", async () => {
+ vi.mocked(api.cancelTaskById).mockResolvedValue({
+ id: "task-queued",
+ cancelled_chat_message: {
+ chat_session_id: "sA",
+ message_id: "message-queued",
+ content: "Revise this follow-up",
+ restore_to_input: true,
+ attachments: [],
+ },
+ } as Awaited<ReturnType<typeof api.cancelTaskById>>);
+ const result = setup("sA", [sA], [agentA]);
+
+ await act(async () => {
+ await result.current.handleEditQueuedTask("task-queued");
+ });
+
+ expect(api.cancelTaskById).toHaveBeenCalledWith("task-queued", {
+ queuedAction: "edit",
+ sessionId: "sA",
+ });
+ expect(h.removeFromCaches).toHaveBeenCalledWith(
+ expect.anything(),
+ "sA",
+ "message-queued",
+ );
+ expect(h.store.enqueuePendingSendRestore).not.toHaveBeenCalled();
+ expect(h.queryClient.invalidateQueries).toHaveBeenCalledWith(
+ expect.objectContaining({ queryKey: expect.arrayContaining(["draft-restores"]) }),
+ );
+ });
+
+ it("uses durable edit cancellation when Stop targets a queued head", async () => {
+ const taskId = "11111111-1111-4111-8111-111111111111";
+ const pending: ChatPendingTask = {
+ task_id: taskId,
+ status: "queued",
+ supports_queue: true,
+ queued_tasks: [],
+ };
+ h.queryClient.getQueryData.mockReturnValue(pending);
+ vi.mocked(api.cancelTaskById).mockResolvedValue({
+ id: taskId,
+ } as Awaited<ReturnType<typeof api.cancelTaskById>>);
+ const result = setup("sA", [sA], [agentA], pending);
+
+ act(() => result.current.handleStop());
+
+ await waitFor(() => {
+ expect(api.cancelTaskById).toHaveBeenCalledWith(taskId, {
+ queuedAction: "edit",
+ sessionId: "sA",
+ });
+ });
+ });
+
+ it("keeps the legacy synchronous restore path when queue capability is absent", async () => {
+ const taskId = "11111111-1111-4111-8111-111111111111";
+ const pending: ChatPendingTask = {
+ task_id: taskId,
+ status: "queued",
+ queued_tasks: [],
+ };
+ h.queryClient.getQueryData.mockReturnValue(pending);
+ vi.mocked(api.cancelTaskById).mockResolvedValue({
+ id: taskId,
+ cancelled_chat_message: {
+ chat_session_id: "sA",
+ message_id: "message-queued",
+ content: "Keep this prompt",
+ restore_to_input: true,
+ attachments: [],
+ },
+ } as Awaited<ReturnType<typeof api.cancelTaskById>>);
+ const result = setup("sA", [sA], [agentA], pending);
+
+ act(() => result.current.handleStop());
+
+ await waitFor(() => {
+ expect(api.cancelTaskById).toHaveBeenCalledWith(taskId, undefined);
+ expect(h.store.enqueuePendingSendRestore).toHaveBeenCalledWith(
+ expect.objectContaining({ content: "Keep this prompt" }),
+ );
+ });
+ });
+
+ it("falls back to active cancellation when a derived queued Stop loses the claim race", async () => {
+ const taskId = "11111111-1111-4111-8111-111111111111";
+ const pending: ChatPendingTask = {
+ task_id: taskId,
+ status: "queued",
+ supports_queue: true,
+ queued_tasks: [],
+ };
+ h.queryClient.getQueryData.mockReturnValue(pending);
+ vi.mocked(api.cancelTaskById)
+ .mockRejectedValueOnce(new ApiError("task is no longer queued", 409, "Conflict"))
+ .mockResolvedValueOnce({
+ id: taskId,
+ cancelled_chat_message: {
+ chat_session_id: "sA",
+ message_id: "message-queued",
+ content: "Stop and restore this",
+ restore_to_input: true,
+ attachments: [],
+ },
+ } as Awaited<ReturnType<typeof api.cancelTaskById>>);
+ const result = setup("sA", [sA], [agentA], pending);
+
+ act(() => result.current.handleStop());
+
+ await waitFor(() => {
+ expect(api.cancelTaskById).toHaveBeenNthCalledWith(1, taskId, {
+ queuedAction: "edit",
+ sessionId: "sA",
+ });
+ expect(api.cancelTaskById).toHaveBeenNthCalledWith(2, taskId);
+ expect(h.store.enqueuePendingSendRestore).toHaveBeenCalledWith(
+ expect.objectContaining({ content: "Stop and restore this" }),
+ );
+ });
+ });
+
+ it("removes a queued prompt without restoring it", async () => {
+ vi.mocked(api.cancelTaskById).mockResolvedValue({
+ id: "task-queued",
+ cancelled_chat_message: {
+ chat_session_id: "sA",
+ message_id: "message-queued",
+ content: "Discard this follow-up",
+ restore_to_input: false,
+ attachments: [],
+ },
+ } as Awaited<ReturnType<typeof api.cancelTaskById>>);
+ const result = setup("sA", [sA], [agentA]);
+
+ await act(async () => {
+ await result.current.handleRemoveQueuedTask("task-queued");
+ });
+
+ expect(api.cancelTaskById).toHaveBeenCalledWith("task-queued", {
+ queuedAction: "remove",
+ sessionId: "sA",
+ });
+ expect(h.removeFromCaches).toHaveBeenCalled();
+ expect(h.store.enqueuePendingSendRestore).not.toHaveBeenCalled();
+ });
+
+ it("restores the pending snapshot when queued-only cancellation loses a race", async () => {
+ const pending: ChatPendingTask = {
+ task_id: "task-active",
+ status: "running",
+ queued_tasks: [
+ { task_id: "task-queued", status: "queued", created_at: "2026-07-01T00:00:01Z" },
+ ],
+ };
+ h.queryClient.getQueryData.mockReturnValue(pending);
+ vi.mocked(api.cancelTaskById).mockRejectedValue(new Error("task is no longer queued"));
+ const result = setup("sA", [sA], [agentA], pending);
+
+ await act(async () => {
+ await result.current.handleRemoveQueuedTask("task-queued");
+ });
+
+ expect(h.queryClient.setQueryData).toHaveBeenLastCalledWith(
+ expect.anything(),
+ pending,
+ );
+ });
+
+ it("refetches the durable restore when a queued edit response is lost", async () => {
+ vi.mocked(api.cancelTaskById).mockRejectedValue(new Error("response lost"));
+ const result = setup("sA", [sA], [agentA]);
+
+ await act(async () => {
+ await result.current.handleEditQueuedTask("task-queued");
+ });
+
+ expect(h.queryClient.invalidateQueries).toHaveBeenCalledWith(
+ expect.objectContaining({ queryKey: expect.arrayContaining(["draft-restores"]) }),
+ );
+ expect(h.store.enqueuePendingSendRestore).not.toHaveBeenCalled();
+ });
+
+ it("clears the queue with one session-scoped request", async () => {
+ vi.mocked(api.clearQueuedChatTasks).mockResolvedValue();
+ const pending: ChatPendingTask = {
+ task_id: "task-active",
+ status: "running",
+ queued_tasks: [
+ {
+ task_id: "task-1",
+ status: "queued",
+ created_at: "2026-07-01T00:00:01Z",
+ message_id: "message-1",
+ },
+ {
+ task_id: "task-2",
+ status: "queued",
+ created_at: "2026-07-01T00:00:02Z",
+ message_id: "message-2",
+ },
+ ],
+ };
+ h.queryClient.getQueryData.mockReturnValue(pending);
+ const result = setup("sA", [sA], [agentA], pending);
+
+ await act(async () => {
+ await result.current.handleClearQueuedTasks();
+ });
+
+ expect(api.clearQueuedChatTasks).toHaveBeenCalledTimes(1);
+ expect(api.clearQueuedChatTasks).toHaveBeenCalledWith("sA");
+ expect(api.cancelTaskById).not.toHaveBeenCalled();
+ expect(h.removeFromCaches).toHaveBeenCalledWith(
+ expect.anything(),
+ "sA",
+ "message-1",
+ );
+ expect(h.removeFromCaches).toHaveBeenCalledWith(
+ expect.anything(),
+ "sA",
+ "message-2",
+ );
+ });
+
+ it("refetches messages when the clear response is lost", async () => {
+ vi.mocked(api.clearQueuedChatTasks).mockRejectedValue(new Error("response lost"));
+ const result = setup("sA", [sA], [agentA]);
+
+ await act(async () => {
+ await result.current.handleClearQueuedTasks();
+ });
+
+ expect(h.queryClient.invalidateQueries).toHaveBeenCalledWith(
+ expect.objectContaining({ queryKey: expect.arrayContaining(["messages"]) }),
+ );
+ expect(h.queryClient.invalidateQueries).toHaveBeenCalledWith(
+ expect.objectContaining({ queryKey: expect.arrayContaining(["messages-page"]) }),
+ );
+ });
+
+ it("prioritizes send-now before stopping the active task", async () => {
+ vi.mocked(api.prioritizeQueuedChatTask).mockResolvedValue({
+ task_id: "task-queued",
+ active_task_id: "task-active",
+ });
+ vi.mocked(api.cancelTaskById).mockResolvedValue({
+ id: "task-active",
+ } as Awaited<ReturnType<typeof api.cancelTaskById>>);
+ const result = setup("sA", [sA], [agentA], {
+ task_id: "task-active",
+ status: "running",
+ queued_tasks: [
+ { task_id: "task-queued", status: "queued", created_at: "2026-07-01T00:00:01Z" },
+ ],
+ });
+
+ await act(async () => {
+ await result.current.handleSendQueuedTaskNow("task-queued");
+ });
+
+ expect(api.prioritizeQueuedChatTask).toHaveBeenCalledWith("sA", "task-queued");
+ expect(api.cancelTaskById).toHaveBeenCalledWith("task-active", undefined);
+ expect(
+ vi.mocked(api.prioritizeQueuedChatTask).mock.invocationCallOrder[0],
+ ).toBeLessThan(vi.mocked(api.cancelTaskById).mock.invocationCallOrder[0]!);
+ });
+
+ it("restores the pending snapshot when send-now loses a queued race", async () => {
+ const pending: ChatPendingTask = {
+ task_id: "task-active",
+ status: "running",
+ queued_tasks: [
+ { task_id: "task-first", status: "queued", created_at: "2026-07-01T00:00:01Z" },
+ { task_id: "task-stale", status: "queued", created_at: "2026-07-01T00:00:02Z" },
+ ],
+ };
+ h.queryClient.getQueryData.mockReturnValue(pending);
+ vi.mocked(api.prioritizeQueuedChatTask).mockRejectedValue(
+ new Error("task is no longer queued"),
+ );
+ const result = setup("sA", [sA], [agentA], pending);
+
+ await act(async () => {
+ await result.current.handleSendQueuedTaskNow("task-stale");
+ });
+
+ expect(h.queryClient.setQueryData).toHaveBeenLastCalledWith(
+ expect.anything(),
+ pending,
+ );
+ });
+});
+
// MUL-4360 mount race: `activeSessionId` is persisted, so on a bare `/chat`
// navigation the page restores the last session as active for one frame before
// its URL→store effect clears it back to null. The auto-mark-read must NOT fire
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index a645658653..d221707b13 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -34,8 +34,12 @@ import {
useSetChatSessionArchived,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
-import { removeChatMessageFromCaches } from "@multica/core/realtime";
+import {
+ enqueuePendingChatTask,
+ hideQueuedChatMessages,
+} from "@multica/core/chat/pending";
import { useChatDraftRestore } from "./use-chat-draft-restore";
+import { useChatTaskActions } from "./use-chat-task-actions";
import { useChatProjectContextSupport } from "./use-chat-project-context-support";
import { createLogger } from "@multica/core/logger";
import type {
@@ -150,6 +154,37 @@ export function hasInFlightPendingTask(
const pending = qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId));
return Boolean(pending?.task_id);
}
+
+export function seedAcceptedPendingTask(
+ qc: ReturnType<typeof useQueryClient>,
+ sessionId: string,
+ task: {
+ task_id: string;
+ created_at: string;
+ message_id: string;
+ content: string;
+ supports_queue?: boolean;
+ },
+) {
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(sessionId),
+ (old) => {
+ const next = enqueuePendingChatTask(old, {
+ task_id: task.task_id,
+ status: "queued",
+ created_at: task.created_at,
+ message_id: task.message_id,
+ content: task.content,
+ });
+ if (task.supports_queue === true || old?.supports_queue === true) {
+ next.supports_queue = true;
+ }
+ return next;
+ },
+ );
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
+}
+
const CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX = 1_000_000;
function appendChatMessageToLatestPageCache(
@@ -229,7 +264,14 @@ export function useChatController(opts?: { isActive?: boolean }) {
} = useInfiniteQuery(chatMessagesPageOptions(activeSessionId ?? ""));
const messagePages = activeSessionId ? rawMessagePages?.pages ?? [] : [];
- const messages = [...messagePages].reverse().flatMap((page) => page.messages);
+ const allMessages = [...messagePages].reverse().flatMap((page) => page.messages);
+
+ const { data: pendingTask, isLoading: pendingTaskLoading } = useQuery(
+ pendingChatTaskOptions(activeSessionId ?? ""),
+ );
+ const showSkeleton =
+ !!activeSessionId && (messagesLoading || pendingTaskLoading);
+ const messages = hideQueuedChatMessages(allMessages, pendingTask);
const olderMessageCount = messagePages
.slice(1)
.reduce((sum, page) => sum + page.messages.length, 0);
@@ -237,11 +279,6 @@ export function useChatController(opts?: { isActive?: boolean }) {
messages.length > 0
? CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX - olderMessageCount
: 0;
- const showSkeleton = !!activeSessionId && messagesLoading;
-
- const { data: pendingTask } = useQuery(
- pendingChatTaskOptions(activeSessionId ?? ""),
- );
const pendingTaskId = pendingTask?.task_id ?? null;
const stopRequestedBeforeTaskRef = useRef(false);
// Durable deferred-cancellation draft restores (#5219). The whole lifecycle —
@@ -256,6 +293,13 @@ export function useChatController(opts?: { isActive?: boolean }) {
const appForeground = useAppForeground();
const { restoreDraftRequest, enqueueLocalRestore, handleRestoreDraftApplied } =
useChatDraftRestore(activeSessionId, isActive && appForeground);
+ const {
+ cancelChatTask,
+ handleEditQueuedTask,
+ handleRemoveQueuedTask,
+ handleClearQueuedTasks,
+ handleSendQueuedTaskNow,
+ } = useChatTaskActions(activeSessionId, enqueueLocalRestore);
// Nonce handed to ChatInput to pull focus into the compose box when a new
// chat starts. Bumped by handleNewChat / handleStartNewChat only, so
// selecting an existing chat or a deep link never steals focus.
@@ -435,55 +479,6 @@ export function useChatController(opts?: { isActive?: boolean }) {
// (MUL-5181 L2); surfaces only forward whether the affordance exists.
const uploadEnabled = !!activeAgent;
- const cancelChatTask = useCallback(
- async (
- taskId: string,
- sessionId: string,
- options: { restoreDraftToInput: boolean; source: string },
- ) => {
- apiLogger.info("cancelTask.start", {
- taskId,
- sessionId,
- source: options.source,
- });
- qc.setQueryData(chatKeys.pendingTask(sessionId), {});
-
- try {
- const result = await api.cancelTaskById(taskId);
- const restored = result.cancelled_chat_message;
- if (restored?.restore_to_input) {
- removeChatMessageFromCaches(qc, restored.chat_session_id, restored.message_id);
- if (options.restoreDraftToInput && restored.chat_session_id === sessionId) {
- enqueueLocalRestore({
- id: restored.message_id,
- content: restored.content,
- attachments: restored.attachments,
- sessionId: restored.chat_session_id,
- });
- }
- }
- qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
- qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
- apiLogger.info("cancelTask.success", {
- taskId,
- sessionId,
- restoredToInput: !!restored?.restore_to_input && options.restoreDraftToInput,
- });
- return result;
- } catch (err) {
- apiLogger.warn("cancelTask.error (task may have already finished)", {
- taskId,
- sessionId,
- err,
- });
- qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
- qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
- return null;
- }
- },
- [qc, enqueueLocalRestore],
- );
-
const handleSend = useCallback(
async (
content: string,
@@ -505,6 +500,12 @@ export function useChatController(opts?: { isActive?: boolean }) {
});
return false;
}
+ if (pendingTaskId && pendingTask?.supports_queue !== true) {
+ apiLogger.warn("sendChatMessage skipped: server does not support follow-up queues", {
+ sessionId: activeSessionId,
+ });
+ return false;
+ }
if (!isAgentRuntimeBound) {
toast.error(t(($) => $.input.runtime_required_toast));
return false;
@@ -595,10 +596,12 @@ export function useChatController(opts?: { isActive?: boolean }) {
chatKeys.messages(sessionId),
(old) => (old ? [...old, sent] : [sent]),
);
- qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {
+ seedAcceptedPendingTask(qc, sessionId, {
task_id: result.task_id,
- status: "queued",
created_at: result.created_at,
+ message_id: result.message_id,
+ content: finalContent,
+ supports_queue: result.supports_queue,
});
// Cache primed → publish the new active session, but only if the user
// hasn't navigated away mid-send. See isStillOnComposeTarget. commitInput
@@ -639,6 +642,8 @@ export function useChatController(opts?: { isActive?: boolean }) {
activeSessionId,
activeAgent,
isAgentArchived,
+ pendingTask,
+ pendingTaskId,
isAgentRuntimeBound,
ensureSession,
cancelChatTask,
@@ -837,6 +842,10 @@ export function useChatController(opts?: { isActive?: boolean }) {
// actions
handleSend,
handleStop,
+ handleSendQueuedTaskNow,
+ handleEditQueuedTask,
+ handleRemoveQueuedTask,
+ handleClearQueuedTasks,
uploadEnabled,
handleNewChat,
handleStartNewChat,
diff --git a/packages/views/chat/components/use-chat-task-actions.ts b/packages/views/chat/components/use-chat-task-actions.ts
new file mode 100644
index 0000000000..da861e66ee
--- /dev/null
+++ b/packages/views/chat/components/use-chat-task-actions.ts
@@ -0,0 +1,235 @@
+"use client";
+
+import { useCallback } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { api, ApiError } from "@multica/core/api";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { chatKeys } from "@multica/core/chat/queries";
+import {
+ prioritizePendingChatTask,
+ removePendingChatTask,
+} from "@multica/core/chat/pending";
+import { removeChatMessageFromCaches } from "@multica/core/realtime";
+import { createLogger } from "@multica/core/logger";
+import type {
+ Attachment,
+ CancelTaskResponse,
+ ChatPendingTask,
+} from "@multica/core/types";
+import { useT } from "../../i18n";
+
+const apiLogger = createLogger("chat.api");
+
+type EnqueueLocalRestore = (restore: {
+ id: string;
+ content: string;
+ attachments?: Attachment[];
+ sessionId: string;
+}) => void;
+
+type CancelOptions = {
+ restoreDraftToInput: boolean;
+ source: string;
+ queuedAction?: "edit" | "remove";
+};
+
+export function useChatTaskActions(
+ activeSessionId: string | null,
+ enqueueLocalRestore: EnqueueLocalRestore,
+) {
+ const { t } = useT("chat");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+
+ const cancelChatTask = useCallback(
+ async (
+ taskId: string,
+ sessionId: string,
+ options: CancelOptions,
+ ): Promise<CancelTaskResponse | null> => {
+ apiLogger.info("cancelTask.start", {
+ taskId,
+ sessionId,
+ source: options.source,
+ });
+ const pendingKey = chatKeys.pendingTask(sessionId);
+ await qc.cancelQueries({ queryKey: pendingKey });
+ const pendingSnapshot = qc.getQueryData<ChatPendingTask>(pendingKey);
+ const derivedQueuedAction = !options.queuedAction &&
+ (options.restoreDraftToInput &&
+ pendingSnapshot?.task_id === taskId &&
+ pendingSnapshot.status === "queued" &&
+ pendingSnapshot.supports_queue === true);
+ let queuedAction = options.queuedAction ??
+ (derivedQueuedAction ? "edit" : undefined);
+ qc.setQueryData<ChatPendingTask>(
+ pendingKey,
+ (old) => removePendingChatTask(old, taskId),
+ );
+
+ try {
+ let result: CancelTaskResponse;
+ try {
+ result = await api.cancelTaskById(
+ taskId,
+ queuedAction ? { queuedAction, sessionId } : undefined,
+ );
+ } catch (err) {
+ if (!(derivedQueuedAction && err instanceof ApiError && err.status === 409)) {
+ throw err;
+ }
+ // The daemon claimed the task after our cached queued snapshot.
+ // Preserve Stop semantics by cancelling its new active state.
+ queuedAction = undefined;
+ result = await api.cancelTaskById(taskId);
+ }
+ const restored = result.cancelled_chat_message;
+ if (restored) {
+ removeChatMessageFromCaches(qc, restored.chat_session_id, restored.message_id);
+ if (
+ restored.restore_to_input &&
+ !queuedAction &&
+ options.restoreDraftToInput &&
+ restored.chat_session_id === sessionId
+ ) {
+ enqueueLocalRestore({
+ id: restored.message_id,
+ content: restored.content,
+ attachments: restored.attachments,
+ sessionId: restored.chat_session_id,
+ });
+ }
+ }
+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
+ qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
+ apiLogger.info("cancelTask.success", {
+ taskId,
+ sessionId,
+ restoredToInput: !!restored?.restore_to_input && options.restoreDraftToInput,
+ });
+ return result;
+ } catch (err) {
+ qc.setQueryData(pendingKey, pendingSnapshot);
+ apiLogger.warn("cancelTask.error (task may have already finished)", {
+ taskId,
+ sessionId,
+ err,
+ });
+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
+ qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
+ return null;
+ } finally {
+ qc.invalidateQueries({ queryKey: pendingKey });
+ if (queuedAction === "edit") {
+ qc.invalidateQueries({ queryKey: chatKeys.draftRestores(sessionId) });
+ }
+ if (wsId) qc.invalidateQueries({ queryKey: chatKeys.pendingTasks(wsId) });
+ }
+ },
+ [qc, enqueueLocalRestore, wsId],
+ );
+
+ const handleEditQueuedTask = useCallback(
+ async (taskId: string) => {
+ if (!activeSessionId) return;
+ const result = await cancelChatTask(taskId, activeSessionId, {
+ restoreDraftToInput: true,
+ source: "queued-message-edit",
+ queuedAction: "edit",
+ });
+ if (!result) toast.error(t(($) => $.queue.action_failed_toast));
+ },
+ [activeSessionId, cancelChatTask, t],
+ );
+
+ const handleRemoveQueuedTask = useCallback(
+ async (taskId: string) => {
+ if (!activeSessionId) return;
+ const result = await cancelChatTask(taskId, activeSessionId, {
+ restoreDraftToInput: false,
+ source: "queued-message-remove",
+ queuedAction: "remove",
+ });
+ if (!result) toast.error(t(($) => $.queue.action_failed_toast));
+ },
+ [activeSessionId, cancelChatTask, t],
+ );
+
+ const handleClearQueuedTasks = useCallback(async () => {
+ if (!activeSessionId) return;
+ const pendingKey = chatKeys.pendingTask(activeSessionId);
+ await qc.cancelQueries({ queryKey: pendingKey });
+ try {
+ await api.clearQueuedChatTasks(activeSessionId);
+ const pending = qc.getQueryData<ChatPendingTask>(pendingKey);
+ for (const task of pending?.queued_tasks ?? []) {
+ if (task.message_id) {
+ removeChatMessageFromCaches(qc, activeSessionId, task.message_id);
+ }
+ }
+ qc.setQueryData<ChatPendingTask>(pendingKey, (old) =>
+ (old?.queued_tasks ?? []).reduce<ChatPendingTask | undefined>(
+ (current, task) => removePendingChatTask(current, task.task_id),
+ old,
+ )
+ );
+ } catch (err) {
+ apiLogger.warn("clearQueuedTasks.error", {
+ sessionId: activeSessionId,
+ err,
+ });
+ toast.error(t(($) => $.queue.action_failed_toast));
+ } finally {
+ qc.invalidateQueries({ queryKey: pendingKey });
+ qc.invalidateQueries({ queryKey: chatKeys.messages(activeSessionId) });
+ qc.invalidateQueries({ queryKey: chatKeys.messagesPage(activeSessionId) });
+ if (wsId) qc.invalidateQueries({ queryKey: chatKeys.pendingTasks(wsId) });
+ }
+ }, [activeSessionId, qc, t, wsId]);
+
+ const handleSendQueuedTaskNow = useCallback(
+ async (taskId: string) => {
+ if (!activeSessionId) return;
+ const pendingKey = chatKeys.pendingTask(activeSessionId);
+ await qc.cancelQueries({ queryKey: pendingKey });
+ const pendingSnapshot = qc.getQueryData<ChatPendingTask>(pendingKey);
+ qc.setQueryData<ChatPendingTask>(
+ pendingKey,
+ (old) => prioritizePendingChatTask(old, taskId),
+ );
+ let prioritizeSucceeded = false;
+ try {
+ const result = await api.prioritizeQueuedChatTask(activeSessionId, taskId);
+ if (result.task_id !== taskId) throw new Error("invalid prioritize response");
+ prioritizeSucceeded = true;
+ if (result.active_task_id) {
+ const cancelled = await cancelChatTask(result.active_task_id, activeSessionId, {
+ restoreDraftToInput: true,
+ source: "queued-message-send-now",
+ });
+ if (!cancelled) throw new Error("current task could not be stopped");
+ }
+ } catch (err) {
+ if (!prioritizeSucceeded) qc.setQueryData(pendingKey, pendingSnapshot);
+ apiLogger.warn("sendQueuedTaskNow.error", {
+ taskId,
+ sessionId: activeSessionId,
+ err,
+ });
+ toast.error(t(($) => $.queue.action_failed_toast));
+ } finally {
+ qc.invalidateQueries({ queryKey: pendingKey });
+ }
+ },
+ [activeSessionId, cancelChatTask, qc, t],
+ );
+
+ return {
+ cancelChatTask,
+ handleEditQueuedTask,
+ handleRemoveQueuedTask,
+ handleClearQueuedTasks,
+ handleSendQueuedTaskNow,
+ };
+}
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index aa82eec11a..3d61685455 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -18,6 +18,7 @@
"placeholder_named": "Message {{name}}…",
"placeholder_default": "Start a message…",
"send_tooltip": "Send",
+ "queue_send_tooltip": "Queue message",
"stop_tooltip": "Stop",
"send_failed_toast": "Failed to send message",
"send_blocked_toast": "Message not sent — you no longer have permission to use this agent",
@@ -31,6 +32,16 @@
"no_projects": "No projects yet",
"project_context_unsupported": "Project description won't apply — this agent's daemon needs an upgrade"
},
+ "queue": {
+ "title_one": "{{count}} queued message",
+ "title_other": "{{count}} queued messages",
+ "clear": "Clear all",
+ "send_now": "Send now",
+ "edit": "Edit queued message",
+ "remove": "Remove queued message",
+ "fallback": "Queued message",
+ "action_failed_toast": "Couldn't update the queued message"
+ },
"message_list": {
"show_details": "Show details",
"replied_in": "Replied in {{elapsed}}",
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index 1c02524b02..99e9296196 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -17,6 +17,7 @@
"placeholder_named": "{{name}} にメッセージ…",
"placeholder_default": "メッセージを入力…",
"send_tooltip": "送信",
+ "queue_send_tooltip": "キューに追加",
"stop_tooltip": "停止",
"send_failed_toast": "メッセージを送信できませんでした",
"send_blocked_toast": "メッセージは送信されませんでした — このエージェントを使用する権限がありません",
@@ -30,6 +31,15 @@
"no_projects": "プロジェクトがまだありません",
"project_context_unsupported": "プロジェクトの説明は適用されません——このエージェントのデーモンのアップグレードが必要です"
},
+ "queue": {
+ "title_other": "キュー内のメッセージ {{count}} 件",
+ "clear": "すべて削除",
+ "send_now": "今すぐ送信",
+ "edit": "キュー内のメッセージを編集",
+ "remove": "キューから削除",
+ "fallback": "キュー内のメッセージ",
+ "action_failed_toast": "キュー内のメッセージを更新できませんでした"
+ },
"message_list": {
"show_details": "詳細を表示",
"replied_in": "{{elapsed}}で返信",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index d3984fe58f..068ebee05f 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -17,6 +17,7 @@
"placeholder_named": "{{name}}에게 메시지 보내기…",
"placeholder_default": "메시지 입력…",
"send_tooltip": "보내기",
+ "queue_send_tooltip": "대기열에 추가",
"stop_tooltip": "중지",
"send_failed_toast": "메시지를 보내지 못했습니다",
"send_blocked_toast": "메시지가 전송되지 않았습니다 — 이 에이전트를 사용할 권한이 없습니다",
@@ -30,6 +31,15 @@
"no_projects": "아직 프로젝트가 없습니다",
"project_context_unsupported": "프로젝트 설명이 적용되지 않습니다 — 이 에이전트의 데몬 업그레이드가 필요합니다"
},
+ "queue": {
+ "title_other": "대기 중인 메시지 {{count}}개",
+ "clear": "모두 지우기",
+ "send_now": "지금 보내기",
+ "edit": "대기 중인 메시지 편집",
+ "remove": "대기열에서 삭제",
+ "fallback": "대기 중인 메시지",
+ "action_failed_toast": "대기 중인 메시지를 업데이트하지 못했습니다"
+ },
"message_list": {
"show_details": "세부 정보 보기",
"replied_in": "{{elapsed}} 만에 답변",
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index e5f6d592c2..3230252553 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -17,6 +17,7 @@
"placeholder_named": "给 {{name}} 发消息…",
"placeholder_default": "输入消息…",
"send_tooltip": "发送",
+ "queue_send_tooltip": "排队发送",
"stop_tooltip": "停止",
"send_failed_toast": "发送消息失败",
"send_blocked_toast": "消息未发送——你已没有该智能体的使用权限",
@@ -30,6 +31,15 @@
"no_projects": "还没有项目",
"project_context_unsupported": "项目描述不会生效——该智能体的守护进程版本过旧,需要升级"
},
+ "queue": {
+ "title_other": "{{count}} 条排队消息",
+ "clear": "全部清空",
+ "send_now": "立即发送",
+ "edit": "编辑排队消息",
+ "remove": "移除排队消息",
+ "fallback": "排队消息",
+ "action_failed_toast": "无法更新排队消息"
+ },
"message_list": {
"show_details": "查看详情",
"replied_in": "{{elapsed}} 内回复",
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index a6de9574cc..ca14a91fe7 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1465,6 +1465,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/messages", h.ListChatMessages)
r.Get("/messages/page", h.ListChatMessagesPage)
r.Get("/pending-task", h.GetPendingChatTask)
+ r.Delete("/queued-tasks", h.ClearQueuedChatTasks)
+ r.Post("/queued-tasks/{taskId}/prioritize", h.PrioritizeQueuedChatTask)
r.Post("/read", h.MarkChatSessionRead)
// Deferred-cancellation draft restores (#5219):
// creator-only fetch + idempotent consume.
diff --git a/server/internal/handler/agent_builder_test.go b/server/internal/handler/agent_builder_test.go
index 5f80e76e96..0843b32aca 100644
--- a/server/internal/handler/agent_builder_test.go
+++ b/server/internal/handler/agent_builder_test.go
@@ -3,6 +3,7 @@ package handler
import (
"context"
"encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
"strings"
@@ -12,6 +13,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -994,6 +996,135 @@ func TestSendDirectChatMessageWaitsForUncommittedRebind(t *testing.T) {
}
}
+func TestSendDirectChatMessageRejectsSessionArchivedWhileWaitingForLock(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID := createHandlerTestAgent(t, "Chat Send Archive Race", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("load chat session: %v", err)
+ }
+ agent, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatalf("load chat agent: %v", err)
+ }
+
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin archive tx: %v", err)
+ }
+ defer tx.Rollback(context.Background())
+ holderPID := holderBackendPID(t, ctx, tx)
+ if _, err := tx.Exec(ctx, `
+ UPDATE chat_session SET status = 'archived' WHERE id = $1
+ `, sessionID); err != nil {
+ t.Fatalf("archive chat session: %v", err)
+ }
+
+ results := make(chan error, 1)
+ go func() {
+ _, err := testHandler.TaskService.SendDirectChatMessage(
+ context.Background(), session, agent, parseUUID(testUserID),
+ "must not enqueue after archive", nil, "member", parseUUID(testUserID),
+ )
+ results <- err
+ }()
+
+ if !waitForWaiterBlockedBy(t, holderPID, 10*time.Second) {
+ t.Fatal("send did not wait for the session archive transaction")
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit archive: %v", err)
+ }
+
+ select {
+ case err := <-results:
+ if !errors.Is(err, service.ErrChatSessionArchived) {
+ t.Fatalf("send after archive error = %v, want ErrChatSessionArchived", err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("send did not return after archive committed")
+ }
+
+ var taskCount, messageCount int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1
+ `, sessionID).Scan(&taskCount); err != nil {
+ t.Fatalf("count chat tasks: %v", err)
+ }
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM chat_message WHERE chat_session_id = $1
+ `, sessionID).Scan(&messageCount); err != nil {
+ t.Fatalf("count chat messages: %v", err)
+ }
+ if taskCount != 0 || messageCount != 0 {
+ t.Fatalf("archived send persisted tasks=%d messages=%d, want zero", taskCount, messageCount)
+ }
+}
+
+func TestDeleteBuilderSessionLocksAgentBeforeTasks(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ created := newBuilderSession(t)
+ taskID := insertPendingChatTask(t, created.BuilderAgentID, created.SessionID, "queued")
+
+ claimTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin claim tx: %v", err)
+ }
+ defer claimTx.Rollback(context.Background())
+ qtx := testHandler.Queries.WithTx(claimTx)
+ agent, err := qtx.GetAgentForClaimUpdate(ctx, parseUUID(created.BuilderAgentID))
+ if err != nil {
+ t.Fatalf("lock builder agent: %v", err)
+ }
+ holderPID := holderBackendPID(t, ctx, claimTx)
+
+ deleteReq := withURLParam(
+ newRequestAs(testUserID, http.MethodDelete, "/api/chat/sessions/"+created.SessionID, nil),
+ "sessionId",
+ created.SessionID,
+ )
+ deleteReq = withChatTestWorkspaceCtx(t, deleteReq)
+ deleteCodes := make(chan int, 1)
+ go func() {
+ w := httptest.NewRecorder()
+ testHandler.DeleteChatSession(w, deleteReq)
+ deleteCodes <- w.Code
+ }()
+
+ if !waitForWaiterBlockedBy(t, holderPID, 10*time.Second) {
+ t.Fatal("delete did not wait for the builder agent lock")
+ }
+ claimed, err := qtx.ClaimAgentTask(ctx, db.ClaimAgentTaskParams{
+ AgentID: agent.ID,
+ PrepareLeaseSecs: 30,
+ })
+ if err != nil {
+ t.Fatalf("claim while delete waits for agent lock: %v", err)
+ }
+ if got := uuidToString(claimed.ID); got != taskID {
+ t.Fatalf("claimed task = %q, want %q", got, taskID)
+ }
+ if err := claimTx.Rollback(ctx); err != nil {
+ t.Fatalf("release claim transaction: %v", err)
+ }
+
+ select {
+ case code := <-deleteCodes:
+ if code != http.StatusNoContent {
+ t.Fatalf("delete returned %d, want 204", code)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("delete did not complete after agent lock released")
+ }
+}
+
// The mirror image: a send that has not committed yet must hold off a rebind,
// and the rebind must then see the now-visible pending task and refuse. Without
// the lock on the switch side, GetPendingChatTask cannot see the uncommitted
diff --git a/server/internal/handler/cancel_task_by_user_test.go b/server/internal/handler/cancel_task_by_user_test.go
index 63f28ace92..35b32a94e0 100644
--- a/server/internal/handler/cancel_task_by_user_test.go
+++ b/server/internal/handler/cancel_task_by_user_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"time"
+ "github.com/multica-ai/multica/server/internal/util"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -143,6 +144,202 @@ func cancelTaskByUserRequest(t *testing.T, userID, taskID string) *http.Request
return withChatTestWorkspaceCtx(t, req)
}
+func cancelQueuedTaskByUserRequest(
+ t *testing.T,
+ userID, taskID, sessionID, action string,
+) *http.Request {
+ t.Helper()
+ req := newRequestAs(
+ userID,
+ http.MethodPost,
+ "/api/tasks/"+taskID+"/cancel?expected_status=queued&chat_session_id="+
+ sessionID+"&queue_action="+action,
+ nil,
+ )
+ req = withURLParam(req, "taskId", taskID)
+ return withChatTestWorkspaceCtx(t, req)
+}
+
+func TestCancelTaskByUser_QueuedOnlyDoesNotCancelPromotedTask(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "CancelQueuedOnlyAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := insertPendingChatTask(t, agentID, sessionID, "running")
+ req := newRequestAs(
+ testUserID,
+ http.MethodPost,
+ "/api/tasks/"+taskID+"/cancel?expected_status=queued&chat_session_id="+sessionID+"&queue_action=remove",
+ nil,
+ )
+ req = withURLParam(req, "taskId", taskID)
+ w := httptest.NewRecorder()
+ testHandler.CancelTaskByUser(w, withChatTestWorkspaceCtx(t, req))
+
+ if w.Code != http.StatusConflict {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := taskStatus(t, taskID); got != "running" {
+ t.Fatalf("queued-only cancellation changed promoted task status to %q", got)
+ }
+}
+
+func TestCancelTaskByUser_QueuedEditPersistsDraftRestore(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "QueuedEditRestoreAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID, messageID, attachmentID := insertQueuedChatInputWithAttachment(
+ t,
+ agentID,
+ sessionID,
+ "edit this queued prompt",
+ )
+
+ w := httptest.NewRecorder()
+ testHandler.CancelTaskByUser(
+ w,
+ cancelQueuedTaskByUserRequest(t, testUserID, taskID, sessionID, "edit"),
+ )
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := taskStatus(t, taskID); got != "cancelled" {
+ t.Fatalf("queued edit task status = %q, want cancelled", got)
+ }
+
+ var restoreCount int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*)
+ FROM chat_draft_restore
+ WHERE id = $1
+ AND chat_session_id = $2
+ AND task_id = $3
+ AND content = 'edit this queued prompt'
+ AND $4::uuid = ANY(attachment_ids)
+ `, messageID, sessionID, taskID, attachmentID).Scan(&restoreCount); err != nil {
+ t.Fatalf("read durable queued edit restore: %v", err)
+ }
+ if restoreCount != 1 {
+ t.Fatalf("queued edit created %d durable restore rows", restoreCount)
+ }
+
+ var messageCount int
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT count(*) FROM chat_message WHERE id = $1`,
+ messageID,
+ ).Scan(&messageCount); err != nil {
+ t.Fatalf("count edited queued message: %v", err)
+ }
+ if messageCount != 0 {
+ t.Fatalf("queued edit left %d input messages", messageCount)
+ }
+ var attachmentMessageID *string
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT chat_message_id::text FROM attachment WHERE id = $1`,
+ attachmentID,
+ ).Scan(&attachmentMessageID); err != nil {
+ t.Fatalf("read detached queued attachment: %v", err)
+ }
+ if attachmentMessageID != nil {
+ t.Fatalf("queued edit attachment still bound to %q", *attachmentMessageID)
+ }
+}
+
+func TestCancelTaskByUser_QueuedEditRollsBackOnRestoreFailure(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "QueuedEditRollbackAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID, messageID, attachmentID := insertQueuedChatInputWithAttachment(
+ t,
+ agentID,
+ sessionID,
+ "do not lose this queued prompt",
+ )
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO chat_draft_restore (id, chat_session_id, task_id, content, attachment_ids)
+ VALUES ($1, $2, $3, 'collision', '{}'::uuid[])
+ `, messageID, sessionID, taskID); err != nil {
+ t.Fatalf("seed restore collision: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_draft_restore WHERE id = $1`, messageID)
+ })
+
+ w := httptest.NewRecorder()
+ testHandler.CancelTaskByUser(
+ w,
+ cancelQueuedTaskByUserRequest(t, testUserID, taskID, sessionID, "edit"),
+ )
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := taskStatus(t, taskID); got != "queued" {
+ t.Fatalf("failed queued edit left task status %q", got)
+ }
+
+ var bindingCount int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*)
+ FROM chat_message AS message
+ JOIN attachment ON attachment.chat_message_id = message.id
+ WHERE message.id = $1 AND attachment.id = $2
+ `, messageID, attachmentID).Scan(&bindingCount); err != nil {
+ t.Fatalf("read rolled back queued input: %v", err)
+ }
+ if bindingCount != 1 {
+ t.Fatalf("failed queued edit did not roll back input binding: count = %d", bindingCount)
+ }
+}
+
+func TestCancelTaskByUser_QueuedRemoveDeletesAttachment(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "QueuedRemoveAttachmentAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID, messageID, attachmentID := insertQueuedChatInputWithAttachment(
+ t,
+ agentID,
+ sessionID,
+ "discard this queued prompt",
+ )
+
+ w := httptest.NewRecorder()
+ testHandler.CancelTaskByUser(
+ w,
+ cancelQueuedTaskByUserRequest(t, testUserID, taskID, sessionID, "remove"),
+ )
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if got := taskStatus(t, taskID); got != "cancelled" {
+ t.Fatalf("queued remove task status = %q, want cancelled", got)
+ }
+
+ var rows int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT
+ (SELECT count(*) FROM chat_message WHERE id = $1) +
+ (SELECT count(*) FROM attachment WHERE id = $2)
+ `, messageID, attachmentID).Scan(&rows); err != nil {
+ t.Fatalf("count discarded queued input rows: %v", err)
+ }
+ if rows != 0 {
+ t.Fatalf("queued remove left %d message/attachment rows", rows)
+ }
+}
+
// createStartedEmptyChatTask seeds the exact shape the deferred cancel is about:
// a chat task the daemon has already started (started_at set) whose transcript is
// still empty, plus the user message that triggered it.
@@ -578,6 +775,89 @@ func TestCancelTaskByUser_ChatTaskWithoutTranscript_RestoresUserDraft(t *testing
}
}
+func TestCancelTaskByUser_ChatRetryRestoresRootInput(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "CancelChatRetryAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ var rootTaskID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, status, priority, chat_session_id, completed_at
+ )
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'completed', 0, $2, now())
+ RETURNING id
+ `, agentID, sessionID).Scan(&rootTaskID); err != nil {
+ t.Fatalf("create root chat task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, rootTaskID)
+ })
+ if _, err := testPool.Exec(
+ context.Background(),
+ `UPDATE agent_task_queue SET chat_input_task_id = id WHERE id = $1`,
+ rootTaskID,
+ ); err != nil {
+ t.Fatalf("seal root chat input: %v", err)
+ }
+
+ var messageID string
+ const content = "restore the retry input"
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO chat_message (chat_session_id, role, content, task_id)
+ VALUES ($1, 'user', $2, $3)
+ RETURNING id
+ `, sessionID, content, rootTaskID).Scan(&messageID); err != nil {
+ t.Fatalf("create root chat message: %v", err)
+ }
+
+ var retryTaskID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, status, priority, chat_session_id,
+ parent_task_id, retry_of_task_id, chat_input_task_id, attempt
+ )
+ VALUES (
+ $1, (SELECT runtime_id FROM agent WHERE id = $1), 'queued', 0, $2,
+ $3, $3, $3, 1
+ )
+ RETURNING id
+ `, agentID, sessionID, rootTaskID).Scan(&retryTaskID); err != nil {
+ t.Fatalf("create retry chat task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, retryTaskID)
+ })
+
+ transcript, err := testHandler.Queries.ListChatMessages(
+ context.Background(),
+ util.MustParseUUID(sessionID),
+ )
+ if err != nil {
+ t.Fatalf("list transcript with queued retry: %v", err)
+ }
+ if len(transcript) != 1 || transcript[0].Content != content {
+ t.Fatalf("queued retry hid its historical root input: %+v", transcript)
+ }
+
+ w := httptest.NewRecorder()
+ testHandler.CancelTaskByUser(w, cancelTaskByUserRequest(t, testUserID, retryTaskID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CancelTaskByUserResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode retry cancel response: %v", err)
+ }
+ if resp.CancelledChatMessage == nil ||
+ resp.CancelledChatMessage.MessageID != messageID ||
+ resp.CancelledChatMessage.Content != content {
+ t.Fatalf("retry did not restore its root input: %#v", resp.CancelledChatMessage)
+ }
+}
+
// TestCancelTaskByUser_ChatTaskWithBoundAttachment_SurvivesCancelAndRebinds
// guards the data-loss path on the empty-chat cancel: the user message bound to
// an attachment is deleted, and attachment.chat_message_id is ON DELETE CASCADE
diff --git a/server/internal/handler/channel_new_e2e_test.go b/server/internal/handler/channel_new_e2e_test.go
index 0e6da6eb2c..81694a5703 100644
--- a/server/internal/handler/channel_new_e2e_test.go
+++ b/server/internal/handler/channel_new_e2e_test.go
@@ -217,12 +217,17 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma
t.Fatalf("created issues = %d, want 0; /new must be mutually exclusive with /issue", issueCount)
}
- messages, err := queries.ListChatMessages(ctx, sessionID)
- if err != nil {
- t.Fatalf("list persisted chat messages: %v", err)
+ var storedText string
+ if err := testPool.QueryRow(ctx, `
+ SELECT content FROM chat_message
+ WHERE chat_session_id = $1 AND role = 'user'
+ ORDER BY created_at DESC, id DESC
+ LIMIT 1
+ `, sessionID).Scan(&storedText); err != nil {
+ t.Fatalf("load persisted chat message: %v", err)
}
- if len(messages) != 1 || messages[0].Content != wantStoredText {
- t.Fatalf("persisted messages = %#v, want one user message %q", messages, wantStoredText)
+ if storedText != wantStoredText {
+ t.Fatalf("persisted message = %q, want %q", storedText, wantStoredText)
}
claimed := claimTaskForRuntimeGuard(t, runtimeID, daemonID)
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index 513cf72271..95400e6afd 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -595,6 +595,14 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
return
}
+ // Claim, clear, prioritize, and direct send all lock the agent before task
+ // rows. Keep delete on the same agent -> task suffix after its session lock,
+ // otherwise a builder-agent delete can deadlock with a concurrent claim.
+ if _, err := qtx.GetAgentForClaimUpdate(r.Context(), session.AgentID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to lock chat agent")
+ return
+ }
+
cancelled, err := qtx.CancelAgentTasksByChatSession(r.Context(), session.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to cancel chat session tasks")
@@ -677,8 +685,9 @@ type SendChatMessageRequest struct {
}
type SendChatMessageResponse struct {
- MessageID string `json:"message_id"`
- TaskID string `json:"task_id"`
+ MessageID string `json:"message_id"`
+ TaskID string `json:"task_id"`
+ SupportsQueue bool `json:"supports_queue"`
// 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
@@ -797,7 +806,16 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
// invoke gate.
sent, err := h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID))
if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to send chat message: "+err.Error())
+ switch {
+ case errors.Is(err, service.ErrChatSessionArchived):
+ writeError(w, http.StatusConflict, "chat session is archived")
+ case errors.Is(err, service.ErrChatTaskAgentArchived):
+ writeError(w, http.StatusConflict, "chat agent is archived")
+ case errors.Is(err, service.ErrChatTaskAgentNoRuntime):
+ writeError(w, http.StatusConflict, "chat agent has no runtime")
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to send chat message: "+err.Error())
+ }
return
}
msg := sent.Message
@@ -850,6 +868,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, SendChatMessageResponse{
MessageID: uuidToString(msg.ID),
TaskID: uuidToString(task.ID),
+ SupportsQueue: true,
CreatedAt: timestampToString(task.CreatedAt),
AttachmentIDs: boundAttachmentIDs,
})
@@ -1099,9 +1118,24 @@ func (h *Handler) ListChatMessagesPage(w http.ResponseWriter, r *http.Request) {
// optimistic seeds don't have a real task created_at and the timer needs to
// survive refresh / reopen.
type PendingChatTaskResponse struct {
- TaskID string `json:"task_id,omitempty"`
- Status string `json:"status,omitempty"`
- CreatedAt string `json:"created_at,omitempty"`
+ TaskID string `json:"task_id,omitempty"`
+ Status string `json:"status,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
+ SupportsQueue bool `json:"supports_queue"`
+ QueuedTasks []QueuedChatTaskResponse `json:"queued_tasks,omitempty"`
+}
+
+type QueuedChatTaskResponse struct {
+ TaskID string `json:"task_id"`
+ Status string `json:"status"`
+ CreatedAt string `json:"created_at"`
+ MessageID string `json:"message_id,omitempty"`
+ Content string `json:"content,omitempty"`
+}
+
+type PrioritizeQueuedChatTaskResponse struct {
+ TaskID string `json:"task_id"`
+ ActiveTaskID string `json:"active_task_id,omitempty"`
}
// MarkChatSessionRead clears the session's unread_since (→ has_unread=false)
@@ -1420,9 +1454,9 @@ func (h *Handler) HasPendingChatTasks(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, HasPendingChatTasksResponse{HasPending: hasPending})
}
-// GetPendingChatTask returns the most recent in-flight task (queued / dispatched
-// / running) for a chat session. The frontend polls this on mount / session
-// switch so pending UI state survives refresh and reopen.
+// GetPendingChatTask returns the current task plus its ordered follow-ups. The
+// root fields retain the original response shape so older clients continue to
+// recover a single pending task after refresh / reopen.
func (h *Handler) GetPendingChatTask(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
@@ -1436,20 +1470,123 @@ func (h *Handler) GetPendingChatTask(w http.ResponseWriter, r *http.Request) {
return
}
- task, err := h.Queries.GetPendingChatTask(r.Context(), session.ID)
+ tasks, err := h.Queries.ListPendingChatTasksForSession(r.Context(), session.ID)
if err != nil {
- // No in-flight task — return an empty object, not an error.
- writeJSON(w, http.StatusOK, PendingChatTaskResponse{})
+ writeError(w, http.StatusInternalServerError, "failed to list pending chat tasks")
+ return
+ }
+ if len(tasks) == 0 {
+ writeJSON(w, http.StatusOK, PendingChatTaskResponse{SupportsQueue: true})
return
}
+ head := tasks[0]
+ queued := make([]QueuedChatTaskResponse, 0, len(tasks))
+ for _, task := range tasks {
+ if task.Status != "queued" {
+ continue
+ }
+ queued = append(queued, QueuedChatTaskResponse{
+ TaskID: uuidToString(task.ID),
+ Status: task.Status,
+ CreatedAt: timestampToString(task.CreatedAt),
+ MessageID: uuidToString(task.MessageID),
+ Content: task.Content,
+ })
+ }
+
writeJSON(w, http.StatusOK, PendingChatTaskResponse{
- TaskID: uuidToString(task.ID),
- Status: task.Status,
- CreatedAt: timestampToString(task.CreatedAt),
+ TaskID: uuidToString(head.ID),
+ Status: head.Status,
+ CreatedAt: timestampToString(head.CreatedAt),
+ SupportsQueue: true,
+ QueuedTasks: queued,
+ })
+}
+
+// PrioritizeQueuedChatTask moves one queued follow-up ahead of its FIFO peers.
+// The client then cancels the current task through the existing cancellation
+// endpoint, preserving that path's transcript and draft-restore semantics.
+func (h *Handler) PrioritizeQueuedChatTask(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ sessionID := chi.URLParam(r, "sessionId")
+ taskID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "taskId"), "task id")
+ if !ok {
+ return
+ }
+
+ session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)
+ if !ok {
+ return
+ }
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to start prioritize transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ // ClaimTask takes this same row lock before selecting work. Holding it here
+ // makes "prioritize + report the active task" one server-authoritative
+ // decision instead of two client requests racing the daemon.
+ if _, err := qtx.GetAgentForClaimUpdate(r.Context(), session.AgentID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to lock chat agent")
+ return
+ }
+ prioritized, err := qtx.PrioritizeQueuedChatTask(
+ r.Context(),
+ db.PrioritizeQueuedChatTaskParams{ID: taskID, ChatSessionID: session.ID},
+ )
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusConflict, "task is no longer queued")
+ return
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to prioritize queued task")
+ return
+ }
+ queuedTask, err := qtx.GetAgentTask(r.Context(), taskID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load prioritized task")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to commit queued task priority")
+ return
+ }
+ h.TaskService.BroadcastTaskQueued(r.Context(), queuedTask)
+
+ writeJSON(w, http.StatusOK, PrioritizeQueuedChatTaskResponse{
+ TaskID: uuidToString(prioritized.TaskID),
+ ActiveTaskID: uuidToString(prioritized.ActiveTaskID),
})
}
+// ClearQueuedChatTasks cancels every queued follow-up without touching the
+// task already running for the session.
+func (h *Handler) ClearQueuedChatTasks(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ sessionID := chi.URLParam(r, "sessionId")
+ session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)
+ if !ok {
+ return
+ }
+ if err := h.TaskService.CancelQueuedChatTasks(r.Context(), session.ID, session.AgentID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to clear queued tasks")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
// ---------------------------------------------------------------------------
// Task cancellation (user-facing, with ownership check)
// ---------------------------------------------------------------------------
@@ -1499,6 +1636,34 @@ func (h *Handler) CancelTaskByUser(w http.ResponseWriter, r *http.Request) {
return
}
+ var (
+ queuedOnly bool
+ expectedSession pgtype.UUID
+ queueAction string
+ )
+ if expectedStatus := r.URL.Query().Get("expected_status"); expectedStatus != "" {
+ if expectedStatus != "queued" {
+ writeError(w, http.StatusBadRequest, "expected_status must be queued")
+ return
+ }
+ sessionID := r.URL.Query().Get("chat_session_id")
+ var ok bool
+ expectedSession, ok = parseUUIDOrBadRequest(w, sessionID, "chat_session_id")
+ if !ok {
+ return
+ }
+ if !task.ChatSessionID.Valid || task.ChatSessionID != expectedSession {
+ writeError(w, http.StatusConflict, "task does not belong to the expected chat session")
+ return
+ }
+ queueAction = r.URL.Query().Get("queue_action")
+ if queueAction != "edit" && queueAction != "remove" {
+ writeError(w, http.StatusBadRequest, "queue_action must be edit or remove")
+ return
+ }
+ queuedOnly = true
+ }
+
if task.ChatSessionID.Valid {
// Chat privacy: only the member who opened the conversation may
// cancel its task, even though the workspace is shared.
@@ -1535,7 +1700,14 @@ func (h *Handler) CancelTaskByUser(w http.ResponseWriter, r *http.Request) {
cancelled, err := h.TaskService.CancelTaskWithResult(r.Context(), taskUUID, service.CancelTaskOptions{
ClientSupportsDraftRestore: requestHasClientCapability(r, protocol.AppCapabilityChatDraftRestoreV1),
+ QueuedOnly: queuedOnly,
+ ExpectedChatSession: expectedSession,
+ QueueAction: queueAction,
})
+ if errors.Is(err, service.ErrTaskNoLongerQueued) {
+ writeError(w, http.StatusConflict, err.Error())
+ return
+ }
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
diff --git a/server/internal/handler/chat_pending_tasks_test.go b/server/internal/handler/chat_pending_tasks_test.go
index 1a973576cf..b8dc6708bb 100644
--- a/server/internal/handler/chat_pending_tasks_test.go
+++ b/server/internal/handler/chat_pending_tasks_test.go
@@ -5,11 +5,15 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "net/url"
"testing"
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/middleware"
"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"
)
// chatPendingCtxAs injects the workspace + member context that the chi
@@ -65,6 +69,46 @@ func insertPendingChatTask(t *testing.T, agentID, sessionID, status string) stri
return taskID
}
+func insertQueuedChatInputWithAttachment(
+ t *testing.T,
+ agentID, sessionID, content string,
+) (taskID, messageID, attachmentID string) {
+ t.Helper()
+ taskID = insertPendingChatTask(t, agentID, sessionID, "queued")
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE agent_task_queue SET chat_input_task_id = id WHERE id = $1
+ `, taskID); err != nil {
+ t.Fatalf("stamp queued input owner: %v", err)
+ }
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO chat_message (chat_session_id, role, content, task_id)
+ VALUES ($1, 'user', $2, $3)
+ RETURNING id
+ `, sessionID, content, taskID).Scan(&messageID); err != nil {
+ t.Fatalf("insert queued input: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_draft_restore WHERE id = $1`, messageID)
+ })
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO attachment (
+ workspace_id, uploader_type, uploader_id, filename, url,
+ content_type, size_bytes, chat_session_id, chat_message_id
+ )
+ VALUES (
+ $1, 'member', $2, 'queued.png', 'https://cdn.example.com/queued.png',
+ 'image/png', 9, $3, $4
+ )
+ RETURNING id
+ `, testWorkspaceID, testUserID, sessionID, messageID).Scan(&attachmentID); err != nil {
+ t.Fatalf("insert queued attachment: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, attachmentID)
+ })
+ return taskID, messageID, attachmentID
+}
+
func decodePendingTasks(t *testing.T, w *httptest.ResponseRecorder) PendingChatTasksResponse {
t.Helper()
if w.Code != http.StatusOK {
@@ -98,6 +142,444 @@ func containsPendingTask(tasks []PendingChatTaskItem, taskID string) bool {
return false
}
+func TestGetPendingChatTask_ReturnsActiveHeadAndFIFOQueue(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "PendingSessionQueueAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ activeID := insertPendingChatTask(t, agentID, sessionID, "running")
+ nextID := insertPendingChatTask(t, agentID, sessionID, "queued")
+ laterID := insertPendingChatTask(t, agentID, sessionID, "queued")
+ regenerateID := insertPendingChatTask(t, agentID, sessionID, "queued")
+ if _, err := testPool.Exec(
+ context.Background(),
+ `UPDATE agent_task_queue SET regenerate_quick_actions_for = $2 WHERE id = $1`,
+ regenerateID,
+ uuid.New(),
+ ); err != nil {
+ t.Fatalf("mark quick-actions regeneration task: %v", err)
+ }
+
+ for _, row := range []struct {
+ id string
+ createdAt string
+ content string
+ }{
+ {activeID, "2026-07-29T01:00:00Z", "active prompt"},
+ {nextID, "2026-07-29T01:00:01Z", "next prompt"},
+ {laterID, "2026-07-29T01:00:02Z", "later prompt"},
+ } {
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE agent_task_queue
+ SET created_at = $2, chat_input_task_id = id
+ WHERE id = $1
+ `, row.id, row.createdAt); err != nil {
+ t.Fatalf("stamp pending task %s: %v", row.id, err)
+ }
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO chat_message (chat_session_id, role, content, task_id, created_at)
+ VALUES ($1, 'user', $2, $3, $4)
+ `, sessionID, row.content, row.id, row.createdAt); err != nil {
+ t.Fatalf("insert pending message %s: %v", row.id, err)
+ }
+ }
+ transcript, err := testHandler.Queries.ListChatMessages(
+ context.Background(),
+ util.MustParseUUID(sessionID),
+ )
+ if err != nil {
+ t.Fatalf("list compatibility transcript: %v", err)
+ }
+ if len(transcript) != 1 || util.UUIDToString(transcript[0].TaskID) != activeID {
+ t.Fatalf("legacy full-list transcript exposed queued prompts: %+v", transcript)
+ }
+ page, err := testHandler.Queries.ListChatMessagesPage(
+ context.Background(),
+ db.ListChatMessagesPageParams{
+ ChatSessionID: util.MustParseUUID(sessionID),
+ Limit: 50,
+ },
+ )
+ if err != nil {
+ t.Fatalf("list paged compatibility transcript: %v", err)
+ }
+ if len(page) != 1 || util.UUIDToString(page[0].TaskID) != activeID {
+ t.Fatalf("paged transcript exposed queued prompts: %+v", page)
+ }
+
+ legacy, err := testHandler.Queries.ListChatMessagesForLegacyTask(
+ context.Background(),
+ util.MustParseUUID(sessionID),
+ )
+ if err != nil {
+ t.Fatalf("list legacy task input: %v", err)
+ }
+ if len(legacy) != 1 || util.UUIDToString(legacy[0].TaskID) != activeID {
+ t.Fatalf("legacy task input leaked queued successor: %+v", legacy)
+ }
+
+ req := withURLParam(
+ newRequestAs(
+ testUserID,
+ http.MethodGet,
+ "/api/chat/sessions/"+sessionID+"/pending-task",
+ nil,
+ ),
+ "sessionId",
+ sessionID,
+ )
+ w := httptest.NewRecorder()
+ testHandler.GetPendingChatTask(w, chatPendingCtxAs(t, req, testUserID))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp PendingChatTaskResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode pending task queue: %v", err)
+ }
+ if resp.TaskID != activeID || resp.Status != "running" {
+ t.Fatalf("unexpected active head: %+v", resp)
+ }
+ if !resp.SupportsQueue {
+ t.Fatal("pending response must advertise queue support")
+ }
+ if len(resp.QueuedTasks) != 2 {
+ t.Fatalf("expected two queued tasks, got %+v", resp.QueuedTasks)
+ }
+ if resp.QueuedTasks[0].TaskID != nextID ||
+ resp.QueuedTasks[0].Content != "next prompt" ||
+ resp.QueuedTasks[1].TaskID != laterID ||
+ resp.QueuedTasks[1].Content != "later prompt" {
+ t.Fatalf("queue is not FIFO with message summaries: %+v", resp.QueuedTasks)
+ }
+ if _, err := testPool.Exec(
+ context.Background(),
+ `UPDATE agent_task_queue SET priority = 4 WHERE id = $1`,
+ nextID,
+ ); err != nil {
+ t.Fatalf("seed prior send-now selection: %v", err)
+ }
+
+ prioritizeReq := newRequestAs(
+ testUserID,
+ http.MethodPost,
+ "/api/chat/sessions/"+sessionID+"/queued-tasks/"+laterID+"/prioritize",
+ nil,
+ )
+ prioritizeReq = withURLParams(
+ prioritizeReq,
+ "sessionId", sessionID,
+ "taskId", laterID,
+ )
+ prioritizeW := httptest.NewRecorder()
+ testHandler.PrioritizeQueuedChatTask(
+ prioritizeW,
+ chatPendingCtxAs(t, prioritizeReq, testUserID),
+ )
+ if prioritizeW.Code != http.StatusOK {
+ t.Fatalf("expected prioritize 200, got %d: %s", prioritizeW.Code, prioritizeW.Body.String())
+ }
+ var prioritized PrioritizeQueuedChatTaskResponse
+ if err := json.Unmarshal(prioritizeW.Body.Bytes(), &prioritized); err != nil {
+ t.Fatalf("decode prioritize response: %v", err)
+ }
+ if prioritized.TaskID != laterID || prioritized.ActiveTaskID != activeID {
+ t.Fatalf("prioritize response is not server-authoritative: %+v", prioritized)
+ }
+
+ w = httptest.NewRecorder()
+ testHandler.GetPendingChatTask(w, chatPendingCtxAs(t, req, testUserID))
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode prioritized queue: %v", err)
+ }
+ if resp.TaskID != activeID ||
+ len(resp.QueuedTasks) != 2 ||
+ resp.QueuedTasks[0].TaskID != laterID ||
+ resp.QueuedTasks[1].TaskID != nextID {
+ t.Fatalf("send-now priority did not move only the selected follow-up: %+v", resp)
+ }
+
+ if _, err := testPool.Exec(
+ context.Background(),
+ `UPDATE agent_task_queue SET status = 'completed' WHERE id = $1`,
+ activeID,
+ ); err != nil {
+ t.Fatalf("complete active task: %v", err)
+ }
+ w = httptest.NewRecorder()
+ testHandler.GetPendingChatTask(w, chatPendingCtxAs(t, req, testUserID))
+ resp = PendingChatTaskResponse{}
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode all-queued state: %v", err)
+ }
+ 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)
+ }
+}
+
+func TestListChatMessagesPage_QueuedRowsDoNotConsumeLimit(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ agentID := createHandlerTestAgent(t, "QueuedPageBudgetAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ settledID := insertPendingChatTask(t, agentID, sessionID, "completed")
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, task_id, created_at)
+ VALUES
+ ($1, 'user', 'settled 1', $2, '2026-07-29T01:00:00Z'),
+ ($1, 'assistant', 'settled 2', $2, '2026-07-29T01:00:01Z'),
+ ($1, 'user', 'settled 3', $2, '2026-07-29T01:00:02Z'),
+ ($1, 'assistant', 'settled 4', $2, '2026-07-29T01:00:03Z')
+ `, sessionID, settledID); err != nil {
+ t.Fatalf("insert settled history: %v", err)
+ }
+
+ for _, row := range []struct {
+ content string
+ createdAt string
+ }{
+ {"queued prompt A", "2026-07-29T01:00:04Z"},
+ {"queued prompt B", "2026-07-29T01:00:05Z"},
+ {"queued prompt C", "2026-07-29T01:00:06Z"},
+ } {
+ taskID := insertPendingChatTask(t, agentID, sessionID, "queued")
+ if _, err := testPool.Exec(ctx, `
+ WITH owned AS (
+ UPDATE agent_task_queue SET chat_input_task_id = id WHERE id = $1
+ RETURNING id
+ )
+ INSERT INTO chat_message (chat_session_id, role, content, task_id, created_at)
+ SELECT $2, 'user', $3, id, $4 FROM owned
+ `, taskID, sessionID, row.content, row.createdAt); err != nil {
+ t.Fatalf("insert queued history: %v", err)
+ }
+ }
+
+ 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.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("CURSOR page=1: created_at=%s id=%s", page1.NextCursor.CreatedAt, page1.NextCursor.ID)
+
+ page2Params := url.Values{
+ "limit": {"2"},
+ "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)
+ 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")
+}
+
+func TestPendingQueueHeadMatchesClaimForEqualCreatedAt(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID := createHandlerTestAgent(t, "Pending Equal Timestamp Agent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+
+ lowID := uuid.New()
+ highID := lowID
+ lowID[15] = 0
+ highID[15] = 255
+ for _, taskID := range []uuid.UUID{highID, lowID} {
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO agent_task_queue (
+ id, agent_id, runtime_id, status, priority, chat_session_id, created_at
+ )
+ VALUES ($1, $2, $3, 'queued', 2, $4, '2026-07-29T01:00:00Z')
+ `, taskID, agentID, handlerTestRuntimeID(t), sessionID); err != nil {
+ t.Fatalf("insert equal-timestamp task %s: %v", taskID, err)
+ }
+ }
+
+ pending, err := testHandler.Queries.ListPendingChatTasksForSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list pending tasks: %v", err)
+ }
+ if len(pending) != 2 || uuidToString(pending[0].ID) != lowID.String() {
+ t.Fatalf("pending head = %+v, want lower id %s", pending, lowID)
+ }
+
+ claimed, err := testHandler.TaskService.ClaimTask(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatalf("claim task: %v", err)
+ }
+ if claimed == nil {
+ t.Fatal("claim returned no task")
+ }
+ if got := uuidToString(claimed.ID); got != lowID.String() {
+ t.Fatalf("claimed task = %s, pending head = %s", got, lowID)
+ }
+}
+
+func TestPrioritizeQueuedChatTask_StaleTargetPreservesExistingPriority(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "StalePrioritizeQueueAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ existingID := insertPendingChatTask(t, agentID, sessionID, "queued")
+ staleID := insertPendingChatTask(t, agentID, sessionID, "completed")
+ if _, err := testPool.Exec(
+ context.Background(),
+ `UPDATE agent_task_queue SET priority = 4 WHERE id = $1`,
+ existingID,
+ ); err != nil {
+ t.Fatalf("seed existing priority: %v", err)
+ }
+
+ req := withURLParams(
+ newRequestAs(
+ testUserID,
+ http.MethodPost,
+ "/api/chat/sessions/"+sessionID+"/queued-tasks/"+staleID+"/prioritize",
+ nil,
+ ),
+ "sessionId", sessionID,
+ "taskId", staleID,
+ )
+ 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 priority int
+ if err := testPool.QueryRow(
+ context.Background(),
+ `SELECT priority FROM agent_task_queue WHERE id = $1`,
+ existingID,
+ ).Scan(&priority); err != nil {
+ t.Fatalf("read preserved priority: %v", err)
+ }
+ if priority != 4 {
+ t.Fatalf("stale prioritize demoted existing queue head to %d", priority)
+ }
+}
+
+func TestPrioritizeQueuedChatTask_BroadcastsQueueInvalidation(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "PrioritizeQueueBroadcastAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ taskID := insertPendingChatTask(t, agentID, sessionID, "queued")
+ got := make(chan events.Event, 1)
+ testHandler.Bus.Subscribe(protocol.EventTaskQueued, func(event events.Event) {
+ payload, ok := event.Payload.(map[string]any)
+ if !ok || payload["task_id"] != taskID {
+ return
+ }
+ got <- event
+ })
+
+ req := withURLParams(
+ newRequestAs(
+ testUserID,
+ http.MethodPost,
+ "/api/chat/sessions/"+sessionID+"/queued-tasks/"+taskID+"/prioritize",
+ nil,
+ ),
+ "sessionId", sessionID,
+ "taskId", taskID,
+ )
+ w := httptest.NewRecorder()
+ testHandler.PrioritizeQueuedChatTask(w, chatPendingCtxAs(t, req, testUserID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ select {
+ case event := <-got:
+ if event.WorkspaceID != testWorkspaceID {
+ t.Fatalf("event workspace = %s, want %s", event.WorkspaceID, testWorkspaceID)
+ }
+ default:
+ t.Fatal("prioritize did not broadcast task:queued invalidation")
+ }
+}
+
+func TestClearQueuedChatTasks_CancelsWholeQueueAndDeletesInputs(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "ClearPendingQueueAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ var taskIDs, attachmentIDs []string
+ for _, content := range []string{"queued prompt A", "queued prompt B"} {
+ taskID, _, attachmentID := insertQueuedChatInputWithAttachment(
+ t,
+ agentID,
+ sessionID,
+ content,
+ )
+ taskIDs = append(taskIDs, taskID)
+ attachmentIDs = append(attachmentIDs, attachmentID)
+ }
+
+ req := withURLParam(
+ newRequestAs(
+ testUserID,
+ http.MethodDelete,
+ "/api/chat/sessions/"+sessionID+"/queued-tasks",
+ nil,
+ ),
+ "sessionId",
+ sessionID,
+ )
+ w := httptest.NewRecorder()
+ testHandler.ClearQueuedChatTasks(w, chatPendingCtxAs(t, req, testUserID))
+ if w.Code != http.StatusNoContent {
+ 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)
+ }
+ }
+ var inputCount int
+ if 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)
+ }
+ if inputCount != 0 {
+ t.Fatalf("clear left %d queued input messages", inputCount)
+ }
+ var attachmentCount int
+ if 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)
+ }
+ if attachmentCount != 0 {
+ t.Fatalf("clear left %d discarded attachment rows", attachmentCount)
+ }
+}
+
// TestListPendingChatTasks_HidesPrivateAgentFromLostAccessCreator verifies the
// P1 rewrite still enforces the private-agent gate now that filtering keys off
// the agent_id returned by the query (instead of a second session-list scan).
@@ -236,7 +718,6 @@ func TestHasPendingChatTasks_IgnoresTerminalTasks(t *testing.T) {
}
}
-
// TestHasPendingChatTasks_HidesOtherCreatorsTask locks the cs.creator_id gate:
// user A's in-flight task on a workspace-visible agent — one B can freely
// access — must still return has_pending=false for B, because B is not the
@@ -274,4 +755,4 @@ func TestHasPendingChatTasks_HidesOtherCreatorsTask(t *testing.T) {
if resp := decodePendingTasks(t, w); len(resp.Tasks) != 0 {
t.Fatalf("list leaked user A's task to user B: %+v", resp.Tasks)
}
-}
\ No newline at end of file
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 8f81751f9c..f202bfa46e 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2248,7 +2248,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
var inputLoadErr error
if task.ChatInputTaskID.Valid {
unanswered, inputLoadErr = h.Queries.ListChatInputMessages(r.Context(), task.ChatInputTaskID)
- } else if msgs, err := h.Queries.ListChatMessages(r.Context(), cs.ID); err == nil {
+ } else if msgs, err := h.Queries.ListChatMessagesForLegacyTask(r.Context(), cs.ID); err == nil {
unanswered = trailingUserMessages(msgs)
} else {
inputLoadErr = err
diff --git a/server/internal/service/chat_quick_actions_generate.go b/server/internal/service/chat_quick_actions_generate.go
index 86881da2b5..ed69f227f8 100644
--- a/server/internal/service/chat_quick_actions_generate.go
+++ b/server/internal/service/chat_quick_actions_generate.go
@@ -208,7 +208,7 @@ func (s *TaskService) GenerateChatQuickActionsForTask(ctx context.Context, task
return s.SupplementChatQuickActions(ctx, task, "", false)
}
- prompt, err := s.buildChatQuickActionsPrompt(ctx, target)
+ prompt, err := s.buildChatQuickActionsPrompt(ctx, target, chatInputOwnerID(task))
if err != nil {
return err
}
@@ -336,7 +336,7 @@ func (s *TaskService) resolveChatQuickActionsPlaceholder(task db.AgentTaskQueue)
// completion callback and this read would otherwise supply the context while
// the result is still written to the older turn, and a newly-sent user message
// would leave the window ending on a user row with no reply to build on.
-func (s *TaskService) buildChatQuickActionsPrompt(ctx context.Context, target db.ChatMessage) (string, error) {
+func (s *TaskService) buildChatQuickActionsPrompt(ctx context.Context, target db.ChatMessage, inputOwnerID pgtype.UUID) (string, error) {
// Strictly older than target, newest-first; reversed below. Over-fetch so
// dropped rows (no_response, failures) don't shrink the window below the
// intended turn count.
@@ -349,10 +349,30 @@ func (s *TaskService) buildChatQuickActionsPrompt(ctx context.Context, target db
if err != nil {
return "", fmt.Errorf("load chat messages for quick actions: %w", err)
}
+ msgs := selectChatQuickActionsContext(rows, target, inputOwnerID)
+ return renderChatQuickActionsContext(msgs, collectPreviousChatQuickActions(msgs)), nil
+}
+func selectChatQuickActionsContext(rows []db.ChatMessage, target db.ChatMessage, inputOwnerID pgtype.UUID) []db.ChatMessage {
+ // A queued successor's input can be stored before target even though it is
+ // logically the next turn. Keep user rows only when their task has already
+ // answered inside this anchored window (or owns the target task's input;
+ // auto-retry replies use the child task ID while their input keeps the root).
+ answeredTaskIDs := map[pgtype.UUID]struct{}{target.TaskID: {}}
+ answeredTaskIDs[inputOwnerID] = struct{}{}
+ for _, msg := range rows {
+ if msg.Role == "assistant" && msg.TaskID.Valid {
+ answeredTaskIDs[msg.TaskID] = struct{}{}
+ }
+ }
msgs := make([]db.ChatMessage, 0, len(rows)+1)
for i := len(rows) - 1; i >= 0; i-- {
msg := rows[i]
+ if msg.Role == "user" && msg.TaskID.Valid {
+ if _, answered := answeredTaskIDs[msg.TaskID]; !answered {
+ continue
+ }
+ }
// Only ordinary turns carry usable text. A no_response row holds an
// English placeholder body and a failure row holds an error, neither of
// which describes what the conversation is about.
@@ -368,7 +388,7 @@ func (s *TaskService) buildChatQuickActionsPrompt(ctx context.Context, target db
msgs = msgs[len(msgs)-(chatQuickActionsContextMessages-1):]
}
msgs = append(msgs, target)
- return renderChatQuickActionsContext(msgs, collectPreviousChatQuickActions(msgs)), nil
+ return msgs
}
// collectPreviousChatQuickActions gathers the labels already offered in this
diff --git a/server/internal/service/chat_quick_actions_generate_test.go b/server/internal/service/chat_quick_actions_generate_test.go
index ad1ae1a3f8..5a1496ddad 100644
--- a/server/internal/service/chat_quick_actions_generate_test.go
+++ b/server/internal/service/chat_quick_actions_generate_test.go
@@ -6,10 +6,59 @@ import (
"testing"
"unicode"
+ "github.com/jackc/pgx/v5/pgtype"
+
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
+func TestSelectChatQuickActionsContextExcludesFutureTurnAfterItCompletes(t *testing.T) {
+ previousID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
+ targetID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}
+ futureID := pgtype.UUID{Bytes: [16]byte{3}, Valid: true}
+ rows := []db.ChatMessage{
+ {Role: "user", Content: "future queued prompt", TaskID: futureID, MessageKind: protocol.ChatMessageKindMessage},
+ {Role: "user", Content: "target prompt", TaskID: targetID, MessageKind: protocol.ChatMessageKindMessage},
+ {Role: "assistant", Content: "previous reply", TaskID: previousID, MessageKind: protocol.ChatMessageKindMessage},
+ {Role: "user", Content: "previous prompt", TaskID: previousID, MessageKind: protocol.ChatMessageKindMessage},
+ }
+ target := db.ChatMessage{
+ Role: "assistant",
+ Content: "target reply",
+ TaskID: targetID,
+ MessageKind: protocol.ChatMessageKindMessage,
+ }
+
+ selected := selectChatQuickActionsContext(rows, target, targetID)
+ if len(selected) != 4 {
+ t.Fatalf("selected %d messages, want previous turn + target turn", len(selected))
+ }
+ for _, msg := range selected {
+ if msg.Content == "future queued prompt" {
+ t.Fatal("a later turn must stay out even if its task completed before generation")
+ }
+ }
+}
+
+func TestSelectChatQuickActionsContextIncludesAutoRetryInputOwner(t *testing.T) {
+ rootID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
+ retryID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}
+ rows := []db.ChatMessage{
+ {Role: "user", Content: "root prompt", TaskID: rootID, MessageKind: protocol.ChatMessageKindMessage},
+ }
+ target := db.ChatMessage{
+ Role: "assistant",
+ Content: "retry reply",
+ TaskID: retryID,
+ MessageKind: protocol.ChatMessageKindMessage,
+ }
+
+ selected := selectChatQuickActionsContext(rows, target, rootID)
+ if len(selected) != 2 || selected[0].Content != "root prompt" {
+ t.Fatalf("selected messages = %+v, want retry input followed by its reply", selected)
+ }
+}
+
func chatMsg(role, content string, actions ...protocol.ChatQuickAction) db.ChatMessage {
msg := db.ChatMessage{
Role: role,
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 89637c17de..87ac8bdbc3 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1466,6 +1466,10 @@ var ErrChatQuickActionsStale = errors.New("chat quick actions: refresh target is
// quota-spending pass (MUL-5149).
var ErrChatQuickActionsBusy = errors.New("chat quick actions: session busy")
+// ErrChatSessionArchived signals that a direct-chat send lost a race with
+// archiving the session and therefore must not persist a new turn.
+var ErrChatSessionArchived = errors.New("chat task: session archived")
+
// EnqueueChatTask creates a task-owned input batch for a chat session. Channel
// media makes the task deferred until binding completes or its durable fallback
// deadline expires; other chat tasks are queued immediately. Unlike issue
@@ -1725,9 +1729,8 @@ type DirectChatSendResult struct {
// instead of scanning trailing history.
//
// The caller must have already gated the session and preflighted the agent
-// (archived / no-runtime), passing the loaded agent in; this method trusts those
-// permission checks. It does NOT trust the agent's runtime_id: that field is
-// re-read inside the transaction (see below).
+// (archived / no-runtime), passing the loaded agent in. Those checks are repeated
+// under the transaction locks below because either row may change before enqueue.
func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.ChatSession, agent db.Agent, initiatorUserID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, uploaderType string, uploaderID pgtype.UUID) (*DirectChatSendResult, error) {
// Build the per-task Composio overlay before the transaction — it can do
// network I/O and must not run with a DB transaction open.
@@ -1758,10 +1761,20 @@ func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.Chat
if _, err := qtx.LockChatSessionForRuntimeBind(ctx, session.ID); err != nil {
return fmt.Errorf("lock chat session: %w", err)
}
- carrier, err := qtx.GetAgent(ctx, session.AgentID)
+ currentSession, err := qtx.GetChatSession(ctx, session.ID)
+ if err != nil {
+ return fmt.Errorf("reload chat session: %w", err)
+ }
+ if currentSession.Status != "active" {
+ return ErrChatSessionArchived
+ }
+ carrier, err := qtx.GetAgentForClaimUpdate(ctx, session.AgentID)
if err != nil {
return fmt.Errorf("reload chat agent: %w", err)
}
+ if carrier.ArchivedAt.Valid {
+ return ErrChatTaskAgentArchived
+ }
if !carrier.RuntimeID.Valid {
return ErrChatTaskAgentNoRuntime
}
@@ -1924,6 +1937,11 @@ func (s *TaskService) BroadcastCancelledTasks(ctx context.Context, cancelled []d
s.notifyTasksFinished(cancelled)
}
+// BroadcastTaskQueued emits a post-commit queue invalidation for clients.
+func (s *TaskService) BroadcastTaskQueued(ctx context.Context, task db.AgentTaskQueue) {
+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
+}
+
func (s *TaskService) CaptureCancelledTasks(ctx context.Context, cancelled []db.AgentTaskQueue) {
for _, t := range cancelled {
s.captureTaskCancelled(ctx, t)
@@ -1946,6 +1964,8 @@ type CancelTaskResult struct {
CancelledChatMessage *CancelledChatMessageResult
}
+var ErrTaskNoLongerQueued = errors.New("task is no longer queued")
+
// CancelTaskOptions carries what the caller knows about the client that asked
// for the cancellation.
type CancelTaskOptions struct {
@@ -1955,6 +1975,10 @@ type CancelTaskOptions struct {
// stays synchronous, because the cancel response is their only chance to get
// the prompt back. See protocol.AppCapabilityChatDraftRestoreV1.
ClientSupportsDraftRestore bool
+ // QueuedOnly turns queue edit/remove into a session-scoped compare-and-set.
+ QueuedOnly bool
+ ExpectedChatSession pgtype.UUID
+ QueueAction string
}
// CancelTask cancels a single task by ID. It broadcasts a task:cancelled event
@@ -1976,29 +2000,55 @@ func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.A
// CancelTaskWithResult cancels a single task and returns any chat-specific
// cleanup result needed by user-facing callers.
func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUID, opts CancelTaskOptions) (*CancelTaskResult, error) {
- // The status flip and the chat resume-pointer advance commit together. Split
- // across two statements, the `cancelled` status becomes visible to every
- // other connection while the pointer still names the PREVIOUS turn's
- // session — and a follow-up the user had already queued can be claimed in
- // that gap and resume the older session, which is the bug this change is
- // supposed to remove (GH #6340). AdvanceCancelledChatSessionPointer reads
- // the row this transaction just wrote, so it also sees a session pinned
- // concurrently rather than a stale in-memory copy.
- var task db.AgentTaskQueue
- err := s.runInTx(ctx, func(qtx *db.Queries) error {
- if err := lockChatSessionForTaskWrite(ctx, qtx, taskID); err != nil {
- return err
+ var (
+ task db.AgentTaskQueue
+ cancelledChatMessage *CancelledChatMessageResult
+ err error
+ )
+ if opts.QueuedOnly {
+ if opts.QueueAction != "edit" && opts.QueueAction != "remove" {
+ return nil, errors.New("queue action must be edit or remove")
}
- cancelled, err := qtx.CancelAgentTask(ctx, taskID)
- if err != nil {
+ err = s.runInTx(ctx, func(qtx *db.Queries) error {
+ if _, err := qtx.LockChatSessionForTask(ctx, taskID); err != nil {
+ return fmt.Errorf("lock queued chat session: %w", err)
+ }
+ task, err = qtx.CancelQueuedAgentTask(ctx, db.CancelQueuedAgentTaskParams{
+ ID: taskID,
+ ChatSessionID: opts.ExpectedChatSession,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ return ErrTaskNoLongerQueued
+ }
+ if err != nil {
+ return fmt.Errorf("cancel queued task: %w", err)
+ }
+ cancelledChatMessage, err = s.settleQueuedChatInput(ctx, qtx, task, opts.QueueAction)
return err
- }
- task = cancelled
- if !cancelled.ChatSessionID.Valid {
- return nil
- }
- return qtx.AdvanceCancelledChatSessionPointer(ctx, cancelled.ID)
- })
+ })
+ } else {
+ // The status flip and the chat resume-pointer advance commit together. Split
+ // across two statements, the `cancelled` status becomes visible to every
+ // other connection while the pointer still names the previous turn's
+ // session, and a queued follow-up can resume that older session.
+ err = s.runInTx(ctx, func(qtx *db.Queries) error {
+ if err := lockChatSessionForTaskWrite(ctx, qtx, taskID); err != nil {
+ return err
+ }
+ cancelled, err := qtx.CancelAgentTask(ctx, taskID)
+ if err != nil {
+ return err
+ }
+ task = cancelled
+ if !cancelled.ChatSessionID.Valid {
+ return nil
+ }
+ return qtx.AdvanceCancelledChatSessionPointer(ctx, cancelled.ID)
+ })
+ }
+ if errors.Is(err, ErrTaskNoLongerQueued) {
+ return nil, err
+ }
if errors.Is(err, pgx.ErrNoRows) {
existing, err := s.Queries.GetAgentTask(ctx, taskID)
if err != nil {
@@ -2012,7 +2062,9 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU
slog.Info("task cancelled", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
s.captureTaskCancelled(ctx, task)
- cancelledChatMessage := s.finalizeCancelledChatMessage(ctx, task, opts)
+ if !opts.QueuedOnly {
+ cancelledChatMessage = s.finalizeCancelledChatMessage(ctx, task, opts)
+ }
// Reconcile agent status
s.ReconcileAgentStatus(ctx, task.AgentID)
@@ -2027,6 +2079,50 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU
}, nil
}
+// CancelQueuedChatTasks atomically cancels every queued follow-up in a chat
+// session. The session lock preserves the delete path's session -> agent -> task
+// order; the agent lock then prevents ClaimTask from promoting a row mid-update.
+func (s *TaskService) CancelQueuedChatTasks(ctx context.Context, sessionID, agentID pgtype.UUID) error {
+ var tasks []db.AgentTaskQueue
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ if _, err := qtx.LockChatSessionForDelete(ctx, sessionID); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ return fmt.Errorf("lock chat session: %w", err)
+ }
+ if _, err := qtx.GetAgentForClaimUpdate(ctx, agentID); err != nil {
+ return fmt.Errorf("lock chat agent: %w", err)
+ }
+ var err error
+ tasks, err = qtx.CancelQueuedAgentTasksForSession(ctx, sessionID)
+ if err != nil {
+ return fmt.Errorf("cancel queued chat tasks: %w", err)
+ }
+ for _, task := range tasks {
+ if _, err := s.settleQueuedChatInput(ctx, qtx, task, "remove"); err != nil {
+ return err
+ }
+ }
+ return nil
+ }); err != nil {
+ return err
+ }
+
+ for _, task := range tasks {
+ slog.Info("task cancelled", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
+ s.captureTaskCancelled(ctx, task)
+ }
+ if len(tasks) > 0 {
+ s.ReconcileAgentStatus(ctx, agentID)
+ }
+ for _, task := range tasks {
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)
+ }
+ s.notifyTasksFinished(tasks)
+ return nil
+}
+
// lockChatSessionForTaskWrite takes the chat_session row a task belongs to. It
// must be the FIRST statement of any transaction that ends up holding both that
// session row and the task's own row, which is every terminal-state path a chat
@@ -2064,6 +2160,74 @@ func chatInputOwnerID(task db.AgentTaskQueue) pgtype.UUID {
return task.ID
}
+func (s *TaskService) settleQueuedChatInput(
+ ctx context.Context,
+ qtx *db.Queries,
+ task db.AgentTaskQueue,
+ action string,
+) (*CancelledChatMessageResult, error) {
+ if !task.ChatSessionID.Valid {
+ return nil, nil
+ }
+ inputOwnerID := chatInputOwnerID(task)
+ channelIngested, err := qtx.TaskHasChannelIngestedMessages(ctx, inputOwnerID)
+ if err != nil {
+ return nil, fmt.Errorf("check queued chat channel provenance: %w", err)
+ }
+ if channelIngested {
+ if _, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ChatSessionID: task.ChatSessionID,
+ Role: "assistant",
+ Content: "Stopped.",
+ TaskID: task.ID,
+ ElapsedMs: computeChatElapsedMs(task),
+ }); err != nil {
+ return nil, fmt.Errorf("create cancelled queued chat message: %w", err)
+ }
+ return nil, nil
+ }
+
+ var detached []db.Attachment
+ if action == "edit" {
+ detached, err = qtx.DetachAttachmentsFromUserChatMessageByTask(ctx, inputOwnerID)
+ if err != nil {
+ return nil, fmt.Errorf("detach edited queued chat attachments: %w", err)
+ }
+ }
+ deleted, err := qtx.DeleteUserChatMessageByTask(ctx, inputOwnerID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("delete queued chat input: %w", err)
+ }
+ cancelled := &CancelledChatMessageResult{
+ ChatSessionID: util.UUIDToString(deleted.ChatSessionID),
+ MessageID: util.UUIDToString(deleted.ID),
+ Content: deleted.Content,
+ }
+ if action == "remove" {
+ return cancelled, nil
+ }
+
+ attachmentIDs := make([]pgtype.UUID, 0, len(detached))
+ for _, attachment := range detached {
+ attachmentIDs = append(attachmentIDs, attachment.ID)
+ }
+ if _, err := qtx.CreateChatDraftRestore(ctx, db.CreateChatDraftRestoreParams{
+ ID: deleted.ID,
+ ChatSessionID: task.ChatSessionID,
+ TaskID: task.ID,
+ Content: deleted.Content,
+ AttachmentIds: attachmentIDs,
+ }); err != nil {
+ return nil, fmt.Errorf("create queued chat draft restore: %w", err)
+ }
+ cancelled.RestoreToInput = true
+ cancelled.Attachments = detached
+ return cancelled, nil
+}
+
func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.AgentTaskQueue, opts CancelTaskOptions) *CancelledChatMessageResult {
if !task.ChatSessionID.Valid {
return nil
@@ -2119,14 +2283,15 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.
return nil
}
if restorable {
+ inputOwnerID := chatInputOwnerID(task)
// Detach attachments BEFORE deleting the user message — the
// attachment FK is ON DELETE CASCADE, so deleting first would
// destroy rows the restored draft needs to re-bind.
- detached, err := qtx.DetachAttachmentsFromUserChatMessageByTask(ctx, task.ID)
+ detached, err := qtx.DetachAttachmentsFromUserChatMessageByTask(ctx, inputOwnerID)
if err != nil {
return fmt.Errorf("detach cancelled chat message attachments: %w", err)
}
- deleted, err := qtx.DeleteUserChatMessageByTask(ctx, task.ID)
+ deleted, err := qtx.DeleteUserChatMessageByTask(ctx, inputOwnerID)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
@@ -2238,6 +2403,7 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID
restorable = !channelIngested
}
if restorable {
+ inputOwnerID := chatInputOwnerID(claimed)
// The transcript stayed empty through the daemon flush: same
// outcome as the synchronous empty branch, but the cancel HTTP
// response is long gone and the broadcast is best-effort. The
@@ -2246,11 +2412,11 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID
// misses the event recovers it on the next session open; the
// event itself carries no content and is only an invalidation
// hint.
- detached, err := qtx.DetachAttachmentsFromUserChatMessageByTask(ctx, claimed.ID)
+ detached, err := qtx.DetachAttachmentsFromUserChatMessageByTask(ctx, inputOwnerID)
if err != nil {
return fmt.Errorf("detach cancelled chat message attachments: %w", err)
}
- deleted, err := qtx.DeleteUserChatMessageByTask(ctx, claimed.ID)
+ deleted, err := qtx.DeleteUserChatMessageByTask(ctx, inputOwnerID)
if errors.Is(err, pgx.ErrNoRows) {
payload.Outcome = ""
return nil
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 1f420738c8..ed70da7f89 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -907,6 +907,161 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
return items, nil
}
+const cancelQueuedAgentTask = `-- name: CancelQueuedAgentTask :one
+UPDATE agent_task_queue
+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
+`
+
+type CancelQueuedAgentTaskParams struct {
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+}
+
+// Queue editing is a compare-and-set: never cancel a task that the daemon
+// promoted between the user's click and this statement.
+func (q *Queries) CancelQueuedAgentTask(ctx context.Context, arg CancelQueuedAgentTaskParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, cancelQueuedAgentTask, arg.ID, arg.ChatSessionID)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ )
+ return i, err
+}
+
+const cancelQueuedAgentTasksForSession = `-- name: CancelQueuedAgentTasksForSession :many
+UPDATE agent_task_queue
+SET 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
+`
+
+func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSessionID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelQueuedAgentTasksForSession, chatSessionID)
+ 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,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const claimAgentTask = `-- name: ClaimAgentTask :one
UPDATE agent_task_queue
SET status = 'dispatched',
@@ -932,7 +1087,7 @@ WHERE id = (
)
)
)
- ORDER BY atq.priority DESC, atq.created_at ASC
+ ORDER BY atq.priority DESC, atq.created_at ASC, atq.id ASC
LIMIT 1
FOR UPDATE SKIP LOCKED
)
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index a77a0932c4..c0997ca819 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -1279,7 +1279,7 @@ ORDER BY created_at ASC, id ASC
// the user sent for this turn — and never absorbs a message that arrived after
// the batch was sealed, no matter what the assistant wrote or when. Only used
// for new task-owned direct-chat tasks; legacy/channel (chat_input_task_id
-// NULL) tasks keep using ListChatMessages + trailingUserMessages.
+// NULL) tasks keep using ListChatMessagesForLegacyTask + trailingUserMessages.
func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID) ([]ChatMessage, error) {
rows, err := q.db.Query(ctx, listChatInputMessages, taskID)
if err != nil {
@@ -1314,9 +1314,19 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)
}
const listChatMessages = `-- name: ListChatMessages :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
-WHERE chat_session_id = $1
-ORDER BY created_at ASC, id ASC
+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions FROM chat_message AS message
+WHERE message.chat_session_id = $1
+ AND NOT (
+ message.role = 'user'
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue AS task
+ WHERE task.chat_session_id = message.chat_session_id
+ AND task.status = 'queued'
+ AND task.id = message.task_id
+ )
+ )
+ORDER BY message.created_at ASC, message.id ASC
`
func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUID) ([]ChatMessage, error) {
@@ -1352,14 +1362,75 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI
return items, nil
}
+const listChatMessagesForLegacyTask = `-- name: ListChatMessagesForLegacyTask :many
+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions FROM chat_message AS message
+WHERE message.chat_session_id = $1
+ AND NOT (
+ message.role = 'user'
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue AS task
+ WHERE task.chat_session_id = message.chat_session_id
+ AND task.status = 'queued'
+ AND task.id = message.task_id
+ )
+ )
+ORDER BY message.created_at ASC, message.id ASC
+`
+
+// Legacy/reclaimed daemon tasks use trailing history, but must not absorb a
+// newer queued successor that is already bound to its own user message.
+func (q *Queries) ListChatMessagesForLegacyTask(ctx context.Context, chatSessionID pgtype.UUID) ([]ChatMessage, error) {
+ rows, err := q.db.Query(ctx, listChatMessagesForLegacyTask, chatSessionID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ChatMessage{}
+ for rows.Next() {
+ var i ChatMessage
+ if err := rows.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.Role,
+ &i.Content,
+ &i.TaskID,
+ &i.CreatedAt,
+ &i.FailureReason,
+ &i.ElapsedMs,
+ &i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
+ &i.QuickActions,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listChatMessagesPage = `-- name: ListChatMessagesPage :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
-WHERE chat_session_id = $1
+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions FROM chat_message AS message
+WHERE message.chat_session_id = $1
+ AND NOT (
+ message.role = 'user'
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue AS task
+ WHERE task.chat_session_id = message.chat_session_id
+ AND task.status = 'queued'
+ AND task.id = message.task_id
+ )
+ )
AND (
$3::timestamptz IS NULL
- OR (created_at, id) < ($3::timestamptz, $4::uuid)
+ OR (message.created_at, message.id) < ($3::timestamptz, $4::uuid)
)
-ORDER BY created_at DESC, id DESC
+ORDER BY message.created_at DESC, message.id DESC
LIMIT $2
`
@@ -1569,6 +1640,71 @@ func (q *Queries) ListPendingChatTasksByCreator(ctx context.Context, arg ListPen
return items, nil
}
+const listPendingChatTasksForSession = `-- name: ListPendingChatTasksForSession :many
+SELECT
+ task.id,
+ task.status,
+ task.created_at,
+ message.id AS message_id,
+ COALESCE(message.content, '')::text AS content
+FROM agent_task_queue AS task
+LEFT JOIN LATERAL (
+ SELECT input.id, input.content
+ FROM chat_message AS input
+ WHERE input.task_id = COALESCE(task.chat_input_task_id, task.id)
+ AND input.role = 'user'
+ ORDER BY input.created_at ASC, input.id ASC
+ LIMIT 1
+) AS message ON TRUE
+WHERE task.chat_session_id = $1
+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ AND task.regenerate_quick_actions_for IS NULL
+ORDER BY
+ CASE WHEN task.status = 'queued' THEN 1 ELSE 0 END,
+ task.priority DESC,
+ task.created_at ASC,
+ task.id ASC
+`
+
+type ListPendingChatTasksForSessionRow struct {
+ ID pgtype.UUID `json:"id"`
+ Status string `json:"status"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ MessageID pgtype.UUID `json:"message_id"`
+ Content string `json:"content"`
+}
+
+// Returns the active task first, followed by prioritized then FIFO follow-ups.
+// 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
+// only need an existence check.
+func (q *Queries) ListPendingChatTasksForSession(ctx context.Context, chatSessionID pgtype.UUID) ([]ListPendingChatTasksForSessionRow, error) {
+ rows, err := q.db.Query(ctx, listPendingChatTasksForSession, chatSessionID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListPendingChatTasksForSessionRow{}
+ for rows.Next() {
+ var i ListPendingChatTasksForSessionRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.Status,
+ &i.CreatedAt,
+ &i.MessageID,
+ &i.Content,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const lockChatSessionForDelete = `-- name: LockChatSessionForDelete :one
SELECT id FROM chat_session
WHERE id = $1
@@ -1778,6 +1914,59 @@ func (q *Queries) MarkChatSessionRead(ctx context.Context, id pgtype.UUID) error
return err
}
+const prioritizeQueuedChatTask = `-- name: PrioritizeQueuedChatTask :one
+WITH target AS MATERIALIZED (
+ SELECT candidate.id
+ FROM agent_task_queue AS candidate
+ WHERE candidate.id = $2
+ AND candidate.chat_session_id = $1
+ AND candidate.status = 'queued'
+ FOR UPDATE
+), demoted AS (
+ UPDATE agent_task_queue AS queued
+ SET priority = 3
+ WHERE queued.chat_session_id = $1
+ AND queued.id <> $2
+ AND queued.status = 'queued'
+ AND queued.priority >= 4
+ AND EXISTS (SELECT 1 FROM target)
+), prioritized AS (
+ UPDATE agent_task_queue AS selected
+ SET priority = 4
+ FROM target
+ WHERE selected.id = target.id
+ RETURNING selected.id
+)
+SELECT
+ prioritized.id AS task_id,
+ (
+ SELECT active.id
+ FROM agent_task_queue AS active
+ WHERE active.chat_session_id = $1
+ AND active.status IN ('dispatched', 'running', 'waiting_local_directory')
+ ORDER BY active.created_at ASC, active.id ASC
+ LIMIT 1
+ )::uuid AS active_task_id
+FROM prioritized
+`
+
+type PrioritizeQueuedChatTaskParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ID pgtype.UUID `json:"id"`
+}
+
+type PrioritizeQueuedChatTaskRow struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ ActiveTaskID pgtype.UUID `json:"active_task_id"`
+}
+
+func (q *Queries) PrioritizeQueuedChatTask(ctx context.Context, arg PrioritizeQueuedChatTaskParams) (PrioritizeQueuedChatTaskRow, error) {
+ row := q.db.QueryRow(ctx, prioritizeQueuedChatTask, arg.ChatSessionID, arg.ID)
+ var i PrioritizeQueuedChatTaskRow
+ err := row.Scan(&i.TaskID, &i.ActiveTaskID)
+ return i, err
+}
+
const promoteChannelChatTasksIfMediaReady = `-- name: PromoteChannelChatTasksIfMediaReady :many
UPDATE agent_task_queue AS task
SET status = 'queued', fire_at = NULL
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 6e99159445..f4e452d943 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -563,7 +563,7 @@ WHERE id = (
)
)
)
- ORDER BY atq.priority DESC, atq.created_at ASC
+ ORDER BY atq.priority DESC, atq.created_at ASC, atq.id ASC
LIMIT 1
FOR UPDATE SKIP LOCKED
)
@@ -1062,6 +1062,23 @@ 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 *;
+-- name: CancelQueuedAgentTask :one
+-- Queue editing is a compare-and-set: never cancel a task that the daemon
+-- promoted between the user's click and this statement.
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+WHERE id = sqlc.arg('id')
+ AND chat_session_id = sqlc.arg('chat_session_id')
+ AND status = 'queued'
+RETURNING *;
+
+-- name: CancelQueuedAgentTasksForSession :many
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+WHERE chat_session_id = $1
+ AND status = 'queued'
+RETURNING *;
+
-- name: MarkChatFinalizeDeferred :one
-- Arms the deferred chat-finalize marker for a cancelled chat task whose
-- empty-transcript judgment must wait for the daemon's flush ack (#5219).
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 84c1aa5b95..adb59a17e2 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -441,9 +441,36 @@ WHERE task_id = $1 AND role = 'user'
RETURNING *;
-- name: ListChatMessages :many
-SELECT * FROM chat_message
-WHERE chat_session_id = $1
-ORDER BY created_at ASC, id ASC;
+SELECT message.* FROM chat_message AS message
+WHERE message.chat_session_id = $1
+ AND NOT (
+ message.role = 'user'
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue AS task
+ WHERE task.chat_session_id = message.chat_session_id
+ AND task.status = 'queued'
+ AND task.id = message.task_id
+ )
+ )
+ORDER BY message.created_at ASC, message.id ASC;
+
+-- name: ListChatMessagesForLegacyTask :many
+-- Legacy/reclaimed daemon tasks use trailing history, but must not absorb a
+-- newer queued successor that is already bound to its own user message.
+SELECT message.* FROM chat_message AS message
+WHERE message.chat_session_id = $1
+ AND NOT (
+ message.role = 'user'
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue AS task
+ WHERE task.chat_session_id = message.chat_session_id
+ AND task.status = 'queued'
+ AND task.id = message.task_id
+ )
+ )
+ORDER BY message.created_at ASC, message.id ASC;
-- name: ListChatInputMessages :many
-- Loads the immutable user-message input batch owned by a direct-chat task.
@@ -452,19 +479,29 @@ ORDER BY created_at ASC, id ASC;
-- the user sent for this turn — and never absorbs a message that arrived after
-- the batch was sealed, no matter what the assistant wrote or when. Only used
-- for new task-owned direct-chat tasks; legacy/channel (chat_input_task_id
--- NULL) tasks keep using ListChatMessages + trailingUserMessages.
+-- NULL) tasks keep using ListChatMessagesForLegacyTask + trailingUserMessages.
SELECT * FROM chat_message
WHERE task_id = $1 AND role = 'user'
ORDER BY created_at ASC, id ASC;
-- name: ListChatMessagesPage :many
-SELECT * FROM chat_message
-WHERE chat_session_id = $1
+SELECT message.* FROM chat_message AS message
+WHERE message.chat_session_id = $1
+ AND NOT (
+ message.role = 'user'
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue AS task
+ WHERE task.chat_session_id = message.chat_session_id
+ AND task.status = 'queued'
+ AND task.id = message.task_id
+ )
+ )
AND (
sqlc.narg('before_created_at')::timestamptz IS NULL
- OR (created_at, id) < (sqlc.narg('before_created_at')::timestamptz, sqlc.narg('before_id')::uuid)
+ OR (message.created_at, message.id) < (sqlc.narg('before_created_at')::timestamptz, sqlc.narg('before_id')::uuid)
)
-ORDER BY created_at DESC, id DESC
+ORDER BY message.created_at DESC, message.id DESC
LIMIT $2;
-- name: GetChatMessage :one
@@ -631,6 +668,71 @@ WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'wa
ORDER BY created_at DESC
LIMIT 1;
+-- name: ListPendingChatTasksForSession :many
+-- Returns the active task first, followed by prioritized then FIFO follow-ups.
+-- 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
+-- only need an existence check.
+SELECT
+ task.id,
+ task.status,
+ task.created_at,
+ message.id AS message_id,
+ COALESCE(message.content, '')::text AS content
+FROM agent_task_queue AS task
+LEFT JOIN LATERAL (
+ SELECT input.id, input.content
+ FROM chat_message AS input
+ WHERE input.task_id = COALESCE(task.chat_input_task_id, task.id)
+ AND input.role = 'user'
+ ORDER BY input.created_at ASC, input.id ASC
+ LIMIT 1
+) AS message ON TRUE
+WHERE task.chat_session_id = $1
+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ AND task.regenerate_quick_actions_for IS NULL
+ORDER BY
+ CASE WHEN task.status = 'queued' THEN 1 ELSE 0 END,
+ task.priority DESC,
+ task.created_at ASC,
+ task.id ASC;
+
+-- name: PrioritizeQueuedChatTask :one
+WITH target AS MATERIALIZED (
+ SELECT candidate.id
+ FROM agent_task_queue AS candidate
+ WHERE candidate.id = sqlc.arg('id')
+ AND candidate.chat_session_id = sqlc.arg('chat_session_id')
+ AND candidate.status = 'queued'
+ FOR UPDATE
+), demoted AS (
+ UPDATE agent_task_queue AS queued
+ SET priority = 3
+ WHERE queued.chat_session_id = sqlc.arg('chat_session_id')
+ AND queued.id <> sqlc.arg('id')
+ AND queued.status = 'queued'
+ AND queued.priority >= 4
+ AND EXISTS (SELECT 1 FROM target)
+), prioritized AS (
+ UPDATE agent_task_queue AS selected
+ SET priority = 4
+ FROM target
+ WHERE selected.id = target.id
+ RETURNING selected.id
+)
+SELECT
+ prioritized.id AS task_id,
+ (
+ SELECT active.id
+ 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')
+ ORDER BY active.created_at ASC, active.id ASC
+ LIMIT 1
+ )::uuid AS active_task_id
+FROM prioritized;
+
-- name: ListPendingChatTasksByCreator :many
-- Aggregate view of all in-flight chat tasks owned by a given creator in a
-- workspace. Drives the FAB's "running" indicator when the chat window is