Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
perf(realtime): stop the task:message fanout from flooding every client (MUL-6396) (#7227)
Bohan Jiang0c0baf050552
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.tsindex 4986501766..91176ca0d0 100644--- a/apps/mobile/data/realtime/chat-ws-updaters.ts+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts@@ -326,4 +326,21 @@ export function appendTaskMessage(return [...old, payload].sort((a, b) => a.seq - b.seq);},);++ // The server clips oversized tool input/output out of the realtime copy so+ // one big Write is not broadcast to every client (MUL-6396). The full row is+ // only in the DB, and `taskMessagesOptions` is staleTime:Infinity — without+ // this the clipped text would be pinned forever. Invalidating refetches for+ // whoever is mounted and is a no-op otherwise.+ //+ // Not reachable today, and kept deliberately: `use-chat-session-realtime`+ // gates `task:message` on `chat_session_id`, which the server's+ // TaskMessagePayload does not carry, so mobile currently appends nothing at+ // all (a pre-existing delivery gap, tracked separately). Whichever side of+ // that is fixed first, this branch must already be here — the clipping is+ // exactly what a client learning to receive these frames would otherwise+ // cache permanently.+ if (payload.truncated) {+ qc.invalidateQueries({ queryKey: chatKeys.taskMessages(payload.task_id) });+ }}diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.tsindex a64a02c20b..4880f54585 100644--- a/apps/mobile/data/schemas.ts+++ b/apps/mobile/data/schemas.ts@@ -350,6 +350,9 @@ export const TaskMessagePayloadSchema: z.ZodType<TaskMessagePayload> = z.object(input: z.record(z.string(), z.unknown()).optional(),output: z.string().optional(),created_at: z.string().optional(),+ // Set on the WS copy when the server clipped input/output for the fanout+ // (MUL-6396); never present on the REST list response.+ truncated: z.boolean().optional(),}).loose();export const TaskMessageListSchema = z.array(TaskMessagePayloadSchema).default([]);diff --git a/packages/core/chat/queries.test.ts b/packages/core/chat/queries.test.tsindex 68b08ef1ed..e6bd2d0af1 100644--- a/packages/core/chat/queries.test.ts+++ b/packages/core/chat/queries.test.ts@@ -8,6 +8,7 @@ import {mergeTaskMessagesBySeq,sortChatSessions,taskMessagesOptions,+ unionTaskMessagesBySeq,} from "./queries";const msg = (seq: number): TaskMessagePayload => ({@@ -34,6 +35,44 @@ describe("taskMessagesOptions", () => {});});+describe("unionTaskMessagesBySeq", () => {+ it("keeps seqs the authoritative list never mentioned", () => {+ // A REST response snapshotted before seq 3 was persisted must not erase it.+ const united = unionTaskMessagesBySeq([msg(1), msg(3)], [msg(1), msg(2)]);++ expect(united.map((m) => m.seq)).toEqual([1, 2, 3]);+ });++ it("lets the authoritative row win on conflict", () => {+ const clipped = { ...msg(1), content: "clip", truncated: true };+ const persisted = { ...msg(1), content: "full" };++ const united = unionTaskMessagesBySeq([clipped], [persisted]);++ expect(united).toEqual([persisted]);+ });++ it("preserves the base reference when nothing differs", () => {+ // Identity is what keeps a duplicate event from re-rendering every+ // subscriber — AssistantMessage memoizes its timeline on this array.+ const base = [msg(1), msg(2)];++ expect(unionTaskMessagesBySeq(base, [base[0]!, base[1]!])).toBe(base);+ expect(unionTaskMessagesBySeq(base, [])).toBe(base);+ });++ it("sorts by seq regardless of arrival order", () => {+ expect(unionTaskMessagesBySeq([msg(5)], [msg(3), msg(9)]).map((m) => m.seq))+ .toEqual([3, 5, 9]);+ });++ it("handles an empty or absent base", () => {+ expect(unionTaskMessagesBySeq(undefined, [msg(2), msg(1)]).map((m) => m.seq))+ .toEqual([1, 2]);+ expect(unionTaskMessagesBySeq([], [msg(1)]).map((m) => m.seq)).toEqual([1]);+ });+});+describe("mergeTaskMessagesBySeq", () => {it("backfills missing seqs and keeps the list seq-ordered", () => {const existing = [msg(1), msg(3)];diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.tsindex 553f559e4f..cea3776015 100644--- a/packages/core/chat/queries.ts+++ b/packages/core/chat/queries.ts@@ -1,4 +1,4 @@-import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";+import { infiniteQueryOptions, queryOptions, type QueryClient } from "@tanstack/react-query";import { api } from "../api";import type { TaskMessagePayload } from "../types/events";import type {@@ -201,6 +201,15 @@ export function taskMessagesOptions(taskId: string) {queryFn: () => api.listTaskMessages(taskId),enabled: isTaskMessageTaskId(taskId),staleTime: Infinity,+ // Every write to this cache — this fetch, a backfill, or a realtime batch —+ // folds into what is already there instead of replacing it. Without this a+ // response that resolves after a live frame was written would drop that+ // seq, and staleTime:Infinity means nothing would ever fetch it again.+ structuralSharing: (prev, next) =>+ unionTaskMessagesBySeq(+ prev as TaskMessagePayload[] | undefined,+ next as TaskMessagePayload[],+ ),});}@@ -227,6 +236,99 @@ export function mergeTaskMessagesBySeq(return [...existing, ...fresh].sort((a, b) => a.seq - b.seq);}+/**+ * Union two task-message lists by seq, with `authoritative` winning on conflict.+ *+ * This is the rule every write to the `["task-messages", taskId]` cache goes+ * through, wired in as `structuralSharing` on the query itself so a fetch+ * result cannot replace the array wholesale.+ *+ * That matters because a normal query response and the realtime stream race:+ * the timeline is fetched on first open, and any frame that arrives while that+ * request is in flight is written to the cache before the response lands. A+ * plain replace would drop those seqs, and `staleTime: Infinity` means nothing+ * would ever refetch them — the gap would survive until a reload.+ *+ * Server data wins on conflict because the persisted row is the authority: a+ * broadcast copy may have been clipped for the fanout, and the fetched row+ * never is. Rows the response did not mention are kept rather than deleted —+ * a response snapshotted before a seq was persisted must not erase it.+ *+ * The `base` reference is returned unchanged when nothing differs, so an event+ * that adds nothing does not re-render every subscriber.+ */+export function unionTaskMessagesBySeq(+ base: readonly TaskMessagePayload[] | undefined,+ authoritative: readonly TaskMessagePayload[],+): TaskMessagePayload[] {+ if (!base || base.length === 0) {+ return [...authoritative].sort((a, b) => a.seq - b.seq);+ }++ const bySeq = new Map(base.map((m) => [m.seq, m]));+ let changed = false;+ for (const msg of authoritative) {+ if (bySeq.get(msg.seq) !== msg) {+ bySeq.set(msg.seq, msg);+ changed = true;+ }+ }+ if (!changed) return base as TaskMessagePayload[];+ return [...bySeq.values()].sort((a, b) => a.seq - b.seq);+}++/**+ * True when this client holds a timeline cache entry for `taskId` — i.e. the+ * task was opened at some point and has not been garbage-collected since.+ *+ * Deliberately NOT "a view is mounted right now". Observer count would be a+ * tighter bound but an unsafe one: with `staleTime: Infinity` a task that+ * briefly drops to zero observers (an unmount/remount while navigating) would+ * discard frames, and the remount would read the surviving cache as fresh and+ * never fetch them back. Entry presence has no such gap — either the entry is+ * there and keeps accumulating, or it is gone and the next open fetches the+ * whole timeline. The cost is a bounded tail: writes do not postpone the GC+ * timer, so an entry outlives its last viewer by at most one `gcTime`.+ *+ * The realtime layer uses this to decide whether a `task:message` frame is+ * worth caching. Every client in the workspace receives every run's frames,+ * but only a handful of runs are ever opened; without this gate every client+ * accumulates the transcript of runs its user will never look at (MUL-6396).+ *+ * Presence, not data: mounting a `useQuery` registers the entry before the+ * fetch resolves, so a frame that lands mid-backfill is still kept. Dropping+ * a frame for an unregistered task is safe — the row is persisted before it+ * is broadcast, so whoever opens the task next fetches it from the server.+ */+export function isTaskMessageTimelineHeld(+ qc: QueryClient,+ taskId: string,+): boolean {+ return qc.getQueryCache().find({ queryKey: chatKeys.taskMessages(taskId) }) !== undefined;+}++/**+ * Refetch a task's full timeline and fold it into the cache.+ *+ * Used when a broadcast frame arrived `truncated`: the live copy carries+ * clipped tool input/output and the full text exists only in the DB. Writing+ * the fetched rows straight in is enough — `unionTaskMessagesBySeq`, installed+ * as the query's `structuralSharing`, is what makes the fetched row replace the+ * clipped one while keeping any seq the response had not yet seen.+ */+export async function backfillTaskMessages(+ qc: QueryClient,+ taskId: string,+): Promise<void> {+ if (!isTaskMessageTaskId(taskId)) return;+ const msgs = await api.listTaskMessages(taskId);+ // The entry can be collected while this request is open. Writing anyway+ // would rebuild a timeline nothing is watching, re-arming another gcTime of+ // accumulation for a task the user has already closed.+ if (!isTaskMessageTimelineHeld(qc, taskId)) return;+ qc.setQueryData<TaskMessagePayload[]>(chatKeys.taskMessages(taskId), msgs);+}+/*** Aggregate of in-flight chat tasks for the current user in this workspace.* Drives the FAB "running" indicator while the chat window is minimised —diff --git a/packages/core/realtime/use-realtime-sync-task-messages.test.tsx b/packages/core/realtime/use-realtime-sync-task-messages.test.tsxnew file mode 100644index 0000000000..8739a9a55e--- /dev/null+++ b/packages/core/realtime/use-realtime-sync-task-messages.test.tsx@@ -0,0 +1,347 @@+/**+ * @vitest-environment jsdom+ */+import { QueryClient, QueryClientProvider, QueryObserver } from "@tanstack/react-query";+import { renderHook } from "@testing-library/react";+import type { ReactNode } from "react";+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import { setApiInstance } from "../api";+import type { ApiClient } from "../api/client";+import { backfillTaskMessages, chatKeys, taskMessagesOptions } from "../chat/queries";+import type { TaskMessagePayload } from "../types/events";+import type { WSClient } from "../api/ws-client";+import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";++vi.mock("../platform/workspace-storage", () => ({+ getCurrentWsId: () => "ws-1",+ getCurrentSlug: () => "test-ws",+ createWorkspaceAwareStorage: (adapter: unknown) => adapter,+ registerForWorkspaceRehydration: () => {},+}));++vi.mock("../paths", () => ({+ useHasOnboarded: () => true,+ resolvePostAuthDestination: () => "/",+}));++const HELD_TASK = "11111111-1111-4111-8111-111111111111";+const UNHELD_TASK = "22222222-2222-4222-8222-222222222222";+const FLUSH_MS = 100;++type Handlers = Map<string, (payload: unknown) => void>;++function createMockWs(handlers: Handlers): WSClient {+ return {+ on: vi.fn((event: string, handler: (payload: unknown) => void) => {+ handlers.set(event, handler);+ return () => handlers.delete(event);+ }),+ onAny: vi.fn(() => () => {}),+ onReconnect: vi.fn(() => () => {}),+ } as unknown as WSClient;+}++function createStores(): RealtimeSyncStores {+ return {+ authStore: Object.assign(() => ({}), {+ getState: () => ({ user: { id: "u1" } }),+ subscribe: () => () => {},+ setState: () => {},+ destroy: () => {},+ }),+ } as unknown as RealtimeSyncStores;+}++function createWrapper(qc: QueryClient) {+ return function Wrapper({ children }: { children: ReactNode }) {+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;+ };+}++function msg(taskId: string, seq: number, extra: Partial<TaskMessagePayload> = {}): TaskMessagePayload {+ return {+ task_id: taskId,+ issue_id: "issue-1",+ seq,+ type: "tool_use",+ ...extra,+ };+}++function cached(qc: QueryClient, taskId: string) {+ return qc.getQueryData<TaskMessagePayload[]>(chatKeys.taskMessages(taskId));+}++describe("useRealtimeSync — task:message fanout guards (MUL-6396)", () => {+ let qc: QueryClient;+ let handlers: Handlers;+ let listTaskMessages: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ vi.useFakeTimers();+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ handlers = new Map();+ listTaskMessages = vi.fn(async () => [] as TaskMessagePayload[]);+ setApiInstance({ listTaskMessages } as unknown as ApiClient);+ });++ afterEach(() => {+ vi.useRealTimers();+ setApiInstance(undefined as unknown as ApiClient);+ });++ function mount() {+ renderHook(() => useRealtimeSync(createMockWs(handlers), createStores()), {+ wrapper: createWrapper(qc),+ });+ const handler = handlers.get("task:message");+ if (!handler) throw new Error("task:message handler was not registered");+ return handler;+ }++ /** Simulates a mounted view rendering this task's timeline. */+ function holdTimeline(taskId: string) {+ const observer = new QueryObserver(qc, taskMessagesOptions(taskId));+ const unsubscribe = observer.subscribe(() => {});+ return unsubscribe;+ }++ it("drops frames for a task no mounted view is rendering", () => {+ const handler = mount();++ handler(msg(UNHELD_TASK, 1));+ handler(msg(UNHELD_TASK, 2));+ vi.advanceTimersByTime(FLUSH_MS * 2);++ // The whole point: a run the user never opened must not build a cache+ // entry, however long it streams.+ expect(cached(qc, UNHELD_TASK)).toBeUndefined();+ expect(qc.getQueryCache().find({ queryKey: chatKeys.taskMessages(UNHELD_TASK) })).toBeUndefined();+ });++ it("keeps frames for a task a mounted view holds, even before its fetch resolves", () => {+ const handler = mount();+ const release = holdTimeline(HELD_TASK);++ // Mounting registers the cache entry immediately; the queryFn above has+ // not resolved yet. A frame landing in that window must still be kept.+ handler(msg(HELD_TASK, 1));+ vi.advanceTimersByTime(FLUSH_MS);++ expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1]);+ release();+ });++ it("coalesces a burst into a single cache write", () => {+ const handler = mount();+ const release = holdTimeline(HELD_TASK);+ const writes = vi.spyOn(qc, "setQueryData");++ for (let seq = 1; seq <= 5; seq++) handler(msg(HELD_TASK, seq));+ // Nothing is written until the window closes.+ expect(writes).not.toHaveBeenCalled();++ vi.advanceTimersByTime(FLUSH_MS);++ expect(writes).toHaveBeenCalledTimes(1);+ expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1, 2, 3, 4, 5]);+ release();+ });++ it("flushes on a fixed window rather than being starved by a continuous stream", () => {+ const handler = mount();+ const release = holdTimeline(HELD_TASK);++ // A frame every 50ms: a resetting debounce would never fire.+ for (let seq = 1; seq <= 4; seq++) {+ handler(msg(HELD_TASK, seq));+ vi.advanceTimersByTime(FLUSH_MS / 2);+ }++ expect(cached(qc, HELD_TASK)?.length).toBeGreaterThan(0);+ release();+ });++ it("backfills the full row once per flush when the broadcast copy was truncated", async () => {+ // The mounted view's own fetch finds nothing yet, so the ONLY path to the+ // full text is the backfill this test is about.+ const handler = mount();+ const release = holdTimeline(HELD_TASK);+ // Let the view's own fetch settle before touching the mock: a resolving+ // queryFn REPLACES the cache, so an in-flight one would clobber the frames.+ await vi.waitFor(() => expect(cached(qc, HELD_TASK)).toEqual([]));+ listTaskMessages.mockClear();+ listTaskMessages.mockResolvedValue([+ msg(HELD_TASK, 1, { input: { content: "full body" } }),+ msg(HELD_TASK, 2, { input: { content: "full body 2" } }),+ ]);++ handler(msg(HELD_TASK, 1, { input: { content: "clip" }, truncated: true }));+ handler(msg(HELD_TASK, 2, { input: { content: "clip" }, truncated: true }));+ vi.advanceTimersByTime(FLUSH_MS);++ // Two truncated frames in one window cost one refetch, not two.+ expect(listTaskMessages).toHaveBeenCalledTimes(1);+ // The clipped copy is rendered immediately — the backfill is a repair pass,+ // not a gate on showing the row at all.+ expect(cached(qc, HELD_TASK)?.[0]?.input).toEqual({ content: "clip" });++ await vi.waitFor(() => {+ // mergeTaskMessagesBySeq lets the cached entry win on conflict, so the+ // backfill has to evict the clipped rows or they would be pinned forever.+ expect(cached(qc, HELD_TASK)?.map((m) => m.input)).toEqual([+ { content: "full body" },+ { content: "full body 2" },+ ]);+ expect(cached(qc, HELD_TASK)?.some((m) => m.truncated)).toBe(false);+ });+ release();+ });++ it("leaves a clipped row that the backfill response did not cover", async () => {+ const handler = mount();+ const release = holdTimeline(HELD_TASK);+ await vi.waitFor(() => expect(cached(qc, HELD_TASK)).toEqual([]));+ listTaskMessages.mockClear();+ // A response snapshotted before seq 2 was persisted — the racing backfill+ // of a later flush must not delete a row it simply has not seen yet.+ listTaskMessages.mockResolvedValue([msg(HELD_TASK, 1, { input: { content: "full body" } })]);++ handler(msg(HELD_TASK, 1, { input: { content: "clip" }, truncated: true }));+ handler(msg(HELD_TASK, 2, { input: { content: "clip 2" }, truncated: true }));+ vi.advanceTimersByTime(FLUSH_MS);++ await vi.waitFor(() => {+ expect(cached(qc, HELD_TASK)?.[0]?.input).toEqual({ content: "full body" });+ });+ // seq 2 survives, still clipped, waiting for the next backfill.+ expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1, 2]);+ expect(cached(qc, HELD_TASK)?.[1]?.input).toEqual({ content: "clip 2" });+ release();+ });++ it("keeps live frames that landed while the first fetch was still in flight", async () => {+ // The regression P0-a newly exposes. Before it, the cache was pre-seeded by+ // the WS handler, so opening a live task found fresh data (staleTime:+ // Infinity) and never fetched. Now first open DOES fetch, and a response+ // that resolves after a live frame was written must not drop that seq —+ // nothing would ever refetch it.+ let resolveFetch: (msgs: TaskMessagePayload[]) => void = () => {};+ listTaskMessages.mockImplementation(+ () => new Promise<TaskMessagePayload[]>((resolve) => { resolveFetch = resolve; }),+ );++ const handler = mount();+ const release = holdTimeline(HELD_TASK);+ await vi.waitFor(() => expect(listTaskMessages).toHaveBeenCalled());++ // Live frame arrives and flushes while the request is still open.+ handler(msg(HELD_TASK, 2, { content: "live" }));+ vi.advanceTimersByTime(FLUSH_MS);+ expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([2]);++ // The response was snapshotted before seq 2 was persisted.+ resolveFetch([msg(HELD_TASK, 1, { content: "persisted" })]);++ await vi.waitFor(() => {+ expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1, 2]);+ });+ expect(cached(qc, HELD_TASK)?.[1]?.content).toBe("live");+ release();+ });++ it("lets the fetched row win over a clipped one for the same seq", async () => {+ const handler = mount();+ const release = holdTimeline(HELD_TASK);+ await vi.waitFor(() => expect(cached(qc, HELD_TASK)).toEqual([]));++ handler(msg(HELD_TASK, 1, { input: { content: "clip" }, truncated: true }));+ vi.advanceTimersByTime(FLUSH_MS);+ // Server data is authoritative: the clipped copy must not survive.+ expect(cached(qc, HELD_TASK)?.[0]?.truncated).toBe(true);++ listTaskMessages.mockResolvedValue([msg(HELD_TASK, 1, { input: { content: "full" } })]);+ await backfillTaskMessages(qc, HELD_TASK);++ expect(cached(qc, HELD_TASK)?.[0]?.input).toEqual({ content: "full" });+ expect(cached(qc, HELD_TASK)?.[0]?.truncated).toBeUndefined();+ release();+ });++ it("drops a batch whose timeline was garbage-collected during the flush window", async () => {+ // Production shape: app-wide staleTime Infinity, and a gcTime short enough+ // to land inside the 100ms batching window. Writes do NOT postpone the GC+ // timer (query-core arms it when the last observer leaves), so a run that+ // keeps streaming after its transcript is closed reaches this every time.+ qc = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: 50 } },+ });+ listTaskMessages.mockResolvedValue([msg(HELD_TASK, 1, { content: "history" })]);++ const handler = mount();+ const release = holdTimeline(HELD_TASK);+ await vi.waitFor(() => expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1]));++ // Frame batched while the entry is still held, then the viewer closes.+ handler(msg(HELD_TASK, 2, { content: "live" }));+ release();++ // GC lands first (50ms), flush second (100ms).+ vi.advanceTimersByTime(60);+ expect(qc.getQueryCache().find({ queryKey: chatKeys.taskMessages(HELD_TASK) })).toBeUndefined();+ vi.advanceTimersByTime(60);++ // Writing would have rebuilt the entry holding ONLY seq 2. Under+ // staleTime: Infinity the next open would read that stub as fresh and+ // never fetch, losing seq 1 until the window is reloaded.+ expect(qc.getQueryCache().find({ queryKey: chatKeys.taskMessages(HELD_TASK) })).toBeUndefined();++ // And the history is still recoverable: reopening fetches the full timeline.+ listTaskMessages.mockClear();+ const reopen = holdTimeline(HELD_TASK);+ await vi.waitFor(() => expect(listTaskMessages).toHaveBeenCalledTimes(1));+ await vi.waitFor(() => expect(cached(qc, HELD_TASK)?.map((m) => m.seq)).toEqual([1]));+ reopen();+ });++ it("does not backfill a timeline that was collected while the batch waited", async () => {+ qc = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: 50 } },+ });+ const handler = mount();+ const release = holdTimeline(HELD_TASK);+ await vi.waitFor(() => expect(cached(qc, HELD_TASK)).toEqual([]));+ listTaskMessages.mockClear();++ handler(msg(HELD_TASK, 1, { input: { content: "clip" }, truncated: true }));+ release();+ vi.advanceTimersByTime(120);++ // The batch was dropped, so its repair fetch must be dropped with it —+ // otherwise the response would rebuild the very entry GC just removed.+ expect(listTaskMessages).not.toHaveBeenCalled();+ expect(qc.getQueryCache().find({ queryKey: chatKeys.taskMessages(HELD_TASK) })).toBeUndefined();+ });++ it("does not rebuild a collected timeline when a backfill response lands late", async () => {+ // The same invariant on the async side: the entry can go away while the+ // repair request is in flight.+ listTaskMessages.mockResolvedValue([msg(HELD_TASK, 1)]);++ await backfillTaskMessages(qc, HELD_TASK);++ expect(qc.getQueryCache().find({ queryKey: chatKeys.taskMessages(HELD_TASK) })).toBeUndefined();+ });++ it("does not refetch when nothing was truncated", () => {+ const handler = mount();+ const release = holdTimeline(HELD_TASK);+ listTaskMessages.mockClear();++ handler(msg(HELD_TASK, 1));+ vi.advanceTimersByTime(FLUSH_MS);++ expect(listTaskMessages).not.toHaveBeenCalled();+ release();+ });+});diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 5189e93324..402ba760fe 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -56,7 +56,9 @@ import {} from "../platform/system-notification";import type { Workspace } from "../types/workspace";import {+ backfillTaskMessages,chatKeys,+ isTaskMessageTimelineHeld,mergeTaskMessagesBySeq,sortChatSessions,QUICK_ACTIONS_PENDING_TIMEOUT_MS,@@ -118,6 +120,18 @@ import type {const chatWsLogger = createLogger("chat.ws");+/**+ * Window over which incoming `task:message` frames are batched into a single+ * timeline cache write (MUL-6396).+ *+ * A fixed window, armed on the first frame and not reset by later ones, so a+ * sustained stream still lands every 100ms rather than being deferred until+ * the stream pauses. Short enough that streamed text still reads as live;+ * long enough that a run emitting several frames per second costs one merge+ * and one render instead of one per frame.+ */+const TASK_MESSAGE_FLUSH_MS = 100;+const logger = createLogger("realtime-sync");export function invalidateChatMessageQueries(@@ -1291,12 +1305,83 @@ export function useRealtimeSync(// task:completed / task:failed invalidate messages + pending-task so the// DB remains authoritative.+ // Two guards stand between the workspace-wide message firehose and the+ // renderer (MUL-6396). `task:message` is broadcast to EVERY client for+ // EVERY run in the workspace, but only the handful of runs a user actually+ // opens is ever rendered:+ //+ // 1. Frames are kept only for a task this client already holds a timeline+ // entry for — opened at some point, and not yet garbage-collected. The+ // old `(old = [])` default built that entry on first sight instead, so+ // every client accumulated the transcript of every run its user would+ // never open, unbounded tool input included.+ // 2. Frames that survive that gate are coalesced into one cache write per+ // window, so a burst costs one merge and one render instead of N.+ //+ // The entry can be collected between the two, which is why the flush+ // re-checks rather than trusting the gate — see flushTaskMessages.+ const taskMessageBatches = new Map<string, TaskMessagePayload[]>();+ const truncatedTaskIds = new Set<string>();+ let taskMessageFlushTimer: ReturnType<typeof setTimeout> | null = null;++ const flushTaskMessages = () => {+ taskMessageFlushTimer = null;++ for (const [taskId, batch] of taskMessageBatches) {+ // Re-check, because holding was last verified up to a window ago and+ // `setQueryData` does NOT postpone garbage collection — query-core arms+ // that timer when the last observer leaves and never again on write.+ // Closing a transcript while its run keeps streaming therefore has the+ // entry disappear mid-window, and writing then REBUILDS it holding only+ // this batch. With the app-wide `staleTime: Infinity` the next open+ // would read that stub as fresh and never fetch, so everything before+ // it would be missing until the window is reloaded. Dropping the batch+ // instead costs nothing: the rows are persisted, so the next open+ // fetches the whole timeline.+ if (!isTaskMessageTimelineHeld(qc, taskId)) {+ truncatedTaskIds.delete(taskId);+ continue;+ }+ qc.setQueryData<TaskMessagePayload[]>(+ chatKeys.taskMessages(taskId),+ (old = []) => mergeTaskMessagesBySeq(old, batch),+ );+ }+ taskMessageBatches.clear();++ // A truncated frame carries clipped tool input/output — the full row+ // lives only in the DB, and `taskMessagesOptions` is staleTime:Infinity,+ // so nothing would ever replace the clipped copy on its own. Backfill+ // once per flush, not once per frame: a run writing several large files+ // in a row would otherwise queue a fetch for each one.+ for (const taskId of truncatedTaskIds) {+ void backfillTaskMessages(qc, taskId).catch((err: unknown) => {+ chatWsLogger.debug("task:message backfill failed", {+ task_id: taskId,+ error: err,+ });+ });+ }+ truncatedTaskIds.clear();+ };+const unsubTaskMessage = ws.on("task:message", (p) => {const payload = p as TaskMessagePayload;- qc.setQueryData<TaskMessagePayload[]>(- chatKeys.taskMessages(payload.task_id),- (old = []) => mergeTaskMessagesBySeq(old, [payload]),- );+ // Cheap Map lookup, and it runs before anything allocates — this is the+ // hot path for every run in the workspace, not just the visible ones.+ if (!isTaskMessageTimelineHeld(qc, payload.task_id)) return;++ const batch = taskMessageBatches.get(payload.task_id);+ if (batch) batch.push(payload);+ else taskMessageBatches.set(payload.task_id, [payload]);+ if (payload.truncated) truncatedTaskIds.add(payload.task_id);++ // Fixed window, not a resetting debounce: a continuous stream must still+ // flush every TASK_MESSAGE_FLUSH_MS instead of being starved until a gap.+ if (!taskMessageFlushTimer) {+ taskMessageFlushTimer = setTimeout(flushTaskMessages, TASK_MESSAGE_FLUSH_MS);+ }+chatWsLogger.debug("task:message (global)", {task_id: payload.task_id,seq: payload.seq,@@ -1638,6 +1723,7 @@ export function useRealtimeSync(unsubChatSessionRead();unsubChatSessionDeleted();unsubChatSessionUpdated();+ if (taskMessageFlushTimer) clearTimeout(taskMessageFlushTimer);if (aggregateRefreshTimer) clearTimeout(aggregateRefreshTimer);timers.forEach(clearTimeout);timers.clear();diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex 4da693022d..48bf7a9fb2 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -277,6 +277,13 @@ export interface TaskMessagePayload {input?: Record<string, unknown>;output?: string;created_at?: string;+ /**+ * Set when the server clipped `input` / `output` for the realtime fanout+ * (MUL-6396). The persisted row is untouched — a client that needs the full+ * text refetches it from the task-messages endpoint. Never set on REST+ * responses.+ */+ truncated?: boolean;}export interface TaskQueuedPayload {diff --git a/packages/views/common/task-transcript/transcript-button.tsx b/packages/views/common/task-transcript/transcript-button.tsxindex 535f4513ac..58f13fdd9a 100644--- a/packages/views/common/task-transcript/transcript-button.tsx+++ b/packages/views/common/task-transcript/transcript-button.tsx@@ -13,7 +13,6 @@ import { api } from "@multica/core/api";import {chatKeys,isTaskMessageTaskId,- mergeTaskMessagesBySeq,taskMessagesOptions,} from "@multica/core/chat/queries";import type { AgentTask } from "@multica/core/types/agent";@@ -229,7 +228,8 @@ function LiveTranscriptDialog({// `taskMessagesOptions` is `staleTime: Infinity`, so a plain subscription// never refetches — a WS reconnect gap (or the final tail of messages a// completed issue task never re-broadcasts) would otherwise leave a hole.- // Merge by seq so the fetch and any concurrent WS append both survive.+ // The query's `structuralSharing` folds this response into whatever the+ // realtime stream has already written, so neither side loses a seq.useEffect(() => {if (!isTaskMessageTaskId(task.id)) return;let cancelled = false;@@ -239,7 +239,7 @@ function LiveTranscriptDialog({if (cancelled) return;queryClient.setQueryData<TaskMessagePayload[]>(chatKeys.taskMessages(task.id),- (old = []) => mergeTaskMessagesBySeq(old, msgs),+ msgs,);}).catch((err) => {diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex d9a9b18ae4..b8e848ae94 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -10,10 +10,12 @@ import ("fmt""log/slog""net/http"+ "os""sort""strconv""strings""time"+ "unicode/utf8""github.com/go-chi/chi/v5""github.com/google/uuid"@@ -4438,7 +4440,8 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {if workspaceID != "" {h.publishTask(protocol.EventTaskMessage, workspaceID, "system", "", taskID,- taskMessageToPayload(created, taskID, uuidToString(task.IssueID)))+ truncateTaskMessageForBroadcast(+ taskMessageToPayload(created, taskID, uuidToString(task.IssueID))))}}@@ -4552,6 +4555,152 @@ func taskMessageToPayload(m db.TaskMessage, taskID, issueID string) protocol.Tas}}+// taskMessageBroadcastClipEnv gates the clipping below. It is OFF by default,+// and must stay off until clients that understand `truncated` have saturated.+//+// Clipping is not an additive field a client can ignore: it changes the meaning+// of `input` / `output`, which every existing client already consumes. A client+// built before this PR writes the clipped copy into a `staleTime: Infinity`+// cache and never refetches, so its execution log would stay incomplete until+// the window is reloaded. The client half of this change (the `truncated`+// reader) ships first; flipping this env var is the second step, once installed+// builds have caught up.+//+// Routing by connection capability instead would be the principled fix, but the+// hub does not retain the `client_version` it is handed at upgrade, and frames+// cross nodes through the Redis relay as already-serialized bytes — so it needs+// the same protocol work that per-task scope routing is waiting on+// (server/cmd/server/listeners.go). Deliberately one env var, not that.+const taskMessageBroadcastClipEnv = "MULTICA_CLIP_TASK_MESSAGE_BROADCAST"++// taskMessageBroadcastClipEnabled reports whether oversized tool input/output+// should be clipped out of the realtime copy of a task message.+func taskMessageBroadcastClipEnabled() bool {+ v := strings.TrimSpace(os.Getenv(taskMessageBroadcastClipEnv))+ return v == "1" || strings.EqualFold(v, "true")+}++// Byte budgets for the realtime fanout of a task message (MUL-6396).+//+// A `task:message` frame is broadcast to EVERY client in the workspace, and a+// tool_use input is unbounded: a Write of a large file, or a MultiEdit with+// long old/new strings, ships the whole body to every open client, which then+// retains it. Persisted rows keep the full content — only the broadcast copy+// is clipped, and `Truncated` tells the client to backfill from the REST+// endpoint when it actually needs the full text.+const (+ // broadcastStringLimit caps each individual string inside Input, so small+ // fields (file_path, command, description) survive intact and only the+ // genuinely large ones are clipped.+ broadcastStringLimit = 4096+ // broadcastInputLimit caps the serialized Input after per-string clipping.+ // A map with thousands of small keys can still be large; past this the+ // input is dropped entirely and the client backfills.+ broadcastInputLimit = 16384+ // broadcastOutputLimit mirrors the daemon-side cap on tool output+ // (see daemon.reportMessages). Belt and braces: other producers, and any+ // future relaxation of the daemon cap, must not reopen the fanout hole.+ broadcastOutputLimit = 8192+)++// clipUTF8 truncates s to at most limit bytes without splitting a rune.+func clipUTF8(s string, limit int) string {+ if len(s) <= limit {+ return s+ }+ cut := limit+ for cut > 0 && !utf8.RuneStart(s[cut]) {+ cut--+ }+ return s[:cut]+}++// clipJSONValue returns v with every string at any depth clipped to+// broadcastStringLimit. It never mutates the input: containers are rebuilt+// only when something inside them actually changed.+func clipJSONValue(v any) (any, bool) {+ switch t := v.(type) {+ case string:+ if len(t) <= broadcastStringLimit {+ return t, false+ }+ return clipUTF8(t, broadcastStringLimit), true+ case map[string]any:+ var out map[string]any+ for k, val := range t {+ clipped, did := clipJSONValue(val)+ if !did {+ continue+ }+ if out == nil {+ out = make(map[string]any, len(t))+ for ck, cv := range t {+ out[ck] = cv+ }+ }+ out[k] = clipped+ }+ if out == nil {+ return t, false+ }+ return out, true+ case []any:+ var out []any+ for i, val := range t {+ clipped, did := clipJSONValue(val)+ if !did {+ continue+ }+ if out == nil {+ out = make([]any, len(t))+ copy(out, t)+ }+ out[i] = clipped+ }+ if out == nil {+ return t, false+ }+ return out, true+ default:+ return v, false+ }+}++// truncateTaskMessageForBroadcast clips the realtime copy of a task message so+// one oversized tool call cannot flood every client in the workspace. The+// returned payload is a copy; the caller's row and the REST responses built+// from it are untouched.+func truncateTaskMessageForBroadcast(p protocol.TaskMessagePayload) protocol.TaskMessagePayload {+ if !taskMessageBroadcastClipEnabled() {+ return p+ }++ truncated := false++ if len(p.Output) > broadcastOutputLimit {+ p.Output = clipUTF8(p.Output, broadcastOutputLimit)+ truncated = true+ }++ if p.Input != nil {+ clipped, didClip := clipJSONValue(p.Input)+ if didClip {+ truncated = true+ if m, ok := clipped.(map[string]any); ok {+ p.Input = m+ }+ }+ // Re-measure: per-string clipping bounds each value, not the total.+ if encoded, err := json.Marshal(p.Input); err != nil || len(encoded) > broadcastInputLimit {+ p.Input = nil+ truncated = true+ }+ }++ p.Truncated = truncated+ return p+}+// ListTaskMessages returns the persisted messages for a task (for catch-up after reconnect).func (h *Handler) ListTaskMessages(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")diff --git a/server/internal/handler/daemon_task_message_broadcast_test.go b/server/internal/handler/daemon_task_message_broadcast_test.gonew file mode 100644index 0000000000..d63e6b1d88--- /dev/null+++ b/server/internal/handler/daemon_task_message_broadcast_test.go@@ -0,0 +1,211 @@+package handler++import (+ "encoding/json"+ "strings"+ "testing"+ "unicode/utf8"++ "github.com/multica-ai/multica/server/pkg/protocol"+)++// A task:message frame reaches every client in the workspace, so an unbounded+// tool input is a workspace-wide broadcast of that input. These tests pin the+// clipping applied to the realtime copy — and, just as importantly, that the+// persisted row it was built from is never touched (MUL-6396).++func TestTruncateTaskMessageForBroadcast_LeavesSmallPayloadsAlone(t *testing.T) {+ enableBroadcastClipping(t)+ p := protocol.TaskMessagePayload{+ TaskID: "t1",+ Type: "tool_use",+ Tool: "Edit",+ Input: map[string]any{"file_path": "/a/b.ts", "old_string": "x", "new_string": "y"},+ Output: "ok",+ }++ got := truncateTaskMessageForBroadcast(p)++ if got.Truncated {+ t.Fatalf("small payload marked truncated")+ }+ if got.Output != "ok" {+ t.Fatalf("output changed: %q", got.Output)+ }+ if len(got.Input) != 3 || got.Input["file_path"] != "/a/b.ts" {+ t.Fatalf("input changed: %#v", got.Input)+ }+}++func TestTruncateTaskMessageForBroadcast_ClipsOversizedOutput(t *testing.T) {+ enableBroadcastClipping(t)+ p := protocol.TaskMessagePayload{Output: strings.Repeat("a", broadcastOutputLimit*2)}++ got := truncateTaskMessageForBroadcast(p)++ if !got.Truncated {+ t.Fatalf("oversized output not marked truncated")+ }+ if len(got.Output) > broadcastOutputLimit {+ t.Fatalf("output %d bytes, want <= %d", len(got.Output), broadcastOutputLimit)+ }+}++func TestTruncateTaskMessageForBroadcast_ClipsLargeStringsKeepsSmallOnes(t *testing.T) {+ enableBroadcastClipping(t)+ // The shape of a Write of a large file: the path must survive so the+ // transcript can still say what was written.+ p := protocol.TaskMessagePayload{+ Input: map[string]any{+ "file_path": "/repo/big.ts",+ "content": strings.Repeat("z", broadcastStringLimit*2),+ },+ }++ got := truncateTaskMessageForBroadcast(p)++ if !got.Truncated {+ t.Fatalf("oversized input not marked truncated")+ }+ if got.Input["file_path"] != "/repo/big.ts" {+ t.Fatalf("small field was clipped: %#v", got.Input["file_path"])+ }+ content, _ := got.Input["content"].(string)+ if len(content) > broadcastStringLimit {+ t.Fatalf("content %d bytes, want <= %d", len(content), broadcastStringLimit)+ }+}++func TestTruncateTaskMessageForBroadcast_ClipsNestedStrings(t *testing.T) {+ enableBroadcastClipping(t)+ // MultiEdit: the large strings sit inside an array of objects.+ p := protocol.TaskMessagePayload{+ Input: map[string]any{+ "file_path": "/repo/x.ts",+ "edits": []any{+ map[string]any{"old_string": strings.Repeat("q", broadcastStringLimit*2), "new_string": "n"},+ },+ },+ }++ got := truncateTaskMessageForBroadcast(p)++ if !got.Truncated {+ t.Fatalf("nested oversized input not marked truncated")+ }+ edits, ok := got.Input["edits"].([]any)+ if !ok || len(edits) != 1 {+ t.Fatalf("edits lost: %#v", got.Input["edits"])+ }+ edit, _ := edits[0].(map[string]any)+ old, _ := edit["old_string"].(string)+ if len(old) > broadcastStringLimit {+ t.Fatalf("nested string %d bytes, want <= %d", len(old), broadcastStringLimit)+ }+ if edit["new_string"] != "n" {+ t.Fatalf("small nested field was clipped: %#v", edit["new_string"])+ }+}++func TestTruncateTaskMessageForBroadcast_DropsInputThatIsStillTooLargeInAggregate(t *testing.T) {+ enableBroadcastClipping(t)+ // Per-string clipping bounds each value, not the total: a map of many+ // modest strings can still blow the budget.+ input := map[string]any{}+ for i := 0; i < 400; i++ {+ input[string(rune('a'+i%26))+strings.Repeat("k", 8)+string(rune(i))] = strings.Repeat("v", 200)+ }+ p := protocol.TaskMessagePayload{Input: input}++ got := truncateTaskMessageForBroadcast(p)++ if !got.Truncated {+ t.Fatalf("aggregate-oversized input not marked truncated")+ }+ if got.Input != nil {+ encoded, _ := json.Marshal(got.Input)+ t.Fatalf("input kept at %d bytes, want dropped", len(encoded))+ }+}++func TestTruncateTaskMessageForBroadcast_DoesNotSplitRunes(t *testing.T) {+ enableBroadcastClipping(t)+ // A clip at a raw byte offset would leave a partial rune, which JSON+ // encoding then rewrites to U+FFFD.+ p := protocol.TaskMessagePayload{Output: strings.Repeat("世", broadcastOutputLimit)}++ got := truncateTaskMessageForBroadcast(p)++ if !utf8.ValidString(got.Output) {+ t.Fatalf("clipped output is not valid UTF-8")+ }+ if len(got.Output) > broadcastOutputLimit {+ t.Fatalf("output %d bytes, want <= %d", len(got.Output), broadcastOutputLimit)+ }+}++func TestTruncateTaskMessageForBroadcast_LeavesTheSourcePayloadIntact(t *testing.T) {+ enableBroadcastClipping(t)+ // The same payload value feeds the REST list responses, which must keep+ // serving the full persisted content.+ big := strings.Repeat("z", broadcastStringLimit*2)+ edits := []any{map[string]any{"old_string": big}}+ input := map[string]any{"content": big, "edits": edits}+ p := protocol.TaskMessagePayload{Input: input, Output: strings.Repeat("a", broadcastOutputLimit*2)}++ _ = truncateTaskMessageForBroadcast(p)++ if got, _ := input["content"].(string); len(got) != len(big) {+ t.Fatalf("source input map was mutated: content is now %d bytes", len(got))+ }+ edit, _ := edits[0].(map[string]any)+ if got, _ := edit["old_string"].(string); len(got) != len(big) {+ t.Fatalf("source nested map was mutated: old_string is now %d bytes", len(got))+ }+ if len(p.Output) != broadcastOutputLimit*2 {+ t.Fatalf("source payload output was mutated")+ }+}++// enableBroadcastClipping opts a case into the clipping path. It is off by+// default in production until clients that understand `truncated` saturate.+func enableBroadcastClipping(t *testing.T) {+ t.Helper()+ t.Setenv(taskMessageBroadcastClipEnv, "1")+}++func TestTruncateTaskMessageForBroadcast_DisabledByDefault(t *testing.T) {+ // The guarantee old clients depend on: with the flag unset, the realtime+ // copy is byte-for-byte what it was before this change. A client that does+ // not understand `truncated` caches the broadcast payload under+ // staleTime:Infinity, so a clipped field would stay clipped until reload.+ big := strings.Repeat("z", broadcastStringLimit*4)+ p := protocol.TaskMessagePayload{+ Input: map[string]any{"content": big},+ Output: strings.Repeat("a", broadcastOutputLimit*4),+ }++ got := truncateTaskMessageForBroadcast(p)++ if got.Truncated {+ t.Fatalf("clipping applied while disabled")+ }+ if content, _ := got.Input["content"].(string); len(content) != len(big) {+ t.Fatalf("input clipped while disabled: %d bytes", len(content))+ }+ if len(got.Output) != broadcastOutputLimit*4 {+ t.Fatalf("output clipped while disabled: %d bytes", len(got.Output))+ }+}++func TestTruncateTaskMessageForBroadcast_EnabledByExplicitValuesOnly(t *testing.T) {+ for _, tc := range []struct {+ value string+ want bool+ }{{"1", true}, {"true", true}, {"TRUE", true}, {"", false}, {"0", false}, {"yes", false}} {+ t.Setenv(taskMessageBroadcastClipEnv, tc.value)+ if got := taskMessageBroadcastClipEnabled(); got != tc.want {+ t.Errorf("%q: enabled=%v, want %v", tc.value, got, tc.want)+ }+ }+}diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex cffa36c951..28a672f392 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -171,6 +171,13 @@ type TaskMessagePayload struct {Input map[string]any `json:"input,omitempty"` // tool input (tool_use only)Output string `json:"output,omitempty"` // tool output (tool_result only)CreatedAt string `json:"created_at,omitempty"`++ // Truncated marks a payload whose Input/Output were clipped for the+ // realtime fanout (MUL-6396). The REST list endpoints never set it — they+ // always return the full persisted row — so a client that sees it knows+ // the authoritative content is one GET away. Clients render the clipped+ // text immediately and backfill the full row in the background.+ Truncated bool `json:"truncated,omitempty"`}// DaemonRegisterPayload is sent from daemon to server on connection.