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.

feat(ui): changes pane ui polish (#7470)

dev-rb2a9f5da006b1
diff --git a/apps/web/src/components/diff-view/DiffStats.tsx b/apps/web/src/components/diff-view/DiffStats.tsx
new file mode 100644
index 0000000000..fc515e1b3b
--- /dev/null
+++ b/apps/web/src/components/diff-view/DiffStats.tsx
@@ -0,0 +1,43 @@
+import { For } from 'solid-js';
+import { DiffCounts } from './DiffCounts';
+
+/** Line totals and five textured squares showing their relative proportions. */
+export function DiffStats(props: { additions: number; deletions: number }) {
+ const additionSquares = () => {
+ const total = props.additions + props.deletions;
+ if (total === 0) return 0;
+ if (props.deletions === 0) return 5;
+ if (props.additions === 0) return 0;
+ return Math.max(1, Math.min(4, Math.round((5 * props.additions) / total)));
+ };
+
+ return (
+ <span
+ role="img"
+ aria-label={`${props.additions} ${props.additions === 1 ? 'addition' : 'additions'}, ${props.deletions} ${props.deletions === 1 ? 'deletion' : 'deletions'}`}
+ class="inline-flex items-center gap-2"
+ >
+ <span aria-hidden="true">
+ <DiffCounts additions={props.additions} deletions={props.deletions} />
+ </span>
+ <span aria-hidden="true" class="inline-flex gap-0.5">
+ <For each={[0, 1, 2, 3, 4]}>
+ {(index) => (
+ <span
+ class="size-2.5 shrink-0 rounded-sm ring-1 ring-inset ring-ink/20 bg-[image:repeating-linear-gradient(135deg,transparent_0_2px,color-mix(in_oklch,var(--color-ink)_15%,transparent)_2px_3px)]"
+ classList={{
+ 'bg-edge-muted': props.additions + props.deletions === 0,
+ 'bg-success':
+ props.additions + props.deletions > 0 &&
+ index < additionSquares(),
+ 'bg-failure':
+ props.additions + props.deletions > 0 &&
+ index >= additionSquares(),
+ }}
+ />
+ )}
+ </For>
+ </span>
+ </span>
+ );
+}
diff --git a/apps/web/src/components/diff-view/DiffView.tsx b/apps/web/src/components/diff-view/DiffView.tsx
index 87bf7edf23..a5e4251a8c 100644
--- a/apps/web/src/components/diff-view/DiffView.tsx
+++ b/apps/web/src/components/diff-view/DiffView.tsx
@@ -6,9 +6,12 @@
* host puts them inside `Root`.
*/
+import { createRenderQueue } from '@app/lib/utils/create-render-queue';
import ArrowsInIcon from '@phosphor/arrows-in.svg';
import ArrowsOutIcon from '@phosphor/arrows-out.svg';
import CaretRightIcon from '@phosphor/caret-right.svg';
+import { createResizeObserver } from '@solid-primitives/resize-observer';
+import { debounce } from '@solid-primitives/scheduled';
import { Button, Card, cn, SegmentedControl } from '@ui';
import {
type Accessor,
@@ -20,6 +23,7 @@ import {
type JSX,
on,
onCleanup,
+ onMount,
type ParentProps,
Show,
useContext,
@@ -35,6 +39,7 @@ import { StatusLetter } from './StatusLetter';
type DiffViewContextValue = {
entries: Accessor<DiffEntry[]>;
+ ready: Accessor<boolean>;
diffStyle: Accessor<DiffStyle>;
themeType: Accessor<ThemeType>;
collapse: DiffCollapse;
@@ -68,10 +73,31 @@ function Root(
active?: string;
}>
) {
- const diffs = createMemo(() => parsePatch(props.patch));
- const entries = createMemo(() => matchFilesToDiffs(props.files, diffs()));
+ const queue = createRenderQueue();
+ // Hosts can invalidate their patch accessor without changing its text (for
+ // example, spotlighting the pane). Do not reparse or remount those diffs.
+ const patch = createMemo(() => props.patch);
+ const [parsed, setParsed] = createSignal<{
+ patch: string;
+ diffs: ReturnType<typeof parsePatch>;
+ }>();
+ // Parsing a cached patch must not block the click that opens the pane.
+ createEffect(
+ on(patch, (patch) => {
+ queue.enqueue('patch', () =>
+ setParsed({ patch, diffs: parsePatch(patch) })
+ );
+ })
+ );
+ const entries = createMemo(() => {
+ const current = parsed();
+ return current?.patch === patch()
+ ? matchFilesToDiffs(props.files, current.diffs)
+ : [];
+ });
const view: DiffViewContextValue = {
entries,
+ ready: () => parsed()?.patch === patch(),
diffStyle: () => props.diffStyle,
themeType: createThemeType(),
collapse:
@@ -131,19 +157,119 @@ function DiffNote(props: { children: JSX.Element }) {
/** Every file as its own card, each rendered by its own Pierre instance. */
function Stack(props: DiffListProps) {
const view = useDiffView();
+ const activePath = createMemo(view.active);
const cards = new Map<string, HTMLElement>();
const [flashing, setFlashing] = createSignal<string>();
+ const queue = createRenderQueue();
+ const [visible, setVisible] = createSignal<ReadonlySet<string>>(new Set());
+ let scroller!: HTMLDivElement;
+ let observer: IntersectionObserver | undefined;
+ let anchoredPath: string | undefined;
+ let pendingSelection = activePath();
+ let scrollingToAnchor = false;
+ let resizePending = false;
+ const alignAnchor = () => {
+ const card = anchoredPath ? cards.get(anchoredPath) : undefined;
+ if (!card?.isConnected) return;
+ const margin =
+ Number.parseFloat(getComputedStyle(card).scrollMarginTop) || 0;
+ const offset =
+ card.getBoundingClientRect().top -
+ scroller.getBoundingClientRect().top -
+ scroller.clientTop -
+ margin;
+ if (Math.abs(offset) > 1) {
+ card.scrollIntoView({ block: 'start', behavior: 'instant' });
+ }
+ };
+ // Wait for a quiet scroll interval so resize corrections do not interrupt
+ // the initial smooth jump. Scroll events extend the interval on every frame.
+ const settleAnchor = debounce(() => {
+ scrollingToAnchor = false;
+ if (resizePending) {
+ resizePending = false;
+ alignAnchor();
+ }
+ }, 120);
+ const releaseAnchor = () => {
+ anchoredPath = undefined;
+ pendingSelection = undefined;
+ scrollingToAnchor = false;
+ resizePending = false;
+ settleAnchor.clear();
+ };
+ onCleanup(() => settleAnchor.clear());
+ const clearFlash = debounce(() => setFlashing(undefined), FLASH_MS);
+ onCleanup(() => clearFlash.clear());
+
+ // Queued bodies and Pierre's later highlighting can resize cards above the
+ // selected file. Keep its header aligned until the user takes over scrolling.
+ if (typeof ResizeObserver !== 'undefined') {
+ createResizeObserver(
+ () => {
+ view.entries();
+ return [...cards.values()];
+ },
+ () => {
+ if (scrollingToAnchor) {
+ resizePending = true;
+ return;
+ }
+ alignAnchor();
+ }
+ );
+ }
+
+ const reveal = (path: string) => {
+ queue.enqueue(path, () => {
+ setVisible((paths) => new Set([...paths, path]));
+ });
+ };
+ onMount(() => {
+ // Older webviews still get queued rendering, without viewport gating.
+ if (typeof IntersectionObserver === 'undefined') {
+ for (const path of cards.keys()) reveal(path);
+ return;
+ }
+ observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ if (!entry.isIntersecting) continue;
+ const path = (entry.target as HTMLElement).dataset.path;
+ if (path) reveal(path);
+ observer?.unobserve(entry.target);
+ }
+ },
+ { root: scroller, rootMargin: '400px 0px' }
+ );
+ for (const card of cards.values()) observer.observe(card);
+ });
+ onCleanup(() => observer?.disconnect());
// 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' });
+ [activePath, view.entries],
+ ([path], previous) => {
+ if (path !== previous?.[0]) {
+ releaseAnchor();
+ clearFlash.clear();
+ setFlashing(undefined);
+ pendingSelection = path;
+ }
+ // Entry refreshes must not reselect an unchanged path after the user
+ // takes over scrolling. A pending selection still waits for its card.
+ if (!path || pendingSelection !== path) return;
+ reveal(path);
+ const card = cards.get(path);
+ if (!card) return;
+ pendingSelection = undefined;
+ anchoredPath = path;
+ scrollingToAnchor = true;
+ card.scrollIntoView({ block: 'start', behavior: 'smooth' });
+ settleAnchor();
setFlashing(path);
- const timer = setTimeout(() => setFlashing(undefined), FLASH_MS);
- onCleanup(() => clearTimeout(timer));
+ clearFlash();
},
{ defer: true }
)
@@ -153,11 +279,24 @@ function Stack(props: DiffListProps) {
// sticky headers, leaving a band above them where lines scroll into view.
return (
<div
+ ref={scroller}
class={cn(
'min-h-0 min-w-0 flex-1 overflow-y-auto scroll-smooth motion-reduce:scroll-auto',
props.class
)}
+ aria-busy={!view.ready()}
+ onWheel={releaseAnchor}
+ onPointerDown={releaseAnchor}
+ onKeyDown={releaseAnchor}
+ onScroll={() => {
+ if (scrollingToAnchor) settleAnchor();
+ }}
>
+ <Show when={!view.ready()}>
+ <div class="flex h-40 items-center justify-center text-xs text-ink-placeholder">
+ Loading the diff…
+ </div>
+ </Show>
<div class="flex min-w-0 flex-col gap-3 p-3 pb-24">
<For each={view.entries()}>
{(entry) => {
@@ -171,8 +310,15 @@ function Stack(props: DiffListProps) {
<FileContext.Provider value={entry}>
<Card
ref={(element: HTMLDivElement) => {
- cards.set(path(), element);
- onCleanup(() => cards.delete(path()));
+ const filePath = path();
+ cards.set(filePath, element);
+ if (observer) observer.observe(element);
+ else if (typeof IntersectionObserver === 'undefined')
+ reveal(filePath);
+ onCleanup(() => {
+ cards.delete(filePath);
+ observer?.unobserve(element);
+ });
}}
class={cn(
'shrink-0 scroll-mt-3 overflow-clip transition',
@@ -183,7 +329,7 @@ function Stack(props: DiffListProps) {
>
<header
class={cn(
- 'sticky top-0 z-5 flex h-10 items-center gap-1 bg-surface px-1.5',
+ 'sticky top-0 z-5 flex h-10 items-center gap-1 bg-surface px-1.5 transition-colors duration-150 hover:overlay-hover motion-reduce:transition-none',
!collapsed() && 'border-b border-edge-muted'
)}
>
@@ -191,25 +337,37 @@ function Stack(props: DiffListProps) {
</header>
<Show when={!collapsed()}>
<Show
- when={!entry.note}
- fallback={<DiffNote>{entry.note}</DiffNote>}
+ when={visible().has(path())}
+ fallback={
+ <div
+ class="flex h-40 items-center justify-center text-xs text-ink-placeholder"
+ aria-label={`Loading diff for ${path()}`}
+ >
+ Loading the diff…
+ </div>
+ }
>
- <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
+ 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>
</Show>
@@ -297,12 +455,13 @@ function FileCounts() {
}
/** Collapses every diff to its header, or opens them all again. */
-function CollapseAll() {
+function CollapseAll(props: { iconOnly?: boolean }) {
const { collapse } = useDiffView();
return (
<Button
variant="ghost"
- size="sm"
+ size={props.iconOnly ? 'icon-sm' : 'sm'}
+ label={collapse.anyExpanded() ? 'Collapse all' : 'Expand all'}
tooltip={
collapse.anyExpanded()
? 'Hide every diff, keeping just the file headers'
@@ -311,7 +470,9 @@ function CollapseAll() {
onClick={() => collapse.toggleAll()}
>
{collapse.anyExpanded() ? <ArrowsInIcon /> : <ArrowsOutIcon />}
- <span>{collapse.anyExpanded() ? 'Collapse all' : 'Expand all'}</span>
+ <Show when={!props.iconOnly}>
+ <span>{collapse.anyExpanded() ? 'Collapse all' : 'Expand all'}</span>
+ </Show>
</Button>
);
}
diff --git a/apps/web/src/components/diff-view/README.md b/apps/web/src/components/diff-view/README.md
index 45a7a70ff0..77ae02353e 100644
--- a/apps/web/src/components/diff-view/README.md
+++ b/apps/web/src/components/diff-view/README.md
@@ -5,10 +5,27 @@ 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.
+Patch parsing runs through the shared render queue after the pane shell mounts.
+Unchanged patch invalidations keep parsed entries and Pierre instances intact,
+including when a host switches between split and full-width layouts.
+`Stack` keeps lightweight file headers and defers expanded diff bodies until their
+cards approach the scroll viewport. The render queue yields between file bodies;
+selecting a file also schedules its body, even outside the viewport. Once a body
+loads, it stays mounted until collapsed or the stack closes.
+Selecting a file keeps its header aligned while queued diffs or asynchronous
+highlighting change earlier card heights. Wheel, pointer, and keyboard interaction
+release the anchor so manual scrolling and review-note editing remain unrestricted.
+Refreshing files or patch text does not reselect an unchanged active file after
+that release; an initial pending selection still waits for its file card.
+
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.
+`text-ink-subtle`), and `text-xs` counts. Both default and custom headers use
+an opaque `bg-surface` with `hover:overlay-hover`, so diff text never shows through
+the sticky row on hover. Hovering the header highlights the row but does not toggle
+it; only the disclosure and path controls toggle collapse. Toolbar parts use
+standard `Button` and `SegmentedControl` sizes, and backgrounds come from the
+card's depth.
The host composes the rest:
@@ -21,6 +38,10 @@ The host composes the rest:
- Toolbar parts, `DiffView.CollapseAll` and `DiffView.StyleToggle`, anywhere
inside `Root`.
- Collapse state that persists, by passing `collapse`; the default lives in memory.
+- `DiffCounts` for compact numeric totals, or `DiffStats` for those same totals
+ beside five green/red squares showing the addition/deletion proportion. A static
+ diagonal hatch and inset edge give the squares texture without changing their size.
+ Exact totals remain accessible without relying on color. Zero totals show neutral squares.
```tsx
<DiffView.Root files={files()} patch={patch()} diffStyle={style()} active={active()}>
diff --git a/apps/web/src/components/diff-view/index.ts b/apps/web/src/components/diff-view/index.ts
index 4e02434d2c..633847e2ea 100644
--- a/apps/web/src/components/diff-view/index.ts
+++ b/apps/web/src/components/diff-view/index.ts
@@ -2,6 +2,7 @@ export type { DiffCollapse } from './collapse';
export { CommentThread } from './comments/CommentThread';
export { createDiffComments } from './comments/create-diff-comments';
export { DiffCounts } from './DiffCounts';
+export { DiffStats } from './DiffStats';
export { DiffView } from './DiffView';
export type { DiffStyle } from './model/diff-file';
export { StatusLetter } from './StatusLetter';
diff --git a/apps/web/src/components/ui/components/CollapseTransition.docs.tsx b/apps/web/src/components/ui/components/CollapseTransition.docs.tsx
index 7c16b7a6cb..2bd12ae00a 100644
--- a/apps/web/src/components/ui/components/CollapseTransition.docs.tsx
+++ b/apps/web/src/components/ui/components/CollapseTransition.docs.tsx
@@ -34,7 +34,7 @@ export default defineDoc({
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.',
+ 'Animates a disclosure body open and closed along its height or width. Sidebar sections, tree branches, and tool groups share it. Externally sized panels can provide their resting size and companion animations for positioned neighbors.',
exports: ['CollapseTransition'],
import:
"import { CollapseTransition } from '@ui/components/CollapseTransition';",
diff --git a/apps/web/src/components/ui/components/CollapseTransition.tsx b/apps/web/src/components/ui/components/CollapseTransition.tsx
index e9e2cab67f..4fbb6ee33f 100644
--- a/apps/web/src/components/ui/components/CollapseTransition.tsx
+++ b/apps/web/src/components/ui/components/CollapseTransition.tsx
@@ -1,5 +1,12 @@
import { createResizeObserver } from '@solid-primitives/resize-observer';
-import { children, type JSX, onCleanup, onMount, Show } from 'solid-js';
+import {
+ children,
+ type JSX,
+ onCleanup,
+ onMount,
+ Show,
+ untrack,
+} from 'solid-js';
import { Transition } from 'solid-transition-group';
const COLLAPSE_DURATION = 140;
@@ -10,6 +17,18 @@ export type CollapseTransitionProps = {
container?: () => HTMLElement | undefined;
axis?: 'height' | 'width';
collapsedSize?: number;
+ /** Resting size when an external layout solver changes size before exit. */
+ expandedSize?: number;
+ /** Animate absolutely positioned neighbors with the same timing and cleanup. */
+ companions?: (transition: {
+ opening: boolean;
+ from: number;
+ interrupted: boolean;
+ }) => readonly { target: HTMLElement; keyframes: Keyframe[] }[];
+ /** Includes exit content that stays mounted until its animation finishes. */
+ onPresenceChange?: (present: boolean) => void;
+ /** Settle active motion synchronously before an external layout change. */
+ captureController?: (controller: { finish: () => void }) => void;
children: JSX.Element;
};
@@ -17,6 +36,8 @@ export type CollapseTransitionProps = {
* 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 Supply `expandedSize` when an external layout solver removes space immediately.
+ * @do Supply `companions` when absolutely positioned neighbors need matching motion.
* @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.
@@ -48,6 +69,7 @@ export function CollapseTransition(props: CollapseTransitionProps) {
const sizeOf = (element: HTMLElement) =>
element.getBoundingClientRect()[axis()];
let measuredSize: number | undefined;
+ let disposed = false;
let running:
| { target: HTMLElement; content: HTMLElement; finish: () => void }
| undefined;
@@ -56,14 +78,21 @@ export function CollapseTransition(props: CollapseTransitionProps) {
if (!running) measuredSize = sizeOf(element);
});
onMount(() => {
+ props.captureController?.({ finish: () => running?.finish() });
const element = container();
+ props.onPresenceChange?.(props.open);
if (element) measuredSize = sizeOf(element);
});
- onCleanup(() => running?.finish());
+ onCleanup(() => {
+ disposed = true;
+ running?.finish();
+ });
function animate(element: Element, opening: boolean, done: () => void) {
- if (!(element instanceof HTMLElement)) return done();
+ if (disposed || !(element instanceof HTMLElement) || opening !== props.open)
+ return done();
+ props.onPresenceChange?.(true);
const target = props.container?.() ?? element;
const collapsedSize = props.collapsedSize ?? 0;
const fromOpacity = running
@@ -75,9 +104,13 @@ export function CollapseTransition(props: CollapseTransitionProps) {
? sizeOf(running.target)
: opening
? collapsedSize
- : (measuredSize ?? sizeOf(target));
+ : (props.expandedSize ?? measuredSize ?? sizeOf(target));
+ // Capture neighbors before releasing an interrupted animation's styles.
+ const companions = untrack(() =>
+ props.companions?.({ opening, from, interrupted: running !== undefined })
+ );
running?.finish();
- const to = opening ? sizeOf(target) : collapsedSize;
+ const to = opening ? (props.expandedSize ?? sizeOf(target)) : collapsedSize;
const style = getComputedStyle(target);
const {
min,
@@ -93,6 +126,7 @@ export function CollapseTransition(props: CollapseTransitionProps) {
typeof target.animate !== 'function' ||
window.matchMedia('(prefers-reduced-motion: reduce)').matches
) {
+ props.onPresenceChange?.(opening || props.open);
done();
return;
}
@@ -134,13 +168,18 @@ export function CollapseTransition(props: CollapseTransitionProps) {
[{ opacity: fromOpacity }, { opacity: opening ? 1 : 0 }],
options
);
+ const companionAnimations = companions?.map(({ target, keyframes }) =>
+ target.animate(keyframes, options)
+ );
const finish = () => {
if (running?.finish !== finish) return;
running = undefined;
measuredSize = to;
+ props.onPresenceChange?.(opening || props.open);
done();
size.cancel();
opacity.cancel();
+ companionAnimations?.forEach((animation) => animation.cancel());
};
running = { target, content: element, finish };
size.onfinish = finish;
diff --git a/apps/web/src/features/agent-changes/README.md b/apps/web/src/features/agent-changes/README.md
index 17e2e0aa91..b0a442e60f 100644
--- a/apps/web/src/features/agent-changes/README.md
+++ b/apps/web/src/features/agent-changes/README.md
@@ -18,8 +18,72 @@ 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.
+path** with a brief, non-pulsing success checkmark for the latest copy request,
+and review notes hang under their lines through `DiffView.Stack`'s annotation slot.
+The file tree fills the body height, with its count on the left and the tree
+visibility toggle on the right of a fixed header. Tree rows scroll independently below it.
+The tree divider supports dragging and Left/Right keyboard resizing; its preferred
+pixel width persists per host scope. Tree visibility uses the sidebar's shared
+`CollapseTransition` on the width axis, with matching diff-column motion and
+reduced-motion support. The divider stays visible but inert through exit, releasing
+its layout space with the tree only when the animation finishes. Hiding retains
+directory state and the diff stack. Starting a drag or keyboard resize, or resizing
+the outer split or viewport, settles the visibility animation synchronously first.
+At 720px or narrower, and on touch devices, the tree starts closed and opens over
+the diff stack as a pane-local drawer, without reserving space or a divider.
+**Show file tree** stays in the diff controls; file selection, Escape, the backdrop,
+and the close toggle dismiss the drawer and restore focus to its opener.
+Closing retains only an inert visual frame; dialog listeners release immediately.
+Drawer state never changes saved wide-tree visibility or width. Directory and diff
+owners survive responsive mode changes. The all-diffs collapse/expand button stays
+in the floating diff controls; a hidden or drawer tree puts its count there too.
+Another host composes the same components its own way.
+
+Native PR and Agents workspace hosts put their title row and content together
+inside `AgentChangesSplit`, so changes occupy the full height beside that row.
+Host title, sharing, and sidebar actions remain available on the left. The Changes
+button stays visible in split view: ghost while closed, accent text on a tinted
+background while open, without the shared foreground pressed overlay; clicking
+it again closes the pane. Below 28rem of the
+header's named `split-header` container, only Changes becomes icon-only, retaining
+its accessible name, tooltip, pressed state, and touch target. Breadcrumbs keep
+their existing layout. The button has no diff totals; those appear beside the
+pane's branch range and PR number in both split and full-width layouts. On a PR
+detail, the diff count pill also opens the pane when a controller is available;
+otherwise it remains a passive count. The pane slides in from the right edge on
+open and completely off that edge on close, without fading in either direction.
+In split view, the session shrinks alongside entry and expands alongside exit.
+Reduced-motion preferences disable both animations.
+Its resize panel stays registered until the exit animation completes; reopening
+cancels exit without remounting the pane. Patch parsing and diff bodies are queued
+after the pane shell mounts, and off-screen bodies wait until needed.
+Split/full toggles retain the host and diff owners and restore the dragged split
+ratio without replaying the visibility slide or reparsing unchanged patch text.
+Hosts at 720px or narrower open Changes at full width and hide the width toggle,
+without changing the saved split ratio or route layout. Widening restores the
+requested wide layout and keeps the same conversation and diff owners.
+A spotlight request during a slide applies after the slide settles. A full-width
+slide reveals the retained host behind it rather than leaving empty space; a
+reversal keeps that underlay until the pane finishes returning.
+`ChangesPane` keeps pane actions beside the linked `head → base · #PR` metadata
+in its header, without a visible Changes title. Diff controls float above the
+stack inside the diff column, with Unified/Split on the left and collapse/refresh
+on the right, without a full-pane toolbar or bottom border. The pane has no outer
+top, right, or bottom border; the resize divider separates it from the host.
+The metadata opens GitHub; narrow panes truncate the branch range. Unified/Split
+retains its text labels at every non-touch width. The shared `DiffStats` shows
+exact totals beside five subtly hatched green/red squares with inset edges,
+summarizing the addition/deletion mix without animation.
+At full width, the header adds a `text-sm` PR title with extra top padding before
+the plain-text `text-xs` branch link, which underlines on hover.
+When title and metadata do not fit together, the smaller branch/number/count group
+wraps below the title; pane actions stay outside that wrapping group. Native PR
+and session hosts supply titles and GitHub totals from existing queries; no extra PR fetch is needed.
+Missing titles stay hidden, and unavailable GitHub totals never fall back to
+captured estimates.
+Legacy embedded agent hosts still render their frame-owned chrome above both
+panes. Moving `AgentSplitHeader` does not change that portal placement; full-height
+embedded changes require a separate host-layout migration.
The source owns fetching, cache identity, and conversion into the feature's core
changeset types. The PR page's adapter is `block-pr/data/pr-changes.ts`, over
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 d380561c21..587f1a3749 100644
--- a/apps/web/src/features/agent-changes/agent-changes.test.tsx
+++ b/apps/web/src/features/agent-changes/agent-changes.test.tsx
@@ -1,18 +1,24 @@
import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';
import { render, screen } from '@solidjs/testing-library';
import { createSignal } from 'solid-js';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
AgentChangesProvider,
ChangesHandoff,
ChangesToggle,
} from './agent-changes';
+import { useAgentChanges } from './context/agent-changes-controller';
import {
createMockAgentChangesContext,
mockChangeset,
} from './tests/mock-context';
const [session, setSession] = createSignal<AgentSessionResponse>();
+const [stats, setStats] = createSignal<{
+ title?: string;
+ counts?: { additions: number; deletions: number };
+}>();
+beforeEach(() => setStats(undefined));
/** Every session id the changes source was asked to read, in order. */
const sourceSessionIds: Array<string | undefined> = [];
@@ -42,7 +48,7 @@ vi.mock('./queries/session-changes', () => ({
}));
vi.mock('./queries/pull-request-stats', () => ({
- createPullRequestStatsSource: () => () => undefined,
+ createPullRequestStatsSource: () => stats,
}));
vi.mock('@core/component/Toast/Toast', () => ({
@@ -57,7 +63,44 @@ function sessionWith(fields: {
return fields as unknown as AgentSessionResponse;
}
+function ChangesHostMetadata() {
+ const { context, changeCounts } = useAgentChanges();
+ return (
+ <>
+ <span aria-label="PR title">{context.host.pullRequestTitle?.()}</span>
+ <span aria-label="PR additions">{changeCounts()?.additions}</span>
+ </>
+ );
+}
describe('AgentChangesProvider', () => {
+ it('shares the existing PR query title and counts through host capabilities', () => {
+ setSession(
+ sessionWith({
+ harness: 'cursor',
+ pullRequestUrl: 'https://github.com/macro-inc/macro/pull/42',
+ })
+ );
+ setStats({
+ title: 'Linked PR title',
+ counts: { additions: 8, deletions: 2 },
+ });
+ render(() => (
+ <AgentChangesProvider>
+ <ChangesHostMetadata />
+ </AgentChangesProvider>
+ ));
+ expect(screen.getByLabelText('PR title').textContent).toBe(
+ 'Linked PR title'
+ );
+ expect(screen.getByLabelText('PR additions').textContent).toBe('8');
+ setStats({ title: 'Updated PR title' });
+ expect(screen.getByLabelText('PR title').textContent).toBe(
+ 'Updated PR title'
+ );
+ expect(screen.getByLabelText('PR additions').textContent).toBe('');
+ setStats(undefined);
+ expect(screen.getByLabelText('PR title').textContent).toBe('');
+ });
it('hides the Changes controls until the coding session links a pull request', () => {
setSession(sessionWith({ harness: 'cursor', pullRequestUrl: null }));
sourceSessionIds.length = 0;
diff --git a/apps/web/src/features/agent-changes/agent-changes.tsx b/apps/web/src/features/agent-changes/agent-changes.tsx
index 9054f8a080..454395aff9 100644
--- a/apps/web/src/features/agent-changes/agent-changes.tsx
+++ b/apps/web/src/features/agent-changes/agent-changes.tsx
@@ -58,12 +58,13 @@ export function AgentChangesProvider(props: ParentProps) {
toast.failure('The review notes could not be sent');
}
};
- const pullRequestChangeCounts = createPullRequestStatsSource(
+ const pullRequestStats = createPullRequestStatsSource(
() => (coding() && session.userId() ? pullRequestUrl() : undefined),
() => source.summary()?.changeset?.id
);
const host: ChangesHost = {
- pullRequestChangeCounts,
+ pullRequestChangeCounts: () => pullRequestStats()?.counts,
+ pullRequestTitle: () => pullRequestStats()?.title,
scopeKey: session.sessionId,
agent: {
send: (markdown) => void sendPrompt(markdown),
diff --git a/apps/web/src/features/agent-changes/components/ChangesHeader.tsx b/apps/web/src/features/agent-changes/components/ChangesHeader.tsx
index 0482a7cbaf..b21a416b4f 100644
--- a/apps/web/src/features/agent-changes/components/ChangesHeader.tsx
+++ b/apps/web/src/features/agent-changes/components/ChangesHeader.tsx
@@ -1,28 +1,26 @@
+import { DiffStats } from '@app/components/diff-view';
import ArrowLeftIcon from '@phosphor/arrow-left.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 } from '@ui';
import { Show } from 'solid-js';
import { pullRequestNumber } from '../core/pull-request';
-/**
- * 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.
- */
+/** Linked PR metadata and totals, expanded-pane title, and pane actions. */
export function ChangesHeader(props: {
mobile?: boolean;
/** The pane fills the width; the session is off screen. */
spotlit: boolean;
/** `head → base`, when known. */
range: string | undefined;
- /** The linked pull request, opened from its number. */
+ /** The linked pull request, opened from the branch range and number. */
pullRequestUrl: string | undefined;
+ pullRequestTitle?: string;
+ changeCounts?: { additions: number; deletions: number };
onViewPullRequest: () => void;
- onSpotlight: () => void;
+ onSpotlight?: () => void;
onClose: () => void;
}) {
const number = () => {
@@ -41,47 +39,103 @@ export function ChangesHeader(props: {
<ArrowLeftIcon />
</Button>
</Show>
- <h2 class="shrink-0 px-1 text-sm font-semibold text-ink">Changes</h2>
- <Show when={props.pullRequestUrl}>
- <Button
- variant="ghost"
- size="sm"
- class="shrink-0"
- label={
- number() ? `View pull request #${number()}` : 'View pull request'
- }
- onClick={() => props.onViewPullRequest()}
- >
- <GitPullRequestIcon />
- <span>{number() ? `#${number()}` : 'Pull request'}</span>
- </Button>
- </Show>
- <Show when={props.range}>
- {(range) => (
- <span
- class="flex min-w-0 items-center gap-1 text-xs text-ink-subtle max-md:hidden"
- title={range()}
+ <div class="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-0.5">
+ <Show when={props.spotlit && props.pullRequestTitle}>
+ {(title) => (
+ <span
+ class="min-w-0 max-w-full truncate pt-1 text-sm font-medium text-ink"
+ title={title()}
+ >
+ {title()}
+ </span>
+ )}
+ </Show>
+ <div class="flex min-w-0 max-w-full flex-nowrap items-center gap-1 text-xs leading-4">
+ <Show
+ when={props.pullRequestUrl}
+ fallback={
+ <Show when={props.range}>
+ {(range) => (
+ <span
+ class="flex min-w-0 items-center gap-1 text-ink-subtle"
+ title={range()}
+ >
+ <GitBranchIcon class="size-3.5 shrink-0" />
+ <span class="truncate">{range()}</span>
+ </span>
+ )}
+ </Show>
+ }
>
- <GitBranchIcon class="size-3.5 shrink-0" />
- <span class="truncate">{range()}</span>
- </span>
- )}
- </Show>
- <span class="flex-1" />
+ {(url) => (
+ <a
+ href={url()}
+ target="_blank"
+ rel="noopener noreferrer"
+ class="inline-flex min-w-0 items-center gap-1 text-ink-subtle underline-offset-2 hover:text-ink hover:underline focus-visible:outline-2 focus-visible:outline-accent"
+ aria-label={
+ number()
+ ? `View pull request #${number()}`
+ : 'View pull request'
+ }
+ title={props.range}
+ onClick={(event) => {
+ if (
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey
+ )
+ return;
+ event.preventDefault();
+ props.onViewPullRequest();
+ }}
+ >
+ <Show when={props.range}>
+ {(range) => (
+ <>
+ <span class="truncate">{range()}</span>
+ <span aria-hidden="true" class="shrink-0">
+ ·
+ </span>
+ </>
+ )}
+ </Show>
+ <span class="shrink-0">
+ {number() ? `#${number()}` : 'Pull request'}
+ </span>
+ </a>
+ )}
+ </Show>
+ <Show when={props.changeCounts}>
+ {(counts) => (
+ <span class="shrink-0 px-1" aria-label="Pull request diff counts">
+ <DiffStats
+ additions={counts().additions}
+ deletions={counts().deletions}
+ />
+ </span>
+ )}
+ </Show>
+ </div>
+ </div>
<Show when={!props.mobile}>
- <Button
- variant="ghost"
- size="icon-sm"
- aria-pressed={props.spotlit}
- label={
- props.spotlit
- ? 'Back to the split'
- : 'Expand changes to the full width'
- }
- onClick={() => props.onSpotlight()}
- >
- {props.spotlit ? <ArrowsInSimpleIcon /> : <ArrowsOutSimpleIcon />}
- </Button>
+ <Show when={props.onSpotlight}>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-pressed={props.spotlit}
+ label={
+ props.spotlit
+ ? 'Back to the split'
+ : 'Expand changes to the full width'
+ }
+ onClick={() => props.onSpotlight?.()}
+ >
+ {props.spotlit ? <ArrowsInSimpleIcon /> : <ArrowsOutSimpleIcon />}
+ </Button>
+ </Show>
<Button
variant="ghost"
size="icon-sm"
diff --git a/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx b/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx
index b7c71c7d47..384c37a8c8 100644
--- a/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx
+++ b/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx
@@ -1,34 +1,25 @@
-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 { Button } from '@ui';
-/** Opens the changes pane and summarizes its added/deleted lines. */
+/** Toggles the changes pane; totals live beside the pane's branch range. */
export function ChangesToggleButton(props: {
open: boolean;
- additions: number;
- deletions: number;
- /** A capture is running, so the counts may move. */
- capturing?: boolean;
onToggle: () => void;
}) {
return (
<Button
- variant="outline"
+ variant={props.open ? 'accent' : 'ghost'}
size="sm"
+ label="Changes"
aria-pressed={props.open}
tooltip={props.open ? 'Hide the changes pane' : 'Show the changes pane'}
// Sits beside the `h-7` pull request chip; the `sm` frame is 4px shorter.
- class={cn('h-7 gap-1.5', props.open && 'bg-active text-ink')}
+ // Preserve pressed semantics without stacking a foreground overlay on the tint.
+ class="h-7 gap-1.5 aria-pressed:[--color-active:transparent] @max-[28rem]/split-header:w-7 @max-[28rem]/split-header:gap-0 @max-[28rem]/split-header:px-0"
onClick={() => props.onToggle()}
>
<SquareSplitHorizontalIcon class="size-3.5" />
- <span>Changes</span>
- <Show when={props.additions > 0 || props.deletions > 0}>
- <span class={cn('text-xs', props.capturing && 'animate-pulse')}>
- <DiffCounts additions={props.additions} deletions={props.deletions} />
- </span>
- </Show>
+ <span class="@max-[28rem]/split-header:hidden">Changes</span>
</Button>
);
}
diff --git a/apps/web/src/features/agent-changes/components/CopyFilePathButton.tsx b/apps/web/src/features/agent-changes/components/CopyFilePathButton.tsx
new file mode 100644
index 0000000000..3f5601310b
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/CopyFilePathButton.tsx
@@ -0,0 +1,51 @@
+import CheckIcon from '@phosphor/check.svg';
+import CopyIcon from '@phosphor/copy.svg';
+import { Button } from '@ui';
+import { createSignal, onCleanup, Show } from 'solid-js';
+
+const FEEDBACK_MS = 1800;
+
+/** Keeps clipboard feedback local to the file whose path was copied. */
+export function CopyFilePathButton(props: {
+ path: string;
+ onCopy: (path: string) => Promise<boolean>;
+}) {
+ const [copied, setCopied] = createSignal(false);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let disposed = false;
+ let request = 0;
+ onCleanup(() => {
+ disposed = true;
+ clearTimeout(timer);
+ });
+
+ const copy = async () => {
+ const current = ++request;
+ clearTimeout(timer);
+ setCopied(false);
+ const success = await props.onCopy(props.path);
+ if (disposed || current !== request) return;
+ setCopied(success);
+ if (success) timer = setTimeout(() => setCopied(false), FEEDBACK_MS);
+ };
+
+ return (
+ <>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ tooltip="Copy path"
+ aria-label="Copy path"
+ class="motion-safe:transition-transform motion-safe:duration-150 motion-safe:active:scale-95"
+ onClick={() => void copy()}
+ >
+ <Show when={copied()} fallback={<CopyIcon />}>
+ <CheckIcon class="text-success" />
+ </Show>
+ </Button>
+ <span class="sr-only" aria-live="polite">
+ {copied() ? 'Path copied' : ''}
+ </span>
+ </>
+ );
+}
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 8bff738647..cf0db758f9 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
@@ -61,6 +61,8 @@ export type ChangesHost = {
pullRequestChangeCounts?: Accessor<
{ additions: number; deletions: number } | undefined
>;
+ /** The PR title from the host's existing query, when known. */
+ pullRequestTitle?: Accessor<string | undefined>;
/** The pull request represented by the source. */
pullRequestUrl: Accessor<string | undefined>;
openExternal: (url: string) => void;
diff --git a/apps/web/src/features/agent-changes/core/layout.ts b/apps/web/src/features/agent-changes/core/layout.ts
index 9bdb3c54c5..1e5c9b6f4e 100644
--- a/apps/web/src/features/agent-changes/core/layout.ts
+++ b/apps/web/src/features/agent-changes/core/layout.ts
@@ -17,6 +17,9 @@ export const DEFAULT_CHANGES_SHARE = 58;
export const MIN_CHANGES_SHARE = 22;
export const MAX_CHANGES_SHARE = 74;
+/** Minimum room for the conversation and Changes pane side by side. */
+export const CHANGES_NARROW_WIDTH = 720;
+
export function isChangesVisible(layout: PaneLayout): boolean {
return layout !== 'closed';
}
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 4b6883191f..228e0ac4b9 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
@@ -44,7 +44,7 @@ export type AgentChangesController = {
/** The handoff card was dismissed for the changeset on screen. */
handoffDismissed: Accessor<boolean>;
dismissHandoff: () => void;
- copyPath: (path: string) => void;
+ copyPath: (path: string) => Promise<boolean>;
};
export function createAgentChanges(options: {
@@ -87,6 +87,7 @@ export function createAgentChanges(options: {
copied ? 'Path copied' : 'The path could not be copied',
copied ? 'success' : 'failure'
);
+ return copied;
};
const consumeSendableNotes = () => {
@@ -126,6 +127,6 @@ export function createAgentChanges(options: {
return id !== undefined && dismissed() === id;
},
dismissHandoff: () => setDismissed(model.changeset()?.id),
- copyPath: (path) => void copyPath(path),
+ copyPath,
};
}
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 929c5d8019..612711d8c1 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
@@ -76,6 +76,7 @@ function setup() {
setPatchStatus,
setVisible,
refreshes: () => refreshes,
+ enabledReads,
};
}
@@ -101,6 +102,33 @@ describe('createChangesModel', () => {
dispose();
});
+ it('retains displayed patch text on close without further reads and clears it for another changeset', () => {
+ const {
+ model,
+ setSummary,
+ setPatchText,
+ setVisible,
+ enabledReads,
+ dispose,
+ } = createRoot((dispose) => ({ ...setup(), dispose }));
+ setSummary(summaryWith(['a.ts']));
+ setVisible(true);
+ setPatchText(PATCH);
+ expect(model.patch()).toBe(PATCH);
+ const reads = enabledReads.length;
+ setVisible(false);
+ expect(model.patch()).toBe(PATCH);
+ setPatchText('next patch');
+ expect(model.patch()).toBe(PATCH);
+ expect(enabledReads).toHaveLength(reads);
+ const next = summaryWith(['b.ts']);
+ next.changeset!.id = 'cs-next';
+ setSummary(next);
+ expect(model.patch()).toBeUndefined();
+ setVisible(true);
+ expect(model.patch()).toBe('next patch');
+ dispose();
+ });
it('does not wait for a patch that has no bytes', () => {
createRoot((dispose) => {
const { model, setSummary, setVisible } = setup();
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 1164768b64..f93c60dfdb 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
@@ -68,6 +68,20 @@ export function createChangesModel(options: {
() => changeset()?.id,
() => options.changesVisible() && hasPatch()
);
+ // Keep the last displayed patch during exit without reading or fetching it
+ // while closed. A new changeset drops the retained text, even while closed.
+ const displayedPatch = createMemo<{
+ id: string | undefined;
+ text: string | undefined;
+ }>((previous) => {
+ const id = changeset()?.id;
+ if (!options.changesVisible()) {
+ return previous && previous.id === id
+ ? previous
+ : { id, text: undefined };
+ }
+ return { id, text: patch.text() };
+ });
const [refreshing, setRefreshing] = createSignal(false);
const [refreshError, setRefreshError] = createSignal<string>();
@@ -88,7 +102,7 @@ export function createChangesModel(options: {
state,
changeset,
files,
- patch: () => (hasPatch() ? patch.text() : ''),
+ patch: () => (hasPatch() ? displayedPatch().text : ''),
patchStatus: patch.status,
retryPatch: patch.retry,
refresh,
diff --git a/apps/web/src/features/agent-changes/primitives/create-changes-narrow.ts b/apps/web/src/features/agent-changes/primitives/create-changes-narrow.ts
new file mode 100644
index 0000000000..bb503c9994
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-changes-narrow.ts
@@ -0,0 +1,17 @@
+import { createSizeBreakpoints } from '@app/util/create-size-breakpoints';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { createElementSize } from '@solid-primitives/resize-observer';
+import type { Accessor } from 'solid-js';
+import { CHANGES_NARROW_WIDTH } from '../core/layout';
+
+/** Respond to the host's width, not the browser viewport. */
+export function createChangesNarrow(
+ element: Accessor<HTMLElement | undefined>
+): Accessor<boolean> {
+ const size = createElementSize(element);
+ const breakpoints = createSizeBreakpoints(
+ () => (size.width != null && size.width > 0 ? size.width : undefined),
+ { narrow: CHANGES_NARROW_WIDTH }
+ );
+ return () => isTouchDevice() || breakpoints.narrow();
+}
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 3311954c73..af8e84d1c0 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
@@ -16,6 +16,15 @@ import {
} from '../core/layout';
import { createPersistedSessionState } from './create-persisted-session-state';
+export const DEFAULT_TREE_WIDTH = 256;
+export const MIN_TREE_WIDTH = 144;
+export const MAX_TREE_WIDTH = 480;
+
+function clampTreeWidth(width: number): number {
+ return Number.isFinite(width)
+ ? Math.min(MAX_TREE_WIDTH, Math.max(MIN_TREE_WIDTH, width))
+ : DEFAULT_TREE_WIDTH;
+}
export type PaneLayoutController = {
layout: Accessor<PaneLayout>;
changesVisible: Accessor<boolean>;
@@ -26,23 +35,34 @@ export type PaneLayoutController = {
/** The file tree shows beside the diffs. */
treeOpen: Accessor<boolean>;
toggleTree: () => void;
+ /** Preferred width in pixels of the file tree. */
+ treeWidth: Accessor<number>;
+ setTreeWidth: (width: number) => void;
toggle: () => void;
spotlight: () => void;
open: () => void;
close: () => void;
};
-type StoredLayout = { share: number; treeOpen: boolean };
+type StoredLayout = { share: number; treeOpen: boolean; treeWidth: number };
function parseLayout(raw: unknown): StoredLayout | undefined {
if (typeof raw !== 'object' || raw === null) return undefined;
- const { share, treeOpen } = raw as { share?: unknown; treeOpen?: unknown };
+ const { share, treeOpen, treeWidth } = raw as {
+ share?: unknown;
+ treeOpen?: unknown;
+ treeWidth?: unknown;
+ };
return {
share:
typeof share === 'number'
? clampChangesShare(share)
: DEFAULT_CHANGES_SHARE,
treeOpen: typeof treeOpen === 'boolean' ? treeOpen : true,
+ treeWidth:
+ typeof treeWidth === 'number'
+ ? clampTreeWidth(treeWidth)
+ : DEFAULT_TREE_WIDTH,
};
}
@@ -55,7 +75,11 @@ export function createPaneLayout(options: {
const [stored, setStored] = createPersistedSessionState<StoredLayout>({
sessionId: options.sessionId,
namespace: 'agent-changes:layout',
- initial: () => ({ share: DEFAULT_CHANGES_SHARE, treeOpen: true }),
+ initial: () => ({
+ share: DEFAULT_CHANGES_SHARE,
+ treeOpen: true,
+ treeWidth: DEFAULT_TREE_WIDTH,
+ }),
parse: parseLayout,
storage: options.storage,
});
@@ -75,6 +99,12 @@ export function createPaneLayout(options: {
treeOpen: () => stored().treeOpen,
toggleTree: () =>
setStored((previous) => ({ ...previous, treeOpen: !previous.treeOpen })),
+ treeWidth: () => stored().treeWidth,
+ setTreeWidth: (width) =>
+ setStored((previous) => ({
+ ...previous,
+ treeWidth: clampTreeWidth(width),
+ })),
toggle: () => move(toggleChanges),
spotlight: () => move(toggleSpotlight),
open: () => move(ensureChangesVisible),
diff --git a/apps/web/src/features/agent-changes/queries/pull-request-stats.test.ts b/apps/web/src/features/agent-changes/queries/pull-request-stats.test.ts
index d757fc100a..bc57f6f943 100644
--- a/apps/web/src/features/agent-changes/queries/pull-request-stats.test.ts
+++ b/apps/web/src/features/agent-changes/queries/pull-request-stats.test.ts
@@ -22,10 +22,14 @@ beforeEach(() => vi.clearAllMocks());
describe('GitHub PR statistics', () => {
it('requests the linked PR and returns GitHub totals unchanged', async () => {
enrich.mockResolvedValue(
- ok({ pullRequests: [{ ...reference, additions: 728, deletions: 193 }] })
+ ok({
+ pullRequests: [
+ { ...reference, name: 'PR title', additions: 728, deletions: 193 },
+ ],
+ })
);
expect(await pullRequestStatsQueryOptions(reference.url).queryFn()).toEqual(
- { additions: 728, deletions: 193 }
+ { title: 'PR title', counts: { additions: 728, deletions: 193 } }
);
expect(enrich).toHaveBeenCalledWith({ pullRequests: [reference] });
});
@@ -35,15 +39,15 @@ describe('GitHub PR statistics', () => {
ok({ pullRequests: [{ ...reference, additions: 0, deletions: 0 }] })
);
expect(await pullRequestStatsQueryOptions(reference.url).queryFn()).toEqual(
- { additions: 0, deletions: 0 }
+ { title: undefined, counts: { additions: 0, deletions: 0 } }
);
});
it('treats missing enrichment as unavailable rather than zero', async () => {
enrich.mockResolvedValue(ok({ pullRequests: [reference] }));
- expect(
- await pullRequestStatsQueryOptions(reference.url).queryFn()
- ).toBeNull();
+ expect(await pullRequestStatsQueryOptions(reference.url).queryFn()).toEqual(
+ { title: undefined, counts: undefined }
+ );
});
it('does not substitute another PR or partial counts', async () => {
@@ -65,11 +69,23 @@ describe('GitHub PR statistics', () => {
enrich.mockResolvedValue(
ok({ pullRequests: [{ ...reference, additions: 8, deletions: null }] })
);
- expect(
- await pullRequestStatsQueryOptions(reference.url).queryFn()
- ).toBeNull();
+ expect(await pullRequestStatsQueryOptions(reference.url).queryFn()).toEqual(
+ { title: undefined, counts: undefined }
+ );
});
+ it('preserves the PR title when GitHub totals are unavailable', async () => {
+ enrich.mockResolvedValue(
+ ok({ pullRequests: [{ ...reference, name: 'PR title' }] })
+ );
+ expect(await pullRequestStatsQueryOptions(reference.url).queryFn()).toEqual(
+ {
+ title: 'PR title',
+ counts: undefined,
+ }
+ );
+ expect(enrich).toHaveBeenCalledTimes(1);
+ });
it('does not request statistics without a PR', async () => {
for (const url of [undefined, 'not a PR']) {
const query = pullRequestStatsQueryOptions(url);
diff --git a/apps/web/src/features/agent-changes/queries/pull-request-stats.ts b/apps/web/src/features/agent-changes/queries/pull-request-stats.ts
index 9c113e76c7..7a60d95b93 100644
--- a/apps/web/src/features/agent-changes/queries/pull-request-stats.ts
+++ b/apps/web/src/features/agent-changes/queries/pull-request-stats.ts
@@ -36,9 +36,15 @@ export function pullRequestStatsQueryOptions(
})
);
const pr = response.pullRequests.find((pr) => pr.githubKey === githubKey);
- // Enrichment can return a bare reference when GitHub is unavailable.
- if (pr?.additions == null || pr.deletions == null) return null;
- return { additions: pr.additions, deletions: pr.deletions };
+ if (!pr) return null;
+ // A title can be known even when GitHub totals are unavailable.
+ return {
+ title: pr.name ?? undefined,
+ counts:
+ pr.additions != null && pr.deletions != null
+ ? { additions: pr.additions, deletions: pr.deletions }
+ : undefined,
+ };
},
staleTime: 30_000,
refetchInterval: 30_000,
diff --git a/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx b/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx
index 11cbb1e131..4a2443b9be 100644
--- a/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx
+++ b/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx
@@ -9,81 +9,300 @@ import { FloatRegions } from '@components/app/mobile/float-regions/float-region-
import { Resize } from '@core/component/Resize';
import type { ResizeZoneCtx } from '@core/component/Resize/types';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import { type ParentProps, Show } from 'solid-js';
+import { createMediaQuery } from '@solid-primitives/media';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onCleanup,
+ type ParentProps,
+ Show,
+} from 'solid-js';
import { useAgentChanges } from '../context/agent-changes-controller';
+import { createChangesNarrow } from '../primitives/create-changes-narrow';
import { ChangesPane } from './ChangesPane';
const SESSION_MIN_PX = 320;
const CHANGES_MIN_PX = 400;
+/** Keep the resize panel registered until its content finishes sliding out. */
+function createChangesPresence(visible: Accessor<boolean>) {
+ const reducedMotion = createMediaQuery('(prefers-reduced-motion: reduce)');
+ const [present, setPresent] = createSignal(visible());
+ const [transitioning, setTransitioning] = createSignal(false);
+ let element: HTMLDivElement | undefined;
+ let animation: Animation | undefined;
+ let siblings: Animation[] = [];
+ const cancelSiblings = () => {
+ for (const sibling of siblings) sibling.cancel();
+ siblings = [];
+ };
+ const animateSplit = (
+ element: HTMLElement,
+ visible: boolean,
+ options: KeyframeAnimationOptions
+ ) => {
+ const continuing = siblings.length > 0;
+ const panel = element.parentElement;
+ if (!panel?.matches('[data-resize-panel]')) {
+ cancelSiblings();
+ return;
+ }
+ const root = panel.parentElement;
+ const sessionContent = root?.querySelector<HTMLElement>(
+ ':scope > [data-resize-panel] > [data-agent-changes-session]'
+ );
+ const session =
+ sessionContent?.hidden ||
+ sessionContent?.hasAttribute('data-slide-underlay')
+ ? undefined
+ : sessionContent?.parentElement;
+ const gutter = root?.querySelector<HTMLElement>(
+ ':scope > [role="separator"]'
+ );
+ const sessionWidth = session
+ ? continuing || !visible
+ ? getComputedStyle(session).width
+ : '100%'
+ : undefined;
+ const gutterTransform = gutter
+ ? continuing || !visible
+ ? getComputedStyle(gutter).transform
+ : `translateX(${panel.style.width})`
+ : undefined;
+ cancelSiblings();
+ // Match the session and divider to the pane's slide in both directions.
+ // The solver holds the resting widths under these temporary animations.
+ if (session) {
+ siblings.push(
+ session.animate(
+ [
+ { width: sessionWidth },
+ { width: visible ? session.style.width : '100%' },
+ ],
+ options
+ )
+ );
+ }
+ if (gutter) {
+ gutter.inert = !visible;
+ siblings.push(
+ gutter.animate(
+ [
+ { transform: gutterTransform },
+ {
+ transform: visible
+ ? 'translateX(0)'
+ : `translateX(${panel.style.width})`,
+ },
+ ],
+ options
+ )
+ );
+ }
+ };
+ let revision = 0;
+
+ // Synchronize the imperative animation with visibility. The retained owner
+ // keeps Resize.Panel's registration and the conversation draft intact on exit.
+ createEffect(
+ on(visible, (visible) => {
+ const current = ++revision;
+ setTransitioning(
+ !reducedMotion() && typeof HTMLElement.prototype.animate === 'function'
+ );
+ if (visible) setPresent(true);
+ if (!visible && (reducedMotion() || !element?.animate)) {
+ animation?.cancel();
+ animation = undefined;
+ cancelSiblings();
+ setPresent(false);
+ setTransitioning(false);
+ return;
+ }
+ queueMicrotask(() => {
+ if (current !== revision || !element) return;
+ // Snapshot values before cancellation: computed styles are live objects.
+ const previousTransform = animation
+ ? getComputedStyle(element).transform
+ : undefined;
+ animation?.cancel();
+ animation = undefined;
+ element.inert = !visible;
+ if (reducedMotion() || !element.animate) {
+ cancelSiblings();
+ setPresent(visible);
+ setTransitioning(false);
+ return;
+ }
+ const options: KeyframeAnimationOptions = {
+ duration: 220,
+ easing: 'ease-in-out',
+ fill: 'forwards',
+ };
+ animateSplit(element, visible, options);
+ animation = element.animate(
+ [
+ {
+ transform:
+ previousTransform ??
+ (visible ? 'translateX(100%)' : 'translateX(0)'),
+ },
+ { transform: visible ? 'translateX(0)' : 'translateX(100%)' },
+ ],
+ options
+ );
+ animation.onfinish = () => {
+ if (current !== revision) return;
+ const finished = animation;
+ animation = undefined;
+ setPresent(visible);
+ // Hold the final frame through unmount, then release WAAPI styles.
+ finished?.cancel();
+ cancelSiblings();
+ setTransitioning(false);
+ };
+ });
+ })
+ );
+ onCleanup(() => {
+ revision += 1;
+ animation?.cancel();
+ cancelSiblings();
+ });
+
+ return {
+ finish: () => {
+ revision += 1;
+ const finished = animation;
+ animation = undefined;
+ setPresent(visible());
+ finished?.cancel();
+ cancelSiblings();
+ setTransitioning(false);
+ },
+ present,
+ transitioning,
+ ref: (node: HTMLDivElement) => {
+ element = node;
+ },
+ };
+}
+
export function AgentChangesSplit(props: ParentProps) {
const { available, layout } = useAgentChanges();
+ const [root, setRoot] = createSignal<HTMLDivElement>();
+ const narrow = createChangesNarrow(root);
let zone: ResizeZoneCtx | undefined;
// A host that can never have changes keeps the session alone on screen,
// whatever a stale URL asks for.
- const sessionVisible = () => !available() || layout.sessionVisible();
- const changesVisible = () => available() && layout.changesVisible();
+ // Split/full changes keep the same visibility and must not replay the slide.
+ const changesVisible = createMemo(
+ () => available() && layout.changesVisible()
+ );
+ const presence = createChangesPresence(changesVisible);
+ const sessionVisible = createMemo<boolean>((previous) => {
+ if (!available()) return true;
+ // A narrow host opens as a takeover without changing the saved wide layout.
+ if (changesVisible() && narrow()) return false;
+ // A spotlight request during a slide waits for the slide to settle, so its
+ // endpoint does not move underneath the running translation.
+ if (presence.transitioning()) return previous ?? layout.sessionVisible();
+ if (changesVisible()) return layout.sessionVisible();
+ // Closing from full width must not shrink the pane before it slides out.
+ return presence.present() ? (previous ?? true) : true;
+ });
+ // Reveal the retained host behind a full-width slide without changing the
+ // Changes panel's solved geometry until the slide finishes, including reversals.
+ const slideUnderlay = () =>
+ presence.present() &&
+ !sessionVisible() &&
+ (!changesVisible() || presence.transitioning());
+ const sessionShown = () => sessionVisible() || slideUnderlay();
return (
- <Show
- when={isTouchDevice()}
- fallback={
- <Resize.Zone
- direction="horizontal"
- gutter={1}
- resizable
- captureResizeCtx={(ctx) => {
- zone = ctx;
- }}
- >
- {/* Panels mount and unmount with the layout: an unregistered panel
- would still paint its content at the zone's left edge. */}
- <Show when={sessionVisible()}>
- <Resize.Panel id="agent-session" minSize={SESSION_MIN_PX} index={0}>
- <div class="flex h-full min-w-0 flex-col overflow-hidden">
- {props.children}
- </div>
- </Resize.Panel>
- </Show>
- <Show when={changesVisible()}>
+ <div
+ ref={setRoot}
+ data-agent-changes-host
+ class="size-full min-h-0 min-w-0 overflow-hidden"
+ >
+ <Show
+ when={isTouchDevice()}
+ fallback={
+ <Resize.Zone
+ direction="horizontal"
+ gutter={1}
+ class="overflow-hidden"
+ resizable
+ captureResizeCtx={(ctx) => {
+ zone = ctx;
+ createEffect(on(ctx.size, presence.finish, { defer: true }));
+ }}
+ >
+ {/* Hiding retains resize intent and the host's editor/composer owner. */}
<Resize.Panel
- id="agent-changes"
- minSize={CHANGES_MIN_PX}
- index={1}
- target={layout.changesShare()}
- onSizeChangeEnd={(size) => {
- const total = zone?.size() ?? 0;
- if (total > 0) layout.setChangesShare((size / total) * 100);
- }}
+ id="agent-session"
+ minSize={SESSION_MIN_PX}
+ index={0}
+ persistent
+ hidden={() => !sessionVisible()}
>
- <div class="h-full min-w-0 overflow-hidden">
- <ChangesPane />
+ <div
+ data-agent-changes-session
+ data-slide-underlay={slideUnderlay() ? '' : undefined}
+ hidden={!sessionShown()}
+ inert={!sessionVisible() && changesVisible()}
+ style={{
+ width: slideUnderlay() ? `${zone?.size() ?? 0}px` : undefined,
+ }}
+ class="flex h-full min-w-0 flex-col overflow-hidden"
+ >
+ {props.children}
</div>
</Resize.Panel>
- </Show>
- </Resize.Zone>
- }
- >
- <div class="relative flex size-full min-w-0 flex-col">
- <div
- class="flex size-full min-w-0 flex-col"
- classList={{ hidden: changesVisible() }}
- inert={changesVisible()}
- >
- {props.children}
- </div>
- <Show when={changesVisible()}>
- <FloatRegion region="accessory" priority={1}>
- <span />
- </FloatRegion>
+ <Show when={presence.present()}>
+ <Resize.Panel
+ id="agent-changes"
+ minSize={CHANGES_MIN_PX}
+ index={1}
+ target={layout.changesShare()}
+ onSizeChangeEnd={(size) => {
+ const total = zone?.size() ?? 0;
+ if (total > 0) layout.setChangesShare((size / total) * 100);
+ }}
+ >
+ <div ref={presence.ref} class="h-full min-w-0 overflow-hidden">
+ <ChangesPane fullWidth={narrow()} />
+ </div>
+ </Resize.Panel>
+ </Show>
+ </Resize.Zone>
+ }
+ >
+ <div class="relative flex size-full min-w-0 flex-col overflow-hidden">
<div
- class="absolute inset-0 min-w-0 pt-(--mobile-content-inset-top)"
- style={{ 'padding-bottom': `${FloatRegions.hostHeight()}px` }}
+ class="flex size-full min-w-0 flex-col"
+ classList={{ hidden: changesVisible() }}
+ inert={changesVisible()}
>
- <ChangesPane />
+ {props.children}
</div>
- </Show>
- </div>
- </Show>
+ <Show when={presence.present()}>
+ <div
+ ref={presence.ref}
+ class="absolute inset-0 min-w-0 pt-(--mobile-content-inset-top)"
+ style={{ 'padding-bottom': `${FloatRegions.hostHeight()}px` }}
+ >
+ <FloatRegion region="accessory" priority={1}>
+ <span />
+ </FloatRegion>
+ <ChangesPane fullWidth />
+ </div>
+ </Show>
+ </div>
+ </Show>
+ </div>
);
}
diff --git a/apps/web/src/features/agent-changes/views/ChangesPane.tsx b/apps/web/src/features/agent-changes/views/ChangesPane.tsx
index 4bcf81cbac..979d2f6ffd 100644
--- a/apps/web/src/features/agent-changes/views/ChangesPane.tsx
+++ b/apps/web/src/features/agent-changes/views/ChangesPane.tsx
@@ -1,9 +1,6 @@
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
/**
- * 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.
+ * The Changes pane: PR metadata above a full-height file tree and diff stack,
+ * with tree actions in its header and borderless controls above the diffs.
*/
import {
@@ -13,18 +10,35 @@ import {
DiffView,
StatusLetter,
} from '@app/components/diff-view';
+import { Resize } from '@core/component/Resize';
+import type { ResizeZoneCtx } from '@core/component/Resize/types';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import * as Dialog from '@kobalte/core/dialog';
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, cn, Panel } from '@ui';
-import { CollapseTransition } from '@ui/components/CollapseTransition';
+import {
+ CollapseTransition,
+ type CollapseTransitionProps,
+} from '@ui/components/CollapseTransition';
import { FileTree } from '@ui/components/FileTree';
-import { Match, Show, Switch } from 'solid-js';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ Match,
+ on,
+ onCleanup,
+ Show,
+ Switch,
+} from 'solid-js';
import { ChangesHeader } from '../components/ChangesHeader';
import { CaptureBanner, ChangesNotice } from '../components/ChangesNotice';
+import { CopyFilePathButton } from '../components/CopyFilePathButton';
import { NoteAnnotation } from '../components/NoteAnnotation';
import { useAgentChanges } from '../context/agent-changes-controller';
import {
@@ -32,6 +46,13 @@ import {
describeFileCount,
describeRange,
} from '../core/changeset';
+import { createChangesNarrow } from '../primitives/create-changes-narrow';
+import {
+ DEFAULT_TREE_WIDTH,
+ MAX_TREE_WIDTH,
+ MIN_TREE_WIDTH,
+} from '../primitives/create-pane-layout';
+import { ChangesTreeDrawer } from './ChangesTreeDrawer';
/** The state narrowed to one kind, for `<Match>` to hand its fields down. */
function stateOf<K extends ChangesState['kind']>(state: ChangesState, kind: K) {
@@ -73,18 +94,134 @@ function CaptureBanners() {
);
}
-/** 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,
- };
+/** Lives in the tree header while open, beside the diffs while closed. */
+function ChangesTreeToggle(props: {
+ narrow?: boolean;
+ open?: boolean;
+ onToggle?: () => void;
+}) {
+ const { layout } = useAgentChanges();
+ const open = () => (props.narrow ? props.open : layout.treeOpen());
+ const label = () => (open() ? 'Hide file tree' : 'Show file tree');
+ return props.narrow && !props.onToggle ? (
+ <Dialog.Trigger
+ class="inline-flex size-7 shrink-0 items-center justify-center rounded-md text-ink hover:bg-hover"
+ aria-label={label()}
+ >
+ <SidebarIcon class="size-4" />
+ </Dialog.Trigger>
+ ) : (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label={label()}
+ aria-expanded={open()}
+ onClick={props.onToggle ?? layout.toggleTree}
+ >
+ <SidebarIcon />
+ </Button>
+ );
+}
+
+/** Borderless diff controls above the stack, scoped to the diff column's width. */
+function ChangesControls(props: { narrow: boolean; drawerOpen: boolean }) {
+ const { model, layout, diffStyle, setDiffStyle } = useAgentChanges();
const refreshing = () =>
model.refreshing() || model.state().kind === 'capturing';
+ const treeVisible = () => !props.narrow && layout.treeOpen();
+ return (
+ <div
+ class="flex min-w-0 shrink-0 items-center gap-1 px-3 pt-2"
+ role="group"
+ aria-label="Diff controls"
+ >
+ <Show
+ when={props.narrow}
+ fallback={
+ <Show when={!layout.treeOpen()}>
+ <ChangesTreeToggle />
+ </Show>
+ }
+ >
+ <ChangesTreeToggle narrow open={props.drawerOpen} />
+ </Show>
+ <Show when={!treeVisible()}>
+ <span class="truncate px-1 text-xs text-ink-subtle">
+ {describeFileCount(model.files().length)}
+ </span>
+ </Show>
+ <Show when={!isTouchDevice()}>
+ <DiffView.StyleToggle
+ value={diffStyle()}
+ onChange={setDiffStyle}
+ class="shrink-0"
+ />
+ </Show>
+ <span class="flex-1" />
+ <DiffView.CollapseAll iconOnly />
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label="Refresh pull request changes"
+ disabled={refreshing()}
+ onClick={() => void model.refresh()}
+ >
+ <ArrowsClockwiseIcon class={cn(refreshing() && 'animate-spin')} />
+ </Button>
+ </div>
+ );
+}
+
+/** Count on the left, with the tree visibility toggle on the right. */
+function ChangesTreeHeader(props: { narrow: boolean; onClose: () => void }) {
+ const { model, layout } = useAgentChanges();
+ return (
+ <div
+ class="flex min-w-0 shrink-0 items-center justify-between gap-1 px-3 pt-2 pb-1"
+ role="group"
+ aria-label="File tree controls"
+ >
+ <span class="truncate text-xs text-ink-subtle">
+ {describeFileCount(model.files().length)}
+ </span>
+ <ChangesTreeToggle
+ narrow={props.narrow}
+ open={true}
+ onToggle={() => (props.narrow ? props.onClose() : layout.toggleTree())}
+ />
+ </div>
+ );
+}
+
+/** The tree beside the diff stack, both over the changeset's files. */
+function ChangesBody() {
+ const [body, setBody] = createSignal<HTMLDivElement>();
+ const narrow = createChangesNarrow(body);
+ const [drawerOpen, setDrawerOpen] = createSignal(false);
+ const closeDrawer = () => setDrawerOpen(false);
+ return (
+ <Dialog.Root
+ open={narrow() && drawerOpen()}
+ onOpenChange={setDrawerOpen}
+ modal={false}
+ >
+ <ChangesBodyContent
+ body={setBody}
+ narrow={narrow}
+ drawerOpen={drawerOpen}
+ closeDrawer={closeDrawer}
+ />
+ </Dialog.Root>
+ );
+}
+
+function ChangesBodyContent(props: {
+ body: (element: HTMLDivElement) => void;
+ narrow: Accessor<boolean>;
+ drawerOpen: Accessor<boolean>;
+ closeDrawer: () => void;
+}) {
+ const { model, review, layout, copyPath, context } = useAgentChanges();
const notes = createDiffComments({
items: review.notes,
rangeOf: (note) => note,
@@ -101,49 +238,137 @@ function ChangesBody() {
/>
),
});
- return (
- <DiffView.Root
- files={model.files()}
- patch={model.patch() ?? ''}
- diffStyle={isTouchDevice() ? 'unified' : diffStyle()}
- collapse={collapse}
- active={review.active()}
+ const treeVisible = () => !props.narrow() && layout.treeOpen();
+ const [treePresent, setTreePresent] = createSignal(treeVisible());
+ const [wideDock, setWideDock] = createSignal<HTMLDivElement>();
+ const [drawerDock, setDrawerDock] = createSignal<HTMLDivElement>();
+ let treeBody!: HTMLDivElement;
+ let diffBody: HTMLDivElement | undefined;
+ let zone: ResizeZoneCtx | undefined;
+ let finishTreeMotion: (() => void) | undefined;
+ let expandedTreeSize: Accessor<number> = layout.treeWidth;
+ const drawerWidth = () => {
+ const available = zone?.size() ?? DEFAULT_TREE_WIDTH;
+ return Math.min(
+ DEFAULT_TREE_WIDTH,
+ Math.max(Math.min(MIN_TREE_WIDTH, available), available - 32)
+ );
+ };
+ const treePanel = () =>
+ wideDock()?.closest<HTMLElement>('[data-resize-panel]');
+ const companions: NonNullable<CollapseTransitionProps['companions']> = ({
+ opening,
+ from,
+ interrupted,
+ }) => {
+ const panel = treePanel();
+ const diffPanel = diffBody?.parentElement;
+ const root = panel?.parentElement;
+ if (!panel || !diffPanel || !root) return [];
+ const width = zone?.size() ?? root.clientWidth;
+ const fromOffset = from > 0 ? from + 1 : 0;
+ const toOffset = opening ? expandedTreeSize() + 1 : 0;
+ const current = getComputedStyle(diffPanel);
+ const animations: { target: HTMLElement; keyframes: Keyframe[] }[] = [
+ {
+ target: diffPanel,
+ keyframes: [
+ interrupted
+ ? { left: current.left, width: current.width }
+ : { left: `${fromOffset}px`, width: `${width - fromOffset}px` },
+ { left: `${toOffset}px`, width: `${width - toOffset}px` },
+ ],
+ },
+ ];
+ const gutter = root.querySelector<HTMLElement>('[role="separator"]');
+ if (gutter) {
+ gutter.inert = !opening;
+ gutter.setAttribute('aria-hidden', String(!opening));
+ const inset = Number.parseFloat(gutter.style.left) - expandedTreeSize();
+ animations.push({
+ target: gutter,
+ keyframes: [
+ {
+ left:
+ interrupted && gutter.getAnimations?.().length
+ ? getComputedStyle(gutter).left
+ : `${from + inset}px`,
+ },
+ { left: `${(opening ? expandedTreeSize() : 0) + inset}px` },
+ ],
+ });
+ }
+ return animations;
+ };
+ const finishTreeAnimation = () => finishTreeMotion?.();
+ const settleTreeAnimation = (event: PointerEvent | KeyboardEvent) => {
+ if (
+ !(event.target instanceof Element) ||
+ !event.target.closest('[role="separator"]')
+ )
+ return;
+ finishTreeAnimation();
+ };
+ // Construct once under Dialog.Root so directory state survives docking and hiding.
+ const tree = (
+ <div
+ ref={treeBody}
+ class="flex size-full min-w-0 flex-col overflow-hidden"
+ inert={!(treeVisible() || (props.narrow() && props.drawerOpen()))}
+ aria-hidden={!(treeVisible() || (props.narrow() && props.drawerOpen()))}
>
- <Panel.Toolbar class="gap-1">
- <Show when={!isTouchDevice()}>
- <Button
- variant="ghost"
- size="icon-sm"
- label={layout.treeOpen() ? 'Hide file tree' : 'Show file tree'}
- aria-expanded={layout.treeOpen()}
- onClick={layout.toggleTree}
- >
- <SidebarIcon />
- </Button>
- </Show>
- <span class="truncate px-1 text-xs text-ink-subtle">
- {describeFileCount(model.files().length)}
- </span>
- <span class="flex-1" />
- <Show when={!isTouchDevice()}>
- <DiffView.StyleToggle
- value={diffStyle()}
- onChange={setDiffStyle}
- class="max-md:hidden"
- />
- </Show>
- <DiffView.CollapseAll />
- <Button
- variant="ghost"
- size="icon-sm"
- label="Refresh pull request changes"
- disabled={refreshing()}
- onClick={() => void model.refresh()}
+ <ChangesTreeHeader narrow={props.narrow()} onClose={props.closeDrawer} />
+ <div class="min-h-0 flex-1 overflow-y-auto p-2 pt-1">
+ <FileTree.Root
+ aria-label="Changed files"
+ items={model.files()}
+ path={(file) => file.path}
+ selected={review.active()}
+ onSelect={(file) => {
+ review.activate(file.path);
+ props.closeDrawer();
+ }}
>
- <ArrowsClockwiseIcon class={cn(refreshing() && 'animate-spin')} />
- </Button>
- </Panel.Toolbar>
- <Panel.Body class="flex flex-col">
+ {(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>
+ </div>
+ );
+ createEffect(() => {
+ const target = props.narrow() ? drawerDock() : wideDock();
+ if (target && tree instanceof Node && treeBody.parentElement !== target)
+ target.append(tree);
+ });
+ createEffect(
+ on(
+ props.narrow,
+ () => {
+ finishTreeAnimation();
+ if (!props.narrow()) props.closeDrawer();
+ },
+ { defer: true }
+ )
+ );
+ return (
+ <Panel.Body class="relative flex flex-col">
+ <div
+ ref={props.body}
+ class="relative flex size-full min-h-0 min-w-0 flex-col"
+ >
<CaptureBanners />
<Show when={model.changeset()?.truncated}>
<CaptureBanner
@@ -151,82 +376,133 @@ function ChangesBody() {
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={!isTouchDevice() && layout.treeOpen()}
- axis="width"
+ <div
+ class="min-h-0 flex-1"
+ ref={(element) => {
+ element.addEventListener('pointerdown', settleTreeAnimation, true);
+ element.addEventListener('keydown', settleTreeAnimation, true);
+ onCleanup(() => {
+ element.removeEventListener(
+ 'pointerdown',
+ settleTreeAnimation,
+ true
+ );
+ element.removeEventListener('keydown', settleTreeAnimation, true);
+ });
+ }}
+ >
+ <Resize.Zone
+ direction="horizontal"
+ gutter={1}
+ class="overflow-hidden"
+ captureResizeCtx={(ctx) => {
+ if (zone === ctx) return;
+ zone = ctx;
+ const size = ctx.sizeOf('changes-file-tree');
+ expandedTreeSize = createMemo<number>((previous) => {
+ const solved = size();
+ return treeVisible() && solved > 0
+ ? solved
+ : (previous ?? layout.treeWidth());
+ });
+ // Outer split and viewport changes invalidate pixel animation endpoints.
+ createEffect(on(ctx.size, finishTreeAnimation, { defer: true }));
+ }}
>
- <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)}
+ <Resize.Panel
+ id="changes-file-tree"
+ index={0}
+ minSize={MIN_TREE_WIDTH}
+ maxSize={MAX_TREE_WIDTH}
+ target={{ kind: 'px', px: layout.treeWidth() }}
+ redistributionPreferredSize={layout.treeWidth()}
+ onSizeChangeEnd={layout.setTreeWidth}
+ hidden={() =>
+ props.narrow() || (!treeVisible() && !treePresent())
+ }
+ persistent
+ >
+ <Show when={!props.narrow()}>
+ <CollapseTransition
+ open={treeVisible()}
+ axis="width"
+ container={() => treePanel() ?? undefined}
+ expandedSize={expandedTreeSize()}
+ companions={companions}
+ onPresenceChange={setTreePresent}
+ captureController={(controller) => {
+ finishTreeMotion = controller.finish;
+ }}
+ >
+ <div ref={setWideDock} class="size-full" />
+ </CollapseTransition>
+ </Show>
+ </Resize.Panel>
+ <Resize.Panel id="changes-diff" index={1} minSize={240}>
+ <div
+ ref={diffBody}
+ class="flex size-full min-w-0 flex-col overflow-hidden @container/changes-diff"
>
- {(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>
+ <ChangesControls
+ narrow={props.narrow()}
+ drawerOpen={props.drawerOpen()}
+ />
+ <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 />
+ <CopyFilePathButton
+ path={entry.file.path}
+ onCopy={copyPath}
+ />
+ </>
+ )}
+ 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>
- </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>
+ </Resize.Panel>
+ </Resize.Zone>
+ <Show when={props.narrow()}>
+ <ChangesTreeDrawer
+ open={props.drawerOpen()}
+ width={drawerWidth()}
+ onClose={props.closeDrawer}
+ dock={setDrawerDock}
+ />
+ </Show>
</div>
- </Panel.Body>
- </DiffView.Root>
+ </div>
+ </Panel.Body>
);
}
@@ -311,8 +587,15 @@ function ChangesNotices() {
);
}
-export function ChangesPane() {
- const { layout, model, context } = useAgentChanges();
+export function ChangesPane(props: { fullWidth?: boolean }) {
+ const { layout, model, review, diffStyle, context, changeCounts } =
+ useAgentChanges();
+ const collapse: DiffCollapse = {
+ isCollapsed: review.isCollapsed,
+ toggle: review.toggleCollapsed,
+ toggleAll: review.toggleAllCollapsed,
+ anyExpanded: review.anyExpanded,
+ };
const range = () => {
const current = model.changeset();
return current ? describeRange(current) : undefined;
@@ -321,24 +604,45 @@ export function ChangesPane() {
model.changeset() !== undefined && model.files().length > 0;
return (
- <Panel class="rounded-none" role="region" aria-label="Changes">
- <Panel.Header class="gap-1.5">
- <ChangesHeader
- mobile={isTouchDevice()}
- 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>
+ <DiffView.Root
+ files={model.files()}
+ patch={model.patch() ?? ''}
+ diffStyle={isTouchDevice() ? 'unified' : diffStyle()}
+ collapse={collapse}
+ active={review.active()}
+ >
+ <Panel
+ hideBorder
+ class="rounded-none @container/changes-pane"
+ role="region"
+ aria-label="Changes"
+ >
+ <Panel.Header class="gap-1 py-1">
+ <div
+ class="flex min-w-0 flex-1 items-center gap-1"
+ role="group"
+ aria-label="Changes controls"
+ >
+ <ChangesHeader
+ mobile={isTouchDevice()}
+ spotlit={!!props.fullWidth || layout.layout() === 'full'}
+ range={range()}
+ pullRequestUrl={context.host.pullRequestUrl()}
+ pullRequestTitle={context.host.pullRequestTitle?.()}
+ changeCounts={changeCounts()}
+ onViewPullRequest={() => {
+ const url = context.host.pullRequestUrl();
+ if (url) context.host.openExternal(url);
+ }}
+ onSpotlight={props.fullWidth ? undefined : layout.spotlight}
+ onClose={layout.close}
+ />
+ </div>
+ </Panel.Header>
+ <Show when={showsFiles()} fallback={<ChangesNotices />}>
+ <ChangesBody />
+ </Show>
+ </Panel>
+ </DiffView.Root>
);
}
diff --git a/apps/web/src/features/agent-changes/views/ChangesTreeDrawer.tsx b/apps/web/src/features/agent-changes/views/ChangesTreeDrawer.tsx
new file mode 100644
index 0000000000..7159a36587
--- /dev/null
+++ b/apps/web/src/features/agent-changes/views/ChangesTreeDrawer.tsx
@@ -0,0 +1,82 @@
+import * as Dialog from '@kobalte/core/dialog';
+import { CollapseTransition } from '@ui/components/CollapseTransition';
+import { Show } from 'solid-js';
+
+/** Keep an inert exit frame, not a retained dialog's document listeners. */
+export function ChangesTreeDrawer(props: {
+ open: boolean;
+ width: number;
+ onClose: () => void;
+ dock: (element: HTMLDivElement) => void;
+}) {
+ // Own the live dialog and its exit dock outside the transition's closing owner.
+ let frameElement!: HTMLDivElement;
+ const frame = (
+ <div
+ data-changes-tree-drawer-frame
+ ref={frameElement}
+ class="relative z-10 flex h-full max-w-full flex-col overflow-hidden border-r border-edge-muted bg-panel"
+ style={{
+ width: `${props.width}px`,
+ 'pointer-events': props.open ? 'auto' : 'none',
+ }}
+ inert={!props.open}
+ aria-hidden={!props.open}
+ >
+ <Show
+ when={props.open}
+ fallback={<div ref={props.dock} class="size-full" />}
+ >
+ <Dialog.Content
+ aria-label="Changed files"
+ class="size-full outline-none"
+ onInteractOutside={(event) => {
+ if (
+ event.target instanceof Element &&
+ event.target.closest('[data-changes-tree-backdrop]')
+ ) {
+ // The backdrop closes explicitly; preserve default trigger restoration.
+ event.preventDefault();
+ }
+ }}
+ onCloseAutoFocus={(event) => {
+ // A queued close must not steal focus after an immediate reopen.
+ if (props.open) event.preventDefault();
+ }}
+ >
+ <div ref={props.dock} class="size-full" />
+ </Dialog.Content>
+ </Show>
+ </div>
+ );
+ return (
+ <div class="pointer-events-none absolute inset-0 z-10 overflow-hidden">
+ <CollapseTransition
+ open={props.open}
+ axis="width"
+ expandedSize={props.width}
+ container={() => frameElement}
+ >
+ <div
+ class="h-full"
+ ref={(element) => {
+ // A fresh wrapper lets an interrupted exit release only its old owner.
+ if (frame instanceof Node) element.append(frame);
+ }}
+ />
+ </CollapseTransition>
+ <button
+ type="button"
+ tabIndex={-1}
+ aria-label="Close file tree backdrop"
+ data-changes-tree-backdrop
+ data-testid="changes-tree-backdrop"
+ class="pointer-events-auto absolute inset-0 bg-modal-overlay"
+ classList={{ hidden: !props.open }}
+ style={{ 'z-index': 0 }}
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={props.onClose}
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx b/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx
index e5d2a41e84..fe681d549b 100644
--- a/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx
+++ b/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx
@@ -1,5 +1,5 @@
/**
- * The pieces the session pane itself shows: the header toggle, the
+ * The pieces the session pane itself shows: the header opener, the
* "changes ready" hand-off card, and the queued-notes chip by the composer.
* Each renders nothing until a host has mounted the controller, and nothing
* at all while the host reports it can never have changes (a chat-only
@@ -15,18 +15,11 @@ import { useOptionalAgentChanges } from '../context/agent-changes-controller';
export function ChangesToggle() {
const controller = useOptionalAgentChanges();
if (!controller) return null;
- const { available, layout, model, context } = controller;
- const counts = controller.changeCounts;
+ const { available, layout } = controller;
return (
<Show when={available()}>
<ChangesToggleButton
open={layout.changesVisible()}
- additions={counts()?.additions ?? 0}
- deletions={counts()?.deletions ?? 0}
- capturing={
- !context.host.pullRequestChangeCounts &&
- model.state().kind === 'capturing'
- }
onToggle={layout.toggle}
/>
</Show>
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
deleted file mode 100644
index 2000f03c8e..0000000000
--- a/apps/web/src/features/agent-changes/views/changes-pane.test.tsx
+++ /dev/null
@@ -1,430 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
-import { createSignal } from 'solid-js';
-import { afterEach, 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,
-} from '../primitives/create-agent-changes';
-import { createMemoryStorage } from '../tests/memory-storage';
-import {
- createMockAgentChangesContext,
- MOCK_PATCH,
- mockChangeset,
-} from '../tests/mock-context';
-import { ChangesPane } from './ChangesPane';
-import {
- ChangesHandoff,
- ChangesToggle,
- ReviewNotesDock,
-} from './SessionChangesControls';
-
-const device = vi.hoisted(() => ({ touch: false }));
-vi.mock('@core/mobile/isTouchDevice', () => ({
- isTouchDevice: () => device.touch,
-}));
-afterEach(() => {
- device.touch = false;
-});
-
-// 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('@app/components/diff-view/pierre/PierreFileDiff', () => ({
- PierreFileDiff: (props: { path: string; diffStyle: string }) => (
- <div
- data-testid="diff"
- data-path={props.path}
- data-style={props.diffStyle}
- />
- ),
-}));
-
-// 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', () => ({
- ws: { send() {}, addEventListener() {}, removeEventListener() {} },
- state: () => 'closed',
- createConnectionBlockWebsocketEffect() {},
- createConnectionWebsocketEffect() {},
- parseWebsocketPayload: () => undefined,
-}));
-
-// The block registry globs every block definition (and their heavy
-// dependencies) at import time; the pane never reads it.
-vi.mock('@core/constant/allBlocks', () => ({
- blocks: {},
- blockAcceptedMimetypeToFileExtension: {},
- blockAcceptedFileExtensionToMimeType: {},
-}));
-
-vi.mock('@service-storage/websocket', () => ({
- storageWS: { send() {}, addEventListener() {}, removeEventListener() {} },
- createWebSocketJob: () => Promise.reject(new Error('no websocket in tests')),
-}));
-
-function mount(
- context: AgentChangesContext,
- ui: () => ReturnType<typeof ChangesPane>
-) {
- const [dismissed, setDismissed] = createSignal<string>();
- let controller!: AgentChangesController;
- const result = render(() => {
- controller = createAgentChanges({
- context,
- storage: createMemoryStorage(),
- view: createLocalPaneViewState(),
- dismissed: [dismissed, setDismissed],
- });
- return (
- <AgentChangesControllerProvider value={controller}>
- {ui()}
- </AgentChangesControllerProvider>
- );
- });
- return { ...result, controller: () => controller };
-}
-
-function readyContext() {
- return createMockAgentChangesContext({
- summary: { capturing: false, changeset: mockChangeset() },
- patch: MOCK_PATCH,
- });
-}
-
-describe('ChangesPane', () => {
- it('returns to the touch conversation and uses unified diffs without a side tree', async () => {
- device.touch = true;
- const { controller } = mount(readyContext(), () => <ChangesPane />);
- controller().layout.open();
- controller().setDiffStyle('split');
- await waitFor(() => expect(screen.getAllByTestId('diff')).toHaveLength(2));
- expect(
- screen
- .getAllByTestId('diff')
- .every((diff) => diff.dataset.style === 'unified')
- ).toBe(true);
- expect(
- screen.queryByRole('button', { name: 'Expand changes to the full width' })
- ).toBeNull();
- expect(screen.queryByRole('button', { name: /file tree/ })).toBeNull();
- expect(screen.queryByLabelText('Diff layout')).toBeNull();
- fireEvent.click(
- screen.getByRole('button', { name: 'Back to conversation' })
- );
- expect(controller().layout.changesVisible()).toBe(false);
- });
- it('lists files and collapses individual or all diffs without viewed controls', async () => {
- const context = readyContext();
- const { controller } = mount(context, () => <ChangesPane />);
- controller().layout.open();
-
- expect(
- screen.getByText('agent/unread-archived-sessions → main')
- ).toBeTruthy();
- await waitFor(() => expect(screen.getAllByTestId('diff')).toHaveLength(2));
- expect(screen.queryByRole('button', { name: /^Viewed$/ })).toBeNull();
- expect(screen.queryByRole('progressbar')).toBeNull();
- expect(
- screen.queryByRole('button', { name: 'Mark all viewed' })
- ).toBeNull();
-
- fireEvent.click(screen.getByRole('button', { name: 'Hide a.ts' }));
- expect(screen.getAllByTestId('diff')).toHaveLength(1);
- expect(screen.getByRole('button', { name: 'Show a.ts' })).toBeTruthy();
-
- fireEvent.click(screen.getByRole('button', { name: 'Collapse all' }));
- expect(screen.queryAllByTestId('diff')).toHaveLength(0);
- fireEvent.click(screen.getByRole('button', { name: 'Expand all' }));
- expect(screen.getAllByTestId('diff')).toHaveLength(2);
- });
-
- it('supports a PR host with no agent capabilities', async () => {
- const context = readyContext();
- const { controller } = mount(
- {
- ...context,
- host: {
- ...context.host,
- scopeKey: () => 'pr:macro-inc/macro/1482',
- agent: undefined,
- },
- },
- () => (
- <>
- <ChangesPane />
- <ReviewNotesDock />
- </>
- )
- );
- controller().layout.open();
- await waitFor(() => expect(screen.getAllByTestId('diff')).toHaveLength(2));
- controller().sendQueuedNotes();
- expect(context.sent).toEqual([]);
- expect(screen.queryByRole('button', { name: 'Send to agent' })).toBeNull();
- });
-
- it('shows refresh failures without discarding the current diff and allows retry', async () => {
- const context = readyContext();
- const refresh = vi
- .fn()
- .mockRejectedValueOnce(new Error('unavailable'))
- .mockResolvedValueOnce(undefined);
- context.source.refresh = refresh;
- const { controller } = mount(context, () => <ChangesPane />);
- controller().layout.open();
- fireEvent.click(
- screen.getByRole('button', { name: /Refresh pull request changes/ })
- );
- await waitFor(() =>
- expect(screen.getByRole('status').textContent).toContain(
- 'could not be refreshed'
- )
- );
- expect(screen.getAllByTestId('diff')).toHaveLength(2);
- fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
- await waitFor(() => expect(screen.queryByRole('status')).toBeNull());
- expect(refresh).toHaveBeenCalledTimes(2);
- });
-
- it('explains that a linked GitHub PR is required', () => {
- const context = createMockAgentChangesContext({
- summary: {
- capturing: false,
- attempt: {
- startedAt: 't',
- finishedAt: 't',
- outcome: 'not_ready',
- error:
- 'Link a GitHub pull request to this session to review its changes.',
- },
- },
- });
- const { controller } = mount(context, () => <ChangesPane />);
- controller().layout.open();
- expect(screen.getByText('Pull request changes unavailable')).toBeTruthy();
- expect(
- screen.getByText(
- 'Link a GitHub pull request to this session to review its changes.'
- )
- ).toBeTruthy();
- });
-
- it('offers to capture when nothing has been captured, and refreshes', async () => {
- const context = createMockAgentChangesContext({
- summary: { capturing: false },
- });
- const { controller } = mount(context, () => <ChangesPane />);
- controller().layout.open();
- fireEvent.click(screen.getByRole('button', { name: /Refresh changes/ }));
- await waitFor(() => expect(context.refreshes()).toBe(1));
- });
-
- it('opens the linked GitHub PR without creating another one', () => {
- const context = readyContext();
- const url = 'https://github.com/macro-inc/macro/pull/1482';
- context.setPullRequestUrl(url);
- const { controller } = mount(context, () => <ChangesPane />);
- controller().layout.open();
- expect(
- screen.queryByRole('button', { name: 'Create pull request' })
- ).toBeNull();
- 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 />);
- controller().layout.open();
- fireEvent.click(
- screen.getByRole('button', { name: 'Expand changes to the full width' })
- );
- 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('closed');
- });
-});
-
-describe('session controls', () => {
- it('toggles the pane and shows addition/deletion totals', () => {
- const context = readyContext();
- const { controller } = mount(context, () => <ChangesToggle />);
- const toggle = screen.getByRole('button', { name: /Changes/ });
- expect(toggle.textContent).toContain('Changes+3−1');
- expect(toggle.getAttribute('aria-pressed')).toBe('false');
- fireEvent.click(toggle);
- expect(controller().layout.layout()).toBe('split');
- expect(toggle.getAttribute('aria-pressed')).toBe('true');
- });
-
- it('uses GitHub API totals without falling back to captured estimates', () => {
- const context = readyContext();
- const [counts, setCounts] = createSignal<
- { additions: number; deletions: number } | undefined
- >({ additions: 8, deletions: 2 });
- context.host.pullRequestChangeCounts = counts;
- const { controller } = mount(context, () => <ChangesToggle />);
- const toggle = screen.getByRole('button', { name: /Changes/ });
- expect(toggle.textContent).toBe('Changes+8−2');
-
- // A missing or stale PR capture must not replace GitHub totals.
- context.setSummary(undefined);
- expect(toggle.textContent).toBe('Changes+8−2');
- context.setSummary({ capturing: true, changeset: mockChangeset() });
- expect(toggle.textContent).toBe('Changes+8−2');
- expect(toggle.querySelector('.animate-pulse')).toBeNull();
- expect(controller().changeCounts()).toEqual({ additions: 8, deletions: 2 });
- // Missing GitHub data must not expose the snapshot's +3 / −1 estimates.
- setCounts(undefined);
- expect(toggle.textContent).toBe('Changes');
- expect(controller().changeCounts()).toBeUndefined();
-
- setCounts({ additions: 12, deletions: 0 });
- expect(toggle.textContent).toBe('Changes+12');
- setCounts({ additions: 0, deletions: 4 });
- expect(toggle.textContent).toBe('Changes−4');
- setCounts({ additions: 0, deletions: 0 });
- expect(toggle.textContent).toBe('Changes');
- fireEvent.click(toggle);
- expect(controller().layout.changesVisible()).toBe(true);
- });
-
- it('does not display fake zero counts before a snapshot loads or for empty snapshots', () => {
- const context = createMockAgentChangesContext();
- mount(context, () => <ChangesToggle />);
- const toggle = screen.getByRole('button', { name: /Changes/ });
- expect(toggle.textContent).toBe('Changes');
- context.setSummary({
- capturing: false,
- changeset: mockChangeset({ files: [], additions: 0, deletions: 0 }),
- });
- expect(toggle.textContent).toBe('Changes');
- context.setSummary({ capturing: false, changeset: mockChangeset() });
- expect(toggle.textContent).toBe('Changes+3−1');
- });
-
- it('hands off to the pane while it is closed, and can be dismissed', () => {
- const context = readyContext();
- const { controller } = mount(context, () => <ChangesHandoff />);
- expect(screen.getByText('Changes ready to review')).toBeTruthy();
- fireEvent.click(screen.getByRole('button', { name: 'Review changes' }));
- expect(controller().layout.layout()).toBe('split');
- expect(controller().review.active()).toBe('apps/web/src/a.ts');
- expect(screen.queryByText('Changes ready to review')).toBeNull();
-
- controller().layout.close();
- expect(screen.getByText('Changes ready to review')).toBeTruthy();
- fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));
- expect(screen.queryByText('Changes ready to review')).toBeNull();
- });
-
- it('sends queued notes to the agent from the dock', () => {
- const context = readyContext();
- const { controller } = mount(context, () => <ReviewNotesDock />);
- expect(screen.queryByText(/review note/)).toBeNull();
- controller().review.addNote(
- {
- path: 'apps/web/src/a.ts',
- side: 'additions',
- lineNumber: 2,
- endLineNumber: 2,
- },
- 'Use a constant'
- );
- expect(screen.getByText(/review note/).textContent).toContain('1');
- fireEvent.click(
- screen.getByRole('button', { name: /1 review note queued/ })
- );
- const editor = screen.getByLabelText(
- 'Review note on apps/web/src/a.ts, line 2 (new)'
- ) as HTMLTextAreaElement;
- expect(editor.value).toBe('Use a constant');
- fireEvent.input(editor, { target: { value: 'Use a named constant' } });
- fireEvent.click(screen.getByRole('button', { name: 'Send to agent' }));
- expect(context.sent[0]).toContain('`apps/web/src/a.ts`, line 2 (new)');
- expect(context.sent[0]).toContain('Use a named constant');
- expect(screen.queryByText(/review note/)).toBeNull();
- });
-
- it('renders nothing for a host that can never have changes', () => {
- const context = readyContext();
- const [coding, setCoding] = createSignal(false);
- const { controller } = mount(
- { ...context, host: { ...context.host, canHaveChanges: coding } },
- () => (
- <>
- <ChangesToggle />
- <ChangesHandoff />
- <ReviewNotesDock />
- </>
- )
- );
- controller().review.addNote(
- {
- path: 'apps/web/src/a.ts',
- side: 'additions',
- lineNumber: 2,
- endLineNumber: 2,
- },
- 'Use a constant'
- );
- expect(screen.queryByRole('button', { name: /Changes/ })).toBeNull();
- expect(screen.queryByText('Changes ready to review')).toBeNull();
- expect(screen.queryByText(/review note/)).toBeNull();
-
- setCoding(true);
- expect(screen.getByRole('button', { name: /Changes/ })).toBeTruthy();
- expect(screen.getByText('Changes ready to review')).toBeTruthy();
- expect(screen.getByText(/review note/)).toBeTruthy();
- });
-
- it("opens the note's file from the expanded dock", () => {
- const context = readyContext();
- const { controller } = mount(context, () => <ReviewNotesDock />);
- controller().review.addNote(
- {
- path: 'apps/web/src/a.ts',
- side: 'additions',
- lineNumber: 2,
- endLineNumber: 2,
- },
- 'Use a constant'
- );
- fireEvent.click(
- screen.getByRole('button', { name: /1 review note queued/ })
- );
- fireEvent.click(
- screen.getByRole('button', { name: /apps\/web\/src\/a.ts/ })
- );
- expect(controller().layout.changesVisible()).toBe(true);
- expect(controller().review.active()).toBe('apps/web/src/a.ts');
- });
-});
diff --git a/apps/web/src/features/block-pr/component/PrChanges.tsx b/apps/web/src/features/block-pr/component/PrChanges.tsx
index cdcb2371d0..bbb39c1d79 100644
--- a/apps/web/src/features/block-pr/component/PrChanges.tsx
+++ b/apps/web/src/features/block-pr/component/PrChanges.tsx
@@ -16,13 +16,21 @@ import { createSignal, type ParentProps } from 'solid-js';
import { createPrChangesSource } from '../data/pr-changes';
export function PrChangesProvider(
- props: ParentProps<{ foreignEntityId: string; pullRequestUrl?: string }>
+ props: ParentProps<{
+ foreignEntityId: string;
+ pullRequestUrl?: string;
+ pullRequestTitle?: string;
+ pullRequestChangeCounts?: { additions: number; deletions: number };
+ }>
) {
const scopeKey = () => `pr:${props.foreignEntityId}`;
const source = createPrChangesSource(() => props.foreignEntityId);
const host: ChangesHost = {
scopeKey,
pullRequestUrl: () => props.pullRequestUrl,
+ pullRequestTitle: () => props.pullRequestTitle,
+ // Missing GitHub totals never fall back to captured estimates.
+ pullRequestChangeCounts: () => props.pullRequestChangeCounts,
openExternal: openExternalUrl,
copyText,
notify: (message, tone) => {
diff --git a/apps/web/src/features/block-pr/views/PrDetail.tsx b/apps/web/src/features/block-pr/views/PrDetail.tsx
index 228c1e188c..0cfaedc199 100644
--- a/apps/web/src/features/block-pr/views/PrDetail.tsx
+++ b/apps/web/src/features/block-pr/views/PrDetail.tsx
@@ -3,6 +3,7 @@ import {
AgentChangesSplit,
ChangesToggle,
} from '@app/features/agent-changes/agent-changes';
+import { useOptionalAgentChanges } from '@app/features/agent-changes/context/agent-changes-controller';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { SidePanel } from '@components/app/side-panel';
import { SplitPanel } from '@components/app/split-panel';
@@ -10,7 +11,6 @@ import {
StaticMarkdown,
StaticMarkdownContext,
} from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
-import { openExternalUrl } from '@core/util/url';
import { GithubLabelPills } from '@entity/components/GithubLabelPill';
import { DebouncedNotificationReadMarker } from '@notifications';
import {
@@ -57,6 +57,12 @@ export function usePrDetail(foreignEntityId: Accessor<string>) {
const discussionSource = createPrDiscussionSource();
const data = (): PrForeignEntityData | undefined =>
query.isPending ? undefined : query.data;
+ const changeCounts = () => {
+ const pullRequest = data()?.pullRequest;
+ return pullRequest?.additions != null && pullRequest.deletions != null
+ ? { additions: pullRequest.additions, deletions: pullRequest.deletions }
+ : undefined;
+ };
const invalidateRefreshedPullRequest = async () => {
const id = foreignEntityId();
await Promise.all([
@@ -81,7 +87,7 @@ export function usePrDetail(foreignEntityId: Accessor<string>) {
},
() => void invalidateRefreshedPullRequest()
);
- return { query, data, discussionSource };
+ return { query, data, discussionSource, changeCounts };
}
type PrDetailBodyProps = {
@@ -152,10 +158,7 @@ export function PrDetailBody(props: PrDetailBodyProps) {
);
}
-/**
- * Native hosts own their header and place this content below it, both inside
- * `PrChangesProvider`.
- */
+/** Native hosts place this content below their header inside `PrChangesProvider`. */
export function PrDetailContent(props: PrDetailBodyProps) {
return (
<div class="relative min-h-0 min-w-0 flex-1">
@@ -174,15 +177,13 @@ export function PrDetailContent(props: PrDetailBodyProps) {
status={props.status}
/>
<div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">
- <AgentChangesSplit>
- <PrDetailBody
- foreignEntityId={props.foreignEntityId}
- data={props.data}
- status={props.status}
- onRetry={props.onRetry}
- discussionSource={props.discussionSource}
- />
- </AgentChangesSplit>
+ <PrDetailBody
+ foreignEntityId={props.foreignEntityId}
+ data={props.data}
+ status={props.status}
+ onRetry={props.onRetry}
+ discussionSource={props.discussionSource}
+ />
</div>
</SidePanel.Layout>
</Suspense>
@@ -190,21 +191,10 @@ export function PrDetailContent(props: PrDetailBodyProps) {
);
}
-export function PrDetailActions(props: { url?: string }) {
+export function PrDetailActions() {
return (
<div class="ml-auto flex shrink-0 items-center gap-2">
<ChangesToggle />
- <Show when={props.url}>
- {(url) => (
- <Button
- variant="outline"
- size="sm"
- onClick={() => openExternalUrl(url())}
- >
- Open on GitHub
- </Button>
- )}
- </Show>
<SidePanel.Toggle />
</div>
);
@@ -228,24 +218,30 @@ export function StandalonePrDetail(props: { foreignEntityId: string }) {
<PrChangesProvider
foreignEntityId={props.foreignEntityId}
pullRequestUrl={githubUrl()}
+ pullRequestTitle={detail.data()?.pullRequest.name ?? undefined}
+ pullRequestChangeCounts={detail.changeCounts()}
>
- <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden @container">
- <ViewShell.TopBar class="touch:flex">
- <SplitPanel.CloseButton class="hidden shrink-0 touch:flex" />
- <Show when={detail.data()?.pullRequest.status}>
- {(status) => <PrStatusIcon status={status()} />}
- </Show>
- <span class="min-w-0 truncate text-sm font-semibold">{name()}</span>
- <PrDetailActions url={githubUrl()} />
- </ViewShell.TopBar>
- <PrDetailContent
- foreignEntityId={props.foreignEntityId}
- data={detail.data()}
- status={detail.query.status}
- discussionSource={detail.discussionSource}
- onRetry={() => void detail.query.refetch()}
- />
- </div>
+ <AgentChangesSplit>
+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden @container">
+ <ViewShell.TopBar class="touch:flex">
+ <SplitPanel.CloseButton class="hidden shrink-0 touch:flex" />
+ <Show when={detail.data()?.pullRequest.status}>
+ {(status) => <PrStatusIcon status={status()} />}
+ </Show>
+ <span class="min-w-0 truncate text-sm font-semibold">
+ {name()}
+ </span>
+ <PrDetailActions />
+ </ViewShell.TopBar>
+ <PrDetailContent
+ foreignEntityId={props.foreignEntityId}
+ data={detail.data()}
+ status={detail.query.status}
+ discussionSource={detail.discussionSource}
+ onRetry={() => void detail.query.refetch()}
+ />
+ </div>
+ </AgentChangesSplit>
</PrChangesProvider>
</SidePanel.Root>
);
@@ -266,6 +262,7 @@ function PrMetadata(props: {
prRef: PrRef;
pullRequest?: GithubPullRequestWithDetails;
}) {
+ const changes = useOptionalAgentChanges();
return (
<div class="mb-6 flex flex-row flex-wrap items-center gap-2 text-sm empty:hidden">
<Show when={props.pullRequest?.status}>
@@ -308,14 +305,34 @@ function PrMetadata(props: {
}
>
<Layer depth={2}>
- <span class={PR_PILL_CLASS}>
- <span class="text-success">
- +{props.pullRequest?.additions ?? 0}
- </span>
- <span class="text-failure">
- −{props.pullRequest?.deletions ?? 0}
- </span>
- </span>
+ <Show
+ when={changes?.available()}
+ fallback={
+ <span class={PR_PILL_CLASS}>
+ <span class="text-success">
+ +{props.pullRequest?.additions ?? 0}
+ </span>
+ <span class="text-failure">
+ −{props.pullRequest?.deletions ?? 0}
+ </span>
+ </span>
+ }
+ >
+ <button
+ type="button"
+ class={PR_PILL_CLASS}
+ aria-label="Open Changes pane"
+ aria-expanded={changes?.layout.changesVisible()}
+ onClick={() => changes?.layout.open()}
+ >
+ <span class="text-success">
+ +{props.pullRequest?.additions ?? 0}
+ </span>
+ <span class="text-failure">
+ −{props.pullRequest?.deletions ?? 0}
+ </span>
+ </button>
+ </Show>
</Layer>
</Show>
<GithubLabelPills
diff --git a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
index 660a5da638..f940f0c03f 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
@@ -1,4 +1,5 @@
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
+import { AgentChangesSplit } from '@app/features/agent-changes/agent-changes';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useRouteParams } from '@app/lib/split-router';
import { reviewsPrRoute } from '@app/routes/routes';
@@ -84,26 +85,30 @@ export function ReviewsPrDetail(props: { foreignEntityId: string }) {
<PrChangesProvider
foreignEntityId={props.foreignEntityId}
pullRequestUrl={githubUrl()}
+ pullRequestTitle={detail.data()?.pullRequest.name ?? undefined}
+ pullRequestChangeCounts={detail.changeCounts()}
>
- <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden @container">
- <ViewShell.TopBar class="touch:flex">
- <SplitPanel.CloseButton class="hidden shrink-0 touch:flex" />
- <ViewBreadcrumbs.Outlet aria-label="Pull request location" />
- <PrDetailActions url={githubUrl()} />
- </ViewShell.TopBar>
- <ReviewsPrBreadcrumb
- foreignEntityId={props.foreignEntityId}
- name={name()}
- status={detail.data()?.pullRequest.status ?? undefined}
- />
- <PrDetailContent
- foreignEntityId={props.foreignEntityId}
- data={detail.data()}
- status={detail.query.status}
- discussionSource={detail.discussionSource}
- onRetry={() => void detail.query.refetch()}
- />
- </div>
+ <ReviewsPrBreadcrumb
+ foreignEntityId={props.foreignEntityId}
+ name={name()}
+ status={detail.data()?.pullRequest.status ?? undefined}
+ />
+ <AgentChangesSplit>
+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden @container">
+ <ViewShell.TopBar class="touch:flex">
+ <SplitPanel.CloseButton class="hidden shrink-0 touch:flex" />
+ <ViewBreadcrumbs.Outlet aria-label="Pull request location" />
+ <PrDetailActions />
+ </ViewShell.TopBar>
+ <PrDetailContent
+ foreignEntityId={props.foreignEntityId}
+ data={detail.data()}
+ status={detail.query.status}
+ discussionSource={detail.discussionSource}
+ onRetry={() => void detail.query.refetch()}
+ />
+ </div>
+ </AgentChangesSplit>
</PrChangesProvider>
</SidePanel.Root>
);
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index eab3239e58..ff8cb08d4e 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -902,9 +902,14 @@ Existing announcement chips remain locked to the turn they announced.
Sessions with a linked GitHub pull request capture that PR's diff when each
turn ends, regardless of the coding runtime. Unpushed workspace changes and
branches without a PR are not included. The capture is the same stored diff the
-PR's Changes pane in Reviews shows for that base and head. The session header gains a **Changes**
-toggle (`aria-pressed`) with green additions and red deletions (`+N −M`); it opens a resizable
-**Changes** pane beside the transcript (drag the 1px divider between them).
+PR's Changes pane in Reviews shows for that base and head. On the PR detail,
+the `+N −M` diff count pill also opens Changes when available; otherwise it stays
+a passive count. The session header gains a **Changes** toggle with green
+additions and red deletions (`+N −M`); it opens a resizable **Changes** pane
+beside the transcript (drag the 1px divider between them). Clicking it again closes the pane.
+In the Agents workspace, changes reach the top of the main area. The session
+title, share, and sidebar controls stay above the conversation on the left;
+the **Changes** toggle stays visible, ghost while closed and active while open.
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.
@@ -915,25 +920,74 @@ 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**.
+Divider widths, whether the file tree shows, collapsed files, and review notes
+stay local to the PR or session.
+The pane (`[role="region"][aria-label="Changes"]`) slides in from the right edge
+on open and slides fully off that edge on close, without fading in either direction.
+In split view, the conversation shrinks alongside entry and expands alongside exit,
+without changing width eagerly before the slide or snapping after it finishes.
+The pane has no outer top, right, or bottom border; the resize divider remains.
+Reduced-motion preferences disable both animations. Closing retains the pane until
+exit finishes; reopening during exit keeps the same pane mounted. From full width,
+the conversation appears behind the sliding pane instead of leaving blank space.
+The shell opens before patch parsing and diff rendering; off-screen
+diff bodies load as you scroll or select their files. A selected file's header
+stays aligned when earlier diffs finish rendering. Wheel, pointer, or keyboard
+interaction releases the anchor for manual scrolling; refreshing files does not
+jump back to an unchanged selection. Its header row
+(`[role="group"][aria-label="Changes controls"]`) has no visible Changes title.
+It shows `head → base · #N` as one plain-text GitHub link (**View pull request #N**),
+with an underline on hover and no icon or pill background. The header Changes toggle
+has no diff totals and becomes icon-only below 28rem of header width, retaining
+its accessible name, tooltip, and pressed state. When open, accent text and a tinted
+background match the side-panel emphasis. Beside the branch link and PR number,
+exact `+N −M` totals and five green/red squares summarize the addition/deletion mix
+in both split and full-width layouts. At full width, a smaller PR title appears
+before the branch link. If the header lacks room, the smaller
+branch/PR/count metadata wraps below the title; pane actions remain separate.
+Missing titles and totals stay hidden instead of showing placeholders or captured
+estimates. Hovering a file header highlights its row.
+Narrow panes truncate the branch range but keep the PR number visible. Wide hosts offer
+**Expand changes to the full width** (pressed while spotlit; its label becomes
+**Back to the split**) and **Close the changes pane** on the right. At 720px or narrower,
+Changes opens full-width automatically and hides the width toggle, preserving the
+saved wide split ratio and draft. Widening restores the requested wide layout.
+With files loaded, the file tree
+fills the body height; its fixed header (`[role="group"][aria-label="File tree controls"]`)
+shows the file count on the left and **Hide file tree** on the right.
+The tree rows scroll below that header. Borderless controls float above the diff
+stack (`[role="group"][aria-label="Diff controls"]`): **Unified / Split**
+(`aria-label="Diff layout"`) on the left, and **Collapse all / Expand all** and
+**Refresh pull request changes** on the right.
+There is no second toolbar spanning the pane. On non-touch devices, Unified/Split
+retains its text labels even in a narrow diff column. Hiding the tree moves the file
+count and **Show file tree** into the diff controls, while **Collapse all / Expand all**
+stays above the diffs. At 720px or narrower, and on touch devices, the tree starts
+closed and **Show file tree** opens an animated drawer over the diffs without
+resizing them. File selection, Escape, the backdrop, or **Hide file tree** dismisses
+the drawer and restores focus to its opener. Drawer visibility never changes the
+saved wide-tree preference or width. Phones keep unified diffs and omit layout
+controls, with **Back to conversation** closing Changes.
+Returning from full width restores the previous split ratio without replaying
+the opening slide or losing the conversation draft, diff state, or scroll position.
+Drag the divider beside the file tree to resize it, or focus that divider and use
+Left/Right (Shift moves farther). Its width persists locally. Hiding or showing the
+tree animates its width with the same reusable transition as sidebar sections,
+while the diff column and divider move alongside it. The divider remains visible
+but inert until exit completes. Reduced-motion preferences skip the motion.
+Starting a divider drag or keyboard resize, or changing the outer split or viewport
+width, settles the animation synchronously so solved geometry applies immediately.
+Hiding retains directory expansion and does not reload the diff stack.
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
+caret, the path, `+adds −dels`, and **Copy path**. A successful copy briefly shows a
+non-pulsing checkmark and announces **Path copied** without collapsing the file. Repeated
+copies show feedback for the latest click, not an older result. Diffs render
+with Pierre; hover a line and click the accent **+** in the gutter (drag for a range) to leave a
review note for the agent (`aria-label="Review note"`; `Cmd/Ctrl+Enter` adds,
`Escape` cancels). Notes hang under their line as "queued for the agent" and a
**N review notes queued · Send to agent** chip appears above the composer.
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 292c12f6e8..9f0f1648d9 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1389,8 +1389,56 @@ byline.
## Pull requests — `/app/reviews/pr/<foreignEntityId>`
Macro-linked GitHub pull requests open inside the Reviews shell, with a Reviews
-breadcrumb, PR title/status, GitHub action, discussion timeline, and Details/Checks
+breadcrumb, PR title/status, linked GitHub metadata, discussion timeline, and Details/Checks
side panel below the top bar. PRs are not tasks and do not appear in the Tasks list.
+Opening **Changes** slides a full-height pane in from the right beside the PR details,
+including beside the PR top bar rather than underneath it. The PR details shrink
+alongside the entry slide instead of eagerly jumping narrower. The Changes pane
+has no outer top, right, or bottom border. The PR's `+N −M` diff count pill also
+opens the pane when changes are available; it remains a passive count without a
+Changes controller or when changes are unavailable.
+Closing slides the pane fully off the right edge while expanding the left pane,
+without fading in either direction or a final width snap. From full width, the PR
+details appear behind the sliding pane, without blank space. Reopening during exit
+keeps the same pane mounted.
+The pane shell opens before the diff bodies render. Reduced-motion preferences
+disable both animations.
+The PR breadcrumb and side-panel toggle remain above the left pane. The
+**Changes** toggle stays visible in split view, ghost while closed and accent text
+on a tinted background while open; clicking it again closes the pane. There is no standalone **Open on
+GitHub** button: the pane header has no visible Changes title, and its
+`head → base · #N` is one plain-text GitHub link, underlined on hover without a
+pill background or icon. GitHub diff totals and five green/red squares appear
+beside the PR number in both split and full-width layouts. The squares summarize
+the addition/deletion mix; the numbers retain exact totals. At full width, a smaller
+PR title appears before the link. Both title and totals come from the existing PR
+query; unavailable values stay hidden, without placeholders or captured-count
+fallbacks. File headers highlight on hover. When space is tight, the smaller
+branch/PR/count metadata wraps below the title, while pane actions stay separate.
+The Changes toggle has no diff totals and becomes icon-only below 28rem of header
+width, retaining its name, tooltip, and active state. Breadcrumbs keep their existing layout.
+The full-height file tree has a fixed header with its file count on the left and
+**Hide file tree** on the right. Borderless diff controls float above the diff stack
+rather than spanning the pane in a second toolbar. Unified/Split retains text labels
+at narrow non-touch widths on the left, with diff collapse/expand and refresh on
+the right. Hiding the tree moves its count
+and **Show file tree** above the diffs, as described in
+[AI Chat](ai-chat.md#reviewing-a-linked-github-pull-request).
+Spotlighting changes hides the left pane and its top bar; **Back to the split**
+restores the prior divider position and retains the draft, diff state, and scroll.
+At host widths of 720px or less, Changes opens full-width automatically without
+that width toggle; widening restores the requested wide layout and split ratio.
+Narrow file trees start closed. **Show file tree** opens an animated drawer over the
+diffs without resizing them, including on phones. File selection, Escape, the
+backdrop, or **Hide file tree** closes the drawer and restores focus to its opener.
+The drawer does not change the saved wide-tree visibility or preferred width.
+The file tree has its own draggable, keyboard-resizable divider and remembers its
+width locally. Tree visibility uses the sidebar's shared width transition while
+retaining directory state and diff owners. Reduced motion skips this transition.
+The divider remains visible but inert through the tree's exit. Resizing the outer
+split or viewport settles active tree motion before applying the new geometry.
+**Copy path** briefly shows a non-pulsing success checkmark without collapsing
+the file. The PR viewer stays read-only and does not offer agent review notes.
Copy Link from a PR in Quick Access copies `/app/reviews/pr/<foreignEntityId>`.
Old `/app/pr/<foreignEntityId>` links redirect to Reviews. Check a copied link,
a PR opened from a list or agent session, a second split, breadcrumb return,