A desktop coding agent with free access to frontier models.
TypeScript
feat: side-by-side diffs for each turn
ogsamrat5106c22a6bed
diff --git a/apps/app/src/components/chat/message-list.tsx b/apps/app/src/components/chat/message-list.tsxindex 1e6b3075..465f223f 100644--- a/apps/app/src/components/chat/message-list.tsx+++ b/apps/app/src/components/chat/message-list.tsx@@ -10,6 +10,7 @@ import {CirclePause,Copy,Download,+ FileDiff,FileIcon,FolderOpen,LoaderCircle,@@ -136,7 +137,7 @@ import { DevProfiler } from "@/react-app/shell/dev-profiler"import { groupMessages, isMessageGroup, getLastTextPart, getAggregateOnlyParts, getAssistantRenderGroups, getFileTitle, getMediaBadge, getMessageCompleted, getMessageCreated, formatMessageTimestamp, splitTurnAtAnswer, type UIMessageWithIndex, getMessagesText, getSafeFileDownloadUrl, getSafeFileRevealPath } from "./utils"import type { AnyToolPart } from "@/lib/tool-aggregate"import { commandTemplateLabel, reviewForTurn } from "@/react-app/domains/session/commands/review-message"-import { useSessionCommandBridge } from "@/react-app/domains/session/commands/session-commands-store"+import { useSessionCommandBridge, useSessionCommandsStore } from "@/react-app/domains/session/commands/session-commands-store"import { ReviewFixBar } from "@/react-app/domains/session/commands/review-fix-bar"import { resolveConnectorToolIdentity } from "@/react-app/domains/connections/connector-tool-identity"@@ -1259,6 +1260,16 @@ interface AssistantMessageGroupProps {isStreaming: boolean/** The text of the user message this group answers (a review turn offers "Fix these"). */turnUserText?: string+ /** The id of that user message (the turn the "Changes in this turn" button opens). */+ turnUserId?: string+}++const FILE_CHANGING_TOOLS = new Set(["edit", "write", "apply_patch", "multiedit", "bash"])++/** The turn ran a tool that changes files (the engine records its diff per turn). */+function changesFiles(items: UIMessageWithIndex[]): boolean {+ return items.some((item) => item.message.parts.some((part) =>+ part.type === "dynamic-tool" && FILE_CHANGING_TOOLS.has(part.toolName)))}function collectMcpAppParts(items: UIMessageWithIndex[]): DynamicToolUIPart[] {@@ -1283,6 +1294,7 @@ function MessageGroup({isLastGroup,isStreaming,turnUserText,+ turnUserId,}: AssistantMessageGroupProps) {const { onRevertToUserMessage, onForkAtMessage, showThinking, onRunCommand, sessionId } = useMessageList()const commandBridge = useSessionCommandBridge(sessionId)@@ -1482,6 +1494,19 @@ function MessageGroup({<Undo2 /></Button></MessageAction>+ {turnUserId && sessionId && changesFiles(items) ? (+ <MessageAction tooltip="Changes in this turn">+ <Button+ variant="ghost"+ size="icon"+ aria-label="Changes in this turn"+ data-testid="turn-changes"+ onClick={() => useSessionCommandsStore.getState().openChanges(sessionId, turnUserId)}+ >+ <FileDiff />+ </Button>+ </MessageAction>+ ) : null}</>) : null}</MessageActions>@@ -1501,6 +1526,7 @@ function sameMessageGroupProps(left: AssistantMessageGroupProps, right: Assistanreturn left.isLastGroup === right.isLastGroup&& left.isStreaming === right.isStreaming&& left.turnUserText === right.turnUserText+ && left.turnUserId === right.turnUserId&& left.items.length === right.items.length&& left.items.every((item, index) => (item.index === right.items[index]?.index@@ -1510,6 +1536,14 @@ function sameMessageGroupProps(left: AssistantMessageGroupProps, right: Assistanconst MemoizedMessageGroup = React.memo(MessageGroup, sameMessageGroupProps)+/** The id of the newest user message before `index`. */+function precedingUserId(messages: UIMessage[], index: number): string | undefined {+ for (let at = index - 1; at >= 0; at -= 1) {+ if (messages[at]?.role === "user") return messages[at]?.id+ }+ return undefined+}+/** The text of the newest user message before `index` (the prompt an assistant group answers). */function precedingUserText(messages: UIMessage[], index: number): string | undefined {for (let at = index - 1; at >= 0; at -= 1) {@@ -1663,6 +1697,7 @@ export function MessageList({ messages, status, activityStatus, retryStatus, synisLastGroup={item.messages.at(-1)?.index === messages.length - 1}isStreaming={isStreaming && item.messages.at(-1)?.index === messages.length - 1}turnUserText={precedingUserText(messages, item.messages[0]?.index ?? 0)}+ turnUserId={precedingUserId(messages, item.messages[0]?.index ?? 0)}/>)}diff --git a/apps/app/src/react-app/domains/session/commands/changes-panel.tsx b/apps/app/src/react-app/domains/session/commands/changes-panel.tsxindex 8f72195a..a6755945 100644--- a/apps/app/src/react-app/domains/session/commands/changes-panel.tsx+++ b/apps/app/src/react-app/domains/session/commands/changes-panel.tsx@@ -1,7 +1,7 @@/** @jsxImportSource react */import { useEffect, useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";-import { ChevronDown, ChevronRight, FileDiff, ListChecks, RefreshCw } from "lucide-react";+import { ChevronDown, ChevronRight, Columns2, FileDiff, ListChecks, RefreshCw, Rows3 } from "lucide-react";import { Button } from "@/components/ui/button";import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";@@ -17,8 +17,10 @@ import {MAX_DIFF_LINES,patchLineCount,patchLines,+ splitRows,type ChangedFile,type ChangesSource,+ type PatchLine,} from "./changes";import { useSessionCommandBridge, useSessionCommandsStore } from "./session-commands-store";import { latestUserMessageId, useCachedQueryData, useOpencodeClient, type SessionCommandTarget } from "./use-session-commands";@@ -31,16 +33,66 @@ const STATUS_BADGE: Record<ChangedFile["status"], string> = {modified: "M",};-function DiffBody({ patch }: { patch: string }) {+type DiffLayout = "unified" | "split";+const LAYOUT_KEY = "omnirush.changes.layout";++function readLayout(): DiffLayout {+ try {+ return window.localStorage.getItem(LAYOUT_KEY) === "split" ? "split" : "unified";+ } catch {+ return "unified";+ }+}++const SIDE_TONE: Record<PatchLine["kind"], string | false> = {+ add: "bg-green-3/40 text-green-11",+ del: "bg-red-3/40 text-red-11",+ hunk: false,+ context: false,+ meta: false,+};++/** One side of a side-by-side row; an empty side is shaded so a pure addition or removal reads at a glance. */+function SplitCell({ line, side }: { line: PatchLine | null; side: "old" | "new" }) {+ if (!line) return <div className="min-w-0 bg-muted/40" />;+ const number = side === "old" ? line.oldLine : line.newLine;+ return (+ <div className={cn("flex min-w-0", SIDE_TONE[line.kind])}>+ <span className="w-10 shrink-0 select-none pr-2 text-right text-muted-foreground/70">{number ?? ""}</span>+ <span className="w-3 shrink-0 select-none">{line.kind === "add" ? "+" : line.kind === "del" ? "-" : ""}</span>+ <span className="min-w-0 whitespace-pre-wrap break-all pr-3">{line.text || " "}</span>+ </div>+ );+}++function SplitLines({ lines }: { lines: readonly PatchLine[] }) {+ const rows = useMemo(() => splitRows(lines), [lines]);+ return (+ <>+ {rows.map((row, index) =>+ row.kind === "line" ? (+ <div key={index} className="grid grid-cols-2 divide-x divide-border/60">+ <SplitCell line={row.left} side="old" />+ <SplitCell line={row.right} side="new" />+ </div>+ ) : (+ <div key={index} className={cn("px-3 whitespace-pre", row.kind === "hunk" ? "bg-blue-2/40 text-blue-11" : "text-muted-foreground")}>{row.text}</div>+ ),+ )}+ </>+ );+}++function DiffBody({ patch, layout }: { patch: string; layout: DiffLayout }) {const [showAll, setShowAll] = useState(false);const all = useMemo(() => patchLines(patch), [patch]);- const lines = showAll ? all : all.slice(0, MAX_DIFF_LINES);+ const lines = useMemo(() => (showAll ? all : all.slice(0, MAX_DIFF_LINES)), [all, showAll]);if (!lines.length) {return <div className="px-3 py-2 text-xs text-muted-foreground">No line changes to show (a binary file, or only its mode changed).</div>;}return (- <div className="max-h-[50vh] overflow-auto border-t border-border font-mono text-[11.5px] leading-[1.55]" data-testid="changes-diff">- {lines.map((line, index) => (+ <div className="max-h-[60vh] overflow-auto border-t border-border font-mono text-[11.5px] leading-[1.55]" data-testid="changes-diff" data-layout={layout}>+ {layout === "split" ? <SplitLines lines={lines} /> : lines.map((line, index) => (<divkey={index}className={cn(@@ -68,7 +120,7 @@ function DiffBody({ patch }: { patch: string }) {);}-function FileRow({ file, defaultOpen }: { file: ChangedFile; defaultOpen: boolean }) {+function FileRow({ file, defaultOpen, layout }: { file: ChangedFile; defaultOpen: boolean; layout: DiffLayout }) {const [open, setOpen] = useState(defaultOpen);return (<div className="overflow-hidden rounded-xl border border-border bg-background/60" data-testid="changes-file" data-path={file.path}>@@ -94,7 +146,7 @@ function FileRow({ file, defaultOpen }: { file: ChangedFile; defaultOpen: boolea<span className="shrink-0 font-mono text-[11.5px] text-green-11">+{file.additions}</span><span className="shrink-0 font-mono text-[11.5px] text-red-11">-{file.deletions}</span></button>- {open ? <DiffBody patch={file.patch} /> : null}+ {open ? <DiffBody patch={file.patch} layout={layout} /> : null}</div>);}@@ -107,23 +159,46 @@ function FileRow({ file, defaultOpen }: { file: ChangedFile; defaultOpen: booleaexport function ChangesPanel(props: SessionCommandTarget) {const openFor = useSessionCommandsStore((state) => state.changesOpenFor);const closeChanges = useSessionCommandsStore((state) => state.closeChanges);+ const turnId = useSessionCommandsStore((state) => state.changesTurn);+ const [layout, setLayout] = useState<DiffLayout>(readLayout);const open = openFor === props.sessionId;+ const chooseLayout = (next: DiffLayout) => {+ setLayout(next);+ try {+ window.localStorage.setItem(LAYOUT_KEY, next);+ } catch {+ // Not remembered; the choice still applies now.+ }+ };return (<Sheet open={open} onOpenChange={(next) => { if (!next) closeChanges(); }}>- <SheetContent side="right" className="w-[min(720px,92vw)] gap-0 data-[side=right]:sm:max-w-[720px]" data-testid="changes-panel">- {open ? <ChangesBody {...props} onClose={closeChanges} /> : null}+ <SheetContent+ side="right"+ className={cn(+ "gap-0",+ layout === "split" ? "w-[min(1280px,96vw)] data-[side=right]:sm:max-w-[1280px]" : "w-[min(720px,92vw)] data-[side=right]:sm:max-w-[720px]",+ )}+ data-testid="changes-panel"+ >+ {open ? <ChangesBody key={turnId ?? "last"} {...props} turnId={turnId} layout={layout} onLayout={chooseLayout} onClose={closeChanges} /> : null}</SheetContent></Sheet>);}-function ChangesBody(props: SessionCommandTarget & { onClose: () => void }) {+function ChangesBody(props: SessionCommandTarget & {+ turnId: string | null;+ layout: DiffLayout;+ onLayout: (layout: DiffLayout) => void;+ onClose: () => void;+}) {const client = useOpencodeClient(props);const bridge = useSessionCommandBridge(props.sessionId);- const [source, setSource] = useState<ChangesSource>("chat");+ // Opened from a reply's "Changes in this turn": that turn first.+ const [source, setSource] = useState<ChangesSource>(props.turnId ? "turn" : "chat");const snapshot = useCachedQueryData<OmniRushSessionSnapshot>(snapshotKey(props.workspaceId, props.sessionId));const status = useCachedQueryData<{ type: string }>(statusKey(props.workspaceId, props.sessionId));- const lastUserId = latestUserMessageId(snapshot?.session.id === props.sessionId ? snapshot : null);+ const lastUserId = props.turnId ?? latestUserMessageId(snapshot?.session.id === props.sessionId ? snapshot : null);const revertId = snapshot?.session.revert?.messageID ?? null;const running = (status?.type ?? "idle") !== "idle";@@ -193,6 +268,7 @@ function ChangesBody(props: SessionCommandTarget & { onClose: () => void }) {</div></div><SheetDescription className="sr-only">The files this chat changed and their diffs.</SheetDescription>+ <div className="flex flex-wrap items-center gap-2"><div className="flex w-fit items-center gap-0.5 rounded-lg bg-muted p-0.5" role="tablist" aria-label="Changes source">{SOURCES.map((item) => (<button@@ -207,10 +283,30 @@ function ChangesBody(props: SessionCommandTarget & { onClose: () => void }) {)}onClick={() => setSource(item)}>- {CHANGES_SOURCE_LABEL[item]}+ {item === "turn" && props.turnId ? "This turn" : CHANGES_SOURCE_LABEL[item]}+ </button>+ ))}+ </div>+ <div className="ml-auto flex w-fit items-center gap-0.5 rounded-lg bg-muted p-0.5" role="radiogroup" aria-label="Diff layout">+ {([["unified", Rows3, "Unified"], ["split", Columns2, "Side by side"]] as const).map(([value, Icon, label]) => (+ <button+ key={value}+ type="button"+ role="radio"+ aria-checked={props.layout === value}+ data-testid={`changes-layout-${value}`}+ className={cn(+ "flex items-center gap-1 rounded-md px-2.5 py-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground",+ props.layout === value && "bg-background text-foreground shadow-sm",+ )}+ onClick={() => props.onLayout(value)}+ >+ <Icon className="size-3.5" />+ {label}</button>))}</div>+ </div></SheetHeader><div className="min-h-0 flex-1 overflow-auto p-4">{query.isLoading ? (@@ -223,12 +319,12 @@ function ChangesBody(props: SessionCommandTarget & { onClose: () => void }) {</div>) : files.length === 0 ? (<div className="rounded-xl border border-dashed border-border p-6 text-center text-sm text-muted-foreground" data-testid="changes-empty">- {CHANGES_EMPTY[source]}+ {source === "turn" && props.turnId ? "This turn changed no files." : CHANGES_EMPTY[source]}</div>) : (<div className="flex flex-col gap-2">{files.map((file) => (- <FileRow key={`${source}:${file.path}`} file={file} defaultOpen={files.length <= 3 && patchLineCount(file.patch) <= MAX_DIFF_LINES} />+ <FileRow key={`${source}:${file.path}`} file={file} layout={props.layout} defaultOpen={files.length <= 3 && patchLineCount(file.patch) <= MAX_DIFF_LINES} />))}</div>)}diff --git a/apps/app/src/react-app/domains/session/commands/changes.ts b/apps/app/src/react-app/domains/session/commands/changes.tsindex 7748f2f4..5eded0d5 100644--- a/apps/app/src/react-app/domains/session/commands/changes.ts+++ b/apps/app/src/react-app/domains/session/commands/changes.ts@@ -94,3 +94,35 @@ export function patchLineCount(patch: string): number {for (let at = patch.indexOf("\n"); at !== -1; at = patch.indexOf("\n", at + 1)) count += 1;return count;}++/** One row of a side-by-side diff: the old line on the left, the new one on the right (either may be empty). */+export type SplitRow =+ | { kind: "hunk" | "meta"; text: string }+ | { kind: "line"; left: PatchLine | null; right: PatchLine | null };++/** Display lines as side-by-side rows: context on both sides, a run of removals paired with the additions after it. */+export function splitRows(lines: readonly PatchLine[]): SplitRow[] {+ const rows: SplitRow[] = [];+ let dels: PatchLine[] = [];+ let adds: PatchLine[] = [];+ const flush = () => {+ for (let at = 0; at < Math.max(dels.length, adds.length); at += 1) {+ rows.push({ kind: "line", left: dels[at] ?? null, right: adds[at] ?? null });+ }+ dels = [];+ adds = [];+ };+ for (const line of lines) {+ if (line.kind === "del") {+ if (adds.length) flush();+ dels.push(line);+ } else if (line.kind === "add") {+ adds.push(line);+ } else {+ flush();+ rows.push(line.kind === "context" ? { kind: "line", left: line, right: line } : { kind: line.kind, text: line.text });+ }+ }+ flush();+ return rows;+}diff --git a/apps/app/src/react-app/domains/session/commands/session-commands-store.ts b/apps/app/src/react-app/domains/session/commands/session-commands-store.tsindex acc19cb3..f14c4de9 100644--- a/apps/app/src/react-app/domains/session/commands/session-commands-store.ts+++ b/apps/app/src/react-app/domains/session/commands/session-commands-store.ts@@ -23,12 +23,14 @@ type SessionCommandsStore = {bridges: Record<string, SessionCommandBridge>;/** The chat whose Changes panel is open, or null. */changesOpenFor: string | null;+ /** The prompt whose turn the open Changes panel shows (a chat's "Changes in this turn"), or null for the last turn. */+ changesTurn: string | null;/** The chat whose Status dialog (header menu) is open, or null. */statusOpenFor: string | null;headerActions: Record<string, SessionHeaderActions>;register: (sessionId: string, bridge: SessionCommandBridge) => () => void;setHeaderActions: (sessionId: string, actions: SessionHeaderActions | null) => void;- openChanges: (sessionId: string) => void;+ openChanges: (sessionId: string, turnMessageId?: string | null) => void;closeChanges: () => void;openStatus: (sessionId: string) => void;closeStatus: () => void;@@ -37,6 +39,7 @@ type SessionCommandsStore = {export const useSessionCommandsStore = create<SessionCommandsStore>((set, get) => ({bridges: {},changesOpenFor: null,+ changesTurn: null,statusOpenFor: null,headerActions: {},setHeaderActions: (sessionId, actions) => set((state) => {@@ -56,8 +59,8 @@ export const useSessionCommandsStore = create<SessionCommandsStore>((set, get) =});};},- openChanges: (sessionId) => set({ changesOpenFor: sessionId }),- closeChanges: () => set({ changesOpenFor: null }),+ openChanges: (sessionId, turnMessageId = null) => set({ changesOpenFor: sessionId, changesTurn: turnMessageId }),+ closeChanges: () => set({ changesOpenFor: null, changesTurn: null }),openStatus: (sessionId) => set({ statusOpenFor: sessionId }),closeStatus: () => set({ statusOpenFor: null }),}));diff --git a/apps/app/tests/changes-split.test.ts b/apps/app/tests/changes-split.test.tsnew file mode 100644index 00000000..6ef1c50a--- /dev/null+++ b/apps/app/tests/changes-split.test.ts@@ -0,0 +1,21 @@+import { describe, expect, test } from "bun:test";++import { patchLines, splitRows } from "../src/react-app/domains/session/commands/changes";++describe("splitRows", () => {+ test("pairs removals with the additions after them and keeps context on both sides", () => {+ const patch = ["@@ -1,4 +1,4 @@", " a", "-b", "-c", "+B", " d", "+e", ""].join("\n");+ const rows = splitRows(patchLines(patch));+ const view = rows.map((row) =>+ row.kind === "line" ? `${row.left?.text ?? "_"}|${row.right?.text ?? "_"}` : `${row.kind}`);+ expect(view).toEqual(["hunk", "a|a", "b|B", "c|_", "d|d", "_|e"]);+ const paired = rows[2];+ expect(paired?.kind === "line" && paired.left?.oldLine).toBe(2);+ expect(paired?.kind === "line" && paired.right?.newLine).toBe(2);+ });++ test("an addition before a removal starts a new pair", () => {+ const rows = splitRows(patchLines(["@@ -1,1 +1,1 @@", "+x", "-y"].join("\n")));+ expect(rows.slice(1).map((row) => row.kind === "line" && `${row.left?.text ?? "_"}|${row.right?.text ?? "_"}`)).toEqual(["_|x", "y|_"]);+ });+});