diff --git a/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.test.ts b/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.test.ts index f5b6283e06..d494f18b7f 100644 --- a/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.test.ts @@ -68,7 +68,6 @@ describe("decodeProviderReplayNdjson", () => { } const causeRecord = cause as Record; assert.equal(causeRecord.name, "SchemaError"); - assert.equal(causeRecord._tag, "SchemaError"); assert.doesNotThrow(() => JSON.stringify(encoded)); }), ); diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.ts b/apps/server/src/orchestration/ActivityPayloadProjection.ts deleted file mode 100644 index 5fd0cc8984..0000000000 --- a/apps/server/src/orchestration/ActivityPayloadProjection.ts +++ /dev/null @@ -1,227 +0,0 @@ -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/test/ActivityPayloadProjection.test.ts b/apps/server/test/ActivityPayloadProjection.test.ts deleted file mode 100644 index 6552dfb140..0000000000 --- a/apps/server/test/ActivityPayloadProjection.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -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, type ThreadFeedActivity } 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", () => { - function comparableActivity(activity: ThreadFeedActivity) { - return { - ...activity, - fullDetail: activity.getFullDetail(), - copyText: activity.getCopyText(), - getFullDetail: undefined, - getCopyText: undefined, - }; - } - - function comparableThreadFeed(activities: ReadonlyArray) { - return buildThreadFeed(makeThread(activities)).map((entry) => - entry.type === "activity-group" - ? { - ...entry, - activities: entry.activities.map(comparableActivity), - } - : entry, - ); - } - - 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(comparableThreadFeed([projected])).toEqual(comparableThreadFeed([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); - }); -});