diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.ts index d8031de9e7a39..bf63418c0ed7e 100644 --- a/apps/mobile/src/connection/environment-cache-store.test.ts +++ b/apps/mobile/src/connection/environment-cache-store.test.ts @@ -286,6 +286,37 @@ describe("mobile SQLite environment cache store", () => { }), ); + it.effect("discards thread records written before file changes carried diffOmitted", () => + Effect.gen(function* () { + const memory = makeDatabase(); + const store = yield* make().pipe( + Effect.provideService(MobileDatabase.MobileDatabase, memory.database), + ); + const id = cacheId(ENVIRONMENT_ID, "thread", THREAD_ID); + yield* store.saveThread(ENVIRONMENT_ID, threadSnapshotWithItems()); + const current = JSON.parse(memory.values.get(id)!); + const legacy = JSON.parse( + yield* encodeLegacyThreadSnapshot({ + schemaVersion: ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION, + environmentId: ENVIRONMENT_ID, + threadId: THREAD_ID, + snapshot: threadSnapshotWithItems(), + }), + ); + // Compact records were 6 and full ones 5 when an older client could strip the field. A + // resumed thread replays only newer events, so these rows would never be replaced. + for (const stale of [ + { ...current, schemaVersion: 6 }, + { ...legacy, schemaVersion: 5 }, + ]) { + memory.values.set(id, JSON.stringify(stale)); + memory.removed.length = 0; + expect(Option.isNone(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID))).toBe(true); + expect(memory.removed).toEqual([id]); + } + }).pipe(Effect.provide(Logger.layer([]))), + ); + it.effect("discards corrupt or partial thread records so they can be refetched", () => Effect.gen(function* () { const memory = makeDatabase(); @@ -431,8 +462,8 @@ describe("mobile SQLite environment cache store", () => { yield* store.saveThread(ENVIRONMENT_ID, snapshot); const id = cacheId(ENVIRONMENT_ID, "thread", THREAD_ID); const encoded = JSON.parse(memory.values.get(id)!); - expect(encoded.schemaVersion).toBe(6); - expect(memory.schemaVersions.get(id)).toBe(6); + expect(encoded.schemaVersion).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION); + expect(memory.schemaVersions.get(id)).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION); expect(encoded.snapshot.turnItemsOmitLocalVisible).toBe(true); expect(encoded.snapshot.turnItemCount).toBe(3); expect(encoded.snapshot.visibleTurnItemCount).toBe(4); @@ -480,7 +511,7 @@ describe("mobile SQLite environment cache store", () => { yield* store.saveThread(ENVIRONMENT_ID, snapshot); const raw = memory.values.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))!; const encoded = JSON.parse(raw); - expect(encoded.schemaVersion).toBe(6); + expect(encoded.schemaVersion).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION); expect(encoded.snapshot.turnItemsOmitLocalVisible).toBe(false); expect(encoded.snapshot.turnItemCount).toBe(2); expect(encoded.snapshot.projection.turnItems).toHaveLength(2); diff --git a/apps/mobile/src/features/threads/FileChangeDiffText.tsx b/apps/mobile/src/features/threads/FileChangeDiffText.tsx new file mode 100644 index 0000000000000..6109c250d408e --- /dev/null +++ b/apps/mobile/src/features/threads/FileChangeDiffText.tsx @@ -0,0 +1,65 @@ +import { toolCallDiff } from "@t3tools/client-runtime/work-log/file-change-diff"; +import type { OrchestrationV2TurnItem } from "@t3tools/contracts"; +import { Text, View } from "react-native"; + +import { patchLines, type PatchLineKind } from "../../lib/patchLines"; + +// Nested Text spans stay cheap to lay out; a full stored diff (32 KB) can reach a thousand lines. +const MAX_DIFF_LINES = 400; + +const LINE_CLASS: Record = { + header: "text-foreground-subtle", + hunk: "text-foreground-subtle", + addition: "text-adaptive-emerald-600-400", + deletion: "text-adaptive-rose-600-400", + context: "text-foreground-muted", +}; + +const monoClassName = "font-mono text-2xs leading-normal"; + +export function FileChangeDiffText(props: { + readonly item: Extract; +}) { + const diff = toolCallDiff(props.item); + const shown = diff.patch?.trim() ? patchLines(diff.patch, MAX_DIFF_LINES) : null; + if (shown === null && diff.content.length === 0) { + return ( + + No diff recorded. + + ); + } + const notes = [ + shown && shown.hiddenCount > 0 ? `${shown.hiddenCount} more lines not shown.` : null, + diff.truncated ? "The recorded change was truncated." : null, + ].filter((note) => note !== null); + return ( + + {shown ? ( + + {shown.lines.map((line, index) => ( + /* oxlint-disable-next-line react/no-array-index-key -- Diff lines are stateless positions. */ + + {index > 0 ? "\n" : ""} + {line.text} + + ))} + + ) : ( + diff.content.map(({ label, text }) => ( + + {label} + + {text === "" ? "Empty content." : text} + + + )) + )} + {notes.map((note) => ( + + {note} + + ))} + + ); +} diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 0ff0271f44fb2..cb9cef8b8b4c6 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -65,6 +65,7 @@ import { cn } from "../../lib/cn"; import { THREAD_WORK_ROW_MIN_HEIGHT, type deriveThreadWorkLogSizing } from "../../lib/layout"; import { formatItemFullDetail, + turnItemShowsFileDiff, type ThreadFeedActivity, workEntryRowLabel, } from "../../lib/threadActivity"; @@ -91,6 +92,7 @@ import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText" import type { FilePreviewSource } from "../../components/FilePreviewModal"; import { FilePreviewGallery } from "../../components/FilePreviewGallery"; import { ThreadMarkdownImage } from "./ThreadMarkdownImage"; +import { FileChangeDiffText } from "./FileChangeDiffText"; import Animated, { FadeIn, FadeOut, @@ -1030,9 +1032,12 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( call && shownItem.type === "command_execution" && shownItem.exitCode ? shownItem.exitCode : null; + const showsFileDiff = turnItemShowsFileDiff(row.projectedItem.item); + const fileDiffItem = + expanded && showsFileDiff && fetchedItem?.type === "file_change" ? fetchedItem : null; const fullDetail = expanded && !reasoning && !call - ? fetchedItem && !isRead + ? fetchedItem && !isRead && !showsFileDiff ? formatItemFullDetail(row.projectedItem, fetchedItem) : row.getFullDetail() : null; @@ -1043,16 +1048,20 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( ? null : shownItem.type === "file_search" || shownItem.type === "web_search" ? turnItemOutputText(shownItem) - : fetchedItem - ? (turnItemOutputText(fetchedItem) ?? - (outputImages.length > 0 || viewedImagePath ? null : "No output.")) - : fetchedDetail.error - ? `Couldn't load output: ${fetchedDetail.error}` - : row.fetchesDetail - ? fetchedDetail.data - ? "Output is no longer available." - : "Loading output…" - : null; + : showsFileDiff && fetchedItem + ? null + : fetchedItem + ? (turnItemOutputText(fetchedItem) ?? + (outputImages.length > 0 || viewedImagePath ? null : "No output.")) + : fetchedDetail.error + ? `Couldn't load output: ${fetchedDetail.error}` + : row.fetchesDetail + ? fetchedDetail.data + ? "Output is no longer available." + : showsFileDiff + ? "Loading diff…" + : "Loading output…" + : null; const exitLine = failedExitCode === null ? null : ( @@ -1203,6 +1212,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( {expanded && (reasoning || fullDetail || + fileDiffItem || call || fetchedOutput || viewedImagePath || @@ -1303,6 +1313,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( {fetchedOutput} ) : null} + {fileDiffItem ? : null} {streamsOutput ? null : exitLine} {streamsOutput ? ( diff --git a/apps/mobile/src/lib/patchLines.test.ts b/apps/mobile/src/lib/patchLines.test.ts new file mode 100644 index 0000000000000..6417c7ddfce8e --- /dev/null +++ b/apps/mobile/src/lib/patchLines.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { patchLines } from "./patchLines"; + +const kinds = (patch: string, maxLines = 100) => + patchLines(patch, maxLines).lines.map((line) => line.kind); + +describe("patchLines", () => { + it("ends a hunk by its counts, so removed lines that look like headers stay deletions", () => { + const patch = [ + "--- a/a.md", + "+++ b/a.md", + "@@ -1,2 +1,1 @@", + "--- not a header", + " kept", + "--- a/b.md", + "+++ b/b.md", + "@@ -1 +1 @@", + "-old", + "+new", + "\\ No newline at end of file", + "", + ].join("\n"); + expect(kinds(patch)).toEqual([ + "header", + "header", + "hunk", + "deletion", + "context", + "header", + "header", + "hunk", + "deletion", + "addition", + "context", + ]); + }); + + it("classifies hunks without ranges until the next hunk or file", () => { + expect(kinds("@@\n-a\n+b\n c\n@@\n+d\ndiff --git a/x b/x\n")).toEqual([ + "hunk", + "deletion", + "addition", + "context", + "hunk", + "addition", + "header", + ]); + }); + + it("caps the rendered lines and reports how many were hidden", () => { + const patch = `@@ -0,0 +1,5 @@\n${["a", "b", "c", "d", "e"].map((line) => `+${line}`).join("\n")}\n`; + const result = patchLines(patch, 3); + expect(result.lines.map((line) => line.text)).toEqual(["@@ -0,0 +1,5 @@", "+a", "+b"]); + expect(result.hiddenCount).toBe(3); + }); +}); diff --git a/apps/mobile/src/lib/patchLines.ts b/apps/mobile/src/lib/patchLines.ts new file mode 100644 index 0000000000000..8a418bcd3e98d --- /dev/null +++ b/apps/mobile/src/lib/patchLines.ts @@ -0,0 +1,55 @@ +export type PatchLineKind = "header" | "hunk" | "addition" | "deletion" | "context"; + +export interface PatchLine { + readonly kind: PatchLineKind; + readonly text: string; +} + +const HUNK_HEADER = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/; + +/** + * Classifies unified-diff lines for plain-text rendering. Hunk line counts decide where a hunk + * ends, so a removed line that reads `-- x` is not mistaken for the next file's `--- x` header. + */ +export function patchLines( + patch: string, + maxLines: number, +): { readonly lines: ReadonlyArray; readonly hiddenCount: number } { + const all = (patch.endsWith("\n") ? patch.slice(0, -1) : patch).split("\n"); + const lines: PatchLine[] = []; + let oldLeft = 0; + let newLeft = 0; + for (const text of all.slice(0, maxLines)) { + // Hunks without ranges carry no counts; they run until the next hunk or file header. + const unbounded = oldLeft === Infinity; + if (unbounded && (text.startsWith("@@") || text.startsWith("diff --git "))) { + oldLeft = 0; + newLeft = 0; + } + if (oldLeft > 0 || newLeft > 0) { + if (text.startsWith("+")) { + lines.push({ kind: "addition", text }); + newLeft -= 1; + } else if (text.startsWith("-")) { + lines.push({ kind: "deletion", text }); + oldLeft -= 1; + } else { + lines.push({ kind: "context", text }); + if (!text.startsWith("\\")) { + oldLeft -= 1; + newLeft -= 1; + } + } + continue; + } + if (text.startsWith("@@")) { + const match = HUNK_HEADER.exec(text); + oldLeft = match ? Number(match[1] ?? 1) : Infinity; + newLeft = match ? Number(match[2] ?? 1) : Infinity; + lines.push({ kind: "hunk", text }); + continue; + } + lines.push({ kind: text.startsWith("\\") ? "context" : "header", text }); + } + return { lines, hiddenCount: Math.max(0, all.length - maxLines) }; +} diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 69ef04feb4f2f..e5497951c45a6 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -33,6 +33,7 @@ import { type ThreadFeedCache, type ThreadFeedEntry, type ThreadFeedLatestRun, + turnItemShowsFileDiff, } from "./threadActivity"; const threadId = ThreadId.make("thread-1"); @@ -597,6 +598,39 @@ describe("buildThreadFeed", () => { expect(items[0]).toMatchObject({ output: rawOutput }); }); + it("expands a Claude Edit to its fetched diff, not the item's JSON", () => { + // The wire form of a completed Claude Edit: the server withholds the patch and marks it. + const edit: OrchestrationV2TurnItem = { + ...base("item-claude-edit", "2026-06-20T00:00:04.000Z", 3), + providerThreadId: ProviderThreadId.make("claude-session"), + providerTurnId: ProviderTurnId.make("claude-turn"), + nativeItemRef: { + driver: ProviderDriverKind.make("claude"), + nativeId: "toolu_01EditPatch", + strength: "strong", + }, + title: "Edit", + type: "file_change", + fileName: "/tmp/scratch/greet.ts", + diffOmitted: true, + }; + const [activity] = buildThreadFeed([projected(edit, 0)]).flatMap((entry) => + entry.type === "activity-group" ? entry.activities : [], + ); + expect(activity).toMatchObject({ canExpand: true, fetchesDetail: true }); + expect(turnItemShowsFileDiff(edit)).toBe(true); + expect(activity?.getFullDetail()).toBeNull(); + expect(activity?.getCopyText()).toContain("greet.ts"); + + // Without a recorded diff (or from an older server) the row keeps today's detail. + const { diffOmitted: _omitted, ...unrecorded } = edit; + const [plain] = buildThreadFeed([projected(unrecorded, 0)]).flatMap((entry) => + entry.type === "activity-group" ? entry.activities : [], + ); + expect(plain?.fetchesDetail).toBe(false); + expect(plain?.getFullDetail()).toContain('"fileName": "/tmp/scratch/greet.ts"'); + }); + it("counts every file of a multi-file patch", () => { const item: OrchestrationV2TurnItem = { ...base("multi-file-change", "2026-06-20T00:00:04.000Z", 3), diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 8cb5ccb043794..2d791215618e9 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -787,6 +787,11 @@ export function formatItemFullDetail( ); } +/** A file change whose recorded diff the expanded row fetches and renders as its body. */ +export function turnItemShowsFileDiff(item: OrchestrationV2TurnItem): boolean { + return item.type === "file_change" && item.status !== "failed" && turnItemNeedsDetailFetch(item); +} + function toFeedActivity( row: OrchestrationV2ProjectedTurnItem, attemptId: RunAttemptId | null, @@ -808,7 +813,10 @@ function toFeedActivity( ? readPaths.join("\n") || null : item.type === "notification" ? item.detail?.trim() || null - : formatItemFullDetail(row, item), + : // The expanded row shows the fetched diff instead, as web does. + turnItemShowsFileDiff(item) + ? null + : formatItemFullDetail(row, item), ); const getCopyText = memoizeValue(() => item.type === "proposed_plan" diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.ts index cfd8ca1363fa4..94029f76600d1 100644 --- a/apps/server/src/guest/GuestShareService.test.ts +++ b/apps/server/src/guest/GuestShareService.test.ts @@ -513,7 +513,7 @@ it.effect("gives the guest a command's detail and output, but no file diffs", () ] as const) { const change = (yield* guestShares.item(session, id)).item; assert.deepInclude(change, { type: "file_change", fileName }); - assert.doesNotHaveAnyKeys(change, ["diffStr", "oldStr", "newStr"]); + assert.doesNotHaveAnyKeys(change, ["diffStr", "oldStr", "newStr", "diffOmitted"]); } const frames = Array.from( yield* Stream.runCollect(yield* guestShares.commandOutput(session, command)), @@ -534,6 +534,60 @@ it.effect("gives the guest a command's detail and output, but no file diffs", () }).pipe(Effect.provide(layerTest)), ); +it.effect("streams file changes to guests without a diff to fetch", () => + Effect.gen(function* () { + const { orchestrator, guestShares, credential } = yield* shareThread; + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" }); + yield* writeItem("item:before", { + type: "file_change", + status: "completed", + fileName: "src/auth.ts", + diffStr: "-const token = 1;\n+const token = 2;\n", + }); + const events = yield* guestShares.stream(session); + yield* writeItem("item:after", { + type: "file_change", + status: "completed", + fileName: "src/config.ts", + oldStr: "", + newStr: "export const key = 1;\n", + }); + yield* writeItem("item:failed", { + type: "file_change", + status: "failed", + fileName: "src/missing.ts", + diffStr: "String to replace not found", + }); + yield* orchestrator.dispatch({ + type: "thread.guest-share.close", + commandId: CommandId.make("close-after-file-changes"), + threadId, + }); + const received = Array.from(yield* Stream.runCollect(events)); + const fileChanges = received.flatMap((event) => + event.type !== "thread" + ? [] + : event.item.kind === "snapshot" + ? event.item.projection.visibleTurnItems.map((row) => row.item) + : event.item.kind === "event" && event.item.event.type === "turn-item.updated" + ? [event.item.event.payload] + : [], + ); + const byId = new Map( + fileChanges.flatMap((item) => (item.type === "file_change" ? [[item.id, item]] : [])), + ); + // The owner's wire marks these diffOmitted; a guest's row must not offer to fetch them. + for (const id of ["item:before", "item:after"]) { + const change = byId.get(TurnItemId.make(id)); + assert.isDefined(change); + assert.doesNotHaveAnyKeys(change, ["diffOmitted", "diffStr", "oldStr", "newStr"]); + } + assert.deepInclude(byId.get(TurnItemId.make("item:failed")), { + diffStr: "String to replace not found", + }); + }).pipe(Effect.provide(layerTest)), +); + it.effect("pages the guest back through turns older than the stream's snapshot", () => Effect.gen(function* () { const { guestShares, credential } = yield* shareThread; @@ -575,8 +629,13 @@ it.effect("pages the guest back through turns older than the stream's snapshot", text: `![Old](${shot})`, streaming: false, }), + turnItem("item:old-edit", 2, { + type: "file_change", + fileName: "src/auth.ts", + diffStr: "@@ -1 +1 @@\n-before\n+after\n", + }), ...Array.from({ length: 30 }, (_, index) => - turnItem(`item:ask-${index}`, index + 2, { + turnItem(`item:ask-${index}`, index + 3, { type: "user_message", text: `Ask ${index}`, createdBy: "user", @@ -597,6 +656,7 @@ it.effect("pages the guest back through turns older than the stream's snapshot", const ids = (rows: ReadonlyArray<{ readonly sourceItemId: string }>) => rows.map((row) => row.sourceItemId); assert.notInclude(ids(opening.item.projection.visibleTurnItems), "item:old-image"); + assert.notInclude(ids(opening.item.projection.visibleTurnItems), "item:old-edit"); let cursor = opening.item.historyCursor ?? null; assert.isNotNull(cursor); // The page has not shown the old reply yet, so its image does not load. @@ -608,9 +668,15 @@ it.effect("pages the guest back through turns older than the stream's snapshot", while (cursor !== null) { const page: OrchestrationV2ThreadHistoryPage = yield* guestShares.history(session, cursor); older.push(...ids(page.items)); + for (const row of page.items) { + if (row.item.type === "file_change") { + assert.doesNotHaveAnyKeys(row.item, ["diffOmitted", "diffStr", "oldStr", "newStr"]); + } + } cursor = page.hasMoreHistory ? page.nextCursor : null; } assert.include(older, "item:old-image"); + assert.include(older, "item:old-edit"); assert.deepStrictEqual(yield* guestShares.media(session, shot), { path: shot, mimeType: "image/png", diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index fd9a0efc3b66b..ddee3db05719e 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -218,6 +218,17 @@ interface SentReply { sources?: ReadonlyArray; } +/** + * Guests never see diffs, so their file changes carry neither a diff nor the `diffOmitted` + * marker that would make the guest's row fetch one. Live events arrive already projected for + * the wire, so both forms are stripped. A failed edit keeps its error text. + */ +function withoutFileDiff(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem { + if (item.type !== "file_change" || item.status === "failed") return item; + const { diffStr: _diff, oldStr: _old, newStr: _new, diffOmitted: _omitted, ...withheld } = item; + return withheld; +} + /** The thread record an event carries, for the share and the view. */ const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | null => { switch (event.type) { @@ -560,7 +571,11 @@ const make = Effect.gen(function* () { Stream.map((stored) => ({ kind: "event" as const, sequence: stored.sequence, - event: projectDomainEventForWire(stored.event), + event: projectDomainEventForWire( + stored.event.type === "turn-item.updated" + ? { ...stored.event, payload: withoutFileDiff(stored.event.payload) } + : stored.event, + ), })), // Ending the source here flushes what the coalescer holds, so `ended` is not held back. Stream.takeUntil((item) => endsShare(item.event)), @@ -588,7 +603,14 @@ const make = Effect.gen(function* () { ); const openingSnapshot = buildBoundedThreadStreamSnapshot({ snapshotSequence: snapshot.snapshotSequence, - projection: snapshot.projection, + projection: { + ...snapshot.projection, + turnItems: snapshot.projection.turnItems.map(withoutFileDiff), + visibleTurnItems: snapshot.projection.visibleTurnItems.map((row) => ({ + ...row, + item: withoutFileDiff(row.item), + })), + }, }); const opening: ReadonlyArray = [ { type: "view", view: initialView }, @@ -665,7 +687,9 @@ const make = Effect.gen(function* () { const { item } = yield* threadItem(session, itemId); return { item: - item.type === "file_change" ? projectTurnItemForWire(item) : projectTurnItemForDetail(item), + item.type === "file_change" + ? projectTurnItemForWire(withoutFileDiff(item)) + : projectTurnItemForDetail(item), }; }); @@ -681,7 +705,10 @@ const make = Effect.gen(function* () { share.id, page.items.map((row) => row.item), ); - return page; + return { + ...page, + items: page.items.map((row) => ({ ...row, item: withoutFileDiff(row.item) })), + }; }); const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* ( diff --git a/apps/server/src/orchestration-v2/WireProjection.test.ts b/apps/server/src/orchestration-v2/WireProjection.test.ts index 95d3fcde7f401..5aa29afe27ed8 100644 --- a/apps/server/src/orchestration-v2/WireProjection.test.ts +++ b/apps/server/src/orchestration-v2/WireProjection.test.ts @@ -298,8 +298,14 @@ describe("orchestration V2 wire projection", () => { expect(projected).not.toHaveProperty("oldStr"); expect(projected).not.toHaveProperty("newStr"); expect(projected).toMatchObject({ fileName: "src/main.ts", additions: 3, deletions: 1 }); + // Clients fetch the withheld diff on expand; re-projection keeps the marker. + expect(projected).toMatchObject({ diffOmitted: true }); + expect(projectTurnItemForWire(projected)).toEqual(projected); expect(item.diffStr).toBe("+new code"); expect(projectTurnItemForDetail(item)).toMatchObject({ diffStr: "+new code" }); + expect(projectTurnItemForDetail({ ...item, diffOmitted: true })).not.toHaveProperty( + "diffOmitted", + ); expect(projectTurnItemForDetail(item)).not.toHaveProperty("oldStr"); expect(projectTurnItemForDetail(item)).not.toHaveProperty("newStr"); const { diffStr: _diff, ...contentOnly } = item; @@ -308,6 +314,12 @@ describe("orchestration V2 wire projection", () => { newStr: "new code", }); expect(projectTurnItemForWire(contentOnly)).not.toHaveProperty("newStr"); + expect(projectTurnItemForWire(contentOnly)).toMatchObject({ diffOmitted: true }); + const { diffStr: _noDiff, oldStr: _noOld, newStr: _noNew, ...nothingRecorded } = item; + expect(projectTurnItemForWire(nothingRecorded)).not.toHaveProperty("diffOmitted"); + expect(projectTurnItemForWire({ ...nothingRecorded, diffStr: " \n" })).not.toHaveProperty( + "diffOmitted", + ); const failed = projectTurnItemForWire({ ...item, status: "failed", @@ -315,6 +327,7 @@ describe("orchestration V2 wire projection", () => { }); expect(failed).toMatchObject({ diffStr: "String to replace not found" }); expect(failed).not.toHaveProperty("newStr"); + expect(failed).not.toHaveProperty("diffOmitted"); }); it("retains only result identities and failure metadata in live tool events", () => { diff --git a/apps/server/src/orchestration-v2/WireProjection.ts b/apps/server/src/orchestration-v2/WireProjection.ts index c4916546cf8e1..27447fade9791 100644 --- a/apps/server/src/orchestration-v2/WireProjection.ts +++ b/apps/server/src/orchestration-v2/WireProjection.ts @@ -176,10 +176,18 @@ export function projectTurnItemForWire(item: OrchestrationV2TurnItem): Orchestra }; } case "file_change": { - const { diffStr, oldStr: _old, newStr: _new, ...projected } = item; - return item.status === "failed" && diffStr?.trim() - ? { ...projected, diffStr: truncateDetail(diffStr) } - : projected; + const { diffStr, oldStr, newStr, ...projected } = item; + // A failed edit's diffStr holds the provider's error, not a diff. + if (item.status === "failed") { + return diffStr?.trim() ? { ...projected, diffStr: truncateDetail(diffStr) } : projected; + } + // Re-projecting an already projected item must keep the marker. + const recorded = + item.diffOmitted === true || + Boolean(diffStr?.trim()) || + oldStr !== undefined || + newStr !== undefined; + return recorded ? { ...projected, diffOmitted: true } : projected; } case "subagent": return { @@ -260,19 +268,20 @@ export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): Orchest result: item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null), }; - case "file_change": + case "file_change": { + const { diffStr, oldStr, newStr, diffOmitted: _omitted, ...projected } = item; + const contentOnly = !diffStr?.trim(); return { - ...projectTurnItemForWire(item), - ...(item.diffStr === undefined - ? {} - : { diffStr: truncateDetail(item.diffStr, MAX_ON_DEMAND_BYTES) }), - ...(!item.diffStr?.trim() && item.oldStr !== undefined - ? { oldStr: truncateDetail(item.oldStr, MAX_ON_DEMAND_BYTES) } + ...projected, + ...(diffStr === undefined ? {} : { diffStr: truncateDetail(diffStr, MAX_ON_DEMAND_BYTES) }), + ...(contentOnly && oldStr !== undefined + ? { oldStr: truncateDetail(oldStr, MAX_ON_DEMAND_BYTES) } : {}), - ...(!item.diffStr?.trim() && item.newStr !== undefined - ? { newStr: truncateDetail(item.newStr, MAX_ON_DEMAND_BYTES) } + ...(contentOnly && newStr !== undefined + ? { newStr: truncateDetail(newStr, MAX_ON_DEMAND_BYTES) } : {}), }; + } case "handoff": return projectTurnItemForWire(item); default: diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 0f1d1e9e28379..91a421ff25728 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -27,7 +27,7 @@ import { useOpenInPreferredEditor } from "../editorPreferences"; import { useFileContextMenuHandler } from "../fileContextMenu"; import { type DraftId } from "../composerDraftStore"; import { openDiffFilePrimaryAction } from "../diffFileActions"; -import { toolCallDiff } from "../lib/toolCallDiff"; +import { toolCallDiff } from "@t3tools/client-runtime/work-log/file-change-diff"; import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries"; import { revisionedQuery } from "~/state/revisionedQuery"; import { cn } from "~/lib/utils"; diff --git a/apps/web/src/components/chat/FileChangeInlineDiff.tsx b/apps/web/src/components/chat/FileChangeInlineDiff.tsx new file mode 100644 index 0000000000000..f3917907ef274 --- /dev/null +++ b/apps/web/src/components/chat/FileChangeInlineDiff.tsx @@ -0,0 +1,68 @@ +import { FileDiff } from "@pierre/diffs/react"; +import { toolCallDiff } from "@t3tools/client-runtime/work-log/file-change-diff"; +import type { OrchestrationV2TurnItem } from "@t3tools/contracts"; + +import { useRenderedAppearance } from "../../hooks/useTheme"; +import { + getRenderablePatch, + resolveDiffThemeName, + resolveFileDiffPath, +} from "../../lib/diffRendering"; +import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting"; +import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; + +type FileChange = Extract; + +const preClassName = + "max-h-80 overflow-auto rounded-md border border-border/60 bg-muted/20 p-2 font-mono text-(length:--font-size-code,var(--text-2xs)) whitespace-pre-wrap break-words text-muted-foreground select-text"; + +export function FileChangeInlineDiff(props: { + readonly item: FileChange; + readonly pending: boolean; + readonly error: string | null; +}) { + const appearance = useRenderedAppearance(); + if (props.pending) return

Loading diff…

; + if (props.error) + return

Couldn't load diff: {props.error}

; + const diff = toolCallDiff(props.item); + const renderable = getRenderablePatch(diff.patch, `tool-call-inline:${appearance}`); + if (renderable === null && diff.content.length === 0) return null; + return ( +
+ {renderable?.kind === "files" ? ( +
+ + {renderable.files.map((fileDiff) => ( + + ))} + +
+ ) : renderable?.kind === "raw" ? ( +
{renderable.text}
+ ) : ( + diff.content.map(({ label, text }) => ( +
+

{label}

+
{text === "" ? "Empty content." : text}
+
+ )) + )} + {diff.truncated ? ( +

The recorded change was truncated.

+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsx index ee6072b926b7e..97ad42fa9f974 100644 --- a/apps/web/src/components/chat/V2ItemInspector.tsx +++ b/apps/web/src/components/chat/V2ItemInspector.tsx @@ -23,6 +23,7 @@ import ChatMarkdown from "../ChatMarkdown"; import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia"; import { RenderErrorBoundary } from "../RenderErrorBoundary"; import { CommandOutputPanel, useCommandOutputStreaming } from "./CommandOutputPanel"; +import { FileChangeInlineDiff } from "./FileChangeInlineDiff"; import { resolveExternalWebLinkHref } from "./externalLinkContextMenu"; import type { ExpandedImagePreview } from "./ExpandedImagePreview"; import { ShellCommandBlock } from "./ShellCommandBlock"; @@ -306,9 +307,17 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec ) : null} - {item.status === "failed" && item.diffStr?.trim() ? ( - - ) : null} + {item.status === "failed" ? ( + item.diffStr?.trim() ? ( + + ) : null + ) : ( + + )} {item.changes !== undefined && item.changes.length > 0 ? (
    {item.changes.map((change) => ( diff --git a/docs/user/activity-log.md b/docs/user/activity-log.md index 0aad505e0faed..8a53989684845 100644 --- a/docs/user/activity-log.md +++ b/docs/user/activity-log.md @@ -2,8 +2,9 @@ On web and desktop, consecutive tool calls appear as an expandable summary. Open it to inspect commands, tool inputs, status, and exit codes. Expand a tool call to see its output. A running -command's output updates live, and long output shows only its most recent part. Use **Open diff** on -a file change to review its contents. +command's output updates live, and long output shows only its most recent part. Expand a file change +to see the diff the agent recorded for that edit, also on mobile. **Open diff** shows the same edit in +the diff panel. Neither needs a Git repository. T3 Orchestrator summaries describe the actions taken, such as **Ran 2 commands and sent messages to 3 threads**. Repeated messages to the same destinations show both counts: **Sent 5 messages to diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 6fd4550d93f31..b7b81ff93ce65 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -391,6 +391,10 @@ "types": "./src/work-log/itemDetail.ts", "default": "./src/work-log/itemDetail.ts" }, + "./work-log/file-change-diff": { + "types": "./src/work-log/fileChangeDiff.ts", + "default": "./src/work-log/fileChangeDiff.ts" + }, "./work-log/presentation": { "types": "./src/work-log/presentation.ts", "default": "./src/work-log/presentation.ts" diff --git a/packages/client-runtime/src/platform/orchestrationCache.ts b/packages/client-runtime/src/platform/orchestrationCache.ts index e7800e20bd33a..712df38d8f18b 100644 --- a/packages/client-runtime/src/platform/orchestrationCache.ts +++ b/packages/client-runtime/src/platform/orchestrationCache.ts @@ -10,8 +10,11 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; export const ORCHESTRATION_CACHE_SCHEMA_VERSION = 3 as const; -// Older caches may contain human turns that bypassed server history budgets. -export const ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION = 5 as const; +// Older caches may contain human turns that bypassed server history budgets. 8 drops records an +// older client wrote without file changes' `diffOmitted`; a resumed thread replays only newer +// events, so those rows would never fetch their diff. 6 and 7 are compact record versions +// (threadCacheEncoding.ts): skipping them keeps mobile from reading a compact record as a full one. +export const ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION = 8 as const; export const StoredOrchestrationShellSnapshot = Schema.Struct({ schemaVersion: Schema.Literal(ORCHESTRATION_CACHE_SCHEMA_VERSION), diff --git a/packages/client-runtime/src/platform/threadCacheEncoding.ts b/packages/client-runtime/src/platform/threadCacheEncoding.ts index b7c233942de43..304ee7b4f4279 100644 --- a/packages/client-runtime/src/platform/threadCacheEncoding.ts +++ b/packages/client-runtime/src/platform/threadCacheEncoding.ts @@ -8,8 +8,9 @@ import * as Schema from "effect/Schema"; import { StoredOrchestrationThreadSnapshot } from "./orchestrationCache.ts"; -// Keep the full format for web/desktop; older clients discard compact records. -export const COMPACT_THREAD_CACHE_SCHEMA_VERSION = 6 as const; +// Keep the full format for web/desktop; older clients discard compact records. 7 drops records +// written without file changes' `diffOmitted` (see ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION). +export const COMPACT_THREAD_CACHE_SCHEMA_VERSION = 7 as const; const StoredCompactThreadSnapshot = StoredOrchestrationThreadSnapshot.mapFields((fields) => ({ ...fields, diff --git a/apps/web/src/lib/toolCallDiff.test.ts b/packages/client-runtime/src/work-log/fileChangeDiff.test.ts similarity index 81% rename from apps/web/src/lib/toolCallDiff.test.ts rename to packages/client-runtime/src/work-log/fileChangeDiff.test.ts index 8efd08ddfa38e..68286c6646e8b 100644 --- a/apps/web/src/lib/toolCallDiff.test.ts +++ b/packages/client-runtime/src/work-log/fileChangeDiff.test.ts @@ -1,6 +1,10 @@ +import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; import { describe, expect, it } from "vite-plus/test"; -import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering"; -import { toolCallDiff } from "./toolCallDiff"; +import { toolCallDiff } from "./fileChangeDiff.ts"; + +function renderedFiles(patch: string | undefined) { + return patch?.trim() ? parsePatchFiles(patch).flatMap((parsed) => parsed.files) : []; +} describe("toolCallDiff", () => { it("renders recorded hunks without reading a repository, including renamed paths", () => { @@ -13,13 +17,11 @@ describe("toolCallDiff", () => { diffStr: "@@ -1 +1 @@\n-before\n+after\n", ...(changes ? { changes } : {}), }); - const rendered = getRenderablePatch(patch); - expect(rendered?.kind).toBe("files"); - if (rendered?.kind !== "files") throw new Error("Expected a file diff"); - expect(rendered.files).toHaveLength(1); - expect(resolveFileDiffPath(rendered.files[0]!)).toBe(changes ? "new.ts" : "old.ts"); - expect(rendered.files[0]!.additionLines.join("")).toContain("after"); - expect(rendered.files[0]!.deletionLines.join("")).toContain("before"); + const files = renderedFiles(patch); + expect(files).toHaveLength(1); + expect(files[0]!.name).toBe(changes ? "new.ts" : "old.ts"); + expect(files[0]!.additionLines.join("")).toContain("after"); + expect(files[0]!.deletionLines.join("")).toContain("before"); } }); @@ -39,17 +41,16 @@ describe("toolCallDiff", () => { ], ] as const) { const recordedContent = `${content}${ending}`; - const rendered = getRenderablePatch( + const files = renderedFiles( toolCallDiff({ fileName: "file with spaces.ts", diffStr: recordedContent, changes: [{ operation, path: "file with spaces.ts" }], }).patch, ); - expect(rendered?.kind).toBe("files"); - if (rendered?.kind !== "files") throw new Error("Expected a file diff"); - expect(resolveFileDiffPath(rendered.files[0]!)).toBe("file with spaces.ts"); - const file = rendered.files[0]!; + expect(files.length).toBeGreaterThan(0); + const file = files[0]!; + expect(file.name ?? file.prevName).toBe("file with spaces.ts"); const lines = content.split("\n").length; expect(file.additionLines).toHaveLength(operation === "add" ? lines : 0); expect(file.deletionLines).toHaveLength(operation === "delete" ? lines : 0); @@ -97,7 +98,7 @@ describe("toolCallDiff", () => { }); expect(diff.truncated).toBe(true); expect(diff.patch).not.toContain("output truncated"); - expect(getRenderablePatch(diff.patch)?.kind).toBe("files"); + expect(renderedFiles(diff.patch)).toHaveLength(1); expect(toolCallDiff({ fileName: "a.ts", newStr: `content${suffix}` })).toMatchObject({ content: [{ label: "Recorded content after", text: "content" }], truncated: true, diff --git a/apps/web/src/lib/toolCallDiff.ts b/packages/client-runtime/src/work-log/fileChangeDiff.ts similarity index 86% rename from apps/web/src/lib/toolCallDiff.ts rename to packages/client-runtime/src/work-log/fileChangeDiff.ts index 2224702601d74..b97ebe28eb83d 100644 --- a/apps/web/src/lib/toolCallDiff.ts +++ b/packages/client-runtime/src/work-log/fileChangeDiff.ts @@ -1,8 +1,17 @@ +import type { FileDiffMetadata } from "@pierre/diffs"; +import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; import type { OrchestrationV2TurnItem } from "@t3tools/contracts"; -import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering"; type FileChange = Extract; +function parsedPatchFiles(patch: string): ReadonlyArray { + try { + return patch.trim() ? parsePatchFiles(patch).flatMap((parsed) => parsed.files) : []; + } catch { + return []; + } +} + function toolCallPatch(item: Pick) { let patch = item.diffStr; if (!patch) return patch; @@ -10,11 +19,11 @@ function toolCallPatch(item: Pick { - const path = resolveFileDiffPath(file).replaceAll("\\", "/"); + files.length > 0 && + files.every((file) => { + const path = (file.name ?? file.prevName ?? "").replaceAll("\\", "/"); return ( file.hunks.length > 0 && item.changes?.some((recorded) => { diff --git a/packages/client-runtime/src/work-log/itemDetail.ts b/packages/client-runtime/src/work-log/itemDetail.ts index 5e16cf538ca98..4606703411759 100644 --- a/packages/client-runtime/src/work-log/itemDetail.ts +++ b/packages/client-runtime/src/work-log/itemDetail.ts @@ -136,6 +136,8 @@ export function turnItemNeedsDetailFetch(item: OrchestrationV2TurnItem): boolean return item.outputOmitted === true; case "dynamic_tool": return item.outputOmitted === true || isSummarizedValue(item.input); + case "file_change": + return item.diffOmitted === true; default: return false; } diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index 29c5f938b5bf0..ee2bbfbb465ef 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -39,7 +39,13 @@ export function toolItemForDisplay(item: OrchestrationV2TurnItem): Orchestration return displayItem; } case "file_change": { - const { diffStr, oldStr: _oldStr, newStr: _newStr, ...displayItem } = item; + const { + diffStr, + oldStr: _oldStr, + newStr: _newStr, + diffOmitted: _diffOmitted, + ...displayItem + } = item; // A failed edit's diffStr holds the provider's error, not a diff. return item.status === "failed" && diffStr?.trim() ? { ...displayItem, diffStr } diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 785f41e3aa0fb..b82fb5fe9e8c9 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1661,6 +1661,8 @@ export const OrchestrationV2TurnItem = Schema.Union([ diffStr: Schema.optional(Schema.String), oldStr: Schema.optional(Schema.String), newStr: Schema.optional(Schema.String), + /** Set on the wire when a recorded diff or file content was withheld; fetch it with getTurnItem. */ + diffOmitted: Schema.optional(Schema.Boolean), changes: Schema.optional(Schema.Array(OrchestrationV2FileChangeDetail)), }), Schema.Struct({ @@ -2494,6 +2496,8 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ diffStr: Schema.optional(Schema.String), oldStr: Schema.optional(Schema.String), newStr: Schema.optional(Schema.String), + /** Set on the wire when a recorded diff or file content was withheld; fetch it with getTurnItem. */ + diffOmitted: Schema.optional(Schema.Boolean), changes: Schema.optional(Schema.Array(OrchestrationV2FileChangeDetail)), }), Schema.Struct({