Skip to content

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

Go

MUL-5493: feat(chat): add a visible follow-up queue (#6133)

TeAmob13657be7108
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index c71ba77023..b830bf9afb 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -183,6 +183,7 @@ import {
AttachmentResponseSchema,
CancelTaskResponseSchema,
ChatDraftRestoresResponseSchema,
+ ChatPendingTaskSchema,
ChildIssuesResponseSchema,
CommentsListSchema,
CommentTriggerPreviewSchema,
@@ -203,6 +204,7 @@ import {
EMPTY_AGENT_TEMPLATE_SUMMARY_LIST,
EMPTY_APP_CONFIG,
EMPTY_ATTACHMENT,
+ EMPTY_CHAT_PENDING_TASK,
EMPTY_CLOUD_RUNTIME_NODE,
EMPTY_CLOUD_RUNTIME_NODE_LIST,
EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE,
@@ -2280,7 +2282,10 @@ export class ApiClient {
}
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",
+ });
}
/**
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 7225e1d16c..66cc8e1684 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -11,9 +11,11 @@ import {
DashboardUsageByAgentListSchema,
DashboardUsageDailyListSchema,
ChatDraftRestoresResponseSchema,
+ ChatPendingTaskSchema,
CreateFeedbackResponseSchema,
DuplicateIssueErrorBodySchema,
EMPTY_CHAT_DRAFT_RESTORES,
+ EMPTY_CHAT_PENDING_TASK,
EMPTY_CREATE_FEEDBACK_RESPONSE,
EMPTY_INBOX_ITEMS,
EMPTY_INBOX_UNREAD_SUMMARY,
@@ -410,6 +412,65 @@ 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",
+ queued_tasks: [],
+ });
+ });
+
+ 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("falls back safely when a queued row is malformed", () => {
+ const parsed = parseWithFallback(
+ {
+ task_id: "task-active",
+ queued_tasks: [{ task_id: 42, status: "queued" }],
+ },
+ ChatPendingTaskSchema,
+ EMPTY_CHAT_PENDING_TASK,
+ ENDPOINT,
+ );
+
+ expect(parsed).toBe(EMPTY_CHAT_PENDING_TASK);
+ });
+});
+
describe("CreateFeedbackResponseSchema", () => {
const ENDPOINT = { endpoint: "POST /api/feedback" };
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index f7b617e63d..1b0d629fa3 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -15,6 +15,7 @@ import type {
BillingTransactionsPage,
CancelTaskResponse,
ChatDraftRestoresResponse,
+ ChatPendingTask,
CreateAgentFromTemplateResponse,
CreateBillingCheckoutSessionResponse,
CreateBillingPortalSessionResponse,
@@ -1113,6 +1114,25 @@ 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();
+
+// Root fields retain the legacy single-task response shape. queued_tasks is
+// additive and defaults to an empty list for older servers.
+export const ChatPendingTaskSchema: z.ZodType<ChatPendingTask> = z.object({
+ task_id: z.string().optional(),
+ status: z.string().optional(),
+ created_at: z.string().optional(),
+ queued_tasks: z.array(ChatQueuedTaskSchema).default([]),
+}).loose();
+
+export const EMPTY_CHAT_PENDING_TASK: ChatPendingTask = { queued_tasks: [] };
+
export const EMPTY_CHAT_DRAFT_RESTORES: ChatDraftRestoresResponse = {
restores: [],
};
diff --git a/packages/core/chat/pending.test.ts b/packages/core/chat/pending.test.ts
new file mode 100644
index 0000000000..d4dc01cb1c
--- /dev/null
+++ b/packages/core/chat/pending.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from "vitest";
+import {
+ enqueuePendingChatTask,
+ 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 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("promotes a queued task without losing later work", () => {
+ const current = {
+ ...task("active", "2026-01-01T00:00:00Z"),
+ status: "running",
+ 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.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("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",
+ 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.queued_tasks?.map((item) => item.task_id)).toEqual(["later"]);
+ });
+});
diff --git a/packages/core/chat/pending.ts b/packages/core/chat/pending.ts
new file mode 100644
index 0000000000..4181e2d74c
--- /dev/null
+++ b/packages/core/chat/pending.ts
@@ -0,0 +1,100 @@
+import type { 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 normalizeQueue(tasks: ChatQueuedTask[]): ChatQueuedTask[] {
+ const byID = new Map<string, ChatQueuedTask>();
+ // Keep the first observation of a task. The send response carries the
+ // authoritative created_at plus the message preview, while the later
+ // task:queued event only carries an id/status. Letting that sparse event win
+ // would replace visible text with the fallback label.
+ for (const task of tasks) {
+ if (!byID.has(task.task_id)) byID.set(task.task_id, task);
+ }
+ return [...byID.values()].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: [] };
+ }
+ if (current.task_id === task.task_id) {
+ return {
+ ...current,
+ status: task.status,
+ created_at: current.created_at || task.created_at,
+ queued_tasks: current.queued_tasks ?? [],
+ };
+ }
+ return {
+ ...current,
+ queued_tasks: normalizeQueue([...(current.queued_tasks ?? []), task]),
+ };
+}
+
+export function promotePendingChatTask(
+ current: ChatPendingTask | undefined,
+ taskID: string,
+ status: string,
+ createdAt?: string,
+): ChatPendingTask {
+ if (current?.task_id === taskID) return { ...current, status };
+
+ const queue = current?.queued_tasks ?? [];
+ const promoted = queue.find((task) => task.task_id === taskID);
+ if (current?.task_id && current.status !== "queued" && !promoted) {
+ return current;
+ }
+ const previousHead = asSummary(current ?? {});
+ return {
+ ...(promoted ?? {
+ task_id: taskID,
+ status,
+ created_at: createdAt ?? "",
+ }),
+ status,
+ created_at: promoted?.created_at ?? createdAt ?? "",
+ queued_tasks: normalizeQueue([
+ ...(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] = normalizeQueue(current.queued_tasks ?? []);
+ if (!next) return EMPTY_PENDING_TASK;
+ return { ...next, queued_tasks: rest };
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index 5aa6fe111e..ea82b9a70a 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/unread": "./chat/unread.ts",
"./runtimes": "./runtimes/index.ts",
"./runtimes/queries": "./runtimes/queries.ts",
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.ts
index 63cf3b11ae..e83be651bc 100644
--- a/packages/core/realtime/use-realtime-sync.test.ts
+++ b/packages/core/realtime/use-realtime-sync.test.ts
@@ -326,6 +326,79 @@ 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-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 788d4e3903..dd1c7b684b 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -50,6 +50,11 @@ import {
import type { Workspace } from "../types/workspace";
import { chatKeys, mergeTaskMessagesBySeq, sortChatSessions } from "../chat/queries";
import { useChatStore } from "../chat";
+import {
+ enqueuePendingChatTask,
+ promotePendingChatTask,
+ removePendingChatTask,
+} from "../chat/pending";
import { resolvePostAuthDestination, useHasOnboarded } from "../paths";
import type {
MemberAddedPayload,
@@ -163,8 +168,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),
+ );
// Authoritative refetch reconciles redaction / migrations / clients
// that took the fallback branch above.
invalidateChatMessageQueries(qc, sessionId);
@@ -317,8 +326,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 &&
@@ -1212,12 +1227,13 @@ export function useRealtimeSync(
if (!payload.chat_session_id) return;
qc.setQueryData<ChatPendingTask>(
chatKeys.pendingTask(payload.chat_session_id),
- (old) => ({
- ...(old ?? {}),
+ (old) => enqueuePendingChatTask(old, {
task_id: payload.task_id,
status: "queued",
+ created_at: new Date().toISOString(),
}),
);
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
invalidatePendingAggregate();
});
@@ -1232,10 +1248,7 @@ 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"),
);
invalidatePendingAggregate();
});
@@ -1250,10 +1263,7 @@ 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"),
);
invalidatePendingAggregate();
});
@@ -1270,10 +1280,12 @@ 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",
+ ),
);
invalidatePendingAggregate();
},
@@ -1294,7 +1306,11 @@ 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();
});
@@ -1306,12 +1322,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();
});
@@ -1328,7 +1343,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 c0a069ac63..4ce8d05bea 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -192,8 +192,21 @@ 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 ChatPendingTask {
task_id?: string;
status?: string;
created_at?: string;
+ /**
+ * FIFO follow-ups waiting behind the current task. The current task itself
+ * remains in the root fields for backward compatibility.
+ */
+ queued_tasks?: ChatQueuedTask[];
}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index c31ec48662..932491e849 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -100,6 +100,7 @@ export type {
ChatMessage,
ChatMessagesPage,
ChatPendingTask,
+ ChatQueuedTask,
PendingChatTaskItem,
PendingChatTasksResponse,
HasPendingChatTasksResponse,
diff --git a/packages/ui/components/common/submit-button.tsx b/packages/ui/components/common/submit-button.tsx
index 08fde2faba..75b9a1a4e2 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 = (
@@ -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 839bc81a1d..4c4743e163 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -19,6 +19,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";
@@ -259,6 +260,11 @@ export function ChatPage() {
<OfflineBanner agentName={c.activeAgent?.name} availability={c.availability} />
)}
+ <ChatQueue
+ tasks={c.pendingTask?.queued_tasks ?? []}
+ onRemove={c.handleRemoveQueuedTask}
+ />
+
<ChatInput
onSend={c.handleSend}
restoreDraftRequest={c.restoreDraftRequest}
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index 788de9d838..0102d2ba1e 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -593,6 +593,23 @@ 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, 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("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 f83f4ce317..e5b42fe2f0 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -429,8 +429,8 @@ 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) {
+ logger.debug("input.send skipped", { disabled, noAgent });
return false;
}
// The editor is still holding a DIFFERENT draft's document than the one
@@ -673,13 +673,18 @@ export function ChatInput({
busy={gate.uploading}
running={isRunning}
onStop={onStop}
+ 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..b0d208f563
--- /dev/null
+++ b/packages/views/chat/components/chat-queue.test.tsx
@@ -0,0 +1,53 @@
+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(onRemove = vi.fn()) {
+ 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",
+ },
+ ]}
+ onRemove={onRemove}
+ />
+ </I18nProvider>,
+ );
+ return onRemove;
+}
+
+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("Remove queued message")).toHaveLength(2);
+ });
+
+ it("removes the selected queued task", async () => {
+ const onRemove = renderQueue(vi.fn().mockResolvedValue(undefined));
+
+ fireEvent.click(screen.getAllByLabelText("Remove queued message")[1]!);
+
+ await waitFor(() => {
+ expect(onRemove).toHaveBeenCalledWith("task-3");
+ });
+ });
+});
diff --git a/packages/views/chat/components/chat-queue.tsx b/packages/views/chat/components/chat-queue.tsx
new file mode 100644
index 0000000000..6b5aa9402b
--- /dev/null
+++ b/packages/views/chat/components/chat-queue.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import { useState } from "react";
+import { Loader2, X } from "lucide-react";
+import type { ChatQueuedTask } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import { useT } from "../../i18n";
+
+interface ChatQueueProps {
+ tasks: ChatQueuedTask[];
+ onRemove: (taskId: string) => Promise<void> | void;
+}
+
+export function ChatQueue({ tasks, onRemove }: ChatQueueProps) {
+ const { t } = useT("chat");
+ const [removingTaskId, setRemovingTaskId] = useState<string | null>(null);
+
+ if (tasks.length === 0) return null;
+
+ const remove = async (taskId: string) => {
+ setRemovingTaskId(taskId);
+ try {
+ await onRemove(taskId);
+ } finally {
+ setRemovingTaskId((current) => current === taskId ? null : current);
+ }
+ };
+
+ return (
+ <div className="mx-3 mb-2 rounded-lg border bg-muted/30 p-2" aria-live="polite">
+ <div className="mb-1 px-1 text-xs font-medium text-muted-foreground">
+ {t(($) => $.queue.title, { count: tasks.length })}
+ </div>
+ <div className="space-y-0.5">
+ {tasks.map((task, index) => {
+ const removing = removingTaskId === 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-sm"
+ >
+ <span className="w-4 shrink-0 text-center text-xs 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={removing}
+ aria-label={t(($) => $.queue.remove)}
+ onClick={() => void remove(task.task_id)}
+ >
+ {removing ? (
+ <Loader2 className="animate-spin" aria-hidden="true" />
+ ) : (
+ <X aria-hidden="true" />
+ )}
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 413661b2d5..d674249a88 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -48,11 +48,16 @@ import {
useUpdateChatSession,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
+import {
+ enqueuePendingChatTask,
+ removePendingChatTask,
+} from "@multica/core/chat/pending";
import { removeChatMessageFromCaches } from "@multica/core/realtime";
import { useChatDraftRestore } from "./use-chat-draft-restore";
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";
@@ -389,7 +394,10 @@ export function ChatWindow() {
sessionId,
source: options.source,
});
- qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(sessionId),
+ (old) => removePendingChatTask(old, taskId),
+ );
try {
const result = await api.cancelTaskById(taskId);
@@ -422,9 +430,12 @@ export function ChatWindow() {
qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
return null;
+ } finally {
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
+ if (wsId) qc.invalidateQueries({ queryKey: chatKeys.pendingTasks(wsId) });
}
},
- [qc, enqueueLocalRestore],
+ [qc, enqueueLocalRestore, wsId],
);
const handleSend = useCallback(
@@ -518,11 +529,16 @@ export function ChatWindow() {
chatKeys.messages(sessionId),
(old) => (old ? [...old, sent] : [sent]),
);
- qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {
- task_id: result.task_id,
- status: "queued",
- created_at: result.created_at,
- });
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(sessionId),
+ (old) => enqueuePendingChatTask(old, {
+ task_id: result.task_id,
+ status: "queued",
+ created_at: result.created_at,
+ message_id: result.message_id,
+ content: finalContent,
+ }),
+ );
// Cache primed → publish the new active session, but only if the user
// hasn't navigated away mid-send. Compare the live store against the
// closure-captured target; see isStillOnComposeTarget for the rule, which
@@ -595,6 +611,17 @@ export function ChatWindow() {
});
}, [pendingTaskId, activeSessionId, cancelChatTask]);
+ const handleRemoveQueuedTask = useCallback(
+ async (taskId: string) => {
+ if (!activeSessionId) return;
+ await cancelChatTask(taskId, activeSessionId, {
+ restoreDraftToInput: true,
+ source: "queued-message",
+ });
+ },
+ [activeSessionId, cancelChatTask],
+ );
+
const handleSelectAgent = useCallback(
(agent: Agent) => {
// No-op when clicking the already-active agent — don't clobber the
@@ -855,6 +882,11 @@ export function ChatWindow() {
<OfflineBanner agentName={activeAgent?.name} availability={availability} />
)}
+ <ChatQueue
+ tasks={pendingTask?.queued_tasks ?? []}
+ onRemove={handleRemoveQueuedTask}
+ />
+
{/* 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). */}
diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsx
index 64a5f83d51..09f93cb14c 100644
--- a/packages/views/chat/components/use-chat-controller.test.tsx
+++ b/packages/views/chat/components/use-chat-controller.test.tsx
@@ -481,6 +481,47 @@ describe("useChatController.archiveSession", () => {
});
});
+describe("useChatController queued task removal", () => {
+ beforeEach(() => {
+ vi.mocked(api.cancelTaskById).mockReset();
+ h.removeFromCaches.mockClear();
+ h.store.enqueuePendingSendRestore.mockClear();
+ h.store.pendingSendRestores = {};
+ });
+
+ it("returns a cancelled queued prompt to the current composer", 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.handleRemoveQueuedTask("task-queued");
+ });
+
+ expect(api.cancelTaskById).toHaveBeenCalledWith("task-queued");
+ expect(h.removeFromCaches).toHaveBeenCalledWith(
+ expect.anything(),
+ "sA",
+ "message-queued",
+ );
+ expect(h.store.enqueuePendingSendRestore).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "message-queued",
+ content: "Revise this follow-up",
+ sessionId: "sA",
+ }),
+ );
+ });
+});
+
// 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 87530ad580..14f70ef0cd 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -30,6 +30,10 @@ import {
useSetChatSessionArchived,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
+import {
+ enqueuePendingChatTask,
+ removePendingChatTask,
+} from "@multica/core/chat/pending";
import { removeChatMessageFromCaches } from "@multica/core/realtime";
import { useChatDraftRestore } from "./use-chat-draft-restore";
import { useChatProjectContextSupport } from "./use-chat-project-context-support";
@@ -441,7 +445,10 @@ export function useChatController(opts?: { isActive?: boolean }) {
sessionId,
source: options.source,
});
- qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(sessionId),
+ (old) => removePendingChatTask(old, taskId),
+ );
try {
const result = await api.cancelTaskById(taskId);
@@ -474,9 +481,12 @@ export function useChatController(opts?: { isActive?: boolean }) {
qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
return null;
+ } finally {
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
+ if (wsId) qc.invalidateQueries({ queryKey: chatKeys.pendingTasks(wsId) });
}
},
- [qc, enqueueLocalRestore],
+ [qc, enqueueLocalRestore, wsId],
);
const handleSend = useCallback(
@@ -580,11 +590,16 @@ export function useChatController(opts?: { isActive?: boolean }) {
chatKeys.messages(sessionId),
(old) => (old ? [...old, sent] : [sent]),
);
- qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {
- task_id: result.task_id,
- status: "queued",
- created_at: result.created_at,
- });
+ qc.setQueryData<ChatPendingTask>(
+ chatKeys.pendingTask(sessionId),
+ (old) => enqueuePendingChatTask(old, {
+ task_id: result.task_id,
+ status: "queued",
+ created_at: result.created_at,
+ message_id: result.message_id,
+ content: finalContent,
+ }),
+ );
// Cache primed → publish the new active session, but only if the user
// hasn't navigated away mid-send. See isStillOnComposeTarget. commitInput
// clears the sent draft, and scrubs the shared editor only when the user
@@ -651,6 +666,17 @@ export function useChatController(opts?: { isActive?: boolean }) {
});
}, [pendingTaskId, activeSessionId, cancelChatTask]);
+ const handleRemoveQueuedTask = useCallback(
+ async (taskId: string) => {
+ if (!activeSessionId) return;
+ await cancelChatTask(taskId, activeSessionId, {
+ restoreDraftToInput: true,
+ source: "queued-message",
+ });
+ },
+ [activeSessionId, cancelChatTask],
+ );
+
const handleNewChat = useCallback(() => {
uiLogger.info("newChat", {
previousSessionId: activeSessionId,
@@ -820,6 +846,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
// actions
handleSend,
handleStop,
+ handleRemoveQueuedTask,
uploadEnabled,
handleNewChat,
handleStartNewChat,
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 2b2ef55d59..2650f4ce33 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -17,6 +17,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",
@@ -29,6 +30,12 @@
"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",
+ "remove": "Remove queued message",
+ "fallback": "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 76ff5c6946..1d13a7b0c2 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -16,6 +16,7 @@
"placeholder_named": "{{name}} にメッセージ…",
"placeholder_default": "メッセージを入力…",
"send_tooltip": "送信",
+ "queue_send_tooltip": "キューに追加",
"stop_tooltip": "停止",
"send_failed_toast": "メッセージを送信できませんでした",
"send_blocked_toast": "メッセージは送信されませんでした — このエージェントを使用する権限がありません",
@@ -28,6 +29,11 @@
"no_projects": "プロジェクトがまだありません",
"project_context_unsupported": "プロジェクトの説明は適用されません——このエージェントのデーモンのアップグレードが必要です"
},
+ "queue": {
+ "title_other": "キュー内のメッセージ {{count}} 件",
+ "remove": "キューから削除",
+ "fallback": "キュー内のメッセージ"
+ },
"message_list": {
"show_details": "詳細を表示",
"replied_in": "{{elapsed}}で返信",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index 288d8f85d5..967cfabb1f 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -16,6 +16,7 @@
"placeholder_named": "{{name}}에게 메시지 보내기…",
"placeholder_default": "메시지 입력…",
"send_tooltip": "보내기",
+ "queue_send_tooltip": "대기열에 추가",
"stop_tooltip": "중지",
"send_failed_toast": "메시지를 보내지 못했습니다",
"send_blocked_toast": "메시지가 전송되지 않았습니다 — 이 에이전트를 사용할 권한이 없습니다",
@@ -28,6 +29,11 @@
"no_projects": "아직 프로젝트가 없습니다",
"project_context_unsupported": "프로젝트 설명이 적용되지 않습니다 — 이 에이전트의 데몬 업그레이드가 필요합니다"
},
+ "queue": {
+ "title_other": "대기 중인 메시지 {{count}}개",
+ "remove": "대기열에서 삭제",
+ "fallback": "대기 중인 메시지"
+ },
"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 9c1c352a13..ab87ba6266 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -16,6 +16,7 @@
"placeholder_named": "给 {{name}} 发消息…",
"placeholder_default": "输入消息…",
"send_tooltip": "发送",
+ "queue_send_tooltip": "排队发送",
"stop_tooltip": "停止",
"send_failed_toast": "发送消息失败",
"send_blocked_toast": "消息未发送——你已没有该智能体的使用权限",
@@ -28,6 +29,11 @@
"no_projects": "还没有项目",
"project_context_unsupported": "项目描述不会生效——该智能体的守护进程版本过旧,需要升级"
},
+ "queue": {
+ "title_other": "{{count}} 条排队消息",
+ "remove": "移除排队消息",
+ "fallback": "排队消息"
+ },
"message_list": {
"show_details": "查看详情",
"replied_in": "{{elapsed}} 内回复",
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index a1e98e3fd1..c9c28fcd3a 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -994,9 +994,18 @@ 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"`
+ 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"`
}
// MarkChatSessionRead clears the session's unread_since (→ has_unread=false)
@@ -1320,9 +1329,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 queued FIFO follow-ups for a
+// chat session. 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 {
@@ -1336,17 +1345,36 @@ 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.
+ writeError(w, http.StatusInternalServerError, "failed to list pending chat tasks")
+ return
+ }
+ if len(tasks) == 0 {
writeJSON(w, http.StatusOK, PendingChatTaskResponse{})
return
}
+ head := tasks[0]
+ queued := make([]QueuedChatTaskResponse, 0, len(tasks)-1)
+ for _, task := range tasks[1:] {
+ 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),
+ QueuedTasks: queued,
})
}
diff --git a/server/internal/handler/chat_pending_tasks_test.go b/server/internal/handler/chat_pending_tasks_test.go
index 1a973576cf..fd4e772363 100644
--- a/server/internal/handler/chat_pending_tasks_test.go
+++ b/server/internal/handler/chat_pending_tasks_test.go
@@ -98,6 +98,75 @@ 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")
+
+ 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)
+ }
+ }
+
+ 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 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)
+ }
+}
+
// 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 +305,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 +342,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/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index db12a6d767..d57e29c1fa 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -1301,6 +1301,69 @@ 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')
+ORDER BY
+ CASE WHEN task.status = 'queued' THEN 1 ELSE 0 END,
+ 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 queued follow-ups in FIFO order.
+// 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
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 92064e500f..78ec0ec59f 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -464,6 +464,34 @@ 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 queued follow-ups in FIFO order.
+-- 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')
+ORDER BY
+ CASE WHEN task.status = 'queued' THEN 1 ELSE 0 END,
+ task.created_at ASC,
+ task.id ASC;
+
-- 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