Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Revert "MUL-5493: feat(chat): add a visible follow-up queue (#6133)" (#6171)
Multica Eve9072cef12cfb
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex b830bf9afb..c71ba77023 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -183,7 +183,6 @@ import {AttachmentResponseSchema,CancelTaskResponseSchema,ChatDraftRestoresResponseSchema,- ChatPendingTaskSchema,ChildIssuesResponseSchema,CommentsListSchema,CommentTriggerPreviewSchema,@@ -204,7 +203,6 @@ 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,@@ -2282,10 +2280,7 @@ export class ApiClient {}async getPendingChatTask(sessionId: string): Promise<ChatPendingTask> {- 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",- });+ return this.fetch(`/api/chat/sessions/${sessionId}/pending-task`);}/**diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 66cc8e1684..7225e1d16c 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -11,11 +11,9 @@ 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,@@ -412,65 +410,6 @@ 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.tsindex 1b0d629fa3..f7b617e63d 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -15,7 +15,6 @@ import type {BillingTransactionsPage,CancelTaskResponse,ChatDraftRestoresResponse,- ChatPendingTask,CreateAgentFromTemplateResponse,CreateBillingCheckoutSessionResponse,CreateBillingPortalSessionResponse,@@ -1114,25 +1113,6 @@ 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.tsdeleted file mode 100644index d4dc01cb1c..0000000000--- a/packages/core/chat/pending.test.ts+++ /dev/null@@ -1,107 +0,0 @@-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.tsdeleted file mode 100644index 4181e2d74c..0000000000--- a/packages/core/chat/pending.ts+++ /dev/null@@ -1,100 +0,0 @@-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.jsonindex ea82b9a70a..5aa6fe111e 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -53,7 +53,6 @@"./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.tsindex e83be651bc..63cf3b11ae 100644--- a/packages/core/realtime/use-realtime-sync.test.ts+++ b/packages/core/realtime/use-realtime-sync.test.ts@@ -326,79 +326,6 @@ 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.tsindex dd1c7b684b..788d4e3903 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -50,11 +50,6 @@ 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,@@ -168,12 +163,8 @@ export function applyChatDoneToCache((old) => patchLatestChatMessagePage(old, assistant),);}- // 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),- );+ // Replacement is in the messages list now; safe to drop pending.+ qc.setQueryData(chatKeys.pendingTask(sessionId), {});// Authoritative refetch reconciles redaction / migrations / clients// that took the fallback branch above.invalidateChatMessageQueries(qc, sessionId);@@ -326,14 +317,8 @@ export function applyChatCancelFinalizedToCache(if (payload.message_id) {removeChatMessageFromCaches(qc, sessionId, payload.message_id);}- // 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),- );+ qc.setQueryData(chatKeys.pendingTask(sessionId), {});invalidateChatMessageQueries(qc, sessionId);- qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });const isInitiator =!!payload.initiator_user_id &&!!currentUserId &&@@ -1227,13 +1212,12 @@ export function useRealtimeSync(if (!payload.chat_session_id) return;qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(payload.chat_session_id),- (old) => enqueuePendingChatTask(old, {+ (old) => ({+ ...(old ?? {}),task_id: payload.task_id,status: "queued",- created_at: new Date().toISOString(),}),);- qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });invalidatePendingAggregate();});@@ -1248,7 +1232,10 @@ export function useRealtimeSync(if (!payload.chat_session_id) return;qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(payload.chat_session_id),- (old) => promotePendingChatTask(old, payload.task_id, "running"),+ (old) => {+ if (!old || old.task_id !== payload.task_id) return old;+ return { ...old, status: "running" };+ },);invalidatePendingAggregate();});@@ -1263,7 +1250,10 @@ export function useRealtimeSync(if (!payload.chat_session_id) return;qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(payload.chat_session_id),- (old) => promotePendingChatTask(old, payload.task_id, "running"),+ (old) => {+ if (!old || old.task_id !== payload.task_id) return old;+ return { ...old, status: "running" };+ },);invalidatePendingAggregate();});@@ -1280,12 +1270,10 @@ export function useRealtimeSync(if (!payload.chat_session_id) return;qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(payload.chat_session_id),- (old) =>- promotePendingChatTask(- old,- payload.task_id,- "waiting_local_directory",- ),+ (old) => {+ if (!old || old.task_id !== payload.task_id) return old;+ return { ...old, status: "waiting_local_directory" };+ },);invalidatePendingAggregate();},@@ -1306,11 +1294,7 @@ export function useRealtimeSync(task_id: payload.task_id,chat_session_id: 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) });+ qc.setQueryData(chatKeys.pendingTask(payload.chat_session_id), {});invalidateChatMessageQueries(qc, payload.chat_session_id);invalidatePendingAggregate();});@@ -1322,11 +1306,12 @@ export function useRealtimeSync(task_id: payload.task_id,chat_session_id: 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) });+ // `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.invalidatePendingAggregate();});@@ -1343,10 +1328,7 @@ 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<ChatPendingTask>(- chatKeys.pendingTask(payload.chat_session_id),- (old) => removePendingChatTask(old, payload.task_id),- );+ qc.setQueryData(chatKeys.pendingTask(payload.chat_session_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.tsindex 4ce8d05bea..c0a069ac63 100644--- a/packages/core/types/chat.ts+++ b/packages/core/types/chat.ts@@ -192,21 +192,8 @@ 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.tsindex 932491e849..c31ec48662 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -100,7 +100,6 @@ 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.tsxindex 75b9a1a4e2..08fde2faba 100644--- a/packages/ui/components/common/submit-button.tsx+++ b/packages/ui/components/common/submit-button.tsx@@ -24,8 +24,6 @@ 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.@@ -48,13 +46,11 @@ function SubmitButton({busy,running,onStop,- allowSubmitWhileRunning,tooltip,ariaLabel,stopTooltip,stopAriaLabel,}: SubmitButtonProps) {- let stopControl: ReactNode = null;if (running) {const stopButton = (<Button@@ -66,13 +62,13 @@ function SubmitButton({<Square className="fill-current" aria-hidden="true" /></Button>);- stopControl = stopTooltip ? (+ if (!stopTooltip) return stopButton;+ return (<Tooltip><TooltipTrigger render={stopButton} /><TooltipContent side="top">{stopTooltip}</TooltipContent></Tooltip>- ) : stopButton;- if (!allowSubmitWhileRunning) return stopControl;+ );}const submitButton = (@@ -97,20 +93,12 @@ function SubmitButton({)}</Button>);- const submitControl = !tooltip- ? submitButton- : (- <Tooltip>- <TooltipTrigger render={submitButton} />- <TooltipContent side="top">{tooltip}</TooltipContent>- </Tooltip>- );- if (!stopControl) return submitControl;+ if (!tooltip) return submitButton;return (- <>- {stopControl}- {submitControl}- </>+ <Tooltip>+ <TooltipTrigger render={submitButton} />+ <TooltipContent side="top">{tooltip}</TooltipContent>+ </Tooltip>);}diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsxindex 4c4743e163..839bc81a1d 100644--- a/packages/views/chat/chat-page.tsx+++ b/packages/views/chat/chat-page.tsx@@ -19,7 +19,6 @@ 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";@@ -260,11 +259,6 @@ export function ChatPage() {<OfflineBanner agentName={c.activeAgent?.name} availability={c.availability} />)}- <ChatQueue- tasks={c.pendingTask?.queued_tasks ?? []}- onRemove={c.handleRemoveQueuedTask}- />-<ChatInputonSend={c.handleSend}restoreDraftRequest={c.restoreDraftRequest}diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsxindex 0102d2ba1e..788de9d838 100644--- a/packages/views/chat/components/chat-input.test.tsx+++ b/packages/views/chat/components/chat-input.test.tsx@@ -593,23 +593,6 @@ 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 projectdiff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex e5b42fe2f0..f83f4ce317 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 (disabled || noAgent) {- logger.debug("input.send skipped", { disabled, noAgent });+ if (isRunning || disabled || noAgent) {+ logger.debug("input.send skipped", { isRunning, disabled, noAgent });return false;}// The editor is still holding a DIFFERENT draft's document than the one@@ -673,18 +673,13 @@ export function ChatInput({busy={gate.uploading}running={isRunning}onStop={onStop}- allowSubmitWhileRunningtooltip={gate.uploading? tEditor(($) => $.upload.in_progress)- : isRunning- ? t(($) => $.input.queue_send_tooltip)- : sendShortcut- ? `${t(($) => $.input.send_tooltip)} · ${formatShortcut(sendShortcut)}`- : t(($) => $.input.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.tsxdeleted file mode 100644index b0d208f563..0000000000--- a/packages/views/chat/components/chat-queue.test.tsx+++ /dev/null@@ -1,53 +0,0 @@-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.tsxdeleted file mode 100644index 6b5aa9402b..0000000000--- a/packages/views/chat/components/chat-queue.tsx+++ /dev/null@@ -1,68 +0,0 @@-"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.tsxindex d674249a88..413661b2d5 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -48,16 +48,11 @@ 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";@@ -394,10 +389,7 @@ export function ChatWindow() {sessionId,source: options.source,});- qc.setQueryData<ChatPendingTask>(- chatKeys.pendingTask(sessionId),- (old) => removePendingChatTask(old, taskId),- );+ qc.setQueryData(chatKeys.pendingTask(sessionId), {});try {const result = await api.cancelTaskById(taskId);@@ -430,12 +422,9 @@ 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, wsId],+ [qc, enqueueLocalRestore],);const handleSend = useCallback(@@ -529,16 +518,11 @@ export function ChatWindow() {chatKeys.messages(sessionId),(old) => (old ? [...old, sent] : [sent]),);- 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,- }),- );+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {+ task_id: result.task_id,+ status: "queued",+ created_at: result.created_at,+ });// 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@@ -611,17 +595,6 @@ 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@@ -882,11 +855,6 @@ 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.tsxindex 09f93cb14c..64a5f83d51 100644--- a/packages/views/chat/components/use-chat-controller.test.tsx+++ b/packages/views/chat/components/use-chat-controller.test.tsx@@ -481,47 +481,6 @@ 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 firediff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex 14f70ef0cd..87530ad580 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -30,10 +30,6 @@ 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";@@ -445,10 +441,7 @@ export function useChatController(opts?: { isActive?: boolean }) {sessionId,source: options.source,});- qc.setQueryData<ChatPendingTask>(- chatKeys.pendingTask(sessionId),- (old) => removePendingChatTask(old, taskId),- );+ qc.setQueryData(chatKeys.pendingTask(sessionId), {});try {const result = await api.cancelTaskById(taskId);@@ -481,12 +474,9 @@ 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, wsId],+ [qc, enqueueLocalRestore],);const handleSend = useCallback(@@ -590,16 +580,11 @@ export function useChatController(opts?: { isActive?: boolean }) {chatKeys.messages(sessionId),(old) => (old ? [...old, sent] : [sent]),);- 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,- }),- );+ qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {+ task_id: result.task_id,+ status: "queued",+ created_at: result.created_at,+ });// 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@@ -666,17 +651,6 @@ 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,@@ -846,7 +820,6 @@ export function useChatController(opts?: { isActive?: boolean }) {// actionshandleSend,handleStop,- handleRemoveQueuedTask,uploadEnabled,handleNewChat,handleStartNewChat,diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex 2650f4ce33..2b2ef55d59 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -17,7 +17,6 @@"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",@@ -30,12 +29,6 @@"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.jsonindex 1d13a7b0c2..76ff5c6946 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -16,7 +16,6 @@"placeholder_named": "{{name}} にメッセージ…","placeholder_default": "メッセージを入力…","send_tooltip": "送信",- "queue_send_tooltip": "キューに追加","stop_tooltip": "停止","send_failed_toast": "メッセージを送信できませんでした","send_blocked_toast": "メッセージは送信されませんでした — このエージェントを使用する権限がありません",@@ -29,11 +28,6 @@"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.jsonindex 967cfabb1f..288d8f85d5 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -16,7 +16,6 @@"placeholder_named": "{{name}}에게 메시지 보내기…","placeholder_default": "메시지 입력…","send_tooltip": "보내기",- "queue_send_tooltip": "대기열에 추가","stop_tooltip": "중지","send_failed_toast": "메시지를 보내지 못했습니다","send_blocked_toast": "메시지가 전송되지 않았습니다 — 이 에이전트를 사용할 권한이 없습니다",@@ -29,11 +28,6 @@"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.jsonindex ab87ba6266..9c1c352a13 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -16,7 +16,6 @@"placeholder_named": "给 {{name}} 发消息…","placeholder_default": "输入消息…","send_tooltip": "发送",- "queue_send_tooltip": "排队发送","stop_tooltip": "停止","send_failed_toast": "发送消息失败","send_blocked_toast": "消息未发送——你已没有该智能体的使用权限",@@ -29,11 +28,6 @@"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.goindex c9c28fcd3a..a1e98e3fd1 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -994,18 +994,9 @@ 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"`- 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"`+ TaskID string `json:"task_id,omitempty"`+ Status string `json:"status,omitempty"`+ CreatedAt string `json:"created_at,omitempty"`}// MarkChatSessionRead clears the session's unread_since (→ has_unread=false)@@ -1329,9 +1320,9 @@ func (h *Handler) HasPendingChatTasks(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, HasPendingChatTasksResponse{HasPending: hasPending})}-// 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.+// 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.func (h *Handler) GetPendingChatTask(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {@@ -1345,36 +1336,17 @@ func (h *Handler) GetPendingChatTask(w http.ResponseWriter, r *http.Request) {return}- tasks, err := h.Queries.ListPendingChatTasksForSession(r.Context(), session.ID)+ task, err := h.Queries.GetPendingChatTask(r.Context(), session.ID)if err != nil {- writeError(w, http.StatusInternalServerError, "failed to list pending chat tasks")- return- }- if len(tasks) == 0 {+ // No in-flight task — return an empty object, not an error.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(head.ID),- Status: head.Status,- CreatedAt: timestampToString(head.CreatedAt),- QueuedTasks: queued,+ TaskID: uuidToString(task.ID),+ Status: task.Status,+ CreatedAt: timestampToString(task.CreatedAt),})}diff --git a/server/internal/handler/chat_pending_tasks_test.go b/server/internal/handler/chat_pending_tasks_test.goindex fd4e772363..1a973576cf 100644--- a/server/internal/handler/chat_pending_tasks_test.go+++ b/server/internal/handler/chat_pending_tasks_test.go@@ -98,75 +98,6 @@ 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).@@ -305,6 +236,7 @@ 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@@ -342,4 +274,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 filediff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex d57e29c1fa..db12a6d767 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -1301,69 +1301,6 @@ func (q *Queries) ListPendingChatTasksByCreator(ctx context.Context, arg ListPenreturn 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 :oneSELECT id FROM chat_sessionWHERE id = $1diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 78ec0ec59f..92064e500f 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -464,34 +464,6 @@ WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waORDER BY created_at DESCLIMIT 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