Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6396: remove unused task message clipping flag (#7292)
Multica Evecb6b0c885f42
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.tsindex 91176ca0d0..4986501766 100644--- a/apps/mobile/data/realtime/chat-ws-updaters.ts+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts@@ -326,21 +326,4 @@ 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 4880f54585..a64a02c20b 100644--- a/apps/mobile/data/schemas.ts+++ b/apps/mobile/data/schemas.ts@@ -350,9 +350,6 @@ 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 e6bd2d0af1..a7108f937f 100644--- a/packages/core/chat/queries.test.ts+++ b/packages/core/chat/queries.test.ts@@ -44,10 +44,10 @@ describe("unionTaskMessagesBySeq", () => {});it("lets the authoritative row win on conflict", () => {- const clipped = { ...msg(1), content: "clip", truncated: true };- const persisted = { ...msg(1), content: "full" };+ const live = { ...msg(1), content: "live" };+ const persisted = { ...msg(1), content: "persisted" };- const united = unionTaskMessagesBySeq([clipped], [persisted]);+ const united = unionTaskMessagesBySeq([live], [persisted]);expect(united).toEqual([persisted]);});diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.tsindex cea3776015..b924dda149 100644--- a/packages/core/chat/queries.ts+++ b/packages/core/chat/queries.ts@@ -249,10 +249,9 @@ export function mergeTaskMessagesBySeq(* 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.+ * Server data wins on conflict because the persisted row is the authority.+ * 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.@@ -307,28 +306,6 @@ export function isTaskMessageTimelineHeld(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.tsxindex 8739a9a55e..da95f28a67 100644--- a/packages/core/realtime/use-realtime-sync-task-messages.test.tsx+++ b/packages/core/realtime/use-realtime-sync-task-messages.test.tsx@@ -7,7 +7,7 @@ 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 { 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";@@ -162,64 +162,6 @@ describe("useRealtimeSync — task:message fanout guards (MUL-6396)", () => {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:@@ -250,24 +192,6 @@ describe("useRealtimeSync — task:message fanout guards (MUL-6396)", () => {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@@ -303,45 +227,4 @@ describe("useRealtimeSync — task:message fanout guards (MUL-6396)", () => {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 18117f694a..8bdbfc8fe7 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -58,7 +58,6 @@ import {} from "../platform/system-notification";import type { Workspace } from "../types/workspace";import {- backfillTaskMessages,chatKeys,isTaskMessageTimelineHeld,mergeTaskMessagesBySeq,@@ -1345,7 +1344,6 @@ export function useRealtimeSync(// 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 = () => {@@ -1363,7 +1361,6 @@ export function useRealtimeSync(// 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[]>(@@ -1372,21 +1369,6 @@ export function useRealtimeSync();}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) => {@@ -1398,7 +1380,6 @@ export function useRealtimeSync(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.diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex dd9c56b38b..29e4456cb2 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -294,13 +294,6 @@ 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/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex f3f68cdea5..ef736215da 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -10,12 +10,10 @@ import ("fmt""log/slog""net/http"- "os""sort""strconv""strings""time"- "unicode/utf8""github.com/go-chi/chi/v5""github.com/google/uuid"@@ -4471,8 +4469,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {if workspaceID != "" {h.publishTask(protocol.EventTaskMessage, workspaceID, "system", "", taskID,- truncateTaskMessageForBroadcast(- taskMessageToPayload(created, taskID, uuidToString(task.IssueID))))+ taskMessageToPayload(created, taskID, uuidToString(task.IssueID)))}}@@ -4602,152 +4599,6 @@ 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.godeleted file mode 100644index d63e6b1d88..0000000000--- a/server/internal/handler/daemon_task_message_broadcast_test.go+++ /dev/null@@ -1,211 +0,0 @@-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 28a672f392..cffa36c951 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -171,13 +171,6 @@ 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.