Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

refactor(diff): update diff view and agent changes viewer implementation and UI (#7127)

dev-rb626941130234
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 4467596819..bfd28f90bd 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -473,6 +473,11 @@ if (LOCAL_ONLY) {
'agent-changes-ui',
lazy(() => import('@app/features/agent-changes/debug/Gallery'))
);
+
+ registerComponent(
+ 'diff-view-ui',
+ lazy(() => import('@app/components/diff-view/debug/DiffViewGallery'))
+ );
}
if (import.meta.env.DEV) {
diff --git a/apps/web/src/components/app/split-layout/split-router/app-routes.ts b/apps/web/src/components/app/split-layout/split-router/app-routes.ts
index 37324469e1..f162d72c5e 100644
--- a/apps/web/src/components/app/split-layout/split-router/app-routes.ts
+++ b/apps/web/src/components/app/split-layout/split-router/app-routes.ts
@@ -1,5 +1,4 @@
import { activityRoute } from '@app/features/activity/route';
-import { DIFF_SEARCH_PARAM } from '@app/features/agent-changes/core/url-state';
import {
agentChatsRoute,
agentsRoute,
@@ -56,9 +55,7 @@ export const appSplitRoutes = defineRoutes({
...debugRoutes,
legacySplitRoute,
],
- // The changes viewer keys its entries by host, not by pane, so its key is
- // owned globally; a route-local one would be dropped on the next commit.
- globalSearch: ['referral_code', DIFF_SEARCH_PARAM],
+ globalSearch: ['referral_code'],
unmatchedPathHandlers: [handleLegacySplitPath],
defaultEntry: () => ({
location: { route: { matches: [{ id: 'view-home', params: {} }] } },
diff --git a/apps/web/src/components/app/split-layout/split-router/debug-routes.ts b/apps/web/src/components/app/split-layout/split-router/debug-routes.ts
index bdd5989e98..52580516eb 100644
--- a/apps/web/src/components/app/split-layout/split-router/debug-routes.ts
+++ b/apps/web/src/components/app/split-layout/split-router/debug-routes.ts
@@ -28,6 +28,7 @@ const debugComponentIds = [
'agent-ui',
'agent-replay',
'agent-changes-ui',
+ 'diff-view-ui',
]
: []),
...(import.meta.env.DEV ? ['spreadsheet-demo'] : []),
diff --git a/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts b/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts
index f740ea2ed9..118acc6d00 100644
--- a/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts
+++ b/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts
@@ -1,4 +1,3 @@
-import { DIFF_SEARCH_PARAM } from '@app/features/agent-changes/core/url-state';
import { createRoutesManifest } from '@app/lib/split-router/routes';
import {
decodeSplitRouterLocation,
@@ -19,7 +18,7 @@ vi.mock('@service-connection/websocket', () => ({
}));
const routes = createRoutesManifest(appSplitRoutes);
-const viewerState = `${DIFF_SEARCH_PARAM}=session-1%3Asplit%3Aunified`;
+const viewerState = 's0.changes.pane=split';
function roundTrip(pathname: string, search: string, committed: boolean) {
const location = { pathname, search: `?${search}`, hash: '' };
@@ -39,16 +38,19 @@ describe('application route search ownership', () => {
['/agents/session-1', 'the agents workspace'],
['/coders/session-1', 'a coding session'],
['/agent/session-1', 'the agent block'],
- ])('keeps the changes viewer state on %s (%s)', (pathname) => {
+ ])('keeps the changes pane state on %s (%s)', (pathname) => {
expect(roundTrip(pathname, viewerState, false)).toContain(viewerState);
expect(roundTrip(pathname, viewerState, true)).toContain(viewerState);
});
- it('keeps a neighbouring pane’s viewer state when one pane navigates', () => {
- const search = `${DIFF_SEARCH_PARAM}=session-1%3Asplit%3Aunified%2Csession-2%3Achanges-only%3Asplit`;
- expect(roundTrip('/agents/session-1/~/mail', search, true)).toContain(
- search
+ it('drops the changes pane state of a split whose route does not own it', () => {
+ const result = roundTrip(
+ '/agents/session-1/~/reviews',
+ 's0.changes.pane=split&s1.changes.pane=full',
+ true
);
+ expect(result).toContain('s0.changes.pane=split');
+ expect(result).not.toContain('s1.changes');
});
it('drops search keys no route owns', () => {
diff --git a/apps/web/src/features/agent-changes/components/DiffCounts.tsx b/apps/web/src/components/diff-view/DiffCounts.tsx
similarity index 75%
rename from apps/web/src/features/agent-changes/components/DiffCounts.tsx
rename to apps/web/src/components/diff-view/DiffCounts.tsx
index 7737e0f165..514eca2b1e 100644
--- a/apps/web/src/features/agent-changes/components/DiffCounts.tsx
+++ b/apps/web/src/components/diff-view/DiffCounts.tsx
@@ -1,10 +1,10 @@
import { Show } from 'solid-js';
-/** Numeric line totals shared by the viewer and its entry controls. */
+/** Added and deleted line totals, hidden when both are zero. */
export function DiffCounts(props: { additions: number; deletions: number }) {
return (
<Show when={props.additions > 0 || props.deletions > 0}>
- <span class="inline-flex shrink-0 items-center gap-2 font-mono tabular-nums">
+ <span class="inline-flex shrink-0 items-center gap-2 tabular-nums">
<Show when={props.additions > 0}>
<span class="text-success">{`+${props.additions}`}</span>
</Show>
diff --git a/apps/web/src/components/diff-view/DiffView.tsx b/apps/web/src/components/diff-view/DiffView.tsx
new file mode 100644
index 0000000000..87bf7edf23
--- /dev/null
+++ b/apps/web/src/components/diff-view/DiffView.tsx
@@ -0,0 +1,348 @@
+/**
+ * A stack of file diffs from one patch. `Root` pairs the host's files with
+ * the patch and holds the view's state; a list renderer (`Stack`) draws the
+ * files, and the host composes each file's header and whatever hangs under
+ * its lines. Toolbar parts (`CollapseAll`, `StyleToggle`) go wherever the
+ * host puts them inside `Root`.
+ */
+
+import ArrowsInIcon from '@phosphor/arrows-in.svg';
+import ArrowsOutIcon from '@phosphor/arrows-out.svg';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import { Button, Card, cn, SegmentedControl } from '@ui';
+import {
+ type Accessor,
+ createContext,
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ type JSX,
+ on,
+ onCleanup,
+ type ParentProps,
+ Show,
+ useContext,
+} from 'solid-js';
+import { createDiffCollapse, type DiffCollapse } from './collapse';
+import { DiffCounts } from './DiffCounts';
+import { type DiffFile, type DiffStyle, splitPath } from './model/diff-file';
+import type { LineAnnotation, LineRange } from './model/lines';
+import { type DiffEntry, matchFilesToDiffs, parsePatch } from './model/patch';
+import { PierreFileDiff } from './pierre/PierreFileDiff';
+import { createThemeType, type ThemeType } from './pierre/theme';
+import { StatusLetter } from './StatusLetter';
+
+type DiffViewContextValue = {
+ entries: Accessor<DiffEntry[]>;
+ diffStyle: Accessor<DiffStyle>;
+ themeType: Accessor<ThemeType>;
+ collapse: DiffCollapse;
+ active: Accessor<string | undefined>;
+};
+
+const DiffViewContext = createContext<DiffViewContextValue>();
+const FileContext = createContext<DiffEntry>();
+
+function useDiffView(): DiffViewContextValue {
+ const context = useContext(DiffViewContext);
+ if (!context) throw new Error('DiffView parts must be inside DiffView.Root');
+ return context;
+}
+
+function useDiffFile(): DiffEntry {
+ const entry = useContext(FileContext);
+ if (!entry) throw new Error('DiffView file parts must be inside a file');
+ return entry;
+}
+
+function Root(
+ props: ParentProps<{
+ files: readonly DiffFile[];
+ /** The unified patch behind `files`; empty when no file has diff text. */
+ patch: string;
+ diffStyle: DiffStyle;
+ /** Defaults to collapse state kept in memory. */
+ collapse?: DiffCollapse;
+ /** The file to bring into view; each change scrolls to it again. */
+ active?: string;
+ }>
+) {
+ const diffs = createMemo(() => parsePatch(props.patch));
+ const entries = createMemo(() => matchFilesToDiffs(props.files, diffs()));
+ const view: DiffViewContextValue = {
+ entries,
+ diffStyle: () => props.diffStyle,
+ themeType: createThemeType(),
+ collapse:
+ props.collapse ??
+ createDiffCollapse(() => props.files.map((file) => file.path)),
+ active: () => props.active,
+ };
+ return (
+ <DiffViewContext.Provider value={view}>
+ {props.children}
+ </DiffViewContext.Provider>
+ );
+}
+
+/** What a list renderer asks of the host for each file. */
+type DiffListProps = {
+ /** What a file's sticky header shows; defaults to its caret, path, and counts. */
+ header?: (entry: DiffEntry) => JSX.Element;
+ /** Where host content hangs on a file. */
+ annotations?: (entry: DiffEntry) => LineAnnotation[];
+ /** The content under one of a file's annotations. */
+ renderAnnotation?: (entry: DiffEntry, key: string) => JSX.Element;
+ /**
+ * The lines to light, one range at a time: the range being annotated, or one
+ * the host points at, such as a focused comment's.
+ */
+ selection?: Accessor<LineRange | undefined>;
+ /** Turns on the gutter "+" for picking lines; omit for a read-only diff. */
+ onSelectLines?: (range: LineRange) => void;
+ /**
+ * CSS injected into Pierre's shadow root, e.g. to restyle annotation rows.
+ * It targets Pierre's internal markup, so it can break on an upgrade.
+ */
+ unsafeCSS?: string;
+ class?: string;
+};
+
+const FLASH_MS = 900;
+
+function DefaultHeader() {
+ return (
+ <>
+ <CollapseButton />
+ <FilePath />
+ <FileCounts />
+ </>
+ );
+}
+
+/** Plain note shown in place of a diff body. */
+function DiffNote(props: { children: JSX.Element }) {
+ return (
+ <div class="px-3 py-2.5 text-xs text-ink-subtle">{props.children}</div>
+ );
+}
+
+/** Every file as its own card, each rendered by its own Pierre instance. */
+function Stack(props: DiffListProps) {
+ const view = useDiffView();
+ const cards = new Map<string, HTMLElement>();
+ const [flashing, setFlashing] = createSignal<string>();
+
+ // Jumping to a file is a DOM concern: scroll the card in and flash it.
+ createEffect(
+ on(
+ view.active,
+ (path) => {
+ if (!path) return;
+ cards.get(path)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
+ setFlashing(path);
+ const timer = setTimeout(() => setFlashing(undefined), FLASH_MS);
+ onCleanup(() => clearTimeout(timer));
+ },
+ { defer: true }
+ )
+ );
+
+ // Padding lives on the inner column: on the scroller itself it insets the
+ // sticky headers, leaving a band above them where lines scroll into view.
+ return (
+ <div
+ class={cn(
+ 'min-h-0 min-w-0 flex-1 overflow-y-auto scroll-smooth motion-reduce:scroll-auto',
+ props.class
+ )}
+ >
+ <div class="flex min-w-0 flex-col gap-3 p-3 pb-24">
+ <For each={view.entries()}>
+ {(entry) => {
+ const path = () => entry.file.path;
+ const collapsed = () => view.collapse.isCollapsed(path());
+ const selection = () => {
+ const range = props.selection?.();
+ return range?.path === path() ? range : undefined;
+ };
+ return (
+ <FileContext.Provider value={entry}>
+ <Card
+ ref={(element: HTMLDivElement) => {
+ cards.set(path(), element);
+ onCleanup(() => cards.delete(path()));
+ }}
+ class={cn(
+ 'shrink-0 scroll-mt-3 overflow-clip transition',
+ flashing() === path() &&
+ 'border-accent ring-2 ring-selected'
+ )}
+ data-path={path()}
+ >
+ <header
+ class={cn(
+ 'sticky top-0 z-5 flex h-10 items-center gap-1 bg-surface px-1.5',
+ !collapsed() && 'border-b border-edge-muted'
+ )}
+ >
+ {props.header ? props.header(entry) : <DefaultHeader />}
+ </header>
+ <Show when={!collapsed()}>
+ <Show
+ when={!entry.note}
+ fallback={<DiffNote>{entry.note}</DiffNote>}
+ >
+ <Show when={entry.diff}>
+ {(diff) => (
+ <PierreFileDiff
+ path={path()}
+ diff={diff()}
+ diffStyle={view.diffStyle()}
+ themeType={view.themeType()}
+ annotations={props.annotations?.(entry) ?? []}
+ renderAnnotation={(key) =>
+ props.renderAnnotation?.(entry, key)
+ }
+ selection={selection()}
+ onSelectLines={props.onSelectLines}
+ unsafeCSS={props.unsafeCSS}
+ />
+ )}
+ </Show>
+ </Show>
+ </Show>
+ </Card>
+ </FileContext.Provider>
+ );
+ }}
+ </For>
+ </div>
+ </div>
+ );
+}
+
+/** Shows or hides the file's diff. */
+function CollapseButton() {
+ const { collapse } = useDiffView();
+ const entry = useDiffFile();
+ const collapsed = () => collapse.isCollapsed(entry.file.path);
+ const base = () => splitPath(entry.file.path).base;
+ return (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-expanded={!collapsed()}
+ aria-label={`${collapsed() ? 'Show' : 'Hide'} ${base()}`}
+ tooltip={collapsed() ? 'Show this diff' : 'Hide this diff'}
+ onClick={() => collapse.toggle(entry.file.path)}
+ >
+ <CaretRightIcon
+ class={cn(
+ 'transition-transform duration-100 motion-reduce:transition-none',
+ !collapsed() && 'rotate-90'
+ )}
+ />
+ </Button>
+ );
+}
+
+/** The file's status and path, where a rename shows where it came from. */
+function FilePath() {
+ const { collapse } = useDiffView();
+ const entry = useDiffFile();
+ const file = () => entry.file;
+ const path = () => splitPath(file().path);
+ return (
+ <button
+ type="button"
+ class="flex h-7 min-w-0 flex-1 items-center gap-2 rounded-md px-1 text-left outline-none focus-visible:outline-2 focus-visible:outline-accent"
+ aria-expanded={!collapse.isCollapsed(file().path)}
+ title={file().path}
+ onClick={() => collapse.toggle(file().path)}
+ >
+ <StatusLetter kind={file().kind} />
+ <span class="flex min-w-0 items-baseline text-xs">
+ <Show when={file().previousPath}>
+ {(previous) => (
+ <span class="truncate text-ink-subtle">
+ {previous()}
+ <span class="px-1">→</span>
+ </span>
+ )}
+ </Show>
+ <span class="min-w-0 shrink truncate text-ink-subtle">
+ {path().dir}
+ </span>
+ <span class="max-w-full shrink-0 truncate font-medium text-ink">
+ {path().base}
+ </span>
+ </span>
+ </button>
+ );
+}
+
+/** The file's added and deleted line totals. */
+function FileCounts() {
+ const entry = useDiffFile();
+ return (
+ <span class="flex shrink-0 items-center px-1 text-xs">
+ <DiffCounts
+ additions={entry.file.additions}
+ deletions={entry.file.deletions}
+ />
+ </span>
+ );
+}
+
+/** Collapses every diff to its header, or opens them all again. */
+function CollapseAll() {
+ const { collapse } = useDiffView();
+ return (
+ <Button
+ variant="ghost"
+ size="sm"
+ tooltip={
+ collapse.anyExpanded()
+ ? 'Hide every diff, keeping just the file headers'
+ : 'Show every diff again'
+ }
+ onClick={() => collapse.toggleAll()}
+ >
+ {collapse.anyExpanded() ? <ArrowsInIcon /> : <ArrowsOutIcon />}
+ <span>{collapse.anyExpanded() ? 'Collapse all' : 'Expand all'}</span>
+ </Button>
+ );
+}
+
+/** Unified or side-by-side diffs. */
+function StyleToggle(props: {
+ value: DiffStyle;
+ onChange: (style: DiffStyle) => void;
+ class?: string;
+}) {
+ return (
+ <SegmentedControl
+ size="sm"
+ aria-label="Diff layout"
+ value={props.value}
+ options={[
+ { value: 'unified', label: 'Unified' },
+ { value: 'split', label: 'Split' },
+ ]}
+ onChange={props.onChange}
+ class={props.class}
+ />
+ );
+}
+
+export const DiffView = {
+ Root,
+ Stack,
+ CollapseButton,
+ FilePath,
+ FileCounts,
+ CollapseAll,
+ StyleToggle,
+};
diff --git a/apps/web/src/components/diff-view/README.md b/apps/web/src/components/diff-view/README.md
new file mode 100644
index 0000000000..45a7a70ff0
--- /dev/null
+++ b/apps/web/src/components/diff-view/README.md
@@ -0,0 +1,81 @@
+# Diff view
+
+File diffs from one unified patch, drawn with Pierre. `DiffView.Root` pairs the
+host's `files` with the `patch`, and holds the diff style, collapse state, and
+the file to scroll to (`active`). A list renderer draws the files:
+`DiffView.Stack` gives each file its own card and Pierre instance.
+
+Each file is an outlined `@ui` `Card` with a 40px sticky header: a ghost
+disclosure button, the status letter and `text-xs` path (directory in
+`text-ink-subtle`), and `text-xs` counts. Toolbar parts use standard `Button`
+and `SegmentedControl` sizes, and backgrounds come from the card's depth.
+
+The host composes the rest:
+
+- Each file's sticky header, from `DiffView.CollapseButton`, `DiffView.FilePath`,
+ `DiffView.FileCounts`, and its own actions. The default header is the first three.
+- Content under lines (`annotations`, `renderAnnotation`), and the gutter **+**
+ for picking lines (`onSelectLines`). `selection` lights one range per file:
+ the range being annotated, or one the host points at, such as a focused
+ comment's. Omit these for a read-only diff.
+- Toolbar parts, `DiffView.CollapseAll` and `DiffView.StyleToggle`, anywhere
+ inside `Root`.
+- Collapse state that persists, by passing `collapse`; the default lives in memory.
+
+```tsx
+<DiffView.Root files={files()} patch={patch()} diffStyle={style()} active={active()}>
+ <DiffView.CollapseAll />
+ <DiffView.Stack
+ header={(entry) => (
+ <>
+ <DiffView.CollapseButton />
+ <DiffView.FilePath />
+ <CopyPathButton path={entry.file.path} />
+ </>
+ )}
+ />
+</DiffView.Root>
+```
+
+## Comments under lines
+
+`createDiffComments` turns a host's items into the four annotation props above.
+It hangs each item under the last line of its `LineRange` (grouping items that
+end on the same line, like a GitHub thread), holds the one comment being
+written, and lights the lines of the thread with focus. The host renders each
+line's `CommentSpot`, its items and the draft when it is there; `CommentThread`
+has the parts for GitHub-style threads (`Root`, `Comment`, `Reply`, and a
+controlled `Composer`). Agent review notes render their own `NoteAnnotation`
+through the same layer.
+
+```tsx
+const comments = createDiffComments({
+ items: threads,
+ rangeOf: (thread) => thread.range,
+ render: (spot) => <ReviewThread spot={spot} comments={comments} />,
+});
+<DiffView.Stack
+ annotations={comments.annotations}
+ renderAnnotation={comments.renderAnnotation}
+ selection={comments.selection}
+ onSelectLines={comments.onSelectLines}
+/>;
+```
+
+A `LineRange` ends on `side`. A unified range dragged from deleted lines into
+added ones also has `startSide`, and each end is in its own side's numbering,
+which is GitHub's `start_side` model.
+
+Pierre decides where annotation rows go: under a line on one side, or above the
+first hunk for line 0. Their content is ours and renders in the light DOM, where
+it would inherit Pierre's mono font; the layer sets `font-sans`. The row itself
+is drawn in Pierre's shadow root: `--diffs-annotation-min-height` can be set from
+outside, but its background and padding need `unsafeCSS`, which targets Pierre's
+markup and can break on an upgrade. Pierre re-creates an annotation's element
+when rows before it change and on every Unified/Split switch, so the draft lives
+in the layer or with the host (`draft` option), never in the rendered editor.
+
+`pierre/theme.ts` holds the theme signal and CSS variables every Pierre diff in
+the app shares, including the transcript's tool-call diffs. Examples, including
+review threads and a generated changeset of up to 500 files, live at
+`/debug/diff-view-ui` in local builds.
diff --git a/apps/web/src/features/agent-changes/components/StatusLetter.tsx b/apps/web/src/components/diff-view/StatusLetter.tsx
similarity index 65%
rename from apps/web/src/features/agent-changes/components/StatusLetter.tsx
rename to apps/web/src/components/diff-view/StatusLetter.tsx
index f495bcb709..591cd0c2fc 100644
--- a/apps/web/src/features/agent-changes/components/StatusLetter.tsx
+++ b/apps/web/src/components/diff-view/StatusLetter.tsx
@@ -1,8 +1,7 @@
import { cn } from '@ui';
-import type { FileChangeKind } from '../core/changeset';
-import { statusLetter } from '../core/changeset';
+import { type DiffFileKind, statusLetter } from './model/diff-file';
-const LABELS: Record<FileChangeKind, string> = {
+const LABELS: Record<DiffFileKind, string> = {
added: 'Added',
modified: 'Modified',
deleted: 'Deleted',
@@ -10,11 +9,11 @@ const LABELS: Record<FileChangeKind, string> = {
};
/** The one-letter change status, coloured like the diff it describes. */
-export function StatusLetter(props: { kind: FileChangeKind; class?: string }) {
+export function StatusLetter(props: { kind: DiffFileKind; class?: string }) {
return (
<span
class={cn(
- 'w-3 shrink-0 text-center font-mono text-[10px] font-medium',
+ 'w-3 shrink-0 text-center text-xs font-medium',
props.kind === 'added' && 'text-success',
props.kind === 'modified' && 'text-blue',
props.kind === 'deleted' && 'text-failure',
diff --git a/apps/web/src/components/diff-view/collapse.ts b/apps/web/src/components/diff-view/collapse.ts
new file mode 100644
index 0000000000..5318a4ba8f
--- /dev/null
+++ b/apps/web/src/components/diff-view/collapse.ts
@@ -0,0 +1,33 @@
+import { type Accessor, createSignal } from 'solid-js';
+
+/** Which files show their diff. A host that persists it supplies its own. */
+export type DiffCollapse = {
+ isCollapsed: (path: string) => boolean;
+ toggle: (path: string) => void;
+ /** Collapse every file, or expand them all when none is open. */
+ toggleAll: () => void;
+ anyExpanded: Accessor<boolean>;
+};
+
+/** Collapse state kept in memory for as long as the view is mounted. */
+export function createDiffCollapse(
+ paths: Accessor<readonly string[]>
+): DiffCollapse {
+ const [collapsed, setCollapsed] = createSignal<ReadonlySet<string>>(
+ new Set()
+ );
+ const anyExpanded = () => paths().some((path) => !collapsed().has(path));
+ return {
+ isCollapsed: (path) => collapsed().has(path),
+ toggle: (path) =>
+ setCollapsed((previous) => {
+ const next = new Set(previous);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ return next;
+ }),
+ toggleAll: () =>
+ setCollapsed(anyExpanded() ? new Set(paths()) : new Set<string>()),
+ anyExpanded,
+ };
+}
diff --git a/apps/web/src/components/diff-view/comments/CommentThread.tsx b/apps/web/src/components/diff-view/comments/CommentThread.tsx
new file mode 100644
index 0000000000..d131e3c1df
--- /dev/null
+++ b/apps/web/src/components/diff-view/comments/CommentThread.tsx
@@ -0,0 +1,129 @@
+/**
+ * The parts of a GitHub-style review thread under a diff line: a card, each
+ * comment with its author, a reply button, and the editor for a new one.
+ * Presentational; `createDiffComments` places them and holds the draft.
+ */
+
+import { Avatar, Button } from '@ui';
+import { type JSX, onMount, Show } from 'solid-js';
+
+function initials(name: string): string {
+ return name
+ .split(/\s+/)
+ .map((part) => part[0] ?? '')
+ .join('')
+ .slice(0, 2)
+ .toUpperCase();
+}
+
+function Root(props: { children: JSX.Element }) {
+ return (
+ <div class="px-3 py-2">
+ <div class="flex flex-col gap-3 rounded-xl border border-edge-muted bg-surface p-3 transition focus-within:border-edge">
+ {props.children}
+ </div>
+ </div>
+ );
+}
+
+function Comment(props: {
+ author: string;
+ avatarUrl?: string;
+ /** When it was written, already formatted. */
+ time?: string;
+ children: JSX.Element;
+}) {
+ return (
+ <div class="flex gap-2">
+ <Avatar size="md">
+ <Show when={props.avatarUrl}>
+ {(url) => <Avatar.Image src={url()} alt="" />}
+ </Show>
+ <Avatar.Fallback>{initials(props.author)}</Avatar.Fallback>
+ </Avatar>
+ <div class="flex min-w-0 flex-1 flex-col gap-0.5">
+ <div class="flex items-baseline gap-2">
+ <span class="text-sm font-medium text-ink">{props.author}</span>
+ <Show when={props.time}>
+ <span class="text-xs text-ink-subtle">{props.time}</span>
+ </Show>
+ </div>
+ <div class="text-sm wrap-break-word whitespace-pre-wrap text-ink-muted">
+ {props.children}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function Reply(props: { onClick: () => void }) {
+ return (
+ <Button
+ variant="ghost"
+ size="sm"
+ class="self-start"
+ onClick={() => props.onClick()}
+ >
+ Reply
+ </Button>
+ );
+}
+
+/** A controlled editor: the text lives with the draft, not in here. */
+function Composer(props: {
+ value: string;
+ onInput: (text: string) => void;
+ onSubmit: () => void;
+ onCancel: () => void;
+ submitLabel: string;
+ placeholder?: string;
+ /** Explains where the comment goes, beside the buttons. */
+ hint?: string;
+}) {
+ let textarea!: HTMLTextAreaElement;
+ onMount(() => textarea.focus());
+ const empty = () => props.value.trim() === '';
+ return (
+ <div class="flex flex-col gap-2">
+ <textarea
+ ref={textarea}
+ class="min-h-16 w-full resize-y rounded-lg border border-edge bg-input px-2.5 py-2 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:border-input-focus"
+ placeholder={props.placeholder ?? 'Leave a comment'}
+ aria-label={props.placeholder ?? 'Comment'}
+ value={props.value}
+ onInput={(event) => props.onInput(event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ props.onCancel();
+ } else if (
+ event.key === 'Enter' &&
+ (event.metaKey || event.ctrlKey) &&
+ !empty()
+ ) {
+ event.preventDefault();
+ props.onSubmit();
+ }
+ }}
+ />
+ <div class="flex items-center gap-1.5">
+ <span class="min-w-0 flex-1 truncate text-xs text-ink-subtle">
+ {props.hint}
+ </span>
+ <Button variant="ghost" size="sm" onClick={() => props.onCancel()}>
+ Cancel
+ </Button>
+ <Button
+ variant="cta"
+ size="sm"
+ disabled={empty()}
+ onClick={() => props.onSubmit()}
+ >
+ {props.submitLabel}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+export const CommentThread = { Root, Comment, Reply, Composer };
diff --git a/apps/web/src/components/diff-view/comments/create-diff-comments.tsx b/apps/web/src/components/diff-view/comments/create-diff-comments.tsx
new file mode 100644
index 0000000000..c8b8f7fbdd
--- /dev/null
+++ b/apps/web/src/components/diff-view/comments/create-diff-comments.tsx
@@ -0,0 +1,158 @@
+/**
+ * Comments under diff lines, for `DiffView.Stack`: groups a host's items by
+ * the line they hang from (the last line of their range, like GitHub), holds
+ * the one comment being written, and lights the lines of the thread with
+ * focus. The host renders what each line shows; `CommentThread` has the
+ * parts for GitHub-style threads.
+ *
+ * Pierre re-creates a line's element when rows before it change and on every
+ * Unified/Split switch, so the draft lives here or with the host, never in
+ * the rendered editor.
+ */
+
+import { type Accessor, createSignal, type JSX } from 'solid-js';
+import type { LineAnnotation, LineRange } from '../model/lines';
+import type { DiffEntry } from '../model/patch';
+
+/** A comment being written: where it goes, and what it says so far. */
+export type CommentDraft = { range: LineRange; text: string };
+
+/** Everything that hangs under one line of one file. */
+export type CommentSpot<T> = {
+ readonly path: string;
+ /** Posted items ending on this line, earliest start first. */
+ readonly items: T[];
+ /** The comment being written here, when it is. */
+ readonly draft: CommentDraft | undefined;
+};
+
+/** The props to spread onto `DiffView.Stack`, and the draft's controls. */
+export type DiffComments = {
+ annotations: (entry: DiffEntry) => LineAnnotation[];
+ renderAnnotation: (entry: DiffEntry, key: string) => JSX.Element;
+ selection: Accessor<LineRange | undefined>;
+ /** Undefined while the host cannot take comments, which hides the gutter "+". */
+ readonly onSelectLines: ((range: LineRange) => void) | undefined;
+ draft: Accessor<CommentDraft | undefined>;
+ /** Start writing on these lines, such as a reply to a thread. */
+ startDraft: (range: LineRange) => void;
+ editDraft: (text: string) => void;
+ cancelDraft: () => void;
+};
+
+const spotKey = (range: Pick<LineRange, 'side' | 'endLineNumber'>) =>
+ `${range.side}:${range.endLineNumber}`;
+
+export function createDiffComments<T>(options: {
+ /** Every posted item on every file. */
+ items: Accessor<readonly T[]>;
+ rangeOf: (item: T) => LineRange;
+ /** Where the draft lives, when the host keeps it; defaults to this layer. */
+ draft?: [
+ get: Accessor<CommentDraft | undefined>,
+ set: (draft: CommentDraft | undefined) => void,
+ ];
+ /** Whether the reviewer can start a comment; defaults to always. */
+ canComment?: Accessor<boolean>;
+ render: (spot: CommentSpot<T>) => JSX.Element;
+}): DiffComments {
+ const [ownDraft, setOwnDraft] = createSignal<CommentDraft>();
+ const [draft, setDraft] = options.draft ?? [ownDraft, setOwnDraft];
+ // A focused editor that is removed on post or cancel sends no focusout, so
+ // focus taken while drafting only counts while that draft still exists.
+ const [focused, setFocused] = createSignal<{
+ range: LineRange;
+ whileDrafting: boolean;
+ }>();
+
+ const itemsAt = (path: string, key: string) =>
+ options
+ .items()
+ .filter((item) => {
+ const range = options.rangeOf(item);
+ return range.path === path && spotKey(range) === key;
+ })
+ .sort(
+ (a, b) => options.rangeOf(a).lineNumber - options.rangeOf(b).lineNumber
+ );
+ const draftAt = (path: string, key: string) => {
+ const current = draft();
+ return current?.range.path === path && spotKey(current.range) === key
+ ? current
+ : undefined;
+ };
+ const rangeAt = (path: string, key: string) => {
+ const first = itemsAt(path, key)[0];
+ return draftAt(path, key)?.range ?? (first && options.rangeOf(first));
+ };
+
+ const startDraft = (range: LineRange) => setDraft({ range, text: '' });
+
+ return {
+ annotations: (entry) => {
+ const spots = new Map<string, LineAnnotation>();
+ const ranges = options
+ .items()
+ .map(options.rangeOf)
+ .concat(draft()?.range ?? []);
+ for (const range of ranges) {
+ if (range.path !== entry.file.path) continue;
+ const key = spotKey(range);
+ spots.set(key, {
+ key,
+ side: range.side,
+ lineNumber: range.endLineNumber,
+ });
+ }
+ return [...spots.values()];
+ },
+ renderAnnotation: (entry, key) => {
+ const path = entry.file.path;
+ return (
+ <div
+ class="font-sans"
+ onFocusIn={() => {
+ const range = rangeAt(path, key);
+ setFocused(
+ range
+ ? { range, whileDrafting: draft() !== undefined }
+ : undefined
+ );
+ }}
+ onFocusOut={(event) => {
+ const next = event.relatedTarget;
+ if (!(next instanceof Node && event.currentTarget.contains(next))) {
+ setFocused(undefined);
+ }
+ }}
+ >
+ {options.render({
+ path,
+ get items() {
+ return itemsAt(path, key);
+ },
+ get draft() {
+ return draftAt(path, key);
+ },
+ })}
+ </div>
+ );
+ },
+ selection: () => {
+ const current = focused();
+ const writing = draft();
+ if (current && (!current.whileDrafting || writing)) return current.range;
+ return writing?.range;
+ },
+ get onSelectLines() {
+ return options.canComment?.() === false ? undefined : startDraft;
+ },
+ draft,
+ startDraft,
+ editDraft: (text) => {
+ const current = draft();
+ if (current) setDraft({ ...current, text });
+ },
+ cancelDraft: () => setDraft(undefined),
+ };
+}
diff --git a/apps/web/src/components/diff-view/debug/CommentsDemo.tsx b/apps/web/src/components/diff-view/debug/CommentsDemo.tsx
new file mode 100644
index 0000000000..4257b9fb20
--- /dev/null
+++ b/apps/web/src/components/diff-view/debug/CommentsDemo.tsx
@@ -0,0 +1,163 @@
+/**
+ * Review threads under diff lines, the way a pull request host shows them:
+ * `createDiffComments` places the threads and holds the draft, and the
+ * `CommentThread` parts draw each one. Threads live in memory here.
+ */
+
+import { createSignal, For, Show } from 'solid-js';
+import { CommentThread } from '../comments/CommentThread';
+import { createDiffComments } from '../comments/create-diff-comments';
+import { DiffView } from '../DiffView';
+import type { LineRange } from '../model/lines';
+import { SAMPLE_FILES, SAMPLE_PATCH } from './fixtures';
+
+type ThreadComment = { id: number; author: string; text: string; at: string };
+type Thread = { id: number; range: LineRange; comments: ThreadComment[] };
+
+const UNREAD = 'apps/web/src/features/block-agent/state/unread.ts';
+const SERVICE = 'crates/macro_agent_sessions/src/service.rs';
+
+const SEED: Thread[] = [
+ {
+ id: 1,
+ range: {
+ path: UNREAD,
+ side: 'additions',
+ lineNumber: 8,
+ endLineNumber: 13,
+ },
+ comments: [
+ {
+ id: 1,
+ author: 'Maya Chen',
+ text: 'Could this take the archive time instead of the whole session?',
+ at: '2h',
+ },
+ {
+ id: 2,
+ author: 'Rahul',
+ text: 'The sidebar only has the summary, so the session is what it can pass.',
+ at: '1h',
+ },
+ ],
+ },
+ {
+ id: 2,
+ range: {
+ path: SERVICE,
+ side: 'additions',
+ startSide: 'deletions',
+ lineNumber: 87,
+ endLineNumber: 91,
+ },
+ comments: [
+ {
+ id: 3,
+ author: 'Sam Ortiz',
+ text: 'Mark read inside the same transaction, so a failed commit leaves both unset.',
+ at: '3h',
+ },
+ ],
+ },
+];
+
+/** Pierre's rows keep the context background unless the host clears it. */
+const THREAD_ROW_CSS = `
+[data-line-annotation], [data-gutter-buffer="annotation"] {
+ --diffs-annotation-bg: transparent;
+}`;
+
+export function CommentsDemo() {
+ const [threads, setThreads] = createSignal<Thread[]>(SEED);
+ let nextId = 100;
+ const post = (range: LineRange, text: string) => {
+ const comment = {
+ id: nextId++,
+ author: 'You',
+ text: text.trim(),
+ at: 'now',
+ };
+ setThreads((list) => {
+ const thread = list.find(
+ (item) =>
+ item.range.path === range.path &&
+ item.range.side === range.side &&
+ item.range.endLineNumber === range.endLineNumber
+ );
+ return thread
+ ? list.map((item) =>
+ item === thread
+ ? { ...item, comments: [...item.comments, comment] }
+ : item
+ )
+ : [...list, { id: nextId++, range, comments: [comment] }];
+ });
+ };
+
+ const comments = createDiffComments({
+ items: threads,
+ rangeOf: (thread) => thread.range,
+ render: (spot) => (
+ <CommentThread.Root>
+ <For each={spot.items}>
+ {(thread) => (
+ <For each={thread.comments}>
+ {(comment) => (
+ <CommentThread.Comment
+ author={comment.author}
+ time={comment.at}
+ >
+ {comment.text}
+ </CommentThread.Comment>
+ )}
+ </For>
+ )}
+ </For>
+ <Show
+ when={spot.draft}
+ fallback={
+ <Show when={spot.items[0]}>
+ {(thread) => (
+ <CommentThread.Reply
+ onClick={() => comments.startDraft(thread().range)}
+ />
+ )}
+ </Show>
+ }
+ >
+ {(draft) => (
+ <CommentThread.Composer
+ value={draft().text}
+ onInput={comments.editDraft}
+ onCancel={comments.cancelDraft}
+ onSubmit={() => {
+ post(draft().range, draft().text);
+ comments.cancelDraft();
+ }}
+ submitLabel={spot.items.length > 0 ? 'Reply' : 'Comment'}
+ placeholder={spot.items.length > 0 ? 'Reply' : 'Leave a comment'}
+ />
+ )}
+ </Show>
+ </CommentThread.Root>
+ ),
+ });
+
+ return (
+ <div class="flex h-[560px] min-h-0 flex-col overflow-hidden rounded-lg border border-edge bg-panel">
+ <DiffView.Root
+ files={SAMPLE_FILES.slice(1, 3)}
+ patch={SAMPLE_PATCH}
+ diffStyle="unified"
+ >
+ <DiffView.Stack
+ annotations={comments.annotations}
+ renderAnnotation={comments.renderAnnotation}
+ selection={comments.selection}
+ onSelectLines={comments.onSelectLines}
+ unsafeCSS={THREAD_ROW_CSS}
+ />
+ </DiffView.Root>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/diff-view/debug/DiffViewGallery.tsx b/apps/web/src/components/diff-view/debug/DiffViewGallery.tsx
new file mode 100644
index 0000000000..7d91a26e41
--- /dev/null
+++ b/apps/web/src/components/diff-view/debug/DiffViewGallery.tsx
@@ -0,0 +1,185 @@
+/**
+ * Debug gallery for the diff view: the parts composed the ways hosts compose
+ * them, over example changes. Registered as the `diff-view-ui` component.
+ */
+
+import CopyIcon from '@phosphor/copy.svg';
+import FileIcon from '@phosphor/file.svg';
+import { Button, SegmentedControl } from '@ui';
+import { FileTree } from '@ui/components/FileTree';
+import { createMemo, createSignal, type JSX, Show } from 'solid-js';
+import { DiffCounts } from '../DiffCounts';
+import { DiffView } from '../DiffView';
+import type { DiffFile, DiffStyle } from '../model/diff-file';
+import { StatusLetter } from '../StatusLetter';
+import { CommentsDemo } from './CommentsDemo';
+import { generatedChanges, SAMPLE_FILES, SAMPLE_PATCH } from './fixtures';
+
+function Item(props: { label: string; children: JSX.Element }) {
+ return (
+ <section class="flex flex-col gap-2">
+ <h2 class="text-xs font-medium uppercase tracking-wide text-ink-extra-muted">
+ {props.label}
+ </h2>
+ <div class="flex flex-col gap-2">{props.children}</div>
+ </section>
+ );
+}
+
+function Frame(props: { children: JSX.Element }) {
+ return (
+ <div class="flex h-[520px] min-h-0 flex-col overflow-hidden rounded-lg border border-edge bg-panel">
+ {props.children}
+ </div>
+ );
+}
+
+/** A file tree beside the stack, with the toolbar a pane would show. */
+function ComposedDemo(props: { files: DiffFile[]; patch: string }) {
+ const [style, setStyle] = createSignal<DiffStyle>('unified');
+ const [active, setActive] = createSignal<string>();
+ const reveal = (path: string) => {
+ // Re-selecting the same file must still scroll, so clear first.
+ setActive(undefined);
+ setActive(path);
+ };
+ return (
+ <Frame>
+ <DiffView.Root
+ files={props.files}
+ patch={props.patch}
+ diffStyle={style()}
+ active={active()}
+ >
+ <div class="flex h-10 shrink-0 items-center gap-2 border-b border-edge-muted px-3">
+ <span class="flex-1 text-xs text-ink-subtle">
+ {props.files.length} files
+ </span>
+ <DiffView.StyleToggle value={style()} onChange={setStyle} />
+ <DiffView.CollapseAll />
+ </div>
+ <div class="flex min-h-0 flex-1">
+ <FileTree.Root
+ aria-label="Changed files"
+ class="w-64 shrink-0 overflow-y-auto border-r border-edge-muted p-2"
+ items={props.files}
+ path={(file) => file.path}
+ selected={active()}
+ onSelect={(file) => reveal(file.path)}
+ >
+ {(node) => (
+ <>
+ <FileTree.Icon>
+ <FileIcon />
+ </FileTree.Icon>
+ <FileTree.Name />
+ <span class="shrink-0 text-xs">
+ <DiffCounts
+ additions={node.item.additions}
+ deletions={node.item.deletions}
+ />
+ </span>
+ <StatusLetter kind={node.item.kind} />
+ </>
+ )}
+ </FileTree.Root>
+ <DiffView.Stack />
+ </div>
+ </DiffView.Root>
+ </Frame>
+ );
+}
+
+/** A header with a host action after the default parts. */
+function CustomHeaderDemo() {
+ const [copied, setCopied] = createSignal<string>();
+ return (
+ <Frame>
+ <DiffView.Root
+ files={SAMPLE_FILES.slice(1, 3)}
+ patch={SAMPLE_PATCH}
+ diffStyle="split"
+ >
+ <DiffView.Stack
+ header={(entry) => (
+ <>
+ <DiffView.CollapseButton />
+ <DiffView.FilePath />
+ <DiffView.FileCounts />
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ tooltip="Copy path"
+ onClick={() => setCopied(entry.file.path)}
+ >
+ <CopyIcon />
+ </Button>
+ </>
+ )}
+ />
+ </DiffView.Root>
+ <p class="shrink-0 border-t border-edge-muted px-3 py-1.5 text-xs text-ink-subtle">
+ {copied() ? `Copied ${copied()}` : 'Copy a path from a header'}
+ </p>
+ </Frame>
+ );
+}
+
+/** Pick a size and scroll; the stack mounts one Pierre instance per file. */
+function LargeChangesetDemo() {
+ const [count, setCount] = createSignal('200');
+ const changes = createMemo(() => generatedChanges(Number(count())));
+ return (
+ <>
+ <SegmentedControl
+ size="sm"
+ aria-label="Files"
+ value={count()}
+ options={[
+ { value: '50', label: '50 files' },
+ { value: '200', label: '200 files' },
+ { value: '500', label: '500 files' },
+ ]}
+ onChange={setCount}
+ class="self-start"
+ />
+ <Show when={changes()} keyed>
+ {(current) => (
+ <ComposedDemo files={current.files} patch={current.patch} />
+ )}
+ </Show>
+ </>
+ );
+}
+
+export default function DiffViewGallery() {
+ return (
+ <div class="size-full overflow-auto">
+ <div class="mx-auto flex max-w-5xl flex-col gap-8 px-6 py-8">
+ <Item label="Composed: file tree, toolbar, and stack">
+ <ComposedDemo files={SAMPLE_FILES} patch={SAMPLE_PATCH} />
+ </Item>
+ <Item label="Custom header (split style)">
+ <CustomHeaderDemo />
+ </Item>
+ <Item label="Review threads under their lines">
+ <CommentsDemo />
+ </Item>
+ <Item label="Files without diff text">
+ <Frame>
+ <DiffView.Root
+ files={SAMPLE_FILES.slice(-2)}
+ patch=""
+ diffStyle="unified"
+ >
+ <DiffView.Stack />
+ </DiffView.Root>
+ </Frame>
+ </Item>
+ <Item label="Large changeset">
+ <LargeChangesetDemo />
+ </Item>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/diff-view/debug/fixtures.ts b/apps/web/src/components/diff-view/debug/fixtures.ts
new file mode 100644
index 0000000000..44df233991
--- /dev/null
+++ b/apps/web/src/components/diff-view/debug/fixtures.ts
@@ -0,0 +1,224 @@
+/**
+ * Example changes for the diff view's debug gallery, and for other
+ * galleries that mount the view.
+ */
+
+import type { DiffFile } from '../model/diff-file';
+
+/** A patch across the web app, two crates, and a migration. */
+export const SAMPLE_PATCH = `diff --git a/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts b/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
+index 1111111..2222222 100644
+--- a/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
++++ b/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
+@@ -7,7 +7,8 @@
+ import { createMemo } from 'solid-js';
+
+ import { useAgentSessionsQuery } from '@queries/agent/sessions';
+-import type { AgentSessionSummary } from '@service-agent-fold/generated/types';
++import { hasUnreadActivity } from '@block-agent/state/unread';
++import type { AgentSessionSummary } from '@service-agent-fold/generated/types';
+
+ import type { SidebarItemId } from '../nav-items';
+
+@@ -19,12 +20,15 @@ const DOTTED: readonly SidebarItemId[] = ['inbox', 'channels', 'agents'];
+ export function useSidebarUnread(): (id: SidebarItemId) => boolean {
+ const sessions = useAgentSessionsQuery();
+
+- // Activity after the read marker lights the dot.
+- const agentsUnread = createMemo(() =>
+- (sessions.data ?? []).some(
+- (session: AgentSessionSummary) => session.lastEventAt > session.lastReadAt
+- )
+- );
++ // Archiving takes a session off the inbox, so its activity stops being
++ // news. The rail has to ask the same question the agents list asks,
++ // through the same predicate.
++ const agentsUnread = createMemo(() =>
++ (sessions.data ?? []).some((session: AgentSessionSummary) =>
++ hasUnreadActivity(session)
++ )
++ );
+
+ return (id) => (id === 'agents' ? agentsUnread() : false);
+ }
+diff --git a/apps/web/src/features/block-agent/state/unread.ts b/apps/web/src/features/block-agent/state/unread.ts
+new file mode 100644
+index 0000000..3333333
+--- /dev/null
++++ b/apps/web/src/features/block-agent/state/unread.ts
+@@ -0,0 +1,14 @@
++import type { AgentSessionSummary } from '@service-agent-fold/generated/types';
++
++/** An archived session is off the inbox, so its activity is not news. */
++export function isArchived(session: AgentSessionSummary): boolean {
++ return session.archivedAt != null;
++}
++
++export function hasUnreadActivity(session: AgentSessionSummary): boolean {
++ if (isArchived(session)) return false;
++ const lastEventAt = session.lastEventAt;
++ if (lastEventAt == null) return false;
++ return lastEventAt > (session.lastReadAt ?? 0);
++}
++
+diff --git a/crates/macro_agent_sessions/src/service.rs b/crates/macro_agent_sessions/src/service.rs
+index 4444444..5555555 100644
+--- a/crates/macro_agent_sessions/src/service.rs
++++ b/crates/macro_agent_sessions/src/service.rs
+@@ -85,8 +85,14 @@ impl SessionService {
+ #[instrument(skip(self), fields(session_id = %id))]
+ pub async fn archive(&self, id: AgentSessionId) -> Result<(), ArchiveError> {
+- self.repo.set_archived(id, Utc::now()).await?;
+- Ok(())
++ let now = Utc::now();
++ let mut tx = self.repo.begin().await?;
++
++ self.repo.set_archived(&mut tx, id, now).await?;
++ self.repo.mark_read(&mut tx, id, now).await?;
++
++ tx.commit().await?;
++ Ok(())
+ }
+
+ #[instrument(skip(self), fields(owner = %owner))]
+diff --git a/crates/macro_agent_sessions/src/legacy_unread.rs b/crates/macro_agent_sessions/src/legacy_unread.rs
+deleted file mode 100644
+index 6666666..0000000
+--- a/crates/macro_agent_sessions/src/legacy_unread.rs
++++ /dev/null
+@@ -1,3 +0,0 @@
+-pub fn unread(last_event_at: i64, last_read_at: i64) -> bool {
+- last_event_at > last_read_at
+-}
+diff --git a/crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql b/crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql
+new file mode 100644
+index 0000000..7777777
+--- /dev/null
++++ b/crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql
+@@ -0,0 +1,5 @@
++-- Archived sessions drop out of the unread count. Without a partial index
++-- the filter falls back to a sequential scan on long workspace histories.
++CREATE INDEX CONCURRENTLY IF NOT EXISTS agent_sessions_unread_active_idx
++ ON agent_sessions (owner_id, last_event_at DESC)
++ WHERE archived_at IS NULL;
+`;
+
+/** The files behind `SAMPLE_PATCH`, plus a binary file and a bare rename. */
+export const SAMPLE_FILES: DiffFile[] = [
+ {
+ path: 'apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts',
+ kind: 'modified',
+ additions: 10,
+ deletions: 7,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'apps/web/src/features/block-agent/state/unread.ts',
+ kind: 'added',
+ additions: 14,
+ deletions: 0,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'crates/macro_agent_sessions/src/service.rs',
+ kind: 'modified',
+ additions: 8,
+ deletions: 2,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'crates/macro_agent_sessions/src/legacy_unread.rs',
+ kind: 'deleted',
+ additions: 0,
+ deletions: 3,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql',
+ kind: 'added',
+ additions: 5,
+ deletions: 0,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'docs/agents/unread.md',
+ previousPath: 'docs/unread.md',
+ kind: 'renamed',
+ additions: 0,
+ deletions: 0,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'static_assets/logo.png',
+ kind: 'modified',
+ additions: 0,
+ deletions: 0,
+ binary: true,
+ patchOmitted: false,
+ },
+];
+
+const GENERATED_DIRECTORIES = [
+ 'apps/web/src/features/inbox/components',
+ 'apps/web/src/features/inbox/queries',
+ 'apps/web/src/lib/core/util',
+ 'crates/macro_inbox/src',
+ 'crates/macro_inbox/src/outbound',
+ 'packages/email-renderer/src',
+];
+
+/**
+ * A changeset of `fileCount` modified files spread over a few directories,
+ * each with one hunk, for trying the view at pull request sizes.
+ */
+export function generatedChanges(fileCount: number): {
+ files: DiffFile[];
+ patch: string;
+} {
+ const files: DiffFile[] = [];
+ const parts: string[] = [];
+ for (let index = 0; index < fileCount; index += 1) {
+ const directory =
+ GENERATED_DIRECTORIES[index % GENERATED_DIRECTORIES.length]!;
+ const extension = directory.startsWith('crates') ? 'rs' : 'ts';
+ const name = `generated_${String(index).padStart(3, '0')}.${extension}`;
+ const path = `${directory}/${name}`;
+ const lineCount = 8 + (index % 5) * 6;
+ const body: string[] = [];
+ let changed = 0;
+ for (let line = 1; line <= lineCount; line += 1) {
+ if (line % 4 === 0) {
+ changed += 1;
+ body.push(`-const value${line} = ${line};`);
+ body.push(`+const value${line} = ${line * 2};`);
+ } else {
+ body.push(` const value${line} = ${line};`);
+ }
+ }
+ parts.push(
+ [
+ `diff --git a/${path} b/${path}`,
+ 'index 1111111..2222222 100644',
+ `--- a/${path}`,
+ `+++ b/${path}`,
+ `@@ -1,${lineCount} +1,${lineCount} @@`,
+ ...body,
+ ].join('\n')
+ );
+ files.push({
+ path,
+ kind: 'modified',
+ additions: changed,
+ deletions: changed,
+ binary: false,
+ patchOmitted: false,
+ });
+ }
+ return { files, patch: `${parts.join('\n')}\n` };
+}
diff --git a/apps/web/src/components/diff-view/index.ts b/apps/web/src/components/diff-view/index.ts
new file mode 100644
index 0000000000..4e02434d2c
--- /dev/null
+++ b/apps/web/src/components/diff-view/index.ts
@@ -0,0 +1,7 @@
+export type { DiffCollapse } from './collapse';
+export { CommentThread } from './comments/CommentThread';
+export { createDiffComments } from './comments/create-diff-comments';
+export { DiffCounts } from './DiffCounts';
+export { DiffView } from './DiffView';
+export type { DiffStyle } from './model/diff-file';
+export { StatusLetter } from './StatusLetter';
diff --git a/apps/web/src/components/diff-view/model/diff-file.ts b/apps/web/src/components/diff-view/model/diff-file.ts
new file mode 100644
index 0000000000..579310c365
--- /dev/null
+++ b/apps/web/src/components/diff-view/model/diff-file.ts
@@ -0,0 +1,46 @@
+/**
+ * A changed file as the diff view shows it, and the small derivations its
+ * rows need. A host's own file records only need to match this shape.
+ */
+
+/** What happened to a file between the base and the head. */
+export type DiffFileKind = 'added' | 'modified' | 'deleted' | 'renamed';
+
+export type DiffFile = {
+ /** The path after the change, or before it for a deletion. */
+ path: string;
+ /** Where a renamed file came from. */
+ previousPath?: string;
+ kind: DiffFileKind;
+ additions: number;
+ deletions: number;
+ /** The diff carries no text for this file. */
+ binary: boolean;
+ /** The file's hunks were left out of the patch to fit a size budget. */
+ patchOmitted: boolean;
+};
+
+export type DiffStyle = 'unified' | 'split';
+
+/** The one-letter status the tree and file headers show. */
+export type StatusLetter = 'A' | 'M' | 'D' | 'R';
+
+export function statusLetter(kind: DiffFileKind): StatusLetter {
+ switch (kind) {
+ case 'added':
+ return 'A';
+ case 'modified':
+ return 'M';
+ case 'deleted':
+ return 'D';
+ case 'renamed':
+ return 'R';
+ }
+}
+
+/** A path split into the directory prefix (with trailing slash) and basename. */
+export function splitPath(path: string): { dir: string; base: string } {
+ const at = path.lastIndexOf('/');
+ if (at < 0) return { dir: '', base: path };
+ return { dir: path.slice(0, at + 1), base: path.slice(at + 1) };
+}
diff --git a/apps/web/src/components/diff-view/model/lines.ts b/apps/web/src/components/diff-view/model/lines.ts
new file mode 100644
index 0000000000..3235d47a04
--- /dev/null
+++ b/apps/web/src/components/diff-view/model/lines.ts
@@ -0,0 +1,32 @@
+/**
+ * Lines of a file's diff that a host picks, or hangs its own content under
+ * (review notes, comments). The view places the content; the host decides
+ * what it says.
+ */
+
+/** Which side of the diff a line belongs to, in Pierre's vocabulary. */
+export type DiffSide = 'additions' | 'deletions';
+
+/**
+ * A run of lines in a file's diff. It ends on `side`, where content hangs. In
+ * the unified view a range can start on the other side, dragged from deleted
+ * lines into added ones, like GitHub's `start_side`.
+ */
+export type LineRange = {
+ path: string;
+ side: DiffSide;
+ /** Set only when the first line is on the other side from the last. */
+ startSide?: DiffSide;
+ /** First line, in `startSide`'s numbering (or `side`'s when unset). */
+ lineNumber: number;
+ /** Last line, in `side`'s numbering; equal to `lineNumber` for one line. */
+ endLineNumber: number;
+};
+
+/** A spot under one line where host content hangs. */
+export type LineAnnotation = {
+ /** Unique within the file; handed back to the host to render. */
+ key: string;
+ side: DiffSide;
+ lineNumber: number;
+};
diff --git a/apps/web/src/features/agent-changes/core/patch.test.ts b/apps/web/src/components/diff-view/model/patch.test.ts
similarity index 94%
rename from apps/web/src/features/agent-changes/core/patch.test.ts
rename to apps/web/src/components/diff-view/model/patch.test.ts
index ee76b020ee..ecde6962d6 100644
--- a/apps/web/src/features/agent-changes/core/patch.test.ts
+++ b/apps/web/src/components/diff-view/model/patch.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import type { ChangedFile } from './changeset';
+import type { DiffFile } from './diff-file';
import { matchFilesToDiffs, parsePatch } from './patch';
const PATCH = `diff --git a/src/a.ts b/src/a.ts
@@ -17,7 +17,7 @@ rename from old.txt
rename to new.txt
`;
-function file(overrides: Partial<ChangedFile>): ChangedFile {
+function file(overrides: Partial<DiffFile>): DiffFile {
return {
path: 'src/a.ts',
kind: 'modified',
diff --git a/apps/web/src/features/agent-changes/core/patch.ts b/apps/web/src/components/diff-view/model/patch.ts
similarity index 77%
rename from apps/web/src/features/agent-changes/core/patch.ts
rename to apps/web/src/components/diff-view/model/patch.ts
index b36f71fac4..02cd0bd4ab 100644
--- a/apps/web/src/features/agent-changes/core/patch.ts
+++ b/apps/web/src/components/diff-view/model/patch.ts
@@ -1,14 +1,14 @@
/**
- * The patch behind a changeset, parsed once into Pierre's per-file diffs and
- * matched back to the summary's files by path.
+ * A unified patch, parsed once into Pierre's per-file diffs and matched back
+ * to the host's files by path.
*/
import { type FileDiffMetadata, parsePatchFiles } from '@pierre/diffs';
-import type { ChangedFile } from './changeset';
+import type { DiffFile } from './diff-file';
-/** One file's parsed diff, or why there is none to render. */
-export type FileDiffEntry = {
- file: ChangedFile;
+/** One file's parsed diff, or why there is none to draw. */
+export type DiffEntry = {
+ file: DiffFile;
/** Absent when the patch has no text for the file. */
diff?: FileDiffMetadata;
/** Why the diff is absent, in a phrase the card can show. */
@@ -29,11 +29,11 @@ export function parsePatch(patch: string): Map<string, FileDiffMetadata> {
return byPath;
}
-/** Pair each summary file with its parsed diff, in summary order. */
+/** Pair each file with its parsed diff, in the files' order. */
export function matchFilesToDiffs(
- files: readonly ChangedFile[],
+ files: readonly DiffFile[],
diffs: ReadonlyMap<string, FileDiffMetadata>
-): FileDiffEntry[] {
+): DiffEntry[] {
return files.map((file) => {
if (file.binary) return { file, note: 'Binary file' };
if (file.patchOmitted) {
diff --git a/apps/web/src/components/diff-view/pierre/PierreFileDiff.tsx b/apps/web/src/components/diff-view/pierre/PierreFileDiff.tsx
new file mode 100644
index 0000000000..adeef360d1
--- /dev/null
+++ b/apps/web/src/components/diff-view/pierre/PierreFileDiff.tsx
@@ -0,0 +1,196 @@
+/**
+ * One file's diff rendered by Pierre's vanilla `FileDiff`, with a host's
+ * content hung under its lines and Pierre's gutter utility (the "+" that
+ * appears on hover, draggable over a range) to pick lines for more.
+ *
+ * Pierre renders inside a shadow root but slots annotation content from
+ * the light DOM, so the host's content is ordinary Solid markup mounted
+ * with `render` into the elements Pierre asks for.
+ */
+
+import {
+ type DiffLineAnnotation,
+ FileDiff,
+ type FileDiffMetadata,
+ type FileDiffOptions,
+ type SelectedLineRange,
+} from '@pierre/diffs';
+import {
+ createEffect,
+ createMemo,
+ type JSX,
+ on,
+ onCleanup,
+ onMount,
+} from 'solid-js';
+import { render } from 'solid-js/web';
+import type { DiffStyle } from '../model/diff-file';
+import type { LineAnnotation, LineRange } from '../model/lines';
+import {
+ PIERRE_APP_COLORS,
+ PIERRE_STYLE_VARIABLES,
+ type ThemeType,
+} from './theme';
+
+const DIFF_STYLE = { ...PIERRE_STYLE_VARIABLES, ...PIERRE_APP_COLORS };
+
+/** Options that never change for the view's diffs. */
+const BASE_OPTIONS = {
+ diffIndicators: 'bars',
+ // The file card renders its own header.
+ disableFileHeader: true,
+ overflow: 'wrap',
+ hunkSeparators: 'line-info-basic',
+ lineDiffType: 'word-alt',
+ expansionLineCount: 20,
+ lineHoverHighlight: 'line',
+} satisfies FileDiffOptions<string>;
+
+export function PierreFileDiff(props: {
+ path: string;
+ diff: FileDiffMetadata;
+ diffStyle: DiffStyle;
+ themeType: ThemeType;
+ /** Where host content hangs on this file. */
+ annotations: LineAnnotation[];
+ /** The content under one of `annotations`, by its key. */
+ renderAnnotation: (key: string) => JSX.Element;
+ /** The lines to light on this file, such as a range being annotated. */
+ selection: LineRange | undefined;
+ /** Turns on the gutter "+"; omit for a diff whose lines cannot be picked. */
+ onSelectLines?: (range: LineRange) => void;
+ /** CSS injected into Pierre's shadow root. */
+ unsafeCSS?: string;
+}) {
+ let container!: HTMLDivElement;
+ let instance: FileDiff<string> | undefined;
+ const roots = new Map<string, () => void>();
+
+ const disposeRoots = () => {
+ for (const dispose of roots.values()) dispose();
+ roots.clear();
+ };
+
+ const annotations = createMemo((): DiffLineAnnotation<string>[] =>
+ props.annotations
+ .map(({ key, side, lineNumber }) => ({ side, lineNumber, metadata: key }))
+ .sort(
+ (a, b) => a.lineNumber - b.lineNumber || a.side.localeCompare(b.side)
+ )
+ );
+
+ const renderAnnotation = (annotation: DiffLineAnnotation<string>) => {
+ const key = annotation.metadata;
+ roots.get(key)?.();
+ const element = document.createElement('div');
+ roots.set(
+ key,
+ render(() => props.renderAnnotation(key), element)
+ );
+ return element;
+ };
+
+ // A unified drag can run from deleted lines into added ones; its ends are
+ // then in different numberings, so they are kept as given, not reordered.
+ const onGutterUtilityClick = (range: SelectedLineRange) => {
+ const side = range.endSide ?? range.side ?? 'additions';
+ const startSide = range.side ?? side;
+ props.onSelectLines?.(
+ startSide === side
+ ? {
+ path: props.path,
+ side,
+ lineNumber: Math.min(range.start, range.end),
+ endLineNumber: Math.max(range.start, range.end),
+ }
+ : {
+ path: props.path,
+ side,
+ startSide,
+ lineNumber: range.start,
+ endLineNumber: range.end,
+ }
+ );
+ };
+
+ const currentOptions = (): FileDiffOptions<string> => ({
+ ...BASE_OPTIONS,
+ diffStyle: props.diffStyle,
+ themeType: props.themeType,
+ unsafeCSS: props.unsafeCSS,
+ renderAnnotation,
+ enableGutterUtility: props.onSelectLines !== undefined,
+ onGutterUtilityClick: props.onSelectLines
+ ? onGutterUtilityClick
+ : undefined,
+ });
+
+ onMount(() => {
+ instance = new FileDiff<string>(currentOptions());
+ });
+
+ // A new diff or layout re-renders from scratch; a change to the
+ // annotations re-renders too, since Pierre only stores annotations handed
+ // to `setLineAnnotations` and paints them on the next render. Elements for
+ // unchanged annotations are kept across renders. A layout change must be
+ // forced: Pierre otherwise treats unchanged content as a partial render.
+ createEffect(
+ on(
+ [() => props.diff, () => props.diffStyle, annotations],
+ ([diff, diffStyle, list], previous) => {
+ if (!instance) return;
+ instance.setOptions(currentOptions());
+ instance.render({
+ fileDiff: diff,
+ containerWrapper: container,
+ lineAnnotations: list,
+ forceRender: previous !== undefined && previous[1] !== diffStyle,
+ });
+ }
+ )
+ );
+
+ // Pierre lights one range per file. It follows the host: the range being
+ // annotated, one the host points at (a focused comment), or none.
+ createEffect(
+ on(
+ () => props.selection,
+ (selection) => {
+ instance?.setSelectedLines(
+ selection
+ ? {
+ start: selection.lineNumber,
+ side: selection.startSide ?? selection.side,
+ end: selection.endLineNumber,
+ endSide: selection.side,
+ }
+ : null,
+ { notify: false }
+ );
+ },
+ { defer: true }
+ )
+ );
+
+ createEffect(
+ on(
+ () => props.themeType,
+ (themeType) => instance?.setThemeType(themeType),
+ { defer: true }
+ )
+ );
+
+ onCleanup(() => {
+ disposeRoots();
+ instance?.cleanUp();
+ instance = undefined;
+ });
+
+ return (
+ <div
+ ref={container}
+ class="overflow-hidden bg-surface"
+ style={DIFF_STYLE}
+ />
+ );
+}
diff --git a/apps/web/src/components/diff-view/pierre/theme.ts b/apps/web/src/components/diff-view/pierre/theme.ts
new file mode 100644
index 0000000000..5631a5836e
--- /dev/null
+++ b/apps/web/src/components/diff-view/pierre/theme.ts
@@ -0,0 +1,73 @@
+/**
+ * What every Pierre diff in the app shares: Macro's light/dark state as a
+ * signal, and the CSS variables Pierre reads inside its shadow DOM.
+ */
+
+import { type Accessor, createSignal, type JSX, onCleanup } from 'solid-js';
+
+export type ThemeType = 'light' | 'dark';
+
+/** Points Pierre at Macro's mono typography so diffs match the text around them. */
+export const PIERRE_STYLE_VARIABLES: JSX.CSSProperties = {
+ '--diffs-font-family': 'var(--font-mono)',
+ '--diffs-font-size': '0.75rem',
+ '--diffs-line-height': '18px',
+ '--diffs-tab-size': '2',
+ '--diffs-gap-block': '0',
+ '--diffs-min-number-column-width': '4ch',
+};
+
+/**
+ * Pierre's colour overrides pointed at Macro's tokens, so a diff sits on its
+ * card's surface and tints changes with the app's success and failure hues.
+ * Tints are mixed onto `--color-surface` rather than using the translucent
+ * `*-bg` tokens, because Pierre paints its theme background underneath.
+ * Syntax colours still come from Pierre's light and dark themes.
+ */
+export const PIERRE_APP_COLORS: JSX.CSSProperties = {
+ '--diffs-addition-color-override': 'var(--color-success)',
+ '--diffs-deletion-color-override': 'var(--color-failure)',
+ '--diffs-modified-color-override': 'var(--color-accent)',
+ '--diffs-bg-context-override': 'var(--color-surface)',
+ '--diffs-bg-context-gutter-override': 'var(--color-surface)',
+ '--diffs-bg-buffer-override': 'var(--color-surface)',
+ '--diffs-bg-separator-override': 'var(--color-inset)',
+ '--diffs-bg-addition-override':
+ 'color-mix(in oklch, var(--color-success) 15%, var(--color-surface))',
+ '--diffs-bg-addition-number-override':
+ 'color-mix(in oklch, var(--color-success) 22%, var(--color-surface))',
+ '--diffs-bg-deletion-override':
+ 'color-mix(in oklch, var(--color-failure) 15%, var(--color-surface))',
+ '--diffs-bg-deletion-number-override':
+ 'color-mix(in oklch, var(--color-failure) 22%, var(--color-surface))',
+ '--diffs-fg-number-override': 'var(--color-ink-subtle)',
+};
+
+function currentThemeType(): ThemeType {
+ if (typeof document === 'undefined') return 'light';
+ return document.documentElement.dataset.themeLight === 'false'
+ ? 'dark'
+ : 'light';
+}
+
+/**
+ * Tracked off the `data-theme-light` attribute the theme feature keeps on
+ * `<html>`, instead of Pierre's OS-preference "system" mode.
+ */
+export function createThemeType(): Accessor<ThemeType> {
+ const [themeType, setThemeType] = createSignal<ThemeType>(currentThemeType());
+ if (
+ typeof document !== 'undefined' &&
+ typeof MutationObserver !== 'undefined'
+ ) {
+ const observer = new MutationObserver(() =>
+ setThemeType(currentThemeType())
+ );
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ['data-theme-light'],
+ });
+ onCleanup(() => observer.disconnect());
+ }
+ return themeType;
+}
diff --git a/apps/web/src/components/ui/components/CollapseTransition.docs.tsx b/apps/web/src/components/ui/components/CollapseTransition.docs.tsx
new file mode 100644
index 0000000000..7c16b7a6cb
--- /dev/null
+++ b/apps/web/src/components/ui/components/CollapseTransition.docs.tsx
@@ -0,0 +1,44 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { createSignal, For } from 'solid-js';
+import { Button } from './Button';
+import { CollapseTransition } from './CollapseTransition';
+
+// #region demo:disclosure
+function DisclosureDemo() {
+ const [open, setOpen] = createSignal(true);
+ return (
+ <div class="flex w-72 flex-col gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ class="self-start"
+ aria-expanded={open()}
+ onClick={() => setOpen((value) => !value)}
+ >
+ {open() ? 'Hide files' : 'Show files'}
+ </Button>
+ <CollapseTransition open={open()}>
+ <ul class="flex flex-col gap-1 rounded-lg border border-edge-muted p-2 text-sm text-ink-muted">
+ <For each={['README.md', 'justfile', 'Cargo.toml']}>
+ {(name) => <li>{name}</li>}
+ </For>
+ </ul>
+ </CollapseTransition>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'CollapseTransition',
+ category: 'Layout',
+ status: 'stable',
+ description:
+ 'Animates a disclosure body open and closed, measuring its height, and mounts the body only while open. Sidebar sections, tree branches, and tool groups share it.',
+ exports: ['CollapseTransition'],
+ import:
+ "import { CollapseTransition } from '@ui/components/CollapseTransition';",
+ demos: [
+ { id: 'disclosure', title: 'Show and hide a body', render: DisclosureDemo },
+ ],
+});
diff --git a/apps/web/src/components/view-shell/CollapseTransition.tsx b/apps/web/src/components/ui/components/CollapseTransition.tsx
similarity index 86%
rename from apps/web/src/components/view-shell/CollapseTransition.tsx
rename to apps/web/src/components/ui/components/CollapseTransition.tsx
index f8b2ad9465..e9e2cab67f 100644
--- a/apps/web/src/components/view-shell/CollapseTransition.tsx
+++ b/apps/web/src/components/ui/components/CollapseTransition.tsx
@@ -4,14 +4,24 @@ import { Transition } from 'solid-transition-group';
const COLLAPSE_DURATION = 140;
-/** Animate a disclosure body, or its containing section when flex owns its size. */
-export function CollapseTransition(props: {
+export type CollapseTransitionProps = {
open: boolean;
+ /** Animate this element's size instead of the body's, when flex owns it. */
container?: () => HTMLElement | undefined;
axis?: 'height' | 'width';
collapsedSize?: number;
children: JSX.Element;
-}) {
+};
+
+/**
+ * Animate a disclosure body, or its containing section when flex owns its size.
+ * @do Wrap the body that opens and closes; it mounts only while `open`.
+ * @do Use `axis="width"` for a side column such as a file tree beside content.
+ * @do Keep state the body needs across closing outside it; closing unmounts it.
+ * @dont Do not add your own height or opacity transition to the body; the
+ * animation measures it and would fight a second one.
+ */
+export function CollapseTransition(props: CollapseTransitionProps) {
const content = children(() => (
<Show when={props.open}>{props.children}</Show>
));
diff --git a/apps/web/src/components/ui/components/FileTree.docs.tsx b/apps/web/src/components/ui/components/FileTree.docs.tsx
new file mode 100644
index 0000000000..719c4977fe
--- /dev/null
+++ b/apps/web/src/components/ui/components/FileTree.docs.tsx
@@ -0,0 +1,180 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import FileIcon from '@phosphor/file.svg';
+import FileCodeIcon from '@phosphor/file-code.svg';
+import FileTextIcon from '@phosphor/file-text.svg';
+import FolderIcon from '@phosphor/folder.svg';
+import { createSignal, type JSX } from 'solid-js';
+import type { FileTreeDirectory, FileTreeNode } from '../utils/file-tree';
+import { FileTree } from './FileTree';
+
+type ExampleFile = { path: string; bytes: number; owner?: string };
+
+const REPOSITORY: ExampleFile[] = [
+ { path: 'apps/web/src/features/inbox/InboxView.tsx', bytes: 8200 },
+ { path: 'apps/web/src/features/inbox/inbox-query.ts', bytes: 2100 },
+ { path: 'apps/web/src/features/inbox/README.md', bytes: 900 },
+ { path: 'apps/web/src/lib/core/util/url.ts', bytes: 1300, owner: 'core' },
+ { path: 'crates/macro_inbox/src/lib.rs', bytes: 4100, owner: 'backend' },
+ {
+ path: 'crates/macro_inbox/src/outbound/postgres.rs',
+ bytes: 6400,
+ owner: 'backend',
+ },
+ { path: 'crates/macro_inbox/Cargo.toml', bytes: 700, owner: 'backend' },
+ { path: 'docs/STYLE_GUIDE.md', bytes: 15_000 },
+ { path: 'justfile', bytes: 2600 },
+ { path: 'README.md', bytes: 3100 },
+];
+
+function FileGlyph(props: { path: string }) {
+ if (/\.(tsx?|rs)$/.test(props.path)) return <FileCodeIcon />;
+ if (/\.md$/.test(props.path)) return <FileTextIcon />;
+ return <FileIcon />;
+}
+
+/** A sidebar-sized frame with the selection read back below the tree. */
+function Frame(props: {
+ files: ExampleFile[];
+ row?: (file: ExampleFile) => JSX.Element;
+ directory?: (directory: FileTreeDirectory<ExampleFile>) => JSX.Element;
+}) {
+ const [selected, setSelected] = createSignal<string>();
+ return (
+ <div class="flex w-80 flex-col overflow-hidden rounded-lg border border-edge bg-panel">
+ <FileTree.Root
+ aria-label="Example files"
+ class="max-h-96 overflow-y-auto p-2"
+ items={props.files}
+ path={(file) => file.path}
+ selected={selected()}
+ onSelect={(file) => setSelected(file.path)}
+ directory={props.directory}
+ >
+ {(node) => (
+ <>
+ <FileTree.Icon>
+ <FileGlyph path={node.path} />
+ </FileTree.Icon>
+ <FileTree.Name />
+ {props.row?.(node.item)}
+ </>
+ )}
+ </FileTree.Root>
+ <p class="truncate border-t border-edge-muted px-3 py-1.5 text-xs text-ink-subtle">
+ {selected() ?? 'Click a file, or use the arrow keys'}
+ </p>
+ </div>
+ );
+}
+
+// #region demo:basic
+function BasicDemo() {
+ return <Frame files={REPOSITORY} />;
+}
+// #endregion
+
+// #region demo:trailing
+function TrailingDemo() {
+ const size = (bytes: number) =>
+ bytes < 1000 ? `${bytes} B` : `${(bytes / 1000).toFixed(1)} kB`;
+ return (
+ <Frame
+ files={REPOSITORY}
+ row={(file) => (
+ <span class="shrink-0 text-xs tabular-nums text-ink-placeholder">
+ {size(file.bytes)}
+ </span>
+ )}
+ />
+ );
+}
+// #endregion
+
+// #region demo:directories
+function DirectoriesDemo() {
+ const countFiles = (node: FileTreeNode<ExampleFile>): number =>
+ node.kind === 'file'
+ ? 1
+ : node.children.reduce((sum, child) => sum + countFiles(child), 0);
+ return (
+ <Frame
+ files={REPOSITORY}
+ row={(file) =>
+ file.owner ? (
+ <span class="shrink-0 rounded-full border border-edge-muted px-1.5 text-xs text-ink-subtle">
+ {file.owner}
+ </span>
+ ) : undefined
+ }
+ directory={(directory) => (
+ <>
+ <FileTree.Icon>
+ <FolderIcon />
+ </FileTree.Icon>
+ <FileTree.Name />
+ <span class="shrink-0 text-xs tabular-nums text-ink-placeholder">
+ {countFiles(directory)}
+ </span>
+ </>
+ )}
+ />
+ );
+}
+// #endregion
+
+// #region demo:compressed
+function CompressedDemo() {
+ return (
+ <Frame
+ files={[
+ { path: 'a/b/c/d/e/f/only-child.ts', bytes: 100 },
+ { path: 'a/b/c/d/sibling.ts', bytes: 100 },
+ { path: 'x/y/z/far/away/file.ts', bytes: 100 },
+ { path: 'x/y/near.ts', bytes: 100 },
+ ]}
+ />
+ );
+}
+// #endregion
+
+// #region demo:large
+function LargeDemo() {
+ const areas = ['apps/web/src/features', 'crates', 'packages', 'services'];
+ const files = Array.from({ length: 600 }, (_, index) => ({
+ path: `${areas[index % areas.length]}/module_${Math.floor(index / 12) % 25}/part_${index % 3}/file_${index}.ts`,
+ bytes: 200 + ((index * 97) % 9000),
+ }));
+ return <Frame files={files} />;
+}
+// #endregion
+
+export default defineDoc({
+ name: 'FileTree',
+ category: 'Navigation',
+ status: 'beta',
+ description:
+ 'Items shown as a tree of paths. The root builds the tree, compresses single-child directories, and owns open directories, the selection, and the arrow keys; the host renders each file row.',
+ exports: ['FileTree'],
+ import: "import { FileTree } from '@ui/components/FileTree';",
+ propTypes: ['FileTreeRootProps'],
+ demos: [
+ { id: 'basic', title: 'Names and file icons', render: BasicDemo },
+ {
+ id: 'trailing',
+ title: 'Trailing content',
+ description: 'Anything after `FileTree.Name` sits at the row end.',
+ render: TrailingDemo,
+ },
+ {
+ id: 'directories',
+ title: 'Custom directory rows',
+ render: DirectoriesDemo,
+ },
+ {
+ id: 'compressed',
+ title: 'Compressed single-child chains',
+ render: CompressedDemo,
+ },
+ { id: 'large', title: '600 files', render: LargeDemo },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/FileTree.tsx b/apps/web/src/components/ui/components/FileTree.tsx
new file mode 100644
index 0000000000..bc66e09c53
--- /dev/null
+++ b/apps/web/src/components/ui/components/FileTree.tsx
@@ -0,0 +1,263 @@
+/**
+ * Items shown as a tree of paths, with rows sized and coloured like the
+ * workspace sidebar's trees (Drive's folders, the tag tree): 32px rows, a
+ * leading icon slot, a disclosure button on the right rail, and a guide line
+ * under each open directory, which opens and closes with the same
+ * `CollapseTransition`. The root owns open directories and the selection;
+ * the host decides what each file row shows.
+ *
+ * Rows are ordinary buttons, reached with Tab like the sidebar trees. The
+ * arrow keys also move between rows, and Left/Right close and open a
+ * directory.
+ */
+
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import FolderIcon from '@phosphor/folder.svg';
+import FolderOpenIcon from '@phosphor/folder-open.svg';
+import {
+ createContext,
+ createMemo,
+ createSignal,
+ For,
+ type JSX,
+ splitProps,
+ useContext,
+} from 'solid-js';
+import { cn } from '../utils/classname';
+import {
+ buildFileTree,
+ type FileTreeDirectory,
+ type FileTreeFile,
+ type FileTreeNode,
+ visibleNodes,
+} from '../utils/file-tree';
+import { Button } from './Button';
+import { CollapseTransition } from './CollapseTransition';
+
+const NodeContext = createContext<FileTreeNode<unknown>>();
+
+/** The leading glyph slot, so every row's name starts on the same line. */
+function Icon(props: { children: JSX.Element; class?: string }) {
+ return (
+ <span
+ aria-hidden="true"
+ class={cn(
+ 'flex size-5 shrink-0 items-center justify-center [&>svg]:size-4',
+ props.class
+ )}
+ >
+ {props.children}
+ </span>
+ );
+}
+
+/** The current row's name: a file's basename, or a directory's segment. */
+function Name(props: { class?: string }) {
+ const node = useContext(NodeContext);
+ if (!node) throw new Error('FileTree.Name must be inside a FileTree row');
+ return (
+ <span class={cn('min-w-0 flex-1 truncate', props.class)}>{node.name}</span>
+ );
+}
+
+function Row(
+ props: JSX.ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean }
+) {
+ const [local, rest] = splitProps(props, ['active', 'class']);
+ return (
+ <button
+ type="button"
+ {...rest}
+ class={cn(
+ 'flex h-8 w-full min-w-0 shrink-0 items-center justify-start gap-1.5 rounded-lg px-2 text-left text-sm leading-5 outline-none focus-visible:outline-2 focus-visible:outline-accent touch:h-11',
+ local.active
+ ? 'bg-active text-ink'
+ : 'text-ink-muted hover:bg-hover hover:text-ink',
+ local.class
+ )}
+ />
+ );
+}
+
+type FileTreeRootProps<T> = {
+ items: readonly T[];
+ path: (item: T) => string;
+ /** The selected file, by path. */
+ selected?: string;
+ onSelect?: (item: T) => void;
+ /** What a file's row shows; lead with `FileTree.Icon`, then `FileTree.Name`. */
+ children: (file: FileTreeFile<T>) => JSX.Element;
+ /** What a directory's row shows; defaults to a folder and its name. */
+ directory?: (directory: FileTreeDirectory<T>) => JSX.Element;
+ 'aria-label': string;
+ class?: string;
+};
+
+function Root<T>(props: FileTreeRootProps<T>) {
+ const nodes = createMemo(() => buildFileTree(props.items, props.path));
+ const [closed, setClosed] = createSignal<ReadonlySet<string>>(new Set());
+ const isOpen = (path: string) => !closed().has(path);
+ const setOpen = (path: string, open: boolean) =>
+ setClosed((previous) => {
+ if (previous.has(path) !== open) return previous;
+ const next = new Set(previous);
+ if (open) next.delete(path);
+ else next.add(path);
+ return next;
+ });
+ const toggle = (path: string) => setOpen(path, !isOpen(path));
+ const rows = createMemo(() => visibleNodes(nodes(), isOpen));
+
+ let container!: HTMLDivElement;
+ const focusRow = (path: string) => {
+ const rowElements = container.querySelectorAll<HTMLElement>(
+ '[data-file-tree-path]'
+ );
+ for (const row of rowElements) {
+ if (row.dataset.fileTreePath === path) {
+ return row.querySelector<HTMLElement>('button')?.focus();
+ }
+ }
+ };
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ const path = (event.target as HTMLElement).closest<HTMLElement>(
+ '[data-file-tree-path]'
+ )?.dataset.fileTreePath;
+ const visible = rows();
+ const index = visible.findIndex((row) => row.node.path === path);
+ const row = visible[index];
+ if (!row) return;
+ const moveTo = (to: string | undefined) => {
+ if (to === undefined) return;
+ event.preventDefault();
+ focusRow(to);
+ };
+ const node = row.node;
+ const directoryOpen = node.kind === 'directory' && isOpen(node.path);
+ switch (event.key) {
+ case 'ArrowDown':
+ return moveTo(visible[index + 1]?.node.path);
+ case 'ArrowUp':
+ return moveTo(visible[index - 1]?.node.path);
+ case 'ArrowRight':
+ if (node.kind !== 'directory') return;
+ event.preventDefault();
+ if (directoryOpen) moveTo(node.children[0]?.path);
+ else setOpen(node.path, true);
+ return;
+ case 'ArrowLeft':
+ if (directoryOpen) {
+ event.preventDefault();
+ setOpen(node.path, false);
+ } else {
+ moveTo(row.parent);
+ }
+ return;
+ }
+ };
+
+ const DirectoryRow = (row: { directory: FileTreeDirectory<T> }) => {
+ const path = () => row.directory.path;
+ const open = () => isOpen(path());
+ return (
+ <li class="min-w-0" data-file-tree-path={path()}>
+ <NodeContext.Provider value={row.directory}>
+ <div class="relative min-w-0">
+ <Row class="pr-9" title={path()} onClick={() => toggle(path())}>
+ {props.directory ? (
+ props.directory(row.directory)
+ ) : (
+ <>
+ <Icon>{open() ? <FolderOpenIcon /> : <FolderIcon />}</Icon>
+ <Name />
+ </>
+ )}
+ </Row>
+ <span class="absolute top-1/2 right-1.5 flex -translate-y-1/2">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ class="size-6 shrink-0 rounded-lg touch:size-9"
+ label={`${open() ? 'Collapse' : 'Expand'} ${row.directory.name}`}
+ aria-expanded={open()}
+ onClick={() => toggle(path())}
+ >
+ <CaretDownIcon
+ class={cn(
+ 'size-3 -rotate-90 transition-transform',
+ open() && 'rotate-0'
+ )}
+ />
+ </Button>
+ </span>
+ </div>
+ </NodeContext.Provider>
+ <CollapseTransition open={open()}>
+ <div class="relative min-w-0 pl-5 before:pointer-events-none before:absolute before:inset-y-0 before:left-4.5 before:w-px before:-translate-x-1/2 before:bg-edge-divider">
+ <Nodes nodes={row.directory.children} />
+ </div>
+ </CollapseTransition>
+ </li>
+ );
+ };
+
+ const FileRow = (row: { file: FileTreeFile<T> }) => {
+ const selected = () => props.selected === row.file.path;
+ return (
+ <li class="min-w-0" data-file-tree-path={row.file.path}>
+ <NodeContext.Provider value={row.file}>
+ <Row
+ active={selected()}
+ aria-current={selected() ? 'true' : undefined}
+ title={row.file.path}
+ onClick={() => props.onSelect?.(row.file.item)}
+ >
+ {props.children(row.file)}
+ </Row>
+ </NodeContext.Provider>
+ </li>
+ );
+ };
+
+ const Nodes = (level: { nodes: FileTreeNode<T>[] }) => (
+ <ul class="flex min-w-0 flex-col gap-0.5">
+ <For each={level.nodes}>
+ {(node) =>
+ node.kind === 'directory' ? (
+ <DirectoryRow directory={node} />
+ ) : (
+ <FileRow file={node} />
+ )
+ }
+ </For>
+ </ul>
+ );
+
+ return (
+ <div
+ ref={container}
+ class={cn('min-w-0', props.class)}
+ role="group"
+ aria-label={props['aria-label']}
+ onKeyDown={onKeyDown}
+ >
+ <Nodes nodes={nodes()} />
+ </div>
+ );
+}
+
+/**
+ * A tree of any items by path, for changed files, attachments, or a repository.
+ * @do Give `Root` the items and a `path` accessor; it builds the tree and
+ * compresses single-child directories itself.
+ * @do Lead each file row with `FileTree.Icon`, then `FileTree.Name`, so names
+ * line up with directory rows.
+ * @do Put trailing content (counts, badges, status) after `FileTree.Name`; the
+ * name takes the remaining width and truncates.
+ * @do Pass `directory` to change what a directory row shows after its folder.
+ * @dont Do not put buttons inside a row; the row is already a button.
+ * @dont Do not restyle row heights or insets at the call site; rows share the
+ * workspace sidebar's tree geometry so trees look alike across panes.
+ */
+export const FileTree = { Root, Icon, Name };
diff --git a/apps/web/src/components/ui/utils/file-tree.test.ts b/apps/web/src/components/ui/utils/file-tree.test.ts
new file mode 100644
index 0000000000..99fbaa3c24
--- /dev/null
+++ b/apps/web/src/components/ui/utils/file-tree.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest';
+import { buildFileTree, visibleNodes } from './file-tree';
+
+const tree = (paths: string[]) => buildFileTree(paths, (path) => path);
+
+describe('buildFileTree', () => {
+ it('compresses single-child directory chains', () => {
+ const nodes = tree(['apps/web/src/a.ts', 'apps/web/src/b.ts']);
+ expect(nodes).toHaveLength(1);
+ const directory = nodes[0]!;
+ if (directory.kind !== 'directory') throw new Error('expected directory');
+ expect(directory.name).toBe('apps/web/src');
+ expect(directory.path).toBe('apps/web/src');
+ expect(directory.children.map((child) => child.name)).toEqual([
+ 'a.ts',
+ 'b.ts',
+ ]);
+ });
+
+ it('stops compressing where the tree branches', () => {
+ const nodes = tree([
+ 'apps/web/src/a.ts',
+ 'apps/web/test/b.ts',
+ 'crates/x/src/lib.rs',
+ ]);
+ expect(nodes.map((node) => node.name)).toEqual([
+ 'apps/web',
+ 'crates/x/src',
+ ]);
+ const web = nodes[0]!;
+ if (web.kind !== 'directory') throw new Error('expected directory');
+ expect(web.children.map((node) => node.name)).toEqual(['src', 'test']);
+ });
+
+ it('lists directories before files and keeps input order', () => {
+ const nodes = tree(['README.md', 'docs/guide.md', 'LICENSE']);
+ expect(nodes.map((node) => `${node.kind}:${node.name}`)).toEqual([
+ 'directory:docs',
+ 'file:README.md',
+ 'file:LICENSE',
+ ]);
+ });
+
+ it('keeps each item and its full path on its file', () => {
+ const nodes = buildFileTree(
+ [{ path: 'a/b.ts', size: 3 }],
+ (item) => item.path
+ );
+ const directory = nodes[0]!;
+ if (directory.kind !== 'directory') throw new Error('expected directory');
+ expect(directory.children[0]).toEqual({
+ kind: 'file',
+ name: 'b.ts',
+ path: 'a/b.ts',
+ item: { path: 'a/b.ts', size: 3 },
+ });
+ });
+});
+
+describe('visibleNodes', () => {
+ it('walks open directories in display order and skips closed ones', () => {
+ const nodes = tree(['b/y.ts', 'a.ts', 'b/x.ts', 'c/z.ts']);
+ const rows = (open: (path: string) => boolean) =>
+ visibleNodes(nodes, open).map(
+ ({ node, level, parent }) => `${level}:${node.path}:${parent ?? '-'}`
+ );
+ expect(rows(() => true)).toEqual([
+ '1:b:-',
+ '2:b/y.ts:b',
+ '2:b/x.ts:b',
+ '1:c:-',
+ '2:c/z.ts:c',
+ '1:a.ts:-',
+ ]);
+ expect(rows((path) => path !== 'b')).toEqual([
+ '1:b:-',
+ '1:c:-',
+ '2:c/z.ts:c',
+ '1:a.ts:-',
+ ]);
+ });
+});
diff --git a/apps/web/src/components/ui/utils/file-tree.ts b/apps/web/src/components/ui/utils/file-tree.ts
new file mode 100644
index 0000000000..9834902eff
--- /dev/null
+++ b/apps/web/src/components/ui/utils/file-tree.ts
@@ -0,0 +1,122 @@
+/**
+ * A tree of items by path: directories compressed along single-child chains
+ * (`apps/web/src` reads as one row when nothing branches off it), items in
+ * input order under their directory, directories before items.
+ */
+
+export type FileTreeDirectory<T> = {
+ kind: 'directory';
+ /** The compressed segment, e.g. `apps/web/src`. */
+ name: string;
+ /** Full path of the directory, for a stable key. */
+ path: string;
+ children: FileTreeNode<T>[];
+};
+
+export type FileTreeFile<T> = {
+ kind: 'file';
+ /** Basename shown in the row. */
+ name: string;
+ /** Full path; the file's identity in the tree. */
+ path: string;
+ item: T;
+};
+
+export type FileTreeNode<T> = FileTreeDirectory<T> | FileTreeFile<T>;
+
+type MutableDirectory<T> = {
+ name: string;
+ path: string;
+ directories: Map<string, MutableDirectory<T>>;
+ files: FileTreeFile<T>[];
+};
+
+function newDirectory<T>(name: string, path: string): MutableDirectory<T> {
+ return { name, path, directories: new Map(), files: [] };
+}
+
+/**
+ * Build the tree from each item's path. Order is preserved: directories
+ * appear in the order their first item appeared, items in input order.
+ */
+export function buildFileTree<T>(
+ items: readonly T[],
+ pathOf: (item: T) => string
+): FileTreeNode<T>[] {
+ const root = newDirectory<T>('', '');
+ for (const item of items) {
+ const path = pathOf(item);
+ const segments = path.split('/').filter((segment) => segment !== '');
+ const name = segments.pop() ?? path;
+ let node = root;
+ for (const segment of segments) {
+ let next = node.directories.get(segment);
+ if (!next) {
+ next = newDirectory(
+ segment,
+ node.path ? `${node.path}/${segment}` : segment
+ );
+ node.directories.set(segment, next);
+ }
+ node = next;
+ }
+ node.files.push({ kind: 'file', name, path, item });
+ }
+ return [...compress(root).map(finish), ...root.files];
+}
+
+/** Fold a directory with exactly one child directory and no files into it. */
+function compress<T>(directory: MutableDirectory<T>): MutableDirectory<T>[] {
+ const out: MutableDirectory<T>[] = [];
+ for (let child of directory.directories.values()) {
+ while (child.files.length === 0 && child.directories.size === 1) {
+ const [only] = child.directories.values();
+ child = {
+ name: `${child.name}/${only!.name}`,
+ path: only!.path,
+ directories: only!.directories,
+ files: only!.files,
+ };
+ }
+ out.push(child);
+ }
+ return out;
+}
+
+function finish<T>(directory: MutableDirectory<T>): FileTreeDirectory<T> {
+ return {
+ kind: 'directory',
+ name: directory.name,
+ path: directory.path,
+ children: [...compress(directory).map(finish), ...directory.files],
+ };
+}
+
+/** A node as it appears on screen: its depth, and the directory above it. */
+export type VisibleNode<T> = {
+ node: FileTreeNode<T>;
+ level: number;
+ parent: string | undefined;
+};
+
+/** The rows on screen, in display order, skipping closed directories. */
+export function visibleNodes<T>(
+ nodes: readonly FileTreeNode<T>[],
+ isOpen: (path: string) => boolean
+): VisibleNode<T>[] {
+ const out: VisibleNode<T>[] = [];
+ const walk = (
+ list: readonly FileTreeNode<T>[],
+ level: number,
+ parent: string | undefined
+ ) => {
+ for (const node of list) {
+ out.push({ node, level, parent });
+ if (node.kind === 'directory' && isOpen(node.path)) {
+ walk(node.children, level + 1, node.path);
+ }
+ }
+ };
+ walk(nodes, 1, undefined);
+ return out;
+}
diff --git a/apps/web/src/components/view-shell/CollapsibleSection.tsx b/apps/web/src/components/view-shell/CollapsibleSection.tsx
index 3eb0ceb171..92b7ad908a 100644
--- a/apps/web/src/components/view-shell/CollapsibleSection.tsx
+++ b/apps/web/src/components/view-shell/CollapsibleSection.tsx
@@ -1,6 +1,7 @@
import { Collapsible, useCollapsibleContext } from '@kobalte/core/collapsible';
import CaretDownIcon from '@phosphor/caret-down.svg';
import { cn } from '@ui';
+import { CollapseTransition } from '@ui/components/CollapseTransition';
import {
type ComponentProps,
type JSX,
@@ -8,7 +9,6 @@ import {
Suspense,
splitProps,
} from 'solid-js';
-import { CollapseTransition } from './CollapseTransition';
import { ViewSidebar } from './ViewSidebar';
export type CollapsibleSectionRootProps = Omit<
diff --git a/apps/web/src/components/view-shell/ViewShell.tsx b/apps/web/src/components/view-shell/ViewShell.tsx
index a5bb5e9a5f..3b9efcd26e 100644
--- a/apps/web/src/components/view-shell/ViewShell.tsx
+++ b/apps/web/src/components/view-shell/ViewShell.tsx
@@ -14,6 +14,7 @@ import SidebarIcon from '@phosphor/sidebar-simple.svg';
import { createWritableMemo } from '@solid-primitives/memo';
import { createElementSize } from '@solid-primitives/resize-observer';
import { Button, cn } from '@ui';
+import { CollapseTransition } from '@ui/components/CollapseTransition';
import {
type Accessor,
batch,
@@ -30,7 +31,6 @@ import {
splitProps,
useContext,
} from 'solid-js';
-import { CollapseTransition } from './CollapseTransition';
import { createSidebarMotion } from './create-sidebar-motion';
import {
type AsideLayout,
diff --git a/apps/web/src/components/view-shell/ViewSidebar.tsx b/apps/web/src/components/view-shell/ViewSidebar.tsx
index 5ed8a4b926..5a411509dc 100644
--- a/apps/web/src/components/view-shell/ViewSidebar.tsx
+++ b/apps/web/src/components/view-shell/ViewSidebar.tsx
@@ -1,9 +1,9 @@
import CaretDownIcon from '@phosphor/caret-down.svg';
import { Button, type ButtonProps, cn } from '@ui';
+import { CollapseTransition } from '@ui/components/CollapseTransition';
import type { JSX } from 'solid-js';
import { Show, splitProps } from 'solid-js';
import { Dynamic } from 'solid-js/web';
-import { CollapseTransition } from './CollapseTransition';
import { ViewSidebarCloseButton, ViewSidebarToggle } from './ViewShell';
function Root(props: JSX.HTMLAttributes<HTMLElement>) {
diff --git a/apps/web/src/features/agent-changes/README.md b/apps/web/src/features/agent-changes/README.md
index 6c724278bc..f198760e48 100644
--- a/apps/web/src/features/agent-changes/README.md
+++ b/apps/web/src/features/agent-changes/README.md
@@ -15,11 +15,19 @@ the linked pull request, so a chat-only (in-memory) session or a coding session
without a pull request yet shows no GitHub chrome. Clipboard, external navigation,
and notifications are host callbacks.
+`views/ChangesPane.tsx` composes the generic `FileTree`
+(`@ui/components/FileTree`) and `DiffView` (`src/components/diff-view`) from the
+controller: tree rows show status letters and counts, file headers add **Copy
+path**, and review notes hang under their lines through `DiffView.Stack`'s
+annotation slot. Another host composes the same components its own way.
+
The source owns fetching, cache identity, and conversion into the feature's core
changeset types. A PR entity adapter should resolve its GitHub owner/repository/PR
number and implement this same contract using shared queries. It does not need to
construct an agent session. That adapter and its backend endpoint are not yet wired.
-Layout and diff style are controlled accessor/setter pairs. Hosts using the app
-router can use `url-diff-state.ts`; embedded viewers can provide local signals.
-The URL codec supports namespaced ids and preserves neighboring viewer entries.
+Layout and diff style come from `createPaneViewState()` (`pane-view-state.ts`).
+Where the host's route lists `changesSearch.namespace` in its `search`, they live
+in that split's search params (`s0.changes.pane`, `s0.changes.style`), so the
+split router drops them when the split closes or navigates away; anywhere else,
+such as a preview, they are local signals.
diff --git a/apps/web/src/features/agent-changes/agent-changes.test.tsx b/apps/web/src/features/agent-changes/agent-changes.test.tsx
index 54e4b2caa7..d380561c21 100644
--- a/apps/web/src/features/agent-changes/agent-changes.test.tsx
+++ b/apps/web/src/features/agent-changes/agent-changes.test.tsx
@@ -45,14 +45,6 @@ vi.mock('./queries/pull-request-stats', () => ({
createPullRequestStatsSource: () => () => undefined,
}));
-vi.mock('./url-diff-state', () => ({
- createUrlDiffState: () => {
- const [layout, setLayout] = createSignal('agent-only');
- const [diffStyle, setDiffStyle] = createSignal('unified');
- return { layout, setLayout, diffStyle, setDiffStyle };
- },
-}));
-
vi.mock('@core/component/Toast/Toast', () => ({
toast: { success() {}, failure() {} },
}));
diff --git a/apps/web/src/features/agent-changes/agent-changes.tsx b/apps/web/src/features/agent-changes/agent-changes.tsx
index 5a57376961..9ed2f7707d 100644
--- a/apps/web/src/features/agent-changes/agent-changes.tsx
+++ b/apps/web/src/features/agent-changes/agent-changes.tsx
@@ -15,10 +15,10 @@ import { createSignal, type ParentProps } from 'solid-js';
import { useAgentSession } from '../block-agent/context/AgentSessionContext';
import type { ChangesHost } from './context/agent-changes-context';
import { AgentChangesControllerProvider } from './context/agent-changes-controller';
+import { createPaneViewState } from './pane-view-state';
import { createAgentChanges } from './primitives/create-agent-changes';
import { createPullRequestStatsSource } from './queries/pull-request-stats';
import { createSessionChangesSource } from './queries/session-changes';
-import { createUrlDiffState } from './url-diff-state';
export { AgentChangesSplit } from './views/AgentChangesSplit';
export {
@@ -81,12 +81,11 @@ export function AgentChangesProvider(props: ParentProps) {
else toast.failure(message);
},
};
- const urlState = createUrlDiffState(session.sessionId);
+ const view = createPaneViewState();
const [dismissed, setDismissed] = createSignal<string>();
const controller = createAgentChanges({
context: { source, host },
- paneLayout: [urlState.layout, urlState.setLayout],
- diffStyle: [urlState.diffStyle, urlState.setDiffStyle],
+ view,
dismissed: [dismissed, (id) => setDismissed(id)],
});
return (
diff --git a/apps/web/src/features/agent-changes/changes-search.ts b/apps/web/src/features/agent-changes/changes-search.ts
new file mode 100644
index 0000000000..e8c0c2c619
--- /dev/null
+++ b/apps/web/src/features/agent-changes/changes-search.ts
@@ -0,0 +1,25 @@
+import { z } from 'zod';
+import {
+ DIFF_STYLES,
+ type DiffStyle,
+ PANE_LAYOUTS,
+ type PaneLayout,
+} from './core/layout';
+
+/**
+ * The Changes pane's view state in its split's own search params
+ * (`s0.changes.pane=split`, `s0.changes.style=split`). A route that hosts the
+ * pane lists this namespace in its `search`, so closing the split or
+ * navigating it elsewhere drops the state with it.
+ */
+export const changesSearch = {
+ namespace: 'changes',
+ schema: z.object({
+ pane: z.enum(PANE_LAYOUTS),
+ style: z.enum(DIFF_STYLES),
+ }),
+ defaults: { pane: 'closed', style: 'unified' } as {
+ pane: PaneLayout;
+ style: DiffStyle;
+ },
+};
diff --git a/apps/web/src/features/agent-changes/components/ChangesHeader.tsx b/apps/web/src/features/agent-changes/components/ChangesHeader.tsx
index 28e5329e30..ff41df28bd 100644
--- a/apps/web/src/features/agent-changes/components/ChangesHeader.tsx
+++ b/apps/web/src/features/agent-changes/components/ChangesHeader.tsx
@@ -1,101 +1,66 @@
-import ArrowLeftIcon from '@phosphor/arrow-left.svg';
-import ArrowsClockwiseIcon from '@phosphor/arrows-clockwise.svg';
import ArrowsInSimpleIcon from '@phosphor/arrows-in-simple.svg';
import ArrowsOutSimpleIcon from '@phosphor/arrows-out-simple.svg';
import GitBranchIcon from '@phosphor/git-branch.svg';
import GitPullRequestIcon from '@phosphor/git-pull-request.svg';
import XIcon from '@phosphor/x.svg';
-import { Button, cn, SegmentedControl } from '@ui';
+import { Button } from '@ui';
import { Show } from 'solid-js';
import { pullRequestNumber } from '../core/pull-request';
-export type DiffStyleValue = 'unified' | 'split';
-
+/**
+ * The pane's title row: what is being reviewed on the left, and only the
+ * pane's own controls (full width, close) on the right. Controls for the
+ * diffs themselves live in the toolbar below.
+ */
export function ChangesHeader(props: {
/** The pane fills the width; the session is off screen. */
spotlit: boolean;
/** `head → base`, when known. */
range: string | undefined;
- diffStyle: DiffStyleValue;
- onDiffStyle: (style: DiffStyleValue) => void;
- /** The linked pull request, opened by the header action. */
+ /** The linked pull request, opened from its number. */
pullRequestUrl: string | undefined;
onViewPullRequest: () => void;
- refreshing: boolean;
- onRefresh: () => void;
- onBack: () => void;
onSpotlight: () => void;
onClose: () => void;
}) {
- const pill = () => {
+ const number = () => {
const url = props.pullRequestUrl;
- const number = url ? pullRequestNumber(url) : undefined;
- if (!props.range) return undefined;
- return number ? `#${number} · ${props.range}` : props.range;
+ return url ? pullRequestNumber(url) : undefined;
};
return (
- <header class="flex h-12 shrink-0 items-center gap-1.5 border-b border-edge pr-2 pl-2.5">
- <Show when={props.spotlit}>
+ <>
+ <h2 class="shrink-0 px-1 text-sm font-semibold text-ink">Changes</h2>
+ <Show when={props.pullRequestUrl}>
<Button
variant="ghost"
- size="icon-sm"
- tooltip="Bring the session back"
- onClick={() => props.onBack()}
+ size="sm"
+ class="shrink-0"
+ label={
+ number() ? `View pull request #${number()}` : 'View pull request'
+ }
+ onClick={() => props.onViewPullRequest()}
>
- <ArrowLeftIcon />
+ <GitPullRequestIcon />
+ <span>{number() ? `#${number()}` : 'Pull request'}</span>
</Button>
</Show>
- <div class="flex min-w-0 items-center gap-1.5">
- <GitBranchIcon class="size-4 shrink-0 text-ink-subtle" />
- <h2 class="truncate text-sm font-semibold text-ink">Changes</h2>
- </div>
- <Show when={pill()}>
- {(text) => (
+ <Show when={props.range}>
+ {(range) => (
<span
- class="inline-flex h-5.5 max-w-64 items-center truncate rounded-full border border-edge-muted px-2 font-mono text-[11px] text-ink-subtle max-lg:hidden"
- title={text()}
+ class="flex min-w-0 items-center gap-1 text-xs text-ink-subtle max-md:hidden"
+ title={range()}
>
- {text()}
+ <GitBranchIcon class="size-3.5 shrink-0" />
+ <span class="truncate">{range()}</span>
</span>
)}
</Show>
<span class="flex-1" />
- <SegmentedControl
- size="sm"
- aria-label="Diff layout"
- value={props.diffStyle}
- options={[
- { value: 'unified', label: 'Unified' },
- { value: 'split', label: 'Split' },
- ]}
- onChange={props.onDiffStyle}
- class="max-md:hidden"
- />
- <Button
- variant="ghost"
- size="icon-sm"
- tooltip="Refresh pull request changes"
- disabled={props.refreshing}
- onClick={() => props.onRefresh()}
- >
- <ArrowsClockwiseIcon class={cn(props.refreshing && 'animate-spin')} />
- </Button>
- <Show when={props.pullRequestUrl}>
- <Button
- variant="outline"
- size="sm"
- class="gap-1.5"
- onClick={props.onViewPullRequest}
- >
- <GitPullRequestIcon class="size-3.5" />
- <span>View pull request</span>
- </Button>
- </Show>
<Button
variant="ghost"
size="icon-sm"
aria-pressed={props.spotlit}
- tooltip={
+ label={
props.spotlit
? 'Back to the split'
: 'Expand changes to the full width'
@@ -107,11 +72,11 @@ export function ChangesHeader(props: {
<Button
variant="ghost"
size="icon-sm"
- tooltip="Close the changes pane"
+ label="Close the changes pane"
onClick={() => props.onClose()}
>
<XIcon />
</Button>
- </header>
+ </>
);
}
diff --git a/apps/web/src/features/agent-changes/components/ChangesReadyCard.tsx b/apps/web/src/features/agent-changes/components/ChangesReadyCard.tsx
index 8d4942aa4e..fa85728725 100644
--- a/apps/web/src/features/agent-changes/components/ChangesReadyCard.tsx
+++ b/apps/web/src/features/agent-changes/components/ChangesReadyCard.tsx
@@ -1,3 +1,4 @@
+import { DiffCounts } from '@app/components/diff-view';
import GitBranchIcon from '@phosphor/git-branch.svg';
import GitPullRequestIcon from '@phosphor/git-pull-request.svg';
import RowsIcon from '@phosphor/rows.svg';
@@ -6,7 +7,6 @@ import { Button } from '@ui';
import { Show } from 'solid-js';
import { describeFileCount } from '../core/changeset';
import { pullRequestNumber } from '../core/pull-request';
-import { DiffCounts } from './DiffCounts';
/** The transcript's hand-off card into the Changes pane. */
export function ChangesReadyCard(props: {
diff --git a/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx b/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx
index 8c04eb39b9..b7c71c7d47 100644
--- a/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx
+++ b/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx
@@ -1,7 +1,7 @@
+import { DiffCounts } from '@app/components/diff-view';
import SquareSplitHorizontalIcon from '@phosphor/square-split-horizontal.svg';
import { Button, cn } from '@ui';
import { Show } from 'solid-js';
-import { DiffCounts } from './DiffCounts';
/** Opens the changes pane and summarizes its added/deleted lines. */
export function ChangesToggleButton(props: {
diff --git a/apps/web/src/features/agent-changes/components/FileCard.tsx b/apps/web/src/features/agent-changes/components/FileCard.tsx
deleted file mode 100644
index 1032a243e3..0000000000
--- a/apps/web/src/features/agent-changes/components/FileCard.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-import CaretRightIcon from '@phosphor/caret-right.svg';
-import CopyIcon from '@phosphor/copy.svg';
-import { Button, cn } from '@ui';
-import { type JSX, Show } from 'solid-js';
-import { splitPath } from '../core/changeset';
-import type { FileDiffEntry } from '../core/patch';
-import { DiffCounts } from './DiffCounts';
-import { StatusLetter } from './StatusLetter';
-
-/** Plain note shown in place of a diff body. */
-export function DiffNote(props: { children: JSX.Element }) {
- return (
- <div class="px-3 py-2.5 font-mono text-xs text-ink-placeholder">
- {props.children}
- </div>
- );
-}
-
-/**
- * One file in the stack: a sticky header with the review controls, and the
- * diff (or a note about why there is none) beneath it.
- */
-export function FileCard(props: {
- entry: FileDiffEntry;
- collapsed: boolean;
- /** Briefly highlighted after the tree jumped here. */
- flash: boolean;
- onToggleCollapsed: () => void;
- onCopyPath: () => void;
- /** The diff body, supplied by the view so this card stays presentational. */
- body: JSX.Element;
- ref?: (element: HTMLElement) => void;
-}) {
- const file = () => props.entry.file;
- const path = () => splitPath(file().path);
- const hidden = () =>
- `${file().additions} ${file().additions === 1 ? 'addition' : 'additions'}, ${file().deletions} ${file().deletions === 1 ? 'deletion' : 'deletions'} hidden`;
- return (
- <article
- ref={props.ref}
- class={cn(
- 'scroll-mt-2 shrink-0 overflow-hidden rounded-lg border border-edge-muted bg-surface transition-shadow',
- props.flash && 'border-accent shadow-[0_0_0_3px_var(--color-selected)]'
- )}
- data-path={file().path}
- >
- <header class="sticky top-0 z-5 flex min-h-8.5 items-center gap-2 border-b border-edge-muted bg-surface-1 pr-2">
- <Button
- variant="ghost"
- size="icon-sm"
- class="ml-1"
- aria-expanded={!props.collapsed}
- aria-label={`${props.collapsed ? 'Show' : 'Hide'} ${path().base}`}
- tooltip={props.collapsed ? 'Show this diff' : 'Hide this diff'}
- onClick={() => props.onToggleCollapsed()}
- >
- <CaretRightIcon
- class={cn(
- 'transition-transform duration-100 motion-reduce:transition-none',
- !props.collapsed && 'rotate-90'
- )}
- />
- </Button>
- <button
- type="button"
- class="flex min-w-0 flex-1 items-center gap-1.5 py-1.5 pr-1 text-left text-ink-muted hover:text-ink"
- aria-expanded={!props.collapsed}
- title={file().path}
- onClick={() => props.onToggleCollapsed()}
- >
- <StatusLetter kind={file().kind} />
- <span class="flex min-w-0 items-baseline font-mono text-[11.5px]">
- <Show when={file().previousPath}>
- {(previous) => (
- <span class="truncate text-ink-placeholder">
- {previous()}
- <span class="px-1">→</span>
- </span>
- )}
- </Show>
- <span class="min-w-0 shrink truncate text-ink-placeholder">
- {path().dir}
- </span>
- <span class="max-w-full shrink-0 truncate font-medium text-ink">
- {path().base}
- </span>
- </span>
- </button>
- <span class="flex shrink-0 items-center gap-2 text-[11px]">
- <DiffCounts
- additions={file().additions}
- deletions={file().deletions}
- />
- </span>
- <Button
- variant="ghost"
- size="icon-sm"
- tooltip="Copy path"
- onClick={() => props.onCopyPath()}
- >
- <CopyIcon />
- </Button>
- </header>
- <Show
- when={!props.collapsed}
- fallback={
- <button
- type="button"
- class="flex w-full items-center gap-2 px-3 py-2.5 text-left font-mono text-[11.5px] text-ink-placeholder hover:bg-hover hover:text-ink-muted"
- onClick={() => props.onToggleCollapsed()}
- >
- <CaretRightIcon class="size-3" />
- <span class="font-sans font-medium text-ink-muted">
- {props.entry.note ? 'Show' : 'Show diff'}
- </span>
- <span class="flex-1">{props.entry.note ?? hidden()}</span>
- </button>
- }
- >
- <Show
- when={!props.entry.note}
- fallback={<DiffNote>{props.entry.note}</DiffNote>}
- >
- {props.body}
- </Show>
- </Show>
- </article>
- );
-}
diff --git a/apps/web/src/features/agent-changes/components/FileTree.tsx b/apps/web/src/features/agent-changes/components/FileTree.tsx
deleted file mode 100644
index 8437b542c5..0000000000
--- a/apps/web/src/features/agent-changes/components/FileTree.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import CaretRightIcon from '@phosphor/caret-right.svg';
-import { cn } from '@ui';
-import { createSignal, For, Show } from 'solid-js';
-import { describeFileCount } from '../core/changeset';
-import type { FileTreeDir, FileTreeNode } from '../core/file-tree';
-import { DiffCounts } from './DiffCounts';
-import { StatusLetter } from './StatusLetter';
-
-export type FileTreeProps = {
- nodes: FileTreeNode[];
- fileCount: number;
- active: string | undefined;
- onSelect: (path: string) => void;
-};
-
-function DirRow(props: {
- dir: FileTreeDir;
- active: string | undefined;
- onSelect: (path: string) => void;
-}) {
- const [open, setOpen] = createSignal(true);
- return (
- <>
- <button
- type="button"
- class="flex min-h-6 w-full items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left text-ink-placeholder hover:bg-hover"
- aria-expanded={open()}
- onClick={() => setOpen((value) => !value)}
- >
- <CaretRightIcon
- class={cn(
- 'size-3 shrink-0 transition-transform duration-100 motion-reduce:transition-none',
- open() && 'rotate-90'
- )}
- />
- <span class="min-w-0 flex-1 truncate font-mono text-[11px]">
- {props.dir.name}
- </span>
- </button>
- <Show when={open()}>
- <div class="ml-[7px] flex flex-col gap-px border-l border-edge-muted pl-2.5">
- <Rows
- nodes={props.dir.children}
- active={props.active}
- onSelect={props.onSelect}
- />
- </div>
- </Show>
- </>
- );
-}
-
-function Rows(props: {
- nodes: FileTreeNode[];
- active: string | undefined;
- onSelect: (path: string) => void;
-}) {
- return (
- <For each={props.nodes}>
- {(node) =>
- node.kind === 'dir' ? (
- <DirRow dir={node} active={props.active} onSelect={props.onSelect} />
- ) : (
- <button
- type="button"
- class={cn(
- 'flex min-h-6 w-full items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left text-xs text-ink-muted hover:bg-hover',
- props.active === node.file.path && 'bg-selected text-ink'
- )}
- aria-current={props.active === node.file.path ? 'true' : undefined}
- title={node.file.path}
- onClick={() => props.onSelect(node.file.path)}
- >
- <StatusLetter kind={node.file.kind} />
- <span class="min-w-0 flex-1 truncate font-mono text-[11.5px]">
- {node.name}
- </span>
- <DiffCounts
- additions={node.file.additions}
- deletions={node.file.deletions}
- />
- </button>
- )
- }
- </For>
- );
-}
-
-/** The changed files, grouped by compressed directory, in patch order. */
-export function FileTree(props: FileTreeProps) {
- return (
- <nav
- class="flex w-58 shrink-0 flex-col gap-px overflow-y-auto border-r border-edge-muted px-1.5 pt-2 pb-4 max-md:w-44"
- aria-label="Changed files"
- >
- <div class="flex items-center gap-1.5 px-1.5 pt-0.5 pb-1.5 text-[10px] tracking-[0.07em] text-ink-placeholder uppercase">
- <span class="flex-1">{describeFileCount(props.fileCount)}</span>
- </div>
- <Rows
- nodes={props.nodes}
- active={props.active}
- onSelect={props.onSelect}
- />
- </nav>
- );
-}
diff --git a/apps/web/src/features/agent-changes/components/NoteAnnotation.tsx b/apps/web/src/features/agent-changes/components/NoteAnnotation.tsx
index bcd0ec514a..dcbdbb752f 100644
--- a/apps/web/src/features/agent-changes/components/NoteAnnotation.tsx
+++ b/apps/web/src/features/agent-changes/components/NoteAnnotation.tsx
@@ -1,19 +1,22 @@
import NoteIcon from '@phosphor/note.svg';
import XIcon from '@phosphor/x.svg';
import { Button, cn } from '@ui';
-import { createSignal, For, onMount, Show } from 'solid-js';
-import type { NoteAnchor, ReviewNote } from '../core/review-notes';
+import { For, onMount, Show } from 'solid-js';
+import type { NoteAnchor, NoteDraft, ReviewNote } from '../core/review-notes';
-/** The editor for a new note on one line. */
+/**
+ * The editor for a new note. Its text lives with the draft, not in here, so
+ * it survives the diff view re-creating this element.
+ */
function NoteEditor(props: {
- anchor: NoteAnchor;
+ draft: NoteDraft;
+ onDraft: (text: string) => void;
onAdd: (anchor: NoteAnchor, text: string) => void;
onCancel: () => void;
}) {
- const [text, setText] = createSignal('');
let textarea!: HTMLTextAreaElement;
onMount(() => textarea.focus());
- const add = () => props.onAdd(props.anchor, text());
+ const add = () => props.onAdd(props.draft.range, props.draft.text);
return (
<div class="flex flex-col gap-1.5">
<textarea
@@ -21,8 +24,8 @@ function NoteEditor(props: {
class="min-h-13 w-full resize-y rounded-md border border-edge bg-input px-2 py-1.5 font-sans text-xs text-ink outline-none placeholder:text-ink-placeholder focus:border-input-focus"
placeholder="What should the agent change here?"
aria-label="Review note"
- value={text()}
- onInput={(event) => setText(event.currentTarget.value)}
+ value={props.draft.text}
+ onInput={(event) => props.onDraft(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === 'Escape') {
event.preventDefault();
@@ -41,7 +44,7 @@ function NoteEditor(props: {
variant="cta"
size="xs"
class="h-6.5 px-2.5"
- disabled={text().trim() === ''}
+ disabled={props.draft.text.trim() === ''}
onClick={add}
>
Add note
@@ -69,7 +72,8 @@ function NoteEditor(props: {
*/
export function NoteAnnotation(props: {
notes: ReviewNote[];
- composing: NoteAnchor | undefined;
+ draft: NoteDraft | undefined;
+ onDraft: (text: string) => void;
onAdd: (anchor: NoteAnchor, text: string) => void;
onCancel: () => void;
onRemove: (id: string) => void;
@@ -106,10 +110,11 @@ export function NoteAnnotation(props: {
</div>
)}
</For>
- <Show when={props.composing}>
- {(anchor) => (
+ <Show when={props.draft}>
+ {(draft) => (
<NoteEditor
- anchor={anchor()}
+ draft={draft()}
+ onDraft={props.onDraft}
onAdd={props.onAdd}
onCancel={props.onCancel}
/>
diff --git a/apps/web/src/features/agent-changes/components/PierreFileDiff.tsx b/apps/web/src/features/agent-changes/components/PierreFileDiff.tsx
deleted file mode 100644
index 276d734edf..0000000000
--- a/apps/web/src/features/agent-changes/components/PierreFileDiff.tsx
+++ /dev/null
@@ -1,209 +0,0 @@
-/**
- * One file's diff rendered by Pierre's vanilla `FileDiff`, with Macro's
- * review notes hung under their lines and Pierre's gutter utility (the "+"
- * that appears on hover, draggable over a range) to leave one.
- *
- * Pierre renders inside a shadow root but slots annotation content from
- * the light DOM, so the note UI here is ordinary Solid markup mounted with
- * `render` into the elements Pierre asks for.
- */
-
-import {
- type DiffLineAnnotation,
- FileDiff,
- type FileDiffMetadata,
- type FileDiffOptions,
- type SelectedLineRange,
-} from '@pierre/diffs';
-import {
- createEffect,
- createMemo,
- type JSX,
- on,
- onCleanup,
- onMount,
-} from 'solid-js';
-import { render } from 'solid-js/web';
-import type { NoteAnchor, ReviewNote } from '../core/review-notes';
-import { NoteAnnotation } from './NoteAnnotation';
-
-export type DiffStyleValue = 'unified' | 'split';
-
-/** Options that never change for the pane's diffs. */
-const BASE_OPTIONS = {
- diffIndicators: 'bars',
- // The file card renders its own header.
- disableFileHeader: true,
- overflow: 'wrap',
- hunkSeparators: 'line-info-basic',
- lineDiffType: 'word-alt',
- expansionLineCount: 20,
- lineHoverHighlight: 'line',
-} satisfies FileDiffOptions<string>;
-
-/**
- * CSS variables Pierre reads inside its shadow DOM, pointed at Macro's
- * typography tokens so the diff matches the surrounding mono text.
- */
-const DIFF_STYLE_VARIABLES: JSX.CSSProperties = {
- '--diffs-font-family': 'var(--font-mono)',
- '--diffs-font-size': '0.75rem',
- '--diffs-line-height': '18px',
- '--diffs-tab-size': '2',
- '--diffs-gap-block': '0',
- '--diffs-min-number-column-width': '4ch',
-};
-
-/** One annotation per annotated line: the anchor the notes hang from. */
-function annotationKey(side: NoteAnchor['side'], lineNumber: number): string {
- return `${side}:${lineNumber}`;
-}
-
-export function PierreFileDiff(props: {
- path: string;
- diff: FileDiffMetadata;
- diffStyle: DiffStyleValue;
- themeType: 'light' | 'dark';
- notes: ReviewNote[];
- composing: NoteAnchor | undefined;
- onOpenNote?: (anchor: NoteAnchor) => void;
- onCancelNote: () => void;
- onAddNote: (anchor: NoteAnchor, text: string) => void;
- onRemoveNote: (id: string) => void;
-}) {
- let container!: HTMLDivElement;
- let instance: FileDiff<string> | undefined;
- const roots = new Map<string, () => void>();
-
- const disposeRoots = () => {
- for (const dispose of roots.values()) dispose();
- roots.clear();
- };
-
- // Notes hang from the last line of their range, like GitHub's review
- // comments; the editor for a new note does the same.
- const annotations = createMemo((): DiffLineAnnotation<string>[] => {
- const keys = new Map<string, DiffLineAnnotation<string>>();
- const add = (side: NoteAnchor['side'], lineNumber: number) => {
- const key = annotationKey(side, lineNumber);
- if (!keys.has(key)) keys.set(key, { side, lineNumber, metadata: key });
- };
- for (const note of props.notes) add(note.side, note.endLineNumber);
- const composing = props.composing;
- if (composing) add(composing.side, composing.endLineNumber);
- return [...keys.values()].sort(
- (a, b) => a.lineNumber - b.lineNumber || a.side.localeCompare(b.side)
- );
- });
-
- const notesAt = (key: string) =>
- props.notes.filter(
- (note) => annotationKey(note.side, note.endLineNumber) === key
- );
- const composingAt = (key: string) => {
- const composing = props.composing;
- return composing &&
- annotationKey(composing.side, composing.endLineNumber) === key
- ? composing
- : undefined;
- };
-
- const renderAnnotation = (annotation: DiffLineAnnotation<string>) => {
- const key = annotation.metadata;
- roots.get(key)?.();
- const element = document.createElement('div');
- roots.set(
- key,
- render(
- () => (
- <NoteAnnotation
- notes={notesAt(key)}
- composing={composingAt(key)}
- onAdd={props.onAddNote}
- onCancel={props.onCancelNote}
- onRemove={props.onRemoveNote}
- />
- ),
- element
- )
- );
- return element;
- };
-
- const onGutterUtilityClick = (range: SelectedLineRange) => {
- props.onOpenNote?.({
- path: props.path,
- side: range.side ?? 'additions',
- lineNumber: Math.min(range.start, range.end),
- endLineNumber: Math.max(range.start, range.end),
- });
- };
-
- const currentOptions = (): FileDiffOptions<string> => ({
- ...BASE_OPTIONS,
- diffStyle: props.diffStyle,
- themeType: props.themeType,
- renderAnnotation,
- enableGutterUtility: props.onOpenNote !== undefined,
- onGutterUtilityClick: props.onOpenNote ? onGutterUtilityClick : undefined,
- });
-
- onMount(() => {
- instance = new FileDiff<string>(currentOptions());
- });
-
- // A new diff or layout re-renders from scratch; a change to the notes
- // re-renders too, since Pierre only stores annotations handed to
- // `setLineAnnotations` and paints them on the next render. Elements for
- // unchanged annotations are kept across renders. A layout change must be
- // forced: Pierre otherwise treats unchanged content as a partial render.
- createEffect(
- on(
- [() => props.diff, () => props.diffStyle, annotations],
- ([diff, diffStyle, list], previous) => {
- if (!instance) return;
- instance.setOptions(currentOptions());
- instance.render({
- fileDiff: diff,
- containerWrapper: container,
- lineAnnotations: list,
- forceRender: previous !== undefined && previous[1] !== diffStyle,
- });
- }
- )
- );
-
- // Pierre keeps the gutter selection lit while the note editor is open;
- // adding or cancelling the note lets the line go.
- createEffect(
- on(
- () => props.composing,
- (composing) => {
- if (!composing) instance?.setSelectedLines(null);
- },
- { defer: true }
- )
- );
-
- createEffect(
- on(
- () => props.themeType,
- (themeType) => instance?.setThemeType(themeType),
- { defer: true }
- )
- );
-
- onCleanup(() => {
- disposeRoots();
- instance?.cleanUp();
- instance = undefined;
- });
-
- return (
- <div
- ref={container}
- class="overflow-hidden bg-surface"
- style={DIFF_STYLE_VARIABLES}
- />
- );
-}
diff --git a/apps/web/src/features/agent-changes/components/ReviewBar.tsx b/apps/web/src/features/agent-changes/components/ReviewBar.tsx
deleted file mode 100644
index d688e46753..0000000000
--- a/apps/web/src/features/agent-changes/components/ReviewBar.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import ArrowsInSimpleIcon from '@phosphor/arrows-in-simple.svg';
-import ArrowsOutSimpleIcon from '@phosphor/arrows-out-simple.svg';
-import { Button } from '@ui';
-
-/** Bulk collapse and expand controls for the file diffs. */
-export function ReviewBar(props: {
- anyExpanded: boolean;
- onToggleCollapsed: () => void;
-}) {
- return (
- <div class="flex shrink-0 flex-wrap items-center gap-2.5 border-b border-edge-muted bg-surface-1 py-1.5 pr-2 pl-3">
- <span class="flex-1" />
- <Button
- variant="outline"
- size="xs"
- class="h-6.5 gap-1.5 px-2 text-[11.5px]"
- tooltip={
- props.anyExpanded
- ? 'Hide every diff, keeping just the file headers'
- : 'Show every diff again'
- }
- onClick={() => props.onToggleCollapsed()}
- >
- {props.anyExpanded ? (
- <ArrowsInSimpleIcon class="size-3" />
- ) : (
- <ArrowsOutSimpleIcon class="size-3" />
- )}
- <span>{props.anyExpanded ? 'Collapse all' : 'Expand all'}</span>
- </Button>
- </div>
- );
-}
diff --git a/apps/web/src/features/agent-changes/context/agent-changes-context.ts b/apps/web/src/features/agent-changes/context/agent-changes-context.ts
index 6d113068eb..8bff738647 100644
--- a/apps/web/src/features/agent-changes/context/agent-changes-context.ts
+++ b/apps/web/src/features/agent-changes/context/agent-changes-context.ts
@@ -10,6 +10,7 @@
import type { Accessor } from 'solid-js';
import type { SessionChanges } from '../core/changeset';
+import type { DiffStyle, PaneLayout } from '../core/layout';
export type QueryStatus = 'idle' | 'pending' | 'error' | 'success';
@@ -67,6 +68,14 @@ export type ChangesHost = {
notify: (message: string, tone: 'success' | 'failure') => void;
};
+/** Which layout the pane is in, and how its diffs are drawn. */
+export type PaneViewState = {
+ layout: Accessor<PaneLayout>;
+ setLayout: (layout: PaneLayout) => void;
+ diffStyle: Accessor<DiffStyle>;
+ setDiffStyle: (style: DiffStyle) => void;
+};
+
export type AgentChangesContext = {
source: ChangesSource;
host: ChangesHost;
diff --git a/apps/web/src/features/agent-changes/core/changeset.test.ts b/apps/web/src/features/agent-changes/core/changeset.test.ts
index 8701dc9cca..5ed9228985 100644
--- a/apps/web/src/features/agent-changes/core/changeset.test.ts
+++ b/apps/web/src/features/agent-changes/core/changeset.test.ts
@@ -4,8 +4,6 @@ import {
changesState,
describeRange,
repositorySlug,
- splitPath,
- statusLetter,
} from './changeset';
function changeset(overrides: Partial<Changeset> = {}): Changeset {
@@ -33,28 +31,6 @@ function changeset(overrides: Partial<Changeset> = {}): Changeset {
};
}
-describe('statusLetter', () => {
- it('maps every kind to its letter', () => {
- expect(statusLetter('added')).toBe('A');
- expect(statusLetter('modified')).toBe('M');
- expect(statusLetter('deleted')).toBe('D');
- expect(statusLetter('renamed')).toBe('R');
- });
-});
-
-describe('splitPath', () => {
- it('keeps the trailing slash on the directory', () => {
- expect(splitPath('apps/web/src/a.ts')).toEqual({
- dir: 'apps/web/src/',
- base: 'a.ts',
- });
- });
-
- it('treats a bare name as having no directory', () => {
- expect(splitPath('README.md')).toEqual({ dir: '', base: 'README.md' });
- });
-});
-
describe('repositorySlug', () => {
it('reads owner/name from a GitHub url', () => {
expect(repositorySlug('https://github.com/macro-inc/macro')).toBe(
diff --git a/apps/web/src/features/agent-changes/core/changeset.ts b/apps/web/src/features/agent-changes/core/changeset.ts
index 7893f46096..c81f4af301 100644
--- a/apps/web/src/features/agent-changes/core/changeset.ts
+++ b/apps/web/src/features/agent-changes/core/changeset.ts
@@ -2,8 +2,8 @@
* The vocabulary of a session's captured changes.
*
* Pure types and functions: what a changed file is, how a capture went, and
- * the small derivations the pane shows (status letters, totals, path
- * splitting). Wire decoding lives in `queries/`; rendering in `components/`.
+ * the small derivations the pane shows (ranges, totals). A `ChangedFile`
+ * is the diff view's `DiffFile` shape. Wire decoding lives in `queries/`.
*/
/** What happened to a file between the base and the head. */
@@ -68,29 +68,6 @@ export type SessionChanges = {
capturing: boolean;
};
-/** The one-letter status the tree and file headers show. */
-export type StatusLetter = 'A' | 'M' | 'D' | 'R';
-
-export function statusLetter(kind: FileChangeKind): StatusLetter {
- switch (kind) {
- case 'added':
- return 'A';
- case 'modified':
- return 'M';
- case 'deleted':
- return 'D';
- case 'renamed':
- return 'R';
- }
-}
-
-/** A path split into the directory prefix (with trailing slash) and basename. */
-export function splitPath(path: string): { dir: string; base: string } {
- const at = path.lastIndexOf('/');
- if (at < 0) return { dir: '', base: path };
- return { dir: path.slice(0, at + 1), base: path.slice(at + 1) };
-}
-
/** `owner/name` from a `https://github.com/owner/name` url, when it is one. */
export function repositorySlug(
repository: string | undefined
diff --git a/apps/web/src/features/agent-changes/core/file-tree.test.ts b/apps/web/src/features/agent-changes/core/file-tree.test.ts
deleted file mode 100644
index eb457c50f5..0000000000
--- a/apps/web/src/features/agent-changes/core/file-tree.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import type { ChangedFile } from './changeset';
-import { buildFileTree, flattenFiles } from './file-tree';
-
-function file(path: string): ChangedFile {
- return {
- path,
- kind: 'modified',
- additions: 1,
- deletions: 0,
- binary: false,
- patchOmitted: false,
- };
-}
-
-describe('buildFileTree', () => {
- it('compresses single-child directory chains', () => {
- const tree = buildFileTree([
- file('apps/web/src/a.ts'),
- file('apps/web/src/b.ts'),
- ]);
- expect(tree).toHaveLength(1);
- const dir = tree[0]!;
- expect(dir.kind).toBe('dir');
- if (dir.kind !== 'dir') return;
- expect(dir.name).toBe('apps/web/src');
- expect(dir.path).toBe('apps/web/src');
- expect(dir.children.map((child) => child.name)).toEqual(['a.ts', 'b.ts']);
- });
-
- it('stops compressing where the tree branches', () => {
- const tree = buildFileTree([
- file('apps/web/src/a.ts'),
- file('apps/web/test/b.ts'),
- file('crates/x/src/lib.rs'),
- ]);
- expect(tree.map((node) => node.name)).toEqual(['apps/web', 'crates/x/src']);
- const web = tree[0]!;
- if (web.kind !== 'dir') throw new Error('expected dir');
- expect(web.children.map((node) => node.name)).toEqual(['src', 'test']);
- });
-
- it('lists directories before files and keeps patch order', () => {
- const tree = buildFileTree([
- file('README.md'),
- file('docs/guide.md'),
- file('LICENSE'),
- ]);
- expect(tree.map((node) => `${node.kind}:${node.name}`)).toEqual([
- 'dir:docs',
- 'file:README.md',
- 'file:LICENSE',
- ]);
- });
-
- it('flattens back to the files in display order', () => {
- const files = [file('b/y.ts'), file('a.ts'), file('b/x.ts')];
- expect(flattenFiles(buildFileTree(files)).map((f) => f.path)).toEqual([
- 'b/y.ts',
- 'b/x.ts',
- 'a.ts',
- ]);
- });
-});
diff --git a/apps/web/src/features/agent-changes/core/file-tree.ts b/apps/web/src/features/agent-changes/core/file-tree.ts
deleted file mode 100644
index 299bf2504e..0000000000
--- a/apps/web/src/features/agent-changes/core/file-tree.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * The changed-files tree: directories compressed along single-child chains
- * (`apps/web/src` reads as one row when nothing branches off it), files in
- * patch order under their directory, directories before files.
- */
-
-import type { ChangedFile } from './changeset';
-
-export type FileTreeDir = {
- kind: 'dir';
- /** The compressed segment, e.g. `apps/web/src`. */
- name: string;
- /** Full path of the directory, for a stable key. */
- path: string;
- children: FileTreeNode[];
-};
-
-export type FileTreeFile = {
- kind: 'file';
- /** Basename shown in the row. */
- name: string;
- file: ChangedFile;
-};
-
-export type FileTreeNode = FileTreeDir | FileTreeFile;
-
-type MutableDir = {
- name: string;
- path: string;
- dirs: Map<string, MutableDir>;
- files: FileTreeFile[];
-};
-
-function newDir(name: string, path: string): MutableDir {
- return { name, path, dirs: new Map(), files: [] };
-}
-
-/**
- * Build the tree from the files' paths. Order is preserved: directories
- * appear in the order their first file appeared, files in patch order.
- */
-export function buildFileTree(files: readonly ChangedFile[]): FileTreeNode[] {
- const root = newDir('', '');
- for (const file of files) {
- const segments = file.path.split('/').filter((segment) => segment !== '');
- const base = segments.pop() ?? file.path;
- let node = root;
- for (const segment of segments) {
- let next = node.dirs.get(segment);
- if (!next) {
- next = newDir(segment, node.path ? `${node.path}/${segment}` : segment);
- node.dirs.set(segment, next);
- }
- node = next;
- }
- node.files.push({ kind: 'file', name: base, file });
- }
- return [...compress(root).map(finish), ...root.files];
-}
-
-/** Fold a directory with exactly one child directory and no files into it. */
-function compress(dir: MutableDir): MutableDir[] {
- const out: MutableDir[] = [];
- for (let child of dir.dirs.values()) {
- while (child.files.length === 0 && child.dirs.size === 1) {
- const [only] = child.dirs.values();
- child = {
- name: `${child.name}/${only!.name}`,
- path: only!.path,
- dirs: only!.dirs,
- files: only!.files,
- };
- }
- out.push(child);
- }
- return out;
-}
-
-function finish(dir: MutableDir): FileTreeDir {
- return {
- kind: 'dir',
- name: dir.name,
- path: dir.path,
- children: [...compress(dir).map(finish), ...dir.files],
- };
-}
-
-/** Every file in the tree, depth first, in display order. */
-export function flattenFiles(nodes: readonly FileTreeNode[]): ChangedFile[] {
- const out: ChangedFile[] = [];
- const walk = (list: readonly FileTreeNode[]) => {
- for (const node of list) {
- if (node.kind === 'file') out.push(node.file);
- else walk(node.children);
- }
- };
- walk(nodes);
- return out;
-}
diff --git a/apps/web/src/features/agent-changes/core/layout.test.ts b/apps/web/src/features/agent-changes/core/layout.test.ts
index a4cc83f1f1..a1204c0d3b 100644
--- a/apps/web/src/features/agent-changes/core/layout.test.ts
+++ b/apps/web/src/features/agent-changes/core/layout.test.ts
@@ -11,26 +11,26 @@ import {
describe('layout moves', () => {
it('toggles the pane from the session header', () => {
- expect(toggleChanges('agent-only')).toBe('split');
- expect(toggleChanges('split')).toBe('agent-only');
- expect(toggleChanges('changes-only')).toBe('agent-only');
+ expect(toggleChanges('closed')).toBe('split');
+ expect(toggleChanges('split')).toBe('closed');
+ expect(toggleChanges('full')).toBe('closed');
});
it('spotlights and comes back', () => {
- expect(toggleSpotlight('split')).toBe('changes-only');
- expect(toggleSpotlight('changes-only')).toBe('split');
- expect(toggleSpotlight('agent-only')).toBe('changes-only');
+ expect(toggleSpotlight('split')).toBe('full');
+ expect(toggleSpotlight('full')).toBe('split');
+ expect(toggleSpotlight('closed')).toBe('full');
});
it('only opens a closed pane', () => {
- expect(ensureChangesVisible('agent-only')).toBe('split');
- expect(ensureChangesVisible('changes-only')).toBe('changes-only');
+ expect(ensureChangesVisible('closed')).toBe('split');
+ expect(ensureChangesVisible('full')).toBe('full');
expect(ensureChangesVisible('split')).toBe('split');
});
it('knows which panes are on screen', () => {
- expect(isChangesVisible('agent-only')).toBe(false);
- expect(isSessionVisible('changes-only')).toBe(false);
+ expect(isChangesVisible('closed')).toBe(false);
+ expect(isSessionVisible('full')).toBe(false);
expect(isChangesVisible('split') && isSessionVisible('split')).toBe(true);
});
});
diff --git a/apps/web/src/features/agent-changes/core/layout.ts b/apps/web/src/features/agent-changes/core/layout.ts
index 883088e10c..9bdb3c54c5 100644
--- a/apps/web/src/features/agent-changes/core/layout.ts
+++ b/apps/web/src/features/agent-changes/core/layout.ts
@@ -1,13 +1,16 @@
/**
* The pane's three layouts and the moves between them.
*
- * `split` shows the session and the changes side by side; `agent-only` hands
- * the width back to the transcript; `changes-only` spotlights the review.
+ * `split` shows the host (a session or a pull request) and the changes side
+ * by side; `closed` hands the width back to the host; `full` spotlights the
+ * review.
*/
-export type DiffStyle = 'unified' | 'split';
+export const DIFF_STYLES = ['unified', 'split'] as const;
+export type DiffStyle = (typeof DIFF_STYLES)[number];
-export type PaneLayout = 'split' | 'agent-only' | 'changes-only';
+export const PANE_LAYOUTS = ['closed', 'split', 'full'] as const;
+export type PaneLayout = (typeof PANE_LAYOUTS)[number];
/** Share of the width the changes pane takes when it first opens. */
export const DEFAULT_CHANGES_SHARE = 58;
@@ -15,26 +18,26 @@ export const MIN_CHANGES_SHARE = 22;
export const MAX_CHANGES_SHARE = 74;
export function isChangesVisible(layout: PaneLayout): boolean {
- return layout !== 'agent-only';
+ return layout !== 'closed';
}
export function isSessionVisible(layout: PaneLayout): boolean {
- return layout !== 'changes-only';
+ return layout !== 'full';
}
-/** The session header toggle: open the split, or close the pane. */
+/** The header toggle: open the split, or close the pane. */
export function toggleChanges(layout: PaneLayout): PaneLayout {
- return layout === 'agent-only' ? 'split' : 'agent-only';
+ return layout === 'closed' ? 'split' : 'closed';
}
/** The pane's spotlight button: take the full width, or come back. */
export function toggleSpotlight(layout: PaneLayout): PaneLayout {
- return layout === 'changes-only' ? 'split' : 'changes-only';
+ return layout === 'full' ? 'split' : 'full';
}
/** Anything that needs the pane on screen goes through this first. */
export function ensureChangesVisible(layout: PaneLayout): PaneLayout {
- return layout === 'agent-only' ? 'split' : layout;
+ return layout === 'closed' ? 'split' : layout;
}
export function clampChangesShare(share: number): number {
diff --git a/apps/web/src/features/agent-changes/core/review-notes.test.ts b/apps/web/src/features/agent-changes/core/review-notes.test.ts
index 4b4686520b..7760a3c47d 100644
--- a/apps/web/src/features/agent-changes/core/review-notes.test.ts
+++ b/apps/web/src/features/agent-changes/core/review-notes.test.ts
@@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest';
import {
describeNoteLines,
formatNotesForAgent,
- notesForFile,
queuedNotes,
type ReviewNote,
sendableNotes,
@@ -51,16 +50,13 @@ describe('describeNoteLines', () => {
)
).toBe('lines 3–6 (old)');
});
-});
-describe('notesForFile', () => {
- it('filters by path and sorts by line', () => {
- const list = [
- note({ id: 'a', lineNumber: 20, endLineNumber: 20 }),
- note({ id: 'b', path: 'b.ts' }),
- note({ id: 'c', lineNumber: 5, endLineNumber: 5 }),
- ];
- expect(notesForFile(list, 'a.ts').map((n) => n.id)).toEqual(['c', 'a']);
+ it('names both sides of a range dragged from deleted lines into added ones', () => {
+ expect(
+ describeNoteLines(
+ note({ startSide: 'deletions', lineNumber: 87, endLineNumber: 91 })
+ )
+ ).toBe('line 87 (old) to line 91 (new)');
});
});
diff --git a/apps/web/src/features/agent-changes/core/review-notes.ts b/apps/web/src/features/agent-changes/core/review-notes.ts
index 91717fdfb4..c0d9471c0e 100644
--- a/apps/web/src/features/agent-changes/core/review-notes.ts
+++ b/apps/web/src/features/agent-changes/core/review-notes.ts
@@ -10,31 +10,36 @@
/** Which side of the diff a line belongs to, in Pierre's vocabulary. */
export type DiffSide = 'additions' | 'deletions';
-export type ReviewNote = {
- id: string;
+/**
+ * Where a note goes: the lines the reviewer picked. It ends on `side`; a
+ * unified range dragged from deleted lines into added ones starts on the
+ * other side, in `startSide`'s numbering.
+ */
+export type NoteAnchor = {
/** The file the note is on, by its current path. */
path: string;
side: DiffSide;
- /** First line of the annotated range, in that side's numbering. */
+ startSide?: DiffSide;
+ /** First line of the range. */
lineNumber: number;
/** Last line, equal to `lineNumber` for a single line. */
endLineNumber: number;
+};
+
+export type ReviewNote = NoteAnchor & {
+ id: string;
text: string;
/** Set once the note has been posted to the agent. */
sentAt?: string;
createdAt: string;
};
-/** Where a new note goes: the line the reviewer picked. */
-export type NoteAnchor = {
- path: string;
- side: DiffSide;
- lineNumber: number;
- endLineNumber: number;
-};
+/** The note being written: where it goes, and its text so far. */
+export type NoteDraft = { range: NoteAnchor; text: string };
export function noteAnchorKey(anchor: NoteAnchor): string {
- return `${anchor.path}:${anchor.side}:${anchor.lineNumber}-${anchor.endLineNumber}`;
+ const start = anchor.startSide ? `${anchor.startSide}@` : '';
+ return `${anchor.path}:${anchor.side}:${start}${anchor.lineNumber}-${anchor.endLineNumber}`;
}
export function queuedNotes(notes: readonly ReviewNote[]): ReviewNote[] {
@@ -55,24 +60,18 @@ export function orderNotes(notes: readonly ReviewNote[]): ReviewNote[] {
);
}
-/** Notes on one file, in line order, queued first. */
-export function notesForFile(
- notes: readonly ReviewNote[],
- path: string
-): ReviewNote[] {
- return notes
- .filter((note) => note.path === path)
- .sort((a, b) => a.lineNumber - b.lineNumber);
-}
+const version = (side: DiffSide) => (side === 'additions' ? 'new' : 'old');
export function describeNoteLines(
- note: Pick<ReviewNote, 'side' | 'lineNumber' | 'endLineNumber'>
+ note: Pick<ReviewNote, 'side' | 'startSide' | 'lineNumber' | 'endLineNumber'>
): string {
- const version = note.side === 'additions' ? 'new' : 'old';
+ if (note.startSide && note.startSide !== note.side) {
+ return `line ${note.lineNumber} (${version(note.startSide)}) to line ${note.endLineNumber} (${version(note.side)})`;
+ }
if (note.endLineNumber > note.lineNumber) {
- return `lines ${note.lineNumber}–${note.endLineNumber} (${version})`;
+ return `lines ${note.lineNumber}–${note.endLineNumber} (${version(note.side)})`;
}
- return `line ${note.lineNumber} (${version})`;
+ return `line ${note.lineNumber} (${version(note.side)})`;
}
/**
diff --git a/apps/web/src/features/agent-changes/core/url-state.test.ts b/apps/web/src/features/agent-changes/core/url-state.test.ts
deleted file mode 100644
index 6bd54eeb2f..0000000000
--- a/apps/web/src/features/agent-changes/core/url-state.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- DEFAULT_DIFF_URL_STATE,
- readDiffUrlState,
- writeDiffUrlState,
-} from './url-state';
-
-describe('diff URL identities', () => {
- it('round-trips namespaced PR ids and preserves adjacent sessions', () => {
- const key = 'pr:macro-inc/macro/1482,revision%2';
- const state = { layout: 'changes-only', diffStyle: 'split' } as const;
- const value = writeDiffUrlState('session-1:split:unified', key, state);
- expect(readDiffUrlState(value, key)).toEqual(state);
- expect(readDiffUrlState(value, 'session-1')).toEqual({
- layout: 'split',
- diffStyle: 'unified',
- });
- expect(writeDiffUrlState(value, key, DEFAULT_DIFF_URL_STATE)).toBe(
- 'session-1:split:unified'
- );
- });
-
- it('ignores malformed escaping', () => {
- expect(readDiffUrlState('%xx:split:unified', '%xx')).toEqual(
- DEFAULT_DIFF_URL_STATE
- );
- });
-});
diff --git a/apps/web/src/features/agent-changes/core/url-state.ts b/apps/web/src/features/agent-changes/core/url-state.ts
deleted file mode 100644
index 8017d78647..0000000000
--- a/apps/web/src/features/agent-changes/core/url-state.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import type { DiffStyle, PaneLayout } from './layout';
-
-/**
- * The query key the viewer stores its state under. One key holds every host's
- * entry, so the split router owns it globally rather than per route: the
- * viewer mounts wherever an agent session does, and a pane that navigates
- * elsewhere must not drop a neighbouring pane's entry.
- */
-export const DIFF_SEARCH_PARAM = 'diff';
-
-export type DiffUrlState = { layout: PaneLayout; diffStyle: DiffStyle };
-
-export const DEFAULT_DIFF_URL_STATE: DiffUrlState = {
- layout: 'agent-only',
- diffStyle: 'unified',
-};
-
-/** Each tuple belongs to a host, so adjacent viewers stay independent. */
-function entries(value: unknown): Map<string, DiffUrlState> {
- const result = new Map<string, DiffUrlState>();
- if (typeof value !== 'string') return result;
- for (const entry of value.split(',')) {
- const [scopeKey, layout, diffStyle, extra] = entry.split(':');
- if (
- !scopeKey ||
- extra !== undefined ||
- (layout !== 'agent-only' &&
- layout !== 'split' &&
- layout !== 'changes-only') ||
- (diffStyle !== 'unified' && diffStyle !== 'split')
- )
- continue;
- try {
- result.set(decodeURIComponent(scopeKey), { layout, diffStyle });
- } catch {
- // Ignore malformed URL entries without disturbing the other viewers.
- }
- }
- return result;
-}
-
-export function readDiffUrlState(
- value: unknown,
- scopeKey: string | undefined
-): DiffUrlState {
- return (
- (scopeKey ? entries(value).get(scopeKey) : undefined) ??
- DEFAULT_DIFF_URL_STATE
- );
-}
-
-export function writeDiffUrlState(
- value: unknown,
- scopeKey: string,
- state: DiffUrlState
-): string | undefined {
- const next = entries(value);
- if (state.layout === 'agent-only' && state.diffStyle === 'unified') {
- next.delete(scopeKey);
- } else {
- next.set(scopeKey, state);
- }
- return (
- [...next]
- .map(
- ([id, state]) =>
- `${encodeURIComponent(id)}:${state.layout}:${state.diffStyle}`
- )
- .join(',') || undefined
- );
-}
diff --git a/apps/web/src/features/agent-changes/debug/Gallery.tsx b/apps/web/src/features/agent-changes/debug/Gallery.tsx
index 2f2d30fba3..23cddf27c4 100644
--- a/apps/web/src/features/agent-changes/debug/Gallery.tsx
+++ b/apps/web/src/features/agent-changes/debug/Gallery.tsx
@@ -5,32 +5,32 @@
* `agent-changes-ui` component.
*/
+import { SAMPLE_PATCH } from '@app/components/diff-view/debug/fixtures';
import { Button } from '@ui';
import { createSignal, For } from 'solid-js';
import { AgentChangesControllerProvider } from '../context/agent-changes-controller';
+import { createPaneViewState } from '../pane-view-state';
import { createAgentChanges } from '../primitives/create-agent-changes';
import { createMockAgentChangesContext } from '../tests/mock-context';
-import { createUrlDiffState } from '../url-diff-state';
import { AgentChangesSplit } from '../views/AgentChangesSplit';
import {
ChangesHandoff,
ChangesToggle,
ReviewNotesDock,
} from '../views/SessionChangesControls';
-import { GALLERY_PATCH, gallerySummary } from './gallery-fixture';
+import { gallerySummary } from './gallery-fixture';
export default function AgentChangesGallery() {
const context = createMockAgentChangesContext({
summary: gallerySummary(),
- patch: GALLERY_PATCH,
+ patch: SAMPLE_PATCH,
sessionId: 'gallery-session',
});
- const urlState = createUrlDiffState(context.host.scopeKey);
+ const view = createPaneViewState();
const [dismissed, setDismissed] = createSignal<string>();
const controller = createAgentChanges({
context,
- paneLayout: [urlState.layout, urlState.setLayout],
- diffStyle: [urlState.diffStyle, urlState.setDiffStyle],
+ view,
dismissed: [dismissed, setDismissed],
});
if (controller.review.queued().length === 0) {
diff --git a/apps/web/src/features/agent-changes/debug/gallery-fixture.ts b/apps/web/src/features/agent-changes/debug/gallery-fixture.ts
index 0037344cf4..a20e51c492 100644
--- a/apps/web/src/features/agent-changes/debug/gallery-fixture.ts
+++ b/apps/web/src/features/agent-changes/debug/gallery-fixture.ts
@@ -1,103 +1,9 @@
+import {
+ SAMPLE_FILES,
+ SAMPLE_PATCH,
+} from '@app/components/diff-view/debug/fixtures';
import type { SessionChanges } from '../core/changeset';
-/** A patch with several files, a rename, and a deletion for the gallery. */
-export const GALLERY_PATCH = `diff --git a/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts b/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
-index 1111111..2222222 100644
---- a/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
-+++ b/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
-@@ -7,7 +7,8 @@
- import { createMemo } from 'solid-js';
-
- import { useAgentSessionsQuery } from '@queries/agent/sessions';
--import type { AgentSessionSummary } from '@service-agent-fold/generated/types';
-+import { hasUnreadActivity } from '@block-agent/state/unread';
-+import type { AgentSessionSummary } from '@service-agent-fold/generated/types';
-
- import type { SidebarItemId } from '../nav-items';
-
-@@ -19,12 +20,15 @@ const DOTTED: readonly SidebarItemId[] = ['inbox', 'channels', 'agents'];
- export function useSidebarUnread(): (id: SidebarItemId) => boolean {
- const sessions = useAgentSessionsQuery();
-
-- // Activity after the read marker lights the dot.
-- const agentsUnread = createMemo(() =>
-- (sessions.data ?? []).some(
-- (session: AgentSessionSummary) => session.lastEventAt > session.lastReadAt
-- )
-- );
-+ // Archiving takes a session off the inbox, so its activity stops being
-+ // news. The rail has to ask the same question the agents list asks,
-+ // through the same predicate.
-+ const agentsUnread = createMemo(() =>
-+ (sessions.data ?? []).some((session: AgentSessionSummary) =>
-+ hasUnreadActivity(session)
-+ )
-+ );
-
- return (id) => (id === 'agents' ? agentsUnread() : false);
- }
-diff --git a/apps/web/src/features/block-agent/state/unread.ts b/apps/web/src/features/block-agent/state/unread.ts
-new file mode 100644
-index 0000000..3333333
---- /dev/null
-+++ b/apps/web/src/features/block-agent/state/unread.ts
-@@ -0,0 +1,14 @@
-+import type { AgentSessionSummary } from '@service-agent-fold/generated/types';
-+
-+/** An archived session is off the inbox, so its activity is not news. */
-+export function isArchived(session: AgentSessionSummary): boolean {
-+ return session.archivedAt != null;
-+}
-+
-+export function hasUnreadActivity(session: AgentSessionSummary): boolean {
-+ if (isArchived(session)) return false;
-+ const lastEventAt = session.lastEventAt;
-+ if (lastEventAt == null) return false;
-+ return lastEventAt > (session.lastReadAt ?? 0);
-+}
-+
-diff --git a/crates/macro_agent_sessions/src/service.rs b/crates/macro_agent_sessions/src/service.rs
-index 4444444..5555555 100644
---- a/crates/macro_agent_sessions/src/service.rs
-+++ b/crates/macro_agent_sessions/src/service.rs
-@@ -85,8 +85,14 @@ impl SessionService {
- #[instrument(skip(self), fields(session_id = %id))]
- pub async fn archive(&self, id: AgentSessionId) -> Result<(), ArchiveError> {
-- self.repo.set_archived(id, Utc::now()).await?;
-- Ok(())
-+ let now = Utc::now();
-+ let mut tx = self.repo.begin().await?;
-+
-+ self.repo.set_archived(&mut tx, id, now).await?;
-+ self.repo.mark_read(&mut tx, id, now).await?;
-+
-+ tx.commit().await?;
-+ Ok(())
- }
-
- #[instrument(skip(self), fields(owner = %owner))]
-diff --git a/crates/macro_agent_sessions/src/legacy_unread.rs b/crates/macro_agent_sessions/src/legacy_unread.rs
-deleted file mode 100644
-index 6666666..0000000
---- a/crates/macro_agent_sessions/src/legacy_unread.rs
-+++ /dev/null
-@@ -1,3 +0,0 @@
--pub fn unread(last_event_at: i64, last_read_at: i64) -> bool {
-- last_event_at > last_read_at
--}
-diff --git a/crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql b/crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql
-new file mode 100644
-index 0000000..7777777
---- /dev/null
-+++ b/crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql
-@@ -0,0 +1,5 @@
-+-- Archived sessions drop out of the unread count. Without a partial index
-+-- the filter falls back to a sequential scan on long workspace histories.
-+CREATE INDEX CONCURRENTLY IF NOT EXISTS agent_sessions_unread_active_idx
-+ ON agent_sessions (owner_id, last_event_at DESC)
-+ WHERE archived_at IS NULL;
-`;
-
export function gallerySummary(): SessionChanges {
return {
capturing: false,
@@ -111,59 +17,10 @@ export function gallerySummary(): SessionChanges {
repository: 'https://github.com/macro-inc/macro',
base: { name: 'main' },
head: { name: 'agent/unread-archived-sessions' },
- files: [
- {
- path: 'apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts',
- kind: 'modified',
- additions: 10,
- deletions: 7,
- binary: false,
- patchOmitted: false,
- },
- {
- path: 'apps/web/src/features/block-agent/state/unread.ts',
- kind: 'added',
- additions: 14,
- deletions: 0,
- binary: false,
- patchOmitted: false,
- },
- {
- path: 'crates/macro_agent_sessions/src/service.rs',
- kind: 'modified',
- additions: 8,
- deletions: 2,
- binary: false,
- patchOmitted: false,
- },
- {
- path: 'crates/macro_agent_sessions/src/legacy_unread.rs',
- kind: 'deleted',
- additions: 0,
- deletions: 3,
- binary: false,
- patchOmitted: false,
- },
- {
- path: 'crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql',
- kind: 'added',
- additions: 5,
- deletions: 0,
- binary: false,
- patchOmitted: false,
- },
- {
- path: 'static_assets/logo.png',
- kind: 'modified',
- additions: 0,
- deletions: 0,
- binary: true,
- patchOmitted: false,
- },
- ],
- additions: 37,
- deletions: 12,
- patchBytes: GALLERY_PATCH.length,
+ files: SAMPLE_FILES,
+ additions: SAMPLE_FILES.reduce((sum, file) => sum + file.additions, 0),
+ deletions: SAMPLE_FILES.reduce((sum, file) => sum + file.deletions, 0),
+ patchBytes: SAMPLE_PATCH.length,
truncated: false,
capturedAt: '2026-09-15T00:00:02Z',
},
diff --git a/apps/web/src/features/agent-changes/pane-view-state.ts b/apps/web/src/features/agent-changes/pane-view-state.ts
new file mode 100644
index 0000000000..853490f53d
--- /dev/null
+++ b/apps/web/src/features/agent-changes/pane-view-state.ts
@@ -0,0 +1,34 @@
+import {
+ createSearchParams,
+ useOwnsSearchNamespace,
+} from '@app/lib/split-router';
+import { createSignal } from 'solid-js';
+import { changesSearch } from './changes-search';
+import type { PaneViewState } from './context/agent-changes-context';
+import type { DiffStyle, PaneLayout } from './core/layout';
+
+/** View state that lives only as long as the host, starting closed. */
+export function createLocalPaneViewState(): PaneViewState {
+ const [layout, setLayout] = createSignal<PaneLayout>('closed');
+ const [diffStyle, setDiffStyle] = createSignal<DiffStyle>('unified');
+ return { layout, setLayout, diffStyle, setDiffStyle };
+}
+
+/**
+ * View state in the split's URL when its route owns `changesSearch`, so a
+ * copied URL, a reload, and Back/Forward restore the pane; local elsewhere,
+ * such as a preview. Opening and closing the pane are history entries;
+ * switching the diff style replaces the current one.
+ */
+export function createPaneViewState(): PaneViewState {
+ if (!useOwnsSearchNamespace(changesSearch.namespace)()) {
+ return createLocalPaneViewState();
+ }
+ const [search, setSearch] = createSearchParams(changesSearch);
+ return {
+ layout: () => search.pane,
+ setLayout: (pane) => setSearch({ pane }, { history: 'push' }),
+ diffStyle: () => search.style,
+ setDiffStyle: (style) => setSearch({ style }, { history: 'replace' }),
+ };
+}
diff --git a/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts b/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts
index 96a878816d..4b6883191f 100644
--- a/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts
+++ b/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts
@@ -4,8 +4,11 @@
*/
import type { Accessor } from 'solid-js';
-import type { AgentChangesContext } from '../context/agent-changes-context';
-import type { DiffStyle, PaneLayout } from '../core/layout';
+import type {
+ AgentChangesContext,
+ PaneViewState,
+} from '../context/agent-changes-context';
+import type { DiffStyle } from '../core/layout';
import { formatNotesForAgent, sendableNotes } from '../core/review-notes';
import { type ChangesModel, createChangesModel } from './create-changes-model';
import {
@@ -47,10 +50,8 @@ export type AgentChangesController = {
export function createAgentChanges(options: {
context: AgentChangesContext;
storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
- /** Optional controlled pane layout, such as the URL state. */
- paneLayout?: [get: Accessor<PaneLayout>, set: (layout: PaneLayout) => void];
- /** Read and write the reviewer's diff layout preference. */
- diffStyle: [get: Accessor<DiffStyle>, set: (style: DiffStyle) => void];
+ /** The pane's layout and diff style, from `createPaneViewState`. */
+ view: PaneViewState;
/** Per-session "dismissed for changeset id" memory. */
dismissed: [
get: Accessor<string | undefined>,
@@ -61,7 +62,7 @@ export function createAgentChanges(options: {
const layout = createPaneLayout({
sessionId: host.scopeKey,
storage: options.storage,
- layout: options.paneLayout,
+ layout: [options.view.layout, options.view.setLayout],
});
const model = createChangesModel({
source,
@@ -72,7 +73,7 @@ export function createAgentChanges(options: {
changeset: model.changeset,
storage: options.storage,
});
- const [diffStyle, setDiffStyle] = options.diffStyle;
+ const { diffStyle, setDiffStyle } = options.view;
const [dismissed, setDismissed] = options.dismissed;
const copyPath = async (path: string) => {
diff --git a/apps/web/src/features/agent-changes/primitives/create-changes-model.test.ts b/apps/web/src/features/agent-changes/primitives/create-changes-model.test.ts
index 819115e7de..929c5d8019 100644
--- a/apps/web/src/features/agent-changes/primitives/create-changes-model.test.ts
+++ b/apps/web/src/features/agent-changes/primitives/create-changes-model.test.ts
@@ -80,26 +80,24 @@ function setup() {
}
describe('createChangesModel', () => {
- it('derives the state, tree, and entries once the patch arrives', () => {
+ it('derives the state and files, and reads the patch once the pane shows', () => {
// Mutations run outside the root body, as event handlers would, so
// every derived value settles synchronously before it is read.
const { model, setSummary, setPatchText, setVisible, dispose } = createRoot(
(dispose) => ({ ...setup(), dispose })
);
expect(model.state().kind).toBe('loading');
- expect(model.entries()).toEqual([]);
+ expect(model.patch()).toBe('');
setSummary(summaryWith(['a.ts']));
expect(model.state().kind).toBe('ready');
- expect(model.tree().map((node) => node.name)).toEqual(['a.ts']);
- // Closed pane: no patch, so no entries yet.
- expect(model.entries()).toBeUndefined();
+ expect(model.files().map((file) => file.path)).toEqual(['a.ts']);
+ // Closed pane: the patch is not read yet.
+ expect(model.patch()).toBeUndefined();
setVisible(true);
setPatchText(PATCH);
- const entries = model.entries();
- expect(entries).toHaveLength(1);
- expect(entries?.[0]?.diff?.name).toBe('a.ts');
+ expect(model.patch()).toBe(PATCH);
dispose();
});
@@ -108,9 +106,7 @@ describe('createChangesModel', () => {
const { model, setSummary, setVisible } = setup();
setVisible(true);
setSummary(summaryWith(['img.png'], 0));
- const entries = model.entries();
- expect(entries).toHaveLength(1);
- expect(entries?.[0]?.note).toBe('No diff text for this file');
+ expect(model.patch()).toBe('');
dispose();
});
});
diff --git a/apps/web/src/features/agent-changes/primitives/create-changes-model.ts b/apps/web/src/features/agent-changes/primitives/create-changes-model.ts
index 8305980283..1164768b64 100644
--- a/apps/web/src/features/agent-changes/primitives/create-changes-model.ts
+++ b/apps/web/src/features/agent-changes/primitives/create-changes-model.ts
@@ -1,7 +1,7 @@
/**
* What the pane shows, derived from the source: the capture state, the
* changeset on screen (the latest good one, even while a newer capture runs
- * or has failed), its files as a tree, and the parsed diff for each file.
+ * or has failed), its files, and the patch behind them.
*/
import { type Accessor, createMemo, createSignal } from 'solid-js';
@@ -15,21 +15,17 @@ import {
type ChangesState,
changesState,
} from '../core/changeset';
-import { buildFileTree, type FileTreeNode } from '../core/file-tree';
-import {
- type FileDiffEntry,
- matchFilesToDiffs,
- parsePatch,
-} from '../core/patch';
export type ChangesModel = {
state: Accessor<ChangesState>;
/** The changeset on screen, if any. */
changeset: Accessor<Changeset | undefined>;
files: Accessor<ChangedFile[]>;
- tree: Accessor<FileTreeNode[]>;
- /** Files paired with their diffs; undefined until the patch has loaded. */
- entries: Accessor<FileDiffEntry[] | undefined>;
+ /**
+ * The patch behind `files`: empty when no file has diff text, so there is
+ * nothing to wait for; undefined until it has loaded.
+ */
+ patch: Accessor<string | undefined>;
patchStatus: Accessor<QueryStatus>;
retryPatch: () => void;
refresh: () => Promise<void>;
@@ -63,7 +59,6 @@ export function createChangesModel(options: {
}
});
const files = createMemo(() => changeset()?.files ?? []);
- const tree = createMemo(() => buildFileTree(files()));
const hasPatch = () => {
const current = changeset();
@@ -73,21 +68,6 @@ export function createChangesModel(options: {
() => changeset()?.id,
() => options.changesVisible() && hasPatch()
);
- const diffs = createMemo(() => {
- const text = patch.text();
- return text === undefined ? undefined : parsePatch(text);
- });
- const entries = createMemo((): FileDiffEntry[] | undefined => {
- const current = files();
- if (current.length === 0) return [];
- // An empty patch body means every file is binary or omitted; there is
- // nothing to wait for.
- if (!hasPatch()) return matchFilesToDiffs(current, new Map());
- const parsed = diffs();
- return parsed === undefined
- ? undefined
- : matchFilesToDiffs(current, parsed);
- });
const [refreshing, setRefreshing] = createSignal(false);
const [refreshError, setRefreshError] = createSignal<string>();
@@ -108,8 +88,7 @@ export function createChangesModel(options: {
state,
changeset,
files,
- tree,
- entries,
+ patch: () => (hasPatch() ? patch.text() : ''),
patchStatus: patch.status,
retryPatch: patch.retry,
refresh,
diff --git a/apps/web/src/features/agent-changes/primitives/create-pane-layout.ts b/apps/web/src/features/agent-changes/primitives/create-pane-layout.ts
index 7648ab783b..3311954c73 100644
--- a/apps/web/src/features/agent-changes/primitives/create-pane-layout.ts
+++ b/apps/web/src/features/agent-changes/primitives/create-pane-layout.ts
@@ -1,6 +1,6 @@
/**
- * Pane visibility can be controlled by the host URL; the split width stays
- * local to the reviewer and session.
+ * Pane visibility belongs to the host (see `createPaneViewState`); the split
+ * width and whether the file tree shows stay local to the reviewer and scope.
*/
import type { Accessor } from 'solid-js';
@@ -23,45 +23,44 @@ export type PaneLayoutController = {
/** Percent of the width the changes pane takes in the split. */
changesShare: Accessor<number>;
setChangesShare: (share: number) => void;
+ /** The file tree shows beside the diffs. */
+ treeOpen: Accessor<boolean>;
+ toggleTree: () => void;
toggle: () => void;
spotlight: () => void;
open: () => void;
close: () => void;
- backToSplit: () => void;
};
-type StoredLayout = { layout: PaneLayout; share: number };
+type StoredLayout = { share: number; treeOpen: boolean };
-const LAYOUTS: readonly PaneLayout[] = ['split', 'agent-only', 'changes-only'];
-
-function parseStored(raw: unknown): StoredLayout | undefined {
+function parseLayout(raw: unknown): StoredLayout | undefined {
if (typeof raw !== 'object' || raw === null) return undefined;
- const { layout, share } = raw as Partial<StoredLayout>;
- if (!layout || !LAYOUTS.includes(layout)) return undefined;
+ const { share, treeOpen } = raw as { share?: unknown; treeOpen?: unknown };
return {
- layout,
- share: clampChangesShare(typeof share === 'number' ? share : Number.NaN),
+ share:
+ typeof share === 'number'
+ ? clampChangesShare(share)
+ : DEFAULT_CHANGES_SHARE,
+ treeOpen: typeof treeOpen === 'boolean' ? treeOpen : true,
};
}
export function createPaneLayout(options: {
sessionId: Accessor<string | undefined>;
- layout?: [get: Accessor<PaneLayout>, set: (layout: PaneLayout) => void];
+ layout: [get: Accessor<PaneLayout>, set: (layout: PaneLayout) => void];
storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
}): PaneLayoutController {
+ const [layout, setLayout] = options.layout;
const [stored, setStored] = createPersistedSessionState<StoredLayout>({
sessionId: options.sessionId,
namespace: 'agent-changes:layout',
- initial: () => ({ layout: 'agent-only', share: DEFAULT_CHANGES_SHARE }),
- parse: parseStored,
+ initial: () => ({ share: DEFAULT_CHANGES_SHARE, treeOpen: true }),
+ parse: parseLayout,
storage: options.storage,
});
- const layout = () => (options.layout ? options.layout[0]() : stored().layout);
- const setLayout = (next: (layout: PaneLayout) => PaneLayout) => {
- if (options.layout) options.layout[1](next(layout()));
- else
- setStored((previous) => ({ ...previous, layout: next(previous.layout) }));
- };
+ const move = (next: (current: PaneLayout) => PaneLayout) =>
+ setLayout(next(layout()));
return {
layout,
@@ -73,10 +72,12 @@ export function createPaneLayout(options: {
...previous,
share: clampChangesShare(share),
})),
- toggle: () => setLayout(toggleChanges),
- spotlight: () => setLayout(toggleSpotlight),
- open: () => setLayout(ensureChangesVisible),
- close: () => setLayout(() => 'agent-only'),
- backToSplit: () => setLayout(() => 'split'),
+ treeOpen: () => stored().treeOpen,
+ toggleTree: () =>
+ setStored((previous) => ({ ...previous, treeOpen: !previous.treeOpen })),
+ toggle: () => move(toggleChanges),
+ spotlight: () => move(toggleSpotlight),
+ open: () => move(ensureChangesVisible),
+ close: () => setLayout('closed'),
};
}
diff --git a/apps/web/src/features/agent-changes/primitives/create-review-state.test.ts b/apps/web/src/features/agent-changes/primitives/create-review-state.test.ts
index 5fb2591343..23a02bd09a 100644
--- a/apps/web/src/features/agent-changes/primitives/create-review-state.test.ts
+++ b/apps/web/src/features/agent-changes/primitives/create-review-state.test.ts
@@ -113,9 +113,9 @@ describe('createReviewState', () => {
endLineNumber: 12,
};
review.openNote(anchor);
- expect(review.composing()).toEqual(anchor);
+ expect(review.draft()).toEqual({ range: anchor, text: '' });
review.addNote(anchor, ' ');
- expect(review.composing()).toBeUndefined();
+ expect(review.draft()).toBeUndefined();
expect(review.notes()).toHaveLength(0);
review.addNote(anchor, 'Extract a helper');
diff --git a/apps/web/src/features/agent-changes/primitives/create-review-state.ts b/apps/web/src/features/agent-changes/primitives/create-review-state.ts
index f22c007a86..e1874f7708 100644
--- a/apps/web/src/features/agent-changes/primitives/create-review-state.ts
+++ b/apps/web/src/features/agent-changes/primitives/create-review-state.ts
@@ -11,6 +11,7 @@ import { type Accessor, createMemo, createSignal } from 'solid-js';
import type { Changeset } from '../core/changeset';
import {
type NoteAnchor,
+ type NoteDraft,
noteAnchorKey,
queuedNotes,
type ReviewNote,
@@ -32,8 +33,12 @@ export type ReviewController = {
notes: Accessor<ReviewNote[]>;
queued: Accessor<ReviewNote[]>;
- /** Where a note is being written, if one is. */
- composing: Accessor<NoteAnchor | undefined>;
+ /**
+ * The note being written, text included, so it survives the diff view
+ * re-creating the editor.
+ */
+ draft: Accessor<NoteDraft | undefined>;
+ setDraft: (draft: NoteDraft | undefined) => void;
openNote: (anchor: NoteAnchor) => void;
cancelNote: () => void;
addNote: (anchor: NoteAnchor, text: string) => void;
@@ -60,6 +65,8 @@ function isNote(raw: unknown): raw is ReviewNote {
typeof note.path === 'string' &&
typeof note.side === 'string' &&
SIDES.has(note.side) &&
+ (note.startSide === undefined ||
+ (typeof note.startSide === 'string' && SIDES.has(note.startSide))) &&
typeof note.lineNumber === 'number' &&
typeof note.endLineNumber === 'number' &&
typeof note.text === 'string' &&
@@ -118,7 +125,7 @@ export function createReviewState(options: {
storage: options.storage,
});
const [active, setActive] = createSignal<string | undefined>();
- const [composing, setComposing] = createSignal<NoteAnchor | undefined>();
+ const [draft, setDraft] = createSignal<NoteDraft | undefined>();
const changesetId = () => options.changeset()?.id;
const paths = createMemo(
@@ -164,14 +171,15 @@ export function createReviewState(options: {
notes,
queued: () => queuedNotes(notes()),
- composing,
- openNote: (anchor) => setComposing(anchor),
- cancelNote: () => setComposing(undefined),
+ draft,
+ setDraft,
+ openNote: (anchor) => setDraft({ range: anchor, text: '' }),
+ cancelNote: () => setDraft(undefined),
addNote: (anchor, text) => {
const trimmed = text.trim();
- const current = composing();
- if (current && noteAnchorKey(current) === noteAnchorKey(anchor)) {
- setComposing(undefined);
+ const current = draft();
+ if (current && noteAnchorKey(current.range) === noteAnchorKey(anchor)) {
+ setDraft(undefined);
}
if (trimmed === '') return;
setStored((previous) => ({
diff --git a/apps/web/src/features/agent-changes/primitives/create-theme-type.ts b/apps/web/src/features/agent-changes/primitives/create-theme-type.ts
deleted file mode 100644
index f5712f09b3..0000000000
--- a/apps/web/src/features/agent-changes/primitives/create-theme-type.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Macro's light/dark state as a signal for Pierre, tracked off the
- * `data-theme-light` attribute the theme feature keeps on `<html>`.
- */
-
-import { type Accessor, createSignal, onCleanup } from 'solid-js';
-
-export type ThemeType = 'light' | 'dark';
-
-function currentThemeType(): ThemeType {
- if (typeof document === 'undefined') return 'light';
- return document.documentElement.dataset.themeLight === 'false'
- ? 'dark'
- : 'light';
-}
-
-export function createThemeType(): Accessor<ThemeType> {
- const [themeType, setThemeType] = createSignal<ThemeType>(currentThemeType());
- if (
- typeof document !== 'undefined' &&
- typeof MutationObserver !== 'undefined'
- ) {
- const observer = new MutationObserver(() =>
- setThemeType(currentThemeType())
- );
- observer.observe(document.documentElement, {
- attributes: true,
- attributeFilter: ['data-theme-light'],
- });
- onCleanup(() => observer.disconnect());
- }
- return themeType;
-}
diff --git a/apps/web/src/features/agent-changes/primitives/create-url-diff-state.test.tsx b/apps/web/src/features/agent-changes/primitives/create-url-diff-state.test.tsx
deleted file mode 100644
index e01a9919f0..0000000000
--- a/apps/web/src/features/agent-changes/primitives/create-url-diff-state.test.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-import { createMemoryHistory, MemoryRouter, Route } from '@solidjs/router';
-import { render, waitFor } from '@solidjs/testing-library';
-import { createSignal } from 'solid-js';
-import { describe, expect, it } from 'vitest';
-import { readDiffUrlState } from '../core/url-state';
-import { createMemoryStorage } from '../tests/memory-storage';
-import { createUrlDiffState } from '../url-diff-state';
-import { createPaneLayout } from './create-pane-layout';
-
-function setup(url: string) {
- const history = createMemoryHistory();
- history.set({ value: url, replace: true });
- const [sessionId, setSessionId] = createSignal('s1');
- let state!: ReturnType<typeof createUrlDiffState>;
- let layout!: ReturnType<typeof createPaneLayout>;
- const mounted = render(() => (
- <MemoryRouter history={history}>
- <Route
- path="/session"
- component={() => {
- state = createUrlDiffState(sessionId);
- layout = createPaneLayout({
- sessionId,
- storage: createMemoryStorage(),
- layout: [state.layout, state.setLayout],
- });
- return (
- <div>
- {layout.layout()}:{state.diffStyle()}
- </div>
- );
- }}
- />
- </MemoryRouter>
- ));
- return {
- ...mounted,
- history,
- state: () => state,
- layout: () => layout,
- setSessionId,
- };
-}
-
-describe('URL diff state', () => {
- it('restores a shared view and follows browser history for open, spotlight, style, and close', async () => {
- const { history, state, layout } = setup(
- '/session?keep=1&diff=s1:split:unified#message'
- );
- expect(layout().changesVisible()).toBe(true);
- expect(layout().sessionVisible()).toBe(true);
- state().setDiffStyle('split');
- await waitFor(() => expect(state().diffStyle()).toBe('split'));
- layout().spotlight();
- await waitFor(() => expect(layout().sessionVisible()).toBe(false));
- const shared = new URL(history.get(), 'http://local');
- expect(shared.searchParams.get('keep')).toBe('1');
- expect(shared.hash).toBe('#message');
- expect(readDiffUrlState(shared.searchParams.get('diff'), 's1')).toEqual({
- layout: 'changes-only',
- diffStyle: 'split',
- });
- layout().close();
- await waitFor(() => expect(layout().changesVisible()).toBe(false));
- history.back();
- await waitFor(() => expect(layout().layout()).toBe('changes-only'));
- history.back();
- await waitFor(() => expect(layout().layout()).toBe('split'));
- history.back();
- await waitFor(() => expect(state().diffStyle()).toBe('unified'));
- history.forward();
- await waitFor(() => expect(state().diffStyle()).toBe('split'));
- });
-
- it('keeps session states separate and a plain URL closed', async () => {
- const { history, state, layout, setSessionId } = setup(
- '/session?diff=s2:changes-only:split'
- );
- expect(layout().changesVisible()).toBe(false);
- layout().open();
- await waitFor(() => expect(layout().layout()).toBe('split'));
- expect(
- readDiffUrlState(
- new URL(history.get(), 'http://local').searchParams.get('diff'),
- 's2'
- )
- ).toEqual({ layout: 'changes-only', diffStyle: 'split' });
- layout().close();
- await waitFor(() => expect(layout().changesVisible()).toBe(false));
- expect(
- new URL(history.get(), 'http://local').searchParams.get('diff')
- ).toBe('s2:changes-only:split');
- setSessionId('s2');
- expect(layout().layout()).toBe('changes-only');
- expect(state().diffStyle()).toBe('split');
- setSessionId('s3');
- expect(layout().changesVisible()).toBe(false);
- });
-
- it('ignores malformed values and does not put divider drags into history', async () => {
- const { history, layout } = setup(
- '/session?diff=s1:invalid:split,s2:split:invalid'
- );
- expect(layout().changesVisible()).toBe(false);
- const before = history.get();
- layout().setChangesShare(65);
- expect(layout().changesShare()).toBe(65);
- expect(history.get()).toBe(before);
- layout().open();
- await waitFor(() => expect(layout().layout()).toBe('split'));
- expect(
- new URL(history.get(), 'http://local').searchParams.get('diff')
- ).toBe('s1:split:unified');
- });
-});
diff --git a/apps/web/src/features/agent-changes/url-diff-state.ts b/apps/web/src/features/agent-changes/url-diff-state.ts
deleted file mode 100644
index ee812684af..0000000000
--- a/apps/web/src/features/agent-changes/url-diff-state.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { useSearchParams } from '@solidjs/router';
-import type { Accessor } from 'solid-js';
-import type { DiffStyle, PaneLayout } from './core/layout';
-import {
- DIFF_SEARCH_PARAM,
- type DiffUrlState,
- readDiffUrlState,
- writeDiffUrlState,
-} from './core/url-state';
-
-/** Read directly from the router so reloads and Back/Forward restore the view. */
-export function createUrlDiffState(scopeKey: Accessor<string | undefined>) {
- const [params, setParams] = useSearchParams();
- const state = () => readDiffUrlState(params[DIFF_SEARCH_PARAM], scopeKey());
- const update = (patch: Partial<DiffUrlState>) => {
- const id = scopeKey();
- if (!id) return;
- setParams(
- {
- [DIFF_SEARCH_PARAM]: writeDiffUrlState(params[DIFF_SEARCH_PARAM], id, {
- ...state(),
- ...patch,
- }),
- },
- { replace: false, scroll: false }
- );
- };
- return {
- layout: () => state().layout,
- setLayout: (layout: PaneLayout) => update({ layout }),
- diffStyle: () => state().diffStyle,
- setDiffStyle: (diffStyle: DiffStyle) => update({ diffStyle }),
- };
-}
diff --git a/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx b/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx
index af78548da7..4290b47f8e 100644
--- a/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx
+++ b/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx
@@ -17,7 +17,7 @@ export function AgentChangesSplit(props: ParentProps) {
const { available, layout } = useAgentChanges();
let zone: ResizeZoneCtx | undefined;
// A host that can never have changes keeps the session alone on screen,
- // whatever a stale URL or persisted layout asks for.
+ // whatever a stale URL asks for.
const sessionVisible = () => !available() || layout.sessionVisible();
const changesVisible = () => available() && layout.changesVisible();
diff --git a/apps/web/src/features/agent-changes/views/ChangesPane.tsx b/apps/web/src/features/agent-changes/views/ChangesPane.tsx
index 43acdaf8e3..c47feb3790 100644
--- a/apps/web/src/features/agent-changes/views/ChangesPane.tsx
+++ b/apps/web/src/features/agent-changes/views/ChangesPane.tsx
@@ -1,146 +1,50 @@
/**
- * The Changes pane: header, review bar, file tree, the stack of file cards,
- * and their inline notes. Reads the controller and hands
- * resolved values to the components.
+ * The Changes pane: a title row with the pane's own controls, a toolbar for
+ * the diffs, the capture notices, and the file tree beside the diff stack
+ * with review notes hung under their lines. Reads the controller and
+ * composes the generic tree and diff view from it.
*/
+import {
+ createDiffComments,
+ type DiffCollapse,
+ DiffCounts,
+ DiffView,
+ StatusLetter,
+} from '@app/components/diff-view';
+import ArrowsClockwiseIcon from '@phosphor/arrows-clockwise.svg';
import CircleNotchIcon from '@phosphor/circle-notch.svg';
+import CopyIcon from '@phosphor/copy.svg';
+import FileIcon from '@phosphor/file.svg';
+import SidebarIcon from '@phosphor/sidebar-simple.svg';
import WarningCircleIcon from '@phosphor/warning-circle.svg';
-import { Button } from '@ui';
-import {
- createEffect,
- createSignal,
- For,
- Match,
- on,
- onCleanup,
- Show,
- Switch,
-} from 'solid-js';
+import { Button, cn, Panel } from '@ui';
+import { CollapseTransition } from '@ui/components/CollapseTransition';
+import { FileTree } from '@ui/components/FileTree';
+import { Match, Show, Switch } from 'solid-js';
import { ChangesHeader } from '../components/ChangesHeader';
import { CaptureBanner, ChangesNotice } from '../components/ChangesNotice';
-import { FileCard } from '../components/FileCard';
-import { FileTree } from '../components/FileTree';
-import { PierreFileDiff } from '../components/PierreFileDiff';
-import { ReviewBar } from '../components/ReviewBar';
+import { NoteAnnotation } from '../components/NoteAnnotation';
import { useAgentChanges } from '../context/agent-changes-controller';
-import { type ChangesState, describeRange } from '../core/changeset';
-import type { FileDiffEntry } from '../core/patch';
-import { notesForFile } from '../core/review-notes';
-import { createThemeType } from '../primitives/create-theme-type';
-
-const FLASH_MS = 900;
-
-function DiffStack(props: { entries: FileDiffEntry[] }) {
- const { review, diffStyle, copyPath, context } = useAgentChanges();
- const themeType = createThemeType();
- const cards = new Map<string, HTMLElement>();
- const [flashing, setFlashing] = createSignal<string>();
-
- // Jumping from the tree is a DOM concern: scroll the card in and flash it.
- createEffect(
- on(
- review.active,
- (path) => {
- if (!path) return;
- cards.get(path)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
- setFlashing(path);
- const timer = setTimeout(() => setFlashing(undefined), FLASH_MS);
- onCleanup(() => clearTimeout(timer));
- },
- { defer: true }
- )
- );
+import {
+ type ChangesState,
+ describeFileCount,
+ describeRange,
+} from '../core/changeset';
- return (
- <div class="flex min-h-0 min-w-0 flex-1 flex-col gap-3 overflow-y-auto scroll-smooth px-3.5 pt-3 pb-24 motion-reduce:scroll-auto">
- <For each={props.entries}>
- {(entry) => {
- const path = () => entry.file.path;
- const composing = () => {
- const anchor = review.composing();
- return anchor?.path === path() ? anchor : undefined;
- };
- return (
- <FileCard
- entry={entry}
- collapsed={review.isCollapsed(path())}
- flash={flashing() === path()}
- onToggleCollapsed={() => review.toggleCollapsed(path())}
- onCopyPath={() => copyPath(path())}
- ref={(element) => {
- cards.set(path(), element);
- onCleanup(() => cards.delete(path()));
- }}
- body={
- <Show when={entry.diff}>
- {(diff) => (
- <PierreFileDiff
- path={path()}
- diff={diff()}
- diffStyle={diffStyle()}
- themeType={themeType()}
- notes={notesForFile(review.notes(), path())}
- composing={composing()}
- onOpenNote={
- context.host.agent ? review.openNote : undefined
- }
- onCancelNote={review.cancelNote}
- onAddNote={review.addNote}
- onRemoveNote={review.removeNote}
- />
- )}
- </Show>
- }
- />
- );
- }}
- </For>
- </div>
- );
+/** The state narrowed to one kind, for `<Match>` to hand its fields down. */
+function stateOf<K extends ChangesState['kind']>(state: ChangesState, kind: K) {
+ return state.kind === kind
+ ? (state as Extract<ChangesState, { kind: K }>)
+ : undefined;
}
-export function ChangesPane() {
- const controller = useAgentChanges();
- const { layout, model, review, context, diffStyle, setDiffStyle } =
- controller;
- const state = model.state;
- const changeset = model.changeset;
- /** The state narrowed to one kind, for `<Match>` to hand its fields down. */
- const stateOf = <K extends ChangesState['kind']>(kind: K) => {
- const current = state();
- return current.kind === kind
- ? (current as Extract<ChangesState, { kind: K }>)
- : undefined;
- };
- const range = () => {
- const current = changeset();
- return current ? describeRange(current) : undefined;
- };
- const hasFiles = () => model.files().length > 0;
- const showsChangeset = () => changeset() !== undefined;
-
+/** Strips over the body: a failed refresh, and a capture over the changeset on screen. */
+function CaptureBanners() {
+ const { model } = useAgentChanges();
+ const showsChangeset = () => model.changeset() !== undefined;
return (
- <section
- class="relative flex h-full min-w-0 flex-col bg-panel"
- aria-label="Changes"
- >
- <ChangesHeader
- spotlit={layout.layout() === 'changes-only'}
- range={range()}
- diffStyle={diffStyle()}
- onDiffStyle={setDiffStyle}
- pullRequestUrl={context.host.pullRequestUrl()}
- onViewPullRequest={() => {
- const url = context.host.pullRequestUrl();
- if (url) context.host.openExternal(url);
- }}
- refreshing={model.refreshing() || state().kind === 'capturing'}
- onRefresh={() => void model.refresh()}
- onBack={layout.backToSplit}
- onSpotlight={layout.spotlight}
- onClose={layout.close}
- />
+ <>
<Show when={model.refreshError()}>
{(message) => (
<CaptureBanner
@@ -151,6 +55,185 @@ export function ChangesPane() {
/>
)}
</Show>
+ <Show when={showsChangeset() && model.state().kind === 'capturing'}>
+ <CaptureBanner tone="progress" text="Capturing the changes again…" />
+ </Show>
+ <Show when={showsChangeset() && stateOf(model.state(), 'failed')}>
+ {(current) => (
+ <CaptureBanner
+ tone="failure"
+ text={`The last capture failed: ${current().message}`}
+ onRefresh={() => void model.refresh()}
+ refreshing={model.refreshing()}
+ />
+ )}
+ </Show>
+ </>
+ );
+}
+
+/** The toolbar and the tree beside the stack, both over the changeset's files. */
+function ChangesBody() {
+ const { model, review, layout, diffStyle, setDiffStyle, copyPath, context } =
+ useAgentChanges();
+ const collapse: DiffCollapse = {
+ isCollapsed: review.isCollapsed,
+ toggle: review.toggleCollapsed,
+ toggleAll: review.toggleAllCollapsed,
+ anyExpanded: review.anyExpanded,
+ };
+ const refreshing = () =>
+ model.refreshing() || model.state().kind === 'capturing';
+ const notes = createDiffComments({
+ items: review.notes,
+ rangeOf: (note) => note,
+ draft: [review.draft, review.setDraft],
+ canComment: () => context.host.agent !== undefined,
+ render: (spot) => (
+ <NoteAnnotation
+ notes={spot.items}
+ draft={spot.draft}
+ onDraft={notes.editDraft}
+ onAdd={review.addNote}
+ onCancel={review.cancelNote}
+ onRemove={review.removeNote}
+ />
+ ),
+ });
+ return (
+ <DiffView.Root
+ files={model.files()}
+ patch={model.patch() ?? ''}
+ diffStyle={diffStyle()}
+ collapse={collapse}
+ active={review.active()}
+ >
+ <Panel.Toolbar class="gap-1">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label={layout.treeOpen() ? 'Hide file tree' : 'Show file tree'}
+ aria-expanded={layout.treeOpen()}
+ onClick={layout.toggleTree}
+ >
+ <SidebarIcon />
+ </Button>
+ <span class="truncate px-1 text-xs text-ink-subtle">
+ {describeFileCount(model.files().length)}
+ </span>
+ <span class="flex-1" />
+ <DiffView.StyleToggle
+ value={diffStyle()}
+ onChange={setDiffStyle}
+ class="max-md:hidden"
+ />
+ <DiffView.CollapseAll />
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label="Refresh pull request changes"
+ disabled={refreshing()}
+ onClick={() => void model.refresh()}
+ >
+ <ArrowsClockwiseIcon class={cn(refreshing() && 'animate-spin')} />
+ </Button>
+ </Panel.Toolbar>
+ <Panel.Body class="flex flex-col">
+ <CaptureBanners />
+ <Show when={model.changeset()?.truncated}>
+ <CaptureBanner
+ tone="failure"
+ text="Some diffs were left out to fit the size budget; the file list is complete."
+ />
+ </Show>
+ <div class="flex min-h-0 flex-1">
+ <CollapseTransition open={layout.treeOpen()} axis="width">
+ <div class="flex w-64 shrink-0 flex-col overflow-y-auto border-r border-edge-muted p-2 max-md:w-48">
+ <FileTree.Root
+ aria-label="Changed files"
+ items={model.files()}
+ path={(file) => file.path}
+ selected={review.active()}
+ onSelect={(file) => review.activate(file.path)}
+ >
+ {(node) => (
+ <>
+ <FileTree.Icon>
+ <FileIcon />
+ </FileTree.Icon>
+ <FileTree.Name />
+ <span class="shrink-0 text-xs">
+ <DiffCounts
+ additions={node.item.additions}
+ deletions={node.item.deletions}
+ />
+ </span>
+ <StatusLetter kind={node.item.kind} />
+ </>
+ )}
+ </FileTree.Root>
+ </div>
+ </CollapseTransition>
+ <Switch>
+ <Match when={model.patchStatus() === 'error'}>
+ <div class="flex flex-1 flex-col items-center justify-center gap-2 text-center">
+ <WarningCircleIcon class="size-6 text-ink-placeholder" />
+ <p class="text-sm font-medium text-ink">
+ The diff could not be loaded
+ </p>
+ <Button variant="outline" size="sm" onClick={model.retryPatch}>
+ Try again
+ </Button>
+ </div>
+ </Match>
+ <Match when={model.patch() !== undefined}>
+ <DiffView.Stack
+ header={(entry) => (
+ <>
+ <DiffView.CollapseButton />
+ <DiffView.FilePath />
+ <DiffView.FileCounts />
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ tooltip="Copy path"
+ onClick={() => copyPath(entry.file.path)}
+ >
+ <CopyIcon />
+ </Button>
+ </>
+ )}
+ annotations={notes.annotations}
+ renderAnnotation={notes.renderAnnotation}
+ selection={notes.selection}
+ onSelectLines={notes.onSelectLines}
+ />
+ </Match>
+ <Match when={true}>
+ <div class="flex flex-1 items-center justify-center gap-2 text-xs text-ink-placeholder">
+ <CircleNotchIcon class="size-4 animate-spin" />
+ Loading the diff…
+ </div>
+ </Match>
+ </Switch>
+ </div>
+ </Panel.Body>
+ </DiffView.Root>
+ );
+}
+
+/** Every state without files to show, each explained in the body. */
+function ChangesNotices() {
+ const { model } = useAgentChanges();
+ const state = model.state;
+ const showsChangeset = () => model.changeset() !== undefined;
+ const range = () => {
+ const current = model.changeset();
+ return current ? describeRange(current) : undefined;
+ };
+ return (
+ <Panel.Body class="flex flex-col">
+ <CaptureBanners />
<Switch>
<Match when={state().kind === 'loading'}>
<ChangesNotice
@@ -167,7 +250,7 @@ export function ChangesPane() {
refreshing={model.refreshing()}
/>
</Match>
- <Match when={stateOf('not_ready')}>
+ <Match when={stateOf(state(), 'not_ready')}>
{(current) => (
<ChangesNotice
title="Pull request changes unavailable"
@@ -185,7 +268,7 @@ export function ChangesPane() {
refreshing={model.refreshing()}
/>
</Match>
- <Match when={showsChangeset() ? undefined : stateOf('failed')}>
+ <Match when={showsChangeset() ? undefined : stateOf(state(), 'failed')}>
{(current) => (
<ChangesNotice
icon={<WarningCircleIcon />}
@@ -204,84 +287,49 @@ export function ChangesPane() {
/>
</Match>
<Match when={showsChangeset()}>
- <Show when={state().kind === 'capturing'}>
- <CaptureBanner
- tone="progress"
- text="Capturing the changes again…"
- />
- </Show>
- <Show when={stateOf('failed')}>
- {(current) => (
- <CaptureBanner
- tone="failure"
- text={`The last capture failed: ${current().message}`}
- onRefresh={() => void model.refresh()}
- refreshing={model.refreshing()}
- />
- )}
- </Show>
- <Show
- when={hasFiles()}
- fallback={
- <ChangesNotice
- title="No changes"
- detail={
- range()
- ? `Nothing differs between ${range()}.`
- : 'The pull request has no changed files.'
- }
- onRefresh={() => void model.refresh()}
- refreshing={model.refreshing()}
- />
+ <ChangesNotice
+ title="No changes"
+ detail={
+ range()
+ ? `Nothing differs between ${range()}.`
+ : 'The pull request has no changed files.'
}
- >
- <ReviewBar
- anyExpanded={review.anyExpanded()}
- onToggleCollapsed={review.toggleAllCollapsed}
- />
- <Show when={changeset()?.truncated}>
- <CaptureBanner
- tone="failure"
- text="Some diffs were left out to fit the size budget; the file list is complete."
- />
- </Show>
- <div class="flex min-h-0 flex-1">
- <FileTree
- nodes={model.tree()}
- fileCount={model.files().length}
- active={review.active()}
- onSelect={review.activate}
- />
- <Switch>
- <Match when={model.patchStatus() === 'error'}>
- <div class="flex flex-1 flex-col items-center justify-center gap-2 text-center">
- <WarningCircleIcon class="size-6 text-ink-placeholder" />
- <p class="text-sm font-medium text-ink">
- The diff could not be loaded
- </p>
- <Button
- variant="outline"
- size="sm"
- onClick={model.retryPatch}
- >
- Try again
- </Button>
- </div>
- </Match>
- <Match when={model.entries()}>
- {(entries) => <DiffStack entries={entries()} />}
- </Match>
- <Match when={true}>
- <div class="flex flex-1 items-center justify-center gap-2 text-xs text-ink-placeholder">
- <CircleNotchIcon class="size-4 animate-spin" />
- Loading the diff…
- </div>
- </Match>
- </Switch>
- </div>
- </Show>
+ onRefresh={() => void model.refresh()}
+ refreshing={model.refreshing()}
+ />
</Match>
</Switch>
- </section>
+ </Panel.Body>
+ );
+}
+
+export function ChangesPane() {
+ const { layout, model, context } = useAgentChanges();
+ const range = () => {
+ const current = model.changeset();
+ return current ? describeRange(current) : undefined;
+ };
+ const showsFiles = () =>
+ model.changeset() !== undefined && model.files().length > 0;
+
+ return (
+ <Panel class="rounded-none" role="region" aria-label="Changes">
+ <Panel.Header class="gap-1.5">
+ <ChangesHeader
+ spotlit={layout.layout() === 'full'}
+ range={range()}
+ pullRequestUrl={context.host.pullRequestUrl()}
+ onViewPullRequest={() => {
+ const url = context.host.pullRequestUrl();
+ if (url) context.host.openExternal(url);
+ }}
+ onSpotlight={layout.spotlight}
+ onClose={layout.close}
+ />
+ </Panel.Header>
+ <Show when={showsFiles()} fallback={<ChangesNotices />}>
+ <ChangesBody />
+ </Show>
+ </Panel>
);
}
diff --git a/apps/web/src/features/agent-changes/views/changes-pane.test.tsx b/apps/web/src/features/agent-changes/views/changes-pane.test.tsx
index cf5a1e67ba..6d32efc25f 100644
--- a/apps/web/src/features/agent-changes/views/changes-pane.test.tsx
+++ b/apps/web/src/features/agent-changes/views/changes-pane.test.tsx
@@ -3,10 +3,10 @@ import { createSignal } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
import type { AgentChangesContext } from '../context/agent-changes-context';
import { AgentChangesControllerProvider } from '../context/agent-changes-controller';
+import { createLocalPaneViewState } from '../pane-view-state';
import {
type AgentChangesController,
createAgentChanges,
- type DiffStyle,
} from '../primitives/create-agent-changes';
import { createMemoryStorage } from '../tests/memory-storage';
import {
@@ -23,12 +23,18 @@ import {
// Pierre mounts a custom element and highlights with shiki; the pane test
// covers everything around it and leaves the diff body to the browser.
-vi.mock('../components/PierreFileDiff', () => ({
+vi.mock('@app/components/diff-view/pierre/PierreFileDiff', () => ({
PierreFileDiff: (props: { path: string }) => (
<div data-testid="diff" data-path={props.path} />
),
}));
+// jsdom has no ResizeObserver; the file tree's collapse animation measures with one.
+vi.mock('@solid-primitives/resize-observer', () => ({
+ createResizeObserver: () => {},
+ createElementSize: () => ({ width: 0, height: 0 }),
+}));
+
// Module-load quarantine, not a dependency substitute: the connection-gateway
// websocket connects when imported, which jsdom cannot do.
vi.mock('@service-connection/websocket', () => ({
@@ -56,14 +62,13 @@ function mount(
context: AgentChangesContext,
ui: () => ReturnType<typeof ChangesPane>
) {
- const [diffStyle, setDiffStyle] = createSignal<DiffStyle>('unified');
const [dismissed, setDismissed] = createSignal<string>();
let controller!: AgentChangesController;
const result = render(() => {
controller = createAgentChanges({
context,
storage: createMemoryStorage(),
- diffStyle: [diffStyle, setDiffStyle],
+ view: createLocalPaneViewState(),
dismissed: [dismissed, setDismissed],
});
return (
@@ -98,9 +103,9 @@ describe('ChangesPane', () => {
screen.queryByRole('button', { name: 'Mark all viewed' })
).toBeNull();
- fireEvent.click(screen.getAllByRole('button', { name: /^Hide / })[0]!);
+ fireEvent.click(screen.getByRole('button', { name: 'Hide a.ts' }));
expect(screen.getAllByTestId('diff')).toHaveLength(1);
- expect(screen.getByText('Show diff')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Show a.ts' })).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Collapse all' }));
expect(screen.queryAllByTestId('diff')).toHaveLength(0);
@@ -198,11 +203,26 @@ describe('ChangesPane', () => {
expect(
screen.queryByRole('button', { name: 'Create pull request' })
).toBeNull();
- fireEvent.click(screen.getByRole('button', { name: 'View pull request' }));
+ fireEvent.click(
+ screen.getByRole('button', { name: 'View pull request #1482' })
+ );
expect(context.opened).toEqual([url]);
expect(context.sent).toEqual([]);
});
+ it('hides and shows the file tree from the toolbar', async () => {
+ const context = readyContext();
+ const { controller } = mount(context, () => <ChangesPane />);
+ controller().layout.open();
+ const tree = () => screen.queryByRole('group', { name: 'Changed files' });
+ expect(tree()).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Hide file tree' }));
+ await waitFor(() => expect(tree()).toBeNull());
+ expect(controller().layout.treeOpen()).toBe(false);
+ fireEvent.click(screen.getByRole('button', { name: 'Show file tree' }));
+ await waitFor(() => expect(tree()).toBeTruthy());
+ });
+
it('closes and spotlights from its header', () => {
const context = readyContext();
const { controller } = mount(context, () => <ChangesPane />);
@@ -210,15 +230,13 @@ describe('ChangesPane', () => {
fireEvent.click(
screen.getByRole('button', { name: 'Expand changes to the full width' })
);
- expect(controller().layout.layout()).toBe('changes-only');
- fireEvent.click(
- screen.getByRole('button', { name: 'Bring the session back' })
- );
+ expect(controller().layout.layout()).toBe('full');
+ fireEvent.click(screen.getByRole('button', { name: 'Back to the split' }));
expect(controller().layout.layout()).toBe('split');
fireEvent.click(
screen.getByRole('button', { name: 'Close the changes pane' })
);
- expect(controller().layout.layout()).toBe('agent-only');
+ expect(controller().layout.layout()).toBe('closed');
});
});
diff --git a/apps/web/src/features/agents-view/route.tsx b/apps/web/src/features/agents-view/route.tsx
index 59dd6fef05..8a04406a1f 100644
--- a/apps/web/src/features/agents-view/route.tsx
+++ b/apps/web/src/features/agents-view/route.tsx
@@ -1,3 +1,4 @@
+import { changesSearch } from '@app/features/agent-changes/changes-search';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { defineRoute } from '@app/lib/split-router';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
@@ -111,6 +112,7 @@ export const agentsRoute = defineRoute({
component: AgentsRouteView,
remountKey: ({ id }) => id,
claim: ({ id }) => ({ namespace: 'agent', id }),
+ search: [changesSearch.namespace],
});
export const codersRoute = defineRoute({
@@ -120,6 +122,7 @@ export const codersRoute = defineRoute({
component: AgentsRouteView,
remountKey: ({ id }) => id,
claim: ({ id }) => ({ namespace: 'agent', id }),
+ search: [changesSearch.namespace],
});
export const agentChatsRoute = defineRoute({
@@ -130,6 +133,7 @@ export const agentChatsRoute = defineRoute({
component: AgentsRouteView,
remountKey: ({ id }) => id,
claim: ({ id }) => ({ namespace: 'chat', id }),
+ search: [changesSearch.namespace],
});
export const agentsViewRoute = defineRoute({
diff --git a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
index b0c98eae72..1c44d5821a 100644
--- a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
+++ b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx
@@ -9,7 +9,7 @@
* use the shared PR changes controller.
*/
-import { DiffCounts } from '@app/features/agent-changes/components/DiffCounts';
+import { DiffCounts } from '@app/components/diff-view';
import { useOptionalAgentChanges } from '@app/features/agent-changes/context/agent-changes-controller';
import { SidePanel } from '@components/app/side-panel';
import { ModelIcon } from '@core/component/AI/component/ProviderIcon';
diff --git a/apps/web/src/features/block-agent/ui/PierreDiff.tsx b/apps/web/src/features/block-agent/ui/PierreDiff.tsx
index d6488fc7b8..b67819937c 100644
--- a/apps/web/src/features/block-agent/ui/PierreDiff.tsx
+++ b/apps/web/src/features/block-agent/ui/PierreDiff.tsx
@@ -19,6 +19,10 @@
* instead of pierre's OS-preference "system" mode.
*/
+import {
+ createThemeType,
+ PIERRE_STYLE_VARIABLES,
+} from '@app/components/diff-view/pierre/theme';
import {
type FileDiffOptions,
FileDiff as PierreFileDiffInstance,
@@ -56,40 +60,6 @@ const DIFF_OPTIONS = {
expansionLineCount: 20,
} satisfies FileDiffOptions<undefined>;
-/**
- * CSS variables pierre reads inside its shadow DOM, pointed at Macro's
- * typography tokens so the diff matches surrounding font-mono text-xs UI.
- */
-const DIFF_STYLE_VARIABLES: JSX.CSSProperties = {
- '--diffs-font-family': 'var(--font-mono)',
- '--diffs-font-size': '0.75rem',
- '--diffs-line-height': '18px',
- '--diffs-tab-size': '2',
- '--diffs-gap-block': '0',
- '--diffs-min-number-column-width': '4ch',
-};
-
-function currentThemeType(): 'light' | 'dark' {
- return document.documentElement.dataset.themeLight === 'false'
- ? 'dark'
- : 'light';
-}
-
-/**
- * Macro's light/dark state as a signal, tracked off the
- * `data-theme-light` attribute the theme feature keeps on `<html>`.
- */
-function createThemeType(): () => 'light' | 'dark' {
- const [themeType, setThemeType] = createSignal(currentThemeType());
- const observer = new MutationObserver(() => setThemeType(currentThemeType()));
- observer.observe(document.documentElement, {
- attributes: true,
- attributeFilter: ['data-theme-light'],
- });
- onCleanup(() => observer.disconnect());
- return themeType;
-}
-
function lineCount(text: string): number {
if (text.length === 0) return 0;
return text.split('\n').length;
@@ -174,7 +144,7 @@ function PierreFileView(props: {
<div
ref={container}
class="overflow-hidden rounded border border-edge-muted"
- style={DIFF_STYLE_VARIABLES}
+ style={PIERRE_STYLE_VARIABLES}
/>
</Show>
);
diff --git a/apps/web/src/features/block-agent/ui/ToolGroup.tsx b/apps/web/src/features/block-agent/ui/ToolGroup.tsx
index 57f09750a4..a54170b33c 100644
--- a/apps/web/src/features/block-agent/ui/ToolGroup.tsx
+++ b/apps/web/src/features/block-agent/ui/ToolGroup.tsx
@@ -6,9 +6,9 @@
* because the cards themselves appear once it opens.
*/
-import { CollapseTransition } from '@app/components/view-shell/CollapseTransition';
import CaretRight from '@phosphor/caret-right.svg';
import { createResizeObserver } from '@solid-primitives/resize-observer';
+import { CollapseTransition } from '@ui/components/CollapseTransition';
import {
createEffect,
createSignal,
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRailSection.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRailSection.tsx
index 4497011c8d..0a34e97eea 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelsRailSection.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRailSection.tsx
@@ -2,13 +2,13 @@ import {
ViewSidebar,
CollapsibleSection as WorkspaceSection,
} from '@app/components/view-shell';
-import { CollapseTransition } from '@app/components/view-shell/CollapseTransition';
import { DebugSuspense } from '@channel/DebugSuspense';
import CaretDownIcon from '@phosphor/caret-down.svg';
import CaretUpIcon from '@phosphor/caret-up.svg';
import PlusIcon from '@phosphor/plus.svg';
import SpinnerIcon from '@phosphor/spinner.svg';
import { Button, cn, Scroll, Tooltip } from '@ui';
+import { CollapseTransition } from '@ui/components/CollapseTransition';
import {
createContext,
createSignal,
diff --git a/apps/web/src/lib/split-router/index.ts b/apps/web/src/lib/split-router/index.ts
index 68e5231f67..99ab45cf9f 100644
--- a/apps/web/src/lib/split-router/index.ts
+++ b/apps/web/src/lib/split-router/index.ts
@@ -60,6 +60,7 @@ export {
type SplitRouterScopeProps,
useCanGo,
useNavigate,
+ useOwnsSearchNamespace,
useParams,
useRouteParams,
useRouteState,
diff --git a/apps/web/src/lib/split-router/solid.tsx b/apps/web/src/lib/split-router/solid.tsx
index a572247653..8cf58e8a9c 100644
--- a/apps/web/src/lib/split-router/solid.tsx
+++ b/apps/web/src/lib/split-router/solid.tsx
@@ -14,6 +14,7 @@ import { Dynamic } from 'solid-js/web';
import { createSplitRouter } from './router';
import {
getRouteEntryState,
+ getRouteSearchNamespaces,
resolveRouteBranch,
routeParams,
type SplitRoutesManifest,
@@ -120,6 +121,23 @@ export function useSplitRouterScope<TSplitId>(): Accessor<TSplitId> {
return splitId as Accessor<TSplitId>;
}
+/**
+ * Whether the enclosing split's current route owns search `namespace`, so
+ * `createSearchParams` may write it. False outside a split.
+ */
+export function useOwnsSearchNamespace(namespace: string): Accessor<boolean> {
+ const context = useContext(SplitRouterContext);
+ const splitId = useContext(SplitRouterScopeContext);
+ if (!context || !splitId) return () => false;
+ return () => {
+ context.track(splitId());
+ const route = context.router.route(splitId());
+ if (!route) return false;
+ const owned = getRouteSearchNamespaces(context.router.routes, route);
+ return owned.has('*') || owned.has(namespace);
+ };
+}
+
export function useNavigate<TSplitId = unknown>(): SplitNavigate<TSplitId> {
const router = useSplitRouter<TSplitId>();
const splitId = useSplitRouterScope<TSplitId>();
diff --git a/apps/web/src/lib/split-router/tests/solid.test.tsx b/apps/web/src/lib/split-router/tests/solid.test.tsx
index 6012c7c945..09be2b67a6 100644
--- a/apps/web/src/lib/split-router/tests/solid.test.tsx
+++ b/apps/web/src/lib/split-router/tests/solid.test.tsx
@@ -19,6 +19,7 @@ import {
SplitRouter,
useCanGo,
useNavigate,
+ useOwnsSearchNamespace,
useParams,
useRouteParams,
useRouteState,
@@ -484,6 +485,30 @@ describe('Solid split router hooks', () => {
expect(navigate).not.toHaveBeenCalled();
});
+ it('reports which search namespaces the split route owns', () => {
+ const Harness = () => {
+ const drive = useOwnsSearchNamespace('drive');
+ const other = useOwnsSearchNamespace('other');
+ return <div>{`${drive()}:${other()}`}</div>;
+ };
+ const view = render(() => (
+ <SplitRouter.Root
+ layout={createLayout()}
+ routes={routes}
+ location={createMemorySplitRouterLocation('/drive/folder/one')}
+ >
+ <SplitRouter.Scope splitId="split">
+ <Harness />
+ </SplitRouter.Scope>
+ <span data-testid="outside">
+ {`${useOwnsSearchNamespace('drive')()}`}
+ </span>
+ </SplitRouter.Root>
+ ));
+ expect(view.getByText('true:false')).toBeTruthy();
+ expect(view.getByTestId('outside').textContent).toBe('false');
+ });
+
it.each(['invalid', 'updated_at'])(
'canonicalizes %s search with replacement rather than a new history entry',
async (sort) => {
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index e24fcfc2a6..7b799af048 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -672,19 +672,29 @@ toggle (`aria-pressed`) with green additions and red deletions (`+N −M`); it o
Chat sessions on Macro's in-memory harness have no repository, so they show
none of this: no **Changes** toggle, pane, hand-off card, or review-notes chip,
and the title menu offers **Open repository** only when the session has one.
-The URL's `diff` query parameter stores each session's pane state and diff
-layout (`session-id:split:unified`, or `changes-only` / `agent-only` and
-`split` for side-by-side diffs). Copying the URL preserves that view; reload
-and Back/Forward restore it. A plain session URL starts with Changes closed.
-Divider width, collapsed files, and review notes stay local.
-The pane header shows a `head → base` branch pill, a **Unified / Split**
-segmented control (`aria-label="Diff layout"`), a refresh button, the
-**View pull request** button (opens GitHub), and **Expand changes to the full width**
-(spotlight; **Bring the session back** returns to the split) and **Close the
-changes pane**. Below it is a **Collapse all / Expand all** button.
-The body is a file tree (`nav[aria-label="Changed files"]`, directories
-compressed along single-child chains, status letters A/M/D/R and +/− counts)
-next to a scrollable stack of file cards. Expanded cards keep their full height;
+The session's split stores the pane in its own search params:
+`s<N>.changes.pane` (`split`, or `full` when spotlit) and `s<N>.changes.style=split`
+for side-by-side diffs, where `<N>` is the split's index; defaults are left out.
+Copying the URL preserves that view, and reload restores it. Opening and closing
+the pane are Back/Forward steps; switching the diff layout is not. A plain
+session URL starts with Changes closed, and leaving the session or closing its
+split drops the state.
+Divider width, whether the file tree shows, collapsed files, and review notes
+stay local.
+The pane (`[role="region"][aria-label="Changes"]`) has a title row and a
+toolbar. The title row shows **Changes**, the linked pull request's number
+(**View pull request #N** opens GitHub), and the `head → base` range, with only
+the pane's own controls on the right: **Expand changes to the full width**
+(pressed while spotlit; its label becomes **Back to the split**) and **Close the
+changes pane**. The toolbar, shown once there are files, has **Hide file tree /
+Show file tree** and the file count on the left, and on the right the
+**Unified / Split** segmented control (`aria-label="Diff layout"`), **Collapse
+all / Expand all**, and **Refresh pull request changes**.
+The body is a file tree (`[role="group"][aria-label="Changed files"]`, rows
+styled like Drive's folder tree, directories compressed along single-child
+chains with **Collapse / Expand** buttons, each file's +/− counts and status
+letter A/M/D/R; the arrow keys move between rows and Left/Right close and open a
+directory) next to a scrollable stack of file cards. Expanded cards keep their full height;
**Collapse all / Expand all** hides or restores their bodies. Each card's header has a disclosure
caret, the path, `+adds −dels`, and **Copy path**. Diffs render with Pierre; hover a
line and click the accent **+** in the gutter (drag for a range) to leave a