Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

fix: cut websocket throughput in half by pruning activity payloads (#4622)

Theo Browned60f6e971f8f
diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.ts b/apps/server/src/orchestration/ActivityPayloadProjection.ts
new file mode 100644
index 000000000..5fd0cc898
--- /dev/null
+++ b/apps/server/src/orchestration/ActivityPayloadProjection.ts
@@ -0,0 +1,227 @@
+import type {
+ OrchestrationEvent,
+ OrchestrationThreadActivity,
+ OrchestrationThreadDetailSnapshot,
+} from "@t3tools/contracts";
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+function asTrimmedString(value: unknown): string | null {
+ if (typeof value !== "string") {
+ return null;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function pushChangedFile(target: string[], seen: Set<string>, value: unknown): void {
+ const normalized = asTrimmedString(value);
+ if (!normalized || seen.has(normalized)) {
+ return;
+ }
+ seen.add(normalized);
+ target.push(normalized);
+}
+
+function collectChangedFiles(
+ value: unknown,
+ target: string[],
+ seen: Set<string>,
+ depth: number,
+): void {
+ if (depth > 4 || target.length >= 12) {
+ return;
+ }
+ if (Array.isArray(value)) {
+ for (const entry of value) {
+ collectChangedFiles(entry, target, seen, depth + 1);
+ if (target.length >= 12) {
+ return;
+ }
+ }
+ return;
+ }
+
+ const record = asRecord(value);
+ if (!record) {
+ return;
+ }
+
+ pushChangedFile(target, seen, record.path);
+ pushChangedFile(target, seen, record.filePath);
+ pushChangedFile(target, seen, record.relativePath);
+ pushChangedFile(target, seen, record.filename);
+ pushChangedFile(target, seen, record.newPath);
+ pushChangedFile(target, seen, record.oldPath);
+
+ for (const nestedKey of [
+ "item",
+ "result",
+ "input",
+ "data",
+ "changes",
+ "files",
+ "edits",
+ "patch",
+ "patches",
+ "operations",
+ ]) {
+ if (!(nestedKey in record)) {
+ continue;
+ }
+ collectChangedFiles(record[nestedKey], target, seen, depth + 1);
+ if (target.length >= 12) {
+ return;
+ }
+ }
+}
+
+function projectCommandData(data: Record<string, unknown>): Record<string, unknown> | undefined {
+ const item = asRecord(data.item);
+ if (!item) {
+ return undefined;
+ }
+
+ const projectedItem: Record<string, unknown> = {};
+ if ("command" in item) {
+ projectedItem.command = item.command;
+ }
+
+ const input = asRecord(item.input);
+ if (input && "command" in input) {
+ projectedItem.input = { command: input.command };
+ }
+
+ const result = asRecord(item.result);
+ if (result && "command" in result) {
+ projectedItem.result = { command: result.command };
+ }
+
+ return Object.keys(projectedItem).length > 0 ? projectedItem : undefined;
+}
+
+function summarizeToolTextOutput(value: string): string | null {
+ const lines: string[] = [];
+ for (const rawLine of value.split(/\r?\n/u)) {
+ const line = rawLine.replace(/\s+/g, " ").trim();
+ if (line.length > 0) {
+ lines.push(line);
+ }
+ }
+
+ const firstLine = lines.find((line) => line !== "```");
+ if (firstLine) {
+ return firstLine.length <= 84 ? firstLine : `${firstLine.slice(0, 83).trimEnd()}…`;
+ }
+ if (lines.length > 1) {
+ return `${lines.length.toLocaleString()} lines`;
+ }
+ return null;
+}
+
+function projectRawOutput(value: unknown): Record<string, unknown> | undefined {
+ const rawOutput = asRecord(value);
+ if (!rawOutput) {
+ return undefined;
+ }
+
+ if (typeof rawOutput.totalFiles === "number" && Number.isFinite(rawOutput.totalFiles)) {
+ return {
+ totalFiles: rawOutput.totalFiles,
+ ...(rawOutput.truncated === true ? { truncated: true } : {}),
+ };
+ }
+
+ const content = asTrimmedString(rawOutput.content);
+ if (content) {
+ const summary = summarizeToolTextOutput(content);
+ return summary ? { content: summary } : undefined;
+ }
+
+ const stdout = asTrimmedString(rawOutput.stdout);
+ if (stdout) {
+ const summary = summarizeToolTextOutput(stdout);
+ return summary ? { content: summary } : undefined;
+ }
+
+ return undefined;
+}
+
+/**
+ * Removes activity payload fields that no current client reads while retaining
+ * the full payload in persistence and the event store.
+ */
+export function projectActivityPayload(
+ activity: OrchestrationThreadActivity,
+): OrchestrationThreadActivity {
+ const payload = asRecord(activity.payload);
+ const data = asRecord(payload?.data);
+ if (!payload || !data || payload.itemType === "mcp_tool_call") {
+ return activity;
+ }
+
+ const projectedData: Record<string, unknown> = {};
+ const item = projectCommandData(data);
+ if (item) {
+ projectedData.item = item;
+ }
+ if ("command" in data) {
+ projectedData.command = data.command;
+ }
+
+ const changedFiles: string[] = [];
+ collectChangedFiles(data, changedFiles, new Set<string>(), 0);
+ if (changedFiles.length > 0) {
+ // Both clients discover file names by walking objects with path-like keys.
+ projectedData.files = changedFiles.map((path) => ({ path }));
+ }
+
+ if ("toolCallId" in data) {
+ projectedData.toolCallId = data.toolCallId;
+ }
+ if ("kind" in data) {
+ projectedData.kind = data.kind;
+ }
+
+ const rawOutput = projectRawOutput(data.rawOutput);
+ if (rawOutput) {
+ projectedData.rawOutput = rawOutput;
+ }
+
+ return {
+ ...activity,
+ payload: {
+ ...payload,
+ data: projectedData,
+ },
+ };
+}
+
+export function projectThreadDetailSnapshot(
+ snapshot: OrchestrationThreadDetailSnapshot,
+): OrchestrationThreadDetailSnapshot {
+ return {
+ ...snapshot,
+ thread: {
+ ...snapshot.thread,
+ activities: snapshot.thread.activities.map(projectActivityPayload),
+ },
+ };
+}
+
+export function projectActivityEvent(event: OrchestrationEvent): OrchestrationEvent {
+ if (event.type !== "thread.activity-appended") {
+ return event;
+ }
+ return {
+ ...event,
+ payload: {
+ ...event.payload,
+ activity: projectActivityPayload(event.payload.activity),
+ },
+ };
+}
diff --git a/apps/server/src/orchestration/http.ts b/apps/server/src/orchestration/http.ts
index 016c3d508..659665e47 100644
--- a/apps/server/src/orchestration/http.ts
+++ b/apps/server/src/orchestration/http.ts
@@ -7,6 +7,7 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
+import { projectThreadDetailSnapshot } from "./ActivityPayloadProjection.ts";
import { normalizeDispatchCommand } from "./Normalizer.ts";
import {
annotateEnvironmentRequest,
@@ -69,7 +70,7 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
if (Option.isNone(snapshot)) {
return yield* failEnvironmentNotFound("thread_not_found");
}
- return snapshot.value;
+ return projectThreadDetailSnapshot(snapshot.value);
}),
)
.handle(
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index f6f46d1e7..b8f4b0712 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -68,6 +68,10 @@ import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as ServerConfig from "./config.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
+import {
+ projectActivityEvent,
+ projectThreadDetailSnapshot,
+} from "./orchestration/ActivityPayloadProjection.ts";
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
@@ -1213,6 +1217,7 @@ const makeWsRpcLayer = (
).pipe(
Effect.map((events) => Array.from(events)),
Effect.flatMap(enrichOrchestrationEvents),
+ Effect.map((events) => events.map(projectActivityEvent)),
Effect.mapError(
(cause) =>
new OrchestrationReplayEventsError({
@@ -1360,7 +1365,7 @@ const makeWsRpcLayer = (
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({
kind: "event" as const,
- event,
+ event: projectActivityEvent(event),
})),
);
@@ -1395,7 +1400,10 @@ const makeWsRpcLayer = (
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
Stream.filter(isThisThreadDetailEvent),
- Stream.map((event) => ({ kind: "event" as const, event })),
+ Stream.map((event) => ({
+ kind: "event" as const,
+ event: projectActivityEvent(event),
+ })),
Stream.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
@@ -1447,7 +1455,7 @@ const makeWsRpcLayer = (
return Stream.concat(
Stream.make({
kind: "snapshot" as const,
- snapshot: snapshot.value,
+ snapshot: projectThreadDetailSnapshot(snapshot.value),
}),
afterSnapshot,
);
diff --git a/apps/server/test/ActivityPayloadProjection.test.ts b/apps/server/test/ActivityPayloadProjection.test.ts
new file mode 100644
index 000000000..f7645a26a
--- /dev/null
+++ b/apps/server/test/ActivityPayloadProjection.test.ts
@@ -0,0 +1,214 @@
+import {
+ EventId,
+ ProjectId,
+ ProviderInstanceId,
+ ThreadId,
+ TurnId,
+ type OrchestrationEvent,
+ type OrchestrationThread,
+ type OrchestrationThreadActivity,
+} from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { buildThreadFeed } from "../../mobile/src/lib/threadActivity.ts";
+import { deriveWorkLogEntries } from "../../web/src/session-logic.ts";
+import {
+ projectActivityEvent,
+ projectActivityPayload,
+ projectThreadDetailSnapshot,
+} from "../src/orchestration/ActivityPayloadProjection.ts";
+
+function makeActivity(
+ id: string,
+ itemType: string,
+ data: Record<string, unknown>,
+): OrchestrationThreadActivity {
+ return {
+ id: EventId.make(id),
+ tone: "tool",
+ kind: "tool.completed",
+ summary: `Completed ${itemType}`,
+ payload: {
+ itemType,
+ title: itemType,
+ detail: `${itemType} detail`,
+ status: "completed",
+ requestKind: "command",
+ data,
+ },
+ turnId: TurnId.make(`turn-${id}`),
+ createdAt: "2026-07-27T00:00:00.000Z",
+ };
+}
+
+function makeThread(activities: ReadonlyArray<OrchestrationThreadActivity>): OrchestrationThread {
+ return {
+ id: ThreadId.make("thread-projection"),
+ projectId: ProjectId.make("project-projection"),
+ title: "Activity projection",
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "gpt-5.4",
+ },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-07-27T00:00:00.000Z",
+ updatedAt: "2026-07-27T00:00:00.000Z",
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ deletedAt: null,
+ messages: [],
+ proposedPlans: [],
+ activities,
+ checkpoints: [],
+ session: null,
+ };
+}
+
+const fixtures = [
+ makeActivity("command", "command_execution", {
+ item: {
+ command: ["bash", "-lc", "pnpm test"],
+ input: { command: "fallback input", ignored: "input bulk" },
+ result: { command: "fallback result", aggregatedOutput: "x".repeat(10_000) },
+ commandActions: [{ type: "unknown", output: "y".repeat(5_000) }],
+ },
+ command: "fallback data",
+ kind: "execute",
+ toolCallId: "tool-command",
+ rawOutput: {
+ content: "\n```\nfirst useful line\nsecond line",
+ stdout: "unused stdout",
+ ignored: "raw bulk",
+ },
+ ignored: "top-level bulk",
+ }),
+ makeActivity("file-change", "file_change", {
+ item: {
+ changes: [
+ { oldPath: "src/old.ts", newPath: "src/new.ts", patch: "large patch".repeat(1_000) },
+ { filePath: "src/second.ts" },
+ ],
+ },
+ ignored: "top-level bulk",
+ }),
+ makeActivity("dynamic", "dynamic_tool_call", {
+ toolCallId: "tool-dynamic",
+ rawOutput: {
+ stdout: "dynamic summary\nlong output".repeat(1_000),
+ },
+ ignored: "top-level bulk",
+ }),
+ makeActivity("collab", "collab_agent_tool_call", {
+ kind: "delegate",
+ rawOutput: {
+ content: "``` \n```",
+ stdout: "must not be used when content is present",
+ },
+ ignored: "top-level bulk",
+ }),
+ makeActivity("mcp", "mcp_tool_call", {
+ item: {
+ server: "repository",
+ tool: "search",
+ arguments: { query: "activity projection" },
+ aggregatedOutput: "mcp payload remains available",
+ },
+ ignored: "MCP data is rendered verbatim",
+ }),
+ makeActivity("search", "web_search", {
+ rawOutput: {
+ totalFiles: 42,
+ truncated: true,
+ content: "ignored because totalFiles wins",
+ },
+ ignored: "top-level bulk",
+ }),
+ makeActivity("image", "image_view", {
+ ignored: "top-level bulk",
+ }),
+] satisfies ReadonlyArray<OrchestrationThreadActivity>;
+
+describe("projectActivityPayload", () => {
+ it("drops unread bulk while retaining command, file, tool, and summary inputs", () => {
+ const projected = projectActivityPayload(fixtures[0]!);
+ expect(projected.payload).toEqual({
+ itemType: "command_execution",
+ title: "command_execution",
+ detail: "command_execution detail",
+ status: "completed",
+ requestKind: "command",
+ data: {
+ item: {
+ command: ["bash", "-lc", "pnpm test"],
+ input: { command: "fallback input" },
+ result: { command: "fallback result" },
+ },
+ command: "fallback data",
+ toolCallId: "tool-command",
+ kind: "execute",
+ rawOutput: { content: "first useful line" },
+ },
+ });
+
+ expect(projectActivityPayload(fixtures[1]!).payload).toMatchObject({
+ data: {
+ files: [{ path: "src/new.ts" }, { path: "src/old.ts" }, { path: "src/second.ts" }],
+ },
+ });
+ });
+
+ it("passes MCP tool data through unchanged", () => {
+ expect(projectActivityPayload(fixtures[4]!)).toBe(fixtures[4]);
+ });
+
+ it("keeps current web and mobile derived output identical for every tool item type", () => {
+ for (const activity of fixtures) {
+ const projected = projectActivityPayload(activity);
+ expect(deriveWorkLogEntries([projected])).toEqual(deriveWorkLogEntries([activity]));
+ expect(buildThreadFeed(makeThread([projected]))).toEqual(
+ buildThreadFeed(makeThread([activity])),
+ );
+ }
+ });
+
+ it("projects snapshot and event transports without mutating their sources", () => {
+ const activity = fixtures[0]!;
+ const thread = makeThread([activity]);
+ const snapshot = { snapshotSequence: 7, thread };
+ const projectedSnapshot = projectThreadDetailSnapshot(snapshot);
+
+ expect(projectedSnapshot.thread.activities[0]).not.toBe(activity);
+ expect(snapshot.thread.activities[0]).toBe(activity);
+
+ const event = {
+ sequence: 8,
+ eventId: EventId.make("event-activity"),
+ aggregateKind: "thread",
+ aggregateId: thread.id,
+ occurredAt: "2026-07-27T00:00:01.000Z",
+ commandId: null,
+ causationEventId: null,
+ correlationId: null,
+ metadata: {},
+ type: "thread.activity-appended",
+ payload: {
+ threadId: thread.id,
+ activity,
+ },
+ } satisfies Extract<OrchestrationEvent, { type: "thread.activity-appended" }>;
+
+ const projectedEvent = projectActivityEvent(event);
+ expect(projectedEvent).not.toBe(event);
+ expect(
+ projectedEvent.type === "thread.activity-appended"
+ ? projectedEvent.payload.activity
+ : undefined,
+ ).toEqual(projectActivityPayload(activity));
+ expect(event.payload.activity).toBe(activity);
+ });
+});