Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(chat): route settled chat messages through one cache door (MUL-5711) (#6559)
Naiyuan Qingc7a8b1699f98
diff --git a/packages/core/chat/message-cache.test.ts b/packages/core/chat/message-cache.test.tsnew file mode 100644index 0000000000..1f9efc50ed--- /dev/null+++ b/packages/core/chat/message-cache.test.ts@@ -0,0 +1,140 @@+import { QueryClient, type InfiniteData } from "@tanstack/react-query";+import { describe, expect, it } from "vitest";+import { chatKeys } from "./queries";+import { upsertChatMessageToCaches } from "./message-cache";+import type { ChatMessage, ChatMessagesPage } from "../types";++const sessionId = "session-1";+const flatKey = chatKeys.messages(sessionId);+const pageKey = chatKeys.messagesPage(sessionId);++function qcWith(messages: ChatMessage[] | null, pages?: ChatMessagesPage[]) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ if (messages) qc.setQueryData<ChatMessage[]>(flatKey, messages);+ if (pages) {+ qc.setQueryData<InfiniteData<ChatMessagesPage>>(pageKey, {+ pages,+ pageParams: pages.map((_, i) => (i === 0 ? null : { created_at: "x", id: "x" })),+ });+ }+ return qc;+}++function message(overrides: Partial<ChatMessage> = {}): ChatMessage {+ return {+ id: "msg-1",+ chat_session_id: sessionId,+ role: "user",+ content: "hello",+ task_id: "task-1",+ created_at: "2026-05-13T05:00:00Z",+ ...overrides,+ };+}++function page(messages: ChatMessage[]): ChatMessagesPage {+ return { messages, limit: 50, has_more: false, next_cursor: null };+}++function flatIds(qc: QueryClient) {+ return qc.getQueryData<ChatMessage[]>(flatKey)?.map((m) => m.id);+}++function pageIds(qc: QueryClient) {+ return qc+ .getQueryData<InfiniteData<ChatMessagesPage>>(pageKey)+ ?.pages.map((p) => p.messages.map((m) => m.id));+}++describe("upsertChatMessageToCaches", () => {+ it("writes into both caches in one call", () => {+ const existing = message({ id: "msg-0" });+ const qc = qcWith([existing], [page([existing])]);++ upsertChatMessageToCaches(qc, sessionId, message());++ expect(flatIds(qc)).toEqual(["msg-0", "msg-1"]);+ expect(pageIds(qc)).toEqual([["msg-0", "msg-1"]]);+ });++ it("appends to the newest page only, never to older pages", () => {+ const older = message({ id: "msg-old", created_at: "2026-05-13T04:00:00Z" });+ const latest = message({ id: "msg-latest" });+ // Page 0 is the newest window; later pages are older cursor pages.+ const qc = qcWith(null, [page([latest]), page([older])]);++ upsertChatMessageToCaches(qc, sessionId, message({ id: "msg-new" }));+ upsertChatMessageToCaches(qc, sessionId, message({ id: "msg-new" }));++ expect(pageIds(qc)).toEqual([["msg-latest", "msg-new"], ["msg-old"]]);+ });++ it("merges a repeat instead of appending, wherever the row lives", () => {+ const inOlderPage = message({ id: "msg-old" });+ const qc = qcWith([inOlderPage], [page([]), page([inOlderPage])]);++ upsertChatMessageToCaches(qc, sessionId, message({ id: "msg-old", elapsed_ms: 42 }));++ expect(pageIds(qc)).toEqual([[], ["msg-old"]]);+ expect(+ qc.getQueryData<InfiniteData<ChatMessagesPage>>(pageKey)?.pages[1]?.messages[0]+ ?.elapsed_ms,+ ).toBe(42);+ });++ // The reason the merge direction matters: the send response carries draft+ // attachments, the chat:message echo of the same send has no attachments+ // field at all. Whichever lands first, the attachments must survive.+ it("keeps the richer row regardless of arrival order", () => {+ const withAttachments = message({ attachments: [{ id: "att-1" } as never] });+ const fromWs = message();++ const sendFirst = qcWith([withAttachments], [page([withAttachments])]);+ upsertChatMessageToCaches(sendFirst, sessionId, fromWs);+ expect(sendFirst.getQueryData<ChatMessage[]>(flatKey)?.[0]?.attachments).toHaveLength(1);++ const wsFirst = qcWith([fromWs], [page([fromWs])]);+ upsertChatMessageToCaches(wsFirst, sessionId, withAttachments);+ expect(wsFirst.getQueryData<ChatMessage[]>(flatKey)?.[0]?.attachments).toHaveLength(1);+ });++ it("keeps the row reference stable when nothing was filled", () => {+ const existing = message({ elapsed_ms: 7 });+ const qc = qcWith([existing], [page([existing])]);++ upsertChatMessageToCaches(qc, sessionId, message({ elapsed_ms: 999, content: "x" }));++ expect(qc.getQueryData<ChatMessage[]>(flatKey)?.[0]).toBe(existing);+ });++ it("leaves an unfetched cache alone by default", () => {+ const qc = qcWith(null);++ upsertChatMessageToCaches(qc, sessionId, message());++ expect(qc.getQueryData(flatKey)).toBeUndefined();+ expect(qc.getQueryData(pageKey)).toBeUndefined();+ });++ it("seeds both caches for a brand-new session when asked", () => {+ const qc = qcWith(null);++ upsertChatMessageToCaches(qc, sessionId, message(), { seedIfMissing: true });++ expect(flatIds(qc)).toEqual(["msg-1"]);+ expect(pageIds(qc)).toEqual([["msg-1"]]);+ const seeded = qc.getQueryData<InfiniteData<ChatMessagesPage>>(pageKey);+ expect(seeded?.pages[0]?.has_more).toBe(false);+ expect(seeded?.pageParams).toEqual([null]);+ });++ it("does not seed twice when the same send is applied again", () => {+ const qc = qcWith(null);++ upsertChatMessageToCaches(qc, sessionId, message(), { seedIfMissing: true });+ upsertChatMessageToCaches(qc, sessionId, message(), { seedIfMissing: true });++ expect(flatIds(qc)).toEqual(["msg-1"]);+ expect(pageIds(qc)).toEqual([["msg-1"]]);+ });+});diff --git a/packages/core/chat/message-cache.ts b/packages/core/chat/message-cache.tsnew file mode 100644index 0000000000..a0953cefa2--- /dev/null+++ b/packages/core/chat/message-cache.ts@@ -0,0 +1,135 @@+import type { InfiniteData, QueryClient } from "@tanstack/react-query";+import { chatKeys } from "./queries";+import type { ChatMessage, ChatMessagesPage } from "../types";++/**+ * The single door a settled chat message goes through on its way into the+ * message caches (MUL-5711).+ *+ * Before this, every writer rolled its own: `chat:done` inline-inserted the+ * assistant reply, `chat:message` threw its payload away and only invalidated,+ * and the three send paths each appended by hand — two of them to both caches,+ * the Agent Builder to the flat one only. The gap that produced this bug was in+ * that inconsistency, not in any single writer: a human's own message was the+ * one row no WebSocket handler ever wrote, so it reached the transcript solely+ * through a refetch, and a refetch that gets cancelled takes the message with+ * it.+ *+ * Two rules, both order-independent, so the same message arriving twice by+ * different routes converges instead of duplicating or downgrading:+ *+ * 1. Identity is `message.id`. A second write for an id already present+ * merges instead of appending.+ * 2. On merge the row already in cache wins every field it defines; the+ * incoming row only fills fields that are missing. A send response+ * carrying `attachments` therefore survives the WebSocket echo that has+ * no attachments field at all — in either arrival order.+ */++/** Fields present on `incoming` fill only the gaps in `existing`. */+function mergeChatMessage(existing: ChatMessage, incoming: ChatMessage): ChatMessage {+ const fills: Partial<ChatMessage> = {};+ let filled = false;+ for (const key of Object.keys(incoming) as (keyof ChatMessage)[]) {+ if (existing[key] !== undefined || incoming[key] === undefined) continue;+ Object.assign(fills, { [key]: incoming[key] });+ filled = true;+ }+ // Reference-stable when nothing was filled, so observers do not re-render.+ return filled ? { ...existing, ...fills } : existing;+}++/**+ * Merge into the row with this id if the list has one. Never appends — the+ * caller decides where a genuinely new message goes, which for a paged cache is+ * one specific page.+ */+function mergeIntoList(messages: ChatMessage[], message: ChatMessage): ChatMessage[] {+ const index = messages.findIndex((m) => m.id === message.id);+ if (index < 0) return messages;+ const merged = mergeChatMessage(messages[index]!, message);+ if (merged === messages[index]) return messages;+ return messages.map((m, i) => (i === index ? merged : m));+}++function upsertIntoList(messages: ChatMessage[], message: ChatMessage): ChatMessage[] {+ const merged = mergeIntoList(messages, message);+ if (merged !== messages) return merged;+ return messages.some((m) => m.id === message.id) ? messages : [...messages, message];+}++function upsertIntoPages(+ data: InfiniteData<ChatMessagesPage>,+ message: ChatMessage,+): InfiniteData<ChatMessagesPage> {+ const seen = data.pages.some((page) => page.messages.some((m) => m.id === message.id));+ if (seen) {+ // Merge in place, wherever the row already lives. Appending here instead+ // would drop a copy into every OTHER page.+ let changed = false;+ const pages = data.pages.map((page) => {+ const next = mergeIntoList(page.messages, message);+ if (next === page.messages) return page;+ changed = true;+ return { ...page, messages: next };+ });+ return changed ? { ...data, pages } : data;+ }+ // Page 0 is the newest window (later pages are older cursor pages), so a new+ // message belongs at the end of it.+ return {+ ...data,+ pages: data.pages.map((page, index) =>+ index === 0 ? { ...page, messages: [...page.messages, message] } : page,+ ),+ };+}++function seedPage(message: ChatMessage): InfiniteData<ChatMessagesPage> {+ return {+ pages: [{ messages: [message], limit: 50, has_more: false, next_cursor: null }],+ pageParams: [null],+ };+}++export interface UpsertChatMessageOptions {+ /**+ * Create the cache entry when the session has never been fetched.+ *+ * Send paths pass `true`: a brand-new session must render its first message+ * before any fetch exists, and the send's own invalidate reconciles the+ * placeholder page immediately after.+ *+ * WebSocket handlers pass `false` (the default). An event for a session this+ * client has not opened must not fabricate a one-message history that a later+ * reader would mistake for the whole transcript — the first real fetch owns+ * that.+ */+ seedIfMissing?: boolean;+}++/**+ * Upsert one settled message into both message caches.+ *+ * Both are written because both are read: `chatKeys.messagesPage` backs the+ * chat surfaces, `chatKeys.messages` backs the Agent Builder. Writing one and+ * not the other is how they drift.+ */+export function upsertChatMessageToCaches(+ qc: QueryClient,+ sessionId: string,+ message: ChatMessage,+ { seedIfMissing = false }: UpsertChatMessageOptions = {},+): void {+ qc.setQueryData<ChatMessage[] | undefined>(chatKeys.messages(sessionId), (old) => {+ if (!old) return seedIfMissing ? [message] : old;+ return upsertIntoList(old, message);+ });+ qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(+ chatKeys.messagesPage(sessionId),+ (old) => {+ if (!old?.pages.length) return seedIfMissing ? seedPage(message) : old;+ return upsertIntoPages(old, message);+ },+ );+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 61bfad1634..aa5db6e72f 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -56,6 +56,7 @@"./chat/queries": "./chat/queries.ts","./chat/mutations": "./chat/mutations.ts","./chat/pending": "./chat/pending.ts",+ "./chat/message-cache": "./chat/message-cache.ts","./chat/use-quick-actions-pending-timeout": "./chat/use-quick-actions-pending-timeout.ts","./chat/unread": "./chat/unread.ts","./runtimes": "./runtimes/index.ts",diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.tsindex f8ac8b478f..965021a85d 100644--- a/packages/core/realtime/use-realtime-sync.test.ts+++ b/packages/core/realtime/use-realtime-sync.test.ts@@ -14,6 +14,7 @@ import { workspaceKeys } from "../workspace/queries";import type {ChatDonePayload,ChatMessage,+ ChatMessageEventPayload,ChatPendingTask,ChatMessagesPage,ChatSession,@@ -23,6 +24,7 @@ import type {import {applyChatCancelFinalizedToCache,applyChatDoneToCache,+ applyChatMessageToCache,applyChatQuickActionsToCache,applyChatSessionUpdatedToCache,applyWorkspaceUpdatedToCache,@@ -129,6 +131,12 @@ describe("applyChatDoneToCache", () => {);});+ // A replay merges instead of appending (MUL-5711): the cached row keeps every+ // field it already has, and only fields it is MISSING are filled from the+ // payload — here `message_kind`, which this hand-built row predates. That+ // fill direction is what lets a send response and its chat:message echo+ // converge in either arrival order without the echo dropping the response's+ // attachments.it("does not duplicate a replayed chat done event", () => {const qc = createQueryClient();const assistant: ChatMessage = {@@ -146,15 +154,38 @@ describe("applyChatDoneToCache", () => {status: "running",});+ applyChatDoneToCache(qc, donePayload());applyChatDoneToCache(qc, donePayload());expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toEqual([userMessage(),- assistant,+ { ...assistant, message_kind: "message" },]);expect(qc.getQueryData<ChatPendingTask>(pendingKey)).toEqual({});});+ // The cached row wins on every field it defines, so a later, thinner write+ // for the same id cannot downgrade it.+ it("does not let a replay overwrite fields the cached row already has", () => {+ const qc = createQueryClient();+ const assistant: ChatMessage = {+ id: "msg-assistant",+ chat_session_id: sessionId,+ role: "assistant",+ content: "done",+ task_id: taskId,+ created_at: "2026-05-13T05:00:02Z",+ elapsed_ms: 1234,+ message_kind: "message",+ attachments: [],+ };+ qc.setQueryData<ChatMessage[]>(messagesKey, [assistant]);++ applyChatDoneToCache(qc, donePayload({ content: "", elapsed_ms: 9999 }));++ expect(qc.getQueryData<ChatMessage[]>(messagesKey)?.[0]).toBe(assistant);+ });+it("falls back to invalidation-only when older servers omit message fields", () => {const qc = createQueryClient();qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage()]);@@ -1061,19 +1092,28 @@ describe("chat quick-actions supplement flow", () => {task_id: taskId,created_at: "2026-05-13T05:00:02Z",};+ const actions = [{ label: "Next", prompt: "Do the next thing", primary: true }];// Settled post-chat:done state: assistant present, no actions yet.const staleRows = [userMessage(), assistant];qc.setQueryData<ChatMessage[]>(messagesKey, staleRows);+ // Server truth, which the broadcast lags: the actions are persisted BEFORE+ // chat:quick_actions is published (SupplementChatQuickActions), so a request+ // issued after the event reads them back while the in-flight one predates+ // them.+ let serverRows = staleRows;+// An active observer (a mounted chat screen) whose refetch we hold open, so// it is genuinely in flight when the supplement lands.let releaseRefetch: ((rows: ChatMessage[]) => void) | undefined;const observer = new QueryObserver<ChatMessage[]>(qc, {queryKey: messagesKey,queryFn: () =>- new Promise<ChatMessage[]>((resolve) => {- releaseRefetch = resolve;- }),+ releaseRefetch+ ? Promise.resolve(serverRows)+ : new Promise<ChatMessage[]>((resolve) => {+ releaseRefetch = resolve;+ }),staleTime: Infinity,gcTime: Infinity,retry: false,@@ -1087,7 +1127,7 @@ describe("chat quick-actions supplement flow", () => {expect(typeof releaseRefetch).toBe("function");});- const actions = [{ label: "Next", prompt: "Do the next thing", primary: true }];+ serverRows = [userMessage(), { ...assistant, quick_actions: actions }];await applyChatQuickActionsToCache(qc, {chat_session_id: sessionId,task_id: taskId,@@ -1106,4 +1146,154 @@ describe("chat quick-actions supplement flow", () => {);unsub();});++ // Regression (MUL-5711): cancelQueries defaults to revert:true, so the cancel+ // above ALSO rolls the cache back to the pre-fetch snapshot. Rows that only+ // the cancelled response carried — a peer's user message, anything that landed+ // while this surface was unmounted — must come back, which is what the+ // re-invalidate after the patch is for. Without it the hole is permanent: both+ // caches are staleTime: Infinity and nothing else re-fetches.+ it("re-syncs after the cancel so rows only the cancelled refetch carried are not lost", async () => {+ const qc = createQueryClient();+ const assistant: ChatMessage = {+ id: "msg-assistant",+ chat_session_id: sessionId,+ role: "assistant",+ content: "done",+ task_id: taskId,+ created_at: "2026-05-13T05:00:02Z",+ };+ // This client never wrote the peer's prompt locally — only the in-flight+ // refetch carries it.+ const peerPrompt: ChatMessage = {+ id: "msg-peer",+ chat_session_id: sessionId,+ role: "user",+ content: "sent from another window",+ task_id: taskId,+ created_at: "2026-05-13T05:00:01Z",+ };+ const actions = [{ label: "Next", prompt: "Do the next thing", primary: true }];+ qc.setQueryData<ChatMessage[]>(messagesKey, [assistant]);++ let serverRows: ChatMessage[] = [peerPrompt, assistant];+ let releaseRefetch: ((rows: ChatMessage[]) => void) | undefined;+ const observer = new QueryObserver<ChatMessage[]>(qc, {+ queryKey: messagesKey,+ queryFn: () =>+ releaseRefetch+ ? Promise.resolve(serverRows)+ : new Promise<ChatMessage[]>((resolve) => {+ releaseRefetch = resolve;+ }),+ staleTime: Infinity,+ gcTime: Infinity,+ retry: false,+ });+ const unsub = observer.subscribe(() => {});++ void qc.invalidateQueries({ queryKey: messagesKey });+ await vi.waitFor(() => {+ expect(qc.getQueryState(messagesKey)?.fetchStatus).toBe("fetching");+ expect(typeof releaseRefetch).toBe("function");+ });++ serverRows = [peerPrompt, { ...assistant, quick_actions: actions }];+ await applyChatQuickActionsToCache(qc, {+ chat_session_id: sessionId,+ task_id: taskId,+ message_id: "msg-assistant",+ quick_actions: actions,+ });+ releaseRefetch?.([peerPrompt, assistant]);++ await vi.waitFor(() => {+ const rows = qc.getQueryData<ChatMessage[]>(messagesKey);+ expect(rows?.map((m) => m.id)).toEqual(["msg-peer", "msg-assistant"]);+ expect(rows?.at(-1)?.quick_actions).toEqual(actions);+ });+ unsub();+ });+});++describe("applyChatMessageToCache", () => {+ function messagePayload(+ overrides: Partial<ChatMessageEventPayload> = {},+ ): ChatMessageEventPayload {+ return {+ chat_session_id: sessionId,+ message_id: "msg-user-2",+ role: "user",+ content: "second prompt",+ task_id: taskId,+ created_at: "2026-05-13T05:00:05Z",+ ...overrides,+ };+ }++ it("writes the user message into both caches without waiting for a refetch", () => {+ const qc = createQueryClient();+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage()]);+ qc.setQueryData<InfiniteData<ChatMessagesPage>>(chatKeys.messagesPage(sessionId), {+ pages: [{ messages: [userMessage()], limit: 50, has_more: false, next_cursor: null }],+ pageParams: [null],+ });++ applyChatMessageToCache(qc, messagePayload());++ const flat = qc.getQueryData<ChatMessage[]>(messagesKey);+ expect(flat?.map((m) => m.id)).toEqual(["msg-user", "msg-user-2"]);+ expect(flat?.at(-1)).toMatchObject({+ role: "user",+ content: "second prompt",+ task_id: taskId,+ created_at: "2026-05-13T05:00:05Z",+ });+ const pages = qc.getQueryData<InfiniteData<ChatMessagesPage>>(+ chatKeys.messagesPage(sessionId),+ );+ expect(pages?.pages[0]?.messages.map((m) => m.id)).toEqual(["msg-user", "msg-user-2"]);+ });++ it("is idempotent against the sender's own write and reconnect replay", () => {+ const qc = createQueryClient();+ // The sender's row is richer than the event: it carries the draft+ // attachments, which this payload has no field for.+ const alreadySent: ChatMessage = {+ id: "msg-user-2",+ chat_session_id: sessionId,+ role: "user",+ content: "second prompt",+ task_id: taskId,+ created_at: "2026-05-13T05:00:05Z",+ attachments: [],+ };+ qc.setQueryData<ChatMessage[]>(messagesKey, [alreadySent]);++ applyChatMessageToCache(qc, messagePayload());+ applyChatMessageToCache(qc, messagePayload());++ const rows = qc.getQueryData<ChatMessage[]>(messagesKey);+ expect(rows).toHaveLength(1);+ expect(rows?.[0]).toBe(alreadySent);+ });++ it("leaves assistant turns to chat:done, which carries the richer row", () => {+ const qc = createQueryClient();+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage()]);++ applyChatMessageToCache(+ qc,+ messagePayload({ message_id: "msg-assistant", role: "assistant", content: "done" }),+ );++ expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toHaveLength(1);+ });++ it("does not seed an unfetched cache — the first fetch owns it", () => {+ const qc = createQueryClient();+ applyChatMessageToCache(qc, messagePayload());+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toBeUndefined();+ expect(qc.getQueryData(chatKeys.messagesPage(sessionId))).toBeUndefined();+ });});diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 54af3c7d3d..32aea87c4f 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -57,6 +57,7 @@ import {QUICK_ACTIONS_PENDING_TIMEOUT_MS,} from "../chat/queries";import { useChatStore } from "../chat";+import { upsertChatMessageToCaches } from "../chat/message-cache";import {promotePendingChatTask,removePendingChatTask,@@ -103,6 +104,7 @@ import type {ChatQuickActionsFailureState,ChatCancelFinalizedPayload,ChatMessage,+ ChatMessageEventPayload,ChatPendingTask,ChatMessagesPage,ChatSession,@@ -142,6 +144,46 @@ export function refetchPendingChatAggregate(qc.invalidateQueries({ queryKey: chatKeys.pendingTasks(wsId) });}+/**+ * Apply a chat:message event: write the turn's USER message into the message+ * caches, then reconcile authoritatively (MUL-5711).+ *+ * The payload has always carried the whole message; this handler used to read+ * `chat_session_id` off it and drop the rest, which made a human's own prompt+ * the one row that reached the transcript ONLY through the refetch below. Any+ * client that did not write it locally — a second window or device, a send+ * whose HTTP response failed after the server committed, a surface mounting+ * mid-flight — lost it whenever that refetch was dropped, most reliably to the+ * chat:quick_actions cancel. Both caches are staleTime: Infinity, so nothing+ * re-fetched afterwards and the prompt stayed missing until a remount.+ *+ * Only `role: "user"` is written. SendChatMessage is the event's one producer,+ * and an assistant row fabricated from this payload would carry no elapsed_ms /+ * message_kind / quick_actions while still claiming the id that+ * applyChatDoneToCache is about to write properly.+ *+ * The invalidate stays: this payload has no `attachments`, so the reconciling+ * refetch is what fills them in for clients that did not send the message.+ */+export function applyChatMessageToCache(+ qc: QueryClient,+ payload: ChatMessageEventPayload,+) {+ const sessionId = payload.chat_session_id;+ if (payload.role === "user" && payload.message_id) {+ upsertChatMessageToCaches(qc, sessionId, {+ id: payload.message_id,+ chat_session_id: sessionId,+ role: "user",+ content: payload.content ?? "",+ task_id: payload.task_id ?? null,+ created_at: payload.created_at ?? new Date().toISOString(),+ });+ }+ invalidateChatMessageQueries(qc, sessionId);+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });+}+export function applyChatDoneToCache(qc: QueryClient,payload: ChatDonePayload,@@ -167,19 +209,9 @@ export function applyChatDoneToCache(? { quick_actions: payload.quick_actions }: {}),};- qc.setQueryData<ChatMessage[] | undefined>(- chatKeys.messages(sessionId),- (old) => {- if (!old) return old; // first fetch will pick it up- // Idempotent against reconnect replay.- if (old.some((m) => m.id === messageId)) return old;- return [...old, assistant];- },- );- qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(- chatKeys.messagesPage(sessionId),- (old) => patchLatestChatMessagePage(old, assistant),- );+ // Idempotent against reconnect replay and against a refetch that already+ // landed this row.+ upsertChatMessageToCaches(qc, sessionId, 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.@@ -256,6 +288,16 @@ export async function applyChatQuickActionsToCache(}: old,);+ // Settle the cancel (MUL-5711). cancelQueries defaults to `revert: true`,+ // so the line above does more than ignore the in-flight response — it rolls+ // the cache back to the snapshot taken when that fetch STARTED, dropping+ // rows only that response carried (a peer's user message, anything that+ // landed while this surface was unmounted). With staleTime: Infinity and no+ // further trigger, the hole survived until a remount. Re-invalidating costs+ // one request per supplement and cannot lose the pills: the server persists+ // the actions BEFORE broadcasting this event (SupplementChatQuickActions),+ // so the refetch this schedules reads them back.+ invalidateChatMessageQueries(qc, sessionId);}// Resolve the marker only when it belongs to THIS message: a late// supplement for turn N must not clear the marker turn N+1's chat:done@@ -277,25 +319,6 @@ export async function applyChatQuickActionsToCache(}}-function patchLatestChatMessagePage(- old: InfiniteData<ChatMessagesPage> | undefined,- message: ChatMessage,-): InfiniteData<ChatMessagesPage> | undefined {- if (!old?.pages.length) return old;- const seen = old.pages.some((page) => page.messages.some((m) => m.id === message.id));- if (seen) return old;- return {- ...old,- pages: old.pages.map((page, index) => {- if (index !== 0) return page;- return {- ...page,- messages: [...page.messages, message],- };- }),- };-}-type ChatSessionUpdatedPayload = {chat_session_id: string;title?: string;@@ -1268,10 +1291,14 @@ export function useRealtimeSync(};const unsubChatMessage = ws.on("chat:message", (p) => {- const payload = p as { chat_session_id: string };- chatWsLogger.info("chat:message (global)", { chat_session_id: payload.chat_session_id });- invalidateChatMessageQueries(qc, payload.chat_session_id);- qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });+ const payload = p as ChatMessageEventPayload;+ chatWsLogger.info("chat:message (global)", {+ chat_session_id: payload.chat_session_id,+ role: payload.role,+ });+ // Write the user turn before invalidating so the prompt does not depend+ // on the refetch surviving (MUL-5711) — same shape as chat:done.+ applyChatMessageToCache(qc, payload);// NOTE: intentionally does NOT touch the pending aggregate. chat:message// fires per streamed message with no status; the aggregate is maintained// by the task lifecycle handlers below (MUL-4159).diff --git a/packages/views/agents/create/use-builder-session-cache.test.tsx b/packages/views/agents/create/use-builder-session-cache.test.tsxnew file mode 100644index 0000000000..1ef5e6db3f--- /dev/null+++ b/packages/views/agents/create/use-builder-session-cache.test.tsx@@ -0,0 +1,183 @@+// @vitest-environment jsdom++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { InfiniteData } from "@tanstack/react-query";+import { createElement, type ReactNode } from "react";++const h = vi.hoisted(() => ({+ sendChatMessage: vi.fn(),+ cancelTaskById: vi.fn(),+ deleteChatSession: vi.fn(),+ listChatMessages: vi.fn(),+ getPendingChatTask: vi.fn(),+ listChatDraftRestores: vi.fn(),+ store: {+ appliedDraftRestoreIds: [] as string[],+ markDraftRestoreApplied: vi.fn(),+ forgetDraftRestoreApplied: vi.fn(),+ inputDrafts: {} as Record<string, string>,+ inputDraftAttachments: {} as Record<string, unknown[]>,+ setInputDraft: vi.fn(),+ setInputDraftAttachments: vi.fn(),+ pendingSendRestores: {} as Record<string, unknown[]>,+ enqueuePendingSendRestore: vi.fn(),+ dequeuePendingSendRestore: vi.fn(),+ },+}));++vi.mock("@multica/core/api", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/api")>(+ "@multica/core/api",+ );+ return {+ ...actual,+ api: {+ sendChatMessage: h.sendChatMessage,+ cancelTaskById: h.cancelTaskById,+ deleteChatSession: h.deleteChatSession,+ listChatMessages: h.listChatMessages,+ getPendingChatTask: h.getPendingChatTask,+ listChatDraftRestores: h.listChatDraftRestores,+ },+ };+});+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/chat", () => ({+ useChatStore: Object.assign((sel: (s: typeof h.store) => unknown) => sel(h.store), {+ getState: () => h.store,+ }),+}));+// `@multica/core/realtime` is deliberately NOT mocked: removeChatMessageFromCaches+// is the behaviour under test.++import { chatKeys } from "@multica/core/chat/queries";+import type { ChatMessage, ChatMessagesPage } from "@multica/core/types";+import { useBuilderSession } from "./use-builder-session";++const sessionId = "session-1";++function harness() {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(QueryClientProvider, { client: qc }, children);+ const { result } = renderHook(+ () => useBuilderSession({ sessionId, encodeInput: (text: string) => text }),+ { wrapper },+ );+ return { qc, result };+}++function pagedIds(qc: QueryClient) {+ return qc+ .getQueryData<InfiniteData<ChatMessagesPage>>(chatKeys.messagesPage(sessionId))+ ?.pages.flatMap((p) => p.messages.map((m) => m.id));+}++function flatIds(qc: QueryClient) {+ return qc+ .getQueryData<ChatMessage[]>(chatKeys.messages(sessionId))+ ?.map((m) => m.id);+}++beforeEach(() => {+ vi.clearAllMocks();+ h.listChatMessages.mockResolvedValue([]);+ h.getPendingChatTask.mockResolvedValue({ task_id: "task-1", status: "running" });+ h.listChatDraftRestores.mockResolvedValue({ restores: [] });+ h.sendChatMessage.mockResolvedValue({+ message_id: "msg-1",+ task_id: "task-1",+ created_at: "2026-08-07T00:00:00Z",+ });+ h.deleteChatSession.mockResolvedValue(undefined);+});++afterEach(cleanup);++// Regression (MUL-5711 review): the Builder send seeds BOTH message caches, so+// every Builder cleanup path has to clear both. `messagesPage` is+// staleTime: Infinity — a copy left behind there stays fresh forever, and any+// chat surface opening the same session reads it instead of the server.+describe("useBuilderSession cache cleanup", () => {+ it("seeds both caches on send", async () => {+ // Server truth once the send is accepted. The Builder holds an active+ // observer on the flat cache, so its reconciling refetch lands on top of the+ // seed within the test — the paged cache has no observer here and keeps the+ // seeded row until something reads it.+ h.listChatMessages.mockResolvedValue([+ {+ id: "msg-1",+ chat_session_id: sessionId,+ role: "user",+ content: "hello",+ task_id: "task-1",+ created_at: "2026-08-07T00:00:00Z",+ },+ ]);+ const { qc, result } = harness();++ await result.current.send("hello");++ await waitFor(() => expect(pagedIds(qc)).toEqual(["msg-1"]));+ await waitFor(() => expect(flatIds(qc)).toEqual(["msg-1"]));+ });++ it("drops both caches when the conversation is discarded", async () => {+ const { qc, result } = harness();++ await result.current.send("hello");+ await waitFor(() => expect(pagedIds(qc)).toEqual(["msg-1"]));++ await result.current.destroy();++ expect(qc.getQueryData(chatKeys.messages(sessionId))).toBeUndefined();+ expect(qc.getQueryData(chatKeys.messagesPage(sessionId))).toBeUndefined();+ });++ it("removes a restored prompt from both caches on stop", async () => {+ const { qc, result } = harness();+ h.cancelTaskById.mockResolvedValue({+ cancelled_chat_message: {+ chat_session_id: sessionId,+ message_id: "msg-1",+ content: "hello",+ restore_to_input: true,+ },+ });++ await result.current.send("hello");+ await waitFor(() => expect(pagedIds(qc)).toEqual(["msg-1"]));++ await result.current.stop();++ // The server deleted this prompt; neither cache may keep serving it.+ expect(pagedIds(qc) ?? []).toEqual([]);+ expect(flatIds(qc) ?? []).toEqual([]);+ });++ it("marks both caches stale when stop fails", async () => {+ const { qc, result } = harness();+ h.cancelTaskById.mockRejectedValue(new Error("nope"));++ await result.current.send("hello");+ await waitFor(() => expect(pagedIds(qc)).toEqual(["msg-1"]));++ // Clear the flag the send's own invalidate raised, so this asserts what+ // STOP did rather than what send did (setQueryData settles the query).+ qc.setQueryData(+ chatKeys.messagesPage(sessionId),+ qc.getQueryData(chatKeys.messagesPage(sessionId)),+ );+ expect(qc.getQueryState(chatKeys.messagesPage(sessionId))?.isInvalidated).toBe(false);++ await result.current.stop();++ // A failed cancel may still have landed server-side, so both caches have to+ // be re-read rather than left pinned by staleTime: Infinity.+ await waitFor(() => {+ expect(qc.getQueryState(chatKeys.messagesPage(sessionId))?.isInvalidated).toBe(true);+ });+ });+});diff --git a/packages/views/agents/create/use-builder-session.ts b/packages/views/agents/create/use-builder-session.tsindex 39b4cd312b..4fd4d966ef 100644--- a/packages/views/agents/create/use-builder-session.ts+++ b/packages/views/agents/create/use-builder-session.ts@@ -15,6 +15,8 @@ import {chatMessagesOptions,pendingChatTaskOptions,} from "@multica/core/chat/queries";+import { upsertChatMessageToCaches } from "@multica/core/chat/message-cache";+import { removeChatMessageFromCaches } from "@multica/core/realtime";import { useWorkspaceId } from "@multica/core/hooks";import type { ChatMessage } from "@multica/core/types";import { useAppForeground } from "../../common/use-app-foreground";@@ -137,6 +139,10 @@ export function useBuilderSession(options: {try {await api.deleteChatSession(sessionId);qc.removeQueries({ queryKey: chatKeys.messages(sessionId) });+ // The send seeds both caches, so both must be dropped here. Leaving the+ // paged one behind would keep a deleted session's transcript sitting+ // fresh forever — it is staleTime: Infinity, so no reader self-corrects.+ qc.removeQueries({ queryKey: chatKeys.messagesPage(sessionId) });qc.removeQueries({ queryKey: chatKeys.pendingTask(sessionId) });void invalidateDraftList();return true;@@ -233,22 +239,21 @@ export function useBuilderSession(options: {const encodedContent = options.encodeInput(text);const result = await api.sendChatMessage(sessionId, encodedContent);const createdAt = new Date().toISOString();- qc.setQueryData<ChatMessage[]>(- chatKeys.messages(sessionId),- (current = []) =>- current.some((message) => message.id === result.message_id)- ? current- : [- ...current,- {- id: result.message_id,- chat_session_id: sessionId,- role: "user",- content: encodedContent,- task_id: result.task_id,- created_at: createdAt,- },- ],+ // Same door as the chat surfaces (MUL-5711). This path used to write the+ // flat cache only, so a Builder send left the paged cache — which the+ // chat surfaces read for the same session — without the message.+ upsertChatMessageToCaches(+ qc,+ sessionId,+ {+ id: result.message_id,+ chat_session_id: sessionId,+ role: "user",+ content: encodedContent,+ task_id: result.task_id,+ created_at: createdAt,+ },+ { seedIfMissing: true },);qc.setQueryData(chatKeys.pendingTask(sessionId), {task_id: result.task_id,@@ -258,6 +263,10 @@ export function useBuilderSession(options: {// Accepted and rendered — release the composer before reconciling.commitInput?.();void qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });+ // Both caches are seeded above, so both need the authoritative refetch —+ // otherwise a seeded one-message page could outlive the send as the whole+ // history a later reader sees.+ void qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });void qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });// The first turn is what makes a brand-new conversation listable at// all, and every later one moves it to the top with a new preview.@@ -280,14 +289,22 @@ export function useBuilderSession(options: {try {const result = await api.cancelTaskById(taskId);const restored = result.cancelled_chat_message;- if (restored?.restore_to_input) {- setRestoreDraft({- id: restored.message_id,- content: decodeBuilderInput(restored.content),- });+ if (restored) {+ // The server deleted this prompt on restore, so drop it from both+ // caches before reconciling — same order as the chat surfaces'+ // cancelChatTask. Without it the row lingers until the refetch lands,+ // and in the paged cache it would linger for good.+ removeChatMessageFromCaches(qc, restored.chat_session_id, restored.message_id);+ if (restored.restore_to_input) {+ setRestoreDraft({+ id: restored.message_id,+ content: decodeBuilderInput(restored.content),+ });+ }}await Promise.all([qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) }),+ qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) }),qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) }),]);} catch (err) {@@ -296,6 +313,10 @@ export function useBuilderSession(options: {? err.message: t(($) => $.creation_studio.builder.stop_failed),);+ // The cancel may still have landed server-side, so re-read the messages+ // too rather than only the pending marker.+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });+ qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });}};diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex c074eeb0b6..e0392400aa 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -1,7 +1,7 @@"use client";import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { useInfiniteQuery, useQuery, useQueryClient, type InfiniteData } from "@tanstack/react-query";+import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";import { motion } from "motion/react";import { Minus, Maximize2, Minimize2, ChevronDown, Plus, Check, Archive, Pencil, Loader2, Square } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";@@ -54,6 +54,7 @@ import {useUpdateChatSession,} from "@multica/core/chat/mutations";import { useChatStore } from "@multica/core/chat";+import { upsertChatMessageToCaches } from "@multica/core/chat/message-cache";import { chatQuickActionsPendingOptions } from "@multica/core/chat/queries";import { useQuickActionsPendingTimeout } from "@multica/core/chat/use-quick-actions-pending-timeout";import { useQuickActionsFailureToast } from "./use-quick-actions-failure-toast";@@ -78,44 +79,13 @@ import {} from "./use-chat-controller";import { useChatProjectContextSupport } from "./use-chat-project-context-support";import { createLogger } from "@multica/core/logger";-import type { Agent, Attachment, ChatMessage, ChatMessagesPage, ChatSession, PendingChatTasksResponse } from "@multica/core/types";+import type { Agent, Attachment, ChatMessage, ChatSession, PendingChatTasksResponse } from "@multica/core/types";import { useT } from "../../i18n";const uiLogger = createLogger("chat.ui");const apiLogger = createLogger("chat.api");const CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX = 1_000_000;-function appendChatMessageToLatestPageCache(- qc: ReturnType<typeof useQueryClient>,- sessionId: string,- message: ChatMessage,-) {- qc.setQueryData<InfiniteData<ChatMessagesPage>>(- chatKeys.messagesPage(sessionId),- (old) => {- if (!old) {- return {- pages: [{- messages: [message],- limit: 50,- has_more: false,- next_cursor: null,- }],- pageParams: [null],- };- }- if (old.pages.some((page) => page.messages.some((m) => m.id === message.id))) {- return old;- }- return {- ...old,- pages: old.pages.map((page, index) =>- index === 0 ? { ...page, messages: [...page.messages, message] } : page,- ),- };- },- );-}export function ChatWindow() {const { t } = useT("chat");@@ -525,11 +495,11 @@ export function ChatWindow() {created_at: result.created_at,attachments: draftAttachments,};- appendChatMessageToLatestPageCache(qc, sessionId, sent);- qc.setQueryData<ChatMessage[]>(- chatKeys.messages(sessionId),- (old) => (old ? [...old, sent] : [sent]),- );+ // Single door into the message caches (MUL-5711): idempotent by id, so+ // this row and the chat:message echo of the same send converge in either+ // arrival order, and this richer row (it carries the draft attachments)+ // is never downgraded by the echo, which has no attachments field.+ upsertChatMessageToCaches(qc, sessionId, sent, { seedIfMissing: true });seedAcceptedPendingTask(qc, sessionId, {task_id: result.task_id,created_at: result.created_at,diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex 8a57ac1c68..8e78e21201 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -5,7 +5,6 @@ import {useInfiniteQuery,useQuery,useQueryClient,- type InfiniteData,} from "@tanstack/react-query";import { toast } from "sonner";import { useWorkspaceId } from "@multica/core/hooks";@@ -34,6 +33,7 @@ import {useSetChatSessionArchived,} from "@multica/core/chat/mutations";import { useChatStore } from "@multica/core/chat";+import { upsertChatMessageToCaches } from "@multica/core/chat/message-cache";import {enqueuePendingChatTask,hideQueuedChatMessages,@@ -46,7 +46,6 @@ import type {Agent,Attachment,ChatMessage,- ChatMessagesPage,ChatPendingTask,} from "@multica/core/types";import { useT } from "../../i18n";@@ -188,37 +187,6 @@ export function seedAcceptedPendingTask(const CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX = 1_000_000;-function appendChatMessageToLatestPageCache(- qc: ReturnType<typeof useQueryClient>,- sessionId: string,- message: ChatMessage,-) {- qc.setQueryData<InfiniteData<ChatMessagesPage>>(- chatKeys.messagesPage(sessionId),- (old) => {- if (!old) {- return {- pages: [{- messages: [message],- limit: 50,- has_more: false,- next_cursor: null,- }],- pageParams: [null],- };- }- if (old.pages.some((page) => page.messages.some((m) => m.id === message.id))) {- return old;- }- return {- ...old,- pages: old.pages.map((page, index) =>- index === 0 ? { ...page, messages: [...page.messages, message] } : page,- ),- };- },- );-}/*** Layout-agnostic chat controller. Holds every piece of chat conversation@@ -592,11 +560,11 @@ export function useChatController(opts?: { isActive?: boolean }) {created_at: result.created_at,attachments: draftAttachments,};- appendChatMessageToLatestPageCache(qc, sessionId, sent);- qc.setQueryData<ChatMessage[]>(- chatKeys.messages(sessionId),- (old) => (old ? [...old, sent] : [sent]),- );+ // Single door into the message caches (MUL-5711): idempotent by id, so+ // this row and the chat:message echo of the same send converge in either+ // arrival order, and this richer row (it carries the draft attachments)+ // is never downgraded by the echo, which has no attachments field.+ upsertChatMessageToCaches(qc, sessionId, sent, { seedIfMissing: true });seedAcceptedPendingTask(qc, sessionId, {task_id: result.task_id,created_at: result.created_at,