diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 902a4ee8b5..0896335ea9 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -108,7 +108,8 @@ export function ThreadWorkLog(props: { {rows.map((row) => { const expanded = props.expandedRows[row.id] ?? false; - const canExpand = row.fullDetail !== null; + const canExpand = row.canExpand; + const fullDetail = expanded ? row.getFullDetail() : null; const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary; const iconIsDestructive = row.icon === "alert" || row.icon === "warning"; @@ -133,7 +134,7 @@ export function ThreadWorkLog(props: { props.onToggleRow(row.id); } }} - onLongPress={() => props.onCopyRow(row.id, row.copyText)} + onLongPress={() => props.onCopyRow(row.id, row.getCopyText())} style={({ pressed }) => ({ backgroundColor: pressed ? pressedBackground : "transparent", })} @@ -204,7 +205,7 @@ export function ThreadWorkLog(props: { - {expanded && row.fullDetail ? ( + {fullDetail ? ( - {row.fullDetail} + {fullDetail} diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index b1bdb61b96..5d323516dd 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -161,20 +161,22 @@ describe("buildThreadFeed", () => { return; } - expect(group.activities).toEqual([ - { - id: "tool-completed", - createdAt: "2026-04-01T00:00:02.000Z", - turnId: "turn-1", - summary: "Run tests", - detail: "bun run test", - fullDetail: "/bin/zsh -lc 'bun run test'", - copyText: "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'", - icon: "command", - toolLike: true, - status: "success", - }, - ]); + expect(group.activities).toHaveLength(1); + expect(group.activities[0]).toMatchObject({ + id: "tool-completed", + createdAt: "2026-04-01T00:00:02.000Z", + turnId: "turn-1", + summary: "Run tests", + detail: "bun run test", + canExpand: true, + icon: "command", + toolLike: true, + status: "success", + }); + expect(group.activities[0]?.getFullDetail()).toBe("/bin/zsh -lc 'bun run test'"); + expect(group.activities[0]?.getCopyText()).toBe( + "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'", + ); }); it("keeps MCP inputs available to expanded mobile work rows", () => { @@ -223,8 +225,55 @@ describe("buildThreadFeed", () => { } expect(group.activities[0]?.icon).toBe("wrench"); - expect(group.activities[0]?.fullDetail).toContain('"query": "work log"'); - expect(group.activities[0]?.fullDetail).toContain("repository.search"); + expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"'); + expect(group.activities[0]?.getFullDetail()).toContain("repository.search"); + }); + + it("defers large tool output expansion until a work row is opened or copied", () => { + let serializedToolOutputs = 0; + const activities = Array.from({ length: 5_000 }, (_, index) => + makeActivity({ + id: EventId.make(`large-tool-${index}`), + kind: "tool.completed", + tone: "tool", + summary: `Tool ${index}`, + createdAt: new Date(Date.UTC(2026, 3, 1, 0, 0, index)).toISOString(), + payload: { + title: `Tool ${index}`, + itemType: "mcp_tool_call", + status: "completed", + data: { + item: { + toJSON: () => { + serializedToolOutputs += 1; + return { output: "x".repeat(32_768) }; + }, + }, + }, + }, + }), + ); + const thread = makeThread({ + id: ThreadId.make("thread-large-tools"), + projectId: ProjectId.make("project-1"), + title: "Large tools", + activities, + }); + + const feed = buildThreadFeed(thread); + expect(serializedToolOutputs).toBe(0); + + const group = feed[0]; + expect(group).toMatchObject({ type: "activity-group" }); + if (!group || group.type !== "activity-group") { + return; + } + + expect(group.activities).toHaveLength(5_000); + expect(group.activities[0]?.getFullDetail()).toContain('"output"'); + expect(serializedToolOutputs).toBe(1); + expect(group.activities[0]?.getCopyText()).toContain('"output"'); + expect(serializedToolOutputs).toBe(1); }); it("folds settled turn work while leaving the terminal answer visible", () => { @@ -439,8 +488,9 @@ describe("buildThreadFeed", () => { turnId: null, summary: `Tool ${id}`, detail: null, - fullDetail: null, - copyText: id, + canExpand: false, + getFullDetail: () => null, + getCopyText: () => id, icon: "command", toolLike: true, status, diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 6278247dc6..0c79217502 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -36,8 +36,9 @@ export interface ThreadFeedActivity { readonly turnId: TurnId | null; readonly summary: string; readonly detail: string | null; - readonly fullDetail: string | null; - readonly copyText: string; + readonly canExpand: boolean; + readonly getFullDetail: () => string | null; + readonly getCopyText: () => string; readonly icon: | "agent" | "alert" @@ -554,6 +555,27 @@ function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null { return blocks.length > 0 ? blocks.join("\n\n") : null; } +function workEntryHasExpandedBody(entry: WorkLogEntry): boolean { + return ( + (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) || + Boolean((entry.rawCommand ?? entry.command)?.trim()) || + Boolean(entry.detail?.trim()) || + (entry.changedFiles?.some((path) => path.trim().length > 0) ?? false) + ); +} + +function memoizeValue(build: () => T): () => T { + let value: T; + let initialized = false; + return () => { + if (!initialized) { + value = build(); + initialized = true; + } + return value; + }; +} + function workEntryPreview( workEntry: Pick, ): string | null { @@ -1353,7 +1375,14 @@ export function buildThreadFeed( .map((entry) => { const summary = workEntryHeading(entry); const detail = workEntryPreview(entry); - const fullDetail = buildWorkEntryExpandedBody(entry); + const getFullDetail = memoizeValue(() => buildWorkEntryExpandedBody(entry)); + const getCopyText = memoizeValue(() => + [summary, detail, getFullDetail()] + .filter((value, index, values): value is string => { + return Boolean(value) && values.indexOf(value) === index; + }) + .join("\n"), + ); return { type: "activity", id: entry.id, @@ -1365,13 +1394,10 @@ export function buildThreadFeed( turnId: entry.turnId, summary, detail, - fullDetail, + canExpand: workEntryHasExpandedBody(entry), + getFullDetail, + getCopyText, icon: workEntryIcon(entry), - copyText: [summary, detail, fullDetail] - .filter((value, index, values): value is string => { - return Boolean(value) && values.indexOf(value) === index; - }) - .join("\n"), toolLike: workLogEntryIsToolLike(entry), status: workEntryStatus(entry), }, diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.ts b/apps/server/src/orchestration/ActivityPayloadProjection.ts new file mode 100644 index 0000000000..5fd0cc8984 --- /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 | null { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : 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, 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, + 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): Record | undefined { + const item = asRecord(data.item); + if (!item) { + return undefined; + } + + const projectedItem: Record = {}; + 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 | 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 = {}; + 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(), 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 016c3d508e..659665e47b 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 00e844a812..d828dac4db 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"; @@ -1229,6 +1233,7 @@ const makeWsRpcLayer = ( ).pipe( Effect.map((events) => Array.from(events)), Effect.flatMap(enrichOrchestrationEvents), + Effect.map((events) => events.map(projectActivityEvent)), Effect.mapError( (cause) => new OrchestrationReplayEventsError({ @@ -1393,7 +1398,7 @@ const makeWsRpcLayer = ( Stream.filter(isThisThreadDetailEvent), Stream.map((event) => ({ kind: "event" as const, - event, + event: projectActivityEvent(event), })), ); @@ -1428,7 +1433,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({ @@ -1480,7 +1488,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 0000000000..f7645a26a6 --- /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, +): 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): 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; + +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; + + 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); + }); +});