Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions apps/mobile/src/connection/environment-cache-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
65 changes: 65 additions & 0 deletions apps/mobile/src/features/threads/FileChangeDiffText.tsx
Original file line number Diff line number Diff line change
@@ -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<PatchLineKind, string> = {
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<OrchestrationV2TurnItem, { type: "file_change" }>;
}) {
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 (
<Text className={`mt-1.5 ${monoClassName} italic text-foreground-subtle`}>
No diff recorded.
</Text>
);
}
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 (
<View className="mt-1.5 gap-1.5">
{shown ? (
<Text selectable className={monoClassName}>
{shown.lines.map((line, index) => (
/* oxlint-disable-next-line react/no-array-index-key -- Diff lines are stateless positions. */
<Text key={index} className={LINE_CLASS[line.kind]}>
{index > 0 ? "\n" : ""}
{line.text}
</Text>
))}
</Text>
) : (
diff.content.map(({ label, text }) => (
<View key={label}>
<Text className={`${monoClassName} text-foreground-subtle`}>{label}</Text>
<Text selectable className={`${monoClassName} text-foreground-muted`}>
{text === "" ? "Empty content." : text}
</Text>
</View>
))
)}
{notes.map((note) => (
<Text key={note} className={`${monoClassName} italic text-foreground-subtle`}>
{note}
</Text>
))}
</View>
);
}
33 changes: 22 additions & 11 deletions apps/mobile/src/features/threads/thread-work-log.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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,
Expand Down Expand Up @@ -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;
Expand All @@ -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 : (
<Text className="mt-1.5 font-mono text-2xs leading-normal text-danger-foreground">
Expand Down Expand Up @@ -1203,6 +1212,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
{expanded &&
(reasoning ||
fullDetail ||
fileDiffItem ||
call ||
fetchedOutput ||
viewedImagePath ||
Expand Down Expand Up @@ -1303,6 +1313,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
{fetchedOutput}
</Text>
) : null}
{fileDiffItem ? <FileChangeDiffText item={fileDiffItem} /> : null}
{streamsOutput ? null : exitLine}
</ScrollView>
{streamsOutput ? (
Expand Down
57 changes: 57 additions & 0 deletions apps/mobile/src/lib/patchLines.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
55 changes: 55 additions & 0 deletions apps/mobile/src/lib/patchLines.ts
Original file line number Diff line number Diff line change
@@ -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<PatchLine>; 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) };
}
34 changes: 34 additions & 0 deletions apps/mobile/src/lib/threadActivity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
type ThreadFeedCache,
type ThreadFeedEntry,
type ThreadFeedLatestRun,
turnItemShowsFileDiff,
} from "./threadActivity";

const threadId = ThreadId.make("thread-1");
Expand Down Expand Up @@ -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),
Expand Down
10 changes: 9 additions & 1 deletion apps/mobile/src/lib/threadActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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"
Expand Down
Loading
Loading