feat(web): collapse large git diffs by default to make chat more readable (#4409)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-07-23 18:06:04 -07:00
1 parent 67a7b1a1d3
commit 51672b6ecb
9 files changed
+455 -188

No files matched your search

@@ -10,23 +10,86 @@ describe("ChangedFilesCard", () => {
<ChangedFilesCard
turnId={TurnId.make("turn-1")}
files={[{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }]}
expanded
showCompactPreview={false}
allDirectoriesExpanded
resolvedTheme="light"
onExpandedChange={() => {}}
onToggleAllDirectories={() => {}}
onOpenTurnDiff={() => {}}
/>,
);
expect(markup).toContain('class="sticky top-0 z-10');
expect(markup).not.toContain("self-start");
expect(markup).toContain('data-changed-files-state="expanded"');
expect(markup).toContain('aria-expanded="true"');
expect(markup).toContain("whitespace-nowrap");
expect(markup).toContain("!size-[22px]");
expect(markup).toContain("size-3");
expect(markup).toContain('aria-label="Collapse all"');
expect(markup).toContain('aria-label="View diff"');
expect(markup).toContain('aria-label="Collapse all folders"');
expect(markup).toContain('aria-label="Open diff"');
expect(markup).toContain('role="group" aria-label="2 additions, 1 deletions"');
expect(markup).toContain("1 changed file");
expect(markup).not.toContain("1 changed files");
});
it("renders a scope and representative-file preview for a large latest change", () => {
const markup = renderToStaticMarkup(
<ChangedFilesCard
turnId={TurnId.make("turn-1")}
files={[
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 },
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 30, deletions: 2 },
{
path: "packages/shared/src/git.ts",
kind: "modified",
additions: 15,
deletions: 4,
},
{ path: "README.md", kind: "modified", additions: 3, deletions: 0 },
]}
expanded={false}
showCompactPreview
allDirectoriesExpanded={false}
resolvedTheme="light"
onExpandedChange={() => {}}
onToggleAllDirectories={() => {}}
onOpenTurnDiff={() => {}}
/>,
);
expect(markup).toContain('data-changed-files-state="preview"');
expect(markup).toContain('aria-expanded="false"');
expect(markup).toContain("apps");
expect(markup).toContain("2 files");
expect(markup).toContain("packages");
expect(markup).toContain("root");
expect(markup).toContain("App.tsx");
expect(markup).toContain("git.ts");
expect(markup).toContain("README.md");
expect(markup).toContain("Show all 4 files");
expect(markup).not.toContain("App.test.tsx");
});
it("keeps older collapsed changes to a one-line receipt", () => {
const markup = renderToStaticMarkup(
<ChangedFilesCard
turnId={TurnId.make("turn-1")}
files={[{ path: "apps/web/src/App.tsx", kind: "modified", additions: 120, deletions: 20 }]}
expanded={false}
showCompactPreview={false}
allDirectoriesExpanded={false}
resolvedTheme="light"
onExpandedChange={() => {}}
onToggleAllDirectories={() => {}}
onOpenTurnDiff={() => {}}
/>,
);
expect(markup).toContain('data-changed-files-state="collapsed"');
expect(markup).toContain("1 changed file");
expect(markup).not.toContain("Show all");
expect(markup).not.toContain("App.tsx");
});
});
describe("ChangedFilesTree", () => {
+139 -50
View File
@@ -19,95 +19,184 @@ import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { PierreEntryIcon } from "./PierreEntryIcon";
import { Button } from "../ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
changedFileName,
selectChangedFilePreview,
summarizeChangedFileScopes,
} from "./changedFilesPresentation";
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
turnId: TurnId;
files: ReadonlyArray<TurnDiffFileChange>;
expanded: boolean;
showCompactPreview: boolean;
allDirectoriesExpanded: boolean;
resolvedTheme: "light" | "dark";
onExpandedChange: (expanded: boolean) => void;
onToggleAllDirectories: () => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const {
turnId,
files,
expanded,
showCompactPreview,
allDirectoriesExpanded,
resolvedTheme,
onExpandedChange,
onToggleAllDirectories,
onOpenTurnDiff,
} = props;
const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);
const scopeSummary = useMemo(() => summarizeChangedFileScopes(files), [files]);
const previewFiles = useMemo(() => selectChangedFilePreview(files), [files]);
const compactPreviewVisible = showCompactPreview && !expanded;
return (
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
<div className="sticky top-0 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{files.length} changed file{files.length === 1 ? "" : "s"}
<div
className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
data-changed-files-state={
expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
}
>
<div
className={cn(
"flex items-center justify-between gap-2 rounded-xl px-1",
expanded &&
"sticky top-2 z-10 mb-2 bg-secondary dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]",
)}
>
<button
type="button"
aria-expanded={expanded}
data-scroll-anchor-ignore
className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onExpandedChange(!expanded)}
>
<ChevronRightIcon
aria-hidden="true"
className={cn(
"size-3.5 shrink-0 text-muted-foreground transition-transform",
expanded && "rotate-90",
)}
/>
<span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{files.length} changed file{files.length === 1 ? "" : "s"}
</span>
{hasNonZeroStat(summaryStat) && (
<DiffStatLabel
additions={summaryStat.additions}
className="text-xs leading-4"
deletions={summaryStat.deletions}
layout="inline"
/>
)}
</span>
{hasNonZeroStat(summaryStat) && (
<DiffStatLabel
additions={summaryStat.additions}
className="text-xs leading-4"
deletions={summaryStat.deletions}
layout="inline"
/>
)}
</p>
<span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
{expanded ? "Hide files" : "Show files"}
</span>
</button>
<div className="flex items-center gap-1.5">
{expanded ? (
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
className="!size-[22px]"
aria-label={
allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"
}
data-scroll-anchor-ignore
onClick={onToggleAllDirectories}
/>
}
>
{allDirectoriesExpanded ? (
<ChevronsDownUpIcon className="size-3" />
) : (
<ChevronsUpDownIcon className="size-3" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{allDirectoriesExpanded ? "Collapse all folders" : "Expand all folders"}
</TooltipPopup>
</Tooltip>
) : null}
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
size="xs"
variant="outline"
className="!size-[22px]"
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
data-scroll-anchor-ignore
onClick={onToggleAllDirectories}
/>
}
>
{allDirectoriesExpanded ? (
<ChevronsDownUpIcon className="size-3" />
) : (
<ChevronsUpDownIcon className="size-3" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
className="!size-[22px]"
aria-label="View diff"
aria-label="Open diff"
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
/>
}
>
<FileDiffIcon className="size-3" />
<span className="hidden sm:inline">Open diff</span>
</TooltipTrigger>
<TooltipPopup side="top">View diff</TooltipPopup>
<TooltipPopup side="top">Open the full diff</TooltipPopup>
</Tooltip>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnId}`}
turnId={turnId}
files={files}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
{expanded ? (
<ChangedFilesTree
key={`changed-files-tree:${turnId}`}
turnId={turnId}
files={files}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
) : compactPreviewVisible ? (
<div className="px-2 pb-1.5 pt-1">
<p className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] text-muted-foreground">
{scopeSummary.map((scope, index) => (
<span key={scope.label} className="inline-flex items-center gap-1">
{index > 0 ? <span aria-hidden="true">·</span> : null}
<span className="font-mono text-foreground/75">{scope.label}</span>
<span>
{scope.fileCount} file{scope.fileCount === 1 ? "" : "s"}
</span>
</span>
))}
</p>
<div className="mt-2 flex flex-wrap items-center gap-1.5">
{previewFiles.map((file) => (
<button
key={file.path}
type="button"
title={file.path}
className="inline-flex max-w-48 items-center gap-1 rounded-md border border-border/70 bg-background/45 px-1.5 py-1 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onOpenTurnDiff(turnId, file.path)}
>
<PierreEntryIcon
pathValue={file.path}
kind="file"
theme={resolvedTheme}
className="size-3 shrink-0 text-muted-foreground/70"
/>
<span className="truncate">{changedFileName(file.path)}</span>
</button>
))}
<button
type="button"
className="rounded-md px-1.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onExpandedChange(true)}
>
Show all {files.length} files
</button>
</div>
</div>
) : null}
</div>
);
});
@@ -31,6 +31,8 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
<>
{showParentheses && <span className="text-muted-foreground/70">(</span>}
<span
role="group"
aria-label={`${additions} additions, ${deletions} deletions`}
className={cn(
layout === "inline"
? "inline-flex items-center gap-1 tabular-nums align-middle"
@@ -38,8 +40,12 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
className,
)}
>
<span className="font-mono text-success">+{formatCompactDiffCount(additions)}</span>
<span className="font-mono text-destructive">-{formatCompactDiffCount(deletions)}</span>
<span aria-hidden="true" className="font-mono text-success">
+{formatCompactDiffCount(additions)}
</span>
<span aria-hidden="true" className="font-mono text-destructive">
-{formatCompactDiffCount(deletions)}
</span>
</span>
{showParentheses && <span className="text-muted-foreground/70">)</span>}
</>
@@ -245,6 +245,12 @@ describe("MessagesTimeline", () => {
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
latestTurn={{
turnId,
state: "completed",
startedAt: MESSAGE_CREATED_AT,
completedAt: MESSAGE_CREATED_AT,
}}
timelineEntries={[
{
id: "entry-assistant-with-files",
@@ -280,13 +286,13 @@ describe("MessagesTimeline", () => {
/>,
);
expect(markup).toContain('class="sticky top-2 z-10');
expect(markup).toContain("sticky top-2 z-10");
expect(markup).not.toContain("self-start");
expect(markup).toContain("whitespace-nowrap");
expect(markup).toContain("!size-[22px]");
expect(markup).toContain("size-3");
expect(markup).toContain('aria-label="Collapse all"');
expect(markup).toContain('aria-label="View diff"');
expect(markup).toContain('aria-label="Collapse all folders"');
expect(markup).toContain('aria-label="Open diff"');
expect(markup).toContain("1 changed file");
});
@@ -32,7 +32,6 @@ import {
workLogEntryIsToolLike,
} from "../../session-logic";
import { type TurnDiffSummary } from "../../types";
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
import {
getRenderablePatch,
resolveDiffThemeName,
@@ -44,11 +43,8 @@ import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
ChevronsDownUpIcon,
ChevronsUpDownIcon,
CircleAlertIcon,
EyeIcon,
FileDiffIcon,
GlobeIcon,
HammerIcon,
MessageCircleIcon,
@@ -65,8 +61,8 @@ import {
import { Button } from "../ui/button";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { ChangedFilesCard } from "./ChangedFilesTree";
import { shouldAutoExpandChangedFiles } from "./changedFilesPresentation";
import { MessageCopyButton } from "./MessageCopyButton";
import {
computeStableMessagesTimelineRows,
@@ -145,6 +141,7 @@ interface TimelineRowActivityState {
isWorking: boolean;
isRevertingCheckpoint: boolean;
activeTurnInProgress: boolean;
latestTurnId: TurnId | null;
}
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
@@ -454,8 +451,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
isWorking,
isRevertingCheckpoint,
activeTurnInProgress,
latestTurnId: latestTurn?.turnId ?? null,
}),
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
[activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId],
);
// Stable renderItem — no closure deps. Row components read shared state
@@ -1278,83 +1276,32 @@ function AssistantChangedFilesSectionInner({
resolvedTheme: "light" | "dark";
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
}) {
const allDirectoriesExpanded = useUiStateStore(
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
const activity = use(TimelineRowActivityCtx);
const isLatestTurn = activity.latestTurnId === turnSummary.turnId;
const persistedExpanded = useUiStateStore(
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId],
);
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const [autoExpanded] = useState(() =>
shouldAutoExpandChangedFiles(checkpointFiles, isLatestTurn),
);
const [allDirectoriesExpanded, setAllDirectoriesExpanded] = useState(autoExpanded);
const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded);
return (
<div className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 pt-4 dark:border-transparent dark:bg-input/32">
<div className="sticky top-2 z-10 mb-3 flex items-center justify-between gap-2 bg-secondary px-2 before:absolute before:inset-x-0 before:-top-4 before:h-4 before:bg-secondary before:content-[''] dark:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))] dark:before:bg-[color-mix(in_srgb,var(--foreground)_2.5%,var(--background))]">
<p className="flex items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{checkpointFiles.length} changed file{checkpointFiles.length === 1 ? "" : "s"}
</span>
{hasNonZeroStat(summaryStat) && (
<DiffStatLabel
additions={summaryStat.additions}
className="text-xs leading-4"
deletions={summaryStat.deletions}
layout="inline"
/>
)}
</p>
<div className="flex items-center gap-1.5">
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
className="!size-[22px]"
aria-label={allDirectoriesExpanded ? "Collapse all" : "Expand all"}
data-scroll-anchor-ignore
onClick={() =>
setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)
}
/>
}
>
{allDirectoriesExpanded ? (
<ChevronsDownUpIcon className="size-3" />
) : (
<ChevronsUpDownIcon className="size-3" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="outline"
className="!size-[22px]"
aria-label="View diff"
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
/>
}
>
<FileDiffIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">View diff</TooltipPopup>
</Tooltip>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
<ChangedFilesCard
turnId={turnSummary.turnId}
files={checkpointFiles}
expanded={expanded}
showCompactPreview={isLatestTurn}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onExpandedChange={(nextExpanded) =>
setExpanded(routeThreadKey, turnSummary.turnId, nextExpanded)
}
onToggleAllDirectories={() => setAllDirectoriesExpanded((current) => !current)}
onOpenTurnDiff={onOpenTurnDiff}
/>
);
}
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vite-plus/test";
import {
changedFileName,
selectChangedFilePreview,
shouldAutoExpandChangedFiles,
summarizeChangedFileScopes,
} from "./changedFilesPresentation";
describe("changed-files presentation", () => {
it("auto-expands only small, low-churn latest changes", () => {
const smallFiles = [
{ path: "src/a.ts", kind: "modified", additions: 80, deletions: 20 },
{ path: "src/b.ts", kind: "modified", additions: 60, deletions: 20 },
];
expect(shouldAutoExpandChangedFiles(smallFiles, true)).toBe(true);
expect(shouldAutoExpandChangedFiles(smallFiles, false)).toBe(false);
expect(
shouldAutoExpandChangedFiles(
[{ path: "src/a.ts", kind: "modified", additions: 201, deletions: 0 }],
true,
),
).toBe(false);
expect(
shouldAutoExpandChangedFiles(
Array.from({ length: 6 }, (_, index) => ({
path: `src/${index}.ts`,
kind: "modified",
additions: 1,
deletions: 0,
})),
true,
),
).toBe(false);
});
it("summarizes the most prominent top-level scopes", () => {
const files = [
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
{ path: "apps/server/src/index.ts", kind: "modified", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
{ path: "apps\\mobile\\App.tsx", kind: "modified", additions: 1, deletions: 0 },
];
expect(summarizeChangedFileScopes(files)).toEqual([
{ label: "apps", fileCount: 3 },
{ label: "root", fileCount: 1 },
{ label: "packages", fileCount: 1 },
]);
});
it("previews files across different scopes before filling from one scope", () => {
const files = [
{ path: "apps/web/src/App.tsx", kind: "modified", additions: 1, deletions: 0 },
{ path: "apps/web/src/App.test.tsx", kind: "modified", additions: 1, deletions: 0 },
{ path: "packages/shared/src/git.ts", kind: "modified", additions: 1, deletions: 0 },
{ path: "README.md", kind: "modified", additions: 1, deletions: 0 },
];
expect(selectChangedFilePreview(files).map((file) => file.path)).toEqual([
"apps/web/src/App.tsx",
"packages/shared/src/git.ts",
"README.md",
]);
expect(changedFileName("apps\\web\\src\\App.tsx")).toBe("App.tsx");
});
});
@@ -0,0 +1,102 @@
import { type TurnDiffFileChange } from "../../types";
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
export const CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT = 5;
export const CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT = 200;
export const CHANGED_FILES_PREVIEW_FILE_LIMIT = 3;
export const CHANGED_FILES_PREVIEW_SCOPE_LIMIT = 4;
export interface ChangedFilesScopeSummary {
readonly label: string;
readonly fileCount: number;
}
function pathSegments(pathValue: string): string[] {
return pathValue
.replaceAll("\\", "/")
.split("/")
.filter((segment) => segment.length > 0);
}
export function changedFileName(pathValue: string): string {
return pathSegments(pathValue).at(-1) ?? pathValue;
}
function changedFileScope(pathValue: string): string {
const segments = pathSegments(pathValue);
return segments.length > 1 ? (segments[0] ?? "root") : "root";
}
export function shouldAutoExpandChangedFiles(
files: ReadonlyArray<TurnDiffFileChange>,
isLatestTurn: boolean,
): boolean {
if (!isLatestTurn || files.length > CHANGED_FILES_AUTO_EXPAND_FILE_LIMIT) {
return false;
}
const stat = summarizeTurnDiffStats(files);
return stat.additions + stat.deletions <= CHANGED_FILES_AUTO_EXPAND_LINE_LIMIT;
}
export function summarizeChangedFileScopes(
files: ReadonlyArray<TurnDiffFileChange>,
limit = CHANGED_FILES_PREVIEW_SCOPE_LIMIT,
): ChangedFilesScopeSummary[] {
const scopes = new Map<string, { fileCount: number; firstIndex: number }>();
files.forEach((file, index) => {
const label = changedFileScope(file.path);
const current = scopes.get(label);
scopes.set(label, {
fileCount: (current?.fileCount ?? 0) + 1,
firstIndex: current?.firstIndex ?? index,
});
});
return Array.from(scopes, ([label, scope]) => ({
label,
fileCount: scope.fileCount,
firstIndex: scope.firstIndex,
}))
.toSorted(
(left, right) =>
right.fileCount - left.fileCount ||
left.firstIndex - right.firstIndex ||
left.label.localeCompare(right.label),
)
.slice(0, limit)
.map(({ label, fileCount }) => ({ label, fileCount }));
}
export function selectChangedFilePreview(
files: ReadonlyArray<TurnDiffFileChange>,
limit = CHANGED_FILES_PREVIEW_FILE_LIMIT,
): TurnDiffFileChange[] {
const selected: TurnDiffFileChange[] = [];
const selectedPaths = new Set<string>();
const selectedScopes = new Set<string>();
for (const file of files) {
const scope = changedFileScope(file.path);
if (selectedScopes.has(scope)) {
continue;
}
selected.push(file);
selectedPaths.add(file.path);
selectedScopes.add(scope);
if (selected.length === limit) {
return selected;
}
}
for (const file of files) {
if (selectedPaths.has(file.path)) {
continue;
}
selected.push(file);
if (selected.length === limit) {
break;
}
}
return selected;
}
+22 -7
View File
@@ -116,7 +116,7 @@ describe("uiStateStore pure functions", () => {
);
});
it("stores only collapsed changed-file turns", () => {
it("stores explicit changed-file expansion choices", () => {
const threadId = ThreadId.make("thread-1");
const collapsed = setThreadChangedFilesExpanded(makeUiState(), threadId, "turn-1", false);
@@ -128,7 +128,11 @@ describe("uiStateStore pure functions", () => {
expect(
setThreadChangedFilesExpanded(collapsed, threadId, "turn-1", true)
.threadChangedFilesExpandedById,
).toEqual({});
).toEqual({
[threadId]: {
"turn-1": true,
},
});
});
it("stores the endpoint preference by stable key", () => {
@@ -155,6 +159,7 @@ describe("parsePersistedState", () => {
invalid: "not-a-date",
},
defaultAdvertisedEndpointKey: "desktop-core:lan:http",
threadChangedFilesExpansionVersion: 1,
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
@@ -175,11 +180,24 @@ describe("parsePersistedState", () => {
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
"turn-2": true,
},
},
});
});
it("ignores changed-file expansion values saved with legacy folder semantics", () => {
const parsed = parsePersistedState({
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
},
},
});
expect(parsed.threadChangedFilesExpandedById).toEqual({});
});
it("migrates legacy CWD project preferences into local alias keys", () => {
const parsed = parsePersistedState({
collapsedProjectCwds: ["/repo/b"],
@@ -278,19 +296,16 @@ describe("uiStateStore persistence", () => {
"environment:thread-1": "2026-02-25T12:35:00.000Z",
},
defaultAdvertisedEndpointKey: "desktop-core:lan:http",
threadChangedFilesExpansionVersion: 1,
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
"turn-2": true,
},
},
});
expect(parsePersistedState(persisted)).toEqual({
...state,
threadChangedFilesExpandedById: {
"environment:thread-1": {
"turn-1": false,
},
},
});
});
+12 -42
View File
@@ -3,6 +3,7 @@ import { create } from "zustand";
import { normalizeProjectPathForComparison } from "./lib/projectPaths";
export const PERSISTED_STATE_KEY = "t3code:ui-state:v1";
const THREAD_CHANGED_FILES_EXPANSION_VERSION = 1;
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v8",
"t3code:renderer-state:v7",
@@ -24,6 +25,7 @@ export interface PersistedUiState {
expandedProjectCwds?: string[];
projectOrderCwds?: string[];
defaultAdvertisedEndpointKey?: string | null;
threadChangedFilesExpansionVersion?: typeof THREAD_CHANGED_FILES_EXPANSION_VERSION;
threadChangedFilesExpandedById?: Record<string, Record<string, boolean>>;
}
@@ -124,9 +126,10 @@ export function parsePersistedState(parsed: PersistedUiState): UiState {
projectExpandedById,
projectOrder,
threadLastVisitedAtById: sanitizeTimestampRecord(parsed.threadLastVisitedAtById),
threadChangedFilesExpandedById: sanitizePersistedThreadChangedFilesExpanded(
parsed.threadChangedFilesExpandedById,
),
threadChangedFilesExpandedById:
parsed.threadChangedFilesExpansionVersion === THREAD_CHANGED_FILES_EXPANSION_VERSION
? sanitizePersistedThreadChangedFilesExpanded(parsed.threadChangedFilesExpandedById)
: {},
defaultAdvertisedEndpointKey:
typeof parsed.defaultAdvertisedEndpointKey === "string" &&
parsed.defaultAdvertisedEndpointKey.length > 0
@@ -172,8 +175,8 @@ function sanitizePersistedThreadChangedFilesExpanded(
const nextTurns: Record<string, boolean> = {};
for (const [turnId, expanded] of Object.entries(turns)) {
if (turnId && typeof expanded === "boolean" && expanded === false) {
nextTurns[turnId] = false;
if (turnId && typeof expanded === "boolean") {
nextTurns[turnId] = expanded;
}
}
@@ -195,14 +198,6 @@ export function persistState(state: UiState): void {
([key]) => key !== LEGACY_PROJECT_EXPANSION_DEFAULT_KEY,
),
);
const threadChangedFilesExpandedById = Object.fromEntries(
Object.entries(state.threadChangedFilesExpandedById).flatMap(([threadId, turns]) => {
const nextTurns = Object.fromEntries(
Object.entries(turns).filter(([, expanded]) => expanded === false),
);
return Object.keys(nextTurns).length > 0 ? [[threadId, nextTurns]] : [];
}),
);
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify({
@@ -210,7 +205,8 @@ export function persistState(state: UiState): void {
projectOrder: state.projectOrder,
threadLastVisitedAtById: state.threadLastVisitedAtById,
defaultAdvertisedEndpointKey: state.defaultAdvertisedEndpointKey,
threadChangedFilesExpandedById,
threadChangedFilesExpansionVersion: THREAD_CHANGED_FILES_EXPANSION_VERSION,
threadChangedFilesExpandedById: state.threadChangedFilesExpandedById,
} satisfies PersistedUiState),
);
if (!legacyKeysCleanedUp) {
@@ -281,43 +277,17 @@ export function setThreadChangedFilesExpanded(
expanded: boolean,
): UiState {
const currentThreadState = state.threadChangedFilesExpandedById[threadId] ?? {};
const currentExpanded = currentThreadState[turnId] ?? true;
if (currentExpanded === expanded) {
if (currentThreadState[turnId] === expanded) {
return state;
}
if (expanded) {
if (!(turnId in currentThreadState)) {
return state;
}
const nextThreadState = { ...currentThreadState };
delete nextThreadState[turnId];
if (Object.keys(nextThreadState).length === 0) {
const nextState = { ...state.threadChangedFilesExpandedById };
delete nextState[threadId];
return {
...state,
threadChangedFilesExpandedById: nextState,
};
}
return {
...state,
threadChangedFilesExpandedById: {
...state.threadChangedFilesExpandedById,
[threadId]: nextThreadState,
},
};
}
return {
...state,
threadChangedFilesExpandedById: {
...state.threadChangedFilesExpandedById,
[threadId]: {
...currentThreadState,
[turnId]: false,
[turnId]: expanded,
},
},
};